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
|
spm/spm5-master
|
spm_figure.m
|
.m
|
spm5-master/spm_figure.m
| 30,162 |
utf_8
|
12f9a21067b2333626a8f244f5655211
|
function varargout=spm_figure(varargin)
% Setup and callback functions for Graphics window
% FORMAT varargout=spm_figure(varargin)
% - An embedded callback, multi-function function
% - For detailed programmers comments, see format specifications
% in main body of code
%_______________________________________________________________________
%
% 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,
% enabling interactive editing of graphic output prior to printing
% (e.g. selection of color maps, deleting, moving and editing graphics
% objects or adding text). (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.
%
% Colormap options:
% * gray, hot, pink: Sets the colormap to its default values and loads
% either a grayscale, 'hot metal' or color map.
% * gray-hot, etc: Creates a 'split' colormap {128 x 3 matrix}.
% The lower half is a gray scale and the upper half
% is 'hot metal' or 'pink'. This color map 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.
%
% Editing: Right button ('alt' button) cancels operations
% * Cut : Deletes the graphics object next selected (if deletable)
% Select with middle mouse button to delete blocks of text,
% or to delete individual elements from a plot.
% * Move : To re-position a text, uicontrol or axis object using a
% 'drag and drop' implementation (i.e. depress - move - release)
% Using the middle 'extend' mouse button on a text object moves
% the axes containing the text - i.e. blocks of text.
% * Size : Re-sizes the text, uicontrol or axis object next selected
% {left button - decrease, middle button - increase} by a factor
% of 1.24 (or increase/decrease FontSize by 2 dpi)
% * Text : Creates an editable text widget that produces a text object as
% its CallBack.
% The text object is provided with a ContextMenu, obtained by
% right-clicking ('alt') on the text, allowing text attributes
% to be changed. Alternatively, the edit facilities on the window
% menu bar or ContextMenu can be used.
% * Edit : To edit text, select a text object with the circle cursor,
% and edit the text in the editable text widget that appears.
% A middle 'extend' mouse click places a context menu on the text
% object, facilitating easy modification of text atributes.
%
% For SPM usage, the figure should be 'Tag'ed as 'Graphics'.
%
% For SPM power users, and programmers, spm_figure provides utility
% routines for using the SPM graphics interface. Of particular use are
% the GetWin, FindWin and Clear functions See the embedded callback
% reference in the main body of spm_figure, below the help text.
%
% See also: spm_print, spm_clf
%
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Andrew Holmes
% $Id: spm_figure.m 902 2007-08-30 09:29:29Z volkmar $
%=======================================================================
% - 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_figure Create` is )
%( equivalent to `spm_figure('Create')`. )
%
% 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 'Tag' is 'Graphics' or
% 'Interactive' and no such 'Tag'ged figure is found, 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 F = spm_figure('ParentFig',h)
% Finds window containing the object whose handle is specified
% h - Handle of object whose parent figure is required
% - If a vector, then first object handle is used
% F - Number or parent figure
%
% 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('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 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 WS = spm_figure('GetWinScale')
% 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.m, repeated to reduce inter-dependencies.)
%
% FORMAT FS = spm_figure('FontSizes',FS)
% Returns fontsizes FS scaled for the current display.
% FS - (vector of) Font sizes to scale
% [default [08,09,11,13,14,6:36]]
%
% FORMAT spm_figure('CreateBar',F)
% Creates toolbar in figure F (defaults to gcf). F can be a 'Tag'
% If the figure is 'Tag'ed as 'Graphics' (SPM usage), then the Print button
% callback is set to attempt to clear an 'Interactive' figure too.
%
% FORMAT spm_figure('ColorMap')
% Callback for "ColorMap" buttons
%
% FORMAT h = spm_figure('GraphicsHandle',F)
% GUI choose object for handle identification. LeftMouse 'normal' returns
% handle, MiddleMouse 'extend' returns parents handle, RightMouse 'alt' cancels.
% F - figure to do a GUI "handle ID" in [Default gcbf]
%_______________________________________________________________________
%-Condition arguments
%-----------------------------------------------------------------------
if (nargin==0), Action = 'Create'; else Action = varargin{1}; end
switch lower(Action), case 'create'
%=======================================================================
% F = spm_figure('Create',Tag,Name,Visible)
%-Condition arguments
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 = findobj(get(0,'Children'),'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==get(0,'Children')), F=[]; end
end
varargout = {F};
case 'getwin'
%=======================================================================
% F=spm_figure('GetWin',Tag)
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 'SI'
F = spm_figure('Create','SI','System Identification');
case 'Interactive'
F = spm('CreateIntWin');
end
end
else
set(0,'CurrentFigure',F);
end
varargout = {F};
case 'parentfig'
%=======================================================================
% F=spm_figure('ParentFig',h)
if nargin<2, error('No object specified'), else h=varargin{2}; end
F = get(h(1),'Parent');
while ~strcmp(get(F,'Type'),'figure'), F=get(F,'Parent'); end
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
%-----------------------------------------------------------------------
if isempty(Tags)
%-Clear figure of objects with 'HandleVisibility' 'on'
pos = get(F,'Position');
delete(findobj(get(F,'Children'),'flat','HandleVisibility','on'));
drawnow
set(F,'Position',pos);
%-Reset figures callback functions
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
cSHH = get(0,'ShowHiddenHandles');
set(0,'ShowHiddenHandles','on')
if ischar(Tags); Tags=cellstr(Tags); end
if any(strcmp(Tags(:),'!all'))
delete(get(F,'Children'))
else
for tag = Tags(:)'
delete(findobj(get(F,'Children'),'flat','Tag',tag{:}));
end
end
set(0,'ShowHiddenHandles',cSHH)
end
set(F,'Pointer','Arrow')
movegui(F);
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 = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo = findobj(F,'Tag','PageNo');
iPaged = ~isempty(hNextPage);
%-Construct print command
%-----------------------------------------------------------------------
%-Temporarily change all units to normalized prior to printing
% (Fixes bizzarre problem with stuff jumping around!)
%-----------------------------------------------------------------------
H = findobj(get(F,'Children'),'flat','Type','axes');
if ~isempty(H),
un = cellstr(get(H,'Units'));
set(H,'Units','normalized')
end;
%-Print
%-----------------------------------------------------------------------
if ~iPaged
spm_print(fname)
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);
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] = uiputfile('*.ps', 'Print to File');
if fn == 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 = spm_figure('ParentFig',h(1));
hNextPage = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo = findobj(F,'Tag','PageNo');
%-Create pagination widgets if required
%-----------------------------------------------------------------------
if isempty(hNextPage)
WS = spm('WinScale');
FS = spm('FontSizes');
SatFig = findobj('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 = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo = findobj(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}) % VG
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 (for neatness)
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 = findobj(F,'Tag','NextPage');
hPrevPage = findobj(F,'Tag','PrevPage');
hPageNo = findobj(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 = findobj(F,'Tag','NextPage');
if isempty(hNextPage)
n = 1;
else
n = size(get(hNextPage,'UserData'),1)+1;
end
varargout = {n};
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(get(0,'Children')), 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',...
'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)
%-Condition arguments
%-----------------------------------------------------------------------
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
WS = spm('WinScale'); %-Window scaling factors
FS = spm('FontSizes'); %-Scaled font sizes
PF = spm_platform('fonts'); %-Font names (for this platform)
Rect = spm('WinSize','Graphics','raw').*WS; %-Graphics window rectangle
F = figure(...
'Tag',Tag,...
'Position',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','painters',...
'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};
case 'getwinscale'
%=======================================================================
% WS = spm_figure('GetWinScale')
warning('spm_figure(''GetWinScale''... is Grandfathered: use spm(''WinScale''')
varargout = {spm('WinScale')};
case 'fontsizes'
%=======================================================================
% FS = spm_figure('FontSizes',FS)
warning('spm_figure(''FontSizes''... is Grandfathered: use spm(''FontSizes''')
if nargin<2, FS=[08,09,11,13,14,6:36]; else FS=varargin{2}; end
varargout = {round(FS*min(spm('WinScale')))};
%=======================================================================
case 'createbar'
%=======================================================================
% spm_figure('CreateBar',F)
if nargin<2, if any(get(0,'Children')), F=gcf; else F=''; end
else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
cSHH = get(0,'ShowHiddenHandles');
set(0,'ShowHiddenHandles','on')
t0 = findobj(get(F,'Children'),'Flat','Label','&Help');
if isempty(t0), t0 = uimenu( F,'Label','&Help'); end;
set(findobj(t0,'Position',1),'Separator','on');
uimenu(t0,'Position',1,...
'Label','SPM web',...
'CallBack','web(''http://www.fil.ion.ucl.ac.uk/spm/'');');
uimenu(t0,'Position',1,...
'Label','SPM help','ForegroundColor',[0 1 0],...
'CallBack','spm_help');
t0=uimenu( F,'Label','Colours','HandleVisibility','off');
t1=uimenu(t0,'Label','ColorMap');
uimenu(t1,'Label','Gray', 'CallBack','spm_figure(''ColorMap'',''gray'')');
uimenu(t1,'Label','Hot', 'CallBack','spm_figure(''ColorMap'',''hot'')');
uimenu(t1,'Label','Pink', 'CallBack','spm_figure(''ColorMap'',''pink'')');
uimenu(t1,'Label','Jet','CallBack','spm_figure(''ColorMap'',''jet'')');
uimenu(t1,'Label','Gray-Hot', 'CallBack','spm_figure(''ColorMap'',''gray-hot'')');
uimenu(t1,'Label','Gray-Cool','CallBack','spm_figure(''ColorMap'',''gray-cool'')');
uimenu(t1,'Label','Gray-Pink','CallBack','spm_figure(''ColorMap'',''gray-pink'')');
uimenu(t1,'Label','Gray-Jet', 'CallBack','spm_figure(''ColorMap'',''gray-jet'')');
t1=uimenu(t0,'Label','Effects');
uimenu(t1,'Label','Invert','CallBack','spm_figure(''ColorMap'',''invert'')');
uimenu(t1,'Label','Brighten','CallBack','spm_figure(''ColorMap'',''brighten'')');
uimenu(t1,'Label','Darken','CallBack','spm_figure(''ColorMap'',''darken'')');
uimenu( F,'Label','Clear','HandleVisibility','off','CallBack','spm_figure(''Clear'',gcbf)');
t0=uimenu( F,'Label','SPM-Print','HandleVisibility','off');
%uimenu( F,'Label','SPM-Print','HandleVisibility','off','CallBack','spm_figure(''Print'',gcbf)');
t1=uimenu(t0,'Label','default print file','HandleVisibility','off','CallBack','spm_figure(''Print'',gcbf)');
t1=uimenu(t0,'Label','other print file','HandleVisibility','off','CallBack','spm_figure(''PrintTo'',spm_figure(''FindWin'',''Graphics''))');
% ### CODE FOR SATELLITE FIGURE ###
% Code checks if there is a satellite window and if results are currently displayed
% It assumes that if hReg is invalid then there are no results currently displayed
% Modified by DRG to display a satellite figure 02/14/01.
cb = ['global SatWindow,',...
'try,',...
'tmp = get(hReg);,',...
'ResFlag = 1;',...
'catch,',...
'ResFlag = 0;',...
'end,',...
'if SatWindow,',...
'figure(SatWindow),',...
'else,',...
'if ResFlag,',...
'spm_setup_satfig,',...
'end,',...
'end'];
uimenu( F,'Label','Results-Fig','HandleVisibility','off','Callback',cb);
% ### END NEW CODE ###
set(0,'ShowHiddenHandles',cSHH)
spm_jobman('pulldown');
%=======================================================================
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');
cSHH = get(0,'ShowHiddenHandles');
set(0,'ShowHiddenHandles','on')
copy_menu(F,h);
set(0,'ShowHiddenHandles',cSHH)
set(F,'UIContextMenu',h)
varargout = {h};
case 'colormap'
%=======================================================================
% spm_figure('ColorMap',ColAction,h)
if nargin<3, h=[]; else h=varargin{3}; end
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 'graphicshandle'
%=======================================================================
% h = spm_figure('GraphicsHandle',F)
if nargin<2, F=gcbf; else F=spm_figure('FindWin',varargin{2}); end
if isempty(F), return, end
tmp = get(F,'Name');
set(F,'Name',...
'Handle: Select item to identify, MiddleMouse=parent, RightMouse=cancel...');
set(F,'Pointer','CrossHair')
waitforbuttonpress;
h = gco(F);
hType = get(h,'Type');
SelnType = get(gcf,'SelectionType');
set(F,'Pointer','Arrow','Name',tmp)
if ~strcmp(SelnType,'alt') && ~isempty(h) && gcf==F
str = sprintf('Selected (%s) object',get(h,'Type'));
if strcmp(SelnType,'normal')
str = sprintf('%s: handle',str);
else
h = get(h,'Parent');
str = sprintf('%s: handle of parent (%s) object',str,get(h,'Type'));
end
if nargout==0
assignin('base','ans',h)
fprintf('\n%s: \n',str)
ans = h
else
varargout={h};
end
else
varargout={[]};
end
otherwise
%=======================================================================
warning(['Illegal Action string: ',Action])
end
return;
%=======================================================================
%=======================================================================
function copy_menu(F,G)
%=======================================================================
handles = findobj(get(F,'Children'),'Flat','Type','uimenu','Visible','on');
if isempty(handles), return; end;
for F1=handles',
if ~strcmp(get(F1,'Label'),'&Window'),
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;
return;
%=======================================================================
|
github
|
spm/spm5-master
|
spm_config_runbatch.m
|
.m
|
spm5-master/spm_config_runbatch.m
| 1,054 |
utf_8
|
c302aa5fcdb0ebe2c500ee8dcace2b9e
|
function opts = spm_config_runbatch
% Configuration file for running batched jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Darren Gitelman
% $Id: spm_config_runbatch.m 1032 2007-12-20 14:45:55Z john $
data.type = 'files';
data.name = 'Batch Files';
data.tag = 'jobs';
data.filter = 'batch';
data.num = [1 Inf];
data.help = {'Select the batch job files to be run.'};
opts.type = 'branch';
opts.name = 'Execute Batch Jobs';
opts.tag = 'runbatch';
opts.val = {data};
opts.prog = @runbatch;
opts.help = {[...
'This facility allows previously created batch jobs to be run. ',...
'These are simply created by the batch user interface ',...
'(which you are currently using).']};
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function runbatch(varargin)
jobs = varargin{1}.jobs;
for i=1:numel(jobs),
spm_jobman('run',jobs{i});
end;
return;
|
github
|
spm/spm5-master
|
spm_P_RF.m
|
.m
|
spm5-master/spm_P_RF.m
| 5,895 |
utf_8
|
93c3a6c9cdea397f20820b00dd056112
|
function [P,p,Em,En,EN] = spm_P_RF(c,k,Z,df,STAT,R,n)
% Returns the [un]corrected P value using unifed EC theory
% FORMAT [P p Em En EN] = 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(n > kmax}
% p - uncorrected P value - P(n > k}
% Em - expected total number of maxima {m}
% En - expected total number of resels per cluster {n}
% EN - expected total number of voxels {N}
%
%___________________________________________________________________________
%
% spm_P_RF returns the probability of c or more clusters with more than
% k voxels 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
%
% Ref: Hasofer AM (1978) Upcrossings of random fields
% Suppl Adv Appl Prob 10:14-21
% Ref: Friston et al (1993) Comparing functional images: Assessing
% the spatial extent of activation foci
% Ref: Worsley KJ et al 1996, Hum Brain Mapp. 4:58-73
%___________________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Karl Friston
% $Id: spm_P_RF.m 707 2006-12-06 16:42:20Z volkmar $
% get expectations
%===========================================================================
% get EC densities
%---------------------------------------------------------------------------
D = max(find(R));
R = R(1:D);
G = sqrt(pi)./gamma(([1:D])/2);
EC = spm_ECdensity(STAT,Z,df);
EC = EC([1:D]) + eps;
% corrected p value
%---------------------------------------------------------------------------
P = triu(toeplitz(EC'.*G))^n;
P = P(1,:);
EM = (R./G).*P; % <maxima> over D dimensions
Em = sum(EM); % <maxima>
EN = P(1)*R(D); % <voxels>
En = EN/EM(D); % En = 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)/En)^(2/D);
p = exp(-beta*(k^(2/D)));
elseif STAT == 'T'
beta = (gamma(D/2 + 1)/En)^(2/D);
p = exp(-beta*(k^(2/D)));
elseif STAT == 'X'
beta = (gamma(D/2 + 1)/En)^(2/D);
p = exp(-beta*(k^(2/D)));
elseif STAT == 'F'
beta = (gamma(D/2 + 1)/En)^(2/D);
p = exp(-beta*(k^(2/D)));
end
% Poisson clumping heuristic {for multiple clusters}
%===========================================================================
P = 1 - spm_Pcdf(c - 1,(Em + eps)*p);
% set P and p = [] for non-implemented cases
%+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if k > 0 & n > 1
P = []; p = [];
end
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
|
spm/spm5-master
|
spm_dicom_headers.m
|
.m
|
spm5-master/spm_dicom_headers.m
| 19,177 |
utf_8
|
881b6df84445c830fb8c99d036502ce3
|
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 2300 2008-10-06 11:16:30Z guillaume $
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;
ret = read_dicom(fp, 'il',dict);
ret.Filename = fopen(fp);
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_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
otherwise,
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 = strread(dat,'%f','delimiter','\\')';
catch
dat = strread(dat,'%f','delimiter','/')';
end
case {'IS'},
dat = strread(dat,'%d','delimiter','\\')';
case {'DA'},
dat = strrep(dat,'.',' ');
[y,m,d] = strread(dat,'%4d%2d%2d');
dat = datenum(y,m,d);
case {'TM'},
if any(dat==':'),
[h,m,s] = strread(dat,'%d:%d:%f');
else
[h,m,s] = strread(dat,'%2d%2d%f');
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 = '';
fseek(fp,tag.length,'cof');
warning(['Unknown VR [' num2str(tag.vr+0) '] in "'...
fopen(fp) '" (offset=' num2str(ftell(fp)) ').']);
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;
n = n + 1;
ret{n} = Item;
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.le = 8;
tag.length = 0;
tmp = fread(fp,1,'ushort');
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);
if strcmp(computer,'PCWIN') || strcmp(computer,'PCWIN64'),
fprintf('This may be because of the way that the .tar.gz files\n');
fprintf('were unpacked when the SPM software was installed.\n');
fprintf('If installing on a Windows platform, then the software\n');
fprintf('used for unpacking may try to be clever and insert\n');
fprintf('additional unwanted control characters. If you use\n');
fprintf('WinZip, then you should ensure that TAR file smart\n');
fprintf('CR/LF conversion is disabled (under the Miscellaneous\n');
fprintf('Configuration Options).\n\n');
end;
rethrow(lasterr);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dict = readdict_txt
file = textread('spm_dicom_dict.txt','%s','delimiter','\n','whitespace','');
clear values
i = 0;
for i0=1:length(file),
words = strread(file{i0},'%s','delimiter','\t');
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>128 || 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)
unused = fread(fp,4,'uint8'); % Unused
unused = fread(fp,4,'uint8'); % Unused
n = fread(fp,1,'uint32');
if n>128 || n < 0,
fseek(fp,lim-4,'cof');
t = struct('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
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
for j=1:t(i).nitems
t(i).item(j).xx = fread(fp,4,'int32')'; % [x x 77 x]
len = t(i).item(j).xx(2);
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 = findstr(str_in,'+AF8-');
if ~isempty(pos),
str_out(pos) = '_';
str_out(repmat(pos,4,1)+repmat((1:4)',1,numel(pos))) = [];
end
return;
%_______________________________________________________________________
|
github
|
spm/spm5-master
|
spm_config_coreg.m
|
.m
|
spm5-master/spm_config_coreg.m
| 13,182 |
utf_8
|
f9c6e0cc429ce2dacdee008d8a00cc6e
|
function opts = spm_config_coreg
% Configuration file for coregister jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_coreg.m 1032 2007-12-20 14:45:55Z john $
ref.type = 'files';
ref.name = 'Reference Image';
ref.tag = 'ref';
ref.filter = 'image';
ref.num = 1;
ref.help = {[...
'This is the image that is assumed to remain stationary (sometimes ',...
'known as the target or template image), while the source image ',...
'is moved to match it.']};
%------------------------------------------------------------------------
source.type = 'files';
source.name = 'Source Image';
source.tag = 'source';
source.filter = 'image';
source.num = 1;
source.help = {...
'This is the image that is jiggled about to best match the reference.'};
%------------------------------------------------------------------------
other.type = 'files';
other.name = 'Other Images';
other.tag = 'other';
other.filter = 'image';
other.num = [0 Inf];
other.val = {''};
other.help = {[...
'These are any images that need to remain in alignment with the ',...
'source image.']};
%------------------------------------------------------------------------
cost_fun.type = 'menu';
cost_fun.name = 'Objective Function';
cost_fun.tag = 'cost_fun';
cost_fun.labels = {'Mutual Information','Normalised Mutual Information',...
'Entropy Correlation Coefficient','Normalised Cross Correlation'};
cost_fun.values = {'mi','nmi','ecc','ncc'};
cost_fun.def = 'coreg.estimate.cost_fun';
cost_fun.help = {[...
'Registration involves finding parameters that either maximise or ',...
'minimise some objective function. ',...
'For inter-modal registration, use Mutual Information\* \cite{collignon95,wells96}*/, Normalised Mutual Information/* \cite{studholme99}*/, or ',...
'Entropy Correlation Coefficient/* \cite{maes97}*/.',...
'For within modality, you could also use Normalised Cross Correlation.']};
%------------------------------------------------------------------------
sep.type = 'entry';
sep.name = 'Separation';
sep.tag = 'sep';
sep.num = [1 Inf];
sep.strtype = 'e';
sep.def = 'coreg.estimate.sep';
sep.help = {[...
'The average distance between sampled points (in mm). Can be a vector ',...
'to allow a coarse registration followed by increasingly fine ones.']};
%------------------------------------------------------------------------
tol.type = 'entry';
tol.name = 'Tolerances';
tol.tag = 'tol';
tol.num = [1 12];
tol.strtype = 'e';
tol.def = 'coreg.estimate.tol';
tol.help = {[...
'The accuracy for each parameter. Iterations stop when differences ',...
'between successive estimates are less than the required tolerance.']};
%------------------------------------------------------------------------
fwhm.type = 'entry';
fwhm.name = 'Histogram Smoothing';
fwhm.tag = 'fwhm';
fwhm.num = [1 2];
fwhm.strtype = 'e';
fwhm.def = 'coreg.estimate.fwhm';
fwhm.help = {[...
'Gaussian smoothing to apply to the 256x256 joint histogram. Other ',...
'information theoretic coregistration methods use fewer bins, but ',...
'Gaussian smoothing seems to be more elegant.']};
%------------------------------------------------------------------------
eoptions.type = 'branch';
eoptions.name = 'Estimation Options';
eoptions.tag = 'eoptions';
eoptions.val = {cost_fun,sep,tol,fwhm};
eoptions.help = {...
['Various registration options, which are passed to the ',...
'Powell optimisation algorithm/* \cite{press92}*/.']};
%------------------------------------------------------------------------
est.type = 'branch';
est.name = 'Coreg: Estimate';
est.tag = 'estimate';
est.val = {ref,source,other,eoptions};
est.prog = @estimate;
p1 = [...
'The registration method used here is based on work by Collignon et al/* \cite{collignon95}*/. ',...
'The original interpolation method described in this paper has been ',...
'changed in order to give a smoother cost function. The images are ',...
'also smoothed slightly, as is the histogram. This is all in order to ',...
'make the cost function as smooth as possible, to give faster ',...
'convergence and less chance of local minima.'];
p2 = [...
'At the end of coregistration, the voxel-to-voxel affine transformation ',...
'matrix is displayed, along with the histograms for the images in the ',...
'original orientations, and the final orientations. The registered ',...
'images are displayed at the bottom.'];
p3 = [...
'Registration parameters are stored in the headers of the "source" ',...
'and the "other" images.'];
est.help = {p1,'',p2,'',p3};
%------------------------------------------------------------------------
interp.type = 'menu';
interp.name = 'Interpolation';
interp.tag = 'interp';
interp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-Spline',...
'3rd Degree B-Spline','4th Degree B-Spline','5th Degree B-Spline',...
'6th Degree B-Spline','7th Degree B-Spline'};
interp.values = {0,1,2,3,4,5,6,7};
interp.def = 'coreg.write.interp';
interp.help = {[...
'The method by which the images are sampled when being written in a ',...
'different space. ',...
'Nearest Neighbour is fastest, but not normally recommended. ',...
'It can be useful for re-orienting images while preserving the original ',...
'intensities (e.g. an image consisting of labels). ',...
'Bilinear Interpolation is OK for PET, or realigned and re-sliced fMRI. ',...
'If subject movement (from an fMRI time series) is included in the transformations ',...
'then it may be better to use a higher degree approach. ',...
'Note that higher degree B-spline interpolation/* \cite{thevenaz00a,unser93a,unser93b}*/ is slower because it uses more ',...
'neighbours.']};
%------------------------------------------------------------------------
wrap.type = 'menu';
wrap.name = 'Wrapping';
wrap.tag = 'wrap';
wrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z',...
'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'};
wrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]};
wrap.def = 'coreg.write.wrap';
wrap.help = {...
'These are typically:',...
[' No wrapping - for PET or images that have already',...
' been spatially transformed.'],...
[' Wrap in Y - for (un-resliced) MRI where phase encoding',...
' is in the Y direction (voxel space).']};
%------------------------------------------------------------------------
mask.type = 'menu';
mask.name = 'Masking';
mask.tag = 'mask';
mask.labels = {'Mask images','Dont mask images'};
mask.values = {1,0};
mask.def = 'coreg.write.mask';
mask.help = {[...
'Because of subject motion, different images are likely to have different ',...
'patterns of zeros from where it was not possible to sample data. ',...
'With masking enabled, the program searches through the whole time series ',...
'looking for voxels which need to be sampled from outside the original ',...
'images. Where this occurs, that voxel is set to zero for the whole set ',...
'of images (unless the image format can represent NaN, in which case ',...
'NaNs are used where possible).']};
%------------------------------------------------------------------------
roptions.type = 'branch';
roptions.name = 'Reslice Options';
roptions.tag = 'roptions';
roptions.val = {interp,wrap,mask};
roptions.help = {'Various reslicing options.'};
%------------------------------------------------------------------------
estwrite.type = 'branch';
estwrite.name = 'Coreg: Estimate & Reslice';
estwrite.tag = 'estwrite';
estwrite.val = {ref,source,other,eoptions,roptions};
estwrite.prog = @estimate_reslice;
estwrite.vfiles = @vfiles_estwrite;
p1 = [...
'The registration method used here is based on work by Collignon et al/* \cite{collignon95}*/. ',...
'The original interpolation method described in this paper has been ',...
'changed in order to give a smoother cost function. The images are ',...
'also smoothed slightly, as is the histogram. This is all in order to ',...
'make the cost function as smooth as possible, to give faster ',...
'convergence and less chance of local minima.'];
p2 = [...
'At the end of coregistration, the voxel-to-voxel affine transformation ',...
'matrix is displayed, along with the histograms for the images in the ',...
'original orientations, and the final orientations. The registered ',...
'images are displayed at the bottom.'];
p3 = [...
'Registration parameters are stored in the headers of the "source" ',...
'and the "other" images. These images are also resliced to match the ',...
'source image voxel-for-voxel. The resliced images are named the same as ',...
'the originals except that they are prefixed by ''r''.'];
estwrite.help = {p1,'',p2,'',p3};
%------------------------------------------------------------------------
ref.type = 'files';
ref.name = 'Image Defining Space';
ref.tag = 'ref';
ref.filter = 'image';
ref.num = 1;
ref.help = {[...
'This is analogous to the reference image. Images are resliced to match ',...
'this image (providing they have been coregistered first).']};
%------------------------------------------------------------------------
source.type = 'files';
source.name = 'Images to Reslice';
source.tag = 'source';
source.filter = 'image';
source.num = Inf;
source.help = {[...
'These images are resliced to the same dimensions, voxel sizes, ',...
'orientation etc as the space defining image.']};
%------------------------------------------------------------------------
write.type = 'branch';
write.name = 'Coreg: Reslice';
write.tag = 'write';
write.val = {ref,source,roptions};
write.prog = @reslice;
write.vfiles = @vfiles_write;
write.help = {[...
'Reslice images to match voxel-for-voxel with an image defining ',...
'some space. The resliced images are named the same as the originals ',...
'except that they are prefixed by ''r''.']};
%------------------------------------------------------------------------
opts.type = 'repeat';
opts.name = 'Coreg';
opts.tag = 'coreg';
opts.values = {est,write,estwrite};
opts.num = [1 Inf];
opts.modality = {'PET','FMRI','VBM'};
p1 = [...
'Within-subject registration using a rigid-body model. ',...
'A rigid-body transformation (in 3D) can be parameterised by three ',...
'translations and three rotations about the different axes.'];
p2 = [...
'You get the options of estimating the transformation, reslicing images ',...
'according to some rigid-body transformations, or estimating and ',...
'applying rigid-body transformations.'];
opts.help = {p1,'',p2};
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function estimate(varargin)
job = varargin{1};
%disp(job);
%disp(job.eoptions);
x = spm_coreg(strvcat(job.ref), strvcat(job.source),job.eoptions);
M = inv(spm_matrix(x));
PO = strvcat(strvcat(job.source),strvcat(job.other));
MM = zeros(4,4,size(PO,1));
for j=1:size(PO,1),
MM(:,:,j) = spm_get_space(deblank(PO(j,:)));
end;
for j=1:size(PO,1),
spm_get_space(deblank(PO(j,:)), M*MM(:,:,j));
end;
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function reslice(varargin)
job = varargin{1};
P = strvcat(strvcat(job.ref),strvcat(job.source));
flags.mask = job.roptions.mask;
flags.mean = 0;
flags.interp = job.roptions.interp;
flags.which = 1;
flags.wrap = job.roptions.wrap;
spm_reslice(P,flags);
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function estimate_reslice(varargin)
job = varargin{1};
%disp(job);
%disp(job.eoptions);
%disp(job.roptions);
job.ref = strvcat(job.ref);
job.source = strvcat(job.source);
job.other = strvcat(job.other);
x = spm_coreg(job.ref, job.source,job.eoptions);
M = inv(spm_matrix(x));
PO = strvcat(job.source,job.other);
MM = zeros(4,4,size(PO,1));
for j=1:size(PO,1),
MM(:,:,j) = spm_get_space(deblank(PO(j,:)));
end;
for j=1:size(PO,1),
spm_get_space(deblank(PO(j,:)), M*MM(:,:,j));
end;
P = strvcat(job.ref,job.source,job.other);
flags.mask = job.roptions.mask;
flags.mean = 0;
flags.interp = job.roptions.interp;
flags.which = 1;
flags.wrap = job.roptions.wrap;
spm_reslice(P,flags);
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles_write(varargin)
job = varargin{1};
vf = cell(size(job.source));
for i=1:numel(job.source),
[pth,nam,ext,num] = spm_fileparts(job.source{i});
vf{i} = fullfile(pth,['r', nam, ext, num]);
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles_estwrite(varargin)
job = varargin{1};
P = {job.source{:},job.other{:}};
vf = cell(size(P));
for i=1:numel(P),
[pth,nam,ext,num] = spm_fileparts(P{i});
vf{i} = fullfile(pth,['r', nam, ext, num]);
end;
|
github
|
spm/spm5-master
|
spm_image.m
|
.m
|
spm5-master/spm_image.m
| 20,429 |
utf_8
|
891123a6397852f97de13a1b3463ab74
|
function spm_image(op,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
% ``.mat'' files of the selected images. The transformations are
% considered to be relative to any existing transformations that may be
% stored in the ``.mat'' files. 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 (as would be displayed
% by Analyze) or world space (the orientation that SPM considers the
% image to be in). 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) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_image.m 2526 2008-12-03 11:42:57Z john $
global st
if nargin == 0,
spm('FnUIsetup','Display',0);
spm('FnBanner',mfilename,'$Rev: 2526 $');
spm_help('!ContextHelp',[mfilename,'.m']);
% get the image's filename {P}
%-----------------------------------------------------------------------
P = spm_select(1,'image','Select image',[],0);
spm_image('init',P);
return;
end;
try
if ~strcmp(op,'init') && ~strcmp(op,'reset') && isempty(st.vols{1})
my_reset; warning('Lost all the image information');
return;
end;
catch
end
if strcmp(op,'repos'),
% The widgets for translation rotation or zooms have been modified.
%-----------------------------------------------------------------------
fg = spm_figure('Findwin','Graphics');
set(fg,'Pointer','watch');
i = varargin{1};
st.B(i) = eval(get(gco,'String'),num2str(st.B(i)));
set(gco,'String',st.B(i));
st.vols{1}.premul = spm_matrix(st.B);
% spm_orthviews('MaxBB');
spm_image('zoom_in');
spm_image('update_info');
set(fg,'Pointer','arrow');
return;
end;
if strcmp(op,'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;
return;
end;
if strcmp(op,'setposmm'),
% Move the crosshairs to the specified position
%-----------------------------------------------------------------------
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;
return;
end;
if strcmp(op,'setposvx'),
% Move the crosshairs to the specified position
%-----------------------------------------------------------------------
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;
return;
end;
if strcmp(op,'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,VOL] = 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,VOL.XYZ,VOL.Z,VOL.M,colours(c,:));
set(st.blobber,'String','Remove Blobs','Callback','spm_image(''rmblobs'');');
end;
spm_orthviews('addcontext',1);
spm_orthviews('Redraw');
end;
if strcmp(op,'rmblobs'),
% Remove all blobs from the images
spm_orthviews('rmblobs',1);
set(st.blobber,'String','Add Blobs','Callback','spm_image(''addblobs'');');
spm_orthviews('rmcontext',1);
spm_orthviews('Redraw');
end;
if strcmp(op,'window'),
op = get(st.win,'Value');
if op == 1,
spm_orthviews('window',1);
else
spm_orthviews('window',1,spm_input('Range','+1','e','',2));
end;
end;
if strcmp(op,'reorient'),
% Time to modify the ``.mat'' files for the images.
% I hope that giving people this facility is the right thing to do....
%-----------------------------------------------------------------------
mat = spm_matrix(st.B);
if det(mat)<=0
spm('alert!','This will flip the images',mfilename,0,1);
end;
P = spm_select(Inf, 'image','Images to reorient');
Mats = zeros(4,4,size(P,1));
spm_progress_bar('Init',size(P,1),'Reading current orientations',...
'Images Complete');
for i=1:size(P,1),
Mats(:,:,i) = spm_get_space(P(i,:));
spm_progress_bar('Set',i);
end;
spm_progress_bar('Init',size(P,1),'Reorienting images',...
'Images Complete');
for i=1:size(P,1),
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;
return;
end;
if strcmp(op,'resetorient'),
% Time to modify the ``.mat'' files for the images.
% I hope that giving people this facility is the right thing to do....
%-----------------------------------------------------------------------
P = spm_select(Inf, 'image','Images to reset orientation of');
spm_progress_bar('Init',size(P,1),'Resetting orientations',...
'Images Complete');
for i=1:size(P,1),
V = spm_vol(deblank(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;
return;
end;
if strcmp(op,'update_info'),
% 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-6,
set(st.posinf.w, 'String', 'Warning: shears involved');
else
set(st.posinf.w, 'String', '');
end;
return;
end;
if strcmp(op,'reset'),
my_reset;
end;
if strcmp(op,'zoom_in'),
op = get(st.zoomer,'Value');
if op==1,
spm_orthviews('resolution',1);
spm_orthviews('MaxBB');
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)';
if op == 2, st.bb = [pos-80*vx ; pos+80*vx] ; spm_orthviews('resolution',1);
elseif op == 3, st.bb = [pos-40*vx ; pos+40*vx] ; spm_orthviews('resolution',.5);
elseif op == 4, st.bb = [pos-20*vx ; pos+20*vx] ; spm_orthviews('resolution',.25);
elseif op == 5, st.bb = [pos-10*vx ; pos+10*vx] ; spm_orthviews('resolution',.125);
else st.bb = [pos- 5*vx ; pos+ 5*vx] ; spm_orthviews('resolution',.125);
end;
end;
return;
end;
if strcmp(op,'init'),
fg = spm_figure('GetWin','Graphics');
if isempty(fg), error('Can''t create graphics window'); end
spm_figure('Clear','Graphics');
P = varargin{1};
if ischar(P), P = spm_vol(P); end;
P = P(1);
spm_orthviews('Reset');
spm_orthviews('Image', P, [0.0 0.45 1 0.55]);
if isempty(st.vols{1}), return; end;
spm_orthviews('MaxBB');
st.callback = 'spm_image(''shopos'');';
st.B = [0 0 0 0 0 0 1 1 1 0 0 0];
% locate Graphics window and clear it
%-----------------------------------------------------------------------
WS = spm('WinScale');
% Widgets for re-orienting images.
%-----------------------------------------------------------------------
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','foward {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);
st.zoomer = uicontrol(fg,'Style','popupmenu' ,'Position',[315 75 125 20].*WS,...
'String',char('Full Volume','160x160x160mm','80x80x80mm','40x40x40mm','20x20x20mm','10x10x10mm'),...
'Callback','spm_image(''zoom_in'')','ToolTipString','zoom in by different amounts');
c = 'if get(gco,''Value'')==1, spm_orthviews(''Space''), else, spm_orthviews(''Space'', 1);end;spm_image(''zoom_in'')';
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');
end;
return;
function my_reset
spm_orthviews('reset');
spm_figure('Clear','Graphics');
return;
|
github
|
spm/spm5-master
|
bst_message_window.m
|
.m
|
spm5-master/bst_message_window.m
| 17,952 |
utf_8
|
351c51b02858e087e1bb53dae05b3986
|
function varargout = bst_message_window(varargin)
%BST_MESSAGE_WINDOW - Application M-file for bst_message_window.fig, with NON CALLBACKS
% function varargout = bst_message_window(varargin)
% FIG = BST_MESSAGE_WINDOW launch bst_message_window GUI.
% BST_MESSAGE_WINDOW('callback_name', ...) invoke the named callback.
% NON CALLBACKS:
% bst_message_window(cellstr) appends cell array of strings cellstr to window
% bst_message_window('append',str) appends string or cell of strings to window
% bst_message_window(str) will also append string, unless it is a valid function call
% bst_message_window('wrap',str) will wrap string or cell of strings to the window
% bst_message_window('unique',str) will wrap string or cell of strings to a unique window,
% bst_message_window('process',str) send str to the ProcessLauncher GUI (see also bst_ProcessLauncher)
% returning the handle to the window, i.e. it won't go to the message window, but rather
% its own message window.
% bst_message_window('overwrite',str) overwrites the last line with the new string
%
% bst_message_window('close') removes the window, otherise the CloseRequestFcn executes
% If window does not exist, 'append' will open it
%<autobegin> ---------------------- 27-Jun-2005 10:43:34 -----------------------
% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------
%
% CATEGORY: GUI and Related
%
% Alphabetical list of external functions (non-Matlab):
% toolbox\bst_color_scheme.m
% toolbox\bst_layout.m
% toolbox\bst_message_window.m NOTE: Routine calls itself explicitly
%
% Subfunctions in this file, in order of occurrence in file:
% varargout = process(str,fig);
% varargout = append(str,fig);
% varargout = unique(str);
% varargout = wrap(str,fig);
% varargout = overwrite(rep_str,fig);
% varargout = close();
% varargout = Messages_Callback(h, eventdata, handles, varargin)
% varargout = clear_selected_Callback(h, eventdata, handles, varargin)
% varargout = clear_all_Callback(h, eventdata, handles, varargin)
% varargout = BrainStormMessages_CloseRequestFcn(h, eventdata, handles, varargin)
% varargout = BrainStormMessages_ResizeFcn(h, eventdata, handles, varargin)
%
% Application data and their calls in this file:
% 'BrainStormMessageWindow'
% 'MAXLength'
% 'TileType'
%
% setappdata(0,'BrainStormMessageWindow',fig);
% setappdata(fig,'MAXLength',200);
% setappdata(fig,'TileType','M');
% setappdata(fig,'TileType','T');
%
% MAXLength = getappdata(fig,'MAXLength');
% delete(getappdata(0,'BrainStormMessageWindow'));
% fig = getappdata(0,'BrainStormMessageWindow');
% if(~ishandle(getappdata(0,'BrainStormMessageWindow')))
%
% Figure Files opened by this function:
% mfilename
%
% Format of strings below: Type:Style:Tag, "String", CallBack Type and Call
% <automatic> callback is <Tag>_Callback by Matlab default
%
% Callbacks by figure bst_message_window.fig
% figure::BrainStormMessages "" uses ResizeFcn for <automatic>
% uicontrol:listbox:Messages "BrainStorm Message Window" uses Callback for <automatic>
%
% At Check-in: $Author: Mosher $ $Revision: 28 $ $Date: 6/27/05 8:59a $
%
% This software is part of BrainStorm Toolbox Version 27-June-2005
%
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
% University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
% Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
% CNRS, Hopital de la Salpetriere, Paris, France
%
% See BrainStorm website at http://neuroimage.usc.edu for further information.
%
% Copyright (c) 2005 BrainStorm by the University of Southern California
% This software distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 27-Jun-2005 10:43:34 -----------------------
% ----------------- Change History ------------------------
% JCM 27 Feb 2002 changed propertyname to BrainStormMessageWindow, handled "catch" for string input
% JCM 3 May 2002 added 'wrap' and 'overwrite' options
% JCM 10 May 2002 changed CloseRequestFcn to allow non-modal closing.
% JCM 15 May 2002 updated 'overwrite' to allow multiple lines of overwrite
% SB 15 Oct 2002 when BrainStorm GUIs are closed (e.g. when using command-line BrainStorm)
% bst_message_window uses the basic DISP command to display info in
% Matlab's command window
% JCM 29 Oct 2002 Preferences should not be erased. Test for presence of taskbar,
% using getappdata(0,'BrainStormTaskbar'); Fixed MAXLength use, should be
% an appdata in the message figure, also rolls the last MAXLength lines,
% rather than clearing. All cases now handle non-gui mode.
% Redid message window to be along the bottom of the screen.
% JCM 13 May 2003 Moved message window buttons to new layout_manager, made window
% compatible with layout manager
% JCM 09 Jun 2003 Added "unique" function to allow use for a convenient message and information window
% JCM 26 Jan 2005 Felix fixed rep_str typo in overwrite function
% SB 08 Feb 2005 Added the 'process' option:
% -> bst_message_window('process',str): send str to the ProcessLauncher GUI (see also bst_ProcessLauncher)
% JCM 08-Jun-2005 Set fonts in the creation and resize functions to be
% fixed 8 point size,after running the bst_color_scheme function.
% ----------------------------------------------------------
% Last Modified by GUIDE v2.5 08-Jun-2005 15:20:15
if nargin == 0 % LAUNCH GUI
fig = openfig(mfilename,'reuse');
% Use system color scheme for figure:
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
% Generate a structure of handles to pass to callbacks, and store it.
handles = guihandles(fig);
guidata(fig, handles);
if nargout > 0
varargout{1} = fig;
end
% BrainStorm specific code here
bst_color_scheme(fig);
set(handles.Messages,'fontname','FixedWidth'); % good for tables
% lock in font units and size to keep from scaling
set(handles.Messages,'fontunits','points','fontsize',8);
setappdata(fig,'TileType','M'); % message window
bst_layout('align',fig);
setappdata(0,'BrainStormMessageWindow',fig); % set the handle in the taskbar application data
% ------ SET MAXIMUM NUMBER OF LINES TO BE DISPLAYED ------------------
setappdata(fig,'MAXLength',200); % Maximum number of lines to be displayed in the message window.
% too many lines significantly slows down all BsT processes.
% JCM changed 29 Oct to roll the last 200 lines, not clear.
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
try
if (nargout)
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
catch
% string was not a valid function call, treat as a string
try
append(varargin); % try appending the string
catch
disp(lasterr);
end
end
elseif iscell(varargin{1}) % input is a cell array
append(varargin{1});
end
% ---------------- subfunctions -----------------
% --------------------------------------------------------------------
function varargout = process(str,fig);
% Send messages to ProcessLauncher GUI
processGUI = findobj(0,'type','figure','tag','bst_ProcessLauncher');
HprocessGUI = guihandles(processGUI);
set(HprocessGUI.dProgressReport,'String',str)
% --------------------------------------------------------------------
function varargout = append(str,fig);
% Call as bst_message_window('append',str)
% alternatively, if string is unrecognized command, switchyard will call this subfunction
if ischar(str),
str = {str}; % convert to cell array
end
% Test whether user is calling BrainStorm routines from command line function calls or GUIs.
if ~isappdata(0,'BrainStormTaskbar')
% The taskbar does not exists, assume we are in command line mode
for i = 1:length(str),
disp(str{i});
end
return % break away
end
% else we are in GUI mode
% get the handle to the message window
if(~isappdata(0,'BrainStormMessageWindow')), % missing
bst_message_window; % create it
end
if(~ishandle(getappdata(0,'BrainStormMessageWindow')))
bst_message_window; % invalid handle, create it again
end
% append a string to the message window. str is either string or cell of strings.
if(~exist('fig','var')), % caller did not give fig handle (default)
fig = getappdata(0,'BrainStormMessageWindow');
end
handles = guidata(fig); % handles in that figure
MAXLength = getappdata(fig,'MAXLength');
lenstr = length(str); % number of lines being added
oldstr = get(handles.Messages,'string');
if ischar(oldstr)
oldstr = {oldstr}; % convert to cell array
end
oldstr(end+[1:lenstr]) = str; % add new strings to end of old string
ndx = [-MAXLength:0]+length(oldstr); % last MAXLength lines
% ndx may be negative, if length shorter than MAXLength
ndx = ndx(ndx > 0); % keep only the positive ones
%trim
oldstr = oldstr(ndx);
% select all of the new message for visibility to the user
set(handles.Messages,'string',oldstr,...
'val',length(oldstr)+[(1-lenstr):0],...
'listboxtop',length(oldstr)); % put in
figure(fig); % bring to the front
drawnow
if nargout > 0
varargout{1} = fig;
end
% -------------------------------------------------------------------
function varargout = unique(str);
% wrap text to a unique message window, not the main window
% JCM 9-Jun-2003 creating a variant of the message window
fig = openfig(mfilename,'new'); % new unique filename
% Use system color scheme for figure:
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
% Generate a structure of handles to pass to callbacks, and store it.
handles = guihandles(fig);
guidata(fig, handles);
if nargout > 0
varargout{1} = fig;
end
% BrainStorm specific code here
bst_color_scheme(fig);
set(handles.Messages,'fontname','FixedWidth'); % good for tables
setappdata(fig,'TileType','T'); % tile
bst_layout('align',fig,1,2,1); % default action, can be set in calling routine as well
% customize for a unique message window
set(fig,'Name','Information','Tag','Information','CloseRequestFcn','closereq','ResizeFcn',[]);
overwrite(sprintf('Information Message %s',datestr(now)),fig); % replace the "BrainStorm Message Window" line
% ------ SET MAXIMUM NUMBER OF LINES TO BE DISPLAYED ------------------
setappdata(fig,'MAXLength',200); % Maximum number of lines to be displayed in the message window.
% too many lines significantly slows down all BsT processes.
% JCM changed 29 Oct to roll the last 200 lines, not clear.
wrap(str,fig); % now wrap the text to just this unique fig
% --------------------------------------------------------------------
function varargout = wrap(str,fig);
% called as mfilename('wrap',str), wrap string to the window
if ischar(str),
str = {str}; % convert to cell for consistent handling
end
if ~isappdata(0,'BrainStormTaskbar')
% The taskbar does not exists, assume we are in command line mode
for i = 1:length(str),
disp(str{i});
end
return % break away
end
% else we are in GUI Mode
% get the handle to the message window
if(~isappdata(0,'BrainStormMessageWindow')), % missing
bst_message_window; % create it
end
if(~exist('fig','var')), % user did not give as input to this function (default)
fig = getappdata(0,'BrainStormMessageWindow');
end
handles = guidata(fig); % handles in that figure
if(0), % deprecated, user may send cell array of strings
% first convert str into one long message string, with proper spaces
msg_str = [];
for i = 1:length(str),
msg_str = [msg_str str{i}];
if(~strcmp(msg_str(end),' ')),
msg_str(end+1) = ' ';
end
end
msg_str(end) = []; % remove last space
else
msg_str = str; % don't alter
end
% wrap the text to the message window
% textwrap in R12.1 is a little too wide
mesPos = get(handles.Messages,'position');
mesWidth = mesPos(3); % current width
set(handles.Messages,'position',[mesPos(1:2) mesWidth*.95 mesPos(4)]); % slightly narrower
outstring = textwrap(handles.Messages,msg_str); % wrap to columns
set(handles.Messages,'position',mesPos); % original size
append(outstring,fig);
if nargout > 0
varargout{1} = fig;
end
% --------------------------------------------------------------------
function varargout = overwrite(rep_str,fig);
% Overwrite the last lines of the message window with cell array of rep_str
% if rep_str is a string, overwrite just the last line.
% Useful for updating a "Processing . . ." with a "Done"
% or a pseudo waitbar,
% bst_message_window('Wait: 1 of 10')
% for i = 2:10,bst_message_window('overwrite',sprintf('Wait: %.0f of 10',i)),<process>,end
if(ischar(rep_str)),
rep_str = {rep_str}; % make cell for consistent handling
end
if ~isappdata(0,'BrainStormTaskbar')
% The taskbar does not exists, assume we are in command line mode
for i = 1:length(rep_str),
disp(rep_str{i});
end
return % break away
end
NumLines = length(rep_str); % how many lines to replace
% get the handle to the message window
if(~isappdata(0,'BrainStormMessageWindow')), % missing
bst_message_window; % create it
end
if(~exist('fig','var')), % user did not give as input to this function (default)
fig = getappdata(0,'BrainStormMessageWindow');
end
handles = guidata(fig); % handles in that figure
str = get(handles.Messages,'string'); %existing strings
if(ischar(str)),
str = {str}; % make cell for consistent handling
end
if(length(str) >= NumLines),
str([(1-NumLines):0]+end) = rep_str;
else
% there are not enough lines in the display, just append
str(end+[1:NumLines]) = rep_str;
end
set(handles.Messages,...
'string',str,'listboxtop',...
length(str),'val',length(str)+[(1-NumLines):0]); % put in, with new strings clearly showing
if nargout > 0
varargout{1} = fig;
end
% --------------------------------------------------------------------
function varargout = close();
% close the message window. Otherwise, the CloseRequestFcn will execute
delete(getappdata(0,'BrainStormMessageWindow')); % close the window
rmappdata(0,'BrainStormMessageWindow'); % clear the application data
% -------------- Callback routines -----------------------
% --------------------------------------------------------------------
function varargout = Messages_Callback(h, eventdata, handles, varargin)
% double clicking will remove a line. Otherwise, no effect
% doulbe right clicking will remove lots of highlighted lines
status = get(handles.BrainStormMessages,'SelectionType');
switch status
case 'normal' % do nothing
case 'open' % user double clicked
clear_selected_Callback(h,eventdata,handles,varargin);
end
% --------------------------------------------------------------------
function varargout = clear_selected_Callback(h, eventdata, handles, varargin)
% clear the selected messages, keep the view stable
val = get(handles.Messages,'val'); % vector of lines to delete
str = get(handles.Messages,'string'); %existing strings
listboxtop = get(handles.Messages,'listboxtop'); %what is showing at the top of window
str(val) = []; % remove the existing strings
val = val(1); % set to last string deleted
val = min(val,length(str)); % in acceptable range
listboxtop = min(listboxtop,val); % in acceptable range
listboxtop = min(listboxtop,length(str)); % in acceptable range
if(length(str) == 0),
set(handles.Messages,'val',1,'ListBoxTop',1,'string',{'BrainStorm Message Window'})
else
set(handles.Messages,'val',val,'string',str,'listboxtop',listboxtop);
end
% --------------------------------------------------------------------
function varargout = clear_all_Callback(h, eventdata, handles, varargin)
% no longer a button for this 13 May 2003
% can instead highlight lots of lines, then double right click to remove them
ButtonName = questdlg('Clear all lines?','Message Window','Yes','No','No');
switch ButtonName
case 'Yes'
set(handles.Messages,'val',1,'ListBoxTop',1,'string',{'BrainStorm Message Window'})
end
% --------------------------------------------------------------------
function varargout = BrainStormMessages_CloseRequestFcn(h, eventdata, handles, varargin)
% since this window now automatically opens when needed, this forced closure
% is no longer really necessary. JCM 13-May-2002
if(0), % deprecated code
str = {'','This BrainStorm message window should stay open.',''};
bst_message_window('append',str);
ButtonName = questdlg('Close the message window?','Message Window','Yes','No','No');
switch ButtonName
case 'Yes'
bst_message_window('close');
end
else % newer code, non-modal closing
bst_message_window('close');
disp(' ')
disp('Generally, the BrainStorm Message Window should remain open.')
disp('Message window closed.')
end
% --------------------------------------------------------------------
function varargout = BrainStormMessages_ResizeFcn(h, eventdata, handles, varargin)
% want to keep the fonts at the same size
bst_color_scheme(handles.BrainStormMessages);
set(handles.Messages,'fontunits','points');
set(handles.Messages,'fontsize',8);
|
github
|
spm/spm5-master
|
spm_transverse.m
|
.m
|
spm5-master/spm_transverse.m
| 14,752 |
utf_8
|
235f415df5b92c21eb90a49c70ebbcbb
|
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) 2005 Wellcome Department of Imaging Neuroscience
% Karl Friston & John Ashburner
% $Id: spm_transverse.m 212 2005-08-19 10:50:18Z will $
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)
%-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]);
% 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.0fmm',tmp(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;
ax=transv.h(5);tpoint=get(ax,'title');
str=sprintf('z = %0.0fmm',tmp(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.0fmm',tmp(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.0fmm',xyzmm(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)
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)
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
|
spm/spm5-master
|
spm_select.m
|
.m
|
spm5-master/spm_select.m
| 41,694 |
utf_8
|
3afb406cb219867c0fbed6974862cc3a
|
function [t,sts] = spm_select(varargin)
% File selector
% FORMAT [t,sts] = spm_select(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
% 'image' - Image files (".img" and ".nii")
% Note that it gives the option to select
% individual volumes of the images.
% 'xml' - XML files
% 'mat' - Matlab .mat files
% 'batch' - SPM batch files (.mat and XML)
% 'dir' - select a directory
% 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)
%
% Files can be selected from disk, but "virtual" files can also be selected.
% Virtual filenames are passed by
% spm_select('addvfiles',list)
% where list is a cell array of filenames
% The list can be cleared by
% spm_select('clearvfiles')
%
% FORMAT [t,sts] = spm_select('Filter',files,typ,filt,frames)
% filter the list of files (cell or char array) in the same way as the GUI would do.
% There is an additional typ 'extimage' which will match images with
% frame specifications, too. Also, there is a typ 'extdir', which will
% match canonicalised directory names.
%
% FORMAT cpath = spm_select('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 [defaut '.']
% cpath - conditioned paths, in same format as input path argument
%
% FORMAT [files,dirs]=spm_select('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]=spm_select('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)
% FORMAT [files,dirs]=spm_select('FPList',direc,filt)
% FORMAT [files,dirs]=spm_select('ExtFPList',direc,filt,frames)
% As above, but returns files with full paths (i.e. prefixes direc to each)
%____________________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_select.m 1746 2008-05-28 17:43:42Z guillaume $
if nargin > 0 && ischar(varargin{1})
switch lower(varargin{1})
case 'addvfiles'
error(nargchk(2,Inf,nargin));
vfiles('add',varargin{2:end});
case 'clearvfiles'
error(nargchk(1,1,nargin));
vfiles('clear');
case 'vfiles'
error(nargchk(1,1,nargin));
t = vfiles('all');
case 'cpath'
error(nargchk(2,Inf,nargin));
t = cpath(varargin{2:end});
case 'filter'
filt = mk_filter(varargin{3:end});
cs = iscell(varargin{2});
if ~cs
t = cellstr(varargin{2});
else
t = varargin{2};
end;
[t,sts] = do_filter(t,filt.ext);
[t,sts] = do_filter(t,filt.filt);
if ~cs
t = strvcat(t);
end;
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)
if regexpi(varargin{1}, 'fplist') % return full pathnames
direc = spm_select('cpath', varargin{2});
% remove trailing path separator if present
direc = regexprep(direc, [filesep '$'], '');
t = strcat(repmat(direc, size(t, 1), 1), filesep, t);
if nargout > 1
% subdirs too
nsd = size(sts, 1);
sts = strcat(repmat(direc, nsd, 1), filesep, sts);
% /blah/blah/. and /blah/blah/.. not canonical, fix:
sts = cellstr(sts);
mch = [filesep '\.$'];
sts = regexprep(sts, mch, '');
mch = [filesep '[^' filesep ']+' filesep '\.\.$'];
sts = regexprep(sts, mch, '');
sts = char(sts);
end
end
otherwise
error('Inappropriate usage.');
end
else
[t,sts] = selector(varargin{:});
end
%=======================================================================
%=======================================================================
function [t,ok] = selector(n,typ,mesg,already,wd,filt,frames,varargin)
if nargin<7, frames = '1'; end;
if nargin<6, filt = '.*'; end;
if nargin<5, wd = pwd; end;
if nargin<4, already = {''}; end;
if nargin<3, mesg = 'Select files...'; end;
if nargin<2, typ = 'any'; end;
if nargin<1, n = [0 Inf]; end;
ok = 0;
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;
already = strvcat(already);
t = '';
sfilt = mk_filter(typ,filt,frames);
[col1,col2,col3,fs] = colours;
fg = figure('IntegerHandle','off',...
'Tag','Select',...
'Name',strvcat(mesg),...
'NumberTitle','off',...
'Units','Pixels',...
'MenuBar','none',...
'DefaultTextInterpreter','none',...
'DefaultUicontrolInterruptible','on',...
'ResizeFcn',@resize_fun,...
'KeyPressFcn',@hitkey);
% Code from Brian Lenoski for dealing with multiple monitors
if spm_matlab_version_chk('7') >=0
S = get(0, 'MonitorPosition');
Rect = get(fg,'Position');
pointer_loc = get(0,'PointerLocation');
for i = 1:size(S,1), % Loop over monitors
h_min = S(i,1);
h_width = S(i,3);
h_max = h_width + h_min - 1;
v_min = S(i,2);
v_len = S(i,4);
v_max = v_min + v_len;
% Use the monitor containing the pointer
if pointer_loc(1) >= h_min && pointer_loc(1) < h_max && ...
pointer_loc(2) >= v_min && pointer_loc(2) < v_max,
hor_min = h_min;
hor_width = h_width;
hor_max = h_max;
ver_min = v_min;
ver_len = v_len;
ver_max = v_max;
end
end
Rect(1) = (hor_max - 0.5*hor_width) - 0.5*Rect(3); % Horizontal
Rect(2) = (ver_max - 0.5*ver_len) - 0.5*Rect(4); % Vertical
set(fg,'Position',Rect);
end
fh = 0.05;
%fs = 10;
sbh = 0.03; % Scroll-bar height. This should be worked out properly
h1 = (0.96-4*fh-5*0.01)/2;
if n(2)*fh+sbh<h1,
h1 = min([max([n(2) size(already,1)+.2])*fh+sbh, h1]);
end;
h2 = 0.96-4*fh-5*0.01-h1;
SPMdir = fileparts(which(mfilename));
if ( spm_matlab_version_chk('7') >= 0 ) && isdeployed,
ind = findstr(SPMdir,'_mcr')-1;
[SPMdir,junk] = fileparts(SPMdir(1:ind(1)));
end;
prevdirs([SPMdir filesep]);
[pd,vl] = prevdirs([wd filesep]);
% Selected Files
hp = 0.02;
sel = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',[0.02 hp 0.96 h1],...
'FontSize',fs,...
'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);
% Messages
hp = hp+h1+0.01;
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',[0.02 hp 0.96 fh],...
'FontSize',fs,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'HorizontalAlignment','left',...
'Tag','msg',...
'String',mesg);
if strcmpi(typ,'image'),
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',[0.61 hp 0.37 fh],...
'Callback',@update_frames,...
'tag','frame',...
'FontSize',fs,...
'BackgroundColor',col1,...
'String',frames,'UserData',eval(frames));
% 'ForegroundGolor',col3,...
end;
% Help
hp = hp+fh+0.01;
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[0.02 hp fh fh],...
'FontSize',fs,...
'Callback',@heelp,...
'tag','?',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','?',...
'FontWeight','bold',...
'ToolTipString','Show Help',...
'FontSize',fs);
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[0.03+fh hp fh fh],...
'FontSize',fs,...
'Callback',@editwin,...
'tag','Ed',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Ed',...
'FontWeight','bold',...
'ToolTipString','Edit Selected Files',...
'FontSize',fs);
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[0.04+2*fh hp fh fh],...
'FontSize',fs,...
'Callback',@select_rec,...
'tag','Rec',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Rec',...
'FontWeight','bold',...
'ToolTipString','Recursively Select Files with Current Filter',...
'FontSize',fs);
% Done
dne = uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[0.05+3*fh hp 0.45-3*fh fh],...
'FontSize',fs,...
'Callback',@delete,...
'tag','D',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'String','Done',...
'FontWeight','bold',...
'FontSize',fs,...
'Enable','off',...
'DeleteFcn',@null);
if size(already,1)>=n(1) && size(already,1)<=n(2),
set(dne,'Enable','on');
end;
% Filter Button
uicontrol(fg,...
'Style','pushbutton',...
'units','normalized',...
'Position',[0.51 hp 0.1 fh],...
'FontSize',fs,...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'Callback',@clearfilt,...
'String','Filt',...
'FontSize',fs);
% Filter
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',[0.61 hp 0.37 fh],...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'FontSize',fs,...
'Callback',@update,...
'tag','regexp',...
'String',filt,...
'UserData',sfilt);
% Directories
hp = hp + fh+0.01;
db = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',[0.02 hp 0.47 h2],...
'FontSize',fs,...
'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',[0.51 hp 0.47 h2],...
'FontSize',fs,...
'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'),
dr = spm_platform('drives');
drivestr = cell(1,numel(dr));
for i=1:numel(dr),
drivestr{i} = [dr(i) ':'];
end;
%drivestr = {'A:','B:','C:','D:'};
sz = get(db,'Position');
sz(4) = sz(4)-fh-2*0.01;
set(db,'Position',sz);
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',[0.02 hp+h2-fh-0.01 0.10 fh],...
'FontSize',fs,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Drive');
uicontrol(fg,...
'style','popupmenu',...
'units','normalized',...
'Position',[0.12 hp+h2-fh-0.01 0.37 fh],...
'FontSize',fs,...
'Callback',@setdrive,...
'tag','drive',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',drivestr,...
'Value',1);
end;
% Previous dirs
hp = hp+h2+0.01;
uicontrol(fg,...
'style','popupmenu',...
'units','normalized',...
'Position',[0.12 hp 0.86 fh],...
'FontSize',fs,...
'Callback',@click_dir_list,...
'tag','previous',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String',pd,...
'Value',vl);
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',[0.02 hp 0.10 fh],...
'FontSize',fs,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Prev');
% Directory
hp = hp + fh+0.01;
uicontrol(fg,...
'style','edit',...
'units','normalized',...
'Position',[0.12 hp 0.86 fh],...
'FontSize',fs,...
'Callback',@edit_dir,...
'tag','edit',...
'BackgroundColor',col1,...
'ForegroundColor',col3,...
'String','');
uicontrol(fg,...
'style','text',...
'units','normalized',...
'Position',[0.02 hp 0.10 fh],...
'FontSize',fs,...
'BackgroundColor',get(fg,'Color'),...
'ForegroundColor',col3,...
'String','Dir');
resize_fun(fg);
update(sel,wd)
waitfor(dne);
drawnow;
if ishandle(sel),
t = get(sel,'String');
if sfilt.code == -1 && ~isempty(t)
% don't canonicalise empty selection
t = cellstr(t);
for k = 1:numel(t);
t{k} = cpath(t{k},pwd);
end;
t = char(t);
end;
ok = 1;
end;
if ishandle(fg), delete(fg); end;
drawnow;
return;
%=======================================================================
%=======================================================================
function null(varargin)
%=======================================================================
%=======================================================================
function msg(ob,str)
ob = sib(ob,'msg');
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)
ob = findobj(fg,'String','Filt','Style','pushbutton');
if ~isempty(ob),
ofs = get(ob,'FontSize');
ex = get(ob,'Extent');
ps = get(ob,'Position');
fs = floor(ofs*min(ps(4)./ex(4))+1);
fs = max(min(fs,30),4);
ob = findobj(fg,'Fontsize',ofs);
set(ob,'FontSize',fs);
end;
return;
%=======================================================================
%=======================================================================
function [d,mch] = prevdirs(d)
persistent pd
if ~iscell(pd), pd = {}; end;
d = deblank(d);
mch = find(strcmp(d,pd));
if isempty(mch),
pd = {pd{:},d};
mch = length(pd);
end;
d = pd;
return;
%=======================================================================
%=======================================================================
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 click_dir_box(lb,varargin)
update(lb,current_dir(lb));
return;
%=======================================================================
%=======================================================================
function dr = current_dir(lb,varargin)
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 = deblank(str(vl,:));
if strcmp(sel,'..'), % Parent directory
dr = fileparts(pd);
elseif strcmp(sel,'.'), % Current directory
dr = pd;
else
dr = fullfile(pd,sel);
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(findstr([filesep filesep],dr)) = [];
[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);
[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 = get(sib(lb,'drive'),'String');
str = cat(1,char(str));
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 = findobj(get(get(ob,'Parent'),'Parent'),'Tag','files');
str = get(lb,'String');
set(lb,'Value',1:size(str,1));
drawnow;
click_file_box(lb);
return;
%=======================================================================
%=======================================================================
function click_file_box(lb,varargin)
lim = get(lb,'UserData');
ob = sib(lb,'selected');
str3 = get(ob,'String');
str = get(lb,'String');
vlo = get(lb,'Value');
lim1 = min(max(lim(2)-size(str3,1),0),length(vlo));
if isempty(vlo),
msg(lb,'Nothing selected');
return;
end;
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 = [current_dir(sib(lb,'dirs')) filesep];
str1 = [repmat(dr,size(str1,1),1) str1];
set(lb,'Value',min(vl(1),size(str2,1)),'String',str2);
r = (1:size(str1,1))+size(str3,1);
str3 = deblank(strvcat(str3,str1));
set(ob,'String',str3,'Value',r);
if length(vlo)>lim1,
msg(lb,['Retained ' num2str(lim1) '/' num2str(length(vlo))...
' of selection.']);
beep;
elseif isfinite(lim(2))
if lim(1)==lim(2),
msg(lb,['Selected ' num2str(size(str3,1)) '/' num2str(lim(2)) ' files.']);
else
msg(lb,['Selected ' num2str(size(str3,1)) '/' num2str(lim(1)) '-' num2str(lim(2)) ' files.']);
end;
else
if size(str3,1) == 1, ss = ''; else ss = 's'; end;
msg(lb,['Selected ' num2str(size(str3,1)) ' file' ss '.']);
end;
if ~isfinite(lim(1)) || size(str3,1)>=lim(1),
set(sib(lb,'D'),'Enable','on');
end;
return;
%=======================================================================
%=======================================================================
function obj = sib(ob,tag)
obj = findobj(get(ob,'Parent'),'Tag',tag);
return;
%if isempty(obj),
% error(['Can''t find object with tag "' tag '".']);
%elseif length(obj)>1,
% error(['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 = ones(size(str,1),1);
if vl~=0, msk(vl) = 0; end;
str2 = str(logical(msk),:);
set(lb,'Value',min(vl(1),size(str2,1)),'String',str2);
lim = get(sib(lb,'files'),'UserData');
if size(str2,1)>= lim(1) && size(str2,1)<= lim(2),
set(sib(lb,'D'),'Enable','on');
else
set(sib(lb,'D'),'Enable','off');
end;
if size(str2,1) == 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(size(str2,1)) ' file' ss1 ' remaining.']);
return;
%=======================================================================
%=======================================================================
function unselect_all(ob,varargin)
lb = findobj(get(get(ob,'Parent'),'Parent'),'Tag','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 varargout = vfiles(option,varargin)
persistent vfs
if isempty(vfs),
vfs = newvfs;
end;
switch option,
case {'clear'}
vfs = newvfs;
case {'add'}
for j=1:numel(varargin),
pth = {};
fle = {};
if ischar(varargin{j}),
for i=1:size(varargin{j},1),
[pth{i} n e v] = spm_fileparts(deblank(varargin{j}(i,:)));
fle{i} = [n e v];
end;
elseif iscell(varargin{j}),
for i=1:numel(varargin{j}),
[pth{i} n e v] = spm_fileparts(deblank(varargin{j}{i}));
fle{i} = [n e v];
end;
end;
[pu pi pj] = unique(pth);
for k = 1:numel(pu)
vfs = addvfile(vfs,pu{k},fle(pj==k));
end;
end;
case {'list'}
[varargout{1:3}] = listvfiles(vfs,varargin{:});
case {'all'}
varargout{1} = vfs;
otherwise
error('Unknown option.');
end;
return;
%=======================================================================
%=======================================================================
function vfs = newvfs(nam)
if nargin==0, nam = ''; end;
vfs = struct('name',nam,'dirs',struct('name',{},'dirs',{},'files',{}),'files',struct('name',{},'ind',{}));
return;
%=======================================================================
%=======================================================================
function vfs = addvfile(vfs,pth,fle)
if isempty(pth),
for k = 1:numel(fle)
[unused,nam,ext,num] = spm_fileparts(fle{k});
if ~isempty(num),
ind = [str2num(num) 1 1];
ind = ind(1);
else
ind = [];
end;
fname = [nam ext];
mch = strcmp(fname,{vfs.files.name});
if any(mch),
mch = find(mch);
vfs.files(mch).ind = [vfs.files(mch).ind ind];
else
vfs.files(end+1).name = fname;
vfs.files(end).ind = ind;
end;
end;
else
ind = find(pth==filesep);
if isempty(ind)
dr = pth;
pth = '';
else
if any(ind==1),
ind = ind(2:end)-1;
pth = pth(2:end);
end;
if isempty(ind)
dr = pth;
pth = '';
else
dr = pth(1:(ind(1)-1));
pth = pth((ind(1)+1):end);
end;
end;
mch = strcmp(dr,{vfs.dirs.name});
if any(mch),
mch = find(mch);
else
mch = numel(vfs.dirs)+1;
vfs.dirs(mch) = newvfs(dr);
end;
vfs.dirs(mch) = addvfile(vfs.dirs(mch),pth,fle);
end;
return;
%=======================================================================
%=======================================================================
function [f,d] = listfiles(dr,filt)
ob = gco;
msg(ob,'Listing directory...');
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;
msg(ob,['Filtering ' num2str(numel(f)) ' files...']);
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),
msg(ob,['Reading headers of ' num2str(numel(f)) ' images...']);
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;
msk = false(size(filt.frames));
for j=1:numel(msk), msk(j) = any(d4==filt.frames(j)); end;
ii{i} = filt.frames(msk);
end;
elseif filt.code==1 && (numel(filt.frames)==1 && filt.frames(1)==1),
for i=1:numel(f),
ii{i} = 1;
end;
end;
msg(ob,'Listing virtual files...');
[fv,dv,iv] = vfiles('list',dr);
if filt.code==-1,
fv = dv;
iv = cell(size(fv));
end;
msg(ob,['Filtering ' num2str(numel(fv)) ' virtual files...']);
[fv,ind] = do_filter(fv,filt.ext);
iv = iv(ind);
[fv,ind] = do_filter(fv,filt.filt);
iv = iv(ind);
if filt.code==1,
for i=1:numel(iv),
msk = false(size(filt.frames));
for j=1:numel(msk), msk(j) = any(iv{i}==filt.frames(j)); end;
iv{i} = filt.frames(msk);
end;
end;
d = { d{:},dv{:}};
f = { f{:},fv{:}};
ii = {ii{:},iv{:}};
msg(ob,['Listing ' num2str(numel(f)) ' files...']);
[f,ind] = sortrows(f(:));
ii = ii(ind);
msk = true(1,numel(f));
if ~isempty(f), f{1} = deblank(f{1}); end;
for i=2:numel(f),
f{i} = deblank(f{i});
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,
ii = ii(msk);
c = cell(size(f));
for i=1:numel(f),
c{i} = [repmat([f{i} ','],numel(ii{i}),1) num2str(ii{i}(:)) ];
end;
f = c;
elseif filt.code==-1,
fs = filesep;
for i=1:numel(f),
f{i} = [f{i} fs];
end;
end;
f = strvcat(f{:});
d = sortrows(d(:));
d = strvcat(d);
sam = find(~any(diff(d+0,1),2));
d(sam,:) = [];
msg(ob,'');
return;
%=======================================================================
%=======================================================================
function [f,ind] = do_filter(f,filt)
t2 = false(numel(f),1);
% This would be a speedup, but does not work on MATLAB < R14SP3 due to
% changes in regexp handling
% 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;
for j=1:numel(filt),
t1 = regexp(f,filt{j});
if numel(f)==1 && ~iscell(t1), t1 = {t1}; end;
for i=1:numel(t1),
t2(i) = t2(i) || ~isempty(t1{i});
end;
end;
ind = find(t2);
f = f(ind);
return;
%=======================================================================
%=======================================================================
function [f,d,ii] = listvfiles(vfs,dr)
f = {};
d = {};
ii = {};
if isempty(dr),
f = {vfs.files.name};
ii = {vfs.files.ind};
d = {vfs.dirs.name};
else
if dr(1)==filesep, dr = dr(2:end); end;
ind = find(dr==filesep);
if isempty(ind),
d1 = dr;
d2 = '';
else
d1 = dr(1:(ind(1)-1));
d2 = dr((ind(1)+1):end);
end;
for i=1:length(vfs.dirs),
if strcmp(d1,vfs.dirs(i).name),
[f,d,ii] = listvfiles(vfs.dirs(i),d2);
break;
end;
end;
end;
return;
%=======================================================================
%=======================================================================
function heelp(ob,varargin)
[col1,col2,col3,fs] = colours;
fg = get(ob,'Parent');
t = uicontrol(fg,...
'style','listbox',...
'units','normalized',...
'Position',[0.01 0.01 0.98 0.98],...
'FontSize',fs,...
'FontName','FixedWidthFont',...
'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);
ext = get(t,'Extent');
pw = floor(0.98/ext(3)*20-4);
str = spm_justify(pw,{[...
'File Selection help. You can return to selecting files via the right mouse button (the "Done" option). ',...
'Because of a bug in Matlab (on some machines), don''t resize this window when viewing the help.'],...
'',[...
'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"), 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. ',...
'Note that the syntax of the filter differs from that used by previous versions of ',...
'SPM. 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'],''});
pad = cellstr(char(zeros(max(0,floor(1.2/ext(4) - numel(str))),1)));
str = {str{:}, pad{:}};
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 hitkey(fg,varargin)
ch = get(fg,'CurrentCharacter');
if isempty(ch), return; end;
ob = findobj(fg,'Tag','files');
if ~isempty(ob),
f = get(ob,'String');
f = f(:,1);
fset = find(f>=ch);
if ~isempty(fset),
fset = fset(1);
%cb = get(ob,'Callback');
%set(ob,'Callback',[]);
set(ob,'ListboxTop',fset);
%set(ob,'Callback',cb);
else
set(ob,'ListboxTop',length(f));
end;
end;
return;
%=======================================================================
%=======================================================================
function t = cpath(t,d)
switch spm_platform('filesys'),
case 'unx',
mch = '^/';
fs = '/';
fs1 = '/';
case 'win',
mch = '^.:\\';
fs = '\';
fs1 = '\\';
otherwise;
error('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)),
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)),
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,fs] = colours;
fg = get(ob,'Parent');
lb = findobj(fg,'Tag','selected');
str = get(lb,'String');
str = cellstr(str);
h = uicontrol(fg,'Style','Edit',...
'units','normalized',...
'String',str,...
'FontSize',16,...
'Max',2,...
'Tag','EditWindow',...
'HorizontalAlignment','Left',...
'ForegroundColor',col3,...
'BackgroundColor',col1,...
'Position',[0.01 0.01 0.98 0.98]);
c0 = uicontextmenu('Parent',fg);
set(h,'uicontextmenu',c0);
uimenu('Label','Cancel', 'Parent',c0,'Callback',@editclear);
uimenu('Label','Accept', 'Parent',c0,'Callback',@editdone);
%=======================================================================
%=======================================================================
function editdone(ob,varargin)
ob = get(ob,'Parent');
ob = sib(ob,'EditWindow');
str = get(ob,'String');
str = deblank(cellstr(strvcat(str)));
if isempty(str{1}), str = {}; 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,['Specified ' 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',strvcat(str),'Value',[]);
delete(ob);
%=======================================================================
%=======================================================================
function editclear(ob,varargin)
ob = get(ob,'Parent');
ob = get(ob,'Parent');
ob = findobj(ob,'Tag','EditWindow');
delete(ob);
%=======================================================================
%=======================================================================
function [c1,c2,c3,fs] = colours
global defaults
c1 = [1 1 1];
c2 = [1 1 1];
c3 = [0 0 0];
fs = 14;
if isfield(defaults,'ui'),
ui = defaults.ui;
if isfield(ui,'colour1'), c1 = ui.colour1; end;
if isfield(ui,'colour2'), c2 = ui.colour2; end;
if isfield(ui,'colour3'), c3 = ui.colour3; end;
if isfield(ui,'fs'), fs = ui.fs; end;
end;
%=======================================================================
%=======================================================================
function select_rec(ob, varargin)
sel = [];
top = get(ob,'Parent');
start = get(findobj(top,'Tag','edit'),'String');
filt = get(findobj(top,'Tag','regexp'),'Userdata');
filt.filt = {get(findobj(top,'Tag','regexp'), 'String')};
fob = findobj(top,'Tag','frame');
if ~isempty(fob)
filt.frames = get(fob,'Userdata');
else
filt.frames = [];
end;
ptr = get(top,'Pointer');
try,
set(top,'Pointer','watch');
sel = select_rec1(start,filt);
catch,
set(top,'Pointer',ptr);
sel = '';
end;
set(top,'Pointer',ptr);
already= get(findobj(top,'Tag','selected'),'String');
fb = sib(ob,'files');
lim = get(fb,'Userdata');
limsel = min(lim(2)-size(already,1),size(sel,1));
set(findobj(top,'Tag','selected'),'String',strvcat(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 = [repmat([cdir,filesep],size(t,1),1),t];
end;
for k = 1:size(d,1)
if ~strcmp(deblank(d(k,:)),'.') && ~strcmp(deblank(d(k,:)),'..')
sel1 = select_rec1(fullfile(cdir,deblank(d(k,:))),filt);
if ~isempty(sel1) && ~isempty(sel),
sel = strvcat(sel, sel1);
elseif ~isempty(sel1),
sel = sel1;
end;
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$','.*\.img$','.*\.NII$','.*\.IMG$'};
case {'nifti'}, code = 0; ext = {'.*\.nii$','.*\.img$','.*\.NII$','.*\.IMG$'};
case {'extimage'}, code = 1; ext = {'.*\.nii(,[0-9]*){0,1}$',...
'.*\.img(,[0-9]*){0,1}$',...
'.*\.NII(,[0-9]*){0,1}$',...
'.*\.IMG(,[0-9]*){0,1}$'};
case {'xml'}, code = 0; ext = {'.*\.xml$','.*\.XML$'};
case {'mat'}, code = 0; ext = {'.*\.mat$','.*\.MAT$'};
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}});
%=======================================================================
%=======================================================================
|
github
|
spm/spm5-master
|
spm_eeg_scalp2d_ext.m
|
.m
|
spm5-master/spm_eeg_scalp2d_ext.m
| 6,685 |
utf_8
|
9cd4f0e11f4b8f2daa8a686d44a20f42
|
function varargout = spm_eeg_scalp2d_ext(varargin)
% SPM_EEG_SCALP2D_EXT M-file for spm_eeg_scalp2d_ext.fig
% SPM_EEG_SCALP2D_EXT, by itself, creates a new SPM_EEG_SCALP2D_EXT or raises the existing
% singleton*.
%
% H = SPM_EEG_SCALP2D_EXT returns the handle to a new SPM_EEG_SCALP2D_EXT or the handle to
% the existing singleton*.
%
% SPM_EEG_SCALP2D_EXT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SPM_EEG_SCALP2D_EXT.M with the given input arguments.
%
% SPM_EEG_SCALP2D_EXT('Property','Value',...) creates a new SPM_EEG_SCALP2D_EXT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before spm_eeg_scalp2d_ext_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to spm_eeg_scalp2d_ext_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Copyright 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help spm_eeg_scalp2d_ext
% Last Modified by GUIDE v2.5 22-Nov-2005 17:06:20
% Colon removed so that times output to Matlab window Doris Eckstein
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @spm_eeg_scalp2d_ext_OpeningFcn, ...
'gui_OutputFcn', @spm_eeg_scalp2d_ext_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before spm_eeg_scalp2d_ext is made visible.
function spm_eeg_scalp2d_ext_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to spm_eeg_scalp2d_ext (see VARARGIN)
% Choose default command line output for spm_eeg_scalp2d_ext
handles.output = hObject;
handles.D = varargin{1};
handles.T = varargin{2}; % input in peri-stimulus time (ms)
handles.ms = [-handles.D.events.start:handles.D.events.stop]*1000/handles.D.Radc;
for i = 1:length(handles.T)
tmp = (handles.T(i) - handles.ms).^2;
[m, ind(i)] = min(tmp);
end
handles.T = ind;
% locations
CTF = load(fullfile(spm('dir'), 'EEGtemplates', handles.D.channels.ctf));
%CTF.Cpos = CTF.Cpos(:, handles.D.channels.order(handles.D.channels.eeg));
handles.D.gfx.channels = intersect(handles.D.gfx.channels,handles.D.channels.eeg); % to ensure EOG not included
CTF.Cpos = CTF.Cpos(:, handles.D.channels.order(handles.D.gfx.channels));
handles.x = min(CTF.Cpos(1,:)):0.005:max(CTF.Cpos(1,:));
handles.y = min(CTF.Cpos(2,:)):0.005:max(CTF.Cpos(2,:));
[handles.x1, handles.y1] = meshgrid(handles.x, handles.y);
handles.xp = CTF.Cpos(1,:)';
handles.yp = CTF.Cpos(2,:)';
handles.event = varargin{3};
if length(handles.T) > 1
% average, remove slider
set(handles.slider1, 'Visible', 'off');
set(handles.text2, 'Visible', 'off');
else
% set slider's range and initial value
set(handles.slider1, 'min', handles.ms(1));
set(handles.slider1, 'max', handles.ms(end));
set(handles.slider1, 'Value', handles.ms(handles.T));
end
% Update handles structure
guidata(hObject, handles);
plot_spatial(hObject, handles);
% UIWAIT makes spm_eeg_scalp2d_ext wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = spm_eeg_scalp2d_ext_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject handle to slider1 (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,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
T = get(handles.slider1, 'Value')
tmp = (T - handles.ms).^2;
[m, i] = min(tmp);
handles.T = i;
guidata(hObject, handles);
plot_spatial(hObject, handles);
% --- Executes during object creation, after setting all properties.
function slider1_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
function plot_spatial(hObject, handles)
T = handles.T;
D = handles.D;
event = handles.event;
% data
if length(T) == 1
d = squeeze(D.data(D.gfx.channels, T, event));
if ~isfield(handles, 'Colourbar')
handles.CLim1 = min(min(D.data(setdiff(D.gfx.channels, D.channels.Bad), :, event)));
handles.CLim2 = max(max(D.data(setdiff(D.gfx.channels, D.channels.Bad), :, event)));
end
else
d = squeeze(mean(D.data(D.gfx.channels, T, event), 2));
end
%Exclude bad channels
badchan = intersect(D.gfx.channels,D.channels.Bad);
if ~isempty(badchan)
d(badchan) = NaN;
end
z = griddata(handles.xp, handles.yp, d, handles.x1, handles.y1);
if length(T) == 1
set(handles.text1, 'String', sprintf('%d ms', round(handles.ms(T))));
else
set(handles.text1, 'String', 'average');
end
axes(handles.axes1);
cla
surface(handles.x, handles.y, z);
axis off
shading('interp')
hold on
plot3(handles.xp, handles.yp, d, 'k.');
if ~isfield(handles, 'Colourbar')
set(handles.axes1, 'CLim', [handles.CLim1 handles.CLim2])
handles.Colourbar = colorbar;
ylabel(handles.Colourbar, D.units, 'FontSize', 16);
end
guidata(hObject, handles);
drawnow
|
github
|
spm/spm5-master
|
spm_eeg_inv_displTes.m
|
.m
|
spm5-master/spm_eeg_inv_displTes.m
| 3,729 |
utf_8
|
8c8ce34a4598902e61b0c9f1559207fe
|
function [p,hFig] = spm_eeg_inv_displTes(tsurf,c)
% FORMAT [p,f] = spm_eeg_inv_displTes(tsurf,c)
%
% Display a tessalated surface, with color c if provided :
% if c is not provided, it uses 1 color for all surface.
% 'spm_eeg_inv_displTes' returns handle to patch & figure
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Christophe Phillips,
% $Id$
% mono_c = 1/0 uses monocolor or provided c
% tri_c = 1/0 , color specified on triangles or vertices
if nargin==0
Pmod = spm_select(1,'^model.*\.mat$','Select model to display');
load(Pmod)
if length(model.head)>1
% Select surface to display
list = '';
for ii=1:length(model.head)
list = strvcat(list,model.head(ii).info.str);
end
tsurf_i = spm_input('Display which surface','+1','m',list);
tsurf = model.head(tsurf_i);
else
tsurf = model.head(1);
end
end
Nvert = tsurf.nr(1) ;
Ntri = tsurf.nr(2) ;
try
vert = tsurf.M*[tsurf.XYZvx ; ones(1,Nvert)]; vert = vert(1:3,:)';
catch
vert = tsurf.XYZmm';
end
tri = tsurf.tri' ;
%colo_skin = [1 .7 .55] ;
%colo_skin = [1 .5 .45] ;
colo_skin = [1 0 0] ;
mono_c = 0 ;
if nargin<2
c = ones(Ntri,1)*colo_skin ;
mono_c = 1 ;
tri_c = 1 ;
elseif nargin==2
if (size(c,1)==1) & ((size(c,2)==1)|(size(c,2)==3))
mono_c = 1 ;
elseif size(c,1)==tsurf.nr(2)
tri_c = 1 ;
c3 = apply_colormap(c) ;
c = c3 ;
elseif size(c,1)==tsurf.nr(1)
tri_c = 0 ;
c3 = apply_colormap(c) ;
c = c3 ;
else
error('Wrong colour specification') ;
end
end
hFig = spm_figure('FindWin');
if isempty(hFig)
hFig = figure;
else
spm_figure('Clear',hFig);
spm_figure('ColorMap','jet');
end
figure(hFig) ;
% set(f,'Render','OpenGL')
set(hFig,'Render','zbuffer')
if mono_c
p = patch('Vertices',vert,'Faces',tri,'FaceColor',colo_skin) ;
% p = patch('Vertices',vert,'Faces',tri,'FaceColor',[ 0.3 0.8 0.8 ]) ;
% p = patch('Vertices',vert,'Faces',tri,'FaceVertexCData',c) ;
% set(p,'FaceLighting','phong','SpecularStrength',.1,...
% 'AmbientStrength',.45,'EdgeColor','none') ;
% ,'FaceColor','interp') ;
% set(p,'FaceLighting','phong','SpecularStrength',.001,...
% 'AmbientStrength',.2,'EdgeColor','none',...
% 'DiffuseStrength',.6,'SpecularExponent',20) ;
% ,'FaceColor','interp') ;
else
if tri_c
p = patch('Vertices',vert,'Faces',tri,'FaceVertexCData',c)
set(p,'FaceLighting','phong','SpecularStrength',.1,...
'AmbientStrength',.45,'EdgeColor','none',...
'FaceColor','interp') ;
else
p = patch('Vertices',vert,'Faces',tri,'FaceVertexCData',c)
set(p,'FaceLighting','phong','SpecularStrength',.1,...
'AmbientStrength',.45,'EdgeColor','none',...
'FaceColor','interp') ;
end
end
view(3)
axis equal
%axis([1 181 1 217 1 181])
axis vis3d
rotate3d on
axis off
view(135,15)
%h1 = light('Position',[1 3 3]) ;
%h2 = light('Position',[1 -1 -1]) ;
%h3 = light('Position',[-3 -1 0]) ;
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function c3 = apply_colormap(c)
% Scale between the min and max of the values in c
mc = min(c) ; Mc = max(c) ; dc = Mc-mc ;
% Scale symetrically around 0 the values of c
%mc = -max(abs(c)) ; dc = -2*mc ;
% Colormap : white-blue-black-red-white
%colormap(hot(128)), tmp_scale = colormap ; tmp2 = fliplr(flipud(tmp_scale)) ; col_scale = [tmp2 ; tmp_scale] ;
%colormap(jet(256)), col_scale = colormap ;
%colormap(gray(256)), col_scale = colormap ;
colormap(cool(256)), col_scale = colormap ;
colormap(col_scale)
ind_c = round((c-mc)/dc*255+1) ;
c3 = col_scale(ind_c,:) ;
|
github
|
spm/spm5-master
|
spm_config_preproc.m
|
.m
|
spm5-master/spm_config_preproc.m
| 27,234 |
utf_8
|
df3bace7f557a516e2708fbde2621df0
|
function job = spm_config_preproc
% Configuration file for Segment jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_preproc.m 1032 2007-12-20 14:45:55Z john $
%_______________________________________________________________________
entry = inline(['struct(''type'',''entry'',''name'',name,'...
'''tag'',tag,''strtype'',strtype,''num'',num,''help'',{{}})'],...
'name','tag','strtype','num');
files = inline(['struct(''type'',''files'',''name'',name,'...
'''tag'',tag,''filter'',fltr,''num'',num,''help'',{{}})'],...
'name','tag','fltr','num');
mnu = inline(['struct(''type'',''menu'',''name'',name,'...
'''tag'',tag,''labels'',{labels},''values'',{values},''help'',{{}})'],...
'name','tag','labels','values');
branch = inline(['struct(''type'',''branch'',''name'',name,'...
'''tag'',tag,''val'',{val},''help'',{{}})'],...
'name','tag','val');
%_______________________________________________________________________
data = files('Data','data','image',[1 Inf]);
data.help = {[...
'Select scans for processing. ',...
'This assumes that there is one scan for each subject. ',...
'Note that multi-spectral (when there are two or more registered ',...
'images of different contrasts) processing is not yet implemented ',...
'for this method.']};
%------------------------------------------------------------------------
priors = files('Tissue probability maps','tpm','image',3);
priors.def = 'preproc.tpm';
priors.dir = fullfile(spm('Dir'),'tpm');
priors.help = {...
[...
'Select the tissue probability images. '...
'These should be maps of grey matter, white matter ',...
'and cerebro-spinal fluid probability. '...
'A nonlinear deformation field is estimated that best overlays the '...
'tissue probability maps on the individual subjects'' image. '...
'The default tissue probability maps are modified versions of the '...
'ICBM Tissue Probabilistic Atlases.',...
'These tissue probability maps are kindly provided by the ',...
'International Consortium for Brain ',...
'Mapping, John C. Mazziotta and Arthur W. Toga. ',...
'http://www.loni.ucla.edu/ICBM/ICBM_TissueProb.html. ',...
'The original data are derived from 452 T1-weighted scans, ',...
'which were aligned with an atlas space, corrected for scan ',...
'inhomogeneities, and classified ',...
'into grey matter, white matter and cerebrospinal fluid. ',...
'These data were then affine registered to the MNI space and ',...
'downsampled to 2mm resolution.'],...
'',...
[...
'Rather than assuming stationary prior probabilities based upon mixing '...
'proportions, additional information is used, based on other subjects'' brain '...
'images. Priors are usually generated by registering a large number of '...
'subjects together, assigning voxels to different tissue types and averaging '...
'tissue classes over subjects. '...
'Three tissue classes are used: grey matter, white matter and cerebro-spinal fluid. '...
'A fourth class is also used, which is simply one minus the sum of the first three. '...
'These maps give the prior probability of any voxel in a registered image '...
'being of any of the tissue classes - irrespective of its intensity.'],...
'',...
[...
'The model is refined further by allowing the tissue probability maps to be '...
'deformed according to a set of estimated parameters. '...
'This allows spatial normalisation and segmentation to be combined into '...
'the same model. '...
'This implementation uses a low-dimensional approach, which parameterises '...
'the deformations by a linear combination of about a thousand cosine '...
'transform bases. '...
'This is not an especially precise way of encoding deformations, but it '...
'can model the variability of overall brain shape. '...
'Evaluations by Hellier et al have shown that this simple model can achieve '...
'a registration accuracy comparable to other fully automated methods with '...
'many more parameters.']};
%------------------------------------------------------------------------
ngaus = entry('Gaussians per class','ngaus','n',[4 1]);
ngaus.def = 'preproc.ngaus';
%ngaus.val = {[2 2 2 4]};
ngaus.help = {[...
'The number of Gaussians used to represent the intensity distribution '...
'for each tissue class can be greater than one. '...
'In other words, a tissue probability map may be shared by several clusters. '...
'The assumption of a single Gaussian distribution for each class does not '...
'hold for a number of reasons. '...
'In particular, a voxel may not be purely of one tissue type, and instead '...
'contain signal from a number of different tissues (partial volume effects). '...
'Some partial volume voxels could fall at the interface between different '...
'classes, or they may fall in the middle of structures such as the thalamus, '...
'which may be considered as being either grey or white matter. '...
'Various other image segmentation approaches use additional clusters to '...
'model such partial volume effects. '...
'These generally assume that a pure tissue class has a Gaussian intensity '...
'distribution, whereas intensity distributions for partial volume voxels '...
'are broader, falling between the intensities of the pure classes. '...
'Unlike these partial volume segmentation approaches, the model adopted '...
'here simply assumes that the intensity distribution of each class may '...
'not be Gaussian, and assigns belonging probabilities according to these '...
'non-Gaussian distributions. '...
'Typical numbers of Gaussians could be two for grey matter, two for white '...
'matter, two for CSF, and four for everything else.']};
%------------------------------------------------------------------------
warpreg = entry('Warping Regularisation','warpreg','e',[1 1]);
warpreg.def = 'preproc.warpreg';
%warpreg.val = {1};
warpreg.help = {[...
'The objective function for registering the tissue probability maps to the ',...
'image to process, involves minimising the sum of two terms. ',...
'One term gives a function of how probable the data is given the warping parameters. ',...
'The other is a function of how probable the parameters are, and provides a ',...
'penalty for unlikely deformations. ',...
'Smoother deformations are deemed to be more probable. ',...
'The amount of regularisation determines the tradeoff between the terms. ',...
'Pick a value around one. However, if your normalised images appear ',...
'distorted, then it may be an idea to increase the amount of ',...
'regularisation (by an order of magnitude). ',...
'More regularisation gives smoother deformations, ',...
'where the smoothness measure is determined by the bending energy of the deformations. ']};
%------------------------------------------------------------------------
warpco = entry('Warp Frequency Cutoff','warpco','e',[1 1]);
warpco.def = 'preproc.warpco';
%warpco.val = {25};
warpco.help = {[...
'Cutoff of DCT bases. Only DCT bases of periods longer than the ',...
'cutoff are used to describe the warps. The number actually used will ',...
'depend on the cutoff and the field of view of your image. ',...
'A smaller cutoff frequency will allow more detailed deformations ',...
'to be modelled, but unfortunately comes at a cost of greatly increasing ',...
'the amount of memory needed, and the time taken.']};
%------------------------------------------------------------------------
biasreg = mnu('Bias regularisation','biasreg',{...
'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)'},...
{0, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1.0, 10});
biasreg.def = 'preproc.biasreg';
%biasreg.val = {0.0001};
biasreg.help = {[...
'MR images are usually corrupted by a smooth, spatially varying artifact that modulates the intensity ',...
'of the image (bias). ',...
'These artifacts, although not usually a problem for visual inspection, can impede automated ',...
'processing of the images.'],...
'',...
[...
'An important issue relates to the distinction between intensity variations that arise because of ',...
'bias artifact due to the physics of MR scanning, and those that arise due to different tissue ',...
'properties. The objective is to model the latter by different tissue classes, while modelling the ',...
'former with a bias field. ',...
'We know a priori that intensity variations due to MR physics tend to be spatially smooth, ',...
'whereas those due to different tissue types tend to contain more high frequency information. ',...
'A more accurate estimate of a bias field can be obtained by including prior knowledge about ',...
'the distribution of the fields likely to be encountered by the correction algorithm. ',...
'For example, if it is known that there is little or no intensity non-uniformity, then it would be wise ',...
'to penalise large values for the intensity non-uniformity parameters. ',...
'This regularisation can be placed within a Bayesian context, whereby the penalty incurred is the negative ',...
'logarithm of a prior probability for any particular pattern of non-uniformity.']};
%------------------------------------------------------------------------
biasfwhm = mnu('Bias FWHM','biasfwhm',{...
'30mm cutoff','40mm cutoff','50mm cutoff','60mm cutoff','70mm cutoff',...
'80mm cutoff','90mm cutoff','100mm cutoff','110mm cutoff','120mm cutoff',...
'130mm cutoff','140mm cutoff','150mm cutoff','No correction'},...
{30,40,50,60,70,80,90,100,110,120,130,140,150,Inf});
biasfwhm.def = 'preproc.biasfwhm';
%biasfwhm.val = {60};
biasfwhm.help = {[...
'FWHM of Gaussian smoothness of bias. ',...
'If your intensity non-uniformity is very smooth, then choose a large ',...
'FWHM. This will prevent the algorithm from trying to model out intensity variation ',...
'due to different tissue types. The model for intensity non-uniformity is one ',...
'of i.i.d. Gaussian noise that has been smoothed by some amount, ',...
'before taking the exponential. ',...
'Note also that smoother bias fields need fewer parameters to describe them. ',...
'This means that the algorithm is faster for smoother intensity non-uniformities.']};
%------------------------------------------------------------------------
regtype = mnu('Affine Regularisation','regtype',...
{'No Affine Registration','ICBM space template - European brains',...
'ICBM space template - East Asian brains', 'Average sized template','No regularisation'},...
{'','mni','eastern','subj','none'});
regtype.def = 'preproc.regtype';
regtype.help = {[...
'The procedure is a local optimisation, so it needs reasonable initial '...
'starting estimates. Images should be placed in approximate alignment '...
'using the Display function of SPM before beginning. '...
'A Mutual Information affine registration with the tissue '...
'probability maps (D''Agostino et al, 2004) is used to achieve '...
'approximate alignment. '...
'Note that this step does not include any model for intensity non-uniformity. '...
'This means that if the procedure is to be initialised with the affine '...
'registration, then the data should not be too corrupted with this artifact.'...
'If there is a lot of intensity non-uniformity, then manually position your '...
'image in order to achieve closer starting estimates, and turn off the '...
'affine registration.'],...
'',...
[...
'Affine registration into a standard space can be made more robust by ',...
'regularisation (penalising excessive stretching or shrinking). The ',...
'best solutions can be obtained by knowing the approximate amount of ',...
'stretching that is needed (e.g. ICBM templates are slightly bigger ',...
'than typical brains, so greater zooms are likely to be needed). ',...
'For example, if registering to an image in ICBM/MNI space, then choose this ',...
'option. If registering to a template that is close in size, then ',...
'select the appropriate option for this.']};
%------------------------------------------------------------------------
samp = entry('Sampling distance','samp','e',[1 1]);
samp.def = 'preproc.samp';
%samp.val = {3};
samp.help = {[...
'The approximate distance between sampled points when estimating the ',...
'model parameters. Smaller values use more of the data, but the procedure ',...
'is slower.']};
%------------------------------------------------------------------------
msk = files('Masking image','msk','image',[0 1]);
msk.val = {''};
msk.help = {[...
'The segmentation can be masked by an image that conforms to ',...
'the same space as the images to be segmented. If an image is selected, then ',...
'it must match the image(s) voxel-for voxel, and have the same ',...
'voxel-to-world mapping. Regions containing a value of zero in this image ',...
'do not contribute when estimating the various parameters. ']};
%------------------------------------------------------------------------
opts = branch('Custom','opts',{priors,ngaus,regtype,warpreg,warpco,biasreg,biasfwhm,samp,msk});
opts.help = {[...
'Various options can be adjusted in order to improve the performance of the '...
'algorithm with your data. Knowing what works best should be a matter '...
'of empirical exploration. For example, if your data has very little '...
'intensity non-uniformity artifact, then the bias regularisation should '...
'be increased. This effectively tells the algorithm that there is very little '...
'bias in your data, so it does not try to model it.']};
%------------------------------------------------------------------------
cleanup.tag = 'cleanup';
cleanup.type = 'menu';
cleanup.name = 'Clean up any partitions';
cleanup.help = {[...
'This uses a crude routine for extracting the brain from segmented',...
'images. It begins by taking the white matter, and eroding it a',...
'couple of times to get rid of any odd voxels. The algorithm',...
'continues on to do conditional dilations for several iterations,',...
'where the condition is based upon gray or white matter being present.',...
'This identified region is then used to clean up the grey and white',...
'matter partitions, and has a slight influences on the CSF partition.'],'',[...
'If you find pieces of brain being chopped out in your data, then you ',...
'may wish to disable or tone down the cleanup procedure.']};
cleanup.labels = {'Dont do cleanup','Light Clean','Thorough Clean'};
cleanup.values = {0 1 2};
cleanup.val = {0};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
% bias = struct('type','branch','name','Bias correction','tag','bias','dim',Inf,'val',{{biasreg,biasfwhm}});
% bias.help = {[...
% 'This 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 regularisation is based upon minimising the ',...
% 'integral of square of the fourth derivatives of the modulation field ',...
% '(the integral of the squares of the first and second derivatives give the ',...
% 'membrane and bending energies respectively).']};
biascor = mnu('Bias Corrected','biascor',{'Save Bias Corrected','Don''t Save Corrected'},{1,0});
biascor.val = {1};
biascor.help = {[...
'This is the option to produce a bias corrected version of your image. ',...
'MR images are usually corrupted by a smooth, spatially varying artifact that modulates the intensity ',...
'of the image (bias). ',...
'These artifacts, although not usually a problem for visual inspection, can impede automated ',...
'processing of the images. The bias corrected version should have more uniform intensities within ',...
'the different types of tissues.']};
grey = mnu('Grey Matter','GM',{...
'None',...
'Native Space',...
'Unmodulated Normalised',...
'Modulated Normalised',...
'Native + Unmodulated Normalised',...
'Native + Modulated Normalised',...
'Native + Modulated + Unmodulated',...
'Modulated + Unmodulated Normalised'},...
{[0 0 0],[0 0 1],[0 1 0],[1 0 0],[0 1 1],[1 0 1],[1 1 1],[1 1 0]});
grey.val = {[0 0 1]};
grey.help = {'Options to produce grey matter images: c1*.img, wc1*.img and mwc1*.img.'};
white = grey;
white.name = 'White Matter';
white.tag = 'WM';
white.help = {'Options to produce white matter images: c2*.img, wc2*.img and mwc2*.img.'};
csf = grey;
csf.name = 'Cerebro-Spinal Fluid';
csf.tag = 'CSF';
csf.val = {[0 0 0]};
csf.help = {'Options to produce CSF images: c3*.img, wc3*.img and mwc3*.img.'};
output = branch('Output Files','output',{grey,white,csf,biascor,cleanup});
output.help = {[...
'This routine produces spatial normalisation parameters (*_seg_sn.mat files) by default. ',...
'These can be used for writing spatially normalised versions of your data, via the "Normalise: Write" option. ',...
'This mechanism may produce superior results than the "Normalise: Estimate" option, although ',...
'this may need some empirical evaluations.'],...
'',...
[...
'In addition, it also produces files that can be used for doing inverse normalisation. ',...
'If you have an image of regions defined in the standard space, then the inverse deformations ',...
'can be used to warp these regions so that it approximately overlay your image. ',...
'To use this facility, the bounding-box and voxel sizes should be set to non-finite values ',...
'(e.g. [NaN NaN NaN] for the voxel sizes, and ones(2,3)*NaN for the bounding box. ',...
'This would be done by the spatial normalisation module, which allows you to select a ',...
'set of parameters that describe the nonlinear warps, and the images that they should be applied to.'],...
'',...
[...
'There are a number of options about what data you would like the routine to produce. ',...
'The routine can be used for producing images of tissue classes, as well as bias corrected images. ',...
'The native space option will produce a tissue class image (c*) that is in alignment with ',...
'the original/* (see Figure \ref{seg1})*/. You can also produce spatially normalised versions - both with (mwc*) and without (wc*) ',...
'modulation/* (see Figure \ref{seg2})*/. The bounding box and voxel sizes of the spatially normalised versions are the ',...
'same as that of the tissue probability maps with which they are registered. ',...
'These can be used for doing voxel-based morphometry with (both un-modulated and modulated). ',...
'All you need to do is smooth them and do the stats (which means no more questions on the mailing list ',...
'about how to do "optimized VBM").'],...
'',...
[...
'Modulation is to compensate for the effect of spatial normalisation. When warping a series ',...
'of images to match a template, it is inevitable that volumetric differences will be introduced ',...
'into the warped images. For example, if one subject''s temporal lobe has half the volume of that of ',...
'the template, then its volume will be doubled during spatial normalisation. This will also ',...
'result in a doubling of the voxels labelled grey matter. In order to remove this confound, the ',...
'spatially normalised grey matter (or other tissue class) is adjusted by multiplying by its relative ',...
'volume before and after warping. If warping results in a region doubling its volume, then the ',...
'correction will halve the intensity of the tissue label. This whole procedure has the effect of preserving ',...
'the total amount of grey matter signal in the normalised partitions.'],...
['/*',...
'\begin{figure} ',...
'\begin{center} ',...
'\includegraphics[width=150mm]{images/seg1} ',...
'\end{center} ',...
'\caption{Segmentation results. ',...
'These are the results that can be obtained in the original space of the image ',...
'(i.e. the results that are not spatially normalised). ',...
'Top left: original image (X.img). ',...
'Top right: bias corrected image (mX.img). ',...
'Middle and bottom rows: segmented grey matter (c1X.img), ',...
'white matter (c2X.img) and CSF (c3X.img). \label{seg1}} ',...
'\end{figure} */'],...
['/*',...
'\begin{figure} ',...
'\begin{center} ',...
'\includegraphics[width=150mm]{images/seg2} ',...
'\end{center} ',...
'\caption{Segmentation results. ',...
'These are the spatially normalised results that can be obtained ',...
'(note that CSF data is not shown). ',...
'Top row: The tissue probability maps used to guide the segmentation. ',...
'Middle row: Spatially normalised tissue maps of grey and white matter ',...
'(wc1X.img and wc2X.img). ',...
'Bottom row: Modulated spatially normalised tissue maps of grey and ',...
'white matter (mwc1X.img and mwc2X.img). \label{seg2}} ',...
'\end{figure} */'],...
[...
'A deformation field is a vector field, where three values are associated with ',...
'each location in the field. The field maps from co-ordinates in the ',...
'normalised image back to co-ordinates in the original image. The value of ',...
'the field at co-ordinate [x y z] in the normalised space will be the ',...
'co-ordinate [x'' y'' z''] in the original volume. ',...
'The gradient of the deformation field at a co-ordinate is its Jacobian ',...
'matrix, and it consists of a 3x3 matrix:'],...
'',...
'% / \',...
'% | dx''/dx dx''/dy dx''/dz |',...
'% | |',...
'% | dy''/dx dy''/dy dy''/dz |',...
'% | |',...
'% | dz''/dx dz''/dy dz''/dz |',...
'% \ /',...
['/* \begin{eqnarray*}',...
'\begin{pmatrix}',...
'\frac{dx''}{dx} & \frac{dx''}{dy} & \frac{dx''}{dz}\cr',...
'\frac{dy''}{dx} & \frac{dy''}{dy} & \frac{dy''}{dz}\cr',...
'\frac{dz''}{dx} & \frac{dz''}{dy} & \frac{dz''}{dz}\cr',...
'\end{pmatrix}\end{eqnarray*}*/'],...
[...
'The value of dx''/dy is a measure of how much x'' changes if y is changed by a ',...
'tiny amount. ',...
'The determinant of the Jacobian is the measure of relative volumes of warped ',...
'and unwarped structures. The modulation step simply involves multiplying by ',...
'the relative volumes /*(see Figure \ref{seg2})*/.']};
%------------------------------------------------------------------------
job = branch('Segment','preproc',{data,output,opts});
job.prog = @execute;
job.vfiles = @vfiles;
job.help = {[...
'Segment, bias correct and spatially normalise - all in the same model/* \cite{ashburner05}*/. ',...
'This function can be used for bias correcting, spatially normalising ',...
'or segmenting your data.'],...
'',...
[...
'Many investigators use tools within older versions of SPM for '...
'a technique that has become known as "optimised" voxel-based '...
'morphometry (VBM). '...
'VBM performs region-wise volumetric comparisons among populations of subjects. '...
'It requires the images to be spatially normalised, segmented into '...
'different tissue classes, and smoothed, prior to performing '...
'statistical tests/* \cite{wright_vbm,am_vbmreview,ashburner00b,john_should}*/. The "optimised" pre-processing strategy '...
'involved spatially normalising subjects'' brain images to a '...
'standard space, by matching grey matter in these images, to '...
'a grey matter reference. The historical motivation behind this '...
'approach was to reduce the confounding effects of non-brain (e.g. scalp) '...
'structural variability on the registration. '...
'Tissue classification in older versions of SPM required the images to be registered '...
'with tissue probability maps. After registration, these '...
'maps represented the prior probability of different tissue classes '...
'being found at each location in an image. Bayes rule can '...
'then be used to combine these priors with tissue type probabilities '...
'derived from voxel intensities, to provide the posterior probability.'],...
'',...
[...
'This procedure was inherently circular, because the '...
'registration required an initial tissue classification, and the '...
'tissue classification requires an initial registration. This circularity '...
'is resolved here by combining both components into a single '...
'generative model. This model also includes parameters that account '...
'for image intensity non-uniformity. '...
'Estimating the model parameters (for a maximum a posteriori solution) '...
'involves alternating among classification, bias correction and registration steps. '...
'This approach provides better results than simple serial applications of each component.'],...
'',[...
'Note that multi-spectral segmentation (e.g. from a registered T1 and T2 image) is ',...
'not yet implemented, but is planned for a future SPM version.']};
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function execute(job)
job.opts.tpm = strvcat(job.opts.tpm{:});
if isfield(job.opts,'msk'),
job.opts.msk = strvcat(job.opts.msk{:});
end;
for i=1:numel(job.data),
res = spm_preproc(job.data{i},job.opts);
[sn(i),isn] = spm_prep2sn(res);
[pth,nam] = spm_fileparts(job.data{i});
savefields(fullfile(pth,[nam '_seg_sn.mat']),sn(i));
savefields(fullfile(pth,[nam '_seg_inv_sn.mat']),isn);
end;
spm_preproc_write(sn,job.output);
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function savefields(fnam,p)
if length(p)>1, error('Can''t save fields.'); end;
fn = fieldnames(p);
if numel(fn)==0, return; end;
for i=1:length(fn),
eval([fn{i} '= p.' fn{i} ';']);
end;
if spm_matlab_version_chk('7') >= 0
save(fnam,'-V6',fn{:});
else
save(fnam,fn{:});
end;
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles(job)
opts = job.output;
sopts = [opts.GM;opts.WM;opts.CSF];
vf = cell(numel(job.data),2);
for i=1:numel(job.data),
[pth,nam,ext,num] = spm_fileparts(job.data{i});
vf{i,1} = fullfile(pth,[nam '_seg_sn.mat']);
vf{i,2} = fullfile(pth,[nam '_seg_inv_sn.mat']);
j = 3;
if opts.biascor,
vf{i,j} = fullfile(pth,['m' nam ext ',1']);
j = j + 1;
end;
for k1=1:3,
if sopts(k1,3),
vf{i,j} = fullfile(pth,[ 'c', num2str(k1), nam, ext, ',1']);
j = j + 1;
end;
if sopts(k1,2),
vf{i,j} = fullfile(pth,[ 'wc', num2str(k1), nam, ext, ',1']);
j = j + 1;
end;
if sopts(k1,1),
vf{i,j} = fullfile(pth,['mwc', num2str(k1), nam, ext, ',1']);
j = j + 1;
end;
end;
end;
vf = vf(:);
|
github
|
spm/spm5-master
|
bst_headmodeler.m
|
.m
|
spm5-master/bst_headmodeler.m
| 111,935 |
utf_8
|
a5f8e1434768799cd03d003a831e2737
|
function [varargout] = bst_headmodeler(varargin);
%BST_HEADMODELER - Solution to the MEG/EEG forward problem
% function [varargout] = bst_headmodeler(varargin);
% Authorized syntax:
% [G, OPTIONS] = bst_headmodeler(StudyFile, OPTIONS);
% [G, OPTIONS] = bst_headmodeler(OPTIONS);
% [OPTIONS] = bst_headmodeler;
%
% --------------------------------- INPUTS -------------------------------------
% INPUTS
%
% [OPTIONS] = bst_headmodeler; Returns the default values for the OPTIONS
% parameter structure
%
% StudyFile: the name of a BrainStorm study file. We suppose the
% corresponding BrainStorm channel file is available in the same folder
% with the conventional file name (e.g., for a study file calles
% meg_brainstormstudy.mat, BST_HEADMODELER expects to find the
% corresponding channel file under the name meg_channel.mat). If the
% channel file were not sitting in the same folder as the study file,
% OPTIONS.ChannelFile enforces computation of the forward model with the
% channel information contained in OPTIONS.ChannelFile.
%
% If no further input arguments are specified, forward modeling is
% completed with the default parameters specified below
%
% OPTIONS a structure where optional parameters may be specified using the
% following fields Note: if no options are specified, BST_HEADMODELER will
% proceed to the computation of the foward problem on a 3D grid of source
% locations that cover the entire head volume See
% OPTIONS.VolumeSourceGridSpacing for default settings
%
% Important notice: there is no need to define all the following fields
% when using the OPTIONS argument. The undefined field(s) will be assigned
% default values.
%
% *
% * Fields Related to forward approach
% *
%
% .Method: is either a character string or a cell array of two strings that
% specifies the kind of approach to be applied to the compuation
% of the foward model In case Method is a cell array, it should
% contain 2 strings, one to specifiy the method to be used for MEG
% and the other for . If only a single string is specified, the
% foward computation will be completed on the set of corresponding
% CHANndx only (i.e. MEG or MEG) Available forward modeling
% methods and corresponding authorized strings for Method:
% - MEG
% 'meg_sphere' (DEFAULT) : Spherical head model designed
% following the Sarvas analytical formulation (i.e.
% considering the true orientation
% of the magnetic field sensors) (see OPTIONS.HeadCenter)
% 'meg_os' : MEG overlapping sphere forward model
% 'meg_bem' : Apply BEM computation (see OPTIONS.BEM for details)
% -
% 'eeg_sphere' : Single-sphere forward modeling (see
% OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity)
% 'eeg_3sphere' : EEG forward modeling with a set of 3
% concentric spheres (Scalp, Skull, Brain/CSF) (see
% OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity)
% 'eeg_3sphereBerg' (DEFAULT) : Same as eeg_3sphere with
% correction for possible dipoles outside the sphere
% 'eeg_os' : EEG overlapping sphere head model (see
% OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity)
% 'eeg_bem' : Apply BEM computation (see OPIONS.BEM for details)
%
% Default is {'meg_sphere','eeg_3sphereBerg'};
%
% .HeadModelName : a character string that specifies the name of the
% headmodel represented by this file, e.g "Spherical",
% "Overlapping Spheres", "Constant Collocation BEM", etc.
% Default is "Default", meaning it will include the the
% name(s) of the method(s) used in the MEG and/or EEG
% forward models
%
% *
% * Fields Related to function's I/O
% *
%
% .HeadModelFile : Specifies the name of the head model file where to store
% the forward model. If set to 'default', the default
% nomenclature for BrainStorm's head model file name is
% used and BST_HEADMODELER creates a file in StudyFile's
% folder.
% Default is empty.
% .ImageGridFile : Specifies the name of the file where to store the full
% cortical gain matrix file If set to 'default', the
% default nomenclature for BrainStorm's head model file
% name is used and BST_HEADMODELER creates a file in
% StudyFile's folder.
% Default is empty.
% .ImageGridBlockSize : Number of sources for which to compute the forward
% model at a time in a block computation routines
% (saves memory space). This option is relevant only
% when some forward modeling on cortical surface is
% requested (i.e. when .Cortex is specified)
% Default is 2000
% .FileNamePrefix : A string that specifies the prefix for all file names
% (Channel, HeadModel, Gain Matrices) when .HeadModelFile
% is set to 'default' and .ChannelFile is empty.
% Default is 'bst_'
% .Verbose : Toggles verbose mode on/off;
% Default is 1 (on)
%
% *
% * Fields Related to Head Geometry *
% *
%
% .Scalp : A structure specifying the Scalp surface envelope to serve
% for parameter adjustment of best-fitting sphere, with
% following fields:
% .FileName : A string specifying the name of the BrainStorm
% tessellation file containing the Scalp
% tessellation (default is 1);
% .iGrid : An integer for the index of the Scalp surface in
% the Faces, Vertices and Comments cell arrays in
% the tessellation file
% Default is empty (Best-fitting sphere is
% computed from the sensor array).
% .HeadCenter: a 3-element vector specifying the coordinates, in the
% sensors coordinate system, of the center of the spheres that
% might be used in the head model.
% Default is estimated from the center of the best-fitting
% sphere to the sensor locations
% .Radii : a 3-element vector containing the radii of the single or 3
% concentric spheres, when needed;
% Order must be the following : [Rcsf, Routerskull, Rscalp];
% Default is estimated from the best-fitting sphere to the
% sensor locations and OPTIONS.Radii is set to: Rscalp [.88
% .93 1]. Rscalp is estimated from the radius of the
% best-fitting sphere;
% .Conductivity : a 3-element vector containing the values for the
% conductivity of the tissues in the following order:
% [Ccsf, Cskull, Cscalp];
% Default is set to [.33 .0042 .33];
% .EEGRef : the NAME (not index of the channel file) of the electrode
% that acts as the reference channel for the EEG. If data is
% referenced to instantaneous average (i.e. so called
% average-reference recording) value is 'AVERAGE REF';
% IMPORTANT NOTICE: When user calls bst_headmodeler with the
% .ChannelLoc option and .ChannelType = 'EEG'and wants the EEG
% reference to be e.g. channel 26, then .EEGRef should be set
% to 'EEG 26'
% Default is 'AVERAGE REF'.
%
% .OS_ComputeParam : if 1, force computation of all sphere parameters when
% choosing a method based on either the MEG or EEG
% overlapping-sphere technique, if 0 and when
% .HeadModelFile is specified, sphere parameters are
% loaded from the pre-computed HeadModel file.
% Default is 1.
%
% .BEM : Structure that specifies the necessary BEM parameters
% .Interpolative : Flag indicating whether exact or
% interpolative approach is used to compute
% the forward solution using BEM.
% if set to 1, exact computation is run on a
% set of points distributed wihtin the inner
% head volume and any subsequent request for
% a forward gain vector (e.g. during a
% volumic source scan using RAP-MUSIC) is
% computed using an interpolation of the
% forward gain vectors of the closest volumic
% grid points. This allows faster computation
% of the BEM solution during source search.
% if set to 0, exact computation is required
% at every source location.
% We recommend to set it to 0 (default) when
% sources have fixed location, e.g.
% constrained on the cortical surface.
% .EnvelopeNames : a cell array of strutures that specifies
% the ORDERED tessellated surfaces to be
% included in the BEM computation.
% .EnvelopeNames{k}.TessFile : A string for
% the name of the tessellation file
% containing the kth surface
% .EnvelopeNames{k}.TessName : A string for
% the name of the surface within the
% tessellation file This string should match
% one of the Comment strings in the
% tessellation file. The chosen surfaces must
% be ordered starting by the the innermost
% surface (e.g. brain or inner skull
% surface) and finishing with the outermost
% layer (e.g. the scalp)
% .Basis : set to either 'constant' or 'linear' (default)
% .Test : set to either 'Galerkin' or 'Collocation' (default)
% .ISA : Isolated-skull approach set to 0 or 1 (default is 1)
% .NVertMax : Maximum number of vertices per envelope,
% therefore leading to decimation of orginal
% surfaces if necessary
% (default is 1000)
% .ForceXferComputation: if set to 1, force recomputation of
% existing transfer matrices in current
% study folder (replace existing
% files);
% Default is 1
%
% *
% * Fields Related to Sensor Information *
% *
%
% .ChannelFile : Specifies the name of the file containing the channel
% information (needs to be a BrainStorm channel file). If
% file does not exists and sensor information is provided in
% .ChannelLoc, a BrainStorm Channl file with name
% .ChannelFile is created
% Default is left blank as this information is extracted
% from the channel file associated to the chosen BrainStorm
% studyfile.
% .Channel : A full BrainStorm channel structure if no channel file is
% specified;
% Default is empty
% .ChannelType : A string specifying the type of channel in ChannelLoc. Can
% be either 'MEG' or 'EEG'. Note that the same channel type
% is assumed for every channel.
% Default is empty
% .ChannelLoc : Specifies the location of the channels where to compute
% the forward model Can be either a 3xNsens (for EEG or
% MEG-magnetometer) or 6xNsens matrix (for the
% MEG-gradiometer case). (for magnetometer or gradiometer
% MEG - channel weights are set to -1 and 1 for each
% magnetometer in the gradiometer respectively) Note that
% in the MEG-gradiometer case, the 3 first (res. last) rows
% of .ChannelLoc stand for each of the magnetometers of the
% gradiometer set. In the case of a mixture of MEG magneto
% and MEG gradio-meters, .ChannelLoc needs to be a 6xNsens
% matrix where the last 3 rows are filled with NaN for
% MEG-magnetometers. If ones wants to handle both EEG and MEG
% sensors, please create a full ChannelFile and use the
% .ChannelFile option.
% Default is empty (Information extracted from the ChannelFile).
% .ChannelOrient : Specifies the orientation of the channels where to
% compute the EEG or MEG forward model Can be either a
% 3xNsens (for EEG and magnetometer MEG) or 6xNsens (for
% gradiometer MEG) matrix or a cell array of such matrices
% (one cell per type of method selected)
% Default is empty (Information extracted from the
% ChannelFile or assume radial orientation when
% .ChannelLoc is filled).
%
% *
% * Fields Related to Source Models *
% *
% .SourceModel : A vector indicating the type of source models to be
% computed; The following code is enfoced:
% -1 : Compute the forward fields of Current Dipole sources
% (available for all forward approaches)
% 1 : 1st-order Current Multipole Sources
% (available for sphere-based MEG approaches only)
% User can set OPTIONS.SourceModel to e.g., [-1 1] to
% compute forward models from both source models.
% Default is -1
%
%
% *
% * Fields Related to Source Localization *
% *
% .Cortex : A structure specifying the Cortex surface
% envelope to serve as an image support with
% following fields.
% .FileName : A string specifying the name of
% the BrainStorm tessellation file
% containing the Cortex
% tessellation;
% .iGrid : An integer for the index of the
% Cortex surface in the Faces,
% Vertices and Comments cell arrays
% in the tessellation file (default
% is 1)
% Default is empty.
% .GridLoc : A 3xNsources matrix that contains the
% locations of the sources at which the forward
% model will be computed
% Default is empty (Information taken from
% OPTIONS.Cortex or OPTIONS.VolumeSourceGrid);
% .GridOrient : a 3xNsources matrix that forces the source
% orientation at every vertex of the .ImageGrid
% cortical surface;
% Defaults is empty; this information being
% extracted from the corresponding tessellated
% surface.
% .ApplyGridOrient : if set to 1, force computation of the forward
% fields by considering the local orientation of
% the cortical surface;
% If set to 0, a set of 3 orthogonal dipoles are
% considered at each vertex location on the
% tessellated surface.
% Default is 1.
% .VolumeSourceGrid : if set to 1, a 3D source grid is designed to
% fit inside the head volume and will serve as a
% source space for scannig techniques such as
% RAP-MUSIC;
% if set to 0, this grid will be computed at the
% first call of e.g. RAP-MUSIC);
% Default is 1
% .VolumeSourceGridSpacing : Spacing in centimeters between two consecutive
% sources in the 3D source grid described above;
% Default is 2 cm.
% .VolumeSourceGridLoc : a 3xN matrix specifying the locations of the
% grid points that will be used to design the
% volumic search grid (see .VolumicSourceGrid)
% Default is empty (locations are estimated
% automatically to cover the estimated inner
% head volume)
% .SourceLoc : a 3xNsources matrix that contains the
% locations of the sources at which the forward
% model will be computed
% Default is empty (Information taken from
% OPTIONS.ImageGrid or
% OPTIONS.VolumeSourceGrid);
% .SourceOrient : a 3xNsources matrix that contains the
% orientations of the sources at which the
% forward model will be computed
% Default is empty.
%
%
% --------------------------------- OUTPUTS ------------------------------------
% OUTPUT
% G if the number of sources (Nsources) if less than
% .ImageGridBlockSize then G is a gain matrix of dimension
% Nsensors x Nsources: Each column of G is the forward field
% created by a dipolar source of unit amplitude. Otherwise, G is
% the name of the binary file containing the gain matrix. This
% file can be read using the READ_GAIN function.
% OPTIONS Returns the OPTIONS structure with updated fields following the
% call to BST_HEADMODELER. Can be useful to obtain a full
% BrainStorm Channel structure when only the .ChannelLoc and
% possibly .ChannelOrient fields were provided.
%<autobegin> ---------------------- 27-Jun-2005 10:43:31 -----------------------
% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------
%
% CATEGORY: Forward Modeling
%
% Alphabetical list of external functions (non-Matlab):
% toolbox\bem_gain.m
% toolbox\bem_xfer.m
% toolbox\berg.m
% toolbox\bst_message_window.m
% toolbox\colnorm.m
% toolbox\get_channel.m
% toolbox\get_user_directory.m
% toolbox\good_channel.m
% toolbox\gridmaker.m
% toolbox\inorcol.m
% toolbox\norlig.m
% toolbox\overlapping_sphere.m
% toolbox\rownorm.m
% toolbox\save_fieldnames.m
% toolbox\source_grids.m
% toolbox\view_surface.m
%
% Subfunctions in this file, in order of occurrence in file:
% BEMGaingridFname = bem_GainGrid(DataType,OPTIONS,BEMChanNdx)
% g = gterm_constant(r,rq)
%
% At Check-in: $Author: Silvin $ $Revision: 68 $ $Date: 12/15/05 4:14a $
%
% This software is part of BrainStorm Toolbox Version 27-June-2005
%
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
% University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
% Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
% CNRS, Hopital de la Salpetriere, Paris, France
%
% See BrainStorm website at http://neuroimage.usc.edu for further information.
%
% Copyright (c) 2005 BrainStorm by the University of Southern California
% This software distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 27-Jun-2005 10:43:31 -----------------------
% /---Script Author--------------------------------------\
% | |
% | *** Sylvain Baillet Ph.D. |
% | Cognitive Neuroscience & Brain Imaging Laboratory |
% | CNRS UPR640 - LENA |
% | Hopital de la Salpetriere, Paris, France |
% | [email protected] |
% | |
% \------------------------------------------------------/
%
% Date of creation: March 2002
% ----------------------------- Script History ---------------------------------
%
% SB 07-Aug-2002 Fixed GridLoc saving issues - now GridLoc
% is a cell array of length one which indicates
% the name of the tessellation file that was
% used as an imaging support.
% SB 03-Sep-2002 Fixed minor bugs when function is called from command line
% Now bst_headmodeler can be called even when Brainstorm is not running
% SB 05-Sep-2002 BEM can now be called from command line as well.
% Updated script header
% SB 06-Sep-2002 Updated EEG BEM : added option for arbitrary reference of the
% potentials (takes now OPTIONS.EEGRef into account).
% SB 18-Nov-2002 Updated EEG reference management.
% SB 21-Nov-2002 Minor fixes for command line calls.
% SB 21-Nov-2002bis Fixed bug from the get(*,'VertexNormals') command that
% sometimes returns [0 0 0] at some vertex
% SB 23-Dec-2002 Correct HeadModelFile name is passed to OPTIONS output argument
% JCM 27-May-2004 Cleaning comments
% Found Matlab bug and temp solution.
% Matlab 6.5.0 bug, Technical Solution Number: 1-19NOK
% http://www.mathworks.com/support/solutions/data/1-19NOK.html?solution=1-19NOK
% Must REWIND first before fseek.
% Apparently fixed in 6.5.1
% Example:
% status = fseek(fdest,0,'bof');
% status = fseek(fdest,offset,'bof');
% SB 08-Mar-2005 Fixed bug in BEM computation
% SB 02-Feb-2005 Fixed bug that occured when ChannelLoc field is used to
% passed EEG channel locations (thanks Jeremie Mattout at the FIL)
% ----------------------------- Script History ---------------------------------
% Default options settings--------------------------------------------------------------------------------------------------
DefaultMethod = {'meg_sphere','eeg_3sphereBerg'};
ReducePatchScalpNVerts = 500; % Number of vertices the scalp tessellation will be reduced to in OS computations
BEM_defaults = struct(...
'Basis','linear',...
'Test','galerkin',...
'Interpolative',0,...
'ISA',1,...
'NVertMax',1000,...
'ForceXferComputation', 1, ...
'checksurf',0);
Def_OPTIONS = struct(...
'ApplyGridOrient',1,...
'BEM', BEM_defaults,...
'Channel', [],...
'ChannelFile', '',...
'ChannelLoc', '',...
'ChannelOrient', '',...
'ChannelType', '',...
'Conductivity', [.33 .0042 .33],...
'Cortex',[],...
'EEGRef','',...
'HeadCenter',[],...
'HeadModelFile', '',...
'HeadModelName','Default',...
'ImageGridBlockSize', 2000,...
'ImageGridFile', '',...
'GridOrient',[],...
'Method', {DefaultMethod},...
'OS_ComputeParam', 1,...
'PrefixFileName','bst_',...
'Radii', [],...
'Scalp',[],...
'SourceLoc',[],...
'SourceModel', [-1],...
'SourceOrient',[],...
'StudyFile','',...
'TessellationFile','',...
'VolumeSourceGrid',1,...
'VolumeSourceGridSpacing', 2,...
'VolumeSourceGridLoc', [],...
'Verbose', 1 ...
);
SourceOrderString = {'Current Dipole',...
'Unvalid Order (was Magnetic Dipole Moment)',...
'Current Multipole Expansion',...
'Current Dipole Pairs',...
'Unvalid Order (was Magnetic Dipole Moment PAIRS)',...
'Current Multipole Expansion Pairs'};
if nargin == 0
if nargout > 1
varargout{1} = Def_OPTIONS;
varargout{2} = Def_OPTIONS;
else
varargout{1} = Def_OPTIONS;
end
return
elseif nargin == 1
if ischar(varargin{1}) % User enters only the studyfile name
StudyFile = varargin{1};
OPTIONS = Def_OPTIONS;
elseif isstruct(varargin{1}) % User enters only the OPTION field
OPTIONS = varargin{1};
else
errordlg('Uncorrect input parameter type, please check the help file'), varargout = cell(nargout,1);
return,
end
elseif nargin == 2 % No options were specified, apply default
StudyFile = varargin{1};
OPTIONS = varargin{2};
else
errordlg('Wrong number of arguments when calling head modeler')
varargout = cell(nargout,1);
return
end
% Check field names of passed OPTIONS and fill missing ones with default values
DefFieldNames = fieldnames(Def_OPTIONS);
for k = 1:length(DefFieldNames)
if ~isfield(OPTIONS,DefFieldNames{k}) | strcmp(DefFieldNames{k},'BEM')
if ~isfield(OPTIONS,DefFieldNames{k})
OPTIONS = setfield(OPTIONS,DefFieldNames{k},getfield(Def_OPTIONS,DefFieldNames{k}));
elseif strcmp(DefFieldNames{k},'BEM')
BEM_DefFieldNames = fieldnames(BEM_defaults);
for kk = 1:length(BEM_DefFieldNames)
if ~isfield(OPTIONS.BEM,BEM_DefFieldNames{kk})
OPTIONS.BEM = setfield(OPTIONS.BEM,BEM_DefFieldNames{kk},getfield(BEM_defaults,BEM_DefFieldNames{kk}));
end
end
end
end
end
if isempty(OPTIONS.Conductivity)
OPTIONS.Conductivity = Def_OPTIONS.Conductivity;
end
clear Def_OPTIONS
if isempty(OPTIONS.HeadModelFile) & ~isempty(OPTIONS.ImageGridFile)
% Force creation of a headmodel file
OPTIONS.HeadModelFile = 'default';
end
OPTIONS.HeadModelFileOld = OPTIONS.HeadModelFile;
% What type of forward model (MEG and/or EEG) ?
DataType.MEG = strmatch('meg',OPTIONS.Method); % Rank of the respective forward method in cell array Method (ie could be Method = {'meg_bem','eeg_sphere'} or vice-versa)
DataType.EEG = strmatch('eeg',OPTIONS.Method);
if ~iscell(OPTIONS.Method)
OPTIONS.Method = {OPTIONS.Method};
end
MegMethod = [];
if ~isempty(DataType.MEG)
MegMethod = OPTIONS.Method{DataType.MEG}; % String indicating the forward method selected for MEG (res. EEG)
end
EegMethod = [];
if ~isempty(DataType.EEG)
EegMethod = OPTIONS.Method{DataType.EEG};
end
% Check inputs integrity
%Source models
if ~isempty(find(OPTIONS.SourceModel == 0)) | ~isempty(find(abs(OPTIONS.SourceModel) > 1)) % unValid source models
if ~isempty(DataType.MEG)
errordlg('Valid source model orders for MEG are: -1 (Current Dipole) and 1 (fist-order Current Multipole Expansion)')
end
if ~isempty(DataType.EEG)
errordlg('Valid source model order for EEG is: -1 (Current Dipole) ')
end
varargout = cell(nargout,1);
return
end
% Source locations
if isempty(OPTIONS.SourceLoc) & ~OPTIONS.VolumeSourceGrid & isempty(OPTIONS.Cortex) % No source locations were specified
errordlg('No source locations are specified. Please fill either one of the following fields of OPTIONS: .SourceLoc / .VolumeSourceGrid / .Cortex')
varargout = cell(nargout,1);
return
end
%--------------------------------------------------------------------------------------------------------------------------------------------
%
% HEAD MODELING BEGINS
%
%--------------------------------------------------------------------------------------------------------------------------------------------
if OPTIONS.Verbose,
clockk = fix(clock);
time0 = clock;
bst_message_window({...
' ',...
'__________________________________________',...
sprintf(...
'Head modeling begins (%s - %dH %dmin %ds)',date,clockk(4:6))...
})
end
User = get_user_directory;
if isempty(User) % Function is called from command line: BrainStorm is not running
% Use default folders
User.SUBJECTS = pwd;
User.STUDIES = pwd;
end
try
cd(User.STUDIES)
catch
end
% Get all Subject and Study information------------------------------------------------------------------------------------------------------
if exist('StudyFile','var')
if OPTIONS.Verbose, bst_message_window('Loading Study and Subject Information...'), end
try
load(StudyFile) % Load study information
[StudyPath,tmp,ext] = fileparts(StudyFile); clear tmp
catch
errordlg(['Could not find ',StudyFile,' in current Matlab path'])
varargout = cell(nargout,1);
return
end
if isempty(OPTIONS.StudyFile)
OPTIONS.StudyFile = StudyFile;
end
SubjectFile = BrainStormSubject; clear BrainStormSubject
OPTIONS.rooot = findstr(StudyFile,'brainstormstudy.mat');
if isempty(OPTIONS.rooot)
errordlg('Study file name should be of the form ''*brainstormstudy.mat''')
varargout = cell(nargout,1);
return
end
OPTIONS.rooot = strrep(StudyFile,'brainstormstudy.mat','');
Study = load(StudyFile);
%User = get_user_directory;
try
cd(User.SUBJECTS)
Subject = load(Study.BrainStormSubject);
catch
errordlg(sprintf('Please make sure the subject''s information in %s is available on this plateform',Study.BrainStormSubject)); return
end
if isempty(OPTIONS.TessellationFile) % No Tessellation file was passed to the headmodeler
if isfield(Subject,'Tesselation')
OPTIONS.TessellationFile = Subject.Tesselation; % Take default (OBSOLETE as for BsT MMII because we now consider all tessellation files in Subject's folder)
else
OPTIONS.TessellationFile = '';
%[OPTIONS.TessellationFile,DataPopup, Leader] = find_brainstorm_files('tess',fullfile(Users.SUBJECTS,OPTIONS.subjectpath));
end
end
end
% Get Channel Information ------------------------------------------------------------------------------------------------------------------
if ~isempty(OPTIONS.Channel)
Channel = OPTIONS.Channel;
else
if isempty(OPTIONS.ChannelFile) & isempty(OPTIONS.ChannelLoc) % Load Channel file in current folder
[Channel, ChannelFile] = get_channel(fullfile(User.STUDIES,OPTIONS.StudyFile));
OPTIONS.ChannelFile = fullfile(fileparts(fullfile(User.STUDIES,OPTIONS.StudyFile)),ChannelFile);
if isempty(ChannelFile)
errordlg(sprintf('Channel file %s is missing. Please have it available it the current study folder.',OPTIONS.ChannelFile), 'Missing Channel File')
return
end
elseif isempty(OPTIONS.ChannelLoc) & exist(OPTIONS.ChannelFile,'file') % If no specific channel locations are given and channel file exists, load the proper channel file
OPTIONS.rooot = strrep(lower(OPTIONS.ChannelFile),'channel.mat','');
try
load(OPTIONS.ChannelFile)
catch
cd(User.STUDIES)
load(OPTIONS.ChannelFile)
end
else % Create a dummy Channel structure with Channel Locations (res. Orientations) specified in OPTIONS.ChannelLoc (res .ChannelOrient)
if OPTIONS.Verbose, bst_message_window('Creating the channel structure from information in the OPTIONS fields. . .'), end
% Get Channel Locations
nchan = size(OPTIONS.ChannelLoc,2); % Number of channels
Channel = struct('Loc',[],'Orient',[],'Comment','','Weight',[],'Type','','Name','');
Channel(1:nchan) = deal(Channel);
ChanType = upper(OPTIONS.ChannelType);
if isempty(ChanType)
errordlg('Please specify a channel type (i.e. MEG or EEG) in the ChannelType field of OPTIONS'),
bst_message_window('Please specify a channel type (i.e. MEG or EEG) in the ChannelType field of OPTIONS'),
varargout = cell(nargout,1);
return
end
[Channel(:).Type] = deal(ChanType);
if size(OPTIONS.ChannelLoc,1) == 6 % MEG Gradiometers or mixture gradio/magneto meters
OPTIONS.ChannelLoc = reshape(OPTIONS.ChannelLoc,3,nchan*2);
iGradFlag = 1; % Flag - gradiometer-type sensor set
else
iGradFlag = 0; % Flag - EEG or magnetometer-type sensor set
end
ichan = 1;
for k = 1:nchan
if iGradFlag
Channel(k).Loc = OPTIONS.ChannelLoc(:,ichan:ichan+1);
ichan = ichan+2;
else
if strcmp(ChanType,'MEG')
Channel(k).Loc = OPTIONS.ChannelLoc(:,ichan);
%elseif strcmp(ChanType,'EEG') % Artificially add a dummy column full of zeros to each Channel(k).Loc
%Channel(k).Loc = [OPTIONS.ChannelLoc(:,ichan) [0 0 0]'];
elseif strcmp(ChanType,'EEG') % Artificially add a dummy column full of zeros to each Channel(k).Loc
Channel(k).Loc = [OPTIONS.ChannelLoc(:,ichan)];
end
ichan = ichan+1;
end
Channel(k).Name = sprintf('%s %d',ChanType,k);
Channel(k).Comment = int2str(k);
end
clear ichan k
% Get Channel Orientations
if isempty(OPTIONS.ChannelOrient) & strcmp(ChanType,'MEG') % No channel orientation were specified: use radial sensors
if OPTIONS.Verbose, bst_message_window('Assign radial orientation to all Channels. . .'), end
if isempty(OPTIONS.HeadCenter)
if iGradFlag
Vertices = OPTIONS.ChannelLoc(:,1:2:end)';
else
Vertices = OPTIONS.ChannelLoc';
end
nscalp = size(Vertices,1);
if nscalp > 500 % 500 points is more than enough to compute scalp's best fitting sphere
Vertices = Vertices(unique(round(linspace(1,nscalp,500))),:);
nscalp = size(Vertices,1);
end
nmes = size(Vertices,1);
% Run parameters fit --------------------------------------------------------------------------------------------------------------
mass = mean(Vertices); % center of mass of the scalp vertex locations
R0 = mean(norlig(Vertices - ones(nscalp,1)*mass)); % Average distance between the center of mass and the scalp points
vec0 = [mass,R0];
[minn,brp] = fminsearch('dist_sph',vec0,[],Vertices);
OPTIONS.HeadCenter = minn(1:end-1);
if isempty(OPTIONS.Radii)
OPTIONS.Radii = minn(end);
OPTIONS.Radii = minn(end)*[1/1.14 1/1.08 1];
end
if OPTIONS.Verbose, bst_message_window({...
sprintf('Center of the Sphere : %3.1f %3.1f %3.1f (cm)',100*OPTIONS.HeadCenter),...
sprintf('Radius : %3.1f (cm)',100*OPTIONS.Radii(3)),...
'-> DONE',' '})
end
clear minn brp mass R0 Vertices vec0
end
tmp = [Channel.Loc] - repmat(OPTIONS.HeadCenter',1,nchan*(1+(iGradFlag==1)));
OPTIONS.ChannelOrient = tmp*inorcol(tmp); % Radial orientation for every channel
clear tmp
elseif ~isempty(OPTIONS.ChannelOrient) & strcmp(ChanType,'MEG') & iGradFlag
OPTIONS.ChannelOrient = reshape(OPTIONS.ChannelOrient,3,nchan*2);
end
if strcmp(ChanType,'MEG')
for k=1:nchan
Channel(k).Orient = OPTIONS.ChannelOrient(:,((1+(iGradFlag==1))*k-1):(1+(iGradFlag==1))*k);
end
end
clear k
% Define Weights
if iGradFlag
[Channel(:).Weight] = deal([1 -1]);
else
[Channel(:).Weight] = deal([1]);
end
if strcmp(ChanType,'MEG') % Force no reference channels
Channel(1).irefsens = [];
end
% New Channel stbemructure completed: save as a new channel file
if ~isempty(OPTIONS.ChannelFile)
%OPTIONS.ChannelFile = [OPTIONS.rooot,'channel.mat'];
save(OPTIONS.ChannelFile,'Channel')
if OPTIONS.Verbose, bst_message_window({...
sprintf('Channel file created in : %s',OPTIONS.ChannelFile),...
'-> DONE',' '}), end
end
end
%load(OPTIONS.ChannelFile)
OPTIONS.Channel = Channel;
end
% Find MEG and EEG channel indices
MEGndx = good_channel(Channel,[],'MEG');
EEGndx = good_channel(Channel,[],'EEG');
EEGREFndx = good_channel(Channel,[],'EEG REF');
MEG = ~isempty(MEGndx) & ~isempty(DataType.MEG); % == 1 if MEG is requested and is available
EEG = ~isempty(EEGndx) & ~isempty(DataType.EEG);
if ~EEG & ~MEG
errordlg('Please check that data (MEG or EEG) and channel types are compatible.')
return
end
% Test whether CME models are requested for EEG
if ~isempty(find(OPTIONS.SourceModel == 1)) & EEG
if MEG
if OPTIONS.Verbose
bst_message_window('wrap',...
{'',...
'CME model not available for EEG - Skipping. . .',...
'Keeping it for MEG forward modeling only',...
''...
})
end
else % EEG only is requested
errordlg(...
{'CME model not available for EEG - Skipping. . .',...
'Keeping it for MEG forward modeling only'...
})
return
end
end
% Detect EEG reference - if none is specified in the .Comment or Type fields,
% and if none was passed through OPTIONS.EEGRef
% -> Apply average-referencing of the potentials by default.
if EEG
if isempty(OPTIONS.EEGRef)
% EEG Reference Channel
EEGREFndx = good_channel(Channel,[],'EEG REF');
if isempty(EEGREFndx) % Average EEG reference anyway
[Channel(EEGndx).Comment] = deal('AVERAGE REF');
end
else % EEG Reference is specified
switch(OPTIONS.EEGRef)
case 'AVERAGE REF'
[Channel(:).Comment] = deal('AVERAGE REF');
otherwise
EEGREFndx = strmatch(OPTIONS.EEGRef,char(Channel(:).Name));
if isempty(EEGREFndx)
errordlg(sprintf(...
'No channel named ''%s'' was found amongst available EEG channels. Cannot use it as a reference for EEG.',OPTIONS.EEGRef...
))
return
end
end
end
% if isempty(EEGREFndx) & ~MEG % No reference electrode was defined for the EEG stop if no MEG to compute...
% errordlg('Please make sure you have defined a reference for the EEG')
% return
% elseif isempty(EEGREFndx) & MEG % Skip EEG forward modeling and proceed to MEG
% EEG = 0;
% if OPTIONS.Verbose
% bst_message_window({...
% 'No reference was defined for the EEG',...
% 'Skipping EEG modeling and completing MEG only...',...
% })
% end
% end
end
if OPTIONS.Verbose,
if EEG & MEG
if ~isempty(EEGREFndx)
bst_message_window({'Channel count for current computation:',[int2str(length(MEGndx)), ' MEG Channels'],...
sprintf('%d EEG Channels with Reference: %s',length(EEGndx),Channel(EEGREFndx).Name),' '})
else
bst_message_window({'Channel count for current computation:',[int2str(length(MEGndx)), ' MEG Channels'],...
sprintf('%d EEG Channels with Average Reference',length(EEGndx)),' '})
end
elseif MEG
bst_message_window({'Channel count for current computation:',[int2str(length(MEGndx)), ' MEG Channels'],...
' '})
elseif EEG
if ~isempty(EEGREFndx)
bst_message_window({'Channel count for current computation:',...
sprintf('%d EEG Channels with Reference: %s',length(EEGndx),Channel(EEGREFndx).Name),' '})
else
bst_message_window({'Channel count for current computation:',...
sprintf('%d EEG Channels with Average Reference',length(EEGndx)),' '})
end
end
end
if MEG & isempty(MEGndx) % User wants to compute MEG but no MEG data is available
errordlg('Sorry - No MEG data is available'), return
end
if EEG & isempty(EEGndx) % User wants to compute EEG but no EEG data is available
errordlg('Sorry - No EEG data is available'), return
end
% Computation of parameters of the best-fitting sphere --------------------------------------------------------------------------------------------------------------
if length(findstr('bem',[OPTIONS.Method{:}])) ~= length(OPTIONS.Method)% Only if sphere-based head model is requested in any modality (MEG or EEG)
% Best-fitting sphere parameters --------------------------------------------------------------------------------------------------------------
if isempty(OPTIONS.HeadCenter) | isempty(OPTIONS.Radii)
if OPTIONS.Verbose, bst_message_window('Estimating Center of the Head. . .'), end
if isempty(OPTIONS.Scalp) % Best-fitting sphere is derived from the sensor array
% ans = questdlg('No scalp surface was selected - Do you want to use a spherical approximation of the head derived from the sensor locations instead ?',...
% '','Yes','No','Yes');
if EEG & length(EEGndx) > 9 % If EEG is available but a reasonable number of electrodes, use it to compute the sphere parameters
ndx = [EEGndx]; % Compute Sphere parameters from EEG sensors only
else
ndx = [MEGndx];
end
Vertices = zeros(length(ndx),3);
for k=1:length(ndx)
Vertices(k,:) = Channel(ndx(k)).Loc(:,1)';
end
else % Best-fitting sphere is computed from the set of vertices of the scalp surface enveloppe
try
load(fullfile(User.SUBJECTS,OPTIONS.Scalp.FileName),'Vertices')
catch
load(OPTIONS.Scalp.FileName,'Vertices')
end
if ~isfield(OPTIONS.Scalp,'iGrid') % Apply Default
OPTIONS.Scalp.iGrid = 1;
end
try
Vertices = Vertices{OPTIONS.Scalp.iGrid}';
catch
errordlg(sprintf(...
'Tessellation file %s does not contain %d enveloppes',...
OPTIONS.Scalp.FileName,OPTIONS.Scalp.iGrid))
end
end
nscalp = size(Vertices,1);
nmes = size(Vertices,1);
% Run parameters fit --------------------------------------------------------------------------------------------------------------
mass = mean(Vertices); % center of mass of the scalp vertex locations
R0 = mean(norlig(Vertices - ones(nscalp,1)*mass)); % Average distance between the center of mass and the scalp points
vec0 = [mass,R0];
[SphereParams,brp] = fminsearch('dist_sph',vec0,[],Vertices);
if OPTIONS.Verbose
bst_message_window({...
sprintf('Center of the Sphere : %3.1f %3.1f %3.1f (cm)',100*SphereParams(1:end-1)'),...
sprintf('Radius : %3.1f (cm)',100*SphereParams(end)),...
'-> DONE',' '})
end
end % no head center and sphere radii were specified by user
% Assign default values for sphere parameters
% if none were specified before
if isempty(OPTIONS.Radii)
OPTIONS.Radii = SphereParams(end)*[1/1.14 1/1.08 1];
end
if isempty(OPTIONS.HeadCenter)
OPTIONS.HeadCenter = SphereParams(1:end-1)';
end
if isempty(OPTIONS.Conductivity)
OPTIONS.Conductivity = [.33 .0042 .33];
end
end % Use BEM Approach, so proceed to the selection of the envelopes
% ---------------------------------------------------------------------------------------------------------
%Create HeadModel Param structure
Param(1:length(Channel)) = deal(struct('Center',[],'Radii',[],'Conductivity',[],'Berg',[]));
if ~isempty(findstr('os',[OPTIONS.Method{:}])) % Overlapping-Sphere EEG or MEG is requested: load the scalp's tessellation
if isempty(OPTIONS.Scalp)
errordlg('Please specify a subject tessellation file for Scalp enveloppe in OPTIONS.Scalp when using Overlapping-Sphere forward approach');
return
end
% load(fullfile(User.SUBJECTS,BrainStorm.SubjectTess),'Faces');
try
load(fullfile(User.SUBJECTS,OPTIONS.Scalp.FileName),'Faces','Vertices');
catch
load(OPTIONS.Scalp.FileName,'Faces','Vertices');
end
Faces = Faces{OPTIONS.Scalp.iGrid};
Vertices = Vertices{OPTIONS.Scalp.iGrid}';
if size(Vertices,1) > ReducePatchScalpNVerts % Reducepatch the scalp tessellation for fastest OS computation
nfv = reducepatch(Faces,Vertices,2*ReducePatchScalpNVerts);
if OPTIONS.Verbose, bst_message_window({...
sprintf('Decimated scalp tessellation from %d to %d vertices.',size(Vertices,1),size(nfv.vertices,1)),...
' '});
end
clear Faces Vertices
SubjectFV.vertices = nfv.vertices';
SubjectFV.faces = nfv.faces;
clear nfv
else
SubjectFV.vertices = Vertices; % Available from the computation of the head center above
clear Vertices
SubjectFV.faces = Faces; clear Faces
end
if length(findstr('os',[OPTIONS.Method{:}])) == 2 % OS approach requested fro both MEG and EEG
ndx = [MEGndx,EEGndx];
else
if MEG
if strcmpi('meg_os',OPTIONS.Method{DataType.MEG}) % OS for MEG only
ndx = MEGndx;
end
end
if EEG
if strcmpi('eeg_os',OPTIONS.Method{DataType.EEG}) % OS for EEG only
ndx = [EEGndx, EEGREFndx];
end
end
end
if OPTIONS.Verbose
bst_message_window({...
' ', 'Computing Overlapping-sphere model. . .'})
end
if isempty(OPTIONS.HeadModelFile) | OPTIONS.OS_ComputeParam
% Compute all spheres parameters
%------------------------------------------------------------------
Sphere = overlapping_sphere(Channel(ndx),SubjectFV,OPTIONS.Verbose,OPTIONS.Verbose);
if OPTIONS.Verbose
bst_message_window({...
'Computing Overlapping-sphere model -> DONE',' '})
end
[Param(ndx).Center] = deal(Sphere.Center);
[Param(ndx).Radii] = deal(Sphere.Radius);
[Param(ndx).Conductivity] = deal(OPTIONS.Conductivity);
elseif exist(OPTIONS.HeadModelFile,'file')
load(OPTIONS.HeadModelFile,'Param') % or use precomputed
if OPTIONS.Verbose
bst_message_window({...
sprintf('Sphere parameters loaded from : %s -> DONE',OPTIONS.HeadModelFile),' '})
end
else
errordlg(sprintf('Headmodel file %s does not exist in Matlab''s search path',OPTIONS.HeadModelFile))
return
end
end
% Saving HeadModel's Param structure in the headmodel file
if strcmp(lower(OPTIONS.HeadModelFile),'default')
if ~isfield(OPTIONS,'rooot')
OPTIONS.rooot = OPTIONS.PrefixFileName;
end
OPTIONS.HeadModelFile = [OPTIONS.rooot,'headmodel.mat'];
ifile = 0;
while exist(OPTIONS.HeadModelFile,'file') % Do not overwrite headmodel files
ifile = ifile + 1;
OPTIONS.HeadModelFile = [OPTIONS.rooot,'headmodel_',int2str(ifile),'.mat'];
end
elseif ~isfield(OPTIONS,'rooot') & ~isempty(OPTIONS.HeadModelFile)
OPTIONS.rooot = strrep(OPTIONS.HeadModelFile,'headmodel.mat','');
end
if ~isfield(OPTIONS,'rooot') % Last Chance
OPTIONS.rooot = 'bst_';
end
if ~isempty(findstr('sphere',[OPTIONS.Method{:}])) % Single or nested-sphere approaches
[Param([MEGndx, EEGndx, EEGREFndx]).Center] = deal(OPTIONS.HeadCenter);
[Param([MEGndx, EEGndx, EEGREFndx]).Radii] = deal(OPTIONS.Radii);
[Param([MEGndx, EEGndx, EEGREFndx]).Conductivity] = deal(OPTIONS.Conductivity);
if EEG & strcmpi('eeg_3sphereberg',lower(OPTIONS.Method{DataType.EEG})) % BERG APPROACH
if ~isempty(OPTIONS.HeadModelFile) & exist(OPTIONS.HeadModelFile,'file')
if OPTIONS.Verbose, bst_message_window('Checking for previous EEG "BERG" parameters'), end
ParamOld = load(OPTIONS.HeadModelFile,'Param');
iFlag = 0; % Flag
if isfield(ParamOld.Param,'Berg') & ~isempty(ParamOld.Param(1).Radii)
% Check if these older parameters were computed with the same as current radii and conductivity values
if ParamOld.Param(1).Radii ~= Param(1).Radii;
iFlag = 1;
end
if ParamOld.Param(1).Conductivity ~= Param(1).Conductivity;
iFlag = 1;
end
else
iFlag = 1;
end
else
iFlag = 1;
end
if iFlag == 1
if OPTIONS.Verbose , bst_message_window('Computing EEG "BERG" Parameters. . .'), end
[mu_berg_tmp,lam_berg_tmp] = berg(OPTIONS.Radii,OPTIONS.Conductivity);
Param(EEGndx(1)).Berg.mu = mu_berg_tmp; clear mu_berg_tmp
Param(EEGndx(1)).Berg.lam = lam_berg_tmp; clear lam_berg_tmp
if OPTIONS.Verbose, bst_message_window({'Computing EEG "BERG" Parameters -> DONE',' '}), end
else
if OPTIONS.Verbose , bst_message_window('Using Previous EEG "BERG" Parameters'), end
Param(EEGndx(1)).Berg.mu = ParamOld.Param(1).Berg.mu;
Param(EEGndx(1)).Berg.lam = ParamOld.Param(1).Berg.lam; clear ParamOld
end
[Param.Berg]= deal(Param(EEGndx(1)).Berg);
end
end
if ~isempty(findstr('bem',[OPTIONS.Method{:}])) % BEM approaches - Compute transfer matrices
if OPTIONS.BEM.Interpolative==0 & OPTIONS.VolumeSourceGrid %& isempty(OPTIONS.Cortex) % User wants volumic grid : force Interpolative approach
OPTIONS.BEM.Interpolative = 1; % CBB (SB, 07-May-2004)| Should work also for volumic grid
hwarn = warndlg('Volumic Source Grid BEM is only available for interpolative BEM. BEM computation will be now forced to interpolative. If you want a non-interpolative BEM on a cortical image grid, first uncheck the Volumic Grid box from headmodeler gui.','Limitation from current BrainStorm version');
drawnow
waitfor(hwarn)
end
if MEG
if ~isempty(findstr('bem',OPTIONS.Method{DataType.MEG})) % BEM is requested for MEG
BEMChanNdx{DataType.MEG} = MEGndx;
end
end
if EEG
if ~isempty(findstr('bem',OPTIONS.Method{DataType.EEG})) % BEM is requested for EEG
BEMChanNdx{DataType.EEG} = sort([EEGndx,EEGREFndx]); % EEGREFndx = [] is average ref
end
end
OPTIONS.Param = Param;
if OPTIONS.BEM.Interpolative % Computation of gain matrix over 3D interpolative grid
if OPTIONS.BEM.ForceXferComputation
BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx); % Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data
else
try
BEMGaingridFileName = OPTIONS.BEM.GaingridFileName;
catch
cd(User.STUDIES)
BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx); % Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data
end
end
if MEG & EEG
[Param(MEGndx).bem_gaingrid_mfname] = deal(BEMGaingridFileName.MEG);
[Param([EEGndx]).bem_gaingrid_mfname] = deal(BEMGaingridFileName.EEG);
else
[Param(:).bem_gaingrid_mfname] = deal(BEMGaingridFileName);
end
else % BEM gain matrix computation over cortical surface
BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx);
[Param(:).bem_gaingrid_mfname] = deal('');
end
OPTIONS = rmfield(OPTIONS,'Param');
ndx = sort([BEMChanNdx{:}]);
[Param(ndx).Center] = deal([]);
test=0; % this test is nowhere defined ?
if OPTIONS.VolumeSourceGrid
% Now define the outer scalp envelope for the source volume gridding if requested
if OPTIONS.BEM.ForceXferComputation | ~test
global nfv
SubjectFV.vertices = nfv(end).vertices';
SubjectFV.faces = nfv(end).faces; clear Faces
else
load(fullfile(User.SUBJECTS,fileparts(OPTIONS.Subject),OPTIONS.BEM.EnvelopeNames{end}.TessFile))
idScalp = find(strcmpi(OPTIONS.BEM.EnvelopeNames{end}.TessName,Comment)); clear Comment
if isempty(idScalp)
errodlg(sprintf(...
'Scalp tessellation %s was not found in %s.',OPTIONS.BEM.EnvelopeNames{end}.TessName, OPTIONS.BEM.EnvelopeNames{end}.TessFile),...
'Error during BEM computation')
return
end
SubjectFV.vertices = Vertices{idScalp}'; clear Vertices
SubjectFV.faces = Faces{idScalp}; clear Faces
end
end
end % if BEM
if EEG
switch(lower(OPTIONS.Method{DataType.EEG}))
case 'eeg_sphere'
[Param(EEGndx).EEGType] = deal('EEG_SINGLE');
case 'eeg_3sphere'
[Param(EEGndx).EEGType] = deal('EEG_3SHELL');
case 'eeg_3sphereberg'
[Param(EEGndx).EEGType] = deal('EEG_BERG');
case 'eeg_os'
[Param(EEGndx).EEGType] = deal('EEG_OS');
case 'eeg_bem'
[Param(EEGndx).EEGType] = deal('BEM');
if EEG & ~MEG
[Param(EEGndx).bem_gaingrid_mfname] = deal(BEMGaingridFileName);
end
end
else
tmp = [];
[Param.Conductivity] = deal(tmp);
[Param.Berg] = deal(tmp);
[Param.EEGType] = deal(tmp);
end
%_________________________________________________________________________________________________________________________________________________________________________
%
% The following part is an adaptation of the former HEADMODEL_MAKE script
%
% ________________________________________________________________________________________________________________________________________________________________________
% Allocate function names depending on the selected forward approaches specified in the Method argument
Function = cell(1,length(Channel)); %allocate function names
if MEG
if ~isempty(findstr('bem',OPTIONS.Method{DataType.MEG})) % MEG BEM
Function(MEGndx) = deal({'meg_bem'});
if isfield(Channel(MEGndx(1)),'irefsens')
Function(Channel(MEGndx(1)).irefsens) = deal({'meg_bem'});
end
else
Function(MEGndx) = deal({'os_meg'});
if isfield(Channel(MEGndx(1)),'irefsens')
Function(Channel(MEGndx(1)).irefsens) = deal({'os_meg'});
end
if isfield(OPTIONS,'BEM')
OPTIONS = rmfield(OPTIONS,'BEM');
end
end
end
if EEG
if ~isempty(findstr('bem',OPTIONS.Method{DataType.EEG})) % MEG BEM
Function(EEGndx) = deal({'eeg_bem'});
else
Function(EEGndx) = deal({'eeg_sph'});
if isfield(OPTIONS,'BEM')
OPTIONS = rmfield(OPTIONS,'BEM');
end
end
end
% --------------------------------------------------------------------------------------------------------
DIMS = [3 12]; % number of columns for each parametric source model: Current Dipole / Current Multipole
HeadModel.Param = Param;
HeadModel.Function = Function;
if OPTIONS.VolumeSourceGrid % if SearchGain matrices are requested
SearchGain = cell(1,6); % One cell for each source order + pairs of sync. sources - keep 2 'phantom' cells for former Magnetic Dipole model
%------------------------------ Computing SearchGridLoc and SearchGain-------------------------------------------
if ~isempty(findstr(MegMethod,'bem')) | (EEG & ~MEG)
if OPTIONS.Verbose, bst_message_window(...
{'Forward modeling not available for EEG''s Current Mulipole models or the BEM approach','Computing forward fields for Current Dipole models. . .'...
,' '}), end
%return
OPTIONS.SourceModel = [-1]; % Force current dipole source model when MEG BEM or any EEG is requested
end
if OPTIONS.Verbose, bst_message_window(...
'Computing the Gain Matrices from the Volumic Search Grid. . .'), end
% Prepare call to source_grids
GUI.VALIDORDER = OPTIONS.SourceModel;
GUI.SPACING = 10*OPTIONS.VolumeSourceGridSpacing; % Pass it to source_grids in millimeters
GUI.VERBOSE = OPTIONS.Verbose;
GUI.MEG = MEG;
GUI.EEG = EEG;
if ~exist('SubjectFV','var')
% Create a spherical tessellation of the INNER SKULL surface boundary for source gridding
[x,y,z] = sphere(30);
%Scale to Radius BrainStorm.R
[TH,PHI,R] = cart2sph(x,y,z);
if OPTIONS.Radii(1) == 0
error('The sphere radius you have specified is ZERO - please change it to a non null positive value')
end
R = OPTIONS.Radii(1) * ones(size(R));
[x,y,z] = sph2cart(TH,PHI,R);
% Tessellate both hemispheres
Im = find(z>=0);
tri = delaunay(x(Im),y(Im));
%Gather everything into the same patch
SubjectFV.vertices = [x(Im),y(Im),z(Im);...
x(Im),y(Im),-z(Im)];
% Translate about the head center
SubjectFV.vertices = SubjectFV.vertices + repmat(OPTIONS.HeadCenter',size(SubjectFV.vertices,1),1);
SubjectFV.faces = [tri;tri(:,[3 2 1])+max(tri(:))];
clear x y z R TH PHI Im tri
end
HeadModel = source_grids(HeadModel,Channel,SubjectFV,GUI);
clear SubjectFV
if OPTIONS.Verbose, bst_message_window({...
'-> DONE',...
'Now saving HeadModel file. . .'...
})
end
% Now save VolumeSourceGrid headmodel(s)
SaveHeadModel.Param = HeadModel.Param;
SaveHeadModel.Function = HeadModel.Function;
if strcmpi(OPTIONS.HeadModelName,'Default') % Specify default HeadModelName
if MEG & EEG
SaveHeadModel.HeadModelName = sprintf('%s | %s', OPTIONS.Method{DataType.MEG},OPTIONS.Method{DataType.EEG});
elseif MEG
SaveHeadModel.HeadModelName = sprintf('%s', OPTIONS.Method{DataType.MEG});
elseif EEG
SaveHeadModel.HeadModelName = sprintf('%s', OPTIONS.Method{DataType.EEG});
end
else
SaveHeadModel.HeadModelName = OPTIONS.HeadModelName;
end
if ~isempty(OPTIONS.HeadModelFile),
[HeadModelFilePath,HeadModelFile,ext] = fileparts(OPTIONS.HeadModelFile);
end
try
cd(User.STUDIES)
catch
end
for k = 1:length(GUI.VALIDORDER) % One file per source order
% Specify Source Model Name and Other Fields
if GUI.VALIDORDER(k) == -1
SourceOrderString = 'CD'; % Current Dipole
elseif GUI.VALIDORDER(k) == 0
SourceOrderString = 'MD'; % Magnetic Dipole
elseif GUI.VALIDORDER(k) == 1
SourceOrderString = 'CME'; % Current Multipole
end
[SaveHeadModel.Param.Order] = deal(GUI.VALIDORDER(k));
SaveHeadModel.SourceOrder = GUI.VALIDORDER(k); % Alternative to previous line
SaveHeadModel.HeadModelType = 'SearchGrid';
if MEG
SaveHeadModel.MEGMethod = OPTIONS.Method{DataType.MEG};
end
if EEG
SaveHeadModel.EEGMethod = OPTIONS.Method{DataType.EEG};
end
SaveHeadModel.GridName = {sprintf('%s Volumic Grid : %3.1f cm spacing',SourceOrderString, OPTIONS.VolumeSourceGridSpacing)};
SaveHeadModel.GridLoc = HeadModel.GridLoc(GUI.VALIDORDER(k)+2);
SaveHeadModel.Gain = {single(HeadModel.Gain{GUI.VALIDORDER(k)+2})}; % Convert to single precision gain matrix as in BST MMII convention
% now collect together and save
if ~isempty(OPTIONS.HeadModelFile), % User has provided a headmodel file name
SaveHeadModelFile = fullfile(HeadModelFilePath,[HeadModelFile,...
sprintf('VolGrid_%s',SourceOrderString),...
ext]);
ifile = 0;
while exist(SaveHeadModelFile,'file') % Do not overwrite headmodel files
ifile = ifile + 1;
SaveHeadModelFile = fullfile(HeadModelFilePath,[HeadModelFile,...
sprintf('VolGrid_%s',SourceOrderString),...
'_',int2str(ifile),ext]);
end
if OPTIONS.Verbose, bst_message_window({...
sprintf('Writing HeadModel file:'),...
sprintf('%s', SaveHeadModelFile)...
})
end
if strcmp(lower(OPTIONS.HeadModelFileOld),'default')
OPTIONS.HeadModelFile = SaveHeadModelFile;
end
save_fieldnames(SaveHeadModel, SaveHeadModelFile);
if OPTIONS.Verbose, bst_message_window(...
{'-> DONE',' '}), end
end
end
OPTIONS.HeadModelName = SaveHeadModel.HeadModelName;
if OPTIONS.Verbose, bst_message_window(...
{'Grid gain matrices are saved','RAP-MUSIC & Least-Squares Fits Approaches are now available',' '})
end
end
%% -------------------------------------------------------------------------
%
% Now proceed to forward modeling of cortical grids or at some other specific source locations
%
%% -------------------------------------------------------------------------
if ~isempty(OPTIONS.Cortex), % subject has cortical vertices as source supports
% First make room in memory
HeadModel.SearchGain = [];
clear SearchGridLoc SearchGain G
if OPTIONS.Verbose, bst_message_window({...
'Computing the Image Gain Matrices (this may take a while). . .'})
end
% Find the cortical grid where to compute the forward model in the tessellation file
try
ImageGrid = load(fullfile(User.SUBJECTS,OPTIONS.Cortex.FileName),'Comment','Vertices');
catch
ImageGrid = load(OPTIONS.Cortex.FileName,'Comment','Vertices');
end
if ~isfield(OPTIONS.Cortex,'iGrid')
OPTIONS.Cortex.iGrid = 1;
end
if OPTIONS.Cortex.iGrid > length(ImageGrid.Comment) % Corresponding cortical surface not found
errordlg(sprintf('Cortical Tessellation file "%s" does not contain %d surfaces',...
OPTIONS.Cortex.FileName,OPTIONS.Cortex.iGrid))
return
end
GridLoc = ImageGrid.Vertices{OPTIONS.Cortex.iGrid}; % keep only the desired cell
ImageGrid = rmfield(ImageGrid,'Vertices');
elseif ~isempty(OPTIONS.SourceLoc) % Specific source locations are provided
if size(OPTIONS.SourceLoc,1) ~= 3
OPTIONS.SourceLoc = OPTIONS.SourceLoc';
end
GridLoc = OPTIONS.SourceLoc;
else
rmfield(OPTIONS,'rooot');
if nargout == 1
varargout{1} = OPTIONS;
else
varargout{1} = HeadModel;
varargout{2} = OPTIONS;
end
return % No ImageGrid requested
end
if ~isempty(OPTIONS.Cortex)
GridName{OPTIONS.Cortex.iGrid} = ImageGrid.Comment{OPTIONS.Cortex.iGrid};
OPTIONS.Cortex.Name = ImageGrid.Comment{OPTIONS.Cortex.iGrid};
end
%for i = 1 % CHEAT - Dipoles only here
for Order = OPTIONS.SourceModel % Compute gain matrices for each requested source models (-1 0 1)
i = 1; % Index to cell in headmodel cell arrays (MMII convention)
switch(Order)
case -1
SourceOrderString = 'CD'; % Current Dipole
Dims = DIMS(1);% number of columns per source
case 0
errordlg(sprintf('Unauthorized Source Model Order %d.',iSrcModel),'Wrong HeadModel parameter assignment')
return
%SourceOrderString = 'MD'; % Magnetic Dipole - OBSOLETE
case 1
SourceOrderString = 'CME'; % Current Multipole
Dims = DIMS(2);% number of columns per source
otherwise
errordlg(sprintf('Unauthorized Source Model Order %d.',iSrcModel),'Wrong HeadModel parameter assignment')
return
end
if OPTIONS.Verbose,
bst_message_window(...
'wrap',...
sprintf('Computing Gain Matrix for the %s Model',SourceOrderString))
h = waitbar(0,sprintf('Computing Gain Matrix for the %s Model',SourceOrderString));
pos = get(h,'position');
end
if ~isempty(OPTIONS.Cortex) & OPTIONS.ApplyGridOrient % Use cortical grid
try
load(OPTIONS.Cortex.FileName,'Faces');
catch
Users = get_user_directory;
load(fullfile(Users.SUBJECTS,OPTIONS.Cortex.FileName),'Faces');
end
Faces = Faces{OPTIONS.Cortex.iGrid};
ptch = patch('Vertices',GridLoc','Faces',Faces,'Visible','off');
set(get(ptch,'Parent'),'Visible','off')
clear Faces
GridOrient{i} = get(ptch,'VertexNormals')'; % == {1} as of MMII conventions. Most data in HeadModel files are single-cell cell arrays.
% Cell array structure kept for backward compatibility with BsT2000.
delete(ptch);
end
if OPTIONS.ApplyGridOrient % Take cortex normals into account
if isempty(OPTIONS.GridOrient) & isempty(OPTIONS.SourceOrient) % Consider the cortical patch's normals
if isempty(OPTIONS.Cortex) % Specific source locations in .SourceLoc but nohing in. SourceOrient
OPTIONS.ApplyGridOrient = 0; % No source orientation specified: Force computation of full gain matrix
else
[nrm,GridOrient{i}] = colnorm(GridOrient{i});
% Now because some orientations may be ill-set to [0 0 0] with the get(*,'VertexNormals' command)
% set these orientation to arbitrary [1 1 1]:
izero = find(nrm == 0);clear nrm
if ~isempty(izero)
GridOrient{i}(:,izero) = repmat([1 1 1]'/norm([1 1 1]),1,length(izero));
end
clear izero
end
elseif ~isempty(OPTIONS.GridOrient) % Apply user-defined cortical source orientations
if size(OPTIONS.GridOrient,2) == size(GridLoc,2) % Check size integrity
GridOrient{i} = OPTIONS.GridOrient;
[nrm,GridOrient{i}] = colnorm(GridOrient{i});
clear nrm
else
errordlg(sprintf('The source orientations you have provided are for %0.f sources. Considered cortical surface has %0.f sources. Computation aborted',...
size(OPTIONS.GridOrient,2),size(GridOrient{i},2)));
return
end
elseif ~isempty(OPTIONS.SourceOrient) % Apply user-defined specific source orientations
if size(OPTIONS.SourceOrient,2) == size(GridLoc,2) % Check size integrity
GridOrient{i} = OPTIONS.SourceOrient;
[nrm,GridOrient{i}] = colnorm(GridOrient{i});
clear nrm
else
errordlg(sprintf('The source orientations you have provided are for %0.f sources. Computation aborted',...
size(OPTIONS.SourceOrient,2)));
return
end
end
end
nv = size(GridLoc,2); % number of grid points
if ~isempty(OPTIONS.ImageGridFile) % Save cortical gain matrix in a binary file
[PATH,NAME,EXT,VER] = spm_fileparts(OPTIONS.HeadModelFile);
if strcmp(lower(OPTIONS.ImageGridFile),'default')
if exist('GridName','var') % Cortical support was specified
destname = [NAME,'_Gain_',strrep(ImageGrid.Comment{OPTIONS.Cortex.iGrid},' ',''),'_',SourceOrderString,'.bin']; % New naming (March, 19 - 2002)
k = 1;
try
while exist(destname,'file') % Don't write over existing .bin gain matrix file
destname = [NAME,'_Gain_',strrep(ImageGrid.Comment{OPTIONS.Cortex.iGrid},' ',''),'_',SourceOrderString,'_',int2str(k),'.bin']; % New naming (March, 19 - 2002)
k = k+1;
end
catch
while exist(destname,'file') % Don't write over existing .bin gain matrix file
destname = [NAME,'_Gain_',strrep(ImageGrid.Comment{OPTIONS.Cortex.iGrid},' ',''),'_',SourceOrderString,'_',int2str(k),'.bin']; % New naming (March, 19 - 2002)
k = k+1;
end
end
clear k
else % Specific location was provided in .SourceLoc
destname = [NAME,'_Gain_SpecLoc_',SourceOrderString,'.bin']; % Specific location was provided in .SourceLoc
k = 1;
while exist(destname,'file') % Don't write over existing .bin gain matrix file
destname = [NAME,'_Gain_SpecLoc_',SourceOrderString,'_',int2str(k),'.bin'];
k = k+1;
end
clear k
end
OPTIONS.ImageGridFile = destname;
else
[PATH,destname,ext,ver] = spm_fileparts(OPTIONS.ImageGridFile);
destname = [destname, ext];
end
% Check whether this name exists - if yes, don't overwrite
try
cd(fullfile(User.STUDIES,PATH))
catch
cd(PATH)
end
hdml = 1;
while exist(destname,'file')
if hdml == 1
destname = strrep(destname,'.bin',['_',int2str(hdml),'.bin']);
else
destname = strrep(destname,[int2str(hdml-1),'.bin'],[int2str(hdml),'.bin']);
end
hdml = hdml+1;
end
clear hdml
destnamexyz = [destname(1:end-4) '_xyz.bin'];
fdest = fopen(destname,'w','ieee-be');
fdestxyz = fopen(destnamexyz,'w','ieee-be');
if ((fdest < 0) | (fdestxyz < 0))
errordlg('Error creating the file for the cortical image forward model; Please check for disk space availability')
return
end
frewind(fdest);
frewind(fdestxyz)
fwrite(fdest,length([OPTIONS.Channel]),'uint32');
fwrite(fdestxyz,length([OPTIONS.Channel]),'uint32');
% % BEM and non-interpolative, store gain matrix already computed
% if isfield(OPTIONS,'BEM') % BEM computation
% if ~OPTIONS.BEM.Interpolative
% global GBEM_grid
% end
% end
if ((fdest < 0) | (fdestxyz < 0)) , errordlg('Please Check Write Permissions', ['Cannot create ',destname]), return, end
else % If no ImageGridFile was specified
%OPTIONS.ImageGridBlockSize = nv; % Force a one-time computation of all source forward fields
end
src_ind = 0;
jj = 0; % Number of OPTIONS.ImageGridBlockSize
for j = 1:(OPTIONS.ImageGridBlockSize):nv,
jj = jj+1;
if 1%OPTIONS.ApplyGridOrient
ndx = [0:OPTIONS.ImageGridBlockSize-1]+j;
else
ndx = [0:3*OPTIONS.ImageGridBlockSize-1]+j;
end
if 1%OPTIONS.ApplyGridOrient
if(ndx(end) > nv), % last OPTIONS.ImageGridOPTIONS.ImageGridBlockSizeSize too long
ndx = [ndx(1):nv];
end
else
if(ndx(end) > 3*nv),
ndx = [ndx(1):3*nv];
end
end
% Compute MEG
if MEG & ~isempty(MEGndx)
Gmeg = NaN*zeros(length(MEGndx),Dims*length(ndx));
if ~isempty(Function{MEGndx(1)})
if MEG & EEG
clear('gain_bem_interp2'); % Free persistent variables to avoid confusion
end
if isfield(OPTIONS,'BEM') % BEM computation
if ~OPTIONS.BEM.Interpolative % ~interpolative : retrieve stored gain matrix
global GBEM_grid
tmpndx = [3*(ndx(1)-1)+1:min([3*nv,3*ndx(end)])];%[0:3*OPTIONS.ImageGridBlockSize-1]+j;
Gmeg = GBEM_grid(MEGndx,tmpndx);
end
else
Gmeg = feval(Function{MEGndx(1)},GridLoc(:,ndx),Channel,Param,Order,OPTIONS.Verbose);
end
end
else
Gmeg = [];
end
if EEG & ~isempty(EEGndx) & i==1 % % Order -1 only for now in EEG
Geeg = NaN*zeros(length(EEGndx),Dims*length(ndx));
if ~isempty(Function{EEGndx(1)})
if MEG & EEG
clear('gain_bem_interp2'); % Free persistent variables to avoid confusion
end
if isfield(OPTIONS,'BEM') % BEM computation
if ~OPTIONS.BEM.Interpolative % ~interpolative : retrieve stored gain matrix
global GBEM_grid
%Geeg = GBEM_grid(EEGndx,[j:min([3*nv,j+3*OPTIONS.ImageGridBlockSize-1])]);
tmpndx = [3*(ndx(1)-1)+1:min([3*nv,3*ndx(end)])];%[0:3*OPTIONS.ImageGridBlockSize-1]+j;
%min(tmpndx ), max(tmpndx)
Geeg = GBEM_grid(EEGndx,tmpndx);
end
else
Geeg = feval(Function{EEGndx(1)},GridLoc(:,ndx),Channel,Param,Order,OPTIONS.Verbose);
end
end
else
Geeg = [];
end
G = NaN*zeros(length(OPTIONS.Channel),length(ndx));
Gxyz = NaN*zeros(length(OPTIONS.Channel),Dims*length(ndx));
if OPTIONS.Verbose, bst_message_window(...
['Computing Cortical Gain Vectors. . . Block # ',int2str(jj),...
' of ',int2str(length(1:OPTIONS.ImageGridBlockSize:nv))])
hh = waitbar(0,['Computing Cortical Gain Vectors. . . Block # ',int2str(jj),...
' of ',int2str(length(1:OPTIONS.ImageGridBlockSize:nv))]);
set(hh,'Position',[pos(1), pos(2)+pos(4),pos(3),pos(4)])
drawnow
end
src = 0;
% Options on cortical source orientation
% if OPTIONS.ApplyGridOrient % Apply source orientation
for k = 1:Dims:Dims*length(ndx)-2
src = src+1;
src_ind = src_ind+1;
if ~isempty(Gmeg)
G(MEGndx,src) = Gmeg(:,k:k+2) * GridOrient{1}(:,src_ind);
end
if ~isempty(Geeg)&(i==1)% % Order -1 only
G(EEGndx,src) = Geeg(:,k:k+2) * GridOrient{1}(:,src_ind);
end
if OPTIONS.Verbose,
if ~rem(src,5000)
waitbar(src/length(1:Dims:Dims*length(ndx)-2),hh)
end
end
end
% else % Do not apply cortical orientation. Keep full gain matrix at each cortical location
if MEG
Gxyz(MEGndx,:) = Gmeg;
end
if EEG
Gxyz(EEGndx,:) = Geeg;
end
% end
if OPTIONS.Verbose,
if ~rem(src_ind,1000)
waitbar(src_ind/nv,h)
end
delete(hh)
end
clear Gmeg Geeg
if ~isempty(OPTIONS.ImageGridFile)
% 4 bytes per element, find starting point
offset = 4 + (ndx(1)-1)*length(Channel)*4;
% Matlab 6.5.0 bug, Technical Solution Number: 1-19NOK
% http://www.mathworks.com/support/solutions/data/1-19NOK.html?solution=1-19NOK
% must REWIND first before fseek.
% Apparently fixed in 6.5.1
% JCM 27-May-2004
status = fseek(fdest,0,'bof');
status = fseek(fdest,offset,'bof');
if(status == -1),
errordlg('Error writing Image Gain Matrix file'); return
end
fwrite(fdest,G,'float32');
%save xyz forward matrix
offset = 4 + 3*(ndx(1)-1)*length(Channel)*4;
status = fseek(fdestxyz,0,'bof');
status = fseek(fdestxyz,offset,'bof');
if(status == -1),
errordlg('Error writing Image Gain Matrix file'); return
end
fwrite(fdestxyz,Gxyz,'float32');
end
end
if exist('destname','var') & ~isempty(OPTIONS.Cortex)
Gain{OPTIONS.Cortex.iGrid}{i} = destname;
OPTIONS.ImageGridFile = destname;
end
if OPTIONS.Verbose
close(h)
end
if ~isempty(OPTIONS.ImageGridFile)
fclose(fdest);
if OPTIONS.Verbose, bst_message_window({...
sprintf('Computing Gain Matrix for the %s Model -> DONE',SourceOrderString),...
sprintf('Saved in:'),...
sprintf('%s',destname)...
}),
end
end
% Now save ImageGrid headmodel(s)-----------------------------------------------------------------------------------
OPTIONS.HeadModelFile = OPTIONS.HeadModelFileOld; % Use original HeadModelFile entry
if strcmp(lower(OPTIONS.HeadModelFile),'default')
if ~isfield(OPTIONS,'rooot')
OPTIONS.rooot = OPTIONS.PrefixFileName;
end
OPTIONS.HeadModelFile = [OPTIONS.rooot,'headmodel.mat'];
ifile = 0;
while exist(OPTIONS.HeadModelFile,'file') % Do not overwrite headmodel files
ifile = ifile + 1;
OPTIONS.HeadModelFile = [OPTIONS.rooot,'headmodel_',int2str(ifile),'.mat'];
end
elseif ~isfield(OPTIONS,'rooot') & ~isempty(OPTIONS.HeadModelFile)
OPTIONS.rooot = strrep(OPTIONS.HeadModelFile,'headmodel.mat','');
end
SaveHeadModel.Param = HeadModel.Param;
SaveHeadModel.Function = HeadModel.Function;
if MEG
SaveHeadModel.MEGMethod = OPTIONS.Method{DataType.MEG};
end
if EEG
SaveHeadModel.EEGMethod = OPTIONS.Method{DataType.EEG};
end
if strcmpi(OPTIONS.HeadModelName,'Default') % Specify default HeadModelName
if MEG & EEG
SaveHeadModel.HeadModelName = sprintf('%s | %s', OPTIONS.Method{DataType.MEG},OPTIONS.Method{DataType.EEG});
elseif MEG
SaveHeadModel.HeadModelName = sprintf('%s', OPTIONS.Method{DataType.MEG});
elseif EEG
SaveHeadModel.HeadModelName = sprintf('%s', OPTIONS.Method{DataType.EEG});
end
else
SaveHeadModel.HeadModelName = OPTIONS.HeadModelName;
end
if ~isempty(OPTIONS.HeadModelFile), % and is not empty
[HeadModelFilePath,HeadModelFile,ext] = fileparts(OPTIONS.HeadModelFile);
end
% Assign proper GridName
switch(Order)
case -1
SourceOrderString = 'CD'; % Current Dipole
case 0
SourceOrderString = 'MD'; % Magnetic Dipole
case 1
SourceOrderString = 'CME'; % Current Multipole
end
[SaveHeadModel.Param.Order] = deal(Order);
SaveHeadModel.SourceOrder = Order; % Alternative to previous line
SaveHeadModel.HeadModelType = 'ImageGrid';
if ~isempty(OPTIONS.Cortex)
SaveHeadModel.GridName = {sprintf('%s Surface Grid : %s',SourceOrderString, OPTIONS.Cortex.Name)};
if ~isempty(OPTIONS.ImageGridFile)
SaveHeadModel.Gain = {OPTIONS.ImageGridFile}; % Store Image Grid File name in the headmodel.mat file
end
SaveHeadModel.GainCovar{1} = cell(1); % May compute it later within headmodel_make
SaveHeadModel.GainCovarName ='';
SaveHeadModel.GridLoc{1} = OPTIONS.Cortex.FileName;
if 1%OPTIONS.Cortex.iGrid > 1 % Meaning that cortical support is not the fisrt surface in tessellation file (default in MMII)
% Add yet another field to headmodel file to specify this information.
SaveHeadModel.iGrid = OPTIONS.Cortex.iGrid;
end
else
SaveHeadModel.GainCovar = [];
SaveHeadModel.GainCovarName = [];
SaveHeadModel.GridName = [];
SaveHeadModel.GridLoc = {OPTIONS.SourceLoc};
SaveHeadModel.Gain = {OPTIONS.ImageGridFile};
end
if ~OPTIONS.ApplyGridOrient
SaveHeadModel.GridOrient = [];
else
SaveHeadModel.GridOrient = {OPTIONS.SourceOrient};
end
% now collect together and save
if ~isempty(OPTIONS.HeadModelFile) & exist('destname','var')
% HeadModel file name
SaveHeadModelFile = fullfile(HeadModelFilePath,[HeadModelFile,...
sprintf('SurfGrid_%s',SourceOrderString),...
ext]);
ifile = 0;
while exist(SaveHeadModelFile,'file') % Do not overwrite headmodel files
ifile = ifile + 1;
SaveHeadModelFile = fullfile(HeadModelFilePath,[HeadModelFile,...
sprintf('SurfGrid_%s',SourceOrderString),...
'_',int2str(ifile),ext]);
end
if OPTIONS.Verbose, bst_message_window({...
sprintf('Writing Cortical Image Support HeadModel file:'),...
sprintf('%s', SaveHeadModelFile)...
})
end
if strcmp(lower(OPTIONS.HeadModelFileOld),'default')
OPTIONS.HeadModelFile = SaveHeadModelFile;
end
try
save_fieldnames(SaveHeadModel, SaveHeadModelFile);
catch
cd(User.STUDIES)
save_fieldnames(SaveHeadModel, SaveHeadModelFile);
end
if OPTIONS.Verbose, bst_message_window(...
{'-> DONE',' '}), end
end
% Save completed -----------------------------------------------------------------------------------
end % Cortical gain matrix for each source model
%% -------------------------------------------------------------------------
if isfield(OPTIONS,'rooot')
OPTIONS = rmfield(OPTIONS,'rooot');
end
if nargout == 0
clear G SearchGain
elseif nargout == 1
varargout{1} = OPTIONS;
else
if OPTIONS.ImageGridBlockSize < nv
varargout{1} = OPTIONS.HeadModelFile;
else
varargout{1} = G;
end
varargout{2} = OPTIONS;
end
fclose('all');
if OPTIONS.Verbose, bst_message_window(...
{'The head model has been properly designed and written to disk'})
end
if OPTIONS.Verbose, bst_message_window({...
sprintf(...
'Head modeling ends (%s - %dH %dmin %ds (took %3.2f seconds))',date,clockk(4:6), etime(clock,time0)),...
'__________________________________________'...
})
end
%------------------------------------------------------------------------------------------------------------------------------
%
% SUB-FUNCTIONS
%
%------------------------------------------------------------------------------------------------------------------------------
function BEMGaingridFname = bem_GainGrid(DataType,OPTIONS,BEMChanNdx)
% Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data
% DataType : a structure with fields MEG and EEG. DataType.MEG (res. DataType.EEG) is set to 1 if MEG (res. EEG) data is available
% OPTIONS : the OPTIONS structure, input argument from bst_headmodeler
% BEMChanNdx : a cell array of channel indices such that : BEMChanNdx{DataType.EEG} = EEGndx (res. MEG).
%
% BEMGaingridFname: a structure with fields:
% .EEG : string with the name of the file containing the gain matrix of the 3D BEM interpolative grid in EEG
% .MEG : same as .EEG respectively to MEG BEM model.
% Detect the requested BEM computations: MEG and/or EEG___________________________________
User = get_user_directory;
if isempty(User)
User.STUDIES = pwd;
User.SUBJECTS = pwd;
end
MEG = ~isempty(BEMChanNdx(DataType.MEG)); % == 1 if MEG is requested
EEG = ~isempty(BEMChanNdx(DataType.EEG)); % == 1 if EEG is requested
if MEG
MEGndx = BEMChanNdx{DataType.MEG};
end
if EEG
%EEGndx = BEMChanNdx{DataType.EEG};
EEGndx = OPTIONS.EEGndx; % EEG sensors (not including EEG reference channel, if any)
EEGREFndx = good_channel(OPTIONS.Channel,[],'EEG REF');
end
if MEG & EEG
[Param(:).mode] = deal(3);
elseif ~MEG & EEG
[Param(:).mode] = deal(1);
elseif MEG & ~EEG
[Param(:).mode] = deal(2);
else
errordlg('Please check that the method requested for forward modeling has an authorized name');
return
end
% BEM parameters ________________________________________________________________________
% Determine what basis functions to use
constant = ~isempty(strmatch('constant',lower(OPTIONS.BEM.Basis)));
if constant == 0
[Param(:).basis_opt] = deal(1);
else
[Param(:).basis_opt] = deal(0);
end
% Determine what Test to operate
collocation = ~isempty(strmatch('collocation',lower(OPTIONS.BEM.Test)));
if collocation == 0
[Param(:).test_opt] = deal(1);
else
[Param(:).test_opt] = deal(0);
end
% Insulated-skull approach
isa = OPTIONS.BEM.ISA;
if isa == 1
[Param(:).ISA] = deal(1);
else
[Param(:).ISA] = deal(0);
end
Param.Ntess_max = OPTIONS.BEM.NVertMax;
Param.Conductivity = deal(OPTIONS.Conductivity);
%_________________________________________________________________________________________
% Load surface envelopes information______________________________________________________
% Find the indices of the enveloppes selected for BEM computation
if ~isfield(OPTIONS.BEM,'EnvelopeNames')
errordlg('Please specify the ordered set of head-tissue envelopes by filling the OPTIONS.BEM.EnvelopeNames field')
return
end
if isempty(OPTIONS.BEM.EnvelopeNames)
errordlg('Please specify the ordered set of head-tissue envelopes by filling the OPTIONS.BEM.EnvelopeNames field')
return
end
for k = 1:length(OPTIONS.BEM.EnvelopeNames)
try
load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Comment');
catch % Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile
try
OPTIONS.BEM.EnvelopeNames{k}.TessFile = [OPTIONS.BEM.EnvelopeNames{k}.TessFile,'.mat'];
load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Comment');
catch
cd(User.SUBJECTS)
load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Comment');
end
end
Comment = strrep(Comment,' ','');
% find surface in current tessellation file
OPTIONS.BEM.EnvelopeNames{k}.SurfId = find(strcmpi(OPTIONS.BEM.EnvelopeNames{k}.TessName,Comment));
IDs(k) = OPTIONS.BEM.EnvelopeNames{k}.SurfId;
if isempty(OPTIONS.BEM.EnvelopeNames{k}.SurfId)
errordlg(...
sprintf('Surface %s was not found in file %s',...
OPTIONS.BEM.EnvelopeNames{k}.TessName, OPTIONS.BEM.EnvelopeNames{k}.TessFile))
return
end
% Load vertex locations
try
tmp = load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Vertices');
catch % Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile
tmp = load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Vertices');
end
Vertices{k} = tmp.Vertices{OPTIONS.BEM.EnvelopeNames{k}.SurfId}';
% Load faces
try
tmp = load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Faces');
catch% Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile
tmp = load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Faces');
end
Faces(k) = tmp.Faces(OPTIONS.BEM.EnvelopeNames{k}.SurfId);
end
clear Comment tmp
cd(User.STUDIES)
%_________________________________________________________________________________________
% Channel Parameters______________________________________________________________________
if MEG
R_meg1 = zeros(length(MEGndx),3);
O_meg1 = R_meg1;
R_meg2 = R_meg1;
O_meg2 = O_meg1;
flaggrad = zeros(length(MEGndx),1);% if = 1 - Flag to indicate there are some gradiometers here
i = 0;
for k = MEGndx
i = i+1;
R_meg1(i,:) = OPTIONS.Channel(k).Loc(:,1)';
O_meg1(i,:) = OPTIONS.Channel(k).Orient(:,1)';
if size(OPTIONS.Channel(k).Loc,2) == 2
if sum(OPTIONS.Channel(k).Loc(:,1)-OPTIONS.Channel(k).Loc(:,2))~=0 % Gradiometer
R_meg2(i,:) = OPTIONS.Channel(k).Loc(:,2)';
O_meg2(i,:) = OPTIONS.Channel(k).Orient(:,2)';
flaggrad(k-min(MEGndx)+1) = 1;
end
end
end
O_meg1 = (O_meg1' * inorcol(O_meg1'))';
if exist('O_meg2','var')
O_meg2 = (O_meg2' * inorcol(O_meg2'))';
end
% Handle MEG reference channels if necessary
% if isfield(OPTIONS.Channel(MEGndx(1)),'irefsens')
% irefsens = OPTIONS.Channel(MEGndx(1)).irefsens;
% else
% irefsens = [];
% end
irefsens = good_channel(OPTIONS.Channel,[],'MEG REF');
if ~isempty(irefsens)
flaggrad_REF = zeros(length(irefsens),1);% if = 1 - Flag to indicate there are some gradiometers here
R_meg_REF = zeros(length(irefsens),3);
O_meg_REF = R_meg_REF;
R_meg_REF = R_meg_REF;
O_meg_REF = R_meg_REF;
if ~isempty(irefsens) & ~isempty(OPTIONS.Channel(MEGndx(1)).Comment) % Reference Channels are present
if OPTIONS.Verbose, bst_message_window('Reference Channels have been detected.'), end
end
i = 0;
for k = irefsens
i = i+1;
R_meg_REF(i,:) = OPTIONS.Channel(k).Loc(:,1)';
O_meg_REF(i,:) = OPTIONS.Channel(k).Orient(:,1)';
if size(OPTIONS.Channel(k).Loc,2) == 2
if sum(OPTIONS.Channel(k).Loc(:,1)-OPTIONS.Channel(k).Loc(:,2))~=0 % Reference Gradiometer
R_meg_REF2(i,:) = OPTIONS.Channel(k).Loc(:,2)';
O_meg_REF2(i,:) = OPTIONS.Channel(k).Orient(:,2)';
flaggrad_REF(k-min(irefsens)+1) = 1;
end
end
end
else
R_meg_REF = [];
O_meg_REF = R_meg_REF;
R_meg_REF = R_meg_REF;
O_meg_REF = R_meg_REF;
end
MEGndx_orig = MEGndx;
else
R_meg1 = zeros(length(EEGndx),3); % Use dummy channel locations
O_meg1 = R_meg1;
R_meg2 = R_meg1;
O_meg2 = O_meg1;
end
if EEG
R_eeg = zeros(length([EEGREFndx,EEGndx]),3);
i = 0;
for k = [EEGREFndx,EEGndx]
i = i+1;
R_eeg(i,:) = OPTIONS.Channel(k).Loc(:,1)';
end
if ~MEG
flaggrad = [];
irefsens = [];
end
else
R_eeg = NaN * zeros(size(R_meg1)); % Dummy coordinates
end
%_________________________________________________________________________________________
%Compute Transfer Matrices__________________________________________________________________
BrainStorm.iscalp = IDs(end); % Index of the outermost surface (scalp, supposedly)
eeg_answ = '';
meg_answ = '';
% Check whether some transfer-matrix files already exist for current study
fn_eeg = sprintf('%s_eegxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
fn_meg = sprintf('%s_megxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
if MEG
test = exist(fn_meg,'file');
elseif EEG
test = exist(fn_eeg,'file');
else MEG& EEG
test = exist(fn_eeg,'file') & exist(fn_meg,'file');
end
if (OPTIONS.BEM.ForceXferComputation | ~test) | OPTIONS.BEM.Interpolative
% Force (re)computation of transfer matrices, even if files exist in current study folder
% if OPTIONS.Verbose, bst_message_window('Computing the BEM Transfer Matrix (this may take a while)....'), end
global nfv
nfv = bem_xfer(R_eeg,R_meg1,O_meg1,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...
Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg,Param.Ntess_max,OPTIONS.Verbose,OPTIONS.BEM.checksurf);
if ~isempty(find(flaggrad))
if OPTIONS.Verbose, bst_message_window({'Gradiometers detected',...
'Computing corresponding Gain Matrix. . .'}), end
%fn_meg_2 = fullfile(pwd,[OPTIONS.rooot,'_megxfer_2.mat']);
fn_meg_2 = sprintf('%s_megxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
bem_xfer(R_eeg,R_meg2,O_meg2,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...
Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_2,Param.Ntess_max,0,OPTIONS.BEM.checksurf); % Verbose = 0
if OPTIONS.Verbose, bst_message_window('Gradiometer Channel Gain Matrix is Completed.'), end
end
if ~isempty(irefsens) % Do the same for reference channels
%fn_meg_REF = fullfile(pwd,[OPTIONS.rooot,'_megxfer_REF.mat']);
fn_meg_REF = sprintf('%s_megREFxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
bem_xfer(R_eeg,R_meg_REF,O_meg_REF,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...
Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_REF,Param.Ntess_max,0,OPTIONS.BEM.checksurf);% Verbose = 0
if ~isempty(find(flaggrad_REF))
if OPTIONS.Verbose, bst_message_window({'MEG Reference Channels detected',...
'Computing corresponding Gain Matrix. . .'}), end
%fn_meg_REF2 = fullfile(pwd,[OPTIONS.rooot,'_megxfer_REF2.mat']);
fn_meg_REF2 = sprintf('%s_megREFxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
bem_xfer(R_eeg,R_meg_REF2,O_meg_REF2,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ...
Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_REF2,Param.Ntess_max,0,OPTIONS.BEM.checksurf);% Verbose = 0
if OPTIONS.Verbose, bst_message_window('MEG Reference Channel Gain Matrix is Completed.'), end
end
end
end
% Computation of TRANSFER MATRIX Completed ___________________________________________________
%%%% THIS PART SPECIFIES PARAMETERS USED TO GENERATE THE 3-D GRID %%%%%%%%%%
if OPTIONS.BEM.Interpolative%1%~exist(BEMGridFileName,'file')
if OPTIONS.Verbose, bst_message_window('Computing BEM Interpolative Grid. . .'), end
BEMGridFileName = [OPTIONS.rooot,'grid.mat'];
% update tessellated envelope with surfaces possibly modified by
% BEM_XFER (downsampling, alignment, embedding etc.)
Vertices = {nfv(:).vertices};
Faces = {nfv(:).faces};
gridmaker(Vertices,Faces,BEMGridFileName,OPTIONS.Verbose);
if OPTIONS.Verbose,
bst_message_window('Computing BEM Interpolative Grid -> DONE'),
% Visualization of surfaces + grid points
for k = 1:length(Vertices)
[hf,hs(k),hl] = view_surface('Head envelopes & a subset of BEM interpolative grid points',Faces{k},Vertices{k});
view(90,0)
delete(hl)
end
camlight
rotate3d on
set(hs(1),'FaceAlpha',.3,'edgealpha',.3,'edgecolor','none','facecolor','r')
set(hs(2),'FaceAlpha',.2,'edgealpha',.2,'edgecolor','none','facecolor','g')
set(hs(3),'FaceAlpha',.1,'edgealpha',.1,'edgecolor','none','facecolor','b')
hold on
load(BEMGridFileName)
hgrid = scatter3(Rq_bemgrid(1:10:end,1),Rq_bemgrid(1:10:end,2),Rq_bemgrid(1:10:end,3),'.','filled');
end
else
global GBEM_grid
% Grid points are the locations of the distributed sources
if isempty(OPTIONS.Cortex) % CBB (SB, 07-May-2004)| Should work also for volumic grid
errordlg('Please select a cortical grid for computation of BEM vector fields')
return
end
try
load(OPTIONS.Cortex.FileName); % Load tessellation supporting the source locations and orientations
catch
Users = get_user_directory;
load(fullfile(Users.SUBJECTS,OPTIONS.Cortex.FileName)); % Load tessellation supporting the source locations and orientations
end
BEMGridFileName.Loc = Vertices{OPTIONS.Cortex.iGrid}; clear Vertices
if OPTIONS.ApplyGridOrient % Take cortex normals into account
ptch = patch('Vertices',BEMGridFileName.Loc','Faces',Faces{OPTIONS.Cortex.iGrid},'Visible','off');
set(get(ptch,'Parent'),'Visible','off')
clear Faces
BEMGridFileName.Orient = get(ptch,'VertexNormals')';
delete(ptch);
[nrm,BEMGridFileName.Orient] = colnorm(BEMGridFileName.Orient);
% Now because some orientations may be ill-set to [0 0 0] with the get(*,'VertexNormals' command)
% set these orientation to arbitrary [1 1 1]:
izero = find(nrm == 0);clear nrm
if ~isempty(izero)
BEMGridFileName.Orient(:,izero) = repmat([1 1 1]'/norm([1 1 1]),1,length(izero));
end
clear izero
else
BEMGridFileName.Orient = [];
end
%if OPTIONS.Verbose, bst_message_window(sprintf('Loading BEM interpolative grid points from %s', BEMGridFileName)), end
end
% This part computes the gain matrices defined on precomputed grid------------------------------------------------------------
% Assign file names where to store the gain matrices
if MEG & ~EEG
bem_xfer_mfname = {fn_meg};
%BEMGaingridFname = [OPTIONS.rooot,'_meggain_grid.mat'];
BEMGaingridFname = sprintf('%s_MEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
test = exist(BEMGaingridFname,'file');
elseif EEG & ~ MEG
bem_xfer_mfname = {fn_eeg};
%BEMGaingridFname = [OPTIONS.rooot,'_eeggain_grid.mat'];
BEMGaingridFname = sprintf('%s_EEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
test = exist(BEMGaingridFname,'file');
elseif EEG & MEG
bem_xfer_mfname = {fn_meg,fn_eeg};
% BEMGaingridFname.MEG = [OPTIONS.rooot,'_meggain_grid.mat'];
% BEMGaingridFname.EEG = [OPTIONS.rooot,'_eeggain_grid.mat'];
BEMGaingridFname.MEG = sprintf('%s_MEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
BEMGaingridFname.EEG = sprintf('%s_EEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
test = exist(BEMGaingridFname.MEG,'file') & exist(BEMGaingridFname.EEG,'file');
end
if 1%OPTIONS.BEM.ForceXferComputation | ~test% Recompute gain matrices when transfer matrices have been recomputed just before
if OPTIONS.Verbose
if OPTIONS.BEM.Interpolative
bst_message_window('Computing the BEM gain matrix for interpolative grid. . .'),
else
bst_message_window('Computing the BEM gain matrix for source grid. . .'),
end
end
t0 = clock;
if OPTIONS.Verbose,
if MEG & EEG
bst_message_window('for MEG and EEG channels. . .')
elseif EEG
bst_message_window('for EEG channels. . .')
elseif MEG
bst_message_window('for MEG channels. . .')
end
end
if length(bem_xfer_mfname) == 1 % xor(MEG,EEG)
bem_gain(BEMGridFileName,bem_xfer_mfname{1},Param(1).ISA,BEMGaingridFname, OPTIONS.Verbose);
else
% MEG gaingrid matrix
bem_gain(BEMGridFileName,bem_xfer_mfname{1},Param(1).ISA,BEMGaingridFname.MEG, OPTIONS.Verbose);
% EEG gaingrid matrix
bem_gain(BEMGridFileName,bem_xfer_mfname{2},Param(1).ISA,BEMGaingridFname.EEG, OPTIONS.Verbose);
end
if OPTIONS.Verbose, bst_message_window('-> DONE'), end
if ~isempty(find(flaggrad)) % Compute forward model on the second set of magnetometers from the gradiometers array
bem_xfer_mfname = sprintf('%s_megxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
bem_gaingrid_mfname_2 = sprintf('%s_MEGGainGrid2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
if OPTIONS.Verbose, bst_message_window('MEG - completing gradiometers. . .'), end
bem_gain(BEMGridFileName,bem_xfer_mfname,Param(1).ISA,bem_gaingrid_mfname_2,OPTIONS.Verbose);
if OPTIONS.Verbose, bst_message_window('-> DONE'), end
if MEG & EEG
G1 = load(BEMGaingridFname.MEG);
else
G1 = load(BEMGaingridFname);
end
G2 = load(bem_gaingrid_mfname_2);
% Apply respective weights within the gradiodmeters
meg_chans = [OPTIONS.Channel(MEGndx(find(flaggrad))).Weight];
w1 = meg_chans(1:2:end);
w2 = meg_chans(2:2:end);
G1.GBEM_grid(find(flaggrad),:) = w1'*ones(1,size(G1.GBEM_grid,2)).*G1.GBEM_grid(find(flaggrad),:)...
+ w2' * ones(1,size(G1.GBEM_grid,2)).*G2.GBEM_grid(find(flaggrad),:);
clear G2
% is there special reference channel considerations?
if ~isempty(irefsens)
% Forward model on all reference sensors
bem_xfer_mfname_REF = sprintf('%s_megREFxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
bem_gaingrid_mfname_REF = sprintf('%s_MEGGainGrid_REF_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
if OPTIONS.Verbose, bst_message_window('MEG reference channels. . .'), end
bem_gain(BEMGridFileName,bem_xfer_mfname_REF,Param(1).ISA,bem_gaingrid_mfname_REF,OPTIONS.Verbose);
if OPTIONS.Verbose, bst_message_window('-> DONE'), end
if ~isempty(find(flaggrad_REF)) % Gradiometers are present in reference channels
bem_xfer_mfname_REF2 = sprintf('%s_megREFxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
bem_gaingrid_mfname_REF2 = sprintf('%s_MEGGainGrid2_REF_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test);
if OPTIONS.Verbose, bst_message_window('MEG reference channels / completing gradiometers. . .'), end
bem_gain(BEMGridFileName,bem_xfer_mfname_REF2,Param(1).ISA,bem_gaingrid_mfname_REF2,OPTIONS.Verbose);
if OPTIONS.Verbose, bst_message_window('-> DONE'), end
GR = load(bem_gaingrid_mfname_REF);
GR2 = load(bem_gaingrid_mfname_REF2);
meg_chans = [OPTIONS.Channel(irefsens(find(flaggrad_REF))).Weight];
w1 = meg_chans(1:2:end);
w2 = meg_chans(2:2:end);
GR.GBEM_grid(find(flaggrad_REF),:) = w1'*ones(1,size(GR.GBEM_grid,2)).*GR.GBEM_grid(find(flaggrad_REF),:)...
+ w2' * ones(1,size(GR.GBEM_grid,2)).*GR2.GBEM_grid(find(flaggrad_REF),:);
%GR.GBEM_grid(find(flaggrad_REF),:) = GR.GBEM_grid(find(flaggrad_REF),:) - GR2.GBEM_grid(find(flaggrad_REF),:);
clear GR2;
end
% Apply nth-order gradient correction on good channels only
%Weight by the current nth-order correction coefficients
%G1.GBEM_grid = G1.GBEM_grid - Channel(MEGndx(1)).Gcoef(find(ChannelFlag(irefsens)>0),:)*GR.GBEM_grid;
G1.GBEM_grid = G1.GBEM_grid - OPTIONS.Channel(MEGndx(1)).Comment*GR.GBEM_grid;
end
GBEM_grid = 1e-7*G1.GBEM_grid;
if MEG & EEG
save(BEMGaingridFname.MEG,'GBEM_grid','-append');
else
save(BEMGaingridFname,'GBEM_grid','-append');
end
end
% Detect EEG reference - if none is specified in the .Comment or Type fields,
% and if none was passed through OPTIONS.EEGRef
% -> Apply average-referencing of the potentials by default.
if EEG
% EEG Reference Channel
EEGREFndx = good_channel(OPTIONS.Channel,[],'EEG REF');
if MEG & EEG
load(BEMGaingridFname.EEG,'GBEM_grid')
else
load(BEMGaingridFname,'GBEM_grid')
end
if isempty(EEGREFndx)% AVERAGE REF
GBEM_grid = GBEM_grid - repmat(mean(GBEM_grid),size(GBEM_grid,1),1);
else
% GBEM_grid = GBEM_grid(setdiff(EEGndx,EEGREFndx)-EEGndx(1)+1,:) - repmat(GBEM_grid(EEGREFndx-EEGndx(1)+1,:),size(GBEM_grid(setdiff(EEGndx,EEGREFndx)-EEGndx(1)+1,:),1),1);
GBEM_grid = GBEM_grid(2:end,:) - repmat(GBEM_grid(1,:),length(EEGndx),1); % SB : EEG REF is stored as first sensor in GBEM_grid; see line 2226
end
if MEG
save(BEMGaingridFname.EEG,'GBEM_grid','-append')
else
save(BEMGaingridFname,'GBEM_grid','-append')
end
end
if MEG & EEG
meg = load(BEMGaingridFname.MEG,'GBEM_grid');
eeg = load(BEMGaingridFname.EEG,'GBEM_grid');
GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2));
GBEM_grid(MEGndx,:)= meg.GBEM_grid; clear meg
GBEM_grid(EEGndx,:)= eeg.GBEM_grid; clear eeg
elseif MEG
meg = load(BEMGaingridFname,'GBEM_grid');
GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2));
GBEM_grid(MEGndx,:)= meg.GBEM_grid; clear meg
elseif EEG
eeg = load(BEMGaingridFname,'GBEM_grid');
GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2));
EEGndx = OPTIONS.EEGndx;
GBEM_grid(EEGndx,:)= eeg.GBEM_grid; clear eeg
%clear GBEM_grid
% % Now save the combined MEG/EEG gaingrid matrix in a single file
% MEGEEG_BEMGaingridFname = strrep(BEMGaingridFname.EEG,'eeg','meg_eeg');
% Gmeg = load(BEMGaingridFname.MEG,'GBEM_grid');
% GBEM_grid = NaN * zeros(length(OPTIONS.Channel),size(Gmeg.GBEM_grid,2));
% GBEM_grid(MEGndx,:) = Gmeg.GBEM_grid; clear Gmeg
% eeg = load(BEMGaingridFname.EEG);
%
% save_fieldnames(eeg,MEGEEG_BEMGaingridFname);
%
% GBEM_grid(setdiff(EEGndx,EEGREFndx),:) = eeg.GBEM_grid; clear eeg
%
% save(MEGEEG_BEMGaingridFname,'GBEM_grid','-append')
%
% BEMGaingridFname = MEGEEG_BEMGaingridFname;
else
save(BEMGaingridFname,'GBEM_grid','-append')
end
telap_meg_interp = etime(clock,t0);
if OPTIONS.Verbose, bst_message_window(sprintf('Completed in %3.1f seconds', telap_meg_interp),...
'Computing the Gain Matrix for the Interpolative Grid Points -> DONE'), end
else
% if MEG & EEG
% if OPTIONS.Verbose, bst_message_window(sprintf('Loading 3D grid gain matrix from %s', BEMGaingridFname.EEG)),end
% else
% if OPTIONS.Verbose, bst_message_window(sprintf('Loading 3D grid gain matrix from %s', BEMGaingridFname)),end
% end
end
function g = gterm_constant(r,rq)
%gterm_constant
% function g = gterm_constant(r,rq)
%<autobegin> -------- 20-Nov-2002 14:06:02 ------------------------------
% ---- Automatically Generated Comments Block using auto_comments -----------
%
% Alphabetical list of external functions (non-Matlab):
% toolbox\rownorm.m
%<autoend> ---------- 20-Nov-2002 14:06:02 ------------------------------
if size(rq,1) == 1 % Just one dipole
r_rq= [r(:,1)-rq(1),r(:,2)-rq(2),r(:,3)-rq(3)];
n = rownorm(r_rq).^3;
g = r_rq./[n,n,n];
else
g = zeros(size(r,1),3*size(rq,1));
isrc = 1;
for k = 1:size(rq,1)
r_rq= [r(:,1)-rq(k,1),r(:,2)-rq(k,2),r(:,3)-rq(k,3)];
n = rownorm(r_rq).^3;
g(:,3*(isrc-1)+1: 3*isrc) = r_rq./[n,n,n];
isrc = isrc + 1;
end
end
|
github
|
spm/spm5-master
|
spm_bias_ui.m
|
.m
|
spm5-master/spm_bias_ui.m
| 5,571 |
utf_8
|
e83510dcfcaf0a173e4edc8fdcceef8e
|
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) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_bias_ui.m 184 2005-05-31 13:23:32Z john $
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: 184 $');
[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
|
spm/spm5-master
|
eeg_sph.m
|
.m
|
spm5-master/eeg_sph.m
| 20,284 |
utf_8
|
39633c72045d669d24460bbb0e2cee96
|
function G = eeg_sph(L,Channel,Param,Order,Verbose,varargin);
%EEG_SPH - Calculate the electric potential , spherical head, arbitrary orientation
% function G = eeg_sph(L,Channel,Param,Order,Verbose,varargin);
% function G = eeg_sph(L,Channel,Param,Order);
% L is 3 x nL, each column a source location
% Channel is the channel structure, same for Param
% Order is
% -1 current dipole
% 0 focal(magnetic) dipole % NOT SUPPORTED
% 1 1st order multipole % NOT SUPPORTED
% Param is
% .EEGType is one of {'EEG_SINGLE', 'EEG_BERG', 'EEG_3SHELL'};
% .Berg is set in Param(1) as
% .mu
% .lam
% .Radii vector of radii, inside to outside
% .Conductivity vector of sigmas inside to outside
% .Center the sphere center
%
% Verbose : toggle Verbose mode
%
% See also BERG
%<autobegin> ---------------------- 27-Jun-2005 10:44:15 -----------------------
% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------
%
% CATEGORY: Forward Modeling
%
% Alphabetical list of external functions (non-Matlab):
% toolbox\dlegpoly.m
% toolbox\dotprod.m
% toolbox\good_channel.m
% toolbox\rownorm.m
%
% Subfunctions in this file, in order of occurrence in file:
% G = gainp_sph6x(Rq,Re,R,sigma,nmax,method,mu_berg_in,lam_berg_in)
%
% At Check-in: $Author: Mosher $ $Revision: 24 $ $Date: 6/27/05 8:59a $
%
% This software is part of BrainStorm Toolbox Version 27-June-2005
%
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
% University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
% Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
% CNRS, Hopital de la Salpetriere, Paris, France
%
% See BrainStorm website at http://neuroimage.usc.edu for further information.
%
% Copyright (c) 2005 BrainStorm by the University of Southern California
% This software distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 27-Jun-2005 10:44:15 -----------------------
% /---Script Authors--------------------------------------\
% | |
% | *** John Ermer, Ph.D. |
% | Signal % Image Processing Institute |
% | University of Southern California |
% | Los Angeles, CA, USA |
% | |
% | *** John C. Mosher, Ph.D. |
% | Biophysics Group |
% | |
% | *** Sylvain Baillet Ph.D. |
% | Cognitive Neuroscience & Brain Imaging Laboratory |
% | CNRS UPR640 - LENA |
% | Hopital de la Salpetriere, Paris, France |
% | [email protected] |
% | |
% \-------------------------------------------------------/
%
% Date of creation: October, 25 1999
%
% Script History -----------------------------------------------------------------------------------------------------------
% SB 19-Nov-2002 : Edited Header
% Updated management of EEG reference
% JCM 20-Nov-2002 : Fixed headers to have only one autocomments block
% SB 09-Mar-2004 : Added verbose mode
% --------------------------------------------------------------------------------------------------------------------------
if nargin < 5
Verbose = 1; % Default
end
%-----------------------------
nmax = 80;
%-----------------------------
% EEG Channels
EEGndx = good_channel(Channel,[],'EEG');
% Reference Channel
REFndx = good_channel(Channel,[],'EEG REF');
% EEG Channel locations
% Add EEG reference at the end of Channel and Param structures
Re = [Channel(EEGndx).Loc,Channel(REFndx).Loc]'; % Electrode location array
if length(Param) ~= length([EEGndx,REFndx])
Param(REFndx) = Param(EEGndx(1));
end
Param = Param([EEGndx,REFndx]);
Rq = L';
center = [Param.Center]';
Re = Re - center;
Rq = Rq - repmat(center(1,:),size(Rq,1),1); % Back to origin [0 0 0] for the sensors and the sources
clear tmp
switch(Param(1).EEGType)
case 'EEG_SINGLE'
R = Param(1).Radii(end);
sigma = Param(1).Conductivity(end);
otherwise
R = Param(1).Radii;
sigma = Param(1).Conductivity;
end
switch(Param(1).EEGType)
case 'EEG_BERG'
method = 2;
mu_berg_in = Param(1).Berg.mu;
lam_berg_in = Param(1).Berg.lam;
case 'EEG_3SHELL'
method = 1;
mu_berg_in = [];
lam_berg_in = [];
otherwise
method = 1;
mu_berg_in = [];
lam_berg_in = [];
end
if 1 % Projection of the EEG sensors on the sphere
[theta phi Re_sph] = cart2sph(Re(:,1),Re(:,2),Re(:,3));
Re_sph = R(end)*ones(size(Re_sph));
[Re(:,1) Re(:,2) Re(:,3)] = sph2cart(theta,phi,Re_sph);
end
Gtmp = gainp_sph6x(Rq,Re,R,sigma,nmax,method,mu_berg_in',lam_berg_in');
if isempty(REFndx) % Average Reference
G = NaN * zeros(length(EEGndx),size(Gtmp,2));
%G(EEGndx,:) = Gtmp - repmat(mean(Gtmp),size(Gtmp,1),1);
G = Gtmp - repmat(mean(Gtmp),size(Gtmp,1),1);
clear Gtmp
else % Specific electrode as reference
% Remove its lead field from all others
% Note: reference leadfield is at the end of original G matrix (from gain_sph)
G = NaN * zeros(length(EEGndx),size(Gtmp,2));
%G(EEGndx,:) = Gtmp(1:end-1,:) - repmat(Gtmp(end,:),size(Gtmp,1)-1,1);
%G = G(EEGndx,:);
G = Gtmp(1:end-1,:) - repmat(Gtmp(end,:),size(Gtmp,1)-1,1);
% % Reference lead field is zero
% G(REFndx,:) = zeros(1,size(G,2));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Subfunctions -------------------------------------------------------------------------------
%
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function G = gainp_sph6x(Rq,Re,R,sigma,nmax,method,mu_berg_in,lam_berg_in)
%GAINP_SPH6X EEG Multilayer Spherical Forward Model
% function G = gainp_sph6x(Rq,Re,R,sigma,nmax,method,mu_berg_in,lam_berg_in)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EEG MULTILAYER SPHERICAL FORWARD MODEL (gainp_sph6x.m)
%
% This function computes the voltage potential forward gain matrix for an array of
% EEG electrodes on the outermost layer of a single/multilayer conductive sphere.
% Each region of the multilayer sphere is assumed to be concentric with
% isontropic conductivity. EEG sensors are assumed to be located on the surface
% of the outermost sphere.
%
% Calculation of the electric potiential is performed using either (user-specified)
% of the following methods (Ref: Z. Zhang "A fast method to compute surface
% potentials generated by dipoles within multilayer anisotropic spheres"
% (Phys. Med. Biol. 40, pp335-349,1995)
%
% 1) Closed Form Solution (Single Shell Case Only). See formulas (1H,1H')
%
% 2) Series Expansion using Legendre Polynomials. See formulas (1I,2I,3I and 4I)
%
% 3) Series Approximiation of a Multilayer Sphere as three dipoles in a
% single shell using "Berg/Sherg" parameter approximation.
% See formulas (1i',5i" and 6i)
%
% Dipole generator(s) are assumed to be interior to the innermost "core" layer. For those
% dipoles external to the sphere, the dipole "image" is computed and used determine the
% gain function. The exception to this is the Legendre Method where all dipoles MUST be
% interior to the innermost "core" layer.
%
% INPUTS (Required):
% Rq : dipole location(in meters) P x 3
% Re : EEG sensors(in meters) on the scalp M x 3
% R : radii(in meters) of sphere from
% INNERMOST to OUTERMOST NL x 1
% sigma: conductivity from INNERMOST to OUTERMOST NL x 1
%
% INPUTS (Optional):
% nmax : # of terms used in Truncated Legendre Series scalar
% If not specified, a default value based on outermost
% dipole magnitude is computed. (Note: This parameter
% is ignored when Berg Approximation is commanded)
% method : Method used for computing forward potential
% 1=Legendre Series Approx; 2=Berg Parameter Approx
% (Note: Default and all other values invoke Legendre
% Series Approx. Exception is single-shell case where
% closed form solution is always used) scalar
% mu_berg_in: User specified initial value for Berg eccentricity
% factors (Required if Berg Method is commanded) 3 x 1
% lam_berg_in: User specified initial value for Berg magnitude
% factors (Required if Berg Method is commanded) 3 x 1
%
% WHERE: M=# of sensors; P=# of dipoles; NL = # of sphere layers
%
% OUTPUTS:
% G : EEG forward model gain matrix M x (3*P)
%
% External Functions and Files:
% dlegpoly.m; rownorm.m; dotprod.m: USC/LANL MEG/EEG Toolbox
% zhang_fit.m: External Function used to fit Berg Parameters (Zhang Eq# 5i")
%
% - John Ermer 6/3/99
% - 8/9/99: Modified to use EM image for dipoles external to brain
% (Applies to single-shell and Berg Methods only) (John Ermer)
% - 10/31/99: Optimized Processing Associated with Dipoles falling outside sphere
% (Applies to single-shell and Berg Methods only) (John Ermer)
% - 01/26/00: Corrected minor dimension error which caused program to fault when
% external dipoles and multiple sensors were present. (John Ermer)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% THIS PART CHECKS INPUT PARAMETERS FOR THEIR DIMENSION AND VALIDITY %%%
%
NL = length(R); % # of concentric sphere layers
P = size(Rq,1);
M = size(Re,1);
%
if R(1)~= min(R)
error('Head radii must be specified from innermost to outmost layer!!! ')
end
%
if size(Rq,2) ~= 3
error('Dipole location must have three columns!!!')
end
%
if nargin < 6, % Check # of input terms to see if method is specified
method = 1; % Default Method = Legendre Series Expansion
else
if (method>2)|(method<0)
method = 0; % Default Method = Legendre Series Expansion
end
end
%
%%% This part pre-initializes parameters used in future calculations %%%
%
G = zeros(M,3*P); % Pre-Allocate Gain Matrix
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% This part computes the potential for a dipole contained within a single-layer
%%% homogeneous sphere using closed form formula
%%% The EEG single-shell solution uses the vector form (which avoids computationally
%%% expensive intrinsic functions) described by Mosher et al ("EEG and MEG: Forward
%%% Solutions for inverse problems" IEEE BME Trans March 1999)
%
if NL == 1 % Single Shell Case (Closed Form Solution)
%
Re_mag = repmat(R(NL),P,M); %(PxM)
Re_mag_sq = repmat(R(NL)*R(NL),P,M); %(PxM)
Rq_mag = rownorm(Rq); %(Px1)
%
Rq1 = Rq; %(Px1)
Rq1_mag = Rq_mag; %(Px1)
Rq1_mag_sq = Rq_mag.*Rq_mag; %(Px1)
Re_dot_Rq1 = Rq1*Re'; %(PxM)
%
const = 4.0*pi*sigma(NL);
term = 1./(const*Rq1_mag_sq); %(Px1)
%
%%% This part checks for the presence of Berg dipoles which are external to
%%% the sphere. For those dipoles external to the sphere, the dipole parameters
%%% are replaced with the electrical image (internal to sphere) of the dipole
%
nx = find(Rq1_mag > R(NL));
%
if nx>0
Rq1_temp = Rq1(nx,:);
Rq1(nx,:) = R(NL)*R(NL)*Rq1_temp./repmat((rownorm(Rq1_temp).*rownorm(Rq1_temp)),1,3);
Rq1_mag(nx,1) = rownorm(Rq1(nx,:));
Rq1_mag_sq(nx,1) = Rq1_mag(nx,1).*Rq1_mag(nx,1);
Re_dot_Rq1(nx,:) = R(NL)*R(NL)*Re_dot_Rq1(nx,:)./repmat((rownorm(Rq1_temp).*rownorm(Rq1_temp)),1,M);
term(nx,:) = (R(NL)./rownorm(Rq1_temp)).*term(nx,:);
% was : term(nx,:) = (R(NL)/rownorm(Rq1_temp))'.*term(nx,:);
end
%
%%% Calculation of Forward Gain Matrix Contribution due to K-th Berg Dipole
%
Rq1_mag = repmat(Rq1_mag,1,M); %(PxM)
Rq1_mag_sq = repmat(Rq1_mag_sq,1,M); %(PxM)
term = repmat(term,1,M); %(PxM)
%
d_mag = reshape( rownorm(reshape(repmat(Re,1,P)',3,P*M)' ...
-repmat(Rq1,M,1)) ,P,M); %(PxM)
d_mag_cub = d_mag.*d_mag.*d_mag; %(PxM)
F_scalar = d_mag.*(Re_mag.*d_mag+Re_mag_sq-Re_dot_Rq1); %(PxM)
c1 = term.*(2*( (Re_dot_Rq1-Rq1_mag_sq)./d_mag_cub) ...
+ 1./d_mag - 1./Re_mag); %(PxM)
c2 = term.*((2./d_mag_cub) + (d_mag+Re_mag)./(Re_mag.*F_scalar));
%
G = G + reshape(repmat((c1 - c2.*Re_dot_Rq1)',3,1),M,3*P) ...
.*repmat(reshape(Rq1',1,3*P),M,1) ...
+ reshape(repmat((c2.*Rq1_mag_sq)',3,1),M,3*P) ...
.*repmat(Re,1,P);
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%%% This part computes the potential for a dipole contained within a multi-layer
%%% isontropic sphere using Legendre Polynomial Expansion (Zhang Eqs 1H, 1H')
%%% (Code based on gainp_sph.m by CCH, Aug/20/1995)
%
elseif (NL>1)&(method==1) % Multi-shell Case Using Legendre Expansion
%
Rq_mag = rownorm(Rq);
%
if ~all( Rq_mag < R(1)+eps ) % check if dipoles within the brain
warndlg('Legendre method assumes all dipoles(s) inside brain layer - please modify dipole locations OR use the "Berg" approach')
return
end
%
% compute weights fn. fn depends only on the radii and cdv
Rq_mag = rownorm(Rq);
Re_mag = R(NL); % Radius of outermost layer (Sensor distance from origin
%
%
if nargin < 5, % check # of inputs to see if nmax was specified
nmax = fix(10/(1-max(Rq_mag)/Re_mag)); % Default for # Legendre Series Terms
end
%
Ren = Re/Re_mag;
Rqn = Rq./[Rq_mag,Rq_mag,Rq_mag];
for k = 1:NL-1
s(k) = sigma(k)/sigma(k+1);
end
a = Re_mag./R;
ainv = R/Re_mag;
sm1 = s-1;
twonp1 = 2*[1:nmax]+1;
twonp1 = twonp1(:);
f = zeros(nmax,1);
%
for n = 1:nmax
np1 = n+1;
Mc = eye(2);
for k = 2:NL-1,
Mc = Mc*[n+np1*s(k), np1*sm1(k)*a(k)^twonp1(n);...
n*sm1(k)*ainv(k)^twonp1(n) , np1+n*s(k)];
end;
Mc(2,:) = [n*sm1(1)*ainv(1)^twonp1(n) , np1+n*s(1)]*Mc;
Mc = Mc/(twonp1(n))^(NL-1);
f(n) = n/(n*Mc(2,2)+np1*Mc(2,1));
end;
%
onevec = ones(M,1);
wtemp = ((twonp1./[1:nmax]').*f)/(4*pi*sigma(NL)*R(NL)^2);
n = [1:nmax]';
nm1 = n-1;
for i = 1:P, % loop over all dipoles
rqn = [Rqn(i,1)*onevec,Rqn(i,2)*onevec,Rqn(i,3)*onevec];
cosgamma = dotprod(rqn,Ren);
rqn = rqn(1,:);
[Pl,dP] = dlegpoly(nmax,cosgamma); % evaluate legendre poly and its derivative
ratio = (Rq_mag(i)/Re_mag).^nm1;
z = Ren- cosgamma*rqn;
w = wtemp.*ratio;
Gterm1 = Pl'*(w.*n);
Gterm2 = dP'*w;
G(:,3*i-2:3*i) = Gterm1*rqn + [z(:,1).*Gterm2,z(:,2).*Gterm2,z(:,3).*Gterm2];
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%----------------------------------------------------------------------------------%%
%%% This part computes the potential for a dipole contained within a multi-layer
%%% isontropic sphere using Berg Parameter Approximation (Zhang Eqs 1i',5i" and 6i)
%%% The EEG single-shell solution uses the vector form (which avoids computationally
%%% expensive intrinsic functions) described by Mosher et al ("EEG and MEG: Forward
%%% Solutions for inverse problems" IEEE BME Trans March 1999)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
elseif (NL>1)&(method==2)
%
if (~exist('mu_berg_in')|~exist('lam_berg_in'))
error('Berg Parameters have not been specified!!!')
elseif size(mu_berg_in)~=size(lam_berg_in)
error('Berg Parameters are of Unequal Lengths!!!')
else
J = length(mu_berg_in);
mu_berg = mu_berg_in;
lam_berg = lam_berg_in;
end
%
Re_mag = repmat(R(NL),P,M); %(PxM)
Re_mag_sq = repmat(R(NL)*R(NL),P,M); %(PxM)
Rq_mag = rownorm(Rq); %(Px1)
Rq_mag_sq = Rq_mag.*Rq_mag; %(Px1)
Re_dot_Rq = Rq*Re'; %(PxM)
%
for k=1:J
%
Rq1 = mu_berg(k)*Rq; %(Px3)
Rq1_mag = mu_berg(k)*Rq_mag; %(Px1)
Rq1_mag_sq = (mu_berg(k)*mu_berg(k))*Rq_mag_sq; %(Px1)
Re_dot_Rq1 = mu_berg(k)*Re_dot_Rq; %(PxM)
%
const = 4.0*pi*sigma(NL);
const1 = const/lam_berg(k);
term = 1./(const1*Rq1_mag_sq); %(PxM)
%
%%% This part checks for the presence of Berg dipoles which are external to
%%% the sphere. For those dipoles external to the sphere, the dipole parameters
%%% are replaced with the electrical image (internal to sphere) of the dipole
%
nx = find(Rq1_mag > R(NL));
%
if nx>0
Rq1_temp = Rq1(nx,:);
Rq1(nx,:) = R(NL)*R(NL)*Rq1_temp./repmat((rownorm(Rq1_temp).*rownorm(Rq1_temp)),1,3);
Rq1_mag(nx,1) = rownorm(Rq1(nx,:));
Rq1_mag_sq(nx,1) = Rq1_mag(nx,1).*Rq1_mag(nx,1);
Re_dot_Rq1(nx,:) = R(NL)*R(NL)*Re_dot_Rq1(nx,:)./repmat((rownorm(Rq1_temp).*rownorm(Rq1_temp)),1,M);
term(nx,:) = (R(NL)/rownorm(Rq1_temp))'.*term(nx,:);
end
%
%%% Calculation of Forward Gain Matrix Contribution due to K-th Berg Dipole
%
Rq1_mag = repmat(Rq1_mag,1,M); %(PxM)
Rq1_mag_sq = repmat(Rq1_mag_sq,1,M); %(PxM)
term = repmat(term,1,M); %(PxM)
%
d_mag = reshape( rownorm(reshape(repmat(Re,1,P)',3,P*M)' ...
-repmat(Rq1,M,1)) ,P,M); %(PxM)
d_mag_cub = d_mag.*d_mag.*d_mag; %(PxM)
%
F_scalar = d_mag.*(Re_mag.*d_mag+Re_mag_sq-Re_dot_Rq1); %(PxM)
%
c1 = term.*(2*( (Re_dot_Rq1-Rq1_mag_sq)./d_mag_cub) ...
+ 1./d_mag - 1./Re_mag); %(PxM)
c2 = term.*((2./d_mag_cub) + (d_mag+Re_mag)./(Re_mag.*F_scalar));
%
G = G + reshape(repmat((c1 - c2.*Re_dot_Rq1)',3,1),M,3*P) ...
.*repmat(reshape(Rq1',1,3*P),M,1) ...
+ reshape(repmat((c2.*Rq1_mag_sq)',3,1),M,3*P) ...
.*repmat(Re,1,P);
end
%
%---------------------------------------------------------------------------------------
%
end % End of Check for Forward Model Calculation Method
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
spm/spm5-master
|
spm_config_realign.m
|
.m
|
spm5-master/spm_config_realign.m
| 18,757 |
utf_8
|
4dc0590fa5df15dcda89cfc0de14114e
|
function opts = spm_config_realign
% Configuration file for realign jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_realign.m 751 2007-02-28 10:56:59Z volkmar $
%_______________________________________________________________________
quality.type = 'entry';
quality.name = 'Quality';
quality.tag = 'quality';
quality.strtype = 'r';
quality.num = [1 1];
quality.def = 'realign.estimate.quality';
quality.extras = [0 1];
quality.help = {[...
'Quality versus speed trade-off. Highest quality (1) gives most ',...
'precise results, whereas lower qualities gives faster realignment. ',...
'The idea is that some voxels contribute little to the estimation of ',...
'the realignment parameters. This parameter is involved in selecting ',...
'the number of voxels that are used.']};
%------------------------------------------------------------------------
weight.type = 'files';
weight.name = 'Weighting';
weight.tag = 'weight';
weight.filter = 'image';
weight.num = [0 1];
weight.val = {{}};
weight.help = {[...
'The option of providing a weighting image to weight each voxel ',...
'of the reference image differently when estimating the realignment ',...
'parameters. The weights are proportional to the inverses of the ',...
'standard deviations. ',...
'For example, when there is a lot of extra-brain motion - e.g., during ',...
'speech, or when there are serious artifacts in a particular region of ',...
'the images.']};
%------------------------------------------------------------------------
interp.type = 'menu';
interp.name = 'Interpolation';
interp.tag = 'interp';
interp.labels = {'Trilinear (1st Degree)','2nd Degree B-Spline',...
'3rd Degree B-Spline ','4th Degree B-Spline','5th Degree B-Spline',...
'6th Degree B-Spline','7th Degree B-Spline'};
interp.values = {1,2,3,4,5,6,7};
interp.def = 'realign.estimate.interp';
interp.help = {...
['The method by which the images are sampled when estimating the optimum transformation. ',...
'Higher degree interpolation methods provide the better interpolation, but they are slower ',...
'because they use more neighbouring voxels /* \cite{thevenaz00a,unser93a,unser93b}*/. ']};
%------------------------------------------------------------------------
wrap.type = 'menu';
wrap.name = 'Wrapping';
wrap.tag = 'wrap';
wrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z',...
'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'};
wrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]};
wrap.def = 'realign.estimate.wrap';
wrap.help = {...
['This indicates which directions in the volumes the values should wrap around in. ',...
'For example, in MRI scans, the images wrap around in the phase encode direction, ',...
'so (e.g.) the subject''s nose may poke into the back of the subject''s head. ',...
'These are typically:'],...
[' No wrapping - for PET or images that have already ',...
' been spatially transformed. Also the recommended option if ',...
' you are not really sure.'],...
[' Wrap in Y - for (un-resliced) MRI where phase encoding ',...
' is in the Y direction (voxel space).']};
%------------------------------------------------------------------------
fwhm.type = 'entry';
fwhm.name = 'Smoothing (FWHM)';
fwhm.tag = 'fwhm';
fwhm.num = [1 1];
fwhm.def = 'realign.estimate.fwhm';
fwhm.strtype = 'e';
p1 = [...
'The FWHM of the Gaussian smoothing kernel (mm) applied to the ',...
'images before estimating the realignment parameters.'];
p2 = ' * PET images typically use a 7 mm kernel.';
p3 = ' * MRI images typically use a 5 mm kernel.';
fwhm.help = {p1,'',p2,'',p3};
%------------------------------------------------------------------------
sep.type = 'entry';
sep.name = 'Separation';
sep.tag = 'sep';
sep.num = [1 1];
sep.strtype = 'e';
sep.def = 'realign.estimate.sep';
%sep.val = {4};
sep.help = {[...
'The separation (in mm) between the points sampled in the ',...
'reference image. Smaller sampling distances gives more accurate ',...
'results, but will be slower.']};
%------------------------------------------------------------------------
rtm.type = 'menu';
rtm.name = 'Num Passes';
rtm.tag = 'rtm';
rtm.labels = {'Register to first','Register to mean'};
rtm.values = {0,1};
rtm.def = 'realign.estimate.rtm';
p1 = [...
'Register to first: Images are registered to the first image in the series. ',...
'Register to mean: A two pass procedure is used in order to register the ',...
'images to the mean of the images after the first realignment.'];
p2 = [...
'PET images are typically registered to the mean. This is because PET data are ',...
'more noisy than fMRI and there are fewer of them, so time is less of an issue.'];
p3 = [...
'MRI images are typically registered to the first image. The more accurate way ',...
'would be to use a two pass procedure, but this probably wouldn''t improve the results ',...
'so much and would take twice as long to run.'];
rtm.help = {p1,'',p2,'',p3};
%------------------------------------------------------------------------
% global defaults
% if ~isempty(defaults) && isfield(defaults,'modality') ...
% && strcmp(lower(defaults.modality),'pet'),
% fwhm.val = {7};
% rtm.val = {1};
% else
% fwhm.val = {5};
% rtm.val = {0};
% end;
eoptions.type = 'branch';
eoptions.name = 'Estimation Options';
eoptions.tag = 'eoptions';
eoptions.val = {quality,sep,fwhm,rtm,interp,wrap,weight};
eoptions.help = {[...
'Various registration options. ',...
'If in doubt, simply keep the default values.']};
%------------------------------------------------------------------------
which.type = 'menu';
which.name = 'Resliced images';
which.tag = 'which';
which.labels = {' All Images (1..n)','Images 2..n',...
' All Images + Mean Image',' Mean Image Only'};
which.values = {[2 0],[1 0],[2 1],[0 1]};
which.val = {[2 1]};
which.help = {...
['All Images (1..n) : ',...
' This reslices all the images - including the first image selected ',...
' - which will remain in its original position.'],...
'',...
['Images 2..n : ',...
' Reslices images 2..n only. Useful for if you wish to reslice ',...
' (for example) a PET image to fit a structural MRI, without ',...
' creating a second identical MRI volume.'],...
'',...
['All Images + Mean Image : ',...
' In addition to reslicing the images, it also creates a mean of the ',...
' resliced image.'],...
'',...
['Mean Image Only : ',...
' Creates the mean resliced image only.']};
%------------------------------------------------------------------------
interp.type = 'menu';
interp.name = 'Interpolation';
interp.tag = 'interp';
interp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-Spline',...
'3rd Degree B-Spline','4th Degree B-Spline','5th Degree B-Spline',...
'6th Degree B-Spline','7th Degree B-Spline','Fourier Interpolation'};
interp.values = {0,1,2,3,4,5,6,7,Inf};
interp.def = 'realign.write.interp';
interp.help = {...
['The method by which the images are sampled when being written in a ',...
'different space.',...
'Nearest Neighbour is fastest, but not recommended for image realignment. ',...
'Bilinear Interpolation is probably OK for PET, but not so suitable for fMRI because ',...
'higher degree interpolation generally gives better results/* \cite{thevenaz00a,unser93a,unser93b}*/. ',...
'Although higher degree methods provide better interpolation, but they are slower ',...
'because they use more neighbouring voxels. ',...
'Fourier Interpolation/* \cite{eddy96,cox99}*/ is another option, but note that it ',...
'is only implemented for purely rigid body transformations. Voxel sizes must all be ',...
'identical and isotropic.']};
%------------------------------------------------------------------------
wrap.type = 'menu';
wrap.name = 'Wrapping';
wrap.tag = 'wrap';
wrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z',...
'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'};
wrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]};
wrap.def = 'realign.write.wrap';
wrap.help = {...
['This indicates which directions in the volumes the values should wrap around in. ',...
'For example, in MRI scans, the images wrap around in the phase encode direction, ',...
'so (e.g.) the subject''s nose may poke into the back of the subject''s head. ',...
'These are typically:'],...
[' No wrapping - for PET or images that have already ',...
' been spatially transformed.'],...
[' Wrap in Y - for (un-resliced) MRI where phase encoding ',...
' is in the Y direction (voxel space).']};
%------------------------------------------------------------------------
mask.type = 'menu';
mask.name = 'Masking';
mask.tag = 'mask';
mask.labels = {'Mask images','Dont mask images'};
mask.values = {1,0};
mask.def = 'realign.write.mask';
mask.help = {[...
'Because of subject motion, different images are likely to have different ',...
'patterns of zeros from where it was not possible to sample data. ',...
'With masking enabled, the program searches through the whole time series ',...
'looking for voxels which need to be sampled from outside the original ',...
'images. Where this occurs, that voxel is set to zero for the whole set ',...
'of images (unless the image format can represent NaN, in which case ',...
'NaNs are used where possible).']};
%------------------------------------------------------------------------
roptions.type = 'branch';
roptions.name = 'Reslice Options';
roptions.tag = 'roptions';
roptions.val = {which,interp,wrap,mask};
roptions.help = {'Various reslicing options. If in doubt, simply keep the default values.'};
%------------------------------------------------------------------------
scans.type = 'files';
scans.name = 'Session';
scans.tag = 'data';
scans.num = [1 Inf];
scans.filter = 'image';
scans.help = {[...
'Select scans for this session. ',...
'In the coregistration step, the sessions are first realigned to ',...
'each other, by aligning the first scan from each session to the ',...
'first scan of the first session. Then the images within each session ',...
'are aligned to the first image of the session. ',...
'The parameter estimation is performed this way because it is assumed ',...
'(rightly or not) that there may be systematic differences ',...
'in the images between sessions.']};
%------------------------------------------------------------------------
data.type = 'repeat';
data.name = 'Data';
% data.tag = 'data';
data.values = {scans};
data.num = [1 Inf];
data.help = {[...
'Add new sessions for this subject. ',...
'In the coregistration step, the sessions are first realigned to ',...
'each other, by aligning the first scan from each session to the ',...
'first scan of the first session. Then the images within each session ',...
'are aligned to the first image of the session. ',...
'The parameter estimation is performed this way because it is assumed ',...
'(rightly or not) that there may be systematic differences ',...
'in the images between sessions.']};
%------------------------------------------------------------------------
est.type = 'branch';
est.name = 'Realign: Estimate';
est.tag = 'estimate';
est.val = {data,eoptions};
est.prog = @estimate;
est.vfiles = @vfiles_estimate;
p1 = [...
'This routine realigns a time-series of images acquired from the same ',...
'subject using a least squares approach and a 6 parameter (rigid body) ',...
'spatial transformation/* \cite{friston95a}*/. The first image in the list specified by the ',...
'user is used as a reference to which all subsequent scans are realigned. ',...
'The reference scan does not have to the the first chronologically and ',...
'it may be wise to chose a "representative scan" in this role.'];
p2 = [...
'The aim is primarily to remove movement artefact in fMRI and PET ',...
'time-series (or more generally longitudinal studies). ',...
'The headers are modified for each of the input images, such that. ',...
'they reflect the relative orientations of the data. ',...
'The details of the transformation are displayed in the results window ',...
'as plots of translation and rotation. ',...
'A set of realignment parameters are saved for each session, named ',...
'rp_*.txt. These can be modelled as confounds within the general linear model/* \cite{friston95a}*/.'];
est.help = {p1,'',p2};
%------------------------------------------------------------------------
scans.type = 'files';
scans.name = 'Images';
scans.tag = 'data';
scans.num = [1 Inf];
scans.filter = 'image';
scans.help = {'Select scans to reslice to match the first.'};
%------------------------------------------------------------------------
write.type = 'branch';
write.name = 'Realign: Reslice';
write.tag = 'write';
write.val = {scans,roptions};
write.help = {[...
'This function reslices a series of registered images such that they ',...
'match the first image selected voxel-for-voxel. The resliced images ',...
'are named the same as the originals, except that they are prefixed ',...
'by ''r''.']};
write.prog = @reslice;
write.vfiles = @vfiles_reslice;
%------------------------------------------------------------------------
estwrit.type = 'branch';
estwrit.name = 'Realign: Estimate & Reslice';
estwrit.tag = 'estwrite';
estwrit.val = {data,eoptions,roptions};
p1 = [...
'This routine realigns a time-series of images acquired from the same ',...
'subject using a least squares approach and a 6 parameter (rigid body)',...
'spatial transformation/* \cite{friston95a}*/. The first image in the list specified by the ',...
'user is used as a reference to which all subsequent scans are realigned. ',...
'The reference scan does not have to the the first chronologically and ',...
'it may be wise to chose a "representative scan" in this role.'];
p2 = [...
'The aim is primarily to remove movement artefact in fMRI and PET ',...
'time-series (or more generally longitudinal studies) /* \cite{ashburner97bir}*/. ',...
'The headers are modified for each of the input images, such that. ',...
'they reflect the relative orientations of the data. ',...
'The details of the transformation are displayed in the results window ',...
'as plots of translation and rotation. ',...
'A set of realignment parameters are saved for each session, named ',...
'rp_*.txt. After realignment, the images are resliced ',...
'such that they match the first image selected voxel-for-voxel. ',...
'The resliced images are named the same as the originals, except that ',...
'they are prefixed by ''r''.'];
estwrit.help = {p1,'',p2};
estwrit.prog = @estwrite_fun;
estwrit.vfiles = @vfiles_estwrit;
%------------------------------------------------------------------------
opts.type = 'repeat';
opts.name = 'Realign';
opts.tag = 'realign';
opts.values = {est,write,estwrit};
opts.num = [1 Inf];
opts.modality = {'PET','FMRI','VBM'};
opts.help = {...
'Within-subject registration of image time series.'};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function estimate(varargin)
job = varargin{1};
P = {};
for i=1:length(job.data),
P{i} = strvcat(job.data{i});
end;
flags.quality = job.eoptions.quality;
flags.fwhm = job.eoptions.fwhm;
flags.sep = job.eoptions.sep;
flags.rtm = job.eoptions.rtm;
flags.PW = strvcat(job.eoptions.weight);
flags.interp = job.eoptions.interp;
flags.wrap = job.eoptions.wrap;
spm_realign(P,flags);
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function reslice(varargin)
job = varargin{1};
P = strvcat(job.data);
flags.mask = job.roptions.mask;
flags.mean = job.roptions.which(2);
flags.interp = job.roptions.interp;
flags.which = job.roptions.which(1);
flags.wrap = job.roptions.wrap;
spm_reslice(P,flags);
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function estwrite_fun(varargin)
job = varargin{1};
P = {};
for i=1:length(job.data),
P{i} = strvcat(job.data{i});
end;
flags.quality = job.eoptions.quality;
flags.fwhm = job.eoptions.fwhm;
flags.sep = job.eoptions.sep;
flags.rtm = job.eoptions.rtm;
flags.PW = strvcat(job.eoptions.weight);
flags.interp = job.eoptions.interp;
flags.wrap = job.eoptions.wrap;
spm_realign(P,flags);
P = strvcat(P);
flags.mask = job.roptions.mask;
flags.mean = job.roptions.which(2);
flags.interp = job.roptions.interp;
flags.which = job.roptions.which(1);
flags.wrap = job.roptions.wrap;
spm_reslice(P,flags);
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles_reslice(job)
P = job.data;
if numel(P)>0 && iscell(P{1}),
P = cat(1,P{:});
end;
switch job.roptions.which(1),
case 0,
vf = {};
case 1,
vf = cell(numel(P)-1,1);
for i=1:length(vf),
[pth,nam,ext,num] = spm_fileparts(P{i+1});
vf{i} = fullfile(pth,['r', nam, ext, num]);
end;
otherwise,
vf = cell(numel(P),1);
for i=1:length(vf),
[pth,nam,ext,num] = spm_fileparts(P{i});
vf{i} = fullfile(pth,['r', nam, ext, num]);
end;
end;
if job.roptions.which(2),
[pth,nam,ext,num] = spm_fileparts(P{1});
vf = {vf{:}, fullfile(pth,['mean', nam, ext, num])};
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles_estimate(job)
P = job.data;
vf = {};
if numel(P) > 0
if ~iscell(P{1})
P = {P};
end;
for k = 1:numel(P)
[pth,nam,ext,num] = spm_fileparts(P{k}{1});
vf{k} = fullfile(pth, sprintf('rp_%s.txt', nam));
end;
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles_estwrit(job)
vf1 = vfiles_estimate(job);
vf2 = vfiles_reslice(job);
vf = {vf1{:}, vf2{:}};
|
github
|
spm/spm5-master
|
spm_eeg_inv_imag_api.m
|
.m
|
spm5-master/spm_eeg_inv_imag_api.m
| 15,750 |
utf_8
|
8085f6df4d7d941d816f7d6411ecbbdc
|
function varargout = spm_eeg_inv_imag_api(varargin)
% SPM_EEG_INV_IMAG_API M-file for spm_eeg_inv_imag_api.fig
% FIG = SPM_EEG_INV_IMAG_API launch spm_eeg_inv_imag_api GUI.
% SPM_EEG_INV_IMAG_API('callback_name', ...) invoke the named callback.
% Last Modified by GUIDE v2.5 09-Jan-2008 16:12:40
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Jeremie Mattout
% $Id: spm_eeg_inv_imag_api.m 1079 2008-01-11 11:05:48Z guillaume $
spm_defaults
spm('Clear')
% Launch API
%==========================================================================
if nargin < 2
% open figure
%----------------------------------------------------------------------
fig = openfig(mfilename,'reuse');
WS = spm('WinScale');
Rect = spm('WinSize','Menu','raw').*WS;
set(fig,'units','pixels');
Fdim = get(fig,'position');
set(fig,'position',[Rect(1) 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(sprintf('Wrong input format\n'));
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);
set(handles.CreateMeshes,'enable','off')
set(handles.Reg2tem, 'enable','off')
Reset(hObject, eventdata, handles);
% --- Executes on button press in Reg2tem.
%--------------------------------------------------------------------------
function Reg2tem_Callback(hObject, eventdata, handles)
str = 'Mesh size (vertices)';
handles.D.inv{handles.D.val}.mesh.Msize = spm_input(str,'+1','3000|4000|5000|7200',[1 2 3 4]);
handles.D = spm_eeg_inv_template(handles.D);
set(handles.CreateMeshes,'enable','off')
DataReg_Callback(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)
if strcmp(handles.D.inv{handles.D.val}.method,'Imaging')
handles.D = spm_eeg_invert_ui(handles.D);
else
handles.D = spm_eeg_inv_ecd_ui(handles.D);
end
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)
Qstr = 'Please choose';
Tstr = 'Smoothing in mm';
handles.D.inv{handles.D.val}.contrast.smooth = str2num(questdlg(Qstr,Tstr,'8','12','16','12'));
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 = spm_select(1, '.mat', 'Select EEG/MEG mat file');
D = spm_eeg_ldata(S);
try
D.modality;
catch
D.modality = questdlg('Modality','Please specify','EEG','MEG',1);
end
[pth,nam,ext] = fileparts(S);
D.path = pth;
D.fname = nam;
set(handles.DataFile,'String',D.fname);
set(handles.Exit,'enable','on')
cd(pth);
handles.D = D;
Reset(hObject, eventdata, handles);
% --- Executes on button press in Exit.
%--------------------------------------------------------------------------
function Exit_Callback(hObject, eventdata, handles)
D = handles.D;
if spm_matlab_version_chk('7.1') >= 0
save(fullfile(D.path, D.fname), '-V6', 'D');
else
save(fullfile(D.path, D.fname), 'D');
end
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 ~length(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')
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 length(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 ~length(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};
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)
if isfield(Q,'mesh')
set(handles.DataReg, 'enable','on')
set(handles.CheckMesh,'enable','on')
if isfield(Q,'datareg')
set(handles.Forward, 'enable','on')
set(handles.CheckReg,'enable','on')
if isfield(Q,'forward')
set(handles.Inverse, 'enable','on')
set(handles.CheckForward,'enable','on')
if isfield(Q,'inverse')
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
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)
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);
else
resdip = handles.D.inv{handles.D.val}.inverse.resdip;
sMRI = handles.D.inv{handles.D.val}.mesh.sMRI
spm_eeg_inv_ecd_DrawDip('Init',resdip,sMRI);
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)
spm_eeg_inv_visu3D_api(handles.D);
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
% --- Executes on button press in fusion.
%--------------------------------------------------------------------------
function fusion_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_invert_fuse_ui;
Reset(hObject, eventdata, handles)
|
github
|
spm/spm5-master
|
spm_smoothto8bit.m
|
.m
|
spm5-master/spm_smoothto8bit.m
| 2,376 |
utf_8
|
a51643d7766b47182eafff1948680218
|
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) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_smoothto8bit.m 946 2007-10-15 16:36:06Z john $
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
|
spm/spm5-master
|
spm_config_fmri_design.m
|
.m
|
spm5-master/spm_config_fmri_design.m
| 44,802 |
utf_8
|
476fe235b583f0a77b9a767e526929e3
|
function conf = spm_config_fmri_design
% Configuration file for specification of fMRI model
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Darren Gitelman and Will Penny
% $Id: spm_config_fmri_design.m 1016 2007-12-03 12:51:33Z volkmar $
% Define inline types.
%-----------------------------------------------------------------------
entry = inline(['struct(''type'',''entry'',''name'',name,'...
'''tag'',tag,''strtype'',strtype,''num'',num,''help'',hlp)'],...
'name','tag','strtype','num','hlp');
files = inline(['struct(''type'',''files'',''name'',name,'...
'''tag'',tag,''filter'',fltr,''num'',num,''help'',hlp)'],...
'name','tag','fltr','num','hlp');
mnu = inline(['struct(''type'',''menu'',''name'',name,'...
'''tag'',tag,''labels'',{labels},''values'',{values},''help'',hlp)'],...
'name','tag','labels','values','hlp');
branch = inline(['struct(''type'',''branch'',''name'',name,'...
'''tag'',tag,''val'',{val},''help'',hlp)'],...
'name','tag','val','hlp');
repeat = inline(['struct(''type'',''repeat'',''name'',name,'...
'''tag'',tag,''values'',{values},''help'',hlp)'],...
'name','tag','values','hlp');
choice = inline(['struct(''type'',''choice'',''name'',name,'...
'''tag'',tag,''values'',{values},''help'',hlp)'],...
'name','tag','values','hlp');
%-----------------------------------------------------------------------
sp_text = [' ',...
' '];
%-----------------------------------------------------------------------
onset = entry('Onsets','onset','e',[Inf 1],'Vector of onsets');
p1 = ['Specify a vector of onset times for this condition type. '];
onset.help = {p1};
%-------------------------------------------------------------------------
duration = entry('Durations','duration','e',[Inf 1],'Duration/s');
duration.help = [...
'Specify the event durations. Epoch and event-related ',...
'responses are modeled in exactly the same way but by specifying their ',...
'different durations. Events are ',...
'specified with a duration of 0. If you enter a single number for the ',...
'durations it will be assumed that all trials conform to this duration. ',...
'If you have multiple different durations, then the number must match the ',...
'number of onset times.'];
%-------------------------------------------------------------------------
time_mod = mnu('Time Modulation','tmod',...
{'No Time Modulation','1st order Time Modulation',...
'2nd order Time Modulation','3rd order Time Modulation',...
'4th order Time Modulation','5th order Time Modulation',...
'6th order Time Modulation'},...
{0,1,2,3,4,5,6},'');
time_mod.val = {0};
p1 = [...
'This option allows for the characterisation of linear or nonlinear ',...
'time effects. ',...
'For example, 1st order modulation ',...
'would model the stick functions and a linear change of the stick function ',...
'heights over time. Higher order modulation will introduce further columns that ',...
'contain the stick functions scaled by time squared, time cubed etc.'];
p2 = [...
'Interactions or response modulations can enter at two levels. Firstly ',...
'the stick function itself can be modulated by some parametric variate ',...
'(this can be time or some trial-specific variate like reaction time) ',...
'modeling the interaction between the trial and the variate or, secondly ',...
'interactions among the trials themselves can be modeled using a Volterra ',...
'series formulation that accommodates interactions over time (and therefore ',...
'within and between trial types).'];
time_mod.help = {p1,'',p2};
%-------------------------------------------------------------------------
%ply = mnu('Polynomial Expansion','poly',...
% {'None','1st order','2nd order','3rd order','4th order','5th order','6th order'},...
% {0,1,2,3,4,5,6},'Polynomial Order');
%ply.val = {0};
%-------------------------------------------------------------------------
name = entry('Name','name','s', [1 Inf],'Name of parameter');
name.val = {'Param'};
name.help = {'Enter a name for this parameter.'};
%-------------------------------------------------------------------------
param = entry('Values','param','e',[Inf 1],'Parameter vector');
param.help = {'Enter a vector of values, one for each occurence of the event.'};
%-------------------------------------------------------------------------
ply = mnu('Polynomial Expansion','poly',...
{'1st order','2nd order','3rd order','4th order','5th order','6th order'},...
{1,2,3,4,5,6},'Polynomial Order');
ply.val = {1};
ply.help = {[...
'For example, 1st order modulation ',...
'would model the stick functions and a linear change of the stick function ',...
'heights over different values of the parameter. Higher order modulation will ',...
'introduce further columns that ',...
'contain the stick functions scaled by parameter squared, cubed etc.']};
%-------------------------------------------------------------------------
pother = branch('Parameter','pmod',{name,param,ply},'Custom parameter');
p1 = [...
'Model interractions with user specified parameters. ',...
'This allows nonlinear effects relating to some other measure ',...
'to be modelled in the design matrix.'];
p2 = [...
'Interactions or response modulations can enter at two levels. Firstly ',...
'the stick function itself can be modulated by some parametric variate ',...
'(this can be time or some trial-specific variate like reaction time) ',...
'modeling the interaction between the trial and the variate or, secondly ',...
'interactions among the trials themselves can be modeled using a Volterra ',...
'series formulation that accommodates interactions over time (and therefore ',...
'within and between trial types).'];
pother.help = {p1,'',p2};
%-------------------------------------------------------------------------
pmod = repeat('Parametric Modulations','pmod',{pother},'');
pmod.help = {[...
'The stick function itself can be modulated by some parametric variate ',...
'(this can be time or some trial-specific variate like reaction time) ',...
'modeling the interaction between the trial and the variate. ',...
'The events can be modulated by zero or more parameters.']};
%-------------------------------------------------------------------------
name = entry('Name','name','s',[1 Inf],'Condition Name');
name.val = {'Trial'};
%-------------------------------------------------------------------------
cond = branch('Condition','cond',{name,onset,duration,time_mod,pmod},...
'Condition');
cond.check = @cond_check;
cond.help = {[...
'An array of input functions is contructed, ',...
'specifying occurrence events or epochs (or both). ',...
'These are convolved with a basis set at a later stage to give ',...
'regressors that enter into the design matrix. Interactions of evoked ',...
'responses with some parameter (time or a specified variate) enter at ',...
'this stage as additional columns in the design matrix with each trial multiplied ',...
'by the [expansion of the] trial-specific parameter. ',...
'The 0th order expansion is simply the main effect in the first column.']};
%-------------------------------------------------------------------------
conditions = repeat('Conditions','condrpt',{cond},'Conditions');
conditions.help = {[...
'You are allowed to combine both event- and epoch-related ',...
'responses in the same model and/or regressor. Any number ',...
'of condition (event or epoch) types can be specified. Epoch and event-related ',...
'responses are modeled in exactly the same way by specifying their ',...
'onsets [in terms of onset times] and their durations. Events are ',...
'specified with a duration of 0. If you enter a single number for the ',...
'durations it will be assumed that all trials conform to this duration.',...
'For factorial designs, one can later associate these experimental conditions ',...
'with the appropriate levels of experimental factors. ';]};
%-------------------------------------------------------------------------
multi = files('Multiple conditions','multi','\.mat$',[0 1],'');
p1=['Select the *.mat file containing details of your multiple experimental conditions. '];
p2=['If you have multiple conditions then entering the details a condition ',...
'at a time is very inefficient. This option can be used to load all the ',...
'required information in one go. You will first need to create a *.mat file ',...
'containing the relevant information. '];
p3=['This *.mat file must include the following cell arrays (each 1 x n): ',...
'names, onsets and durations. eg. names=cell(1,5), onsets=cell(1,5), ',...
'durations=cell(1,5), then names{2}=''SSent-DSpeak'', onsets{2}=[3 5 19 222], ',...
'durations{2}=[0 0 0 0], contain the required details of the second condition. ',...
'These cell arrays may be made available by your stimulus delivery program, ',...
'eg. COGENT. The duration vectors can contain a single entry if the durations ',...
'are identical for all events.'];
p4=['Time and Parametric effects can also be included. For time modulation ',...
'include a cell array (1 x n) called tmod. It should have a have a single ',...
'number in each cell. Unused cells may contain either a 0 or be left empty. The number ',...
'specifies the order of time modulation from 0 = No Time Modulation to ',...
'6 = 6th Order Time Modulation. eg. tmod{3} = 1, modulates the 3rd condition ',...
'by a linear time effect.'];
p5=['For parametric modulation include a structure array, which is up to 1 x n in size, ',...
'called pmod. n must be less than or equal to the number of cells in the ',...
'names/onsets/durations cell arrays. The structure array pmod must have the fields: ',...
'name, param and poly. Each of these fields is in turn a cell array to allow the ',...
'inclusion of one or more parametric effects per column of the design. The field ',...
'name must be a cell array containing strings. The field param is a cell array ',...
'containing a vector of parameters. Remember each parameter must be the same length as its ',...
'corresponding onsets vector. The field poly is a cell array (for consistency) ',...
'with each cell containing a single number specifying the order of the polynomial ',...
'expansion from 1 to 6.'];
p6=['Note that each condition is assigned its corresponding ',...
'entry in the structure array (condition 1 parametric modulators are in pmod(1), ',...
'condition 2 parametric modulators are in pmod(2), etc. Within a condition ',...
'multiple parametric modulators are accessed via each fields cell arrays. ',...
'So for condition 1, parametric modulator 1 would be defined in ',...
'pmod(1).name{1}, pmod(1).param{1}, and pmod(1).poly{1}. A second parametric ',...
'modulator for condition 1 would be defined as pmod(1).name{2}, pmod(1).param{2} ',...
'and pmod(1).poly{2}. If there was also a parametric modulator for condition 2, ',...
'then remember the first modulator for that condition is in cell array 1: ',...
'pmod(2).name{1}, pmod(2).param{1}, and pmod(2).poly{1}. If some, but not ',...
'all conditions are parametrically modulated, then the non-modulated indices ',...
'in the pmod structure can be left blank. For example, if conditions 1 and 3 but ',...
'not condition 2 are modulated, then specify pmod(1) and pmod(3). ',...
'Similarly, if conditions 1 and 2 are modulated but there are 3 conditions ',...
'overall, it is only necessary for pmod to be a 1 x 2 structure array.'];
p7=['EXAMPLE:'];
p8=['Make an empty pmod structure: '];
p9=[' pmod = struct(''name'',{''''},''param'',{},''poly'',{});'];
p10=['Specify one parametric regressor for the first condition: '];
p11=[' pmod(1).name{1} = ''regressor1'';'];
p12=[' pmod(1).param{1} = [1 2 4 5 6];'];
p13=[' pmod(1).poly{1} = 1;'];
p14=['Specify 2 parametric regressors for the second condition: '];
p15=[' pmod(2).name{1} = ''regressor2-1'';'];
p16=[' pmod(2).param{1} = [1 3 5 7]; '];
p17=[' pmod(2).poly{1} = 1;'];
p18=[' pmod(2).name{2} = ''regressor2-2'';'];
p19=[' pmod(2).param{2} = [2 4 6 8 10];'];
p20=[' pmod(2).poly{2} = 1;'];
p21=['The parametric modulator should be mean corrected if appropriate. Unused ',...
'structure entries should have all fields left empty.'];
multi.help = {p1,sp_text,p2,sp_text,p3,sp_text,p4,sp_text,p5,sp_text,p6,...
sp_text,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,sp_text,p21};
multi.val={''};
%-------------------------------------------------------------------------
name = entry('Name','name','s',[1 Inf],'');
name.val = {'Regressor'};
p1=['Enter name of regressor eg. First movement parameter'];
name.help={p1};
%-------------------------------------------------------------------------
val = entry('Value','val','e',[Inf 1],'');
val.help={['Enter the vector of regressor values']};
%-------------------------------------------------------------------------
regress = branch('Regressor','regress',{name,val},'regressor');
regressors = repeat('Regressors','regress',{regress},'Regressors');
regressors.help = {[...
'Regressors are additional columns included in the design matrix, ',...
'which may model effects that would not be convolved with the ',...
'haemodynamic response. One such example would be the estimated movement ',...
'parameters, which may confound the data.']};
%-------------------------------------------------------------------------
multi_reg = files('Multiple regressors','multi_reg','.*',[0 1],'');
p1=['Select the *.mat/*.txt file containing details of your multiple regressors. '];
p2=['If you have multiple regressors eg. realignment parameters, then entering the ',...
'details a regressor at a time is very inefficient. ',...
'This option can be used to load all the ',...
'required information in one go. '];
p3=['You will first need to create a *.mat file ',...
'containing a matrix R or a *.txt file containing the regressors. ',...
'Each column of R will contain a different regressor. ',...
'When SPM creates the design matrix the regressors will be named R1, R2, R3, ..etc.'];
multi_reg.help = {p1,sp_text,p2,sp_text,p3};
multi_reg.val={''};
%-------------------------------------------------------------------------
nscan = entry('# Scans','nscan','e',[1 1],'');
nscan.help = {['Specify the number of scans for this session.'...
'The actual scans must be specified in a separate '...
'batch job ''Specify Data''.']};
%-------------------------------------------------------------------------
hpf = entry('High-pass filter','hpf','e',[1 1],'');
hpf.val = {128};
hpf.help = {[...
'The default high-pass filter cutoff is 128 seconds.',...
'Slow signal drifts with a period longer than this will be removed. ',...
'Use ''explore design'' ',...
'to ensure this cut-off is not removing too much experimental variance. ',...
'High-pass filtering is implemented using a residual forming matrix (i.e. ',...
'it is not a convolution) and is simply to a way to remove confounds ',...
'without estimating their parameters explicitly. The constant term ',...
'is also incorporated into this filter matrix.']};
%-------------------------------------------------------------------------
sess = branch('Subject/Session','sess',{nscan,conditions,multi,regressors,multi_reg,hpf},'Session');
sess.check = @sess_check;
p1 = [...
'The design matrix for fMRI data consists of one or more separable, ',...
'session-specific partitions. These partitions are usually either one per ',...
'subject, or one per fMRI scanning session for that subject.'];
sess.help = {p1};
%-------------------------------------------------------------------------
block = repeat('Data & Design','blocks',{sess},'');
block.num = [1 Inf];
p1 = [...
'The design matrix defines the experimental design and the nature of ',...
'hypothesis testing to be implemented. The design matrix has one row ',...
'for each scan and one column for each effect or explanatory variable. ',...
'(e.g. regressor or stimulus function). '];
p2 = [...
'This allows you to build design matrices with separable ',...
'session-specific partitions. Each partition may be the same (in which ',...
'case it is only necessary to specify it once) or different. Responses ',...
'can be either event- or epoch related, where the latter model involves prolonged ',...
'and possibly time-varying responses to state-related changes in ',...
'experimental conditions. Event-related response are modelled in terms ',...
'of responses to instantaneous events. Mathematically they are both ',...
'modelled by convolving a series of delta (stick) or box-car functions, ',...
'encoding the input or stimulus function. with a set of hemodynamic ',...
'basis functions.'];
block.help = {p1,'',p2};
% Specification of factorial designs
fname.type = 'entry';
fname.name = 'Name';
fname.tag = 'name';
fname.strtype = 's';
fname.num = [1 1];
fname.help = {'Name of factor, eg. ''Repetition'' '};
levels = entry('Levels','levels','e',[Inf 1],'');
p1=['Enter number of levels for this factor, eg. 2'];
levels.help ={p1};
factor.type = 'branch';
factor.name = 'Factor';
factor.tag = 'fact';
factor.val = {fname,levels};
factor.help = {'Add a new factor to your experimental design'};
factors.type = 'repeat';
factors.name = 'Factorial design';
factors.tag = 'factors';
factors.values = {factor};
p1 = ['If you have a factorial design then SPM can automatically generate ',...
'the contrasts necessary to test for the main effects and interactions. '];
p2 = ['This includes the F-contrasts necessary to test for these effects at ',...
'the within-subject level (first level) and the simple contrasts necessary ',...
'to generate the contrast images for a between-subject (second-level) ',...
'analysis.'];
p3 = ['To use this option, create as many factors as you need and provide a name ',...
'and number of levels for each. ',...
'SPM assumes that the condition numbers of the first factor change slowest, ',...
'the second factor next slowest etc. It is best to write down the contingency ',...
'table for your design to ensure this condition is met. This table relates the ',...
'levels of each factor to the ',...
'conditions. '];
p4= ['For example, if you have 2-by-3 design ',...
' your contingency table has two rows and three columns where the ',...
'the first factor spans the rows, and the second factor the columns. ',...
'The numbers of the conditions are 1,2,3 for the first row and 4,5,6 ',...
'for the second. '];
factors.help ={p1,sp_text,p2,sp_text,p3,sp_text,p4};
%-------------------------------------------------------------------------
glob = mnu('Global normalisation','global',...
{'Scaling','None'},{'Scaling','None'},{'Global intensity normalisation'});
glob.val={'None'};
%-------------------------------------------------------------------------
derivs = mnu('Model derivatives','derivs',...
{'No derivatives', 'Time derivatives', 'Time and Dispersion derivatives'},...
{[0 0],[1 0],[1 1]},'');
derivs.val = {[0 0]};
p1=['Model HRF Derivatives. The canonical HRF combined with time and ',...
'dispersion derivatives comprise an ''informed'' basis set, as ',...
'the shape of the canonical response conforms to the hemodynamic ',...
'response that is commonly observed. The incorporation of the derivate ',...
'terms allow for variations in subject-to-subject and voxel-to-voxel ',...
'responses. The time derivative allows the peak response to vary by plus or ',...
'minus a second and the dispersion derivative allows the width of the response ',...
'to vary. The informed basis set requires an SPM{F} for inference. T-contrasts ',...
'over just the canonical are perfectly valid but assume constant delay/dispersion. ',...
'The informed basis set compares ',...
'favourably with eg. FIR bases on many data sets. '];
derivs.help = {p1};
%-------------------------------------------------------------------------
hrf = branch('Canonical HRF','hrf',{derivs},'Canonical Hemodynamic Response Function');
hrf.help = {[...
'Canonical Hemodynamic Response Function. This is the default option. ',...
'Contrasts of these effects have a physical interpretation ',...
'and represent a parsimonious way of characterising event-related ',...
'responses. This option is also ',...
'useful if you wish to ',...
'look separately at activations and deactivations (this is implemented using a ',...
't-contrast with a +1 or -1 entry over the canonical regressor). ']};
%-------------------------------------------------------------------------
len = entry('Window length','length','e',[1 1],'');
len.help={'Post-stimulus window length (in seconds)'};
order = entry('Order','order','e',[1 1],'');
order.help={'Number of basis functions'};
o1 = branch('Fourier Set','fourier',{len,order},'');
o1.help = {'Fourier basis functions. This option requires an SPM{F} for inference.'};
o2 = branch('Fourier Set (Hanning)','fourier_han',{len,order},'');
o2.help = {'Fourier basis functions with Hanning Window - requires SPM{F} for inference.'};
o3 = branch('Gamma Functions','gamma',{len,order},'');
o3.help = {'Gamma basis functions - requires SPM{F} for inference.'};
o4 = branch('Finite Impulse Response','fir',{len,order},'');
o4.help = {'Finite impulse response - requires SPM{F} for inference.'};
%-------------------------------------------------------------------------
bases = choice('Basis Functions','bases',{hrf,o1,o2,o3,o4},'');
bases.val = {hrf};
bases.help = {[...
'The most common choice of basis function is the Canonical HRF with ',...
'or without time and dispersion derivatives. ']};
%-------------------------------------------------------------------------
volt = mnu('Model Interactions (Volterra)','volt',{'Do not model Interactions','Model Interactions'},{1,2},'');
volt.val = {1};
p1 = ['Generalized convolution of inputs (U) with basis set (bf).'];
p2 = [...
'For first order expansions the causes are simply convolved ',...
'(e.g. stick functions) in U.u by the basis functions in bf to create ',...
'a design matrix X. For second order expansions new entries appear ',...
'in ind, bf and name that correspond to the interaction among the ',...
'orginal causes. The basis functions for these efects are two dimensional ',...
'and are used to assemble the second order kernel. ',...
'Second order effects are computed for only the first column of U.u.'];
p3 = [...
'Interactions or response modulations can enter at two levels. Firstly ',...
'the stick function itself can be modulated by some parametric variate ',...
'(this can be time or some trial-specific variate like reaction time) ',...
'modeling the interaction between the trial and the variate or, secondly ',...
'interactions among the trials themselves can be modeled using a Volterra ',...
'series formulation that accommodates interactions over time (and therefore ',...
'within and between trial types).'];
volt.help = {p1,'',p2,p3};
%-------------------------------------------------------------------------
cdir = files('Directory','dir','dir',1,'');
cdir.help = {[...
'Select a directory where the SPM.mat file containing the ',...
'specified design matrix will be written.']};
%-------------------------------------------------------------------------
fmri_t0 = entry('Microtime onset','fmri_t0','e',[1 1],'');
p1=['The microtime onset, t0, is the first time-bin at which the regressors ',...
'are resampled to coincide ',...
'with data acquisition. If t0 = 1 then the ',...
'regressors will be appropriate for the first slice. If you want to ',...
'temporally realign the regressors so that they match responses in the ',...
'middle slice then make t0 = t/2 ',...
'(assuming there is a negligible gap between ',...
'volume acquisitions). '];
p2=['Do not change the default setting unless you have a long TR. '];
fmri_t0.val={1};
fmri_t0.help={p1,sp_text,p2};
fmri_t = entry('Microtime resolution','fmri_t','e',[1 1],'');
p1=['The microtime resolution, t, is the number of time-bins per ',...
'scan used when building regressors. '];
p2=['Do not change this parameter unless you have a long TR and wish to ',...
'shift regressors so that they are ',...
'aligned to a particular slice. '];
fmri_t.val={16};
fmri_t.help={p1,sp_text,p2};
rt = entry('Interscan interval','RT','e',[1 1],'Interscan interval {secs}');
rt.help = {[...
'Interscan interval, TR, (specified in seconds). This is the time between acquiring a plane of one volume ',...
'and the same plane in the next volume. It is assumed to be constant throughout.']};
%-------------------------------------------------------------------------
units = mnu('Units for design','units',{'Scans','Seconds'},{'scans','secs'},'');
p1=['The onsets of events or blocks can be specified in either scans or seconds.'];
units.help = {p1};
timing = branch('Timing parameters','timing',{units,rt,fmri_t,fmri_t0},'');
p1=['Specify various timing parameters needed to construct the design matrix. ',...
'This includes the units of the design specification and the interscan interval.'];
p2 = ['Also, with longs TRs you may want to shift the regressors so that they are ',...
'aligned to a particular slice. This is effected by changing the ',...
'microtime resolution and onset. '];
timing.help={p1,sp_text,p2};
%-------------------------------------------------------------------------
cvi = mnu('Serial correlations','cvi',{'none','AR(1)'},{'none','AR(1)'},...
{'Correct for serial correlations'});
cvi.val={'AR(1)'};
p1 = [...
'Serial correlations in fMRI time series due to aliased biorhythms and unmodelled ',...
'neuronal activity can be accounted for using an autoregressive AR(1) ',...
'model during Classical (ReML) parameter estimation. '];
p2=['This estimate assumes the same ',...
'correlation structure for each voxel, within each session. ReML ',...
'estimates are then used to correct for non-sphericity during inference ',...
'by adjusting the statistics and degrees of freedom appropriately. The ',...
'discrepancy between estimated and actual intrinsic (i.e. prior to ',...
'filtering) correlations are greatest at low frequencies. Therefore ',...
'specification of the high-pass filter is particularly important. '];
p3=[...
'Serial correlation can be ignored if you choose the ''none'' option. ',...
'Note that the above options only apply if you later specify that your model will be ',...
'estimated using the Classical (ReML) approach. If you choose Bayesian estimation ',...
'these options will be ignored. For Bayesian estimation, the choice of noise',...
'model (AR model order) is made under the estimation options. '];
cvi.help = {p1,sp_text,p2,sp_text,p3};
%-------------------------------------------------------------------------
conf = branch('fMRI model specification (design only)','fmri_design',...
{cdir,timing,block,factors,bases,volt,glob,cvi},'fMRI design');
conf.prog = @run_stats;
conf.vfiles = @vfiles_stats;
% conf.check = @check_dir;
conf.modality = {'FMRI'};
p1=['Statistical analysis of fMRI data uses a mass-univariate approach ',...
'based on General Linear Models (GLMs). It comprises the following ',...
'steps (1) specification of the GLM design matrix, fMRI data files and filtering ',...
'(2) estimation of GLM paramaters using classical or ',...
'Bayesian approaches and (3) interrogation of results using contrast vectors to ',...
'produce Statistical Parametric Maps (SPMs) or Posterior Probability Maps (PPMs).' ];
p2 = [...
'The design matrix defines the experimental design and the nature of ',...
'hypothesis testing to be implemented. The design matrix has one row ',...
'for each scan and one column for each effect or explanatory variable. ',...
'(eg. regressor or stimulus function). ',...
'You can build design matrices with separable ',...
'session-specific partitions. Each partition may be the same (in which ',...
'case it is only necessary to specify it once) or different. '];
p3 = ['Responses ',...
'can be either event- or epoch related, the only distinction is the duration ',...
'of the underlying input or stimulus function. Mathematically they are both ',...
'modeled by convolving a series of delta (stick) or box functions (u), ',...
'indicating the onset of an event or epoch with a set of basis ',...
'functions. These basis functions model the hemodynamic convolution, ',...
'applied by the brain, to the inputs. This convolution can be first-order ',...
'or a generalized convolution modeled to second order (if you specify the ',...
'Volterra option). The same inputs are used by the Hemodynamic model or ',...
'Dynamic Causal Models which model the convolution explicitly in terms of ',...
'hidden state variables. '];
p4=['Basis functions can be used to plot estimated responses to single events ',...
'once the parameters (i.e. basis function coefficients) have ',...
'been estimated. The importance of basis functions is that they provide ',...
'a graceful transition between simple fixed response models (like the ',...
'box-car) and finite impulse response (FIR) models, where there is one ',...
'basis function for each scan following an event or epoch onset. The ',...
'nice thing about basis functions, compared to FIR models, is that data ',...
'sampling and stimulus presentation does not have to be synchronized ',...
'thereby allowing a uniform and unbiased sampling of peri-stimulus time.'];
p5 = [...
'Event-related designs may be stochastic or deterministic. Stochastic ',...
'designs involve one of a number of trial-types occurring with a ',...
'specified probability at successive intervals in time. These ',...
'probabilities can be fixed (stationary designs) or time-dependent ',...
'(modulated or non-stationary designs). The most efficient designs ',...
'obtain when the probabilities of every trial type are equal. ',...
'A critical issue in stochastic designs is whether to include null events ',...
'If you wish to estimate the evoked response to a specific event ',...
'type (as opposed to differential responses) then a null event must be ',...
'included (even if it is not modeled explicitly).'];
p6 = [...
'In SPM, analysis of data from multiple subjects typically proceeds in two stages ',...
'using models at two ''levels''. The ''first level'' models are used to ',...
'implement a within-subject analysis. Typically there will be as many first ',...
'level models as there are subjects. Analysis proceeds as described using the ',...
'''Specify first level'' and ''Estimate'' options. The results of these analyses ',...
'can then be presented as ''case studies''. More often, however, one wishes to ',...
'make inferences about the population from which the subjects were drawn. This is ',...
'an example of a ''Random-Effects (RFX) analysis'' (or, more properly, a mixed-effects ',...
'analysis). In SPM, RFX analysis is implemented using the ''summary-statistic'' ',...
'approach where contrast images from each subject are used as summary ',...
'measures of subject responses. These are then entered as data into a ''second level'' ',...
'model. '];
conf.help = {p1,'',p2,'',p3,'',p4,'',p5,'',p6};
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
% COMMENTED OUT BY DRG. I THINK THIS SUB-FUNCTION WAS A HOLDOVER FROM AN
% EARLY VERSION OF THIS FILE. PLEASE REMOVE IF REALLY NOT USED. ALSO REMOVE
% REFERENCE ON LINE 510 (COMMENTED OUT) TO CHECK_DIR
% function t = check_dir(job)
% t = {};
%d = pwd;
%try,
% cd(job.dir{1});
%catch,
% t = {['Cannot Change to directory "' job.dir{1} '".']};
%end;
%disp('Checking...');
%disp(fullfile(job.dir{1},'SPM.mat'));
% Should really include a check for a "virtual" SPM.mat
%if exist(fullfile(job.dir{1},'SPM.mat'),'file'),
% t = {'SPM files exist in the analysis directory.'};
%end;
%return;
% END COMMENTED OUT BY DRG
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function t = cond_check(job)
t = {};
if (numel(job.onset) ~= numel(job.duration)) && (numel(job.duration)~=1),
t = {sprintf('"%s": Number of event onsets (%d) does not match the number of durations (%d).',...
job.name, numel(job.onset),numel(job.duration))};
end;
for i=1:numel(job.pmod),
if numel(job.onset) ~= numel(job.pmod(i).param),
t = {t{:}, sprintf('"%s" & "%s":Number of event onsets (%d) does not equal the number of parameters (%d).',...
job.name, job.pmod(i).name, numel(job.onset),numel(job.pmod(i).param))};
end;
end;
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function t = sess_check(sess)
t = {};
for i=1:numel(sess.regress),
if sess.nscan ~= numel(sess.regress(i).val),
t = {t{:}, sprintf('Num scans (%d) ~= Num regress[%d] (%d).',numel(sess.nscan),i,numel(sess.regress(i).val))};
end;
end;
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function my_cd(varargin)
% jobDir must be the actual directory to change to, NOT the job structure.
jobDir = varargin{1};
if ~isempty(jobDir)
try
cd(char(jobDir));
fprintf('Changing directory to: %s\n',char(jobDir));
catch
error('Failed to change directory. Aborting run.')
end
end
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function run_stats(job)
% Set up the design matrix and run a design.
spm_defaults;
global defaults
defaults.modality='FMRI';
original_dir = pwd;
my_cd(job.dir);
%-Ask about overwriting files from previous analyses...
%-------------------------------------------------------------------
if exist(fullfile(job.dir{1},'SPM.mat'),'file')
str = { 'Current directory contains existing SPM file:',...
'Continuing will overwrite existing file!'};
if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);
fprintf('%-40s: %30s\n\n',...
'Abort... (existing SPM file)',spm('time'));
return
end
end
% If we've gotten to this point we're committed to overwriting files.
% Delete them so we don't get stuck in spm_spm
%------------------------------------------------------------------------
files = {'^mask\..{3}$','^ResMS\..{3}$','^RPV\..{3}$',...
'^beta_.{4}\..{3}$','^con_.{4}\..{3}$','^ResI_.{4}\..{3}$',...
'^ess_.{4}\..{3}$', '^spm\w{1}_.{4}\..{3}$'};
for i=1:length(files)
j = spm_select('List',pwd,files{i});
for k=1:size(j,1)
spm_unlink(deblank(j(k,:)));
end
end
% Variables
%-------------------------------------------------------------
SPM.xY.RT = job.timing.RT;
% Slice timing
defaults.stats.fmri.t=job.timing.fmri_t;
defaults.stats.fmri.t0=job.timing.fmri_t0;
% Basis function variables
%-------------------------------------------------------------
SPM.xBF.UNITS = job.timing.units;
SPM.xBF.dt = job.timing.RT/defaults.stats.fmri.t;
SPM.xBF.T = defaults.stats.fmri.t;
SPM.xBF.T0 = defaults.stats.fmri.t0;
% Basis functions
%-------------------------------------------------------------
if strcmp(fieldnames(job.bases),'hrf')
if all(job.bases.hrf.derivs == [0 0])
SPM.xBF.name = 'hrf';
elseif all(job.bases.hrf.derivs == [1 0])
SPM.xBF.name = 'hrf (with time derivative)';
elseif all(job.bases.hrf.derivs == [1 1])
SPM.xBF.name = 'hrf (with time and dispersion derivatives)';
else
error('Unrecognized hrf derivative choices.')
end
else
nambase = fieldnames(job.bases);
if ischar(nambase)
nam=nambase;
else
nam=nambase{1};
end
switch nam,
case 'fourier',
SPM.xBF.name = 'Fourier set';
case 'fourier_han',
SPM.xBF.name = 'Fourier set (Hanning)';
case 'gamma',
SPM.xBF.name = 'Gamma functions';
case 'fir',
SPM.xBF.name = 'Finite Impulse Response';
otherwise
error('Unrecognized hrf derivative choices.')
end
SPM.xBF.length = job.bases.(nam).length;
SPM.xBF.order = job.bases.(nam).order;
end
SPM.xBF = spm_get_bf(SPM.xBF);
if isempty(job.sess),
SPM.xBF.Volterra = false;
else
SPM.xBF.Volterra = job.volt;
end;
for i = 1:numel(job.sess),
sess = job.sess(i);
% Image filenames
%-------------------------------------------------------------
SPM.nscan(i) = sess.nscan;
U = [];
% Augment the singly-specified conditions with the multiple conditions
% specified in a .mat file provided by the user
%------------------------------------------------------------
if ~isempty(sess.multi{1})
try
multicond = load(sess.multi{1});
catch
error('Cannot load %s',sess.multi{1});
end
if ~(isfield(multicond,'names')&&isfield(multicond,'onsets')&&...
isfield(multicond,'durations')) || ...
~all([numel(multicond.names),numel(multicond.onsets), ...
numel(multicond.durations)]==numel(multicond.names))
error(['Multiple conditions MAT-file ''%s'' is invalid.\n',...
'File must contain names, onsets, and durations '...
'cell arrays of equal length.\n'],sess.multi{1});
end
%-contains three cell arrays: names, onsets and durations
for j=1:length(multicond.onsets)
cond.name = multicond.names{j};
cond.onset = multicond.onsets{j};
cond.duration = multicond.durations{j};
% ADDED BY DGITELMAN
% Mutiple Conditions Time Modulation
%------------------------------------------------------
% initialize the variable.
cond.tmod = 0;
if isfield(multicond,'tmod');
try
cond.tmod = multicond.tmod{j};
catch
error('Error specifying time modulation.');
end
end
% Mutiple Conditions Parametric Modulation
%------------------------------------------------------
% initialize the parametric modulation variable.
cond.pmod = [];
if isfield(multicond,'pmod')
% only access existing modulators
try
% check if there is a parametric modulator. this allows
% pmod structures with fewer entries than conditions.
% then check whether any cells are filled in.
if (j <= numel(multicond.pmod)) && ...
~isempty(multicond.pmod(j).name)
% we assume that the number of cells in each
% field of pmod is the same (or should be).
for ii = 1:numel(multicond.pmod(j).name)
cond.pmod(ii).name = multicond.pmod(j).name{ii};
cond.pmod(ii).param = multicond.pmod(j).param{ii};
cond.pmod(ii).poly = multicond.pmod(j).poly{ii};
end
end;
catch
error('Error specifying parametric modulation.');
end
end
sess.cond(end+1) = cond;
end
end
% Configure the input structure array
%-------------------------------------------------------------
for j = 1:length(sess.cond),
cond = sess.cond(j);
U(j).name = {cond.name};
U(j).ons = cond.onset(:);
U(j).dur = cond.duration(:);
if length(U(j).dur) == 1
U(j).dur = U(j).dur*ones(size(U(j).ons));
elseif length(U(j).dur) ~= length(U(j).ons)
error('Mismatch between number of onset and number of durations.')
end
P = [];
q1 = 0;
if cond.tmod>0,
% time effects
P(1).name = 'time';
P(1).P = U(j).ons*job.timing.RT;
P(1).h = cond.tmod;
q1 = 1;
end;
if ~isempty(cond.pmod)
for q = 1:numel(cond.pmod),
% Parametric effects
q1 = q1 + 1;
P(q1).name = cond.pmod(q).name;
P(q1).P = cond.pmod(q).param(:);
P(q1).h = cond.pmod(q).poly;
end;
end
if isempty(P)
P.name = 'none';
P.h = 0;
end
U(j).P = P;
end
SPM.Sess(i).U = U;
% User specified regressors
%-------------------------------------------------------------
C = [];
Cname = cell(1,numel(sess.regress));
for q = 1:numel(sess.regress),
Cname{q} = sess.regress(q).name;
C = [C, sess.regress(q).val(:)];
end
% Augment the singly-specified regressors with the multiple regressors
% specified in the regressors.mat file
%------------------------------------------------------------
if ~strcmp(sess.multi_reg,'')
tmp=load(char(sess.multi_reg{:}));
if isstruct(tmp) && isfield(tmp,'R')
R = tmp.R;
elseif isnumeric(tmp)
% load from e.g. text file
R = tmp;
else
warning('Can''t load user specified regressors in %s', ...
char(sess.multi_reg{:}));
R = [];
end
C=[C, R];
nr=size(R,2);
nq=length(Cname);
for inr=1:nr,
Cname{inr+nq}=['R',int2str(inr)];
end
end
SPM.Sess(i).C.C = C;
SPM.Sess(i).C.name = Cname;
end
% Factorial design
%-------------------------------------------------------------
if isfield(job,'fact')
if ~isempty(job.fact)
NC=length(SPM.Sess(1).U); % Number of conditions
CheckNC=1;
for i=1:length(job.fact)
SPM.factor(i).name=job.fact(i).name;
SPM.factor(i).levels=job.fact(i).levels;
CheckNC=CheckNC*SPM.factor(i).levels;
end
if ~(CheckNC==NC)
disp('Error in fmri_spec job: factors do not match conditions');
return
end
end
else
SPM.factor=[];
end
% Globals
%-------------------------------------------------------------
SPM.xGX.iGXcalc = job.global;
SPM.xGX.sGXcalc = 'mean voxel value';
SPM.xGX.sGMsca = 'session specific';
% High Pass filter
%-------------------------------------------------------------
for i = 1:numel(job.sess),
SPM.xX.K(i).HParam = job.sess(i).hpf;
end
% Autocorrelation
%-------------------------------------------------------------
SPM.xVi.form = job.cvi;
% Let SPM configure the design
%-------------------------------------------------------------
SPM = spm_fMRI_design(SPM);
%-Save SPM.mat
%-----------------------------------------------------------------------
fprintf('%-40s: ','Saving SPM configuration') %-#
if str2num(version('-release'))>=14,
save('SPM','-V6','SPM');
else
save('SPM','SPM');
end;
fprintf('%30s\n','...SPM.mat saved') %-#
my_cd(original_dir); % Change back dir
fprintf('Done\n')
return
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function vf = vfiles_stats(job)
direc = job.dir{1};
vf = {spm_select('CPath','SPM.mat',direc)};
|
github
|
spm/spm5-master
|
spm_defs.m
|
.m
|
spm5-master/spm_defs.m
| 9,319 |
utf_8
|
92fb4adf7d39d590d189b142d2912e4b
|
function spm_defs(job)
% Various deformation field utilities.
% FORMAT spm_defs(job)
% job - a job created via spm_config_defs.m and spm_jobman.m
%
% See spm_config_defs.m for more information.
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_defs.m 991 2007-11-02 14:01:28Z john $
[Def,mat] = get_comp(job.comp);
save_def(Def,mat,strvcat(job.ofname));
apply_def(Def,mat,strvcat(job.fnames),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));
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});
[bb0,vox0] = bbvox_from_V(sn.VG(1));
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)];
[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 [bb,vx] = bbvox_from_V(V)
% Return the default bounding box for an image volume
vx = sqrt(sum(V.mat(1:3,1:3).^2));
o = V.mat\[0 0 0 1]';
o = o(1:3)';
bb = [-vx.*(o-1) ; vx.*(V.dim(1:3)-o)];
return;
%_______________________________________________________________________
%_______________________________________________________________________
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_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 save_def(Def,mat,ofname)
% Save a deformation field as an image
if isempty(ofname), return; end;
fname = ['y_' ofname '.nii'];
dim = [size(Def{1},1) size(Def{1},2) size(Def{1},3) 1 3];
dtype = 'FLOAT32-BE';
off = 0;
scale = 1;
inter = 0;
dat = file_array(fname,dim,dtype,off,scale,inter);
N = nifti;
N.dat = dat;
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Aligned';
N.mat0_intent = 'Aligned';
N.intent.code = 'VECTOR';
N.intent.name = 'Mapping';
N.descrip = 'Deformation field';
create(N);
N.dat(:,:,:,1,1) = Def{1};
N.dat(:,:,:,1,2) = Def{2};
N.dat(:,:,:,1,3) = Def{3};
return;
%_______________________________________________________________________
%_______________________________________________________________________
function apply_def(Def,mat,fnames,intrp)
% Warp an image or series of images according to a deformation field
intrp = [intrp*[1 1 1], 0 0 0];
for i=1:size(fnames,1),
V = spm_vol(fnames(i,:));
M = inv(V.mat);
[pth,nam,ext] = spm_fileparts(fnames(i,:));
ofname = fullfile(pth,['w',nam,ext]);
Vo = struct('fname',ofname,...
'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);
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
|
spm/spm5-master
|
spm_sp.m
|
.m
|
spm5-master/spm_sp.m
| 38,364 |
utf_8
|
adb92133e990f9484e8215c6e97e5080
|
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) 2005 Wellcome Department of Imaging Neuroscience
% Jean-Baptiste Poline
% $Id: spm_sp.m 112 2005-05-04 18:20:52Z john $
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
|
spm/spm5-master
|
spm_config_dicom.m
|
.m
|
spm5-master/spm_config_dicom.m
| 5,010 |
utf_8
|
a78fea091fd42391c4ba7d36f53f0289
|
function opts = spm_config_dicom
% Configuration file for dicom import jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_dicom.m 2300 2008-10-06 11:16:30Z guillaume $
%_______________________________________________________________________
data.type = 'files';
data.name = 'DICOM files';
data.tag = 'data';
data.filter = '.*';
data.num = Inf;
data.help = {'Select the DICOM files to convert.'};
outdir.type = 'files';
outdir.name = 'Output directory';
outdir.tag = 'outdir';
outdir.filter = 'dir';
outdir.num = 1;
outdir.val = {''};
outdir.help = {[...
'Select a directory where files are written. '...
'Default is current directory.']};
root.type = 'menu';
root.name = 'Directory structure for converted files';
root.tag = 'root';
root.labels = {'Output directory: ./<StudyDate-StudyTime>', ...
'Output directory: ./<PatientID>', ...
'Output directory: ./<PatientID>/<StudyDate-StudyTime>', ...
'Output directory: ./<PatientName>', ...
'No directory hierarchy'};
root.values = {'date_time',...
'patid', 'patid_date', 'patname','flat'};
root.def = 'util.dicom.root';
root.help = {['Choose root directory of converted file tree. The options ' ...
'are:'], '',...
['* Output directory: ./<StudyDate-StudyTime>: ' ...
'Automatically determine the project name and try to ' ...
'convert into the output directory, starting with '...
'a StudyDate-StudyTime subdirectory. This option is useful if automatic '...
'project recognition fails and one wants to convert data into '...
'a project directory.'], '',...
['* Output directory: ./<PatientID>: ' ...
'Convert into the output directory, starting with '...
'a PatientID subdirectory.'], '',...
['* Output directory: ./<PatientName>: ' ...
'Convert into the output directory, starting with '...
'a PatientName subdirectory.'],...
['* No directory hierarchy: Convert all files into the output ' ...
'directory, without sequence/series subdirectories']};
format.type = 'menu';
format.name = 'Output image format';
format.tag = 'format';
format.labels = {'Two file (img+hdr) NIfTI', 'Single file (nii) NIfTI'};
format.values = {'img', 'nii'};
format.val = {'nii'};
format.help = {['DICOM conversion can create separate img and hdr files ' ...
'or combine them in one file. The single file option will ' ...
'help you save space on your hard disk, but may be ' ...
'incompatible with programs that are not NIfTI-aware.'],...
['In any case, only 3D image files will be produced.']};
icedims.type = 'menu';
icedims.name = 'Use ICEDims in filename';
icedims.tag = 'icedims';
icedims.labels = {'No','Yes'};
icedims.values = {0, 1};
icedims.val = {0};
icedims.help = {['If image sorting fails, one can try using the additional ' ...
'SIEMENS ICEDims information to create unique filenames. ' ...
'Use this only if there would be multiple volumes with '...
'exactly the same file names.']};
convopts.type = 'branch';
convopts.name = 'Conversion options';
convopts.tag = 'convopts';
convopts.val = {format,icedims};
opts.type = 'branch';
opts.name = 'DICOM Import';
opts.tag = 'dicom';
opts.val = {data,root,outdir,convopts};
opts.prog = @convert_dicom;
opts.help = {[...
'DICOM Conversion. Most scanners produce data in DICOM format. '...
'This routine attempts to convert DICOM files into SPM compatible '...
'image volumes, which are written into the current directory by '...
'default. Note that not all flavours of DICOM can be handled, as '...
'DICOM is a very complicated format, and some scanner manufacturers '...
'use their own fields, which are not in the official documentation '...
'at http://medical.nema.org/']};
% add defaults, if not already set
global defaults
if isfield(defaults,'util')
if isfield(defaults.util,'dicom')
return;
end;
end;
defaults.util.dicom.root = 'flat';
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function convert_dicom(job)
wd = pwd;
try
if ~isempty(job.outdir{:})
cd(job.outdir{:});
fprintf(' Changing directory to: %s\n', job.outdir{:});
end
catch
error('Failed to change directory. Aborting DICOM import.');
end
if job.convopts.icedims
root_dir = ['ice' job.root];
else
root_dir = job.root;
end;
hdr = spm_dicom_headers(strvcat(job.data), true);
spm_dicom_convert(hdr,'all',root_dir,job.convopts.format);
if ~isempty(job.outdir)
fprintf(' Changing back to directory: %s\n', wd);
cd(wd);
end
|
github
|
spm/spm5-master
|
spm_dicom_essentials.m
|
.m
|
spm5-master/spm_dicom_essentials.m
| 2,998 |
utf_8
|
73532b1b79cbf320fa7ba72709659e78
|
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 2300 2008-10-06 11:16:30Z guillaume $
used_fields = {...
'AcquisitionDate',...
'AcquisitionNumber',...
'AcquisitionTime',...
'BitsAllocated',...
'BitsStored',...
'CSAImageHeaderInfo',...
'Columns',...
'EchoNumbers',...
'EchoTime',...
'Filename',...
'FlipAngle',...
'HighBit',...
'ImageOrientationPatient',...
'ImagePositionPatient',...
'ImageType',...
'InstanceNumber',...
'MRAcquisitionType',...
'MagneticFieldStrength',...
'Modality',...
'PatientID',...
'PatientsName',...
'PixelRepresentation',...
'PixelSpacing',...
'Private_0029_1210',...
'ProtocolName',...
'RepetitionTime',...
'RescaleIntercept',...
'RescaleSlope',...
'Rows',...
'SOPClassUID',...
'SamplesperPixel',...
'ScanningSequence',...
'SequenceName',...
'SeriesDescription',...
'SeriesInstanceUID',...
'SeriesNumber',...
'SliceNormalVector',...
'SliceThickness',...
'SpacingBetweenSlices',...
'StartOfPixelData',...
'StudyDate',...
'StudyTime',...
'TransferSyntaxUID',...
'VROfPixelData'};
fnames = fieldnames(hdr0);
for i=1:numel(used_fields),
if any(strmatch(used_fields{i},fnames,'exact')),
hdr1.(used_fields{i}) = hdr0.(used_fields{i});
end
end
if isfield(hdr1,'Private_0029_1210'),
Private_0029_1210_fields = {...
'Columns',...
'Rows',...
'ImageOrientationPatient',...
'ImagePositionPatient',...
'SliceThickness',...
'PixelSpacing'};
hdr1.Private_0029_1210 = ...
getfields(hdr1.Private_0029_1210,...
Private_0029_1210_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
|
spm/spm5-master
|
spm_config_factorial_design.m
|
.m
|
spm5-master/spm_config_factorial_design.m
| 68,674 |
utf_8
|
7f82700d08ffaff7cd9e0dabd4c20de9
|
function conf = spm_config_factorial_design
% Configuration file for specification of factorial designs
%
% This function 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 (via the Estimate button) which estimates the design.
% Inference on these estimated parameters is then handled by the SPM
% results section.
%
% This function comprises two parts. The first defines
% the user interface and the second sets up the necessary SPM structures.
% The second part has been largely cannibalised from spm_spm_ui.m which
% we have retained for developmental continuity.
%
% It has in common with spm_spm_ui.m its use of the I factor matrix,
% the H,C,B,G design matrix partitions, the sF,sCFI,CFIforms,sCC,CCforms,
% sGXcalc,sGloNorm,sGMsca option definition variables and use of the
% functions spm_DesMtx.m, spm_meanby.m and spm_non_sphericity.m.
%
% It departs from spm_spm_ui.m in that it does not use the design
% definition data structure D. Also, it uses the new SPM.factor field,
% which for the case of full factorial designs, is used to automatically
% generate contrasts testing for main effects and interactions.
%
% This function departs from spm_spm_ui.m in that it does not provide
% the same menu of design options (these were hardcoded in D). Instead it
% provides a number of options for simple designs (1) One-sample t-test,
% (2) Two-sample t-test, (3) Paired t-test and (4) Multiple regression.
% Two facilities are provided for specifying more complicated designs
% (5) Full-factorial and (6) Flexible-factorial. These should be able to
% specify all design options (and more) that were available in SPM2.
% For each of these design types one can additionally specify regressors using the
% `covariates' option.
%
% Options (5) and (6) differ in the
% efficiency (eg. number of key strokes/button presses) with which a given
% design can be specified. For example, one-way ANOVAs can be specified
% using either option, but (5) is usually more efficient.
%
% Full-factorial designs
% ______________________
%
% This option is best used when you wish to test for all
% main effects and interactions in one-way, two-way or three-way ANOVAs.
%
% Design specification proceeds in 2 stages. Firstly, by creating new
% factors and specifying the
% number of levels and name for each. Nonsphericity, ANOVA-by-factor (for PET data)
% and
% scaling options (for PET data) can also be specified at this stage. Secondly,
% scans are assigned separately to each cell. This accomodates unbalanced designs.
%
% For example, if you wish to test for a main effect in the population
% from which your subjects are drawn
% and have modelled that effect at the first level using K basis functions
% (eg. K=3 informed basis functions) you can use a one-way ANOVA with K-levels.
% Create a single factor with K levels and then assign the data to each
% cell eg. canonical, temporal derivative and dispersion derivative cells,
% where each cell is assigned scans from multiple subjects.
%
% SPM will automatically generate the contrasts necessary to test for all
% main effects and interactions
%
% Flexible-factorial designs
% __________________________
%
% In this option the design matrix is created a block at a time. You can
% decide whether you wish each block to be a main effect or a (two-way)
% interaction.
%
% This option is best used for one-way, two-way or
% three-way ANOVAs but where you do not wish to test for all possible
% main effects and interactions. This is perhaps most useful for PET
% where there is usually not enough data to test for all possible
% effects. Or for 3-way ANOVAs where you do not wish to test for all
% of the two-way interactions. A typical example here would be a
% group-by-drug-by-task analysis where, perhaps, only (i) group-by-drug or
% (ii) group-by-task interactions are of interest. In this case it is only
% necessary to have two-blocks in the design matrix - one for each
% interaction. The three-way interaction can then be tested for using a
% contrast that computes the difference between (i) and (ii).
%
% Design specification then proceeds in 3 stages. Firstly, factors
% are created and names specified for each. Nonsphericity, ANOVA-by-factor and
% scaling options can also be specified at this stage.
%
% Secondly, a list of
% scans is produced along with a factor matrix, I. This is an nscan x 4 matrix
% of factor level indicators (see xX.I below). The first factor must be
% 'replication' but the other factors can be anything. Specification of I and
% the scan list can be achieved in
% one of two ways (a) the 'Specify All' option allows I
% to be typed in at the user interface or (more likely) loaded in from the matlab
% workspace. All of the scans are then selected in one go. (b) the
% 'Subjects' option allows you to enter scans a subject at a time. The
% corresponding experimental conditions (ie. levels of factors) are entered
% at the same time. SPM will then create the factor matrix I. This style of
% interface is similar to that available in SPM2.
%
% Thirdly, the design matrix is built up a block at a time. Each block
% can be a main effect or a (two-way) interaction.
%
%
% ----------------------------------------------------------------------
%
% 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.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%
%
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Will Penny
% $Id: spm_config_factorial_design.m 1601 2008-05-12 14:11:02Z guillaume $
% Define inline types.
%-----------------------------------------------------------------------
entry = inline(['struct(''type'',''entry'',''name'',name,'...
'''tag'',tag,''strtype'',strtype,''num'',num,''help'',hlp)'],...
'name','tag','strtype','num','hlp');
files = inline(['struct(''type'',''files'',''name'',name,'...
'''tag'',tag,''filter'',fltr,''num'',num,''help'',hlp)'],...
'name','tag','fltr','num','hlp');
mnu = inline(['struct(''type'',''menu'',''name'',name,'...
'''tag'',tag,''labels'',{labels},''values'',{values},''help'',hlp)'],...
'name','tag','labels','values','hlp');
branch = inline(['struct(''type'',''branch'',''name'',name,'...
'''tag'',tag,''val'',{val},''help'',hlp)'],...
'name','tag','val','hlp');
repeat = inline(['struct(''type'',''repeat'',''name'',name,'...
'''tag'',tag,''values'',{values},''help'',hlp)'],...
'name','tag','values','hlp');
choice = inline(['struct(''type'',''choice'',''name'',name,'...
'''tag'',tag,''values'',{values},''help'',hlp)'],...
'name','tag','values','hlp');
%-----------------------------------------------------------------------
sp_text = [' ',...
' '];
%-------------------------------------------------------------------------
% Covariates for general use
iCFI = mnu('Interactions','iCFI',{'None','With Factor 1',...
'With Factor 2','With Factor 3'},{1,2,3,4},'');
iCFI.val={1};
p1 = ['For each covariate you have defined, there is an opportunity to ',...
'create an additional regressor that is the interaction between the ',...
'covariate and a chosen experimental factor. '];
iCFI.help={p1,sp_text};
iCC = mnu('Centering','iCC',{'Overall mean','Factor 1 mean',...
'Factor 2 mean','Factor 3 mean','No centering',...
'User specified value','As implied by ANCOVA',...
'GM'},{1,2,3,4,5,6,7,8},'');
iCC.val={1};
p1 = ['The appropriate centering option is usually the one that ',...
'corresponds to the interaction chosen, and ensures that main ',...
'effects of the interacting factor aren''t affected by the covariate. ',...
'You are advised to choose this option, unless you have other ',...
'modelling considerations. '];
iCC.help={p1,sp_text};
cname = entry('Name','cname','s', [1 Inf],'Name of covariate');
c = entry('Vector','c','e',[Inf 1],'Vector of covariate values');
cov = branch('Covariate','cov',{c,cname,iCFI,iCC},'Covariate');
cov.help = {'Add a new covariate to your experimental design'};
covs = repeat('Covariates','covariates',{cov},'');
p1 = ['This option allows for the specification of covariates and ',...
'nuisance variables. Unlike SPM94/5/6, where the design was ',...
'partitioned into effects of interest and nuisance effects ',...
'for the computation of adjusted data and the F-statistic ',...
'(which was used to thresh out voxels where there appeared to ',...
'be no effects of interest), SPM5 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. '];
covs.help={p1,sp_text};
%-------------------------------------------------------------------------
% Covariates for multiple regression
miCC = mnu('Centering','iCC',{'Overall mean','No centering'},...
{1,5},'');
miCC.val= {1};
mcov = branch('Covariate','mcov',{c,cname,miCC},'Covariate');
mcov.help = {'Add a new covariate to your experimental design'};
mcovs = repeat('Covariates','covariates',{mcov},'Covariates');
incint = mnu('Intercept','incint',{'Include Intercept','Omit Intercept'},{1,0},'');
incint.val = {1};
p1=['By default, an intercept is always added to the model. If the ',...
'covariates supplied by the user include a constant effect, the ',...
'intercept may be omitted.'];
incint.help = {p1,sp_text};
%-----------------------------------------------------------------------
% Specify names of factors, numbers of levels and statistical dependencies
name = entry('Name','name','s',[1 Inf],'');
name.val = {'Covariate'};
p1=['Enter name of covariate eg. reaction time'];
name.help={p1};
val = entry('Value','val','e',[Inf 1],'');
val.help={['Enter the vector of covariate values']};
variance = mnu('Variance','variance',{'Equal','Unequal'},{0,1},'');
variance.val={1};
p1=['By default, the measurements in each level are assumed to have unequal variance. '];
p2=['This violates the assumption of ''sphericity'' and is therefore an example of ',...
'''non-sphericity''.'];
p3=['This can occur, for example, in a 2nd-level analysis of variance, one ',...
'contrast may be scaled differently from another. Another example would ',...
'be the comparison of qualitatively different dependent variables ',...
'(e.g. normals vs. patients). Different variances ',...
'(heteroscedasticy) induce different error covariance components that ',...
'are estimated using restricted maximum likelihood (see below).'];
p4=['Restricted Maximum Likelihood (REML): The ensuing covariance components ',...
'will be estimated using ReML in spm_spm (assuming the same for all ',...
'responsive voxels) and used to adjust the ',...
'statistics and degrees of freedom during inference. By default spm_spm ',...
'will use weighted least squares to produce Gauss-Markov or Maximum ',...
'likelihood estimators using the non-sphericity structure specified at this ',...
'stage. The components will be found in SPM.xVi and enter the estimation ',...
'procedure exactly as the serial correlations in fMRI models.'];
variance.help = {p1,sp_text,p2,sp_text,p3,sp_text,p4,sp_text};
dept = mnu('Independence','dept',{'Yes','No'},{0,1},'');
dept.val={0};
p1=['By default, the measurements are assumed to be independent between levels. '];
p2=['If you change this option to allow for dependencies, this will violate ',...
'the assumption of sphericity. It would therefore be an example ',...
'of non-sphericity. One such example would be where you had repeated ',...
'measurements from the same subjects - it may then be the case that, over ',...
'subjects, measure 1 is correlated to measure 2. '];
dept.help = {p1,sp_text,p2,sp_text,p4,sp_text};
fname.type = 'entry';
fname.name = 'Name';
fname.tag = 'name';
fname.strtype = 's';
fname.num = [1 1];
fname.help = {'Name of factor, eg. ''Repetition'' '};
levels = entry('Levels','levels','e',[Inf 1],'');
p1=['Enter number of levels for this factor, eg. 2'];
levels.help ={p1};
gmsca = mnu('Grand mean scaling','gmsca',...
{'No','Yes'},{0,1},'');
gmsca.val={0};
p0=['This option is only used for PET data.'];
p1=['Selecting YES will specify ''grand mean scaling by factor'' which could ',...
'be eg. ''grand mean scaling by subject'' if the factor is ''subject''. '];
p2 =['Since differences between subjects may be due to gain and sensitivity ',...
'effects, AnCova by subject could be combined with "grand mean scaling ',...
'by subject" to obtain a combination of between subject proportional ',...
'scaling and within subject AnCova. '];
gmsca.help={p0,sp_text,p1,sp_text,p2,sp_text};
ancova = mnu('ANCOVA','ancova',...
{'No','Yes'},{0,1},'');
ancova.val={0};
p1=['Selecting YES will specify ''ANCOVA-by-factor'' regressors. ',...
'This includes eg. ''Ancova by subject'' or ''Ancova by effect''. ',...
'These options allow eg. different subjects ',...
'to have different relationships between local and global measurements. '];
ancova.help={p0,sp_text,p1,sp_text};
factor.type = 'branch';
factor.name = 'Factor';
factor.tag = 'fact';
factor.val = {fname,levels,dept,variance,gmsca,ancova};
factor.help = {'Add a new factor to your experimental design'};
factors.type = 'repeat';
factors.name = 'Factors';
factors.tag = 'factors';
factors.values = {factor};
factors.num = [1 Inf];
p1 = ['Specify your design a factor at a time. '];
factors.help ={p1,sp_text};
%-------------------------------------------------------------------------
% Associate each cell in factorial design with a list of images
scans = files('Scans','scans','image',[1 Inf],'Select scans');
scans.help = {[...
'Select the images for this cell. They must all have the same ',...
'image dimensions, orientation, voxel size etc.']};
levels = entry('Levels','levels','e',[Inf 1],'');
p1=['Enter a vector or scalar that specifies which cell in the factorial ',...
'design these images belong to. The length of this vector should '...
'correspond to the number of factors in the design'];
p2=['For example, length 2 vectors should be used for two-factor designs ',...
'eg. the vector [2 3] specifies the cell corresponding to the 2nd-level of the first ',...
'factor and the 3rd level of the 2nd factor.'];
levels.help ={p1,sp_text,p2,sp_text};
icell.type = 'branch';
icell.name = 'Cell';
icell.tag = 'icell';
icell.val = {levels,scans};
icell.help = {'Enter data for a cell in your design'};
cells.type = 'repeat';
cells.name = 'Specify cells';
cells.tag = 'cells';
cells.values = {icell};
cells.num = [1 Inf];
p1 = ['Enter the scans a cell at a time'];
cells.help={p1,sp_text};
%-------------------------------------------------------------------------
% Create a design block-by-block
fac.type = 'branch';
fac.name = 'Factor';
fac.tag = 'fac';
fac.val = {fname,dept,variance,gmsca,ancova};
p1=['Add a new factor to your design.'];
p2=['If you are using the ''Subjects'' option to specify your scans ',...
'and conditions, you may wish to make use of the following facility. ',...
'There are two reserved words for the names of factors. These are ',...
'''subject'' and ''repl'' (standing for replication). If you use these ',...
'factor names then SPM can automatically create replication and/or ',...
'subject factors without you having to type in an extra entry in the ',...
'condition vector.'];
p3=['For example, if you wish to model Subject and Task effects (two factors), ',...
'under Subjects->Subject->Conditions you can type in simply ',...
'[1 2 1 2] to specify eg. just the ''Task'' factor level. You do not need to ',...
'eg. for the 4th subject enter the matrix [1 4; 2 4; 1 4; 2 4]. '];
fac.help = {p1,sp_text,p2,sp_text,p3,sp_text};
facs.type = 'repeat';
facs.name = 'Factors';
facs.tag = 'facs';
facs.values = {fac};
facs.num = [1 Inf];
p1=['Specify your design a factor at a time.'];
facs.help={p1,sp_text};
fnum = entry('Factor number','fnum','e',[Inf 1],'');
p1=['Enter the number of the factor.'];
fnum.help ={p1};
fnums = entry('Factor numbers','fnums','e',[2 1],'');
p1=['Enter the numbers of the factors of this (two-way) interaction.'];
fnums.help ={p1};
fmain.type = 'branch';
fmain.name = 'Main effect';
fmain.tag = 'fmain';
fmain.val = {fnum};
fmain.help = {'Add a main effect to your design matrix'};
inter.type = 'branch';
inter.name = 'Interaction';
inter.tag = 'inter';
inter.val = {fnums};
inter.help = {'Add an interaction to your design matrix'};
maininters.type = 'repeat';
maininters.name = 'Main effects & Interactions';
maininters.num = [1 Inf];
maininters.tag = 'maininters';
maininters.values = {fmain, inter};
scans = files('Scans','scans','image',[1 Inf],'Select scans');
scans.help = {[...
'Select the images to be analysed. They must all have the same ',...
'image dimensions, orientation, voxel size etc.']};
imatrix = entry('Factor matrix','imatrix','e',[Inf Inf],'');
imatrix.val = {0};
imatrix.help = {['Specify factor/level matrix as a nscan-by-4 matrix. Note' ...
' that the first row of I is reserved for the internal' ...
' replication factor and must not be used for experimental' ...
' factors.']};
specall.type = 'branch';
specall.name = 'Specify all';
specall.tag = 'specall';
specall.val = {scans,imatrix};
p1=['Specify (i) all scans in one go and (ii) all conditions using a ',...
'factor matrix, I. This option is for ''power users''. The matrix ',...
'I must have four columns and as ',...
'as many rows as scans. It has the same format as SPM''s internal ',...
'variable SPM.xX.I. '];
p2=['The first column of I denotes the replication number and entries in' ...
' the other columns denote the levels of each experimental factor.'];
p3=['So, for eg. a two-factor design the first column ',...
'denotes the replication number and columns two and three have entries ',...
'like 2 3 denoting the 2nd level of the first factor and 3rd level of ',...
'the second factor. The 4th column in I would contain all 1s.'];
specall.help = {p1,sp_text,p2,sp_text,p3};
conds = entry('Conditions','conds','e',[Inf Inf],'');
fsubject.type = 'branch';
fsubject.name = 'Subject';
fsubject.tag = 'fsubject';
fsubject.val = {scans,conds};
fsubject.help = {'Enter data and conditions for a new subject'};
fsubjects.type = 'repeat';
fsubjects.name = 'Subjects';
fsubjects.tag = 'fsubjects';
fsubjects.values = {fsubject};
fsubjects.num = [1 Inf];
fsuball.type = 'choice';
fsuball.name = 'Specify Subjects or all Scans & Factors';
fsuball.tag = 'fsuball';
fsuball.values = {fsubjects specall};
%-------------------------------------------------------------------------
% Two-sample t-test
scans1 = files('Group 1 scans','scans1','image',[1 Inf],'Select scans');
scans1.help = {[...
'Select the images from sample 1. They must all have the same ',...
'image dimensions, orientation, voxel size etc.']};
scans2 = files('Group 2 scans','scans2','image',[1 Inf],'Select scans');
scans2.help = {[...
'Select the images from sample 2. They must all have the same ',...
'image dimensions, orientation, voxel size etc.']};
%-------------------------------------------------------------------------
% Paired t-test
pscans = files('Scans [1,2]','scans','image',[1 2],'Select scans');
pscans.help = {[...
'Select the pair of images. ']};
pair.type = 'branch';
pair.name = 'Pair';
pair.tag = 'pair';
pair.val = {pscans};
pair.help = {'Add a new pair of scans to your experimental design'};
pairs.type = 'repeat';
pairs.name = 'Pairs';
pairs.tag = 'pairs';
pairs.num = [1 Inf];
pairs.values = {pair};
p1 = [' ',...
' '];
pairs.help ={p1,sp_text};
%-------------------------------------------------------------------------
% One sample t-test
t1scans = files('Scans','scans','image',[1 Inf],'Select scans');
t1scans.help = {[...
'Select the images. They must all have the same ',...
'image dimensions, orientation, voxel size etc.']};
%-------------------------------------------------------------------------
% Design menu
t1 = branch('One-sample t-test','t1',...
{t1scans},'');
t2 = branch('Two-sample t-test','t2',...
{scans1,scans2,dept,variance,gmsca,ancova},'');
pt = branch('Paired t-test','pt',...
{pairs,dept,variance,gmsca,ancova},'');
mreg = branch('Multiple regression','mreg',...
{t1scans,mcovs,incint},'');
fblock = branch('Flexible factorial','fblock',...
{facs,fsuball,maininters},'');
pb1 = ['Create a design matrix a block at a time by specifying which ',...
'main effects and interactions you wish to be included.'];
pb2=['This option is best used for one-way, two-way or ',...
'three-way ANOVAs but where you do not wish to test for all possible ',...
'main effects and interactions. This is perhaps most useful for PET ',...
'where there is usually not enough data to test for all possible ',...
'effects. Or for 3-way ANOVAs where you do not wish to test for all ',...
'of the two-way interactions. A typical example here would be a ',...
'group-by-drug-by-task analysis where, perhaps, only (i) group-by-drug or ',...
'(ii) group-by-task interactions are of interest. In this case it is only ',...
'necessary to have two-blocks in the design matrix - one for each ',...
'interaction. The three-way interaction can then be tested for using a ',...
'contrast that computes the difference between (i) and (ii).'];
pb3=['Design specification then proceeds in 3 stages. Firstly, factors ',...
'are created and names specified for each. Nonsphericity, ANOVA-by-factor and ',...
'scaling options can also be specified at this stage.'];
pb4=['Secondly, a list of ',...
'scans is produced along with a factor matrix, I. This is an nscan x 4 matrix ',...
'of factor level indicators (see xX.I below). The first factor must be ',...
'''replication'' but the other factors can be anything. Specification of I and ',...
'the scan list can be achieved in ',...
'one of two ways (a) the ''Specify All'' option allows I ',...
'to be typed in at the user interface or (more likely) loaded in from the matlab ',...
'workspace. All of the scans are then selected in one go. (b) the ',...
'''Subjects'' option allows you to enter scans a subject at a time. The ',...
'corresponding experimental conditions (ie. levels of factors) are entered ',...
'at the same time. SPM will then create the factor matrix I. This style of ',...
'interface is similar to that available in SPM2.'];
pb5=['Thirdly, the design matrix is built up a block at a time. Each block ',...
'can be a main effect or a (two-way) interaction. '];
fblock.help={pb1,sp_text,pb2,sp_text,pb3,sp_text,pb4,sp_text,pb5,sp_text};
fd = branch('Full factorial','fd',...
{factors,cells},'');
pfull1=['This option is best used when you wish to test for all ',...
'main effects and interactions in one-way, two-way or three-way ANOVAs. ',...
'Design specification proceeds in 2 stages. Firstly, by creating new ',...
'factors and specifying the ',...
'number of levels and name for each. Nonsphericity, ANOVA-by-factor and ',...
'scaling options can also be specified at this stage. Secondly, scans are ',...
'assigned separately to each cell. This accomodates unbalanced designs.'];
pfull2=['For example, if you wish to test for a main effect in the population ',...
'from which your subjects are drawn ',...
'and have modelled that effect at the first level using K basis functions ',...
'(eg. K=3 informed basis functions) you can use a one-way ANOVA with K-levels. ',...
'Create a single factor with K levels and then assign the data to each ',...
'cell eg. canonical, temporal derivative and dispersion derivative cells, ',...
'where each cell is assigned scans from multiple subjects.'];
pfull3 = ['SPM will also automatically generate ',...
'the contrasts necessary to test for all main effects and interactions. '];
fd.help={pfull1,sp_text,pfull2,sp_text,pfull3,sp_text};
des = choice('Design','des',...
{t1,t2,pt,mreg,fd,fblock},'');
%-------------------------------------------------------------------------
% Masking options
im = mnu('Implicit Mask','im',{'Yes','No'},{1,0},'');
im.val={1};
p1=['An "implicit mask" is a mask implied by a particular voxel ',...
'value. Voxels with this mask value are excluded from the ',...
'analysis. '];
p2=['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). '];
p3=['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.'];
p4=['By default, an implicit mask is used. '];
im.help = {p1,sp_text,p2,sp_text,p3,sp_text,p4,sp_text};
em = files('Explicit Mask','em','image',[0 1],'');
em.val={''};
em.help = {['Select an explicit mask ']};
p1=['Explicit masks are other images containing (implicit) masks ',...
'that are to be applied to the current analysis.'];
p2=['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. '];
p3=['Explicit mask images can have any orientation and voxel/image ',...
'size. Nearest neighbour interpolation of a mask image is used if ',...
'the voxel centers of the input images do not coincide with that ',...
'of the mask image.'];
em.help = {p1,sp_text,p2,sp_text,p3,sp_text};
tm_none.type = 'const';
tm_none.name = 'None';
tm_none.tag = 'tm_none';
tm_none.val = {[]};
tm_none.help = {'No threshold masking'};
athresh = entry('Threshold','athresh','e',[1 1],'');
athresh.val={100};
p1=['Enter the absolute value of the threshold.'];
athresh.help = {p1,sp_text};
tma = branch('Absolute','tma',...
{athresh},'');
p1=['Images are thresholded at a given value and ',...
'only voxels at which all images exceed the threshold are included. '];
p2=['This option allows you to specify the absolute value of the threshold.'];
tma.help = {p1,sp_text,p2,sp_text};
p2=['By default, Relative Threshold Masking is turned off. '];
rselect.help = {p1,sp_text,p2,sp_text};
rthresh = entry('Threshold','rthresh','e',[1 1],'');
rthresh.val={0.8};
p1=['Enter the threshold as a proportion of the global value'];
rthresh.help = {p1,sp_text};
tmr = branch('Relative','tmr',...
{rthresh},'');
p1=['Images are thresholded at a given value and ',...
'only voxels at which all images exceed the threshold are included. '];
p2=['This option allows you to specify the value of the threshold ',...
'as a proportion of the global value. '];
tmr.help = {p1,sp_text,p2,sp_text};
tm = choice('Threshold masking','tm',...
{tm_none,tma,tmr},'');
p1=['Images are thresholded at a given value and ',...
'only voxels at which all images exceed the threshold are included. '];
tm.help={p1,sp_text};
masking = branch('Masking','masking',...
{tm,im,em},'');
p1=['The mask specifies the voxels within the image volume which are to be ',...
'assessed. SPM supports three methods of masking (1) Threshold, ',...
'(2) Implicit and (3) Explicit. The volume analysed ',...
'is the intersection of all masks.'];
masking.help={p1,sp_text};
%-------------------------------------------------------------------------
% Global calculation
global_uval = entry('Global values','global_uval','e',[Inf 1],'');
p1=['Enter the vector of global values'];
global_uval.val={0};
global_uval.help={p1,sp_text};
g_user = branch('User','g_user',{global_uval},'');
g_user.help={'User defined global effects (enter your own ',...
'vector of global values)'};
g_mean.type = 'const';
g_mean.name = 'Mean';
g_mean.tag = 'g_mean';
g_mean.val = {[]};
p1=['SPM standard mean voxel value'];
p2=['This defines the global mean via a two-step process. Firstly, the overall ',...
'mean is computed. Voxels with values less than 1/8 of this value are then ',...
'deemed extra-cranial and get masked out. The mean is then recomputed on the ',...
'remaining voxels.'];
g_mean.help = {p1,sp_text,p2,sp_text};
g_omit.type = 'const';
g_omit.name = 'Omit';
g_omit.tag = 'g_omit';
g_omit.val = {[]};
g_omit.help = {'Omit'};
globalc = choice('Global calculation','globalc',...
{g_omit,g_user,g_mean},'');
p1=['There are three methods for estimating global effects ',...
'(1) Omit (assumming no other options requiring the global value chosen) ',...
'(2) User defined (enter your own vector of global values) ',...
'(3) Mean: SPM standard mean voxel value (within per image fullmean/8 mask) '];
globalc.help={p0,sp_text,p1,sp_text};
%-------------------------------------------------------------------------
% Global options
gmsca_no.type = 'const';
gmsca_no.name = 'No';
gmsca_no.tag = 'gmsca_no';
gmsca_no.val = {[]};
gmsca_no.help = {'No overall grand mean scaling'};
gmscv = entry('Grand mean scaled value','gmscv','e',[Inf 1],'');
gmscv.val={50};
p1=['The default value of 50, scales the global flow to a physiologically ',...
'realistic value of 50ml/dl/min.'];
gmscv.help={p1,sp_text};
gmsca_yes=branch('Yes','gmsca_yes',{gmscv},'');
p1 =['Scaling of the overall grand mean simply ',...
'scales all the data by a common factor such that the mean of all the ',...
'global values is the value specified. For qualitative data, this puts ',...
'the data into an intuitively accessible scale without altering the ',...
'statistics. '];
gmsca_yes.help={p1,sp_text};
gmsca = choice('Overall grand mean scaling','gmsca',...
{gmsca_no,gmsca_yes},'');
p2=['When proportional scaling global normalisation is used ',...
'each image is separately scaled such that it''s global ',...
'value is that specified (in which case the grand mean is also ',...
'implicitly scaled to that value). ',...
'So, to proportionally scale each image so that its global value is ',...
'eg. 20, select <Yes> then type in 20 for the grand mean scaled value.'];
p3=['When using AnCova or no global ',...
'normalisation, with data from different subjects or sessions, an ',...
'intermediate situation may be appropriate, and you may be given the ',...
'option to scale group, session or subject grand means separately. '];
gmsca.help={p1,sp_text,p2,sp_text,p3,sp_text};
glonorm = mnu('Normalisation','glonorm',...
{'None','Proportional','ANCOVA'},{1,2,3},'');
glonorm.val={1};
p1 = ['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. '];
p2=['''Ancova by subject'' or ''Ancova by effect'' options are implemented ',...
'using the ANCOVA options provided where each experimental factor ',...
'(eg. subject or effect), is defined. These allow eg. different subjects ',...
'to have different relationships between local and global measurements. '];
p3 =['Since differences between subjects may be due to gain and sensitivity ',...
'effects, AnCova by subject could be combined with "grand mean scaling ',...
'by subject" (an option also provided where each experimental factor is ',...
'originally defined) to obtain a combination of between subject proportional ',...
'scaling and within subject AnCova. '];
glonorm.help={p1,sp_text,p2,sp_text,p3,sp_text};
globalm = branch('Global normalisation','globalm',...
{gmsca,glonorm},'');
globalm.help={p0,sp_text,p1,sp_text,p2,sp_text,p3,sp_text};
%-------------------------------------------------------------------------
% Directory
cdir = files('Directory','dir','dir',1,'');
cdir.help = {[...
'Select a directory where the SPM.mat file containing the ',...
'specified design matrix will be written.']};
%-------------------------------------------------------------------------
% Main routine
conf = branch('Factorial design specification','factorial_design',...
{des,covs,masking,globalc,globalm,cdir},'');
p1=['This interface is used for setting up analyses of PET data. It is also ',...
'used for ''2nd level'' or ''random effects'' analysis which allow ',...
'one to make a population inference. First level models can be used to produce ',...
'appropriate summary data, which can then be used as raw data for a second-level ',...
'analysis. For example, a simple t-test on contrast images from the first-level ',...
'turns out to be a random-effects analysis with random subject effects, inferring ',...
'for the population based on a particular sample of subjects.'];
p2=['This interface configures the design matrix, describing the general ',...
'linear model, data specification, and other parameters necessary for ',...
'the statistical analysis. These parameters are saved in a ',...
'configuration file (SPM.mat), which can then be ',...
'passed on to spm_spm.m which estimates the design. This is achieved by ',...
'pressing the ''Estimate'' button. Inference on these ',...
'estimated parameters is then handled by the SPM results section. '];
p3=['A separate interface handles design configuration ',...
'for fMRI time series.'];
p4=['Various data and parameters need to be supplied to specify the design ',...
'(1) the image files, (2) indicators of the corresponding condition/subject/group ',...
'(2) any covariates, nuisance variables, or design matrix partitions ',...
'(3) the type of global normalisation (if any) ',...
'(4) grand mean scaling options ',...
'(5) thresholds and masks defining the image volume to analyse. ',...
'The interface supports a comprehensive range of options for all these parameters.'];
conf.help={p1,sp_text,p2,sp_text,p3,sp_text,p4,sp_text};
conf.prog = @run_stats;
conf.vfiles = @vfiles_stats;
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function vf = vfiles_stats(job)
direc = job.dir{1};
vf = {fullfile(direc,'SPM.mat')};
% Should really create a few vfiles for beta images etc here as well.
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function run_stats(job)
spm_defaults;
original_dir = pwd;
cd(job.dir{1});
%-Ask about overwriting files from previous analyses...
%-------------------------------------------------------------------
if exist(fullfile(job.dir{1},'SPM.mat'),'file')
str = { 'Current directory contains existing SPM file:',...
'Continuing will overwrite existing file!'};
if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);
fprintf('%-40s: %30s\n\n',...
'Abort... (existing SPM file)',spm('time'));
return
end
end
% If we've gotten to this point we're committed to overwriting files.
% Delete them so we don't get stuck in spm_spm
%------------------------------------------------------------------------
files = {'^mask\..{3}$','^ResMS\..{3}$','^RPV\..{3}$',...
'^beta_.{4}\..{3}$','^con_.{4}\..{3}$','^ResI_.{4}\..{3}$',...
'^ess_.{4}\..{3}$', '^spm\w{1}_.{4}\..{3}$'};
for i=1:length(files)
j = spm_select('List',pwd,files{i});
for k=1:size(j,1)
spm_unlink(deblank(j(k,:)));
end
end
%-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', '{sF{1}}';... %-2
'I(:,2)', 'FxC', '{sF{2}}';... %-3
'I(:,3)', 'FxC', '{sF{3}}';... %-4
'I(:,4)', 'FxC', '{sF{4}}';... %-5
'I(:,[4,2])', 'FxC', '{sF{4},sF{2}}';... %-6
'I(:,[4,3])', 'FxC', '{sF{4},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 calculation options (GXcalc)
sGXcalc = { 'omit';... %-1
'user specified';... %-2
'mean voxel value (within per image fullmean/8 mask)'}; %-3
%-Global normalization options (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
% Conditions of no interest defaults
B=[];
Bnames={};
switch strvcat(fieldnames(job.des)),
case 't1',
% One sample t-test
DesName='One sample t-test';
P=job.des.t1.scans;
n=length(P);
I=[1:n]';
I=[I,ones(n,3)];
[H,Hnames]=spm_DesMtx(I(:,2),'-','mean');
SPM.factor(1).name='Group';
SPM.factor(1).levels=1;
SPM.factor(1).variance=0;
SPM.factor(1).dept=0;
case 't2',
% Two-sample t-test
DesName='Two-sample t-test';
P=job.des.t2.scans1;
n1=length(job.des.t2.scans1);
P=[P;job.des.t2.scans2];
n2=length(job.des.t2.scans2);
I=[];
I=[1:n1]';
I=[I;[1:n2]'];
I=[I,[ones(n1,1);2*ones(n2,1)]];
I=[I,ones(n1+n2,2)];
[H,Hnames]=spm_DesMtx(I(:,2),'-','Group');
% Names and levels
SPM.factor(1).name='Group';
SPM.factor(1).levels=2;
% Ancova options
SPM.factor(1).gmsca=job.des.t2.gmsca;
SPM.factor(1).ancova=job.des.t2.ancova;
% Nonsphericity options
SPM.factor(1).variance=job.des.t2.variance;
SPM.factor(1).dept=job.des.t2.dept;
case 'pt',
% Paired t-test
DesName='Paired t-test';
Npairs=length(job.des.pt.pair);
P=[];
for p=1:Npairs,
P=[P;job.des.pt.pair(p).scans];
end
I=ones(Npairs*2,1);
I(:,2)=kron([1:Npairs]',ones(2,1));
I(:,3)=kron(ones(Npairs,1),[1 2]');
I(:,4)=I(:,1);
[H,Hnames]=spm_DesMtx(I(:,2),'-','Subject');
[B,Bnames]=spm_DesMtx(I(:,3),'-','Condition');
% Names and levels
SPM.factor(1).name='Subject';
SPM.factor(1).levels=Npairs;
SPM.factor(2).name='Condition';
SPM.factor(2).levels=2;
% Ancova options
SPM.factor(1).gmsca=0;
SPM.factor(1).ancova=0;
SPM.factor(2).gmsca=job.des.pt.gmsca;
SPM.factor(2).ancova=job.des.pt.ancova;
% Nonsphericity options
SPM.factor(1).variance=0;
SPM.factor(1).dept=0;
SPM.factor(2).variance=job.des.pt.variance;
SPM.factor(2).dept=job.des.pt.dept;
case 'mreg',
% Multiple regression
DesName='Multiple regression';
P=job.des.mreg.scans;
n=length(P);
I=[1:n]';
I=[I,ones(n,3)];
% Names and levels
SPM.factor(1).name='';
SPM.factor(1).levels=1;
% Nonsphericity options
SPM.factor(1).variance=0;
SPM.factor(1).dept=0;
H=[];Hnames=[];
if job.des.mreg.incint==0
B = []; Bnames = '';
else
[B,Bnames] = spm_DesMtx(I(:,2),'-','mean');
end
for i=1:length(job.des.mreg.mcov)
job.cov(end+1).c = job.des.mreg.mcov(i).c;
job.cov(end).cname = job.des.mreg.mcov(i).cname;
job.cov(end).iCC = job.des.mreg.mcov(i).iCC;
job.cov(end).iCFI = 1;
end
case 'fd',
% Full Factorial Design
DesName='Full factorial';
[I,P,H,Hnames] = spm_set_factorial_design (job);
Nfactors=length(job.des.fd.fact);
for i=1:Nfactors,
% Names and levels
SPM.factor(i).name=job.des.fd.fact(i).name;
SPM.factor(i).levels=job.des.fd.fact(i).levels;
% Ancova options
SPM.factor(i).gmsca=job.des.fd.fact(i).gmsca;
SPM.factor(i).ancova=job.des.fd.fact(i).ancova;
% Nonsphericity options
SPM.factor(i).variance=job.des.fd.fact(i).variance;
SPM.factor(i).dept=job.des.fd.fact(i).dept;
end
case 'fblock',
% Flexible factorial design
DesName='Flexible factorial';
if isfield(job.des.fblock.fsuball,'fsubject')
nsub=length(job.des.fblock.fsuball.fsubject);
% Specify design subject-by-subject
P=[];I=[];
subj=[];
for s=1:nsub,
P = [P; job.des.fblock.fsuball.fsubject(s).scans];
ns = length(job.des.fblock.fsuball.fsubject(s).scans);
cc = job.des.fblock.fsuball.fsubject(s).conds;
[ccr,ccc] = size(cc);
if ~(ccr==ns) && ~(ccc==ns)
disp(sprintf('Error for subject %d: conditions not specified for each scan',s));
return
elseif ~(ccr==ccc) && (ccc==ns)
warning('spm:transposingConditions',['Condition matrix ',...
'appears to be transposed. Transposing back to fix.\n',...
'Alert developers if it is not actually transposed.'])
cc=cc';
end
subj=[subj;s*ones(ns,1)];
% get real replications within each subject cell
[unused cci ccj] = unique(cc,'rows');
repl = zeros(ns, 1);
for k=1:max(ccj)
repl(ccj==k) = 1:sum(ccj==k);
end;
I = [I; [repl cc]];
end
nf=length(job.des.fblock.fac);
subject_factor=0;
for i=1:nf,
if strcmpi(job.des.fblock.fac(i).name,'repl')
% Copy `replications' column to create explicit `replications' factor
nI=I(:,1:i);
nI=[nI,I(:,1)];
nI=[nI,I(:,i+1:end)];
I=nI;
end
if strcmpi(job.des.fblock.fac(i).name,'subject')
% Create explicit `subject' factor
nI=I(:,1:i);
nI=[nI,subj];
nI=[nI,I(:,i+1:end)];
I=nI;
subject_factor=1;
end
end
% Re-order scans conditions and covariates into standard format
% This is to ensure compatibility with how variance components are created
if subject_factor
U=unique(I(:,2:nf+1),'rows');
Un=length(U);
Uc=zeros(Un,1);
r=1;rj=[];
for k=1:Un,
for j=1:size(I,1),
match=sum(I(j,2:nf+1)==U(k,:))==nf;
if match
Uc(k)=Uc(k)+1;
Ir(r,:)=[Uc(k),I(j,2:end)];
r=r+1;
rj=[rj;j];
end
end
end
P=P(rj); % -scans
I=Ir; % -conditions
for k=1:numel(job.cov) % -covariates
job.cov(k).c = job.cov(k).c(rj);
end;
end
else % specify all scans and factor matrix
[ns,nc]=size(job.des.fblock.fsuball.specall.imatrix);
if ~(nc==4)
disp('Error: factor matrix must have four columns');
return
end
I=job.des.fblock.fsuball.specall.imatrix;
% Get number of factors
nf=length(job.des.fblock.fac);
% nf=0;
% for i=1:4,
% if length(unique(I(:,i)))>1
% nf=nf+1;
% end
% end
P=job.des.fblock.fsuball.specall.scans;
end
% Pad out factorial matrix to cover the four canonical factors
[ns,nI]=size(I);
if nI < 4
I = [I, ones(ns,4-nI)];
end
% Sort main effects and interactions
fmain = struct('fnum',{});
inter = struct('fnums',{});
for k=1:numel(job.des.fblock.maininters)
if isfield(job.des.fblock.maininters{k},'fmain')
fmain(end+1)=job.des.fblock.maininters{k}.fmain;
elseif isfield(job.des.fblock.maininters{k},'inter')
inter(end+1)=job.des.fblock.maininters{k}.inter;
end;
end;
% Create main effects
H=[];Hnames=[];
nmain=length(fmain);
for f=1:nmain,
fcol=fmain(f).fnum;
fname=job.des.fblock.fac(fcol).name;
% Augment H partition - explicit factor numbers are 1 lower than in I matrix
[Hf,Hfnames]=spm_DesMtx(I(:,fcol+1),'-',fname);
H=[H,Hf];
Hnames=[Hnames;Hfnames];
end
% Create interactions
ni=length(inter);
for i=1:ni,
% Get the two factors for this interaction
fnums=inter(i).fnums;
f1=fnums(1);f2=fnums(2);
% Names
iname{1}=job.des.fblock.fac(f1).name;
iname{2}=job.des.fblock.fac(f2).name;
% Augment H partition - explicit factor numbers are 1 lower than in I matrix
Isub=[I(:,f1+1),I(:,f2+1)];
[Hf,Hfnames]=spm_DesMtx(Isub,'-',iname);
H=[H,Hf];
Hnames=[Hnames;Hfnames];
end
if nmain==0 && ni==0
disp('Error in design specification: You have not specified any main effects or interactions');
return
end
for i=1:nf,
% Names and levels
SPM.factor(i).name=job.des.fblock.fac(i).name;
SPM.factor(i).levels=length(unique(I(:,i+1)));
% Ancova options
SPM.factor(i).gmsca=job.des.fblock.fac(i).gmsca;
SPM.factor(i).ancova=job.des.fblock.fac(i).ancova;
% Nonsphericity options
SPM.factor(i).variance=job.des.fblock.fac(i).variance;
SPM.factor(i).dept=job.des.fblock.fac(i).dept;
end
end
nScan=size(I,1); %-#obs
% Set up data structures for non-sphericity routine
SPM.xVi.I=I;
SPM = spm_get_vc(SPM);
%-Covariate partition(s): interest (C) & nuisance (G) excluding global
%===================================================================
dstr = {'covariate','nuisance variable'};
C = []; Cnames = []; %-Covariate DesMtx partitions & names
G = []; Gnames = [];
xC = []; %-Struct array to hold raw covariates
% Covariate options:
nc=length(job.cov); % number of covariates
for i=1:nc,
c = job.cov(i).c;
cname = job.cov(i).cname;
rc = c; %-Save covariate value
rcname = cname; %-Save covariate name
if job.cov(i).iCFI==1,
iCFI=1;
else
% SPMs internal factor numbers are 1 higher than specified in user
% interface as, internally, the first factor is always `replication'
iCFI=job.cov(i).iCFI+1;
end
switch job.cov(i).iCC,
case 1
iCC=1;
case {2,3,4}
iCC=job.cov(i).iCC+1;
otherwise
iCC=job.cov(i).iCC+3;
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',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
typ = 1;
tmp = struct( 'rc',rc, 'rcname',rcname,...
'c',c, 'cname',{cname},...
'iCC',iCC, 'iCFI',iCFI,...
'type',typ,...
'cols',[1:size(c,2)] + ...
size([H,C],2) + ...
size([B,G],2)*min(typ-1,1),...
'descrip',{str} );
if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end
C = [C,c];
Cnames = [Cnames; cname];
end
clear c tI tConst tFnames
xGX=[];
xM=[];
%===================================================================
% - C O N F I G U R E D E S I G N -
%===================================================================
%-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 strvcat(fieldnames(job.globalc))
case 'g_omit',
iGXcalc=1;
case 'g_user',
iGXcalc=2;
case 'g_mean',
iGXcalc=3;
end
switch job.globalm.glonorm
case 1,
iGloNorm=9;
case 2,
iGloNorm=8;
case 3,
iGloNorm=1;
end
if SPM.factor(1).levels > 1
% Over-ride if factor-specific ANCOVA has been specified
for i=1:length(SPM.factor),
if SPM.factor(i).ancova
iGloNorm=i+2;
end
end
end
%-Analysis threshold mask
%-------------------------------------------------------------------
%-Work out available options:
% -Inf=>None, real=>absolute, complex=>proportional, (i.e. times global)
M_T = -Inf;
switch strvcat(fieldnames(job.masking.tm)),
case 'tma',
% Absolute
M_T = job.masking.tm.tma.athresh;
case 'tmr',
% Relative
M_T = job.masking.tm.tmr.rthresh*sqrt(-1);
% Need to force calculation of globals
if iGXcalc~=2, iGXcalc=3; end
case 'tm_none'
% None
M_T = -Inf;
end
if (any(iGloNorm == [1:5]) || iGloNorm==8) && iGXcalc==1
% Over-ride omission of global calculation if we need it
disp(' ');
disp(sprintf('For %s, SPM needs estimates of global activity.',sGloNorm{iGloNorm}));
disp('But you have specified to omit this computation.');
disp('SPM has overridden this omission and will automatically compute ');
disp('globals as the mean value of within brain voxels');
disp(' ');
iGXcalc=3;
end
sGXcalc = sGXcalc{iGXcalc};
switch iGXcalc,
case 1
%-Don't compute => no GMsca (iGMsca==9) or GloNorm (iGloNorm==9)
g = [];
case 2
%-User specified globals
g = job.globalc.g_user.global_uval;
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') %-#
%-Grand mean scaling options (GMsca)
%-------------------------------------------------------------------
if iGloNorm==8
iGMsca=8; %-grand mean scaling implicit in PropSca GloNorm
else
switch strvcat(fieldnames(job.globalm.gmsca))
case 'gmsca_yes',
iGMsca=1;
case 'gmsca_no',
iGMsca=9;
end
if SPM.factor(1).levels > 1
% Over-ride if factor-specific scaling has been specified
for i=1:length(SPM.factor),
if SPM.factor(i).gmsca
iGMsca=i+2;
end
end
end
end
%-Value for PropSca / GMsca (GM)
%-------------------------------------------------------------------
switch iGMsca,
case 9 %-Not scaling (GMsca or PropSca)
GM = 0; %-Set GM to zero when not scaling
case 1 %-Ask user value of GM
GM = job.globalm.gmsca.gmsca_yes.gmscv;
otherwise
if iGloNorm==8
switch strvcat(fieldnames(job.globalm.gmsca))
case 'gmsca_yes',
% Proportionally scale to this value
GM = job.globalm.gmsca.gmsca_yes.gmscv;
case 'gmsca_no',
GM = 50;
end
else
% Grand mean scaling by factor eg. scans are scaled so that the
% mean global value over each level of the factor is set to GM
GM=50;
end
end
%-If GM is zero then don't GMsca! or PropSca GloNorm
if GM==0,
iGMsca=9;
if iGloNorm==8,
iGloNorm=9;
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
%-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
%-Global centering (for AnCova GloNorm) (GC)
%-If not doing AnCova then GC is irrelevant
if ~any(iGloNorm == [1:7])
iGC = 12;
gc = [];
else
iGC = 10;
gc = 0;
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);
%-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
%-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
%-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')
M_I = job.masking.im; % Implicit mask ?
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 masking
%-------------------------------------------------------------------
if isempty(job.masking.em{:})
VM = [];
xsM.Explicit_masking = 'No';
else
VM = spm_vol(char(job.masking.em));
xsM.Explicit_masking = 'Yes';
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', {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', {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.xM = xM; % mask structure
SPM.xsDes = xsDes; % description
% Automatic contrast generation only works for 'Full factorials'
if ~strcmp(DesName,'Full factorial')
% Remove the .factor field to prevent attempted automatic contrast generation
SPM=rmfield(SPM,'factor');
end
%-Save SPM.mat and set output argument
%-------------------------------------------------------------------
fprintf('%-40s: ','Saving SPM configuration') %-#
if spm_matlab_version_chk('7') >= 0
save('SPM', 'SPM', '-V6');
else
save('SPM', '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')
cd(original_dir); % Change back dir
fprintf('Done\n')
|
github
|
spm/spm5-master
|
spm_ecat2nifti.m
|
.m
|
spm5-master/spm_ecat2nifti.m
| 16,103 |
utf_8
|
4cc89d7d1ccc8140385d57f70fb567fa
|
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) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner & Roger Gunn
% $Id: spm_ecat2nifti.m 112 2005-05-04 18:20:52Z john $
if nargin==1,
opts = struct('ext','.nii');
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
|
spm/spm5-master
|
spm_config_fmri_est.m
|
.m
|
spm5-master/spm_config_fmri_est.m
| 27,815 |
utf_8
|
c8488b2513dccecb54fef8c96cdf60fb
|
function conf = spm_config_fmri_est
% Configuration file for estimation of fMRI model
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Darren Gitelman and Will Penny
% $Id: spm_config_fmri_est.m 832 2007-06-22 11:33:31Z will $
% Define inline types.
%-----------------------------------------------------------------------
entry = inline(['struct(''type'',''entry'',''name'',name,'...
'''tag'',tag,''strtype'',strtype,''num'',num,''help'',hlp)'],...
'name','tag','strtype','num','hlp');
files = inline(['struct(''type'',''files'',''name'',name,'...
'''tag'',tag,''filter'',fltr,''num'',num,''help'',hlp)'],...
'name','tag','fltr','num','hlp');
mnu = inline(['struct(''type'',''menu'',''name'',name,'...
'''tag'',tag,''labels'',{labels},''values'',{values},''help'',hlp)'],...
'name','tag','labels','values','hlp');
branch = inline(['struct(''type'',''branch'',''name'',name,'...
'''tag'',tag,''val'',{val},''help'',hlp)'],...
'name','tag','val','hlp');
repeat = inline(['struct(''type'',''repeat'',''name'',name,'...
'''tag'',tag,''values'',{values},''help'',hlp)'],...
'name','tag','values','hlp');
choice = inline(['struct(''type'',''choice'',''name'',name,'...
'''tag'',tag,''values'',{values},''help'',hlp)'],...
'name','tag','values','hlp');
%-----------------------------------------------------------------------
sp_text = [' ',...
' '];
%-------------------------------------------------------------------------
spm.type = 'files';
spm.name = 'Select SPM.mat';
spm.tag = 'spmmat';
spm.num = [1 1];
spm.filter = 'mat';
spm.ufilter = '^SPM\.mat$';
spm.help = {'Select the SPM.mat file that contains the design specification. ',...
'The directory containing this file is known as the input directory.'};
% Bayesian estimation over slices or whole volume ?
slices = entry('Slices','Slices','e',[Inf 1],'');
p1=['Enter Slice Numbers. This can be a single slice or multiple slices. ',...
'If you select a single slice or only a few slices you must be aware of the ',...
'interpolation options when, after estimation, displaying the estimated ',...
'images eg. images of contrasts or AR maps. ',...
'The default interpolation option may need to be changed to nearest neighbour (NN) ',...
'(see bottom right hand of graphics window) for you slice maps to be visible.'];
slices.help={p1};
volume = struct('type','const','name','Volume','tag','Volume','val',{{1}});
p1=['You have selected the Volume option. SPM will analyse fMRI ',...
'time series in all slices of each volume.'];
volume.help={p1};
space = choice('Analysis Space','space',{volume,slices},'');
p1=['Because estimation can be time consuming an option is provided to analyse ',...
'selected slices rather than the whole volume.'];
space.help={p1};
space.val={volume};
% Regression coefficient priors for Bayesian estimation
w_prior = mnu('Signal priors','signal',{'GMRF','LORETA','Global','Uninformative'},...
{'GMRF','LORETA','Global','Uninformative'},{'Signal priors'});
w_prior.val={'GMRF'};
p1=['[GMRF] Gaussian Markov Random Field. This spatial prior is the recommended option. ',...
'Regression coefficients at a given voxel are (softly) constrained to be similar to those at ',...
'nearby voxels. The strength of this constraint is determined by a spatial precision ',...
'parameter that is estimated from the data. Different regression coefficients have ',...
'different spatial precisions allowing each putative experimental effect to have its ',...
'own spatial regularity. '];
p2=['[LORETA] Low resolution Tomography Prior. This spatial prior is very similar to the GMRF ',...
'prior and is a standatd choice for EEG source localisation algorithms. It does, however, ',...
'have undesirable edge effects.'];
p3=['[Global] Global Shrinkage prior. This is not a spatial prior in the sense that ',...
'regression coefficients are constrained to be similar to neighboring voxels. ',...
'Instead, the average effect over all voxels (global effect) is assumed to be zero ',...
'and all regression coefficients are shrunk towards this value in proporation to the ',...
'prior precision. This is the same prior that is used for Bayesian estimation at the ',...
'second level models, except that here the prior precision is estimated separaetly ',...
'for each slice. '];
p4=['[Uninformative] A flat prior. Essentially, no prior information is used. ',...
'If you select this option then VB reduces to Maximum Likelihood (ML)',...
'estimation. This option is useful if, for example, you do not wish to ',...
'use a spatial prior but wish to take advantage of the voxel-wise AR(P) ',...
'modelling of noise processes. In this case, you would apply the algorithm ',...
'to images that have been spatially smoothed. For P=0, ML estimation ',...
'in turn reduces to Ordinary Least Squares (OLS) estimates, and for P>0 ',...
'ML estimation is equivalent to a weighted least squares (WLS) but where the ',...
'weights are different at each voxel (reflecting the different noise correlation ',...
'at each voxel). '];
w_prior.help={p1,sp_text,p2,sp_text,p3,sp_text,p4};
% AR model order for Bayesian estimation
arp = entry('AR model order','ARP','e',[Inf 1],'Enter AR model order');
arp.val={3};
p1=['An AR model order of 3 is the default. Cardiac and respiratory artifacts ',...
'are periodic in nature and therefore require an AR order of at least 2. In ',...
'previous work, voxel-wise selection of the optimal model order showed that a ',...
'value of 3 was the highest order required. '];
p2=['Higher model orders have little ',...
'effect on the estimation time. If you select a model order of zero this ',...
'corresponds to the assumption that the errors are IID. This AR specification ',...
'overrides any choices that were made in the model specification stage.'];
p3=['Voxel-wise AR models are fitted separately for each session of data. For each ',...
'session this therefore produces maps of AR(1), AR(2) etc coefficients in the ',...
'output directory. '];
arp.help={p1,sp_text,p2,sp_text,p3};
% AR coefficient priors for Bayesian estimation
a_gmrf = struct('type','const','name','GMRF','tag','GMRF','val',{{1}});
p1=['[GMRF] Gaussian Markov Random Field. This is the default option. ',...
'This spatial prior is the same as that used for the ',...
'regression coefficients. Spatial precisions are estimated separately for each ',...
'AR coefficient eg. the AR(1) coefficient over space, AR(2) over space etc. '];
a_gmrf.help={p1};
a_loreta = struct('type','const','name','LORETA','tag','LORETA','val',{{1}});
p1=['[LORETA] Low resolution Tomography Prior. See comments on LORETA priors ',...
'for regresion coefficients.'];
a_loreta.help={p1};
a_tissue_type = files('Tissue-type','tissue_type','image',[1 Inf],'Select tissue-type images');
p1=['[Tissue-type] AR estimates at each voxel are biased towards typical ',...
'values for that tissue type (eg. gray, white, CSF). If you select this ',...
'option you will need to then ',...
'select files that contain tissue type maps (see below). ',...
'These are typically chosen to be ',...
'Grey Matter, White Matter and CSF images derived from segmentation of ',...
'registered structural scans.'];
p2=['Previous work has shown that ',...
'there is significant variation in AR values with tissue type. However, GMRF priors ',...
'have previously been favoured by Bayesian model comparison.'];
a_tissue_type.help={p1,sp_text,p2};
a_robust = struct('type','const','name','Robust','tag','Robust','val',{{1}});
p1=['Robust GLM. Uses Mixture of Gaussians noise model.'];
a_robust.help={p1};
a_prior = choice('Noise priors','noise',{a_gmrf,a_loreta,a_tissue_type,a_robust},'Noise priors');
a_prior.val={a_gmrf};
a_prior.help={'There are four noise prior options here (1) GMRF, (2) LORETA ',...
'(3) Tissue-type and (4) Robust'};
% ANOVA options
first = mnu('First level','first',...
{'No','Yes'},{'No','Yes'},{''});
first.val={'No'};
p1=['This is implemented using Bayesian model comparison. For example, to test for ',...
'the main effect of a factor two models are compared, one where the levels are ',...
'represented using different regressors and one using the same regressor. ',...
'This therefore requires explicit fitting of several models at each voxel and is ',...
'computationally demanding (requiring several hours of computation). ',...
'The recommended option is therefore NO.'];
p2=['To use this option you must have already specified your factorial design ',...
'during the model specification stage. '];
first.help={p1,sp_text,p2};
second = mnu('Second level','second',...
{'No','Yes'},{'No','Yes'},{''});
second.val={'Yes'};
p1=['This option tells SPM to automatically generate ',...
'the simple contrasts that are necessary to produce the contrast images ',...
'for a second-level (between-subject) ANOVA. Naturally, these contrasts can ',...
'also be used to characterise simple effects for each subject. '];
p2= ['With the Bayesian estimation ',...
'option it is recommended that contrasts are computed during the parameter ',...
'estimation stage (see ''simple contrasts'' below). ',...
'The recommended option here is therefore YES.'];
p3=['To use this option you must have already specified your factorial design ',...
'during the model specification stage. '];
p4=['If you wish to use these contrast images for a second-level analysis then ',...
'you will need to spatially smooth them to take into account between-subject ',...
'differences in functional anatomy ie. the fact that one persons V5 may be in ',...
'a different position than anothers. '];
second.help={p1,sp_text,p2,sp_text,p3,sp_text,p4};
anova.type = 'branch';
anova.name = 'ANOVA';
anova.tag = 'anova';
anova.val = {first,second};
anova.help = {'Perform 1st or 2nd level Analysis of Variance.'};
% Contrasts to be computed during Bayesian estimation
name.type = 'entry';
name.name = 'Name';
name.tag = 'name';
name.strtype = 's';
name.num = [1 1];
name.help = {'Name of contrast eg. ''Positive Effect'''};
gconvec = entry('Contrast vector','convec','e',[Inf 1],'');
p1=['These contrasts are used to generate PPMs which ',...
'characterise effect ',...
'sizes at each voxel. This is in contrast to SPMs in which eg. maps of t-statistics ',...
'show the ratio of the effect size to effect variability (standard deviation). ',...
'SPMs are therefore a-dimensional. This is not the case for PPMs as the size of the ',...
'effect is of primary interest. Some care is therefore needed about the scaling of ',...
'contrast vectors. For example, if you are interested in the differential effect ',...
'size averaged over conditions then the contrast 0.5 0.5 -0.5 -0.5 would be more ',...
'suitable than the 1 1 -1 -1 contrast which looks at the differential effect size ',...
'summed over conditions. '];
gconvec.help = {p1};
gcon.type = 'branch';
gcon.name = 'Simple contrast';
gcon.tag = 'gcon';
gcon.val = {name,gconvec};
gcon.help = {''};
contrast.type = 'repeat';
contrast.name = 'Simple contrasts';
contrast.tag = 'contrasts';
contrast.values = {gcon};
p1=['''Simple'' contrasts refers to a contrast that spans one-dimension ie. ',...
'to assess an effect that is increasing or decreasing.'];
p2 =['If you have a factoral design then the contrasts needed to generate ',...
'the contrast images for a 2nd-level ANOVA (or to assess these simple effects ',...
'within-subject) can be specified automatically ',...
'using the ANOVA->Second level option.'];
p3 =['When using the Bayesian estimation option it is computationally more ',...
'efficient to compute the contrasts when the parameters are estimated. ',...
'This is because estimated parameter vectors have potentially different ',...
'posterior covariance matrices at different voxels ',...
'and these matrices are not stored. If you compute contrasts ',...
'post-hoc these matrices must be recomputed (an approximate reconstruction ',...
'based on a Taylor series expansion is used). ',...
'It is therefore recommended to specify as many contrasts as possible ',...
'prior to parameter estimation.'];
p4=['If you wish to use these contrast images for a second-level analysis then ',...
'you will need to spatially smooth them to take into account between-subject ',...
'differences in functional anatomy ie. the fact that one persons V5 may be in ',...
'a different position than anothers. '];
contrast.help={p1,sp_text,p2,sp_text,p3,sp_text,p4};
% Bayesian estimation
est_bayes2 = struct('type','const','name','Bayesian 2nd-level','tag','Bayesian2','val',{{1}});
p1=['Bayesian estimation of 2nd level models. This option uses the Empirical Bayes ',...
'algorithm with global shrinkage priors that was previously implemented in SPM2. ',...
'Use of the global shrinkage prior embodies a prior belief that, on average over all ',...
'voxels, there is no net experimental effect. Some voxels will respond negatively ',...
'and some positively with a variability determined by the prior precision. ',...
'This prior precision can be estimated from the data using Empirical Bayes. '];
est_bayes2.help={p1};
est_bayes1 = branch('Bayesian 1st-level','Bayesian',{space,w_prior,arp,a_prior,anova,contrast},'Bayesian Estimation');
bayes_1 = ['Model parameters are estimated using Variational Bayes (VB). ',...
'This allows you to specify spatial priors for regression coefficients ',...
'and regularised voxel-wise AR(P) models for fMRI noise processes. ',...
'The algorithm does not require functional images to be spatially smoothed. ',...
'Estimation will take about 5 times longer than with the classical approach. ',...
'This is why VB is not the default estimation option. '];
p2=['Model estimation using this option is only efficient ',...
'if MATLAB can load a whole slice of data into physical memory. With modern PCs ',...
'this is usually achieved if the within-plane voxel sizes are 3 by 3 mm. This is therefore ',...
'the minimum recommended voxel size that your spatial normalisation process should ',...
'produce. Within-plane voxel sizes of 2 by 2 mm usually result in too many voxels per slice and result ',...
'in estimation times lasting several hours or days. Such a high resolution is therefore to be ',...
'avoided. '];
bayes_2 = ['After estimation, contrasts are used to find regions with effects larger ',...
'than a user-specified size eg. 1 per cent of the global mean signal. ',...
'These effects are assessed statistically using a Posterior Probability Map (PPM).'];
est_bayes1.help={bayes_1,sp_text,p2,sp_text,bayes_2};
% Classical (ReML) estimation
est_class = struct('type','const','name','Classical','tag','Classical','val',{{1}});
classical_1 =['Model parameters are estimated using Restricted Maximum ',...
'Likelihood (ReML). This assumes the error correlation structure is the ',...
'same at each voxel. This correlation can be specified using either an ',...
'AR(1) or an Independent and Identically Distributed (IID) error ',...
'model. These options are chosen at the model specification stage. ',...
'ReML estimation should be applied to spatially ',...
'smoothed functional images.'];
classical_2 = ['After estimation, specific profiles of parameters are tested using a linear ',...
'compound or contrast with the T or F statistic. The resulting statistical map ',...
'constitutes an SPM. The SPM{T}/{F} is then characterised in terms of ',...
'focal or regional differences by assuming that (under the null hypothesis) ',...
'the components of the SPM (ie. residual fields) behave as smooth stationary ',...
'Gaussian fields.'];
est_class.help={classical_1,sp_text,classical_2};
% Select method of estimation - Bayesian or classical
meth = choice('Method','method',{est_class,est_bayes1,est_bayes2},{'Type of estimation procedure'});
meth.val={est_class};
p1=['There are three possible estimation procedures for fMRI models (1) classical (ReML) estimation of ',...
'first or second level models, (2) Bayesian estimation of first level models and ',...
'(3) Bayesian estimation of second level models. ',...
'Option (2) uses a Variational Bayes (VB) algorithm that is new to SPM5. ',...
'Option (3) uses the Empirical ',...
'Bayes algorithm with global shrinkage priors that was also in SPM2. '];
p2=['To use option (3) you must have already estimated the model using option (1). ',...
'That is, for second-level models you must run a ReML estimation before ',...
'running a Bayesian estimation. This is not necessary for option (2). Bayesian ',...
'estimation of 1st-level models using VB does not require a prior ReML estimation.'];
meth.help={p1,sp_text,p2};
%-------------------------------------------------------------------------
conf = branch('Model estimation','fmri_est',...
{spm,meth},'Model estimation');
conf.prog = @run_est;
conf.vfiles = @vfiles_stats;
conf.modality = {'FMRI','PET'};
p1 = [...
'Model parameters can be estimated using ',...
'classical (ReML - Restricted Maximum Likelihood) or Bayesian algorithms. ',...
'After parameter estimation, the RESULTS button can be used to specify ',...
'contrasts that will produce Statistical Parametric Maps (SPMs) or ',...
'Posterior Probability Maps (PPMs) and tables of statistics.'];
conf.help = {p1};
return;
%=======================================================================
%=======================================================================
function run_est(job)
% Set up the design matrix and run a design.
global defaults
if isempty(defaults)
spm_defaults;
end;
if ~isfield(defaults,'modality')
defaults.modality = 'FMRI';
end;
%-Load SPM.mat file
%-----------------------------------------------------------------------
SPM = [];
load(job.spmmat{:});
original_dir = pwd;
%-Move to the directory where the SPM.mat file is
%-----------------------------------------------------------------------
cd(fileparts(job.spmmat{:}));
% COMMENTED OUT BY DRG. THIS SHOULD BE TAKEN CARE OF WITHIN SPM_SPM AND
% SPM_SPM_BAYES. REMOVE THIS SECTION ONCE THIS HAS BEEN VERIFIED.
%-If we've gotten to this point we're committed to overwriting files.
% Delete them so we don't get stuck in spm_spm
%-----------------------------------------------------------------------
% files = {'^mask\..{3}$','^ResMS\..{3}$','^RPV\..{3}$',...
% '^beta_.{4}\..{3}$','^con_.{4}\..{3}$','^ResI_.{4}\..{3}$',...
% '^ess_.{4}\..{3}$', '^spm\w{1}_.{4}\..{3}$'};
%
% for i=1:length(files)
% j = spm_select('List',pwd,files{i});
% for k=1:size(j,1)
% spm_unlink(deblank(j(k,:)));
% end
% end
% END COMMENTED OUT BY DRG
%=======================================================================
% B A Y E S I A N 2nd L E V E L E S T I M A T I O N
%=======================================================================
if isfield(job.method,'Bayesian2')
SPM = spm_spm_Bayes(SPM);
cd(original_dir); % Change back
fprintf('Done\n');
return
end
%=======================================================================
% R E M L E S T I M A T I O N
%=======================================================================
if isfield(job.method,'Classical'),
SPM = spm_spm(SPM);
%-Automatically set up contrasts for factorial designs
%-------------------------------------------------------------------
if isfield(SPM,'factor')
if SPM.factor(1).levels > 1
% don't both if you've only got 1 level and 1 factor
cons = spm_design_contrasts(SPM);
%-Create F-contrasts
%-----------------------------------------------------------
for i=1:length(cons)
con = cons(i).c;
name = cons(i).name;
STAT = 'F';
[c,I,emsg,imsg] = spm_conman('ParseCon',con,SPM.xX.xKXs,STAT);
if all(I)
DxCon = spm_FcUtil('Set',name,STAT,'c',c,SPM.xX.xKXs);
else
DxCon = [];
end
if isempty(SPM.xCon),
SPM.xCon = DxCon;
else
SPM.xCon(end+1) = DxCon;
end
SPM = spm_contrasts(SPM,length(SPM.xCon));
end
%-Create t-contrasts
%-----------------------------------------------------------
for i=1:length(cons)
% Create a t-contrast for each row of each F-contrast
% The resulting contrast image can be used in a 2nd-level analysis
Fcon = cons(i).c;
nrows = size(Fcon,1);
STAT = 'T';
for r=1:nrows,
con = Fcon(r,:);
str = cons(i).name;
if ~isempty(strmatch('Interaction',str))
name = ['Positive ',str,'_',int2str(r)];
else
sp1 = min(find(isspace(str)));
name = ['Positive',str(sp1:end),'_',int2str(r)];
end
[c,I,emsg,imsg] = spm_conman('ParseCon',con,SPM.xX.xKXs,STAT);
if all(I)
DxCon = spm_FcUtil('Set',name,STAT,'c',c,SPM.xX.xKXs);
else
DxCon = [];
end
if isempty(SPM.xCon),
SPM.xCon = DxCon;
else
SPM.xCon(end+1) = DxCon;
end
SPM = spm_contrasts(SPM,length(SPM.xCon));
end
end
end % if SPM.factor(1).levels > 1
end % if isfield(SPM,'factor')
cd(original_dir); % Change back
fprintf('Done\n');
return
end
%=======================================================================
% B A Y E S I A N 1st L E V E L E S T I M A T I O N
%=======================================================================
%-Analyse specific slices or whole volume
%-----------------------------------------------------------------------
if isfield(job.method.Bayesian.space,'Slices')
SPM.PPM.space_type = 'Slices';
SPM.PPM.AN_slices = job.method.Bayesian.space.Slices;
else
SPM.PPM.space_type = 'Volume';
end
%-Regression coefficient priors
%-----------------------------------------------------------------------
switch job.method.Bayesian.signal
case 'GMRF',
SPM.PPM.priors.W = 'Spatial - GMRF';
case 'LORETA',
SPM.PPM.priors.W = 'Spatial - LORETA';
case 'Global',
SPM.PPM.priors.W = 'Voxel - Shrinkage';
case 'Uninformative',
SPM.PPM.priors.W = 'Voxel - Uninformative';
otherwise
error('Unkown prior for W in spm_config_fmri_est');
end
%-Number of AR coefficients
%-----------------------------------------------------------------------
SPM.PPM.AR_P = job.method.Bayesian.ARP;
%-AR coefficient priors
%-----------------------------------------------------------------------
if isfield(job.method.Bayesian.noise,'GMRF')
SPM.PPM.priors.A = 'Spatial - GMRF';
elseif isfield(job.method.Bayesian.noise,'LORETA')
SPM.PPM.priors.A = 'Spatial - LORETA';
elseif isfield(job.method.Bayesian.noise,'tissue_type')
SPM.PPM.priors.A = 'Discrete';
SPM.PPM.priors.SY = job.method.Bayesian.noise.tissue_type;
elseif isfield(job.method.Bayesian.noise,'Robust')
SPM.PPM.priors.A = 'Robust';
SPM.PPM.AR_P=0;
SPM.PPM.update_F=1;
end
%-Define an empty contrast
%-----------------------------------------------------------------------
NullCon = spm_FcUtil('Set','','P','c',[],1);
NullCon.X0 = [];
NullCon.iX0 = [];
NullCon.X1o = [];
NullCon.eidf = 1;
SPM.xCon = [];
%-Set up contrasts for 2nd-level ANOVA
%-----------------------------------------------------------------------
if strcmp(job.method.Bayesian.anova.second,'Yes')
if isfield(SPM,'factor')
cons=spm_design_contrasts(SPM);
for i=1:length(cons),
% Create a simple contrast for each row of each F-contrast
% The resulting contrast image can be used in a 2nd-level analysis
Fcon=cons(i).c;
nrows=size(Fcon,1);
STAT='P';
for r=1:nrows,
con=Fcon(r,:);
% Normalise contrast st. sum of positive elements is 1
% and sum of negative elements is 1
s1=length(find(con==1));
con=con./s1;
% Change name
str=cons(i).name;
sp1=min(find(str==' '));
if strcmp(str(1:11),'Interaction')
name=['Positive ',str,'_',int2str(r)];
else
name=['Positive',str(sp1:end),'_',int2str(r)];
end
DxCon=NullCon;
DxCon.name=name;
DxCon.c=con';
if isempty(SPM.xCon),
SPM.xCon = DxCon;
else
SPM.xCon(end+1) = DxCon;
end
end
end
end
end
%-Set up user-specified simple contrasts
%-----------------------------------------------------------------------
ncon = length(job.method.Bayesian.gcon);
K = size(SPM.xX.X,2);
for c = 1:ncon
DxCon = NullCon;
DxCon.name = job.method.Bayesian.gcon(c).name;
convec = job.method.Bayesian.gcon(c).convec(:);
if length(convec) == K
DxCon.c = convec;
else
str = ['Error in contrast specification:' ...
sprintf('\n contrast has %d entries ', length(convec)) ...
sprintf('but there are %d regressors !\n', K)];
error(str);
end
if isempty(SPM.xCon),
SPM.xCon = DxCon;
else
SPM.xCon(end+1) = DxCon;
end
end
%-1st level Bayesian ANOVA ?
%-----------------------------------------------------------------------
bayes_anova = 0;
if strcmp(job.method.Bayesian.anova.first,'Yes')
bayes_anova = 1;
SPM.PPM.update_F = 1; % Compute evidence for each model
SPM.PPM.compute_det_D = 1;
end
%-Variational Bayes estimation
%-----------------------------------------------------------------------
SPM = spm_spm_vb(SPM);
%-Bayesian ANOVA using model comparison
%-----------------------------------------------------------------------
if bayes_anova
% We don't want to estimate contrasts for each different model
SPM.xCon = [];
spm_vb_ppm_anova(SPM);
end
cd(original_dir); % Change back
fprintf('Done\n')
return
%=======================================================================
function vf = vfiles_stats(job)
vf = {job.spmmat{:}};
% Should really create a few vfiles for beta images etc here as well.
|
github
|
spm/spm5-master
|
spm_platform.m
|
.m
|
spm5-master/spm_platform.m
| 8,489 |
utf_8
|
1f602bafb359d64bef775a8d7b66b76d
|
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
% - Inf - is not IEEE floating point
% - 0 - is little end
% - 1 - big end
% - 'filesys' - type of filesystem
% - 'unx' - UNIX
% - 'win' - DOS
% - 'mac' - Macintosh
% - 'vms' - VMS
% - 'sepchar' - returns directory separator
% - 'rootlen' - returns number of chars in root directory name
% - 'user' - returns username
% - '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 difinitions are contained in the data structures at
% the beginning of the init_platform subfunction at the end of this
% file.
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Matthew Brett
% $Id: spm_platform.m 1962 2008-07-28 15:40:56Z 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};
if ~isfinite(PLATFORM.bigend),
if isnan(PLATFORM.bigend)
error(['I don''t know if "',computer,'" is big-endian.'])
else
error(['I don''t think that "',computer,...
'" uses IEEE floating point ops.'])
end
end
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 '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; end
%-Platform definitions
%-----------------------------------------------------------------------
PDefs = { 'PCWIN', 'win', 0;...
'PCWIN64', 'win', 0;...
'MAC', 'unx', 1;...
'MACI', 'unx', 0;...
'MACI64', 'unx', 0;...
'SUN4', 'unx', 1;...
'SOL2', 'unx', 1;...
'SOL64', 'unx', 1;...
'HP700', 'unx', 1;...
'SGI', 'unx', 1;...
'SGI64', 'unx', 1;...
'IBM_RS', 'unx', 1;...
'ALPHA', 'unx', 0;...
'AXP_VMSG', 'vms', Inf;...
'AXP_VMSIEEE', 'vms', 0;...
'LNX86', 'unx', 0;...
'GLNX86', 'unx', 0;...
'GLNXA64', 'unx', 0;...
'VAX_VMSG', 'vms', Inf;...
'VAX_VMSD', 'vms', Inf };
PDefs = cell2struct(PDefs,{'computer','filesys','endian'},2);
%-Which computer?
%-----------------------------------------------------------------------
ci = find(strcmp({PDefs.computer},comp));
if isempty(ci), error([comp,' not supported architecture for SPM']), end
%-Set bigend
%-----------------------------------------------------------------------
PLATFORM.bigend = PDefs(ci).endian;
%-Set filesys
%-----------------------------------------------------------------------
PLATFORM.filesys = PDefs(ci).filesys;
%-Set filesystem dependent stuff
%-----------------------------------------------------------------------
%-File separators character
%-Length of root directory strings
%-User name finding
%-(mouse button labels?)
switch (PLATFORM.filesys)
case 'unx'
PLATFORM.sepchar = '/';
PLATFORM.rootlen = 1;
PLATFORM.user = getenv('USER');
case 'win'
PLATFORM.sepchar = '\';
PLATFORM.rootlen = 3;
PLATFORM.user = getenv('USERNAME');
if isempty(PLATFORM.user)
PLATFORM.user = 'anon';
end
otherwise
error(['Don''t know filesystem ',PLATFORM.filesys])
end
%-Drives
%-----------------------------------------------------------------------
PLATFORM.drives = '';
if strcmp(comp,'PCWIN') || strcmp(comp,'PCWIN64'),
driveLett = cellstr(char(('C':'Z')'));
for i=1:numel(driveLett),
if exist([driveLett{i} ':\']) == 7,
PLATFORM.drives = [PLATFORM.drives driveLett{i}];
end
end
end
%-Fonts
%-----------------------------------------------------------------------
switch comp
case {'SOL2'} %-Some Sol2 platforms give segmentation violations with Helvetica
PLATFORM.font.helvetica = 'Lucida';
PLATFORM.font.times = 'Times';
PLATFORM.font.courier = 'Courier';
PLATFORM.font.symbol = 'Symbol';
case {'SUN4','SOL2','SOL64','HP700','SGI','SGI64','IBM_RS','ALPHA','LNX86','GLNX86','GLNXA64','MAC','MACI','MACI64'}
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
|
spm/spm5-master
|
spm_config_fmri_data.m
|
.m
|
spm5-master/spm_config_fmri_data.m
| 5,006 |
utf_8
|
38c392121fbd8c522ef579797945a857
|
function conf = spm_config_fmri_data
% Configuration file for specification of fMRI model
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Darren Gitelman and Will Penny
% $Id: spm_config_fmri_data.m 766 2007-03-15 14:09:30Z volkmar $
% Define inline types.
%-----------------------------------------------------------------------
entry = inline(['struct(''type'',''entry'',''name'',name,'...
'''tag'',tag,''strtype'',strtype,''num'',num,''help'',hlp)'],...
'name','tag','strtype','num','hlp');
files = inline(['struct(''type'',''files'',''name'',name,'...
'''tag'',tag,''filter'',fltr,''num'',num,''help'',hlp)'],...
'name','tag','fltr','num','hlp');
mnu = inline(['struct(''type'',''menu'',''name'',name,'...
'''tag'',tag,''labels'',{labels},''values'',{values},''help'',hlp)'],...
'name','tag','labels','values','hlp');
branch = inline(['struct(''type'',''branch'',''name'',name,'...
'''tag'',tag,''val'',{val},''help'',hlp)'],...
'name','tag','val','hlp');
repeat = inline(['struct(''type'',''repeat'',''name'',name,'...
'''tag'',tag,''values'',{values},''help'',hlp)'],...
'name','tag','values','hlp');
choice = inline(['struct(''type'',''choice'',''name'',name,'...
'''tag'',tag,''values'',{values},''help'',hlp)'],...
'name','tag','values','hlp');
%-----------------------------------------------------------------------
sp_text = [' ',...
' '];
%-----------------------------------------------------------------------
scans = files('Scans','scans','image',[1 Inf],'Select scans');
scans.help = {[...
'Select the fMRI scans for this session. They must all have the same ',...
'image dimensions, orientation, voxel size etc.']};
%-------------------------------------------------------------------------
mask = files('Explicit mask','mask','image',[0 1],'Image mask');
mask.val = {''};
p1=['Specify an image for explicitly masking the analysis. ',...
'A sensible option here is to use a segmention of structural images ',...
'to specify a within-brain mask. If you select that image as an ',...
'explicit mask then only those voxels in the brain will be analysed. ',...
'This both speeds the estimation and restricts SPMs/PPMs to within-brain ',...
'voxels. Alternatively, if such structural images are unavailble or no ',...
'masking is required, then leave this field empty.'];
mask.help={p1};
%-------------------------------------------------------------------------
spmmat = files('Select SPM.mat','spmmat','mat',1,'');
spmmat.help = {[...
'Select the SPM.mat file containing the ',...
'specified design matrix.']};
%-------------------------------------------------------------------------
conf = branch('fMRI data specification','fmri_data',...
{scans,spmmat,mask},'fMRI data');
conf.prog = @run_stats;
conf.vfiles = @vfiles_stats;
conf.modality = {'FMRI'};
conf.help = {['Select the data and optional explicit mask for a specified ' ...
'design']};
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function my_cd(varargin)
% jobDir must be the actual directory to change to, NOT the job structure.
jobDir = varargin{1};
if ~isempty(jobDir)
try
cd(char(jobDir));
fprintf('Changing directory to: %s\n',char(jobDir));
catch
error('Failed to change directory. Aborting run.')
end
end
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function run_stats(job)
% Set up the design matrix and run a design.
spm_defaults;
global defaults
defaults.modality='FMRI';
original_dir = pwd;
[p n e v] = fileparts(job.spmmat{1});
my_cd(p);
load(job.spmmat{1});
% Image filenames
%-------------------------------------------------------------
SPM.xY.P = strvcat(job.scans);
% Let SPM configure the design
%-------------------------------------------------------------
SPM = spm_fmri_spm_ui(SPM);
if ~isempty(job.mask)&&~isempty(job.mask{1})
SPM.xM.VM = spm_vol(job.mask{:});
SPM.xM.xs.Masking = [SPM.xM.xs.Masking, '+explicit mask'];
end
%-Save SPM.mat
%-----------------------------------------------------------------------
fprintf('%-40s: ','Saving SPM configuration') %-#
if str2num(version('-release'))>=14,
save('SPM','-V6','SPM');
else
save('SPM','SPM');
end;
fprintf('%30s\n','...SPM.mat saved') %-#
my_cd(original_dir); % Change back dir
fprintf('Done\n')
return
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function vf = vfiles_stats(job)
vf = job.spmmat;
|
github
|
spm/spm5-master
|
spm_preproc.m
|
.m
|
spm5-master/spm_preproc.m
| 20,570 |
utf_8
|
65a2123b974d0b044cd06712ed982964
|
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 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_preproc.m 946 2007-10-15 16:36:06Z john $
[dir,nam,ext] = fileparts(which(mfilename));
opts0.tpm = char(...
fullfile(dir,'tpm','grey.nii'),...
fullfile(dir,'tpm','white.nii'),...
fullfile(dir,'tpm','csf.nii'));
opts0.ngaus = [2 2 2 4];
opts0.warpreg = 1;
opts0.warpco = 25;
opts0.biasreg = 0.0001;
opts0.biasfwhm = 75;
opts0.regtype = 'mni';
opts0.fudge = 5;
opts0.samp = 3;
opts0.msk = '';
if nargin==0
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);
rand('state',0); % give same results each time
for k1=1:Kb,
kk = sum(lkp==k1);
mn(lkp==k1) = rand(kk,1)*mx;
end;
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 ~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_chi2_plot('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_chi2_plot('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_chi2_plot('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_chi2_plot('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_chi2_plot('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_chi2_plot('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
|
spm/spm5-master
|
spm_preproc_write.m
|
.m
|
spm5-master/spm_preproc_write.m
| 8,606 |
utf_8
|
81348572564ad18beb736b2ebde90b4b
|
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 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_preproc_write.m 1746 2008-05-28 17:43:42Z guillaume $
if nargin==1,
opts = struct('biascor',0,'GM',[0 0 1],'WM',[0 0 1],'CSF',[0 0 0],'cleanup',0);
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];
[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
|
spm/spm5-master
|
spm_config_contrasts.m
|
.m
|
spm5-master/spm_config_contrasts.m
| 31,917 |
utf_8
|
38447033c92a1a4cb1f381be46468bc5
|
function con = spm_config_contrasts
% Configuration file for contrast jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Darren Gitelman
% $Id: spm_config_contrasts.m 948 2007-10-15 21:37:49Z Darren $
%_______________________________________________________________________
spm.type = 'files';
spm.name = 'Select SPM.mat';
spm.tag = 'spmmat';
spm.num = [1 1];
spm.filter = 'mat';
spm.ufilter = '^SPM\.mat$';
spm.help = {'Select SPM.mat file for contrasts'};
sessrep.type = 'menu';
sessrep.name = 'Replicate over sessions';
sessrep.tag = 'sessrep';
sessrep.labels = {'Don''t replicate','Replicate','Create per session','Both'};
sessrep.values = {'none','repl','sess','both'};
sessrep.val = {'none'};
sessrep.help = {['If there are multiple sessions with identical conditions, ' ...
'one might want to specify contrasts which are identical over ',...
'sessions. This can be done automatically based on the contrast '...
'spec for one session.'],...
['Contrasts can be either replicated (thus testing average ' ...
'effects over sessions) or created per session. In both ' ...
'cases, zero padding up to the length of each session ' ...
'and the block effects is done automatically.']};
name.type = 'entry';
name.name = 'Name';
name.tag = 'name';
name.strtype = 's';
name.num = [1 1];
name.help = {'Name of contrast'};
tconvec.type = 'entry';
tconvec.name = 'T contrast vector';
tconvec.tag = 'convec';
tconvec.strtype = 'e';
tconvec.num = [1 Inf];
tconvec.help = {[...
'Enter T contrast vector. This is done similarly to the ',...
'SPM2 contrast manager. A 1 x n vector should be entered ',...
'for T-contrasts.']};
fconvec.type = 'entry';
fconvec.name = 'F contrast vector';
fconvec.tag = 'convec';
fconvec.strtype = 'e';
fconvec.num = [Inf Inf];
fconvec.help = {[...
'Enter F contrast vector. This is done similarly to the ',...
'SPM2 contrast manager. One or multiline contrasts ',...
'may be entered.']};
fconvecs.type = 'repeat';
fconvecs.name = 'Contrast vectors';
fconvecs.tag = 'convecs';
fconvecs.values = {fconvec};
fconvecs.help = {...
'F contrasts are defined by a series of vectors.'};
tcon.type = 'branch';
tcon.name = 'T-contrast';
tcon.tag = 'tcon';
tcon.val = {name,tconvec,sessrep};
tcon.help = {...
'* Simple one-dimensional contrasts for an SPM{T}','',[...
'A simple contrast for an SPM{T} tests the null hypothesis c''B=0 ',...
'against the one-sided alternative c''B>0, where c is a column vector. '],'',[...
' Note that throughout SPM, the transpose of the contrast weights is ',...
'used for display and input. That is, you''ll enter and visualise c''. ',...
'For an SPM{T} this will be a row vector.'],'',[...
'For example, if you have a design in which the first two columns of ',...
'the design matrix correspond to the effects for "baseline" and ',...
'"active" conditions respectively, then a contrast with weights ',...
'c''=[-1,+1,0,...] (with zero weights for any other parameters) tests ',...
'the hypothesis that there is no "activation" (the parameters for both ',...
'conditions are the same), against the alternative that there is some ',...
'activation (i.e. the parameter for the "active" condition is greater ',...
'than that for the "baseline" condition). The resulting SPM{T} ',...
'(created by spm_getSPM.m) is a statistic image, with voxel values the ',...
'value of the t-statistic for the specified contrast at that location. ',...
'Areas of the SPM{T} with high voxel values indicate evidence for ',...
'"activation". To look for areas of relative "de-activation", the ',...
'inverse contrast could be used c''=[+1,-1,0,...].'],'',[...
'Similarly, if you have a design where the third column in the design ',...
'matrix is a covariate, then the corresponding parameter is ',...
'essentially a regression slope, and a contrast with weights ',...
'c''=[0,0,1,0,...] (with zero weights for all parameters but the third) ',...
'tests the hypothesis of zero regression slope, against the ',...
'alternative of a positive slope. This is equivalent to a test no ',...
'correlation, against the alternative of positive correlation. If ',...
'there are other terms in the model beyond a constant term and the ',...
'covariate, then this correlation is apartial correlation, the ',...
'correlation between the data Y and the covariate, after accounting ',...
'for the other effects.']};
fcon.type = 'branch';
fcon.name = 'F-contrast';
fcon.tag = 'fcon';
fcon.val = {name,fconvecs,sessrep};
fcon.help = {...
'* Linear constraining matrices for an SPM{F}',...
'',[...
'The null hypothesis c''B=0 can be thought of as a (linear) constraint ',...
'on the full model under consideration, yielding a reduced model. ',...
'Taken from the viewpoint of two designs, with the full model an ',...
'extension of the reduced model, the null hypothesis is that the ',...
'additional terms in the full model are redundent.'],...
'',[...
'Statistical inference proceeds by comparing the additional variance ',...
'explained by full design over and above the reduced design to the ',...
'error variance (of the full design), an "Extra Sum-of-Squares" ',...
'approach yielding an F-statistic for each voxel, whence an SPM{F}.'],...
'',...
'This is useful in a number of situations:',...
'',...
'* Two sided tests',...
'',[...
'The simplest use of F-contrasts is to effect a two-sided test of a ',...
'simple linear contrast c''B, where c is a column vector. The SPM{F} is ',...
'the square of the corresponding SPM{T}. High values of the SPM{F} ',...
'therefore indicate evidence against the null hypothesis c''B=0 in ',...
'favour of the two-sided alternative c''B~=0.'],...
'',...
'* General linear hypotheses',...
'',[...
'Where the contrast weights is a matrix, the rows of the (transposed) ',...
'contrast weights matrix c'' must define contrasts in their own right, ',...
'and the test is effectively simultaneously testing the null ',...
'hypotheses associated with the individual component contrasts with ',...
'weights defined in the rows. The null hypothesis is still c''B=0, but ',...
'since c is a matrix, 0 here is a zero vector rather than a scalar ',...
'zero, asserting that under the null hypothesis all the component ',...
'hypotheses are true.'],...
'',[...
'For example: Suppose you have a language study with 3 word categories ',...
'(A,B & C), and would like to test whether there is any difference ',...
'at all between the three levels of the "word category" factor.'],...
'',...
'The design matrix might look something like:',...
'',...
' [ 1 0 0 ..]',...
' [ : : : ..]',...
' [ 1 0 0 ..]',...
' [ 0 1 0 ..]',...
' X = [ : : : ..]',...
' [ 0 1 0 ..]',...
' [ 0 0 1 ..]',...
' [ : : : ..]',...
' [ 0 0 1 ..]',...
' [ 0 0 0 ..]',...
' [ : : : ..]',...
'',[...
' ...with the three levels of the "word category" factor modelled in the ',...
' first three columns of the design matrix.'],...
'',...
'The matrix of contrast weights will look like:',...
'',...
' c'' = [1 -1 0 ...;',...
' 0 1 -1 ...]',...
'',[...
'Reading the contrasts weights in each row of c'', we see that row 1 ',...
'states that category A elicits the same response as category B, row 2 ',...
'that category B elicits the same response as category C, and hence ',...
'together than categories A, B & C all elicit the same response.'],...
'',[...
'The alternative hypothesis is simply that the three levels are not ',...
'all the same, i.e. that there is some difference in the paraeters for ',...
'the three levels of the factor: The first and the second categories ',...
'produce different brain responses, OR the second and third ',...
'categories, or both.'],...
'',[...
'In other words, under the null hypothesis (the categories produce the ',...
'same brain responses), the model reduces to one in which the three ',...
'level "word category" factor can be replaced by a single "word" ',...
'effect, since there is no difference in the parameters for each ',...
'category. The corresponding design matrix would have the first three ',...
'columns replaced by a single column that is the sum (across rows) of ',...
'the first three columns in the design matric above, modelling the ',...
'brain response to a word, whatever is the category. The F-contrast ',...
'above is in fact testing the hypothesis that this reduced design ',...
'doesn''t account for significantly less variance than the full design ',...
'with an effect for each word category.'],...
'',[...
'Another way of seeing that, is to consider a reparameterisation of ',...
'the model, where the first column models effects common to all three ',...
'categories, with the second and third columns modelling the ',...
'differences between the three conditions, for example:'],...
'',...
' [ 1 1 0 ..]',...
' [ : : : ..]',...
' [ 1 1 0 ..]',...
' [ 1 0 1 ..]',...
' X = [ : : : ..]',...
' [ 1 0 1 ..]',...
' [ 1 -1 -1 ..]',...
' [ : : : ..]',...
' [ 1 -1 -1 ..]',...
' [ 0 0 0 ..]',...
' [ : : : ..]',...
'',...
'In this case, an equivalent F contrast is of the form',...
' c'' = [ 0 1 0 ...;',...
' 0 0 1 ...]',[...
'and would be exactly equivalent to the previous contrast applied to ',...
'the previous design. In this latter formulation, you are asking ',...
'whewher the two columns modelling the "interaction space" account for ',...
'a significant amount of variation (variance) of the data. Here the ',...
'component contrasts in the rows of c'' are simply specifying that the ',...
'parameters for the corresponding rows are are zero, and it is clear ',...
'that the F-test is comparing this full model with a reduced model in ',...
'which the second and third columns of X are omitted.'],...
'',...
' Note the difference between the following two F-contrasts:',...
' c'' = [ 0 1 0 ...; (1)',...
' 0 0 1 ...]',...
' and',...
' c'' = [ 0 1 1 ...] (2)',...
'',[...
' The first is an F-contrast, testing whether either of the ',...
'parameters for the effects modelled in the 2nd & 3rd columns of the ',...
'design matrix are significantly different from zero. Under the null ',...
'hypothesis c''B=0, the first contrast imposes a two-dimensional ',...
'constraint on the design. The second contrast tests whether the SUM ',...
'of the parameters for the 2nd & 3rd columns is significantly ',...
'different from zero. Under the null hypothesis c''B=0, this second ',...
'contrast only imposes a one dimensional constraint on the design.'],...
'',[...
' An example of the difference between the two is that the first ',...
'contrast would be sensitive to the situation where the 2nd & 3rd ',...
'parameters were +a and -a, for some constant a, wheras the second ',...
'contrast would not detect this, since the parameters sum to zero.'],...
'',[...
'The test for an effect of the factor "word category" is an F-test ',...
'with 3-1=2 "dimensions", or degrees of freedom.'],...
'',...
'* Testing the significance of effects modelled by multiple columns',...
'',[...
'A conceptially similar situation arises when one wonders whether a ',...
'set of coufound effects are explaining any variance in the data. One ',...
'important advantage of testing the with F contrasts rather than one ',...
'by one using SPM{T}''s is the following. Say you have two covariates ',...
'that you would like to know whether they can "predict" the brain ',...
'responses, and these two are correlated (even a small correlation ',...
'would be important in this instance). Testing one and then the other ',...
'may lead you to conclude that there is no effect. However, testing ',...
'with an F test the two covariates may very well show a not suspected ',...
'effect. This is because by testing one covariate after the other, one ',...
'never tests for what is COMMON to these covariates (see Andrade et ',...
'al, Ambiguous results in functional neuroimaging, NeuroImage, 1999).'],...
'','',[...
'More generally, F-tests reflect the usual analysis of variance, while ',...
't-tests are traditionally post hoc tests, useful to see in which ',...
'direction is an effect going (positive or negative). The introduction ',...
'of F-tests can also be viewed as a first means to do model selection.'],...
'','',[...
'Technically speaking, an F-contrast defines a number of directions ',...
'(as many as the rank of the contrast) in the space spanned by the ',...
'column vectors of the design matrix. These directions are simply ',...
'given by X*c if the vectors of X are orthogonal, if not, the space ',...
'define by c is a bit more complex and takes care of the correlation ',...
'within the design matrix. In essence, an F-contrast is defining a ',...
'reduced model by imposing some linear constraints (that have to be ',...
'estimable, see below) on the parameters estimates. Sometimes, this ',...
'reduced model is simply made of a subset of the column of the ',...
'original design matrix but generally, it is defined by a combination ',...
'of those columns. (see spm_FcUtil for what (I hope) is an efficient ',...
'handling of F-contrats computation).']};
% Column-wise contrast definition for fancy fMRI designs
%_______________________________________________________________________
conweight.type = 'entry';
conweight.name = 'Contrast weight';
conweight.tag = 'conweight';
conweight.strtype = 'e';
conweight.num = [1 1];
conweight.help = {'The contrast weight for the selected column.'};
colcond.type = 'entry';
colcond.name = 'Condition #';
colcond.tag = 'colcond';
colcond.strtype = 'e';
colcond.num = [1 1];
colcond.help = {['Select which condition function set is to be contrasted.']};
colbf.type = 'entry';
colbf.name = 'Basis function #';
colbf.tag = 'colbf';
colbf.strtype = 'e';
colbf.num = [1 1];
colbf.help = {['Select which basis function from the basis' ...
' function set is to be contrasted.']};
colmod.type = 'entry';
colmod.name = 'Parametric modulation #';
colmod.tag = 'colmod';
colmod.strtype = 'e';
colmod.num = [1 1];
colmod.help = {['Select which parametric modulation is to be contrasted.' ...
' If there is no time/parametric modulation, enter' ...
' "1". If there are both time and parametric modulations, '...
'then time modulation comes before parametric modulation.']};
colmodord.type = 'entry';
colmodord.name = 'Parametric modulation order';
colmodord.tag = 'colmodord';
colmodord.strtype = 'e';
colmodord.num = [1 1];
colmodord.help = {'Order of parametric modulation to be contrasted. ','', ...
'0 - the basis function itself, 1 - 1st order mod etc'};
colconds.type = 'branch';
colconds.name = 'Contrast entry';
colconds.tag = 'colconds';
colconds.val = {conweight,colcond,colbf,colmod,colmodord};
colcondrep.type = 'repeat';
colcondrep.name = 'T contrast for conditions';
colcondrep.tag = 'colcondrep';
colcondrep.values = {colconds};
colcondrep.num = [1 Inf];
colcondrep.help = {'Assemble your contrast column by column.'};
colreg = tconvec;
colreg.name = 'T contrast for extra regressors';
colreg.tag = 'colreg';
colreg.help = {...
['Enter T contrast vector for extra regressors.']};
coltype.type = 'choice';
coltype.name = 'Contrast columns';
coltype.tag = 'coltype';
coltype.values = {colcondrep, colreg};
coltype.help = {...
['Contrasts can be specified either over conditions or over extra regressors.']};
sessions.type = 'entry';
sessions.name = 'Session(s)';
sessions.tag = 'sessions';
sessions.strtype = 'e';
sessions.num = [1 Inf];
sessions.help = {...
['Enter session number(s) for which this contrast should be created. If' ...
' more than one session number is specified, the contrast will be an' ...
' average contrast over the specified conditions or regressors from these' ...
' sessions.']};
tconsess.type = 'branch';
tconsess.name = 'T-contrast (cond/sess based)';
tconsess.tag = 'tconsess';
tconsess.val = {name,coltype,sessions};
tconsess.modality = {'FMRI'};
tconsess.help = {...
['Define a contrast in terms of conditions or regressors instead of' ...
' columns of the design matrix. This allows to create contrasts automatically' ...
' even if some columns are not always present (e.g. parametric modulations).'], ...
'', ...
'Each contrast column can be addressed by specifying', ...
'* session number', ...
'* condition number', ...
'* basis function number', ...
'* parametric modulation number and', ...
'* parametric modulation order.', ...
'', ...
['If the design is specified without time or parametric modulation, SPM' ...
' creates a "pseudo-modulation" with order zero. To put a contrast weight' ...
' on a basis function one therefore has to enter "1" for parametric' ...
' modulation number and "0" for parametric modulation order.'], ...
'', ...
['Time and parametric modulations are not distinguished internally. If' ...
' time modulation is present, it will be parametric modulation "1", and' ...
' additional parametric modulations will be numbered starting with "2".'], ...
'', ...
tcon.help{:}};
consess.type = 'repeat';
consess.name = 'Contrast Sessions';
consess.tag = 'consess';
consess.values = {tcon,fcon,tconsess};
consess.help = {'contrast'};
consess.help = {[...
'For general linear model Y = XB + E with data Y, desgin matrix X, ',...
'parameter vector B, and (independent) errors E, a contrast is a ',...
'linear combination of the parameters c''B. Usually c is a column ',...
'vector, defining a simple contrast of the parameters, assessed via an ',...
'SPM{T}. More generally, c can be a matrix (a linear constraining ',...
'matrix), defining an "F-contrast" assessed via an SPM{F}.'],'',[...
'The vector/matrix c contains the contrast weights. It is this ',...
'contrast weights vector/matrix that must be specified to define the ',...
'contrast. The null hypothesis is that the linear combination c''B is ',...
'zero. The order of the parameters in the parameter (column) vector B, ',...
'and hence the order to which parameters are referenced in the ',...
'contrast weights vector c, is determined by the construction of the ',...
'design matrix.'],'',[...
'There are two types of contrast in SPM: simple contrasts for SPM{T}, ',...
'and "F-contrasts" for SPM{F}.'],'',[...
'For a thorough theoretical treatment, see the Human Brain Function book ',...
'and the statistical literature referenced therein.'],...
'','',...
'* Non-orthogonal designs',...
'',[...
'Note that parameters zero-weighted in the contrast are still included ',...
'in the model. This is particularly important if the design is not ',...
'orthogonal (i.e. the columns of the design matrix are not ',...
'orthogonal). In effect, the significance of the contrast is assessed ',...
'*after* accounting for the other effects in the design matrix. Thus, ',...
'if two covariates are correlated, testing the significance of the ',...
'parameter associated with one will only test for the part that is not ',...
'present in the second covariate. This is a general point that is also ',...
'true for F-contrasts. See Andrade et al, Ambiguous results in ',...
'functional neuroimaging, NeuroImage, 1999, for a full description of ',...
'the effect of non othogonal design testing.'],...
'','',...
'* Estimability',...
'',[...
'The contrast c''B is estimated by c''b, where b are the parameter ',...
'estimates given by b=pinv(X)*Y.'],...
'',[...
'However, if a design is rank-deficient (i.e. the columns of the ',...
'design matrix are not linearly independent), then the parameters are ',...
'not unique, and not all linear combinations of the parameter are ',...
'valid contrasts, since contrasts must be uniquely estimable.'],...
'',[...
'A weights vector defines a valid contrast if and only if it can be ',...
'constructed as a linear combination of the rows of the design matrix. ',...
'That is c'' (the transposed contrast vector - a row vector) is in the ',...
'row-space of the design matrix.'],...
'',[...
'Usually, a valid contrast will have weights that sum to zero over the ',...
'levels of a factor (such as condition).'],...
'',[...
'A simple example is a simple two condition design including a ',...
'constant, with design matrix'],...
'',...
' [ 1 0 1 ]',...
' [ : : : ]',...
' X = [ 1 0 1 ]',...
' [ 0 1 1 ]',...
' [ : : : ]',...
' [ 0 1 1 ]',...
'',[...
'The first column corresponds to condition 1, the second to condition ',...
'2, and the third to a constant (mean) term. Although there are three ',...
'columns to the design matrix, the design only has two degrees of ',...
'freedom, since any one column can be derived from the other two (for ',...
'instance, the third column is the sum of the first two). There is no ',...
'unique set of parameters for this model, since for any set of ',...
'parameters adding a constant to the two condition effects and ',...
'subtracting it from the constant effect yields another set of viable ',...
'parameters. However, the difference between the two condition effects ',...
'is uniquely estimated, so c''=[-1,+1,0] does define a contrast.'],...
'',[...
'If a parameter is estimable, then the weights vector with a single ',...
'"1" corresponding to that parameter (and zero elsewhere) defines a ',...
'valid contrast.'],...
'','',...
'* Multiple comparisons',...
'',[...
'Note that SPM implements no corrections to account for you looking at ',...
'multiple contrasts.'],...
'',[...
'If you are interested in a set of hypotheses that together define a ',...
'consistent question, then you should account for this when assessing ',...
'the individual contrasts. A simple Bonferroni approach would assess N ',...
'simultaneous contrasts at significance level alpha/N, where alpha is ',...
'the chosen significance level (usually 0.05).'],...
'',[...
'For two sided t-tests using SPM{T}s, the significance level should ',...
'be halved. When considering both SPM{T}s produced by a contrast and ',...
'it''s inverse (the contrast with negative weights), to effect a ',...
'two-sided test to look for both "increases" and "decreases", you ',...
'should review each SPM{T} at at level 0.05/2 rather than 0.05. (Or ',...
'consider an F-contrast!)'],...
'','',...
'* Contrast images and ESS images',...
'',[...
'For a simple contrast, SPM (spm_getSPM.m) writes a contrast image: ',...
'con_????.{img,nii}, with voxel values c''b. (The ???? in the image ',...
'names are replaced with the contrast number.) These contrast images ',...
'(for appropriate contrasts) are suitable summary images of an effect ',...
'at this level, and can be used as input at a higher level when ',...
'effecting a random effects analysis. See spm_RandFX.man for further ',...
'details.'],...
'',[...
'For an F-contrast, SPM (spm_getSPM.m) writes the Extra Sum-of-Squares ',...
'(the difference in the residual sums of squares for the full and ',...
'reduced model) as ess_????.{img,nii}. (Note that the ',...
'ess_????.{img,nii} and SPM{T,F}_????.{img,nii} images are not ',...
'suitable input for a higher level analysis.)']};
delete.type = 'menu';
delete.name = 'Delete existing contrasts';
delete.tag = 'delete';
delete.labels = {'Yes', 'No'};
delete.values = {1, 0};
delete.val = {0};
con.type = 'branch';
con.name = 'Contrast Manager';
con.tag = 'con';
con.val = {spm,consess,delete};
con.prog = @setupcon;
con.help = {'Set up T and F contrasts.'};
%-----------------------------------------------------------------------
function setupcon(varargin)
wd = pwd;
job = varargin{1};
% Change to the analysis directory
%-----------------------------------------------------------------------
if ~isempty(job)
try
pth = fileparts(job.spmmat{:});
cd(char(pth));
fprintf(' Changing directory to: %s\n',char(pth));
catch
error('Failed to change directory. Aborting contrast setup.')
end
end
% Load SPM.mat file
%-----------------------------------------------------------------------
tmp=load(job.spmmat{:});
SPM=tmp.SPM;
if ~strcmp(pth,SPM.swd)
warning(['Path to SPM.mat: %s\n and SPM.swd: %s\n differ, using current ' ...
'SPM.mat location as new working directory.'], pth, ...
SPM.swd);
SPM.swd = pth;
end;
if job.delete && isfield(SPM,'xCon')
for k=1:numel(SPM.xCon)
[p n e v] = spm_fileparts(SPM.xCon(k).Vcon.fname);
switch e,
case '.img'
spm_unlink([n '.img'],[n '.hdr']);
case '.nii'
spm_unlink(SPM.xCon(k).Vcon.fname);
end;
[p n e v] = spm_fileparts(SPM.xCon(k).Vspm.fname);
switch e,
case '.img'
spm_unlink([n '.img'],[n '.hdr']);
case '.nii'
spm_unlink(SPM.xCon(k).Vspm.fname);
end;
end;
SPM.xCon = [];
end;
bayes_con=isfield(SPM,'PPM');
if bayes_con
if ~isfield(SPM.PPM,'xCon')
% Retrospectively label Bayesian contrasts as T's, if this info is missing
for ii=1:length(SPM.xCon)
SPM.PPM.xCon(ii).PSTAT='T';
end
end
end
for i = 1:length(job.consess)
if isfield(job.consess{i},'tcon')
name = job.consess{i}.tcon.name;
if bayes_con
STAT = 'P';
SPM.PPM.xCon(end+1).PSTAT = 'T';
SPM.xX.V=[];
else
STAT = 'T';
end
con = job.consess{i}.tcon.convec(:)';
sessrep = job.consess{i}.tcon.sessrep;
elseif isfield(job.consess{i},'tconsess')
job.consess{i}.tconsess = job.consess{i}.tconsess; % save some typing
name = job.consess{i}.tconsess.name;
if bayes_con
STAT = 'P';
SPM.PPM.xCon(end+1).PSTAT = 'T';
SPM.xX.V=[];
else
STAT = 'T';
end
if isfield(job.consess{i}.tconsess.coltype,'colconds')
ccond = job.consess{i}.tconsess.coltype.colconds;
con = zeros(1,size(SPM.xX.X,2)); % overall contrast
for cs = job.consess{i}.tconsess.sessions
for k=1:numel(ccond)
if SPM.xBF.order < ccond(k).colbf
error(['Session-based contrast %d:\n'...
'Basis function order (%d) in design less ' ...
'than specified basis function number (%d).'],...
i, SPM.xBF.order, ccond(k).colbf);
end;
% Index into columns belonging to the specified
% condition
try
cind = ccond(k).colbf + ...
ccond(k).colmodord*SPM.xBF.order ...
*SPM.Sess(cs).U(ccond(k).colcond).P(ccond(k) ...
.colmod).i(ccond(k).colmodord+1);
con(SPM.Sess(cs).col(SPM.Sess(cs).Fc(ccond(k).colcond).i(cind))) ...
= ccond(k).conweight;
catch
error(['Session-based contrast %d:\n'...
'Column "Cond%d Mod%d Order%d" does not exist.'],...
i, ccond(k).colcond, ccond(k).colmod, ccond(k).colmodord);
end;
end;
end;
else % convec on extra regressors
con = zeros(1,size(SPM.xX.X,2)); % overall contrast
for cs = job.consess{i}.tconsess.sessions
nC = size(SPM.Sess(cs).C.C,2);
if nC < numel(job.consess{i}.tconsess.coltype.colreg)
error(['Session-based contrast %d:\n'...
'Contrast vector for extra regressors too long.'],...
i);
end;
ccols = numel(SPM.Sess(cs).col)-(nC-1)+...
[0:numel(job.consess{i}.tconsess.coltype.colreg)-1];
con(SPM.Sess(cs).col(ccols)) = job.consess{i}.tconsess.coltype.colreg;
end;
end;
sessrep = 'none';
else %fcon
name = job.consess{i}.fcon.name;
if bayes_con
STAT = 'P';
SPM.PPM.xCon(end+1).PSTAT = 'F';
SPM.xX.V=[];
else
STAT = 'F';
end
try
con = cat(1,job.consess{i}.fcon.convec{:});
catch
error('Error concatenating F-contrast vectors. Sizes are:\n %s\n',...
num2str(cellfun('length',job.consess{i}.fcon.convec)))
end
sessrep = job.consess{i}.fcon.sessrep;
end
if isfield(SPM,'Sess') && ~strcmp(sessrep,'none')
% assume identical sessions, no check!
nc = numel(SPM.Sess(1).U);
nsessions=numel(SPM.Sess);
rcon = zeros(size(con,1),nc);
switch sessrep
case 'repl',
% within-session zero padding, replication over sessions
cons{1}= zeros(size(con,1),size(SPM.xX.X,2));
for sess=1:nsessions
sfirst=SPM.Sess(sess).col(1);
cons{1}(:,sfirst:sfirst+size(con,2)-1)=con;
end
names{1} = sprintf('%s - All Sessions', name);
case 'sess',
for k=1:numel(SPM.Sess)
cons{k} = [zeros(size(con,1),SPM.Sess(k).col(1)-1) con];
names{k} = sprintf('%s - Session %d', name, k);
end;
case 'both'
for k=1:numel(SPM.Sess)
cons{k} = [zeros(size(con,1),SPM.Sess(k).col(1)-1) con];
names{k} = sprintf('%s - Session %d', name, k);
end;
if numel(SPM.Sess) > 1
% within-session zero padding, replication over sessions
cons{end+1}= zeros(size(con,1),size(SPM.xX.X,2));
for sess=1:nsessions
sfirst=SPM.Sess(sess).col(1);
cons{end}(:,sfirst:sfirst+size(con,2)-1)=con;
end
names{end+1} = sprintf('%s - All Sessions', name);
end;
end;
else
cons{1} = con;
names{1} = name;
end;
% Loop over created contrasts
%-------------------------------------------------------------------
for k=1:numel(cons)
% Basic checking of contrast
%-------------------------------------------------------------------
[c,I,emsg,imsg] = spm_conman('ParseCon',cons{k},SPM.xX.xKXs,STAT);
if ~isempty(emsg)
disp(emsg);
error('Error in contrast specification');
else
disp(imsg);
end;
% Fill-in the contrast structure
%-------------------------------------------------------------------
if all(I)
DxCon = spm_FcUtil('Set',names{k},STAT,'c',c,SPM.xX.xKXs);
else
DxCon = [];
end
% Append to SPM.xCon. SPM will automatically save any contrasts that
% evaluate successfully.
%-------------------------------------------------------------------
if isempty(SPM.xCon)
SPM.xCon = DxCon;
elseif ~isempty(DxCon)
SPM.xCon(end+1) = DxCon;
end
SPM = spm_contrasts(SPM,length(SPM.xCon));
end
end;
% Change back directory
%-----------------------------------------------------------------------
fprintf(' Changing back to directory: %s\n', wd);
cd(wd);
|
github
|
spm/spm5-master
|
spm.m
|
.m
|
spm5-master/spm.m
| 47,017 |
utf_8
|
c70b7f4583a4385043a1d626f2c05867
|
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 Department of Cognitive Neurology, 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(SPECT) & fMRI
% modalities Alternatively, `spm('pet')` and `spm('fmri')`
% (equivalently `spm pet` and `spm mri`) 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 1807 2008-06-10 13:39:01Z john $
%=======================================================================
% - 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 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 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 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 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,c]=spm('Ver',Mfile,ReDo,Cache,Con)
% Returns the current version (v) & copyright notice, extracted from
% the top line of the Contents.m file in the directory containing the
% currently used file Mfile (defaults on omission or empty to 'spm').
%
%-The version and copyright information are saved in a global
% variable called [upper(spm_str_manip(Mfile,'rt')),'_VER'], as a
% structure with fields 'v' and 'c'. This enables repeat use without
% recomputation.
%
%-If Con [default (missing or empty) 1] is false, then the version
% information is extracted from Mfile itself, rather than the
% Contents.m file in the same directory. When using a Contents.m file,
% the first line is read. For other files, the second line (the H1 help
% line) is used. This is for consistency with MATLAB's ver and help
% commands respectively. (This functionality enables toolboxes to be
% identified by a function rather than a Contents.m file, allowing
% installation in a directory which already has a Contents.m file.)
%
%-If Cache [default (missing or empty) 1] is true, then the version and
% copyright information cached in the global variable
% [upper(Mfile),'_VER'], as a structure with fields 'v' and 'c'. This
% enables repeat use without recomputation.
%
%-If ReDo [default (missing or empty) 0] is true, then the version and
% copyright information are recomputed (regardless of any stored global
% data).
%
% 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 [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 [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 v = spm('MLver')
% Returns MATLAB version, truncated to major & minor revision numbers
%
% 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 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 [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 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 spm('GUI_FileDelete')
% CallBack for GUI for file deletion, using spm_select and confirmation dialogs
%
% 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 spm('Help',varargin)
% Merely a gateway to spm_help(varargin) - so you can type "spm help"
%
%_______________________________________________________________________
%-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')
check_installation;
spm_defaults;
global defaults
if isfield(defaults,'modality'), spm(defaults.modality); return; end
%-Open startup window, set window defaults
%-----------------------------------------------------------------------
[T, Fwelcome] = evalc('openfig(''spm_Welcome'',''new'',''invisible'');');
set(Fwelcome,'name',sprintf('%s%s',spm('ver'),spm('GetUser',' (%s)')));
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(3)-RectW(3))/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)
check_installation;
%-Initialisation and workspace canonicalisation
%-----------------------------------------------------------------------
local_clc;
spm('AsciiWelcome'); fprintf('\n\nInitialising SPM');
Modality = upper(Action); fprintf('.');
delete(get(0,'Children')); fprintf('.');
%-Load startup global defaults
%-----------------------------------------------------------------------
spm_defaults; fprintf('.');
%-Draw SPM windows
%-----------------------------------------------------------------------
Fmenu = spm('CreateMenuWin','off'); fprintf('.');
Finter = spm('CreateIntWin','off'); fprintf('.');
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 'createmenuwin' %-Create SPM menu window
%=======================================================================
% Fmenu = spm('CreateMenuWin',Vis)
%-Close any existing 'Menu' 'Tag'ged windows
%-----------------------------------------------------------------------
delete(spm_figure('FindWin','Menu'))
[T, Fmenu] = evalc('openfig(''spm_Menu'',''new'',''invisible'');');
set(Fmenu,'name',sprintf('%s%s',spm('ver'),spm('GetUser',' (%s)')));
set(Fmenu,'Units','pixels', 'Position',spm('WinSize','M'));
%-Set SPM colour
%-----------------------------------------------------------------------
set(findobj(Fmenu,'Tag', 'frame'),'backgroundColor',spm('colour'));
%-Set toolbox
%-----------------------------------------------------------------------
xTB = spm('tbs');
set(findobj(Fmenu,'Tag', 'Toolbox'),'String',{'Toolbox:' xTB.name });
set(findobj(Fmenu,'Tag', 'Toolbox'),'UserData',xTB);
varargout = {Fmenu};
%=======================================================================
case 'createintwin' %-Create SPM interactive window
%=======================================================================
% Finter = spm('CreateIntWin',Vis)
%-----------------------------------------------------------------------
delete(spm_figure('FindWin','Interactive'))
[T, Finter] = evalc('openfig(''spm_Interactive'',''new'',''invisible'');');
set(Finter,'name',spm('Ver'));
set(Finter,'Units','pixels', 'Position',spm('WinSize','I'));
varargout = {Finter};
%=======================================================================
case 'chmod' %-Change SPM modality PET<->fMRI
%=======================================================================
% 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), error('SPM Menu window not found'), end
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);
spm_jobman('chmod',Modality);
%=======================================================================
case 'defaults' %-Set SPM defaults (as global variables)
%=======================================================================
% spm('defaults',Modality)
%-----------------------------------------------------------------------
global defaults
if isempty(defaults), spm_defaults; end
%-Sort out arguments
%-----------------------------------------------------------------------
if nargin<2, Modality=''; else Modality=varargin{2}; end
Modality = spm('CheckModality',Modality);
defaults.modality = Modality;
defaults.SWD = spm('Dir'); % SPM directory
defaults.TWD = spm_platform('tempdir'); % Temp directory
%-Set Modality specific default (global variables)
%-----------------------------------------------------------------------
global UFp
if strcmpi(defaults.modality,'pet')
UFp = defaults.stats.pet.ufp; % Upper tail F-prob
elseif strcmpi(defaults.modality,'fmri')
UFp = defaults.stats.fmri.ufp; % Upper tail F-prob
elseif strcmpi(defaults.modality,'eeg')
;
elseif strcmpi(defaults.modality,'unknown')
else
error('Illegal Modality');
end
%=======================================================================
case 'quit' %-Quit SPM and clean up
%=======================================================================
% spm('Quit')
%-----------------------------------------------------------------------
delete(get(0,'Children'));
local_clc;
fprintf('Bye for now...\n\n');
%=======================================================================
case 'checkmodality' %-Check & canonicalise modality string
%=======================================================================
% [Modality,ModNum] = spm('CheckModality',Modality)
%-----------------------------------------------------------------------
if nargin<2, Modality=''; else Modality=upper(varargin{2}); end
if isempty(Modality)
global defaults
if isfield(defaults,'modality'), Modality = defaults.modality;
else Modality = 'UNKNOWN'; 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), error('Unknown Modality'), end
varargout = {upper(Modality),ModNum};
%=======================================================================
case 'winscale' %-Window scale factors (to fit display)
%=======================================================================
% WS = spm('WinScale')
%-----------------------------------------------------------------------
if spm_matlab_version_chk('7') >=0
S0 = get(0, 'MonitorPosition');
else
S0 = get(0,'ScreenSize');
end
if all(S0(:)==1), error('Can''t open any graphics windows...'), end
S0 = S0(:,[3 4]) - S0(:,[1 2]) + 1;
S0 = S0 - rem(S0,2);
[m,i] = max(prod(S0,2));
S0 = S0(i,:);
tmp = [S0(1)/1152 (S0(2)-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
sf = 1 + 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]];
WS = spm('WinScale');
if isempty(Win)
WS = ones(3,1)*WS;
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
if spm_matlab_version_chk('7') >=0
Rect = get(0, 'MonitorPosition');
Rect = Rect(1,:);
else
Rect = get(0,'ScreenSize');
end
else
error('Unknown Win type');
end
if ~raw, Rect = Rect.*WS; end
varargout = {Rect};
%=======================================================================
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);
if exist('isdeployed','builtin') && isdeployed,
ind = findstr(SPMdir,'_mcr')-1;
SPMdir = fileparts(SPMdir(1:ind(1)));
end
varargout = {SPMdir};
%=======================================================================
case 'ver' %-SPM version
%=======================================================================
% SPMver = spm('Ver',Mfile,ReDo,Cache,Con)
%-----------------------------------------------------------------------
if nargin<5, Con=[]; else Con=varargin{5}; end
if isempty(Con), Con=1; end
if nargin<4, Cache=[]; else Cache=varargin{4}; end
if isempty(Cache), Cache=1; end
if nargin<3, ReDo=[]; else ReDo=varargin{3}; end
if isempty(ReDo), ReDo=0; end
if nargin<2, Mfile=''; else Mfile=varargin{2}; end
if isempty(Mfile), Mfile='spm'; end
xVname = [upper(spm_str_manip(Mfile,'rt')),'_VER'];
%-See if version info exists in global variable
%-----------------------------------------------------------------------
xV = spm('GetGlobal',xVname);
if ~ReDo && ~isempty(xV)
if isstruct(xV) && isfield(xV,'v') && isfield(xV,'c')
varargout = {xV.v,xV.c};
return
end
end
%-Work version out from file
%-----------------------------------------------------------------------
if Con
Vfile = fullfile(spm('Dir',Mfile),'Contents.m');
skip = 0; %-Don't skip first line
else
Vfile = which(Mfile);
if isempty(Vfile), error(['Can''t find ',Mfile,' on MATLABPATH']); end
skip = 1; %-Skip first line
end
if exist(Vfile,'file')
fid = fopen(Vfile,'r');
str = fgets(fid);
for i=1:skip, str=fgets(fid); end
fclose(fid);
str(1:max(1,min(find(str~='%' & str~=' '))-1))=[];
tmp = min(find(str==10|str==32));
v = str(1:tmp-1);
if str(tmp)==32
c = str(tmp+1:tmp+min(find(str(tmp+1:end)==10))-1);
else
c = '(c) Copyright reserved';
end
else
v = 'SPM';
c = '(c) Copyright reserved';
end
%-Store version info in global variable
%-----------------------------------------------------------------------
if Cache
eval(['global ',xVname])
eval([xVname,' = struct(''v'',v,''c'',c);'])
end
varargout = {v,c};
%=======================================================================
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(findstr(xTB(i).dir,path))
addpath(xTB(i).dir,'-begin');
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 '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'};
global defaults
if isempty(defaults), spm_defaults; end
if isfield(defaults,'ui') && isfield(defaults.ui,'colour2')
varargout{1} = defaults.ui.colour2;
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)
global defaults
if ~isempty(defaults) && isfield(defaults,'cmdline')
CmdLine = defaults.cmdline;
else
CmdLine = 0;
end
end
varargout = {CmdLine * (get(0,'ScreenDepth')>0)};
%=======================================================================
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 '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');
evalin('base',CBs{v-1})
%=======================================================================
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 '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',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 {'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, str = [str,' (v',varargin{3},')']; 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 '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 '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 'gui_filedelete' %-GUI file deletion
%=======================================================================
% spm('GUI_FileDelete')
%-----------------------------------------------------------------------
P = cellstr(spm_select(Inf,'.*','Select file(s) to delete'));
n = numel(P);
if n==0
spm('alert"','Nothing selected to delete!','file delete',0);
return
elseif 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 '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
set(0,'CurrentFigure',cF)
spm('FnBanner','GUI show');
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_select('clearvfiles');
spm_conman('Initialise','reset');
local_clc, spm('FnBanner','GUI cleared');
fprintf('\n');
%evalin('base','clear')
%=======================================================================
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
%=======================================================================
otherwise %-Unknown action string
%=======================================================================
error('Unknown action string')
%=======================================================================
end
%=======================================================================
function local_clc
%=======================================================================
if ~(exist('isdeployed','builtin') && isdeployed),
clc
end
%=======================================================================
function check_installation
%=======================================================================
if (exist('isdeployed','builtin') && isdeployed),
return
end
%-Disable warning messages due to dll files still existing
%-----------------------------------------------------------------------
if spm_matlab_version_chk('7') >=0,
warning('off','MATLAB:dispatcher:ShadowedMEXExtension');
end
%-Disable Java if necessary
%-----------------------------------------------------------------------
try
feature('JavaFigures',0);
end
%-Check installation
%-----------------------------------------------------------------------
spm('Ver','spm',1);
d = spm('Dir');
%-Check the search path
%-----------------------------------------------------------------------
if ~ismember(lower(d),lower(strread(path,'%s','delimiter',pathsep)))
error(sprintf([...
'You do not appear to have the MATLAB search path\n'...
'set up to include your SPM5 distribution. This\n'...
'means that you can start SPM in this directory,\n'...
'but if you change to another directory then MATLAB\n'...
'will be unable to find the SPM functions. You\n'...
'can use the editpath command in MATLAB to set it up.\n'...
'For more information, try typing the following:\n'...
' help path\n help editpath']));
end
%-Ensure that the original release - as well as the updates - was installed.
%-----------------------------------------------------------------------
if ~exist(fullfile(d,'spm_showdoc.m'),'file'), % This is a file that should not have changed
if isunix,
error(sprintf([...
'There appears to be some problem with the installation.\n'...
'The original spm5.tar.gz distribution should be installed\n'...
'and the updates installed on top of this. Unix commands\n'...
'to do this are:\n'...
' gunzip < spm5.tar.gz | tar xvf -\n'...
' cd spm5\n'...
' gunzip < Updates_????.tar.gz | tar xvf -\n'...
'You may need help from your local network administrator.']));
else
error(sprintf([...
'There appears to be some problem with the installation.\n'...
'The original spm5.tar.gz distribution should be installed\n'...
'and the updates installed on top of this. If in doubt,\n'...
'consult your local network administrator.']));
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\n'...
'.mat 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 .tar.gz files.'...
'Please ensure that the files are unpacked so that the\n'...
'directory structure is retained.']));
end
end
%-Check the mex files
%-----------------------------------------------------------------------
try
feval(@spm_atranspa,1);
catch
error(sprintf([...
'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\n'...
'for information about how to compile mex files for %s\n'...
'in MATLAB %s.'],...
d,filesep,filesep,computer,version));
end
|
github
|
spm/spm5-master
|
spm_orthviews.m
|
.m
|
spm5-master/spm_orthviews.m
| 68,912 |
utf_8
|
1dc045bfb0614e8391a168a981d1b05f
|
function varargout = spm_orthviews(action,varargin)
% Display Orthogonal Views of a Normalized Image
% FORMAT H = spm_orthviews('Image',filename[,position])
% filename - name of image to display
% area - position of image
% - area(1) - position x
% - area(2) - position y
% - area(3) - size x
% - area(4) - size y
% H - handle for ortho sections
% FORMAT spm_orthviews('BB',bb)
% bb - bounding box
% [loX loY loZ
% hiX hiY hiZ]
%
% 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 spm_orthviews('MaxBB')
% sets the bounding box big enough display the whole of all images
%
% FORMAT spm_orthviews('Resolution',res)
% res - resolution (mm)
%
% 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)
% Adds blobs from a pointlist to the image specified by the handle(s).
% handle - image number to add blobs to
% XYZ - blob voxel locations (currently in millimeters)
% Z - blob voxel intensities
% mat - matrix from millimeters to voxels 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('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 (currently in millimeters)
% Z - blob voxel intensities
% mat - matrix from millimeters to voxels 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('Register',hReg)
% See spm_XYZreg for more information.
%
% FORMAT spm_orthviews('RemoveBlobs',handle)
% Removes all blobs from the image specified by the handle(s).
%
% spm_orthviews('Register',hReg)
% hReg - Handle of HandleGraphics object to build registry in.
% See spm_XYZreg for more information.
%
% spm_orthviews('AddContext',handle)
% handle - image number to add context menu to
%
% spm_orthviews('RemoveContext',handle)
% handle - image number to remove context menu from
%
% CONTEXT MENU
% spm_orthviews offers many of its features in a context menu, which is
% accessible via the right mouse button in each displayed image.
%
% PLUGINS
% The display capabilities of spm_orthviews can be extended with
% plugins. These are located in the spm_orthviews subdirectory of the SPM
% distribution. Currently there are 3 plugins available:
% quiver Add Quiver plots to a displayed image
% quiver3d Add 3D Quiver plots to a displayed image
% roi ROI creation and modification
% 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) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner, Matthew Brett, Tom Nichols and Volkmar Glauche
% $Id: spm_orthviews.m 2946 2009-03-25 11:17:36Z volkmar $
% 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 I will document 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 files with a name
% spm_ov_PLUGINNAME.m in the directory 'SWD/spm_orthviews'.
% 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;
if isempty(st), reset_st; end;
spm('Pointer','watch');
if nargin == 0, action = ''; end;
action = lower(action);
switch lower(action),
case 'image',
H = specify_image(varargin{1});
if ~isempty(H)
st.vols{H}.area = [0 0 1 1];
if length(varargin)>=2, st.vols{H}.area = varargin{2}; end;
if isempty(st.bb), st.bb = maxbb; end;
bbox;
cm_pos;
end;
varargout{1} = H;
st.centre = mean(maxbb);
redraw_all
case 'bb',
if length(varargin)> 0 && 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 length(varargin)<1, tmp = findcent;
else tmp = varargin{1}; end;
if length(tmp)==3,
h = valid_handles(st.snap);
if ~isempty(h)
tmp=st.vols{h(1)}.mat*...
round(inv(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 length(varargin)<1,
st.Space = eye(4);
st.bb = maxbb;
bbox;
redraw_all;
else
space(varargin{:});
bbox;
redraw_all;
end;
case 'maxbb',
st.bb = maxbb;
bbox;
redraw_all;
case 'resolution',
resolution(varargin{1});
bbox;
redraw_all;
case 'window',
if length(varargin)<2,
win = 'auto';
elseif length(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 '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',
% 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 of image containing blob data [default - request via GUI]
% colourmap - colormap to display blobs in [GUI input]
% prop - intensity proportion of activation cf grayscale [0.4]
% mx - maximum intensity to scale to [maximum value in activation image]
% mn - minimum intensity to scale to [minimum value in activation image]
%
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 'rmblobs',
rmblobs(varargin{1});
redraw(varargin{1});
case 'addcontext',
if nargin == 1,
handles = 1:24;
else
handles = varargin{1};
end;
addcontexts(handles);
case '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);
otherwise,
addonaction = strcmp(st.plugins,action);
if any(addonaction)
feval(['spm_ov_' st.plugins{addonaction}],varargin{:});
end;
end;
spm('Pointer');
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 = length(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 = length(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 = length(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:length(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
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
res = arg1/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),
bb = [[1 1 1];st.vols{i}.dim(1:3)];
c = [ bb(1,1) bb(1,2) bb(1,3) 1
bb(1,1) bb(1,2) bb(2,3) 1
bb(1,1) bb(2,2) bb(1,3) 1
bb(1,1) bb(2,2) bb(2,3) 1
bb(2,1) bb(1,2) bb(1,3) 1
bb(2,1) bb(1,2) bb(2,3) 1
bb(2,1) bb(2,2) bb(1,3) 1
bb(2,1) bb(2,2) bb(2,3) 1]';
tc = st.Space\(st.vols{i}.premul*st.vols{i}.mat)*c;
tc = tc(1:3,:)';
mx = max([tc ; mx]);
mn = min([tc ; 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 H = specify_image(arg1)
global st
H=[];
ok = true;
if isstruct(arg1),
V = arg1(1);
else
try
V = spm_vol(arg1);
catch
fprintf('Can not use image "%s"\n', arg1);
return;
end;
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',...
['if strcmp(get(gcf,''SelectionType''),''normal''),spm_orthviews(''Reposition'');',...
'elseif strcmp(get(gcf,''SelectionType''),''extend''),spm_orthviews(''Reposition'');',...
'spm_orthviews(''context_menu'',''ts'',1);end;']);
d = image(0,'Tag','Transverse','Parent',ax,...
'DeleteFcn',DeleteFcn);
set(ax,'Ydir','normal','ButtonDownFcn',...
['if strcmp(get(gcf,''SelectionType''),''normal''),spm_orthviews(''Reposition'');',...
'elseif strcmp(get(gcf,''SelectionType''),''extend''),spm_orthviews(''reposition'');',...
'spm_orthviews(''context_menu'',''ts'',1);end;']);
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 addcontexts(handles)
global st
for ii = valid_handles(handles),
cm_handle = 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;
DeleteFcn = ['spm_orthviews(''Delete'',' num2str(i) ');'];
% 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.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*(st.Space\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*(st.Space\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*(st.Space\M)); SD = Dims([3 2]);
else
SM0 = [ 0 1 0 -bb(1,2)+1
0 0 1 -bb(1,3)+1
1 0 0 -cent(1)
0 0 0 1];
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*(st.Space\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.vols{i}.premul*st.vols{i}.blobs{1}.mat;
tmpt = spm_slice_vol(vol,inv(TM0*(st.Space\M)),TD,[0 NaN])';
tmpc = spm_slice_vol(vol,inv(CM0*(st.Space\M)),CD,[0 NaN])';
tmps = spm_slice_vol(vol,inv(SM0*(st.Space\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
vol = st.vols{i}.blobs{1}.vol;
mat = st.vols{i}.premul*st.vols{i}.blobs{1}.mat;
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.vols{i}.premul*st.vols{i}.blobs{1}.mat;
tmpt = spm_slice_vol(vol,inv(TM0*(st.Space\M)),TD,[0 NaN])';
tmpc = spm_slice_vol(vol,inv(CM0*(st.Space\M)),CD,[0 NaN])';
tmps = spm_slice_vol(vol,inv(SM0*(st.Space\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]);
redraw_colourbar(i,1,[cmn cmx],(1:64)'+64);
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));
for j=1:length(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:length(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;
handles = handles(:)';
handles = handles(handles<=24 & handles>=1 & ~rem(handles,1));
for h=handles,
if isempty(st.vols{h}), handles(handles==h)=[]; 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);
pluginpath = fullfile(spm('Dir'),'spm_orthviews');
if isdir(pluginpath)
pluginfiles = dir(fullfile(pluginpath,'spm_ov_*.m'));
if ~isempty(pluginfiles)
addpath(pluginpath);
% fprintf('spm_orthviews: Using Plugins in %s\n', pluginpath);
for k = 1:length(pluginfiles)
[p, pluginname, e, v] = spm_fileparts(pluginfiles(k).name);
st.plugins{k} = strrep(pluginname, 'spm_ov_','');
% fprintf('%s\n',st.plugins{k});
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', 'Separator','on');
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');
item1_1 = uimenu(item1, 'Label','Full Volume', 'Callback','spm_orthviews(''context_menu'',''zoom'',6);', 'Checked','on');
item1_2 = uimenu(item1, 'Label','160x160x160mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',5);');
item1_3 = uimenu(item1, 'Label','80x80x80mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',4);');
item1_4 = uimenu(item1, 'Label','40x40x40mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',3);');
item1_5 = uimenu(item1, 'Label','20x20x20mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',2);');
item1_6 = uimenu(item1, 'Label','10x10x10mm', 'Callback','spm_orthviews(''context_menu'',''zoom'',1);');
%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');
for i=1:3,
set(st.vols{volhandle}.ax{i}.ax,'UIcontextmenu',item_parent);
st.vols{volhandle}.ax{i}.cm = item_parent;
end;
if ~isempty(st.plugins) % process any plugins
for k = 1:numel(st.plugins),
feval(['spm_ov_', st.plugins{k}], ...
'context_menu', volhandle, item_parent);
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});
bbox;
redraw_all;
case 'xhair',
spm_orthviews('Xhairs',varargin{2});
cm_handles = get_cm_handles;
for i = 1:length(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:length(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:length(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:length(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:length(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:length(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:length(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;
spm_orthviews('window',current_handle,spm_input('Range','+1','e',defstr,2));
end;
case 'window_gl',
if varargin{2} == 2,
for i = 1:length(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;
data = spm_input('Range','+1','e',defstr,2);
for i = 1:length(get_cm_handles),
st.vols{i}.window = data;
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_figure('Clear','Interactive');
[SPM,VOL] = spm_getSPM;
for i = 1:length(cm_handles),
addblobs(cm_handles(i),VOL.XYZ,VOL.Z,VOL.M);
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;
end;
redraw_all;
case 'remove_blobs',
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
for i = 1:length(cm_handles),
rmblobs(cm_handles(i));
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');
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_figure('Clear','Interactive');
fname = spm_select(1,'image','select image');
for i = 1:length(cm_handles),
addimage(cm_handles(i),fname);
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;
end;
redraw_all;
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_figure('Clear','Interactive');
[SPM,VOL] = 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];
c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};
hlabel = sprintf('%s (%s)',VOL.title,c_names{c});
for i = 1:length(cm_handles),
addcolouredblobs(cm_handles(i),VOL.XYZ,VOL.Z,VOL.M,colours(c,:),VOL.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;
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];
c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};
for i = 1:length(cm_handles),
if isfield(st.vols{cm_handles(i)},'blobs'),
for j = 1:length(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_figure('Clear','Interactive');
fname = spm_select(1,'image','select image');
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)',fname,c_names{c});
for i = 1:length(cm_handles),
addcolouredimage(cm_handles(i),fname,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;
%_______________________________________________________________________
%_______________________________________________________________________
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:length(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(op)
global st
cm_handles = get_cm_handles;
res = [.125 .125 .25 .5 1 1];
if op==6,
st.bb = maxbb;
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)';
if op == 5, st.bb = [pos-80*vx ; pos+80*vx] ;
elseif op == 4, st.bb = [pos-40*vx ; pos+40*vx] ;
elseif op == 3, st.bb = [pos-20*vx ; pos+20*vx] ;
elseif op == 2, st.bb = [pos-10*vx ; pos+10*vx] ;
elseif op == 1; st.bb = [pos- 5*vx ; pos+ 5*vx] ;
else disp('no Zoom possible');
end;
end
resolution(res(op));
redraw_all;
for i = 1:length(cm_handles)
z_handle = get(findobj(cm_handles(i),'label','Zoom'),'Children');
set(z_handle,'Checked','off');
set(z_handle(op),'Checked','on');
end
return;
|
github
|
spm/spm5-master
|
spm_FcUtil.m
|
.m
|
spm5-master/spm_FcUtil.m
| 30,335 |
utf_8
|
e21305cc85524f7992a76dc648ebb11f
|
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) 2005 Wellcome Department of Imaging Neuroscience
% Jean-Baptiste Poline
% $Id: spm_FcUtil.m 112 2005-05-04 18:20:52Z john $
%-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',[]),... %!15/10
'iX0', [],...
'X1o', struct('ukX1o',[]),... %!15/10
'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; i = 1;
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
|
spm/spm5-master
|
spm_read_hdr.m
|
.m
|
spm5-master/spm_read_hdr.m
| 5,383 |
utf_8
|
97dd94a3164b5766dcc739ab2cdd041d
|
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) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_read_hdr.m 112 2005-05-04 18:20:52Z john $
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 = setstr([in(1:tmp)' zeros(1,length(in)-(tmp))])';
return;
%_______________________________________________________________________
%_______________________________________________________________________
|
github
|
spm/spm5-master
|
spm_eeg_inv_visu3D_api.m
|
.m
|
spm5-master/spm_eeg_inv_visu3D_api.m
| 26,874 |
utf_8
|
54b206a78840c7f9488c6600fa85999b
|
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 01-Feb-2007 20:16:13
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Jeremie Mattout
% $Id: spm_eeg_inv_visu3D_api.m 1079 2008-01-11 11:05:48Z guillaume $
% 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(lasterr);
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_ldata(spm_select(1, '.mat', 'Select EEG/MEG mat file'));
end
if ~isfield(D,'inv')
error(sprintf('Please specify and invert a foward 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 > length(D.inv{D.val}.inverse.J)
con = 1; D.con = 1;
end
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(:)));
% sensor data
%----------------------------------------------------------------------
handles.sens_data = U*Y*T(Ts,:)';
handles.pred_data = U*L*J(Is,:);
catch
warndlg({'Please invert your model';'inverse.J not found'});
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)')); 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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
try
load(fullfile(spm('dir'),'EEGtemplates',D.channels.ctf));
catch
try
Cpos = D.inv{1}.datareg.sens_coreg(:,[1 2])';
catch
[f,p] = uigetfile({'*.mat'}, 'EEGtemplate file (Cpos)');
load(fullfile(p,f))
end
end
try
Cpos = Cpos(:,D.channels.order(Cs));
catch
Cpos = Cpos(:,D.channels.order(D.channels.eeg));
end
xp = Cpos(1,:)';
yp = Cpos(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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(handles.fig)
axes(handles.sensors_axes);
cla; axis off
ic = 1:length(handles.sens_coord);
disp = full(handles.sens_data(ic,1));
imagesc(x,y,griddata(xp,yp,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(:,1),handles.sens_coord(:,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,yp,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');
ic = 1:length(handles.sens_coord);
% 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); cla
disp = griddata(handles.sens_coord(:,1),handles.sens_coord(:,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
axes(handles.pred_axes); cla
disp = griddata(handles.sens_coord(:,1),handles.sens_coord(:,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
% add sensor locations
%----------------------------------------------------------------------
axes(handles.sensors_axes)
try, delete(handles.sensor_loc); end
hold on
handles.sensor_loc = plot(handles.sens_coord(:,1),handles.sens_coord(:,2),'o','MarkerFaceColor',[1 1 1]/2,'MarkerSize',6);
hold 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,'b-.',handles.pst,handles.pred_data,'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_ldata(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
handles.vert = handles.D.inv{handles.D.val}.mesh.tess_ctx.vert;
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);
try
vde = getCursorInfo(handles.location);
catch
vde = [];
end
if ~length(vde)
handles.location = datacursormode(handles.fig);
set(handles.location,'Enable','on','DisplayStyle','datatip','SnapToDataVertex','on');
waitforbuttonpress
datacursormode off
end
vde = getCursorInfo(handles.location);
spm_eeg_invert_display(handles.D,vde.Position)
guidata(hObject,handles);
% --- Executes on button press in Rot.
function Rot_Callback(hObject, eventdata, handles)
%--------------------------------------------------------------------------
rotate3d(handles.sources_axes)
return
|
github
|
spm/spm5-master
|
spm_load.m
|
.m
|
spm5-master/spm_load.m
| 1,192 |
utf_8
|
dd89d9c3959f433fc4eefb539b6c1560
|
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) 2005 Wellcome Department of Imaging Neuroscience
% Karl Friston
% $Id: spm_load.m 184 2005-05-31 13:23:32Z john $
%-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
|
spm/spm5-master
|
spm_config_norm.m
|
.m
|
spm5-master/spm_config_norm.m
| 20,935 |
utf_8
|
b8b78e7c46191b433681134e138b9c25
|
function opts = spm_config_norm
% Configuration file for normalise jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_norm.m 1032 2007-12-20 14:45:55Z john $
%_______________________________________________________________________
smosrc.type = 'entry';
smosrc.name = 'Source Image Smoothing';
smosrc.tag = 'smosrc';
smosrc.strtype = 'e';
smosrc.num = [1 1];
smosrc.def = 'normalise.estimate.smosrc';
smosrc.help = {[...
'Smoothing to apply to a copy of the source image. ',...
'The template and source images should have approximately ',...
'the same smoothness. Remember that the templates supplied ',...
'with SPM have been smoothed by 8mm, and that smoothnesses ',...
'combine by Pythagoras'' rule.']};
%------------------------------------------------------------------------
smoref.type = 'entry';
smoref.name = 'Template Image Smoothing';
smoref.tag = 'smoref';
smoref.strtype = 'e';
smoref.num = [1 1];
smoref.def = 'normalise.estimate.smoref';
smoref.help = {[...
'Smoothing to apply to a copy of the template image. ',...
'The template and source images should have approximately ',...
'the same smoothness. Remember that the templates supplied ',...
'with SPM have been smoothed by 8mm, and that smoothnesses ',...
'combine by Pythagoras'' rule.']};
%------------------------------------------------------------------------
regtype.type = 'menu';
regtype.name = 'Affine Regularisation';
regtype.tag = 'regtype';
regtype.labels = {'ICBM space template', 'Average sized template','No regularisation'};
regtype.values = {'mni','subj','none'};
regtype.def = 'normalise.estimate.regtype';
regtype.help = {[...
'Affine registration into a standard space can be made more robust by ',...
'regularisation (penalising excessive stretching or shrinking). The ',...
'best solutions can be obtained by knowing the approximate amount of ',...
'stretching that is needed (e.g. ICBM templates are slightly bigger ',...
'than typical brains, so greater zooms are likely to be needed). ',...
'If registering to an image in ICBM/MNI space, then choose the first ',...
'option. If registering to a template that is close in size, then ',...
'select the second option. If you do not want to regularise, then ',...
'choose the third.']};
%------------------------------------------------------------------------
template.type = 'files';
template.name = 'Template Image';
template.tag = 'template';
template.filter = 'image';
template.num = [1 Inf];
template.help = {[...
'Specify a template image to match the source image with. ',...
'The contrast in the template must be similar to that of the ',...
'source image in order to achieve a good registration. It is ',...
'also possible to select more than one template, in which case ',...
'the registration algorithm will try to find the best linear ',...
'combination of these images in order to best model the intensities ',...
'in the source image.']};
%------------------------------------------------------------------------
weight.type = 'files';
weight.name = 'Template Weighting Image';
weight.tag = 'weight';
weight.filter = 'image';
weight.num = [0 1];
weight.def = 'normalise.estimate.weight';
p1 = [...
'Applies a weighting mask to the template(s) during the parameter ',...
'estimation. With the default brain mask, weights in and around the ',...
'brain have values of one whereas those clearly outside the brain are ',...
'zero. This is an attempt to base the normalisation purely upon ',...
'the shape of the brain, rather than the shape of the head (since ',...
'low frequency basis functions can not really cope with variations ',...
'in skull thickness).'];
p2 = [...
'The option is now available for a user specified weighting image. ',...
'This should have the same dimensions and mat file as the template ',...
'images, with values in the range of zero to one.'];
weight.help = {p1,'',p2};
%------------------------------------------------------------------------
cutoff.type = 'entry';
cutoff.name = 'Nonlinear Frequency Cutoff';
cutoff.tag = 'cutoff';
cutoff.strtype = 'e';
cutoff.num = [1 1];
cutoff.def = 'normalise.estimate.cutoff';
cutoff.help = {[...
'Cutoff of DCT bases. Only DCT bases of periods longer than the ',...
'cutoff are used to describe the warps. The number used will ',...
'depend on the cutoff and the field of view of the template image(s).']};
%------------------------------------------------------------------------
nits.type = 'entry';
nits.name = 'Nonlinear Iterations';
nits.tag = 'nits';
nits.strtype = 'w';
nits.num = [1 1];
nits.def = 'normalise.estimate.nits';
nits.help = {'Number of iterations of nonlinear warping performed.'};
%------------------------------------------------------------------------
reg.type = 'entry';
reg.name = 'Nonlinear Regularisation';
reg.tag = 'reg';
reg.strtype = 'e';
reg.num = [1 1];
reg.def = 'normalise.estimate.reg';
reg.help = {[...
'The amount of regularisation for the nonlinear part of the spatial ',...
'normalisation. ',...
'Pick a value around one. However, if your normalised images appear ',...
'distorted, then it may be an idea to increase the amount of ',...
'regularisation (by an order of magnitude) - or even just use an affine ',...
'normalisation. ',...
'The regularisation influences the smoothness of the deformation ',...
'fields.']};
%------------------------------------------------------------------------
wtsrc.type = 'files';
wtsrc.name = 'Source Weighting Image';
wtsrc.tag = 'wtsrc';
wtsrc.filter = 'image';
wtsrc.num = [0 1];
wtsrc.val = {{}};
wtsrc.help = {[...
'Optional weighting images (consisting of pixel ',...
'values between the range of zero to one) to be used for registering ',...
'abnormal or lesioned brains. These images should match the dimensions ',...
'of the image from which the parameters are estimated, and should contain ',...
'zeros corresponding to regions of abnormal tissue.']};
%------------------------------------------------------------------------
eoptions.type = 'branch';
eoptions.name = 'Estimation Options';
eoptions.tag = 'eoptions';
eoptions.val = {template,weight,smosrc,smoref,regtype,cutoff,nits,reg};
eoptions.help = {'Various settings for estimating warps.'};
%------------------------------------------------------------------------
preserve.type = 'menu';
preserve.name = 'Preserve';
preserve.tag = 'preserve';
preserve.labels = {'Preserve Concentrations','Preserve Amount'};
preserve.values = {0,1};
preserve.def = 'normalise.write.preserve';
p1 = ['Preserve Concentrations: ',...
'Spatially normalised images are not "modulated". The warped images ',...
'preserve the intensities of the original images.'];
p2 = ['Preserve Total: ',...
'Spatially normalised images are "modulated" in order to preserve the ',...
'total amount of signal in the images. Areas that are expanded during ',...
'warping are correspondingly reduced in intensity.'];
preserve.help = {p1,'',p2};
%------------------------------------------------------------------------
bb.type = 'entry';
bb.name = 'Bounding box';
bb.tag = 'bb';
bb.num = [2 3];
bb.strtype = 'e';
bb.def = 'normalise.write.bb';
bb.help = {[...
'The bounding box (in mm) of the volume which is to be written ',...
'(relative to the anterior commissure).']};
%------------------------------------------------------------------------
vox.type = 'entry';
vox.name = 'Voxel sizes';
vox.tag = 'vox';
vox.num = [1 3];
vox.strtype = 'e';
vox.def = 'normalise.write.vox';
vox.help = {'The voxel sizes (x, y & z, in mm) of the written normalised images.'};
%------------------------------------------------------------------------
interp.type = 'menu';
interp.name = 'Interpolation';
interp.tag = 'interp';
interp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-spline',...
'3rd Degree B-Spline ','4th Degree B-Spline ','5th Degree B-Spline',...
'6th Degree B-Spline','7th Degree B-Spline'};
interp.values = {0,1,2,3,4,5,6,7};
interp.def = 'normalise.write.interp';
interp.help = {...
['The method by which the images are sampled when being written in a ',...
'different space.'],...
[' Nearest Neighbour: ',...
' - Fastest, but not normally recommended.'],...
[' Bilinear Interpolation: ',...
' - OK for PET, or realigned fMRI.'],...
[' B-spline Interpolation: ',...
' - Better quality (but slower) interpolation/* \cite{thevenaz00a}*/, especially ',...
' with higher degree splines. Do not use B-splines when ',...
' there is any region of NaN or Inf in the images. '],...
};
%------------------------------------------------------------------------
wrap.type = 'menu';
wrap.name = 'Wrapping';
wrap.tag = 'wrap';
wrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z',...
'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'};
wrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]};
wrap.def = 'normalise.write.wrap';
wrap.help = {...
'These are typically:',...
[' No wrapping: for PET or images that have already ',...
' been spatially transformed. '],...
[' Wrap in Y: for (un-resliced) MRI where phase encoding ',...
' is in the Y direction (voxel space).']};
%------------------------------------------------------------------------
roptions.type = 'branch';
roptions.name = 'Writing Options';
roptions.tag = 'roptions';
roptions.val = {preserve,bb,vox,interp,wrap};
roptions.help = {'Various options for writing normalised images.'};
%------------------------------------------------------------------------
source.type = 'files';
source.name = 'Source Image';
source.tag = 'source';
source.num = [1 1];
source.filter = 'image';
source.help = {[...
'The image that is warped to match the template(s). The result is ',...
'a set of warps, which can be applied to this image, or any other ',...
'image that is in register with it.']};
scansr.type = 'files';
scansr.name = 'Images to Write';
scansr.tag = 'resample';
scansr.num = [1 Inf];
scansr.filter = 'image';
scansr.help = {[...
'These are the images for warping according to the estimated parameters. ',...
'They can be any images that are in register with the "source" image used ',...
'to generate the parameters.']};
matname.type = 'files';
matname.name = 'Parameter File';
matname.tag = 'matname';
matname.num = [1 1];
matname.filter = 'mat';
matname.ufilter = '.*_sn\.mat$';
matname.help = {[...
'Select the ''_sn.mat'' file containing the spatial normalisation ',...
'parameters for that subject.']};
%------------------------------------------------------------------------
subj.type = 'branch';
subj.name = 'Subject';
subj.tag = 'subj';
subj.val = {source, wtsrc};
subj.help = {'Data for this subject. The same parameters are used within subject.'};
data.type = 'repeat';
data.name = 'Data';
data.values = {subj};
data.num = [1 Inf];
data.help = {'List of subjects. Images of each subject should be warped differently.'};
est.type = 'branch';
est.name = 'Normalise: Estimate';
est.tag = 'est';
est.val = {data,eoptions};
est.prog = @estimate;
est.vfiles = @vfiles_estimate;
est.help = {[...
'Computes the warp that best registers a source image (or series of ',...
'source images) to match ',...
'a template, saving it to a file imagename''_sn.mat''.']};
%------------------------------------------------------------------------
subj.type = 'branch';
subj.name = 'Subject';
subj.tag = 'subj';
subj.val = {matname,scansr};
subj.help = {'Data for this subject. The same parameters are used within subject.'};
data.type = 'repeat';
data.name = 'Data';
data.values = {subj};
data.num = [1 Inf];
data.help = {'List of subjects. Images of each subject should be warped differently.'};
writ.type = 'branch';
writ.name = 'Normalise: Write';
writ.tag = 'write';
writ.val = {data,roptions};
writ.prog = @write;
writ.vfiles = @vfiles_write;
writ.help = {[...
'Allows previously estimated warps (stored in imagename''_sn.mat'' files) ',...
'to be applied to series of images.']};
%------------------------------------------------------------------------
subj.type = 'branch';
subj.name = 'Subject';
subj.tag = 'subj';
subj.val = {source, wtsrc, scansr};
subj.help = {'Data for this subject. The same parameters are used within subject.'};
data.type = 'repeat';
data.name = 'Data';
data.values = {subj};
data.num = [1 Inf];
data.help = {'List of subjects. Images of each subject should be warped differently.'};
estwrit.type = 'branch';
estwrit.name = 'Normalise: Estimate & Write';
estwrit.tag = 'estwrite';
estwrit.val = {data,eoptions,roptions};
estwrit.prog = @estwrite;
estwrit.vfiles = @vfiles_estwrite;
estwrit.help = {[...
'Computes the warp that best registers a source image (or series of ',...
'source images) to match ',...
'a template, saving it to the file imagename''_sn.mat''. ',...
'This option also allows the contents of the imagename''_sn.mat'' ',...
'files to be applied to a series of images.']};
%------------------------------------------------------------------------
opts.type = 'repeat';
opts.name = 'Normalise';
opts.tag = 'normalise';
opts.values = {est,writ,estwrit};
opts.num = [1 Inf];
opts.modality = {'FMRI','PET','VBM'};
p1 = [...
'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.'];
p2 = [...
'Generally, the algorithms work by minimising the sum of squares ',...
'difference between the image which is to be normalised, and a linear ',...
'combination of one or more template images. For the least squares ',...
'registration to produce an unbiased estimate of the spatial ',...
'transformation, the image contrast in the templates (or linear ',...
'combination of templates) should be similar to that of the image from ',...
'which the spatial normalisation is derived. The registration simply ',...
'searches for an optimum solution. If the starting estimates are not ',...
'good, then the optimum it finds may not find the global optimum.'];
p3 = [...
'The first step of the normalisation 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 maximises the a ',...
'posteriori probability of it being correct /* \cite{ashburner97b} */. i.e., it maximises the ',...
'product of the likelihood function (derived from the residual squared ',...
'difference) and the prior function (which is based on the probability ',...
'of obtaining a particular set of zooms and shears).'];
p4 = [...
'The affine registration is followed by estimating nonlinear deformations, ',...
'whereby the deformations are defined by a linear combination of three ',...
'dimensional discrete cosine transform (DCT) basis functions /* \cite{ashburner99a} */. The default ',...
'options result in each of the deformation fields being described by 1176',...
'parameters, where these represent the coefficients of the deformations in ',...
'three orthogonal directions. The matching involved simultaneously ',...
'minimising the membrane energies of the deformation fields and the ',...
'residual squared difference between the images and template(s).'];
p5 = [...
'The primarily use is for stereotactic normalisation to facilitate inter-subject ',...
'averaging and precise characterisation of functional anatomy /* \cite{ashburner97bir} */. It is ',...
'not necessary to spatially normalise the data (this is only a ',...
'pre-requisite for inter-subject averaging or reporting in the ',...
'Talairach space). If you wish to circumnavigate this step (e.g. if ',...
'you have single slice data or do not have an appropriate high ',...
'resolution MRI scan) simply specify where you think the anterior ',...
'commissure is with the ORIGIN in the header of the first scan ',...
'(using the ''Display'' facility) and proceed directly to ''Smoothing''',...
'or ''Statistics''.'];
p6 = [...
'All normalised *.img scans are written to the same subdirectory as ',...
'the original *.img, prefixed with a ''w'' (i.e. w*.img). The details ',...
'of the transformations are displayed in the results window, and the ',...
'parameters are saved in the "*_sn.mat" file.'];
opts.help = {p1,'',...
p2,'',p3,'',p4,'',...
p5,'',...
p6};
%------------------------------------------------------------------------
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function estimate(varargin)
job = varargin{1};
o = job.eoptions;
eflags = struct(...
'smosrc', o.smosrc,...
'smoref', o.smoref,...
'regtype',o.regtype,...
'cutoff', o.cutoff,...
'nits', o.nits,...
'reg', o.reg);
for i=1:length(job.subj),
[pth,nam,ext,ind] = spm_fileparts(strvcat(job.subj(i).source{:}));
matname = fullfile(pth,[nam '_sn.mat']);
spm_normalise(strvcat(job.eoptions.template{:}),...
strvcat(job.subj(i).source{:}), matname,...
strvcat(job.eoptions.weight{:}), strvcat(job.subj(i).wtsrc{:}), eflags);
end;
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function write(varargin)
job = varargin{1};
o = job.roptions;
rflags = struct(...
'preserve',o.preserve,...
'bb', o.bb,...
'vox', o.vox,...
'interp', o.interp,...
'wrap', o.wrap);
for i=1:length(job.subj),
spm_write_sn(strvcat(job.subj(i).resample{:}),...
strvcat(job.subj(i).matname{:}),rflags);
end;
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function estwrite(varargin)
job = varargin{1};
o = job.eoptions;
eflags = struct(...
'smosrc', o.smosrc,...
'smoref', o.smoref,...
'regtype',o.regtype,...
'cutoff', o.cutoff,...
'nits', o.nits,...
'reg', o.reg);
o = job.roptions;
rflags = struct(...
'preserve',o.preserve,...
'bb', o.bb,...
'vox', o.vox,...
'interp', o.interp,...
'wrap', o.wrap);
for i=1:length(job.subj),
[ pth,nam ] = spm_fileparts(deblank(job.subj(i).source{:}));
matname = fullfile(pth,[nam,'_sn.mat']);
spm_normalise(strvcat(job.eoptions.template{:}),...
strvcat(job.subj(i).source{:}), matname,...
strvcat(job.eoptions.weight{:}), strvcat(job.subj(i).wtsrc{:}), eflags);
spm_write_sn(strvcat(job.subj(i).resample{:}), matname, rflags);
end;
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles_estimate(varargin)
job = varargin{1};
vf = cell(length(job.subj),1);
for i=1:length(job.subj),
[pth,nam,ext,num] = spm_fileparts(deblank(job.subj(i).source{:}));
vf{i} = fullfile(pth,[nam,'_sn.mat']);
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles_estwrite(varargin)
job = varargin{1};
vf = cell(length(job.subj),1);
for i=1:length(job.subj),
[pth,nam,ext,num] = spm_fileparts(deblank(job.subj(i).source{:}));
vf{i} = fullfile(pth,[nam,'_sn.mat']);
end;
for i=1:length(job.subj),
res = job.subj(i).resample;
vf1 = cell(1,length(res));
for j=1:length(res),
[pth,nam,ext,num] = spm_fileparts(res{j});
vf1{j} = fullfile(pth,['w', nam, ext, num]);
end;
vf = {vf{:} vf1{:}};
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles_write(varargin)
job = varargin{1};
vf = {};
for i=1:length(job.subj),
res = job.subj(i).resample;
vf1 = cell(1,length(res));
for j=1:length(res),
[pth,nam,ext,num] = spm_fileparts(res{j});
vf1{j} = fullfile(pth,['w', nam, ext, num]);
end;
vf = {vf{:} vf1{:}};
end;
|
github
|
spm/spm5-master
|
spm_reslice.m
|
.m
|
spm5-master/spm_reslice.m
| 14,569 |
utf_8
|
6fed692ad7fdef9eb860ab513323f73d
|
function spm_reslice(P,flags)
% Rigid body reslicing of images
% FORMAT spm_reslice(P,flags)
%
% P - matrix 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 (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 (1 for yes, 0 for no)
% The average of all the realigned scans is written to
% mean*.img.
%
% interp - the B-spline interpolation method.
% 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.
% 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.
%
% The spatially realigned images are written to the orginal
% subdirectory with the same filename but prefixed with an 'r'.
% They are all aligned with the first.
%__________________________________________________________________________
%
% Inputs
% A series of *.img conforming to SPM data format (see 'Data Format'). The
% relative displacement of the images is stored in their ".mat" files.
%
% Outputs
% The routine uses information in these ".mat" files and writes the
% realigned *.img files to the same subdirectory prefixed with an 'r'
% (i.e. r*.img).
%__________________________________________________________________________
%
% The `.mat' files.
%
% This simply contains a 4x4 affine transformation matrix in a variable `M'.
% These files are normally generated by the `realignment' and
% `coregistration' modules. What these matrixes 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). By default, the
% the new coordinate system is derived from the `origin' and `vox' fields
% of the image header.
%
% 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).
%
% These `.mat' files allow several realignment or coregistration steps to be
% combined into a single operation (without the necessity of resampling the
% images several times). The `.mat' files are also used by the spatial
% normalisation module.
%__________________________________________________________________________
% 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. Submitted to MRM (April 1999) and avaliable from:
% http://varda.biophysics.mcw.edu/~cox/index.html.
%
%__________________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_reslice.m 1020 2007-12-06 20:20:31Z john $
def_flags = struct('interp',1,'mask',1,'mean',1,'which',2,'wrap',[0 0 0]');
if nargin < 2,
flags = def_flags;
else,
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));
end;
end;
end;
if iscell(P), P = strvcat(P{:}); end;
if ischar(P), P = spm_vol(P); end;
reslice_images(P,flags);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function reslice_images(P,flags)
% Reslices images volume by volume
% FORMAT reslice_images(P,flags)
%
% P - matrix of image handles from spm_vol.
% All operations are performed relative to the first image.
% ie. resampling of images is into the space of the first image.
%
% 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 B-spline interpolation method (see spm_bsplinc and spm_bsplins).
% Non-finite values result in Fourier interpolation
%
% which - Values of 0, 1 or 2 are allowed.
% 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.
% 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].
%
% The spatially realigned images are written to the orginal
% subdirectory with the same filename but prefixed with an 'r'.
% They are all aligned with the first.
if ~isfinite(flags.interp), % Use Fourier method
% Check for non-rigid transformations in the matrixes
for i=1:prod(size(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:prod(size(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 ~= prod(size(P))); end;
if flags.mean, Count(:,:,x3) = tmp; end;
spm_progress_bar('Set',x3);
end;
end;
nread = prod(size(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');
tiny = 5e-2; % From spm_vol_utils.c
[x1,x2] = ndgrid(1:P(1).dim(1),1:P(1).dim(2));
PO = P;
nread = 0;
d = [flags.interp*[1 1 1]' flags.wrap(:)];
for i = 1:prod(size(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,['r' 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,vr] = 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 = [4 spm_platform('bigend')];
spm_write_vol(PO,Integral);
end
spm_figure('Clear','Interactive');
return;
%_______________________________________________________________________
%_______________________________________________________________________
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
% Submitted to MRM (April 1999) and avaliable from:
% http://varda.biophysics.mcw.edu/~cox/index.html.
% and:
% 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;
return;
%_______________________________________________________________________
%_______________________________________________________________________
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
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]];
return;
%_______________________________________________________________________
%_______________________________________________________________________
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 = logical(ones(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;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vo = nan2zero(vi)
vo = vi;
vo(~isfinite(vo)) = 0;
return;
%_______________________________________________________________________
%_______________________________________________________________________
|
github
|
spm/spm5-master
|
spm_config_defs.m
|
.m
|
spm5-master/spm_config_defs.m
| 9,994 |
utf_8
|
2b2b68477701f342d0f333362d8fb2ec
|
function conf = spm_config_defs
% Configuration file for deformation jobs.
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_defs.m 1032 2007-12-20 14:45:55Z john $
entry = inline(['struct(''type'',''entry'',''name'',name,'...
'''tag'',tag,''strtype'',strtype,''num'',num)'],...
'name','tag','strtype','num');
files = inline(['struct(''type'',''files'',''name'',name,'...
'''tag'',tag,''filter'',fltr,''num'',num)'],...
'name','tag','fltr','num');
branch = inline(['struct(''type'',''branch'',''name'',name,'...
'''tag'',tag,''val'',{val})'],...
'name','tag','val');
repeat = inline(['struct(''type'',''repeat'',''name'',name,'...
'''tag'',tag,''values'',{values})'],...
'name','tag','values');
mnu = inline(['struct(''type'',''menu'',''name'',name,'...
'''tag'',tag,''labels'',{labels},''values'',{values},''help'',{{}})'],...
'name','tag','labels','values');
%--------------------------------------------------------------------
hsummary = {[...
'This is a utility for working with deformation fields. ',...
'They can be loaded, inverted, combined etc, and the results ',...
'either saved to disk, or applied to some image.'],...
'',[...
'Note that ideal deformations can be treated as members of a Lie group. ',...
'Future versions of SPM may base its warping on such principles.']};
hinv = {[...
'Creates the inverse of a deformation field. ',...
'Deformations are assumed to be one-to-one, in which case they ',...
'have a unique inverse. If y'':A->B is the inverse of y:B->A, then ',...
'y'' o y = y o y'' = Id, where Id is the identity transform.'],...
'',...
'Deformations are inverted using the method described in the appendix of:',...
[' * Ashburner J, Andersson JLR & Friston KJ (2000) ',...
'"Image Registration using a Symmetric Prior - in Three-Dimensions." ',...
'Human Brain Mapping 9(4):212-225']};
hcomp = {[...
'Deformation fields can be thought of as mappings. ',...
'These can be combined by the operation of "composition", which is ',...
'usually denoted by a circle "o". ',...
'Suppose x:A->B and y:B->C are two mappings, where A, B and C refer ',...
'to domains in 3 dimensions. ',...
'Each element a in A points to element x(a) in B. ',...
'This in turn points to element y(x(a)) in C, so we have a mapping ',...
'from A to C. ',...
'The composition of these mappings is denoted by yox:A->C. ',...
'Compositions can be combined in an associative way, such that zo(yox) = (zoy)ox.'],...
'',[...
'In this utility, the left-to-right order of the compositions is ',...
'from top to bottom (note that the rightmost deformation would ',...
'actually be applied first). ',...
'i.e. ...((first o second) o third)...o last. The resulting deformation field will ',...
'have the same domain as the first deformation specified, and will map ',...
'to voxels in the codomain of the last specified deformation field.']};
hsn = {[...
'Spatial normalisation, and the unified segmentation model of ',...
'SPM5 save a parameterisation of deformation fields. These consist ',...
'of a combination of an affine transform, and nonlinear warps that ',...
'are parameterised by a linear combination of cosine transform ',...
'basis functions. These are saved in *_sn.mat files, which can be ',...
'converted to deformation fields.']};
hvox = {[...
'Specify the voxel sizes of the deformation field to be produced. ',...
'Non-finite values will default to the voxel sizes of the template image',...
'that was originally used to estimate the deformation.']};
hbb = {[...
'Specify the bounding box of the deformation field to be produced. ',...
'Non-finite values will default to the bounding box of the template image',...
'that was originally used to estimate the deformation.']};
himgr = {[...
'Deformations can be thought of as vector fields. These can be represented ',...
'by three-volume images.']};
himgw = {[...
'Save the result as a three-volume image. "y_" will be prepended to the ',...
'filename. The result will be written to the current directory.']};
happly = {[...
'Apply the resulting deformation field to some images. ',...
'The warped images will be written to the current directory, and the ',...
'filenames prepended by "w". Note that trilinear interpolation is used ',...
'to resample the data, so the original values in the images will ',...
'not be preserved.']};
hmatname = {[...
'Specify the _sn.mat to be used.']};
himg = {[...
'Specify the image file on which to base the dimensions, orientation etc.']};
hid = {[...
'This option generates an identity transform, but this can be useful for '...
'changing the dimensions of the resulting deformation (and any images that '...
'are generated from it). Dimensions, orientation etc are derived from '...
'an image.']};
def = files('Deformation Field','def','.*y_.*\.nii$',1);
def.help = himgr;
matname = files('Parameter File','matname','.*_sn\.mat$',[1 1]);
matname.help = hmatname;
vox = entry('Voxel sizes','vox','e',[1 3]);
vox.val = {[NaN NaN NaN]};
vox.help = hvox;
bb = entry('Bounding box','bb','e',[2 3]);
bb.val = {NaN*ones(2,3)};
bb.help = hbb;
sn2def = branch('Imported _sn.mat','sn2def',{matname,vox,bb});
sn2def.help = hsn;
img = files('Image to base Id on','space','image',1);
img.help = himg;
id = branch('Identity','id',{img});
id.help = hid;
if spm_matlab_version_chk('7') <= 0,
ffield = files('Flow field','flowfield','nifti',[1 1]);
ffield.ufilter = '^u_.*';
ffield.help = {...
['The flow field stores the deformation information. '...
'The same field can be used for both forward or backward deformations '...
'(or even, in principle, half way or exaggerated deformations).']};
%------------------------------------------------------------------------
forbak = mnu('Forward/Backwards','times',{'Backward','Forward'},{[1 0],[0 1]});
forbak.val = {[1 0]};
forbak.help = {[...
'The direction of the DARTEL flow. '...
'Note that a backward transform will warp an individual subject''s '...
'to match the template (ie maps from template to individual). '...
'A forward transform will warp the template image to the individual.']};
%------------------------------------------------------------------------
K = mnu('Time Steps','K',...
{'1','2','4','8','16','32','64','128','256','512'},...
{0,1,2,3,4,5,6,7,8,9});
K.val = {6};
K.help = {...
['The number of time points used for solving the '...
'partial differential equations. A single time point would be '...
'equivalent to a small deformation model. '...
'Smaller values allow faster computations, '...
'but are less accurate in terms '...
'of inverse consistency and may result in the one-to-one mapping '...
'breaking down.']};
%------------------------------------------------------------------------
drtl = branch('DARTEL flow','dartel',{ffield,forbak,K});
drtl.help = {'Imported DARTEL flow field.'};
%------------------------------------------------------------------------
other = {sn2def,drtl,def,id};
else
other = {sn2def,def,id};
end
img = files('Image to base inverse on','space','image',1);
img.help = himg;
comp0 = repeat('Composition','comp',other);
comp0.help = hcomp;
iv0 = branch('Inverse','inv',{comp0,img});
iv0.help = hinv;
comp1 = repeat('Composition','comp',{other{:},iv0,comp0});
comp1.help = hcomp;
comp1.check = @check;
iv1 = branch('Inverse','inv',{comp1,img});
iv1.help = hinv;
comp2 = repeat('Composition','comp',{other{:},iv1,comp1});
comp2.help = hcomp;
comp2.check = @check;
iv2 = branch('Inverse','inv',{comp2,img});
iv2.help = hinv;
comp = repeat('Composition','comp',{other{:},iv2,comp2});
comp.help = hcomp;
comp.check = @check;
saveas = entry('Save as','ofname','s',[1 Inf]);
saveas.val = {''};
saveas.help = himgw;
applyto = files('Apply to','fnames','image',[0 Inf]);
applyto.val = {''};
applyto.help = happly;
interp.type = 'menu';
interp.name = 'Interpolation';
interp.tag = 'interp';
interp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-spline',...
'3rd Degree B-Spline ','4th Degree B-Spline ','5th Degree B-Spline',...
'6th Degree B-Spline','7th Degree B-Spline'};
interp.values = {0,1,2,3,4,5,6,7};
interp.def = 'normalise.write.interp';
interp.help = {...
['The method by which the images are sampled when being written in a ',...
'different space.'],...
[' Nearest Neighbour: ',...
' - Fastest, but not normally recommended.'],...
[' Bilinear Interpolation: ',...
' - OK for PET, or realigned fMRI.'],...
[' B-spline Interpolation: ',...
' - Better quality (but slower) interpolation/* \cite{thevenaz00a}*/, especially ',...
' with higher degree splines. Do not use B-splines when ',...
' there is any region of NaN or Inf in the images. '],...
};
conf = branch('Deformations','defs',{comp,saveas,applyto,interp});
conf.prog = @spm_defs;
conf.vfiles = @vfiles;
conf.help = hsummary;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function str = check(job)
str = '';
if isempty(job),
str = 'Empty Composition';
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vf = vfiles(job)
vf = {};
s = strvcat(job.ofname);
if ~isempty(s),
vf = {vf{:}, fullfile(pwd,['y_' s '.nii,1'])};
end;
s = strvcat(job.fnames);
for i=1:size(s,1),
[pth,nam,ext,num] = spm_fileparts(s(i,:));
vf = {vf{:}, fullfile(pwd,['w',nam,ext,num])};
end;
return;
|
github
|
spm/spm5-master
|
spm_showdoc.m
|
.m
|
spm5-master/spm_showdoc.m
| 4,017 |
utf_8
|
63defc367211a2209a2d1710248b6cdc
|
function spm_showdoc(c)
% Show SPM documentation
%
% This function extracts and displays SPM documentation.
%
% Example usage:
% diary('spmdoc.txt'); spm_showdoc; diary off
%
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_showdoc.m 112 2005-05-04 18:20:52Z john $
if nargin==0,
c = spm_config;
end;
fprintf('\n\nSPM DOCUMENTATION\n\nTable of Contents\n----- -- --------\n');
contents(c);
fprintf('%s\n%s\n\n\n',repmat('_',1,80),repmat('_',1,80));
maintext(c);
return;
function contents(c,lev)
if nargin==1,
lev = '';
end;
if isfield(c,'name'),
str = [lev repmat(' ',1,25-length(lev)) c.name];
fprintf('%s\n',str);
i = 0;
if isfield(c,'values'),
for ii=1:length(c.values),
if isstruct(c.values{ii}) && isfield(c.values{ii},'name'),
i = i+1;
lev1 = sprintf('%s%d.', lev, i);
contents(c.values{ii},lev1);
end;
end;
end;
if isfield(c,'val'),
for ii=1:length(c.val),
if isstruct(c.val{ii}) && isfield(c.val{ii},'name'),
i = i+1;
lev1 = sprintf('%s%d.', lev, i);
contents(c.val{ii},lev1);
end;
end;
end;
end;
return;
function maintext(c, lev)
if nargin==1,
lev = '';
end;
if ~isempty(lev) && sum(lev=='.')==1,
disp(repmat('_',1,80));
fprintf('\n');
end;
if isfield(c,'name'),
str = sprintf('%s %s', lev, c.name);
under = repmat('-',1,length(str));
fprintf('%s\n%s\n', str, under);
if isfield(c,'modality'),
fprintf('Only for');
for i=1:numel(c.modality),
fprintf(' %s',c.modality{i});
end;
fprintf('\n\n');
end;
if isfield(c,'help');
hlp = spm_justify(80,c.help);
disp(strvcat(hlp{:}));
end;
switch (c.type),
case {'repeat'},
if length(c.values)==1,
fprintf('\nRepeat "%s", any number of times.\n',c.values{1}.name);
else
fprintf('\nAny of the following options can be chosen, any number of times\n');
i = 0;
for ii=1:length(c.values),
if isstruct(c.values{ii}) && isfield(c.values{ii},'name'),
i = i+1;
fprintf(' %2d) %s\n', i,c.values{ii}.name);
end;
end;
end;
fprintf('\n');
case {'choice'},
fprintf('\nAny one of these options can be selected:\n');
i = 0;
for ii=1:length(c.values),
if isstruct(c.values{ii}) && isfield(c.values{ii},'name'),
i = i+1;
fprintf(' %2d) %s\n', i,c.values{ii}.name);
end;
end;
fprintf('\n');
case {'branch'},
fprintf('\nThis item contains %d fields:\n', length(c.val));
i = 0;
for ii=1:length(c.val),
if isstruct(c.val{ii}) && isfield(c.val{ii},'name'),
i = i+1;
fprintf(' %2d) %s\n', i,c.val{ii}.name);
end;
end;
fprintf('\n');
case {'menu'},
fprintf('\nOne of these values is chosen:\n');
for k=1:length(c.labels),
fprintf(' %2d) %s\n', k, c.labels{k});
end;
fprintf('\n');
case {'files'},
if length(c.num)==1 && isfinite(c.num(1)) && c.num(1)>=0,
fprintf('\nA "%s" file is selected by the user.\n',c.filter);
else
fprintf('\n"%s" files are selected by the user.\n',c.filter);
end;
case {'entry'},
switch c.strtype,
case {'e'},
d = 'Evaluated statements';
case {'n'},
d = 'Natural numbers';
case {'r'},
d = 'Real numbers';
case {'w'},
d = 'Whole numbers';
otherwise,
d = 'Values';
end;
fprintf('\n%s are typed in by the user.\n',d);
end;
i = 0;
fprintf('\n');
if isfield(c,'values'),
for ii=1:length(c.values),
if isstruct(c.values{ii}) && isfield(c.values{ii},'name'),
i = i+1;
lev1 = sprintf('%s%d.', lev, i);
maintext(c.values{ii},lev1);
end;
end;
end;
if isfield(c,'val'),
for ii=1:length(c.val),
if isstruct(c.val{ii}) && isfield(c.val{ii},'name'),
i = i+1;
lev1 = sprintf('%s%d.', lev, i);
maintext(c.val{ii},lev1);
end;
end;
end;
fprintf('\n');
end;
|
github
|
spm/spm5-master
|
spm_maff.m
|
.m
|
spm5-master/spm_maff.m
| 11,342 |
utf_8
|
137adfbac77cee275f3852ad16738cf3
|
function [M,h] = 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) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_maff.m 2526 2008-12-03 11:42:57Z john $
[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] = priors(regtyp);
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_chi2_plot('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_chi2_plot('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 + spm_atranspa(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_chi2_plot('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.'); 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]);
P = real(P);
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 [mu,isig] = priors(typ)
% The parameters for this distribution were derived empirically from 227
% scans, that were matched to the ICBM space.
%% Values can be derived by...
%sn = spm_select(Inf,'.*seg_inv_sn.mat$');
%X = zeros(size(sn,1),12);
%for i=1:size(sn,1),
% p = load(deblank(sn(i,:)));
% M = p.VF(1).mat*p.Affine/p.VG(1).mat;
% J = M(1:3,1:3);
% V = sqrtm(J*J');
% R = V\J;
% lV = logm(V);
% lR = -logm(R);
% 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]);
% X(i,:) = P';
%end;
%mu = mean(X(:,7:12));
%XR = X(:,7:12) - repmat(mu,[size(X,1),1]);
%isig = inv(XR'*XR/(size(X,1)-1))
mu = zeros(6,1);
isig = zeros(6);
switch deblank(lower(typ))
case 'mni', % For registering with MNI templates...
mu = [0.0667 0.0039 0.0008 0.0333 0.0071 0.1071]';
isig = 1e4 * [
0.0902 -0.0345 -0.0106 -0.0025 -0.0005 -0.0163
-0.0345 0.7901 0.3883 0.0041 -0.0103 -0.0116
-0.0106 0.3883 2.2599 0.0113 0.0396 -0.0060
-0.0025 0.0041 0.0113 0.0925 0.0471 -0.0440
-0.0005 -0.0103 0.0396 0.0471 0.2964 -0.0062
-0.0163 -0.0116 -0.0060 -0.0440 -0.0062 0.1144];
case 'imni', % For registering with MNI templates...
mu = -[0.0667 0.0039 0.0008 0.0333 0.0071 0.1071]';
isig = 1e4 * [
0.0902 -0.0345 -0.0106 -0.0025 -0.0005 -0.0163
-0.0345 0.7901 0.3883 0.0041 -0.0103 -0.0116
-0.0106 0.3883 2.2599 0.0113 0.0396 -0.0060
-0.0025 0.0041 0.0113 0.0925 0.0471 -0.0440
-0.0005 -0.0103 0.0396 0.0471 0.2964 -0.0062
-0.0163 -0.0116 -0.0060 -0.0440 -0.0062 0.1144];
case 'rigid', % Constrained to be almost rigid...
mu = zeros(6,1);
isig = eye(6)*1e8;
case 'subj', % For inter-subject registration...
mu = zeros(6,1);
isig = 1e3 * [
0.8876 0.0784 0.0784 -0.1749 0.0784 -0.1749
0.0784 5.3894 0.2655 0.0784 0.2655 0.0784
0.0784 0.2655 5.3894 0.0784 0.2655 0.0784
-0.1749 0.0784 0.0784 0.8876 0.0784 -0.1749
0.0784 0.2655 0.2655 0.0784 5.3894 0.0784
-0.1749 0.0784 0.0784 -0.1749 0.0784 0.8876];
case 'eastern', % For East Asian brains to MNI...
mu = [0.0719 -0.0040 -0.0032 0.1416 0.0601 0.2578]';
isig = 1e4 * [
0.0757 0.0220 -0.0224 -0.0049 0.0304 -0.0327
0.0220 0.3125 -0.1555 0.0280 -0.0012 -0.0284
-0.0224 -0.1555 1.9727 0.0196 -0.0019 0.0122
-0.0049 0.0280 0.0196 0.0576 -0.0282 -0.0200
0.0304 -0.0012 -0.0019 -0.0282 0.2128 -0.0275
-0.0327 -0.0284 0.0122 -0.0200 -0.0275 0.0511];
case 'none', % No regularisation...
mu = zeros(6,1);
isig = zeros(6);
otherwise
error(['"' typ '" not recognised as type of regularisation.']);
end;
mu = [zeros(6,1) ; mu];
isig = [zeros(6,12) ; zeros(6,6) isig];
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
|
spm/spm5-master
|
spm_config_movefile.m
|
.m
|
spm5-master/spm_config_movefile.m
| 2,999 |
utf_8
|
5669e37f39c3defe8479460f98d0e80b
|
function opts = spm_config_movefile
% Configuration file for move file function
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Volkmar Glauche
% $Id: spm_config_movefile.m 549 2006-06-07 12:37:29Z volkmar $
%_______________________________________________________________________
srcfiles.type = 'files';
srcfiles.name = 'Files to move';
srcfiles.tag = 'srcfiles';
srcfiles.filter = '.*';
srcfiles.num = [0 Inf];
srcfiles.help = {'Select files to move.'};
targetdir.type = 'files';
targetdir.name = 'Target directory';
targetdir.tag = 'targetdir';
targetdir.filter = 'dir';
targetdir.num = 1;
targetdir.help = {'Select target directory.'};
opts.type = 'branch';
opts.name = 'Move Files';
opts.tag = 'movefile';
opts.val = {srcfiles,targetdir};
opts.prog = @my_movefile;
opts.vfiles = @vfiles_movefile;
opts.help = {[...
'This facilty allows to move files in a batch. Note that moving files ' ...
'will not make them disappear from file selection lists. Therefore one' ...
'has to be careful not to select the original files after they have ' ...
'been programmed to be moved.'],'',...
['If image files (.*img or .*nii) are selected, corresponding hdr or mat files will ' ...
'be moved as well, if they exist.']};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function my_movefile(varargin)
job = varargin{1};
for k = 1:numel(job.srcfiles)
[p n e v] = spm_fileparts(job.srcfiles{k});
if strncmp(e,'.img',4)||strncmp(e,'.nii',4)
try_movefile(fullfile(p,[n e]),job.targetdir{1});
try_movefile(fullfile(p,[n '.mat']),job.targetdir{1});
try_movefile(fullfile(p,[n '.hdr']),job.targetdir{1});
else
try_movefile(job.srcfiles{k},job.targetdir{1});
end;
end;
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function try_movefile(src,dest)
% silently try to move files
try
movefile(src,dest);
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles_movefile(varargin)
job = varargin{1};
vf={};
for k = 1:numel(job.srcfiles)
[p n e v] = spm_fileparts(job.srcfiles{k});
if strncmp(e,'.img',4)||strncmp(e,'.nii',4)
vi = strfind(e,',');
if ~isempty(vi)
e=e(1:vi-1);
end;
vf{end+1} = fullfile(job.targetdir{1},[n e v]);
if exist(fullfile(p,[n '.mat']),'file')
vf{end+1} = fullfile(job.targetdir{1},[n '.mat']);
end;
if exist(fullfile(p,[n '.hdr']))
vf{end+1}= fullfile(job.targetdir{1},[n '.hdr']);
end;
else
vf{end+1} = fullfile(job.targetdir{1},[n e v]);
end;
end;
return;
|
github
|
spm/spm5-master
|
spm_justify.m
|
.m
|
spm5-master/spm_justify.m
| 6,226 |
utf_8
|
49239b75dcd1c0bebd8523ee21724d50
|
function out = spm_justify(varargin)
% SPM_JUSTIFY Justifies a text string
% OUT = SPM_JUSTIFY(N,TXT) justifies text string TXT to
% the length specified by N.
%
% OUT = SPM_JUSTIFY(OBJ,TXT) justifies text string to
% the width of the OBJ in characters - 1.
%
% If TXT is a cell array, then each element is treated
% as a paragraph and justified, otherwise the string is
% treated as a paragraph and is justified.
% Non a-z or A-Z characters at the start of a paragraph
% are used to define any indentation required (such as
% for enumeration, bullets etc. If less than one line
% of text is returned, then no formatting is done.
%
% Example:
% out = spm_justify(40,{['Statistical Parametric ',...
% 'Mapping refers to the construction and ',...
% 'assessment of spatially extended ',...
% 'statistical process used to test hypotheses ',...
% 'about [neuro]imaging data from SPECT/PET & ',...
% 'fMRI. These ideas have been instantiated ',...
% 'in software that is called SPM']});
% strvcat(out{:})
%
%------------------------------------------------------------------------
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_justify.m 491 2006-03-31 17:36:45Z john $
out = {};
% DRG added code to estimate the actual size of the listbox and how many
% characters will fit per line.
if nargin < 2
error('Incorrect usage of spm_justify.')
end
n = varargin{1};
if ishandle(n)
% n is presumably the handle of some object that can deal with text.
% use try catch statements so that if try fails the
% UI is returned to its original state.
h = n;
oldStr = get(h,'String');
oldUnits = get(h,'Units');
try
set(h,'Units','Characters');
% Matlab is very inaccurate at estimating the width of single
% characters, so we'll use 100.
set(h,'string',repmat(' ',1,100));
ext = get(h,'extent');
% calculate width of 1 character.
ext = ext(3)/100;
pos = get(h,'position');
pos = pos(3);
% hack because Matlab cannot tell us how wide the scrollbar is.
pos = pos - 5;
wGuess = floor(pos/ext);
str = repmat(' ',1,wGuess);
set(h,'string',str);
ext = get(h,'extent');
ext = ext(3);
if ext > pos
while ext > pos
if numel(str) == 1
error('Too few characters for object handle provided.');
end
str = str(1:end-1);
set(h,'String',str);
ext = get(h,'extent');
ext = ext(3);
end
n = numel(str);
else
while ext < pos
str = [str(1), str];
if numel(str) > 200
error('Too many characters for object handle provided.');
end
set(h,'String',str);
ext = get(h,'extent');
ext = ext(3);
end
n = numel(str)-2;
end
set(h,'String',oldStr);
set(h,'Units',oldUnits);
catch
set(h,'String',oldStr);
set(h,'Units',oldUnits);
error('Problem estimating characters for object handle provided');
end
end
for i=2:nargin,
if iscell(varargin{i}),
for j=1:numel(varargin{i}),
para = justify_paragraph(n,varargin{i}{j});
out = {out{:},para{:}};
end;
else
para = justify_paragraph(n,varargin{i});
out = {out{:},para{:}};
end;
end;
function out = justify_paragraph(n,txt)
if numel(txt)>1 && txt(1)=='%',
txt = txt(2:end);
end;
%txt = regexprep(txt,'/\*([^(/\*)]*)\*/','');
st1 = findstr(txt,'/*');
en1 = findstr(txt,'*/');
st = [];
en = [];
for i=1:numel(st1),
en1 = en1(en1>st1(i));
if ~isempty(en1),
st = [st st1(i)];
en = [en en1(1)];
en1 = en1(2:end);
end;
end;
str = [];
pen = 1;
for i=1:numel(st),
str = [str txt(pen:st(i)-1)];
pen = en(i)+2;
end;
str = [str txt(pen:numel(txt))];
txt = str;
off = find((txt'>='a' & txt'<='z') | (txt'>='A' & txt'<='Z'));
off = off(off<n);
if isempty(off),
out{1} = txt;
else
off = off(1);
para = justify_para(n-off+1,txt(off:end));
if numel(para)>1,
out{1} = [txt(1:(off-1)) para{1}];
for j=2:numel(para),
out{j} = [repmat(' ',1,off-1) para{j}];
end;
else
out{1} = txt;
end;
end;
return;
function out = justify_para(n,varargin)
% Collect varargs into a single string
str = varargin{1};
for i=2:length(varargin),
str = [str ' ' varargin{i}];
end;
if isempty(str), out = {''}; return; end;
% Remove repeats
sp = find(str==' ');
rep = sp(diff(sp)==1);
str(rep) = [];
if str(1) ==' ', str(1) = ''; end;
if str(end)==' ', str(end) = ''; end;
out = {};
while length(str)>n,
% Break the string into lines
sp = find(str==' ');
brk = sp(sp<=n);
if isempty(brk),
if isempty(sp),
brk = length(str)+1;
else
brk = sp(1);
end;
else
brk = brk(end);
end;
% Pad the line to n characters wide
current = str(1:(brk-1));
% l = length(current);
% l = n-l;
sp = find(current==' ');
if ~isempty(sp),
% Break into words
sp = [sp length(current)+1];
words = {current(1:(sp(1)-1))};
for i=1:(length(sp)-1),
words = {words{:}, current((sp(i)+1):(sp(i+1)-1))};
end;
% Figure out how much padding on average
nsp = length(sp)-1;
pad = (n-(length(current)-nsp))/nsp;
% Pad all spaces by the same integer amount
sp = repmat(floor(pad),1,nsp);
% Pad a random selection of spaces by one
pad = round((pad-floor(pad))*nsp);
[unused,ind] = sort(rand(pad,1));
ind = ind(1:pad);
sp(ind) = sp(ind)+1;
% Re-construct line from individual words
current = words{1};
for i=2:length(words),
current = [current repmat(' ',1,sp(i-1)) words{i}];
end;
end;
out = {out{:},current};
str = str((brk+1):end);
end;
out = {out{:},str};
|
github
|
spm/spm5-master
|
spm_diff.m
|
.m
|
spm5-master/spm_diff.m
| 4,445 |
utf_8
|
4511e813264b278c428bfab7ce2324fa
|
function [varargout] = spm_diff(varargin)
% matrix high-order numerical differentiiation
% FORMAT [dfdx] = spm_diff(f,x,...,n,[V])
%
% f - [inline] function f(x{1},...)
% x - input argument[s]
% n - arguments to differentiate w.r.t.
%
% dfdx - df/dx{i} ; n = i
% dfdx{p}...{q} - df/dx{i}dx{j}(q)...dx{k}(p) ; n = [i j ... k]
%
% V - cell array of matices that allow for differentiation w.r.t.
% to a linear trasnformation of the parameters: i.e., returns
%
% df/dy{i}; x = V{i}y{i}; V = dx(i)/dy(i)
%
% - a cunning recursive routine
%__________________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Karl Friston
% $Id: spm_diff.m 1070 2008-01-07 19:03:15Z guillaume $
% 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};
elseif isnumeric(varargin{end})
x = varargin(2:(end - 1));
n = varargin{end};
V = cell(1,length(x));
else
error('improper call')
end
% check transform matrices V = dx.dy
%--------------------------------------------------------------------------
for i = 1:length(x)
try
V{i};
catch
V{i} = [];
end
if ~length(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 ~length(xm)
J = sparse(length(f),0);
% or there are no arguments to differentiate
%----------------------------------------------------------------------
elseif ~length(f)
J = sparse(0,length(xm));
end
% or differentiation of a vector w.r.t. a vector
%----------------------------------------------------------------------
if isvec(f0) && isvec(x{m})
% concatenate into a matrix
%------------------------------------------------------------------
if size(f0,2) == 1
J = spm_cat(J);
else
J = spm_cat(J')';
end
end
% assign ouput 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
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 && (size(v,1) == 1 || size(v,2) == 1);
|
github
|
spm/spm5-master
|
spm_config_eeg_filter.m
|
.m
|
spm5-master/spm_config_eeg_filter.m
| 1,124 |
utf_8
|
f4f6f38824ad861a9e282c83b29f1a82
|
function S = spm_config_eeg_filter
% configuration file for EEG Filtering
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
%
% $Id: spm_config_eeg_filter.m 112 2005-05-04 18:20:52Z john $
D = struct('type','files','name','File Name','tag','D',...
'filter','mat','num',1,...
'help',{{'Select the EEG mat file.'}});
typ = struct('type','menu','name','Filter type','tag','type',...
'labels',{{'Butterworth'}},'values',{{1}},'val',{{1}},...
'help', {{'Select the filter type.'}});
PHz = struct('type','entry','name','Cutoff','tag','cutoff',...
'strtype','r','num',[1 1],...
'help', {{'Enter the filter cutoff'}});
flt = struct('type','branch','name','Filter','tag','filter','val',{{typ,PHz}});
S = struct('type','branch','name','EEG Filter','tag','eeg_filter',...
'val',{{D,flt}},'prog',@eeg_filter,'modality',{{'EEG'}},...
'help',{{'Low-pass filters EEG/MEG epoched data.'}});
function eeg_filter(S)
S.D = strvcat(S.D{:});
spm_eeg_filter(S)
|
github
|
spm/spm5-master
|
os_meg.m
|
.m
|
spm5-master/os_meg.m
| 29,178 |
utf_8
|
a416129ad14306a2e88665ae304c934e
|
function G = os_meg(L,Channel,Param,Order,imegsens,irefsens,Verbose);
%OS_MEG - Calculate the (overlapping) sphere models for MEG
% function G = os_meg(L,Channel,Param,Order,imegsens,irefsens,Verbose);
% function G = os_meg(L,Channel,Param,Order,imegsens,irefsens);
% function G = os_meg(L,Channel,Param,Order);
% Modified for CME, not MME, as Order = 1.
% Calculate the magnetic field, spherical head, arbitrary orientation
%
% INPUTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% L : a 3 x nL array, each column a source location (x y z coordinates); nL sources
% Channel is a BrainStorm channel structure
% Param an array of structures:
% For every channel i:
% Param(i).Center = a vector of the x, y, z locations for the sphere model
% (assume the same center for every sphere for the classical spherical head model);
%
% Param(i).Radii = a vector containing the radius in meters of the concentric spheres ;
% Can be a scalar for the single-sphere head model
%
% Param(i).EEGType = [] % Leave it empty for MEG;
%
% Order: Defines the source order for which to compute the forward problem:
% -1 current dipole
% 0 focal(magnetic) dipole
% 1 1st order current multipole
%
% imegsens is the index to the MEG sensors in the Channel information
% irefsens is the index to the MEG reference sensors in the Channel
% if imegsens (irefsens) is not given, then routine (expensively)
% searches the Channel structure for 'MEG' ('MEG REF') values
%
% Verbose : toggle verbose mode (1 is default)
%
% OUTPUTS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% G is the gain matrix: each column is the forward field of each source
%<autobegin> ---------------------- 27-Jun-2005 10:45:21 -----------------------
% ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 -------
%
% CATEGORY: Forward Modeling
%
% Alphabetical list of external functions (non-Matlab):
% toolbox\blk_diag.m
% toolbox\blk_lex.m
% toolbox\bst_message_window.m
% toolbox\colnorm.m
% toolbox\cross_mat.m
% toolbox\good_channel.m
% toolbox\inorcol.m
% toolbox\makeuswait.m
% toolbox\mby3check.m
% toolbox\norcol.m
% toolbox\vec.m
%
% Subfunctions in this file, in order of occurrence in file:
% c = cross(a,b);
% k = kronmat(a,b);
% G = sarvas(L,P,Order);
% G = sarvas_dipole(L,P,Order);
% D = sarvas_partial(L,P);
%
% At Check-in: $Author: Mosher $ $Revision: 35 $ $Date: 6/27/05 9:00a $
%
% This software is part of BrainStorm Toolbox Version 27-June-2005
%
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
% University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
% Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
% CNRS, Hopital de la Salpetriere, Paris, France
%
% See BrainStorm website at http://neuroimage.usc.edu for further information.
%
% Copyright (c) 2005 BrainStorm by the University of Southern California
% This software distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 27-Jun-2005 10:45:21 -----------------------
% NOT OPTIMIZED FOR BRAINSTORM STRUCTURE.
% But it's a whole lot better now (October 99 version).
% John C. Mosher, Ph.D.
% ------------------------ HISTORY -------------------------------------------
% 29-Oct-1999 JCM tried to speed up cross products, which are a substantial portion of
% the total calculation time, for a lot of dipoles.
% Also added the waitbar feature for big calculations.
%
% 28-Nov-2000 SB Modified for updated 3rd-order gradient correction of CTF data
% 24-Jan-2002 JCM in Paris, modified code to run old partial gradient calculation
% in this code
% 20-Feb-2002 JCM fixed missing translocation of the partial gradient location
% information. Put center shifting into the partial_gradient
% code itself. Major change to gradient interface to handle
% head center in different location.
% 20-Feb-2002 SB Fixed different version to handle case of m x 3 L matrix,
% force L to be 3 x N or return error.
% 12-Mar-2002 JCM Force L to be 3 x N or return error.
% 19-Jun-2002 JCM Realized version differences between toolbox and developers
% toolbox, carefully merged two version together into toolbox,
% updated comments, history, switched waitbar to message window
% 02-Jul-2002 SB Fixed display using the 'overwrite' option of bst_message_window
% ........... Added progression messages during computation of large CME gain matrices
% 03-Sep-2002 SB Fixed bug when Channel contains magnetometers and when head center is at origin ([0 0 0])
% 20-Nov-2002 SB Updated computation with CTF 3rd order gradient correction
% Now must pass the entire Channel structure to OS_MEG
% MEG and MEG REF channels are extracted using GOOD_CHANNEL
% Lightly altered display
% 21-Oct-2003 JCM added optional imegsens and irefsens indexed inputs
% 09-Mar-2004 SB added Verbose argument
% -----------------------------------------------------------------------------
% Which verbose mode ?
if 0 % deprecated code - get a warning in Matlab 6.5.0 because 'Verbose' is an argument and has to be declared as GLOBAL before first use
global Verbose % Pass Verbose to subfunctions
end
if nargin == 5
Verbose = imegsens;
clear imegsens
elseif nargin < 7 ^ ~exist('Verbose','var')
Verbose = 1;% Default
end
% Indices of MEG and MEG REF channels in Channel structure array:
if ~exist('imegsens','var') | isempty(imegsens),
imegsens = good_channel(Channel,[],'MEG');
end
if isempty(imegsens)
error('No MEG channels available')
end
if ~exist('irefsens','var'),
irefsens = good_channel(Channel,[],'MEG REF');
end
if ~isempty(irefsens)
ChannelRef = Channel(irefsens); % Fill out a specific channel structure with MEG REF channels only
[ChannelRef(:).Type] = deal('MEG'); % Ref channels will be treated as regular MEG sensors when Sarvas is called to compute their forward fields
refFlag = 1;
else
refFlag = 0;
end
Channel = Channel(imegsens); % Keep Channel as a MEG-channel only channel set.
Param = Param(imegsens);
% ----------------------------
NumCoils = size(Channel(1).Loc,2); % number of coils, assumed same for all channels
NumSensors = length(Channel); % how many channels
if(size([Channel.Loc],2) ~= NumSensors*NumCoils),
errordlg({'Sorry, OS_MEG not equipped to handle different number of coils'});
G = [];
return
end
% load up the old parameter array
% P.sensor is 3 x nR,each column a sensor location
% P.orient is 3 x nR, the sensor orientation
% P.center is 3 x nR, the sphere center for each sensor
[P(1:NumCoils)] = deal(struct('sensor',zeros(3,NumSensors),...
'orient',zeros(3,NumSensors),...
'center',zeros(3,NumSensors),'weight',[]));
AllLocs = [Channel.Loc]; % remap all Locations
AllLocs = reshape(AllLocs,NumCoils*3,size(AllLocs,2)/NumCoils);
AllOrient = [Channel.Orient];
AllOrient = AllOrient*inorcol(AllOrient);
AllOrient= reshape(AllOrient,NumCoils*3,size(AllOrient,2)/NumCoils);
AllWeight = [Channel.Weight];
AllWeight = reshape(AllWeight(:),NumCoils,length(AllWeight(:))/NumCoils);
% -- modified from original version: JM 30/10/05 --
AllCenter = [Param.Center];
%AllCenter = reshape(AllCenter,NumCoils*3,size(AllLocs,2)/NumCoils);
% Bug fix by Rik Henson 6/6/07
AllCenter = reshape(AllCenter,NumCoils*3,size(AllCenter,2)/NumCoils);
for j = 1:NumCoils,
P(j).sensor = AllLocs([-2:0]+j*3,:);
P(j).orient = AllOrient([-2:0]+j*3,:);
P(j).weight = AllWeight(j,:);
% -- modified from original version: JM 30/10/05 --
P(j).center = AllCenter([-2:0]+j*3,:);
% P(j).center = [Param.Center]; %one center for both coils
end
[m,n] = size(L);
if(m~=3), % should be 3 x m
% Old Mosher convention was to give L as m x 3
% Newer Mathworks convention is for sets of vectors to
% be 3 x m (except paradoxically the "patch" command).
% Error to user, force correction in calling code.
if Verbose
bst_message_window('wrap',{'LOCATION GIVEN AS M X 3.',...
'Please adjust calling code to handle new convention'});
end
error('Matrix not given as 3 x n. Correct calling code');
end
G = 0;
for i = 1:length(P),
G = G + sarvas(L,P(i),Order); % local call below
end
% is there special reference channel considerations?
% See Channel.mat structure description in the ParameterDescriptions document.
if (refFlag) % Gradient correction is available as well
% read the CTF reference channel information
meanCenter = mean([Param.Center],2); % mean head center of all of the channels
% create a temporary parameters file with the same center for all reference channels.
[RefParam(1:length(irefsens))] = ...
deal(struct('Center',meanCenter));
% recursively call
% Forward model on all reference sensors
% JCM 19-Jun-2002 switched to feval of mfilename
Gr = feval(mfilename,L,ChannelRef,RefParam,Order,[1:length(irefsens)],[]); % refs now called as MEG
% Apply nth-order gradient correction on good channels only
global ChannelFlag
if isempty(ChannelFlag)
ChannelFlag = ones(size(G,1),1); % Take all channels
end
%Weight by the current nth-order correction coefficients
try
G = G - Channel(1).Comment * Gr;
catch
errordlg(lasterr,...
'Inconsistency detected in MEG data structure')
makeuswait('stop')
return
end
end
clear global Verbose
% ------------- SUBFUNCTIONS, First the simple utilities, then more complicated -----
% -----------------------------------------------------------------------------------
function c = cross(a,b);
% fast and simple, and row major should be faster
% 10/29/99 conversion to row major was slightly faster
% in the calculation, but overall slower in the transposes needed.
% retained the column major multiplies below
c = zeros(size(a));
c(1,:) = a(2,:).*b(3,:) - a(3,:).*b(2,:);
c(2,:) = a(3,:).*b(1,:) - a(1,:).*b(3,:);
c(3,:) = a(1,:).*b(2,:) - a(2,:).*b(1,:);
% ----------------------------------------------------------------------------
function k = kronmat(a,b);
% column by column, not element by matrix
k = [a([1 1 1],:) .* b; ...
a([2 2 2],:) .* b; ...
a([3 3 3],:) .* b];
% ----------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Local Sarvas functions %%%%%%%%%%%%%%%%%%%%%%%%
% First, the standard interface to above
% If the Order is -1 or 0, then same as before. Order 1 is handled separately
function G = sarvas(L,P,Order);
global Verbose
% Bronzan Sarvas forward model, spherical head
% Order = -1 is current dipole
% Order = 0 is magnetic dipole of BST 2000
% Order = 1 is the new 1st order current multipole
% L is 3 x nL
%
% P.sensor is 3 x nR,each column a sensor location
% P.orient is 3 x nR, the sensor orientation
% P.center is 3 x nR, the sphere center for each sensor
% January 18, 2002 from sarvas_partial function of 1995
% Used old parameter convention to continue to handle Sylvain's exceptions
% for the CTF weighting coils
% if P.center in nonexistant or null, then assumed to be
% all zeros.
%%%%%%%%%%%%%%%%%%%% which multipolar model to run %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch Order
case {-1,0} %%%%%%%%%% CURRENT or MAGNETIC DIPOLE %%%%%%%%%%%%%%%%%%%
G = sarvas_dipole(L,P,Order); % BST 2000 function still used here
case {1} %%%%%%%%%%%%%%%%%%%%%%%%% CURRENT MULTIPOLE MODEL %%%%%%%%%%%%%%%%%%555
% new CME multipole, not MME multipole
% each set of three columns corresponds to a dipole
% first call the dipolar term
% SB 02-Jul-2002
if(size(L,2) > 5*size(P.sensor,2)) & size(P.sensor,2) > 1 & Verbose, %arbitrary definition of a lot
MESSAGE = 1; % let's show messages
else
MESSAGE = 0; % let's keep quiet
end
if MESSAGE
bst_message_window('wrap','Initiating the computation of CME modeling . . .')
end
Gdip = sarvas_dipole(L,P,-1);
% now call the quadrupole component
if MESSAGE
bst_message_window('Refining model . . .') % Not very explicit but gives hint about the progression here - John any better message ?
end
Gquad = sarvas_partial(L,P); % form the gradient in a local function
% weights are not applied in this routine, applied separately in the
% below forloop
% For example:
% Gquad(4:6,2) is the gradient of the second coil wrt to the second dipole
% So we must Vec for each coil to get it into the proper format
nR = size(P.sensor,2); % number of sensors
nL = size(L,2); % number of source points
G = zeros(nR,12*nL); % the full gain matrix
for i = 1:nL, % for each dipole
ndx = [-11:0]+i*12; % indexer for this source
G(:,ndx(1:3)) = Gdip(:,[-2:0]+i*3); % map next dipole to the first columns
temp = Gquad(:,[-2:0]+i*3); % next block of partial gradients
for j = 1:nR, % for each sensor position, also apply appropriate weight
G(j,ndx(4:12)) = vec(temp([-2:0]+j*3,:))' * P.weight(j);
end
end
end
G = G*1e-7; % mu_o over 4 pi
%--------------------------------------------------------------------------
function G = sarvas_dipole(L,P,Order);
global Verbose
% SARVAS MEG Forward Model, spherical head
% if P.center in nonexistant or null, then assumed to be
% all zeros.
if(~isfield(P,'center')), % user did not provide
P.center = []; % initialize to null
end
if(isempty(P.center)), % user gave as null
P.center = zeros(size(P.sensor)); % set to coordinate origin
end
P.sensor = P.sensor - P.center; % shift sensor coordinates
% SB 03-Sep-2002
% Now there is the issue of having a sensor array being a mixture of magnetometers and gradiometers.
% Magnetometers are referred as pseudo-gradiometers: the corresponding .Loc field of the Channel array of structures
% is still 3x2. For magnetometers though, the 2nd colum is filled with zeros (i.e.: [0 0 0]').
% Same story holds for the .Orient field.
% The full gain matrices are computed for these channels located at [0 0 0] but when the orientation vector is applied
% the net field is set to 0. Therefore, the second call to sarvas_dipole produces a null field which is substracted frim the field
% from the magnetometer (i.e the fisrt coil of the pseudo-gradiometer).
% Calculations fail (divide by zero) when head center is also at [0 0 0].
% I'm therefore testing this out here and fix things by virtually translating the virtual coils located at [0 0 0]
% to [1 1 1] (arbitrary). The net field will still be null when the orientation is applied anyway.
% Any more elegant fix is welcome at this point.
iMag = find(norcol(P.sensor)==0); % Indices of channels located at P.center.
if ~isempty(iMag)
P.sensor(:,iMag) = repmat([1 1 1]',1,length(iMag)); % Move them away (arbitrary location).
end
nR = size(P.sensor,2); % number of sensors
nL = size(L,2); % number of source points
Rn2 = sum(P.sensor.^2,1); % distance to sensor squared
Rn = sqrt(Rn2); % distance
if (nR >= nL), % more sensors than dipoles
if(Order == 1),
G = zeros(nR,12*nL); % gain matrix
else
G = zeros(nR,3*nL); % gain matrix
end
for Li = 1:nL,
Lmat = L(:,Li+zeros(1,nR)); % matrix of location repeated
Lmat = Lmat - P.center; % each center shifted relative to its center
D = P.sensor - Lmat; % distance from souce to sensors
Dn2 = sum(D.^2,1); % distance squared
Dn = sqrt(Dn2); % distance
R_dot_D = sum(P.sensor .* D); % dot product of sensor and distance
R_dot_Dhat = R_dot_D ./ Dn; % dot product of sensor and distance
F = Dn2 .* Rn + Dn .* R_dot_D; % Sarvas' function F
GF_dot_o = Dn2 .* sum(P.sensor.*P.orient) ./ Rn + ...
(2 * Rn + R_dot_Dhat) .* sum(D.*P.orient) + ...
Dn .* sum((D+P.sensor).*P.orient);
tempF = GF_dot_o ./ F.^2;
if(Order == -1), % current dipole model
temp = cross(Lmat,P.orient) ./ F([1 1 1],:) - ...
cross(Lmat,P.sensor) .* tempF([1 1 1],:);
G(:,Li*3+[-2 -1 0]) = temp';
elseif(Order == 0) % magnetic dipole model
temp = P.sensor .* tempF([1 1 1],:) - P.orient ./ F([1 1 1],:);
G(:,Li*3+[-2 -1 0]) = temp';
elseif(Order == 1), % 1st order multipole
% first the dipole
temp_m = P.sensor .* tempF([1 1 1],:) - P.orient ./ F([1 1 1],:);
% then the quadrupole
temp1 = -(2*Rn + R_dot_Dhat + Dn);
temp2 = -sum(D.*P.orient) ./ Dn;
temp3 = -(2*sum(P.sensor.*P.orient)./Rn + sum((D+P.sensor).*P.orient)./Dn - ...
sum(D.*P.orient).*R_dot_D./(Dn2.*Dn));
GGpF_dot_o = temp1([1 1 1],:) .* P.orient + ...
temp2([1 1 1],:).*P.sensor + temp3([1 1 1],:) .* D;
temp1 = -(2*Rn + R_dot_Dhat);
GpF = temp1([1 1 1],:) .* D - Dn([1 1 1],:) .* P.sensor;
temp1 = 1 ./ F.^2;
temp2 = 2*GF_dot_o./F;
temp_q = temp1(ones(1,9),:) .* (kronmat(GGpF_dot_o,P.sensor) + ...
kronmat(GpF,P.orient - temp2([1 1 1],:).*P.sensor));
G(:,Li*12+[-11:0]) = [temp_m;temp_q]';
end
end
else % more dipoles than sensors nL > nR
if(Order == 1)
G = zeros(12*nL,nR); % 1st order multipole gain matrix transposed
else
G = zeros(3*nL,nR); % gain matrix transposed
end
% if there are a lot of dipoles, let's watch on the screen
% JCM 18-Jun-2002 no more waitbar, use message window
if (nL > 5*nR) & nR > 1 & Verbose, %arbitrary definition of a lot
MESSAGE = 1; % let's show messages
% bst_message_window('wrap',sprintf(...
% 'Making order %.0f matrix of %.0f sensors x %.0f sources',Order,nR,nL));
% bst_message_window('append','Making first sensor . . .'); % prepare for overwrite
bst_message_window('overwrite',sprintf(...
'Making Current Dipole matrix of %.0f sensors x %.0f sources',nR,nL));
bst_message_window('append','Making first sensor . . .'); % prepare for overwrite else
else % SB 03-Sep-2002 : else was probably missing
MESSAGE = Verbose; % let's be quiet
end
for Ri = 1:nR,
if(MESSAGE), % want to show the user progress?
if(~rem(Ri,30)), % every tenth sensor
bst_message_window('overwrite',sprintf('Progress report:....... %.0f of %.0f . . .',Ri,nR));
end
end
Rmat = P.sensor(:,Ri+zeros(1,nL)); % matrix of sensor repeated
Omat = P.orient(:,Ri+zeros(1,nL)); % orientations
Lmat = L - P.center(:,Ri+zeros(1,nL)); % shift centers to this coordinate
D = Rmat - Lmat;
Dn2 = sum(D.^2,1); % distance squared
Dn = sqrt(Dn2); % distance
R_dot_D = sum(Rmat .* D); % dot product of sensor and distance
R_dot_Dhat = R_dot_D ./ Dn; % dot product of sensor and distance
F = Dn2 * Rn(Ri) + Dn .* R_dot_D; % Sarvas' function F
GF_dot_o = Dn2 * sum(P.sensor(:,Ri).*P.orient(:,Ri)) / Rn(Ri) + ...
(2 * Rn(Ri) + R_dot_D ./ Dn) .* sum(D.*Omat) + ...
Dn .* sum((D+Rmat).*Omat);
tempF = GF_dot_o ./ F.^2;
if(Order == -1), % current dipole model
temp = cross(Lmat,Omat) ./ F([1 1 1],:) - ...
cross(Lmat,Rmat) .* tempF([1 1 1],:);
elseif(Order == 0) % magnetic dipole model
temp = Rmat .* tempF([1 1 1],:) - Omat ./ F([1 1 1],:);
elseif(Order == 1), % 1st order multipole
% first the dipole
temp_m = Rmat .* tempF([1 1 1],:) - Omat ./ F([1 1 1],:);
% then the quadrupole
temp1 = -(2*Rn(Ri) + R_dot_Dhat + Dn);
temp2 = -sum(D.*Omat) ./ Dn;
temp3 = -(2*sum(P.sensor(:,Ri).*P.orient(:,Ri))./Rn(Ri) + sum((D+Rmat).*Omat)./Dn - ...
sum(D.*Omat).*R_dot_D./(Dn2.*Dn));
GGpF_dot_o = temp1([1 1 1],:) .* Omat + ...
temp2([1 1 1],:).*Rmat + temp3([1 1 1],:) .* D;
temp1 = -(2*Rn(Ri) + R_dot_Dhat);
GpF = temp1([1 1 1],:) .* D - Dn([1 1 1],:) .* Rmat;
temp1 = 1 ./ F.^2;
temp2 = 2*GF_dot_o./F;
temp_q = temp1(ones(1,9),:) .* (kronmat(GGpF_dot_o,Rmat) + ...
kronmat(GpF,Omat - temp2([1 1 1],:).*Rmat));
temp = [temp_m;temp_q];
else % unimplemented order
disp('SARVAS: Unimplemented source order');
G = [];
return
end
G(:,Ri) = temp(:);
end
G = G';
end
if(isfield(P,'weight')),
Weights = P.weight(:); %make sure column
% scale each row by its appropriate weight
G = Weights(:,ones(1,size(G,2))) .* G;
end
% ----------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%% Partial calculation for the sarvas %%%%%%%%%%%%%%%%%%%
function D = sarvas_partial(L,P);
%SARVAS_PARTIAL Calculate the partial of the Sarvas Formula w.r.t L
% function D = sarvas_partial(L,P);
% For dipole locations in L and sensor information in R, calculate the
% partial of the Sarvas formula (dipole in a sphere, arbitrary sensor
% orientation) with respect to the dipole location. The result is a matrix
% D of partials information.
% If there are M sensors and P dipoles, then D
% is 3*M by 3*P. Let the corresponding moments Q be 3 by M.
% Then partial = D * blk_diag(Q,1) is 3*M by P. Each column of partial
% corresponds to a different dipole in L. Each set of three rows
% corresponds to a different sensor location. Thus partial(4:6,2) is the
% partial of the Sarvas formula at the second sensor location, with respect
% to the second dipole.
%
% Used to calculate the Cramer-Rao Lower Bounds
% structure P has fields .weight, length of the number of sensors, which
% is applied to each row of the gain matrix. Weight is usually 1 or -1
% Field .center is 3 x number of sensors, head center for each coil.
% P.sensor and P.orient are the location and orientation information, resp.
% P.weight is not applied, must be applied separately, see above calling code.
% Author: John C. Mosher, Ph.D.
% Los Alamos National Laboratory
% Los Alamos, NM 87545
% email: [email protected]
% August 15, 1995 author
% 20 Feb 2002 JCM extensive I/O changes to adapt into os_meg, handle arbitrary
% head center
L = mby3check(L,0); % matrices are now 3 x <>, but don't warn if 3 x 3
numSens = size(P.sensor,2); % number of sensors
numDip = size(L,2); % number of source points
% use some older notation for programming reuse below
R = [P.sensor]; % sensor locations
Rs = [P.orient]; % sensor orientations
if(~isfield(P,'center')), % user did not provide
P.center = []; % initialize to null
end
if(isempty(P.center)), % user gave as null
P.center = zeros(size(R)); % set to coordinate origin
end
% each channel coil is shifted to its relative location
R = R - P.center; % shift sensor coordinates
% SB 03-Sep-2002
% Now there is the issue of having a sensor array being a mixture of magnetometers and gradiometers.
% Magnetometers are referred as pseudo-gradiometers: the corresponding .Loc field of the Channel array of structures
% is still 3x2. For magnetometers though, the 2nd colum is filled with zeros (i.e.: [0 0 0]').
% Same story holds for the .Orient field.
% The full gain matrices are computed for these channels located at [0 0 0] but when the orientation vector is applied
% the net field is set to 0. Therefore, the second call to sarvas_dipole produces a null field which is substracted frim the field
% from the magnetometer (i.e the fisrt coil of the pseudo-gradiometer).
% Calculations fail (divide by zero) when head center is also at [0 0 0].
% I'm therefore testing this out here and fix things by virtually translating the virtual coils located at [0 0 0]
% to [1 1 1] (arbitrary). The net field will still be null when the orientation is applied anyway.
% Any more elegant fix is welcome at this point.
iMag = find(norcol(R)==0); % Indices of channels located at P.center.
if ~isempty(iMag)
R(:,iMag) = repmat([1 1 1]',1,length(iMag)); % Move them away (arbitrary location).
end
Rn = colnorm(R); % distance to sensor
iRn = 1../Rn; % inverse distance
o3 = ones(3,1); % col vector of three ones
% three by three matrices per sensor and dipole
D = zeros(numSens*3,3*numDip);
if(size(L,2) > 5*size(R,2)) & size(R,2) > 1 & Verbose, %arbitrary definition of a lot
MESSAGE = Verbose; % let's show messages
bst_message_window({...
'Computing quadrupolar moments',...
sprintf('for sources %.0f of %.0f . . .',100,numDip)...
});
else
MESSAGE = Verbose; % let's be quiet
end
for Dip = 1:numDip % foreach dipole,
%################ main loop ########################
% if there are a lot of dipoles, let's watch on the screen
% SB 02-Jul-2002 no more waitbar, use message window
if(MESSAGE), % want to show the user progress?
if(~rem(Dip,100)), % every tenth source
bst_message_window('overwrite',sprintf('for sources %.0f of %.0f . . .',Dip,numDip));
end
end
ThisDipole = L(:,Dip); % next dipole
Lmat = repmat(ThisDipole,1,numSens); % repeat this dipole for all sensors
Lmat = Lmat - P.center; % shift each location relative to the sensor's center
% let "a" be the same as Sarvas' "a", a = sensor - dipole.
a = R - Lmat;
an = colnorm(a); % norm of each a
ian=1../an; % inverse of norm a
ian3 = ian.^3; % inverse cubed of norm a
aDotR = sum(a.*R,1);
% Form F
F = (an .* Rn + aDotR) .* an;
iF = 1../F;
% From gradient F
tmp1 = an.^2 .* iRn + aDotR .* ian + 2*an + 2*Rn;
tmp1 = tmp1(o3,:).* R;
tmp2 = an + 2*Rn + aDotR .* ian;
tmp2 = tmp2(o3,:) .* Lmat;
gradF = tmp1 - tmp2;
% take partials of (Rs dot grad(F)) wrt r_q. Result is 3 by 1 per sensor
tmp1 = aDotR.*ian3 - 2*(iRn+ian);
tmp1 = (tmp1(o3,:) .* a) - (R .* ian(o3,:));
tmp1 = tmp1 .* (o3*sum(Rs.*R,1));
tmp2 = an + 2*Rn + ian.*aDotR;
tmp2 = tmp2(o3,:) .* Rs;
tmp3 = aDotR.*ian3 - ian;
tmp3 = tmp3(o3,:).*a - (R .* ian(o3,:));
tmp3 = tmp3 .* (o3*sum(Rs.*Lmat,1));
partRsGradF = tmp1 - tmp2 - tmp3;
% take partial of F wrt r_q
tmp1 = aDotR .* ian;
tmp1 = tmp1(o3,:).*a;
partF = -2*Rn(o3,:).*a - an(o3,:).*R - tmp1;
% now take partial of ((gradF dot s) / F^2).
tmp1 = F(o3,:) .* partRsGradF;
tmp2 = 2*sum(gradF.*Rs,1);
tmp2 = tmp2(o3,:) .* partF;
partGradFdotRsOverF2 = (tmp1 - tmp2) .* iF(o3,:).^3;
% now take partial of inverse of F
partInvF = -partF .* iF(o3,:).^2;
% Now we are ready to generate the partial of the Sarvas' formula wrt dipole
% location. The result is a 3 by 1 per sensor location; however, we want
% to separate out the dipole moment q. So our "partials matrix" D is 3 x 3
% per sensor location. We will concatenate into a 3*M by 3 matrix for each
% dipole.
% Rs cross q divide by F
% Want the cross product matrix tensor
tmp1 = blk_diag(cross_mat(Rs),3); % each set of three columns is a tensor
tmp1 = tmp1 .* kron(iF,ones(3)); % divide each tensor by F
tmp1 = blk_lex(tmp1,3); % now each set of three rows is a tensor
% L cross Rs dot q time partInvF
% Want the direct (outer) product of partInvF and (L cross Rs)
tmp2 = cross(Lmat,Rs); % cross products
% each set of three columns is the outer product
tmp2 = partInvF * blk_diag(tmp2,1)';
tmp2 = blk_lex(tmp2,3); % now each set of three rows is a tensor
% (R cross q)*(gradF dot Rs)/F^2
% Want scalar times the cross product tensor
tmp3 = sum(gradF .* Rs,1) .* iF.^2;
tmp3 = kron(tmp3,ones(3)); % repeat scalar for each submatrix
tmp3 = tmp3 .* blk_diag(cross_mat(R),3);
tmp3 = blk_lex(tmp3,3); % vertically stacked now
% ((L cross R) dot q) * partial(gradF dot Rs over F^2)
% Want direct (outer) product of partGradFdotRsOverF2 and (L cross R)
tmp4 = cross(Lmat,R);
tmp4 = partGradFdotRsOverF2 * blk_diag(tmp4,1)';
tmp4 = blk_lex(tmp4,3);
% Now combine into the appropriate columns of D.
D(:,(Dip-1)*3 + [1:3]) = tmp1 + tmp2 - tmp3 - tmp4;
%################ end main loop ########################
end % next dipole
|
github
|
spm/spm5-master
|
spm_eeg_inv_Lana.m
|
.m
|
spm5-master/spm_eeg_inv_Lana.m
| 4,801 |
utf_8
|
6c3018b4e87db5b117f417660e7b28bb
|
function [Lan,nit]=spm_eeg_inv_Lana(XYZmm,SseXYZ,Rsc,Rsk,Rbr,sigma)
% FUNCTION Lan,nit]=spm_eeg_inv_Lana(XYZmm,SseXYZ,Rsc,Rsk,Rbr)
% Calculates the leadfield in a 3-shell sphere head model for a set of
% distributed dipoles. As this is a spherical model, the solution is analytical
% but it relies on a truncated infinite series.
% IN :
% - XYZmm : dipoles location, moved to fit the spherical model.
% - SseXYZ : coordinates of the electrodes on the "scalp sphere".
% - Rsc,Rsk,Rbr : radii of the scalp, skull, brain spheres.
% - sigma : conductivities for the scalp, skull and brain volumes.
% OUT :
% - Lan : (orientation free) leadfield obtained with the analytical formula
% - nit : number of terms used in the infinite series
%
% Based on formulas found in :
% James P. Ary, Stanley A. Klein, Derek H. Fender
% Location of fources of evoked scalp potentials: Corrections for skull
% and scalp thicknesses
% IEEE TBME, 28-6, 447452, 1981
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Christophe Phillips,
% $Id: spm_eeg_inv_Lana.m 1039 2007-12-21 20:20:38Z karl $
if nargin<6
sigma = [.33 .004 .33];
end
e=sigma(2)/sigma(1) ;
f1=Rbr/Rsc ;
f2=Rsk/Rsc ;
Ndip = size(XYZmm,2) ;
Lan=zeros(size(SseXYZ,2),3*Ndip) ;
nit =zeros(1,Ndip) ;
% aff=1000 ;
% fprintf('\n')
for ii=1:Ndip
% disp(['ii = ',num2str(ii)])
% if rem(ii,aff)==0
% fprintf(' %3.1f%% calculated. \n',ii/Ndip*100)
% end
xyz_d = XYZmm(:,ii) ;
% This is not the same spherical coordinates as produced by cart2sph !!!
% azimuth is expressed as:
% - in here: phi = angle betwee e_x and proj of point on 'oxy' plane
% - in cart2sph: *th* = idem
% elevation is expressed as:
% - in here: thet = angle between e_z and point
% - in cartsph : *phi* = angle between point and 'oxy' plane
% i.e. *phi* = pi/2 - thet
no = norm(xyz_d) ;
b=no/Rsc ; % eccentricity
if no==0
thet=0 ;
else
thet=acos(xyz_d(3)/no) ;
end
phi = atan2(xyz_d(2),xyz_d(1)) ;
% Rotation matrix in order to bring the point (i.e. dipole) on e_z
rotyz = [cos(phi)*cos(thet) sin(phi)*cos(thet) -sin(thet) ;...
-sin(phi) cos(phi) 0 ;...
cos(phi)*sin(thet) sin(phi)*sin(thet) cos(thet)] ;
% Apply the same rotation on electrode locations
Pt_m = rotyz * SseXYZ ;
% and get their spherical coordinates.
alpha_p = acos(Pt_m(3,:)/Rsc)' ;
beta_p = atan2(Pt_m(2,:),Pt_m(1,:))' ;
mx = [ cos(phi)*cos(thet) -sin(phi) sin(thet)*cos(phi) ] ;
my = [ sin(phi)*cos(thet) cos(phi) sin(thet)*sin(phi)] ;
mz = [ -sin(thet) 0 cos(thet) ] ;
% All data are prepared proceed to main calculation for all electrodes at once.
[VR,VT,nit(ii)] = V1dip(Rsc,f1,f2,e,sigma(1),b,alpha_p) ;
y = cos(beta_p) ; yy = sin(beta_p) ;
% the source orientation (after rotation) m_xyz is combined here
% with the potential V for tangent (VT) and radial (VR) dipole
% and electrodes location beta_p).
Lan(:,3*ii-2) = mx(1)*y.*VT + mx(2)*yy.*VT + mx(3)*VR ;
Lan(:,3*ii-1) = my(1)*y.*VT + my(2)*yy.*VT + my(3)*VR ;
Lan(:,3*ii) = mz(1)*y.*VT + mz(3)*VR ;
end
% fprintf('\n')
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SUBFUNCTION
%
function [VR,VT,n] = V1dip(R,f1,f2,e,sig1,b,alpha_p)
x = cos(alpha_p) ; xx = sin(alpha_p) ;
lim=1e-12 ; nlim=200 ;
% Formula (2a) for d_n
d1 = e*e + 1 + 2.5*e + (1-2*e*e+e)*(f1^3-f2^3) - (1-e)^2*(f1/f2)^3 ; % n=1
d2 = 2*e*e + 2 + e*13/3 + (2-3*e*e+e)*(f1^5-f2^5) - 2*(1-e)^2*(f1/f2)^5 ;% n=2
% This correspnonds to the terms using 'n', 'b' & 'e' in (2)
% (2n+1)/n * e*(2n+1)^2 * b^(n-1) /(d_n*(n+1)) = (2n+1)^3 / ( n*d_n*(n+1) ) * e/b^(n-1)
w1 = 27/2*e/d1 ; % n=1
w2 = 125/6*b*e/d2 ; % n=2
P0_1 = x ; P1_1 = xx ;
P0_2 = .5*(3*x.*x-1) ; P1_2 = 3*xx.*x ;
VtempR = w1*P0_1 + w2*2*P0_2 ;
VtempT = w1*P1_1 + w2*P1_2 ;
Pn_2=P0_1 ; Pn_1=P0_2 ;
P1n_2=P1_1 ; P1n_1=P1_2 ;
VtempR_1=VtempR ;
VtempT_1=VtempT ;
n=3 ; diR=10 ; diT=10 ;
while ((max(abs(diR))>lim) & (max(abs(diT))>lim) & (n<nlim))
% Update Legendre polynome.
Pn = (2*n-1)/n*x.*Pn_1-(n-1)/n*Pn_2 ;
P1n = -(2*n-1)/(1-n)*x.*P1n_1+n/(1-n)*P1n_2 ;
% Equation (2a) as in paper
dn = ( (n+1)*e + n )*( (n*e)/(n+1) + 1 ) ...
+ (1-e)*( (n+1)*e + n ) * ( f1^(2*n+1) - f2^(2*n+1) )...
- n*(1-e)^2*(f1/f2)^(2*n+1) ;
wn = b^(n-1) * e * (2*n+1)^3 / dn / (n+1) / n ;
VtempR = VtempR_1 + wn*n*Pn ;
VtempT = VtempT_1 + wn*P1n ;
diR=(VtempR-VtempR_1) ; % ./ VtempR_1 ;
diT=(VtempT-VtempT_1) ; % ./ VtempT_1 ;
n=n+1 ;
Pn_2 = Pn_1 ; P1n_2 = P1n_1 ;
Pn_1 = Pn ; P1n_1 = P1n ;
VtempR_1 = VtempR ;
VtempT_1 = VtempT ;
end
VR = VtempR / (4*pi*sig1*R^2) ;
VT = VtempT / (4*pi*sig1*R^2) ;
return
|
github
|
spm/spm5-master
|
loadxml.m
|
.m
|
spm5-master/loadxml.m
| 3,893 |
utf_8
|
fb0e9f8657c033469c24d5750518420a
|
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: 112 $ $Date: 2003/07/10 13:50 $
% $Id: loadxml.m 112 2005-05-04 18:20:52Z john $
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
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
|
spm/spm5-master
|
spm_eeg_make3dimage.m
|
.m
|
spm5-master/spm_eeg_make3dimage.m
| 842 |
utf_8
|
56786cc3d8080f1ea73122f241ca284c
|
function D = spm_eeg_make3dimage(S)
% function for converting 2D images to 3D volumes for ERPs
% FORMAT D = spm_eeg_downsample(S)
%
% S - optional input struct
% (optional) fields of S:
% D - filename of EEG mat-file
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% James Kilner
try
D = S.D;
catch
D = spm_select(1, '\.img$', 'Select EEG image file');
end
v=spm_vol([D]);
data=zeros(v(1).dim(1),v(1).dim(1),length(v));
for n=1:length(v)
[temp,XYZ]=spm_read_vols(v(n));
data(:,:,n)=temp;
end
V=v(1);
[pathstr,name,ext,cersn] = spm_fileparts(D) ;
V.fname = fullfile(pathstr,[name '3d.img']);
V.dim = [v(1).dim(1) v(1).dim(2) length(v)];
V.mat = eye(4);
%V.pinfo = [1 0 0]';
V = rmfield(V,'pinfo');
spm_write_vol(V, data);
|
github
|
spm/spm5-master
|
treelist.m
|
.m
|
spm5-master/treelist.m
| 10,461 |
utf_8
|
58343a29b98e2a4ea6134a424ebb9b43
|
% TREELIST - Lists data in cell arrays and structs as ascii "tree"
%
% Version 1.1
%
% This functions lists the contents of structs, sub struct, cell arrays
% and sub cell array with chars: |-\ viewing the connection in the data.
% The main differents from the builtin DISP, DISPLAY is that this function
% lists all levels of sub cell arrays or struct in cells or structs.
%
% The syntax is similar to WHOS:
%
% treelist varname1 varname2 .....
%
% By default, treelist does not show field contents and does not expand
% struct arrays. This behaviour can be changed by calling treelist as a
% function:
%
% treelist('varname1','varname2',...,flags)
%
% where flags is a struct that may contain the following fields:
% .dval - display values of fields?
% 0 (default) don't display values
% 1 display values in tree structure
% 2 display values in (nearly) MATLAB script syntax, suitable for
% output to a script file (see fname below) - see BUGs for the
% limitations to this option
% .exps - expand struct arrays?
% 0 (default) don't expand
% 1 expand each member of struct arrays
% .fname - output file name. If not empty, output will be redirected to
% the given file
%
% (C) Copyright 2002 Peter Rydesaeter, GNU General Public License.
% 2004 Modified by Volkmar Glauche to make struct array expansion and
% value display optional.
%
% Se also:
%
% WHOS, WHO, DISP, DISPLAY, CELL, STRUCT
%
% BUGs:
% Displaying values as MATLAB code is limited by the following
% constraints:
% * Object treatment is implemented only to a limited degree.
function treelist(varargin)
defflags = struct('dval',0, 'exps',0, 'fid',1, 'fname','');
if isstruct(varargin{end})
flags = fillstruct(defflags,varargin{end});
nvars = nargin-1;
else
flags = defflags;
nvars = nargin;
end;
if ~isempty(flags.fname)
flags.fid = fopen(flags.fname,'w');
end;
for n=1:nvars,
try
v = evalin('caller',varargin{n});
iname = varargin{n};
catch
v = varargin{n};
iname = inputname(n);
end;
% for documentation, list things twice if creating MATLAB code and
% writing to a file - first listing the variable structure only
if flags.dval==2 && flags.fid > 2
flags1=flags;
flags1.dval=0;
treelistsub(v,iname,'','',flags1);
end;
treelistsub(v,iname,'','',flags);
end
if flags.fid > 2
fclose(flags.fid);
end;
return;
function treelistsub(dt,name,nameprefix,level,flags)
if nargin<4, level=''; end
if nargin<3, nameprefix=''; end
if nargin<2, name=inputname(1); end
whosdt=whos('dt');
if isobject(dt)
dtclass='object';
else
dtclass=whosdt.class;
end;
switch dtclass
case {'double', 'logical', 'single', 'uint8', 'uint16', 'uint32', 'uint64', ...
'int8', 'int16', 'int32', 'int64', 'char'}
if isempty(dt),
if flags.dval <= 1
dtstr={{'[]'}};
elseif flags.dval == 2
dtstr={{''}};
end;
else
if (flags.dval == 1) || strcmp(dtclass, 'char')
dtstr=textscan(evalc('format compact;format long g;disp(full(dt));format'), '%s', ...
'delimiter', char(10));
elseif (flags.dval == 2) && ~strcmp(dtclass, 'char')
% Display full(dt(:)) and reshape it after printing - this
% should remedy all problems with sparse and multidim arrays
dtstr=textscan(evalc('format compact;format long g;disp(full(dt(:)));format'),...
'%s', 'delimiter', char(10));
else
dtstr={{sprintf('%s%d %s', sprintf('%d-x-',whosdt.size(1:end-1)), ...
whosdt.size(end), dtclass)}};
end;
end
if flags.dval < 2
if length(level)==0,
ss=sprintf('%s',name);
else
ss=sprintf('%s-%s ',level,name);
end
lv=length(level)+20;
if length(ss)<lv, ss(end+1:lv)='.'; end
idx=[1 find(ss=='-')];
ss2=ss;
ss2(idx(end):end)=' ';
for k=1:numel(dtstr{1})
if length(dtstr{1}{k})<79-length(ss),
fprintf(flags.fid,'%% %s %s\n',ss,dtstr{1}{k});
else
if k==1,
fprintf(flags.fid,'%%%s\n', ss);
end
fprintf(flags.fid,'%%%s\n', dtstr{1}{k});
end
ss=ss2;
end
else
if strcmp(dtclass,'char')
reshead='';
resfoot='';
else
reshead='reshape(';
resfoot=sprintf(',[%s%d])',sprintf('%d,',whosdt.size(1:end-1)), ...
whosdt.size(end));
end;
if whosdt.sparse
sphead='sparse(';
spfoot=')';
else
sphead='';
spfoot='';
end;
headstr=sprintf('%s%s = %s%s%s([\n', ...
nameprefix, name, reshead, sphead, dtclass);
fprintf(flags.fid,headstr);
indentstr=char(repmat(' ',1, ...
length(headstr)));
if strcmp(dtclass, 'char')
delim='''';
else
delim='';
end;
for k=1:numel(dtstr{1})
fprintf(flags.fid,indentstr);
if strcmp(dtclass, 'char')
% if there is a string with single
% quotes, replace them with double ones
dtstr{1}{k}=strrep(dtstr{1}{k},'''', ...
'''''');
end;
fprintf(flags.fid,'%s%s%s\n', delim,dtstr{1}{k},delim);
end;
fprintf(flags.fid,'%s])%s%s;\n',indentstr,spfoot,resfoot);
end;
case {'struct','object'}
fn=fieldnames(dt);
if numel(dt)==0,
fprintf(flags.fid,sprintf('%% %s-%s Empty STRUCT\n',level,name));
if flags.dval > 1
fprintf(flags.fid,'%s%s = struct([]);\n',nameprefix,name);
end;
return;
elseif numel(dt)>1,
if flags.exps
fprintf(flags.fid,'%% %s-%s \n',level,name);
level(find(level=='\'))=' ';
if flags.dval > 1
fprintf(flags.fid,['%%==============================================' ...
'================\n']);
fprintf(flags.fid,'%% %s%s\n',nameprefix,name);
fprintf(flags.fid,['%%==============================================' ...
'================\n']);
end;
% get ndims and size to produce correct indices
funcstr=get_index_func(dt);
for m=1:numel(dt),
eval(funcstr);
newname = sprintf('%s(%s)',name,msubstr);
if flags.dval > 1
fprintf(flags.fid,['%%----------------------------------------------' ...
'----------------\n']);
fprintf(flags.fid,'%% %s%s\n',nameprefix,newname);
fprintf(flags.fid,['%%----------------------------------------------' ...
'----------------\n']);
end;
if m==numel(dt),
treelistsub(dt(m),newname,nameprefix,[level ' \'],flags);
else
treelistsub(dt(m),newname,nameprefix,[level ' |'],flags);
end
end
else
dtstr=sprintf('%s-%s %d-x-',level,name,whosdt.size(1:end-1));
level(find(level=='\'))=' ';
dtstr=fprintf(flags.fid,'%% %s%d struct array with fields\n',dtstr,whosdt.size(end));
for n=1:numel(fn)
fprintf(flags.fid,'%%%s %s\n', level, fn{n});
end;
end;
return;
else
if flags.dval<2
fprintf(flags.fid,'%% %s-%s\n',level,name);
end;
level(find(level=='\'))=' ';
ww = warning('off'); %%HACK To remove warning msg
if flags.dval==2 && strcmp(dtclass,'object')
fprintf(flags.fid,'%s%s = %s;\n', ...
nameprefix,name,whosdt.class);
end;
for n=1:numel(fn),
dts=getfield(dt,fn{n});
newname=sprintf('%s',fn{n});
newnameprefix=sprintf('%s%s.',nameprefix,name);
if n==numel(fn),
treelistsub(dts,newname,newnameprefix,[level ' \'],flags);
else
treelistsub(dts,newname,newnameprefix,[level ' |'],flags);
end
end;
warning(ww);
end
return;
case 'cell',
if numel(dt)==0,
fprintf(flags.fid,'%% %s-%s Empty CELL\n',level,name);
if flags.dval > 1
fprintf(flags.fid,'%s%s = {};\n',nameprefix,name);
end;
return;
end
fprintf(flags.fid,'%% %s-%s \n',level,name);
level(find(level=='\'))=' ';
% get ndims and size to produce correct indices
funcstr=get_index_func(dt);
for m=1:numel(dt),
eval(funcstr);
newname=sprintf('%s{%s}',name,msubstr);
if m==numel(dt),
treelistsub(dt{m},newname,nameprefix,[level ' \'],flags);
else
treelistsub(dt{m},newname,nameprefix,[level ' |'],flags);
end
end
return;
otherwise
fprintf('%% %s-%s Unknown item of class ''%s''\n', level, name, ...
whosdt.class);
end
return;
function funcstr = get_index_func(dt,varargin)
% produce code to correctly convert linear indexes to subscript indexes
% for variable dt
% Assumptions:
% - index array will be called 'ind'
% - running variable is called 'm'
% - printout of subscript index is called 'msubstr'
defflags = struct('indname','ind', 'runname','m', 'subsname','msubstr');
if nargin > 1
flags = fillstruct(defflags,varargin{1});
else
flags = defflags;
end;
% get ndims and size to produce correct indices
nddt = ndims(dt);
szdt = size(dt);
% omit last dimension for 1-x-N arrays (vectors), but don't do that for
% N-x-1 arrays. The former ones may be created using assignments like
% dt(k)=val_of_dt, while the latter ones must have been created with
% dt(k,1)=val_of_dt and must be assumed to be deliberately assigned to
% columns instead of rows.
if szdt(1)==1
nddt = nddt-1;
szdt = szdt(2:end);
end;
indstr = sprintf(sprintf('%s(%%d),',flags.indname),1:nddt);
funcstr = sprintf(['[%s] = ind2sub([%s],%s);%s=sprintf(''%%d,'',%s);' ...
'%s=%s(1:end-1);'], indstr(1:end-1), num2str(szdt), flags.runname, ...
flags.subsname, flags.indname, flags.subsname, flags.subsname);
|
github
|
spm/spm5-master
|
spm_normalise.m
|
.m
|
spm5-master/spm_normalise.m
| 13,162 |
utf_8
|
20a4dada77c2a5124d6b3710a07e7d31
|
function params = spm_normalise(VG,VF,matname,VWG,VWF,flags)
% Spatial (stereotactic) normalization
%
% FORMAT params = spm_normalise(VG,VF,matname,VWG,VWF,flags)
% VG - template handle(s)
% VF - handle of image to estimate params from
% matname - name of file to store deformation definitions
% VWG - template weighting image
% VWF - source weighting image
% flags - flags. If any field is not passed, then defaults are assumed.
% smosrc - smoothing of source image (FWHM of Gaussian in mm).
% Defaults to 8.
% smoref - smoothing of template image (defaults to 0).
% regtype - regularisation type for affine registration
% See spm_affreg.m (default = 'mni').
% cutoff - Cutoff of the DCT bases. Lower values mean more
% basis functions are used (default = 30mm).
% nits - number of nonlinear iterations (default=16).
% reg - amount of regularisation (default=0.1)
% ___________________________________________________________________________
%
% This module spatially (stereotactically) normalizes MRI, PET or SPECT
% images into a standard space defined by some ideal model or template
% image[s]. The template images supplied with SPM conform to the space
% defined by the ICBM, NIH P-20 project, and approximate that of the
% the space described in the atlas of Talairach and Tournoux (1988).
% The transformation can also be applied to any other image that has
% been coregistered with these scans.
%
%
% Mechanism
% Generally, the algorithms work by minimising the sum of squares
% difference between the image which is to be normalised, and a linear
% combination of one or more template images. For the least squares
% registration to produce an unbiased estimate of the spatial
% transformation, the image contrast in the templates (or linear
% combination of templates) should be similar to that of the image from
% which the spatial normalization is derived. The registration simply
% searches for an optimum solution. If the starting estimates are not
% good, then the optimum it finds may not find the global optimum.
%
% The first step of the normalization is to determine the optimum
% 12-parameter affine transformation. Initially, the registration is
% performed by matching the whole of the head (including the scalp) to
% the template. Following this, the registration proceeded by only
% matching the brains together, by appropriate weighting of the template
% voxels. This is a completely automated procedure (that does not
% require ``scalp editing'') that discounts the confounding effects of
% skull and scalp differences. A Bayesian framework is used, such that
% the registration searches for the solution that maximizes the a
% posteriori probability of it being correct. i.e., it maximizes the
% product of the likelihood function (derived from the residual squared
% difference) and the prior function (which is based on the probability
% of obtaining a particular set of zooms and shears).
%
% The affine registration is followed by estimating nonlinear deformations,
% whereby the deformations are defined by a linear combination of three
% dimensional discrete cosine transform (DCT) basis functions.
% The parameters represent coefficients of the deformations in
% three orthogonal directions. The matching involved simultaneously
% minimizing the bending energies of the deformation fields and the
% residual squared difference between the images and template(s).
%
% An option is provided for allowing weighting images (consisting of pixel
% values between the range of zero to one) to be used for registering
% abnormal or lesioned brains. These images should match the dimensions
% of the image from which the parameters are estimated, and should contain
% zeros corresponding to regions of abnormal tissue.
%
%
% Uses
% Primarily for stereotactic normalization to facilitate inter-subject
% averaging and precise characterization of functional anatomy. It is
% not necessary to spatially normalise the data (this is only a
% pre-requisite for intersubject averaging or reporting in the
% Talairach space).
%
% Inputs
% The first input is the image which is to be normalised. This image
% should be of the same modality (and MRI sequence etc) as the template
% which is specified. The same spatial transformation can then be
% applied to any other images of the same subject. These files should
% conform to the SPM data format (See 'Data Format'). Many subjects can
% be entered at once, and there is no restriction on image dimensions
% or voxel size.
%
% Providing that the images have a correct ".mat" file associated with
% them, which describes the spatial relationship between them, it is
% possible to spatially normalise the images without having first
% resliced them all into the same space. The ".mat" files are generated
% by "spm_realign" or "spm_coregister".
%
% Default values of parameters pertaining to the extent and sampling of
% the standard space can be changed, including the model or template
% image[s].
%
%
% Outputs
% All normalized *.img scans are written to the same subdirectory as
% the original *.img, prefixed with a 'n' (i.e. n*.img). The details
% of the transformations are displayed in the results window, and the
% parameters are saved in the "*_sn.mat" file.
%
%
%____________________________________________________________________________
% Refs:
% K.J. Friston, J. Ashburner, C.D. Frith, J.-B. Poline,
% J.D. Heather, and R.S.J. Frackowiak
% Spatial Registration and Normalization of Images.
% Human Brain Mapping 2:165-189(1995)
%
% J. Ashburner, P. Neelin, D.L. Collins, A.C. Evans and K. J. Friston
% Incorporating Prior Knowledge into Image Registration.
% NeuroImage 6:344-352 (1997)
%
% J. Ashburner and K. J. Friston
% Nonlinear Spatial Normalization using Basis Functions.
% Human Brain Mapping 7(4):in press (1999)
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_normalise.m 946 2007-10-15 16:36:06Z john $
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 = struct('smosrc',8,'smoref',0,'regtype','mni',...
'cutoff',30,'nits',16,'reg',0.1,'graphics',1);
if nargin < 6,
flags = def_flags;
else
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags = setfield(flags,fnms{i},getfield(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_chi2_plot('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_chi2_plot('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_matlab_version_chk('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 normalize.
% VWG - weighting Volume - for template.
% VWF - weighting Volume - for object.
% Affine - A 4x4 transformation (in voxel space).
% fwhm - smoothness of images.
% cutoff - frequency cutoff of basis functions.
% nits - number of iterations.
% reg - regularisation.
% Tr - Discrete cosine transform of the warps in X, Y & Z.
%
% snbasis performs a spatial normalization based upon a 3D
% discrete cosine transform.
%
%______________________________________________________________________
fwhm = [fwhm 30];
% Number of basis functions for x, y & z
%-----------------------------------------------------------------------
tmp = sqrt(sum(VG(1).mat(1:3,1:3).^2));
k = max(round((VG(1).dim(1:3).*tmp)/cutoff),[1 1 1]);
% 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 - for some bizarre reason, this needs to be done
% as two seperate statements in Matlab 6.5...
%-----------------------------------------------------------------------
Tr = reshape(T(1:s1),[k 3]);
drawnow;
Tr = Tr*stabilise.^3;
return;
|
github
|
spm/spm5-master
|
spm_pf.m
|
.m
|
spm5-master/spm_pf.m
| 6,775 |
utf_8
|
2789f6cf4185c0bae57568078459b24d
|
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) 2005 Wellcome Department of Imaging Neuroscience
% Karl Friston
% $Id: spm_pf.m 894 2007-08-23 18:37:51Z karl $
% 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
|
spm/spm5-master
|
spm_SpUtil.m
|
.m
|
spm5-master/spm_SpUtil.m
| 26,532 |
utf_8
|
3b40e62f97e91ccb5a8bc1cac222f39d
|
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) 2005 Wellcome Department of Imaging Neuroscience
% Andrew Holmes Jean-Baptiste Poline
% $Id: spm_SpUtil.m 112 2005-05-04 18:20:52Z john $
% (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
|
spm/spm5-master
|
spm_config_checkreg.m
|
.m
|
spm5-master/spm_config_checkreg.m
| 1,973 |
utf_8
|
22083b0d66942baadf969c8ccc65c399
|
function opts = spm_config_checkreg
% Configuration file for check-reg jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_checkreg.m 171 2005-05-20 19:20:10Z john $
data.type = 'files';
data.name = 'Images to Display';
data.tag = 'data';
data.filter = 'image';
data.num = [1 15];
data.help = {'Images to display.'};
opts.type = 'branch';
opts.name = 'Check Registration';
opts.tag = 'checkreg';
opts.val = {data};
opts.prog = @dispims;
opts.help = {[...
'Orthogonal views of one or more images are displayed. Clicking in '...
'any image moves the centre of the orthogonal views. Images are '...
'shown in orientations relative to that of the first selected image. '...
'The first specified image is shown at the top-left, and the last at '...
'the bottom right. The fastest increment is in the left-to-right '...
'direction (the same as you are reading this).'],...
'',...
['If you have put your images in the correct file format, ',...
'then (possibly after specifying some rigid-body rotations):'],...
[' The top-left image is coronal with the top (superior) ',...
'of the head displayed at the top and the left shown on the left. ',...
'This is as if the subject is viewed from behind.'],...
[' The bottom-left image is axial with the front (anterior) of the ',...
'head at the top and the left shown on the left. ',...
'This is as if the subject is viewed from above.'],...
[' The top-right image is sagittal with the front (anterior) of ',...
'the head at the left and the top of the head shown at the top. ',...
'This is as if the subject is viewed from the left.']};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dispims(varargin)
job = strvcat(varargin{1}.data);
spm_check_registration(job);
return;
|
github
|
spm/spm5-master
|
spm_dicom_convert.m
|
.m
|
spm5-master/spm_dicom_convert.m
| 40,700 |
utf_8
|
feaec8fcbfd853cc66ad24c8f1367572
|
function 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)
% 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 (position only)
% This will write out a mask image volume with 1's
% set at the position of spectroscopy voxel(s).
% 'raw' - convert raw FIDs (not implemented)
% root_dir - 'flat' - SPM5 standard, do not produce file tree
% 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>
% 'name' - Place files under ./<PatName>
% format - output format
% 'img' Two file (hdr+img) NIfTI format
% 'nii' Single file NIfTI format
% All images will contain a single 3D dataset, 4D images
% will not be created.
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner & Jesper Andersson
% $Id: spm_dicom_convert.m 917 2007-09-14 09:28:55Z volkmar $
if nargin<2, opts = 'all'; end;
if nargin<3, root_dir='flat';end;
if nargin<4, format='img';end;
[images,guff] = select_tomographic_images(hdr);
[spect,images] = select_spectroscopy_images(images);
[mosaic,standard] = select_mosaic_images(images);
if (strcmp(opts,'all') || strcmp(opts,'mosaic')) && ~isempty(mosaic),
convert_mosaic(mosaic,root_dir,format);
end;
if (strcmp(opts,'all') || strcmp(opts,'standard')) && ~isempty(standard),
convert_standard(standard,root_dir,format);
end;
if (strcmp(opts,'all') || strcmp(opts,'spect')) && ~isempty(spect),
convert_spectroscopy(spect,root_dir,format);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function convert_mosaic(hdr,root_dir,format)
spm_progress_bar('Init',length(hdr),'Writing Mosaic', 'Files written');
for i=1:length(hdr),
% Output filename
%-------------------------------------------------------------------
fname = 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 = [spm_type('int16') spm_platform('bigend')];
% 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(fname,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;
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function convert_standard(hdr,root_dir,format)
hdr = sort_into_volumes(hdr);
for i=1:length(hdr),
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;
dist2 = sum((xy1-xy2).^2);
% 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 = 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-5 &&...
sum((hdr{i}.PixelSpacing - vol{j}{1}.PixelSpacing).^2)<1e-5 && ...
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;
[z,index] = sort(z);
dist = diff(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 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 = [spm_type('int16') spm_platform('bigend')];
% 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]'];
orient = reshape(hdr{1}.ImageOrientationPatient,[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end;
if length(hdr)>1,
z = zeros(length(hdr),1);
for i=1:length(hdr),
z(i) = hdr{i}.ImagePositionPatient*orient(:,3);
end;
z = mean(diff(z));
else
if checkfields(hdr{1},'SliceThickness'),
z = hdr{1}.SliceThickness;
else
z = 1;
end;
end;
vox = [hdr{1}.PixelSpacing z];
pos = hdr{1}.ImagePositionPatient';
dicom_to_patient = [orient*diag(vox) pos ; 0 0 0 1];
patient_to_tal = diag([-1 -1 1 1]);
mat = patient_to_tal*dicom_to_patient*analyze_to_dicom;
if strcmp(hdr{1}.Modality,'CT') && numel(hdr)>1
shear = (hdr{1}.ImagePositionPatient-hdr{2}.ImagePositionPatient) ...
* reshape(hdr{1}.ImageOrientationPatient,[3 2]);
if shear(1)
warning('shear(1) = %f not applied\n', shear(1));
end;
warning('shear(2) = %f applied\n', shear(2));
try
prms = spm_imatrix(mat);
prms(12) = shear(2);
mat = spm_matrix(prms);
end;
end;
% 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;
pinfo = [1 0 0]';
if isfield(hdr{1},'RescaleSlope') || isfield(hdr{1},'RescaleIntercept'),
pinfo = repmat(pinfo,1,length(hdr));
bytepix = spm_type('int16','bits')/8;
for i=1:length(hdr),
if isfield(hdr{i},'RescaleSlope'), pinfo(1,i) = hdr{i}.RescaleSlope; end;
if isfield(hdr{i},'RescaleIntercept'), pinfo(2,i) = hdr{i}.RescaleIntercept; end;
pinfo(3,i) = dim(1)*dim(2)*(i-1)*bytepix;
end;
end;
% Write the image volume
%-------------------------------------------------------------------
spm_progress_bar('Init',length(hdr),['Writing ' fname], 'Planes written');
%V = struct('fname',fname, 'dim',dim, 'dt',dt, 'pinfo',pinfo, 'mat',mat, 'descrip',descrip);
%V = spm_create_vol(V);
N = nifti;
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);
volume = zeros(dim);
for i=1:length(hdr),
plane = read_image_data(hdr{i});
if isfield(hdr{i},'RescaleSlope'), plane = plane*hdr{i}.RescaleSlope; end;
if isfield(hdr{i},'RescaleIntercept'), plane = plane+hdr{i}.RescaleIntercept; end;
plane = fliplr(plane);
if ~true, plane = flipud(plane); end; % LEFT-HANDED STORAGE
%V = spm_write_plane(V,plane,i);
% collect all planes before writing to disk
volume(:,:,i) = plane;
spm_progress_bar('Set',i);
end;
% write volume at once - see spm_write_plane for performance comments
N.dat(:,:,:) = volume;
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function convert_spectroscopy(hdr,root_dir,format)
for i=1:length(hdr),
write_spectroscopy_volume(hdr(i),root_dir,format);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function write_spectroscopy_volume(hdr,root_dir,format)
% Output filename
%-------------------------------------------------------------------
fname = getfilelocation(hdr{1}, root_dir,'S',format);
% Image dimensions
%-------------------------------------------------------------------
nc = get_numaris4_numval(hdr{1}.Private_0029_1210,'Columns');
nr = get_numaris4_numval(hdr{1}.Private_0029_1210,'Rows');
dim = [nc nr numel(hdr)];
dt = [spm_type('int16') spm_platform('bigend')];
% 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]'];
orient = reshape(get_numaris4_numval(hdr{1}.Private_0029_1210,...
'ImageOrientationPatient'),[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end;
if length(hdr)>1,
z = zeros(length(hdr),1);
for i=1:length(hdr),
z(i) = get_numaris4_numval(hdr{i}.Private_0029_1210,...
'ImagePositionPatient')*orient(:,3);
end;
z = mean(diff(z));
else
try
z = get_numaris4_numval(hdr{1}.Private_0029_1210,...
'SliceThickness');
catch
z = 1;
end;
end;
vox = [get_numaris4_numval(hdr{1}.Private_0029_1210,'PixelSpacing') z];
pos = get_numaris4_numval(hdr{1}.Private_0029_1210,'ImagePositionPatient')';
%dicom_to_patient = [orient*diag(vox) pos-1.5*orient*([0 vox(2) 0]') ; 0 0 0 1];
dicom_to_patient = [orient*diag(vox) pos ; 0 0 0 1];
patient_to_tal = diag([-1 -1 1 1]);
warning('Don''t know exactly what positions in spectroscopy files should be - just guessing!')
mat = patient_to_tal*dicom_to_patient*analyze_to_dicom;
if strcmp(hdr{1}.Modality,'CT') && numel(hdr)>1
shear = (hdr{1}.ImagePositionPatient-hdr{2}.ImagePositionPatient) ...
* reshape(hdr{1}.ImageOrientationPatient,[3 2]);
if shear(1)
warning('shear(1) = %f not applied\n', shear(1));
end;
warning('shear(2) = %f applied\n', shear(2));
try
prms = spm_imatrix(mat);
prms(12) = shear(2);
mat = spm_matrix(prms);
end;
end;
% 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;
pinfo = [1 0 0]';
if isfield(hdr{1},'RescaleSlope') || isfield(hdr{1},'RescaleIntercept'),
pinfo = repmat(pinfo,1,length(hdr));
bytepix = spm_type('int16','bits')/8;
for i=1:length(hdr),
if isfield(hdr{i},'RescaleSlope'), pinfo(1,i) = hdr{i}.RescaleSlope; end;
if isfield(hdr{i},'RescaleIntercept'), pinfo(2,i) = hdr{i}.RescaleIntercept; end;
pinfo(3,i) = dim(1)*dim(2)*(i-1)*bytepix;
end;
end;
% Write the image volume
%-------------------------------------------------------------------
spm_progress_bar('Init',length(hdr),['Writing ' fname], 'Planes written');
%V = struct('fname',fname, 'dim',dim, 'dt',dt, 'pinfo',pinfo, 'mat',mat, 'descrip',descrip);
%V = spm_create_vol(V);
N = nifti;
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);
volume = zeros(dim);
for i=1:length(hdr),
plane = read_spect_data(hdr{i});
if isfield(hdr{i},'RescaleSlope'), plane = plane*hdr{i}.RescaleSlope; end;
if isfield(hdr{i},'RescaleIntercept'), plane = plane+hdr{i}.RescaleIntercept; end;
plane = fliplr(plane);
if ~true, plane = flipud(plane); end; % LEFT-HANDED STORAGE
%V = spm_write_plane(V,plane,i);
% collect all planes before writing to disk
volume(:,:,i) = plane;
spm_progress_bar('Set',i);
end;
% write volume at once - see spm_write_plane for performance comments
N.dat(:,:,:) = volume;
spm_progress_bar('Clear');
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'))
disp(['Cant find appropriate modality information for "' hdr{i}.Filename '".']);
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_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')
disp('Setting AcquisitionNumber to 1');
hdr{i}.AcquisitionNumber=1;
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}))
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') && isfield(hdr{i},'Private_0029_1210')
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 = find((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;
fseek(fp,hdr.StartOfPixelData,'bof');
img = fread(fp,hdr.Rows*hdr.Columns,prec);
fclose(fp);
if length(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)
% Image dimensions
%-------------------------------------------------------------------
nc = get_numaris4_numval(hdr.Private_0029_1210,'Columns');
nr = get_numaris4_numval(hdr.Private_0029_1210,'Rows');
img = ones(nr,nc);
%_______________________________________________________________________
%_______________________________________________________________________
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);
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 SPM5 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',
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);
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 = findstr(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
% 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
X=get_numaris4_val(hdr.CSASeriesHeaderInfo,'MrProtocol');
ascstart = findstr(X,'### ASCCONV BEGIN ###');
ascend = findstr(X,'### ASCCONV END ###');
if ~isempty(ascstart) && ~isempty(ascend)
tokens = textscan(char(X((ascstart+22):(ascend-1))),'%s', ...
'delimiter',char(10));
for k = 1:numel(tokens{1})
tokens{1}{k}=regexprep(tokens{1}{k},'\[([0-9]*)\]','($1+1)');
tokens{1}{k}=regexprep(tokens{1}{k},'"(.*)"','''$1''');
tokens{1}{k}=regexprep(tokens{1}{k},'0x([0-9a-fA-F]*)','hex2dec(''$1'')');
try
eval(['ret.' tokens{1}{k} ';']);
catch
disp(['AscConv: Error evaluating ''ret.' tokens{1}{k} ''';']);
end;
end;
end;
%_______________________________________________________________________
|
github
|
spm/spm5-master
|
spm_spm_ui.m
|
.m
|
spm5-master/spm_spm_ui.m
| 96,520 |
utf_8
|
bd545cfada5972c76b467ca0170c4274
|
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) 2005 Wellcome Department of Imaging Neuroscience
% Andrew Holmes
% $Id: spm_spm_ui.m 539 2006-05-19 17:59:30Z Darren $
SCCSid = '$Rev: 539 $';
%=======================================================================
% - 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_matlab_version_chk('7') >=0
save('SPM', 'SPM', '-V6');
else
save('SPM', '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
|
spm/spm5-master
|
spm_eeg_inv_model.m
|
.m
|
spm5-master/spm_eeg_inv_model.m
| 61,788 |
utf_8
|
f4208f6ed03ec4d5192751a4d7c2b53f
|
function varargout = spm_eeg_inv_model(action,varargin)
% spm_eeg_inv_model is a multi-purpose routine that deals with the generation
% of the head model for the solution of the forward problem.
%
% Called without arguments :
%
% >> model = spm_eeg_inv_model
%
% the function calls GUI to select the operation(s) to be performed and
% to enter/select the required inputs.
% Here are the main options:
% - Generate scalp/brain vol & tessalate
% - Tessalate predefined binarized volume
% - Project electrodes coord (sphere or real) on scalp/brain surface
% - Define realistic sphere model
% - The 4 steps at once
%
% A 'model' structure is returned. Depending on the operation executed,
% the model will contain: surface meshes, electrodes information,
% realistic sphere model.
%
% Most subfunctions can be called individually. Some even have their own
% little GUI because I used to use them on their own...
%
% The various structure formats (model, head, electrodes) are described
% at the end of this help.
%
%__________________________________________________________________________
% FORMAT [Pvol,Pinv_sn,flags] = spm_eeg_inv_model('GenBin',Pvol,flag_bi);
%
% Generate the binarised image of the brain (and scalp if the image allows).
%
% Input :
% Pvol : filename of the image used to build the head model.
% flag_bi : useful flags
% * img_type: image type 1=T1 MRI, 2 = PET, 3 = EPI
% * img_norm: flag indicating if the image is normalised (1) or not (0)
% * ne,ng : # iteration for erosion and growing
% * thr_im : threhold applied to binarise image
% NOTE: these flags are not always necessary anymore...
% Output :
% Pvol : file name of the bin images gnerated, scalp and iskull
% Pinv_sn : file name of mat file containing inverse of the normalisation
% transform.
% flags : all the flags with added file names for original image, brain
% mask and spatial transformation
%__________________________________________________________________________
%
% FORMAT [head,flags] = spm_eeg_inv_model('GenMesh',Pvol,flags);
%
% Generate the tesselated surface of the 1 to 3 head volumes
% (brain-skull-scalp) from the binarized volumes.
% Input :
% Pvol : filenames of 3 head volumes 'brain', 'skull' & 'scalp'.
% flags : various flags
% * n : (1x3) provides the number of vertices on each surface
% Npt = n(i)^2*5/4+2
% * br_only : only use the binarised brain volume (1) or scalp (0, default)
% * q_elastm: Correct mesh using an elastic model (1, default), or not (0).
% * q_meased: Measure edges of mesh (1), or not (0, default)
% * q_4thpt : Determine 4th point central of each traingle (1), or not (0, default)
% Output :
% head : head structures with 1 to 3 tesselated surfaces
% flags : all the flags used
%__________________________________________________________________________
%
% FORMAT [electrodes,flags] = spm_eeg_inv_model('Elec2Scalp',surf,el_loc,el_name,flags);
%
% Projecting the electrodes (in spherical or realistic coordinates)
% on the realistic head model.
%
% Input :
% - surf : surface on which the electrodes are projected,
% if it's the brain surface, then the scalp-brain width is added
% - el_loc : provided electrode coordinates, on a standard sphere or
% real coordinates as measured estimated on the patient's head.
% - el_name : electrode names.
% - flags : various option flags and extra bits of information
% * q_RealLoc : 'el_loc' contains coordinates on a standard sphere (0),
% or as measured on the patient's head (1)
% * q_RealNI : nasion/inion coordinates are from the template (0),
% or as estimated on the patient's image
% * br_only : only the brain surface is available (1),
% or the scalp surface can be used (0)
% * nasion : coordiantes (in mm), on the template (defaults value filled
% * inion : in if left empty) or as estimated on the patient's image
% * scbr_w : scalp-brain surface width, in mm. (Default 20)
% * Mtempl : Affine transform mapping from the patient image space
% into the template space
% Output :
% electrodes : electrode structure
% flags : all the flags used
%
% When dealing with standard electrode locations on a sphere, one uses
% the coordinates of the nasion and inion to estimate the pitch angle, then
% the electrode locations are mapped into the patient space
% When the real (approximate) electrode locations is provided, these are
% simply adjusted on the scalp surface
% If the model is 'brain only' (from a PET or EPI scan), the approximate
% brain-scalp width is required.
%
% The electrodes substructure is created at the end.
%__________________________________________________________________________
%
% FORMAT [pt_mm] = spm_eeg_inv_model('vx2mm',pt_vx,M);
%
% Transforms point(s) 'pt_vx' voxel coordinates into mm coordinates 'pt_mm'
% according to the transformation matrix 'M'.
% 'M' is the 4x4 affine transformation matrix : from vx to mm
%__________________________________________________________________________
%
% FORMAT [pt_vx] = spm_eeg_inv_model('mm2vx',pt_mm,M);
%
% Transforms point(s) 'pt_mm' mm coordinates into voxel coordinates 'pt_vx'
% according to the transformation matrix 'M'.
% 'M' is the 4x4 affine transformation matrix : from vx to mm
%__________________________________________________________________________
%
% FORMAT [Centre,c_mm] = spm_eeg_inv_model('CtrBin',P);
%
% Determine the "centre of mass" (vx and mm) of a bin image.
%__________________________________________________________________________
%
% FORMAT [vn,vn_i,S,S_i] = spm_eeg_inv_model('NormTri',l_tr,ts)
%
% Calcultates the normal and surface of a triangle on a tesselated surface.
% If a list of triangle is provided, then the "mean" normal and the normals are calculated.
% Input :
% l_tr = index of triangle
% ts = tesselated surface
% Output:
% vn = (mean) normalised normal vector
% vn_i = individual normal vectors
% S = (mean) surface
% S_i = individual surfaces
%__________________________________________________________________________
%
% FORMAT ts = spm_eeg_inv_model('TesBin',n,Centre,P,info);
%
% Generate a mesh covering a binarized volume
% 1. Generate a simple spherical mesh
% 2. The spherical mesh is projected radially on the bin volume
% Afterwards, "elastic" mesh correction can thus be useful to correct
% some overlong edges.
%
% Input :
% n: number of vertices on each surface Npt = n^2*5/4+2
% Centre: centre of bin volume for the radial projection
% P: filename of bin volume
% info: information string
%__________________________________________________________________________
%
% FORMAT ts = spm_eeg_inv_model('ElastM',ts);
%
% Modify the the mesh in order to reduce overlong edges.
% The procedure uses an elastic model :
% At each vertex, the neighbouring triangles and vertices connected directly
% are considered.
% Each edge is considered elastic and can be lengthened or shortened,
% depending on their legnth.
% Algorithm: G.Taubin, A signal processing approach to fair surface design, 1995
% This is a non-shrinking smoothing algo.
%
% Input :
% ts: tesselated surface
% Output :
% ts: tesselated surface with corrected mesh
%__________________________________________________________________________
%
% FORMAT ts = spm_eeg_inv_model('MeasEd',ts);
%
% This measures the edges of the mesh.
% Input : ts
% Output : ts with measured edges
%__________________________________________________________________________
%
% FORMAT ts = spm_eeg_inv_model('Tr4thPt',ts);
%
% Finds the 4th' point of each triangle:
% a flat triangle is only an approximation of the real underlying volume surface,
% a 4th point taken at the centre of the triangle is found by approximating
% the neighbouring triangles in a sphere, to provide an idea of the local curvature.
% This is used in the BEM solution of the forward problem, to sort out
% the problem of the auto-solid angle.
%
% Input :
% ts: tesselated surface
% Output :
% ts: tesselated surface with 4th point at each triangle
%__________________________________________________________________________
%
% FORMAT tsph = spm_eeg_inv_model('TesSph',n,r);
%
% Generate a structure 'tsph' containing a tesselated sphere.
% Input :
% n : number of 'latitude' divisions on the sphere. It MUST be even!
% r : radius of the sphere
% Output :
% tsph .vert : vertices coordinates (3 x Nvert)
% .tri : triangle patches (3 x Ntri)
% .info : info string
%__________________________________________________________________________
%
% FORMAT [Pout/val] = spm_eeg_inv_model('ErodeGrow',P/val,ne,ng,thr_im)
%
% It erodes then grows an image after thresholding it.
% Inputs : P/val,ne,ng,thr_im
% P : file name of image to erode/grow
% val : full volume of image (as loaded by spm_read_vols)
% ne : nr of steps for erosion, default 3
% ng : nr of steps for growing, default 6
% thr_im : threshold value to apply, default .8
% (compared to the maximal value of image)
% Output : Pout/val
% Pout : name of the file generated
% val : full value of eroded-grown image
%
% Notes:
% - if 2 file names are specified in P[input], the 2nd one is used as the name
% of the generated file otherwise the new filename is creted from P as
% [P,'_e',num2str(ne),'g',num2str(ng),'.img']
% - If a file name is passed the output is a filename.
% If a matrix of values is passed, the output is a matrix of values.
%
% IMPORTATNT !!!
% - It uses brutal force as it loads the whole image into memory !!!
% things are eased up by usint unsigned integers.
% - voxels are supposed to be isotropic in size...
%
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Christophe Phillips,
% $Id: spm_eeg_inv_model.m 1039 2007-12-21 20:20:38Z karl $
% Format of 'model' structure :
% #############################
%
% model.
% head : structure of head surfaces (1x3)
% electrodes : structure for electrodes
% Mtempl : affine transformation from the patient into the template space
% sigma : conductivity values (1x3)
% (IFS : cells containing Intermediate Forward Solution (1x3),
% these do NOT depend on the dipoles grid.)
% Only used for the BEM solution !
%
% 'head' sub-structure format
% ===========================
% .head(i) : i=1,2,3 for brain, skull & scalp surfaces
% XYZmm : coordinates of vertices (3xNv)
% tri : indices of vertices in triangles (3xNt)
% M : voxel-to-mm space transformation matrix
% nr : [nr_of_vertices (Nv) & nr_of_triangles (Nt)]
% pt4.XYZvx : coord of projected triangle centre (3xNt)
% edges. : triangles edges information structure
% ed : edges length, vertices indices and triangles indices
% nr : [nr_edges mean_length std_length]
% info : informations
%
%
% Format of .edges :
% ------------------
% .edges.ed :
% ed(:,1) = length,
% ed(:,[2 3]) = indices of 2 vertices, e.g ind. of a and c
% ed(:,[4 5]) = indices of 2 triangles, e.g ind. of I and II
%
% length a x------x b
% _______ /\ I /
% ' ` / o /
% x---o---x / II \ /
% d x------x c
%
% .edges.nr :
% nr(1) : number of edges,
% nr([2 3]) : mean and std of edges length.
%
% 'electrodes' sub-structure format
% =================================
% .electrodes. : structure for electrodes
% vert : index of the closest vertex (Nel x 1)
% tri : index of the triangle beneath each electrode
% nr : nr of electrodes
% XYZmm : coord. of electrodes on the scalp (in voxel)
% M : voxel-to-mm space transformation matrix
% Cnames : electrodes names
% info :
% nasion :
% inion :
spm('FigName','Realistic head model');
if nargin == 0, action = 'Init'; end;
switch lower(action),
%________________________________________________________________________
case 'init'
%------------------------------------------------------------------------
% Use a GUI.
%------------------------------------------------------------------------
pos = 1 ;
% Select the operation through the GUI or from passed variable
if nargin==2 && isnumeric(varargin{1})
gener = round(varargin{1});
if gener<1 || gener>5
gener = 5;
warning('Wrong options for model, I assume "generate all at once"');
end
else
text_opt = [...
'Generate scalp/brain vol & tessalate|',...
'Tessalate predefined binarized volume|',...
'Project electrodes coord (spher or real) on scalp/brain surface|',...
'Define realistic sphere model|',...
'The 4 steps at once'];
gener = spm_input('Generate what ?',pos,'m',text_opt);
end
% Load required inputs
%======================
if gener==1 || gener==5
% Generate scalp/brain vol & tessalate
Pvol = spm_select(1,'image','Image to build model');
% flag_bi.img_type = spm_input('Image type :','+1','T1 MRI|PET|EPI',[1,2,3],1);
flag_bi.img_type = 1; % Assume it's always a structural MR image.
% flag_bi.img_norm = spm_input('Image normalised already :','+1','y/n',[1,0],2);
flag_bi.img_norm = 0; % Assume it is not normalised yet.
if flag_bi.img_type==1
flag_te.br_only=0;
flag_te.Nvol = 2;
else
flag_te.br_only=1;
flag_te.Nvol = 1;
end
end
if gener==2
% Tessalate predefined binarized volume only.
Pvol = spm_select(Inf,'*_o*.img','1-2-3 bin images to tessalate (br-sk-sc)');
flag_te.Nvol = size(Pvol,1);
if flag_te.Nvol==1
flag_te.br_only = spm_input('Is this the brain bin volume ?','+1','y/n',[1,0],0);
else
flag_te.br_only=0;
end
if ~isempty(PMtempl)
load(PMtempl)
else
warning('It is assumed that the bin volumes are in the template space !')
Mtempl = eye(4);
end
end
if gener==1 || gener==2 || gener==5
% Generate scalp/brain vol & tessalate binarized volume
if flag_te.Nvol>1 || flag_te.br_only
% Npt = spm_input('Approx. nr of vertices on brain surf','+1','e',4000);
Npt = 4000; % 4000 seems a "good" number for the inner skull surface
flag_te.n = zeros(1,3); flag_te.n(1) = 2*round((sqrt((Npt-2)*4/5))/2);
end
if ~flag_te.br_only
% Npt = spm_input('Approx. nr of vertices on sk/sc surf','+1','e',2000);
Npt = 4000; % Use also about 4000 vertices for the scalp surface
if flag_te.Nvol>1
flag_te.n(2:3) = 2*round((sqrt((Npt-2)*4/5))/2);
else
flag_te.n = 2*round((sqrt((Npt-2)*4/5))/2);
end
end
% flag_te.q_elast_m = spm_input('Correct the projected mesh ?','+1','y/n',[1,0],1) ;
flag_te.q_elast_m = 1 ; % of course do the "surface smoothing".
[pth,fn,ext,nr] = spm_fileparts(Pvol);
Pmod = fullfile(pth,['model_head_',fn,'.mat']);
end
if gener==3 || gener==5
% Project electrodes coord (spher or real) on scalp/brain surface
if gener==3
Pmod = spm_select(1,'^model.*\.mat$','Head model file');
load(Pmod)
end
if exist('flag_te') && isfield(flag_te,'br_only')
flags_el.br_only = flag_te.br_only;
elseif exist('model') && isfield(model.param,'br_only');
flags_el.br_only = model.param.br_only;
else
if length(model.head)>1
flags_el.br_only = 0;
else
flags_el.br_only = spm_input('Only one surface modeled :','+1',...
'scalp|brain',[0,1],1);
if flags_el.br_only
flags_el.scbr_w = spm_input('Scalp-brain width :','+1','e',20);
end
end
model.br_only = flags_el.br_only;
end
if exist('Mtempl')
flags_el.Mtempl = Mtempl;
elseif exist('model') && isfield(model.param,'Mtempl');
flags_el.Mtempl = model.param.Mtempl;
else
warning('It is assumed that your original image was in template space.')
end
q_StdElec = spm_input('Electrode set :','+1','standard|user defined',[1,0],1);
if q_StdElec
% Select standard electrode set, as defined in 'spm_eeg_inv_electrset'
[set_Nel,set_name] = spm_eeg_inv_electrset;
el_set = spm_input('Which set of electrodes', ...
'+1','m',set_name);
[el_sphc,el_name] = spm_eeg_inv_electrset(el_set) ;
flags_el.q_RealLoc = 0;
else
% Enter user defined electrode set.
el_sphc = spm_input('All electrode coordinates','+1','e')
el_name = spm_input('Electrod names (cell array)','+1','e')
flags_el.q_RealLoc = spm_input('Electrode set :','+1', ...
'real location|on a sphere',[1,0],1);
flags_el.q_RealNI = spm_input('Do you have the nasion/inion location',...
'+1','y/n',[1,0],2);
if flags_el.q_RealNI
flags_el.nasion = spm_input('Nasion coordinates (in mm)','+1','e',[],3);
flags_el.inion = spm_input('Inion coordinates (in mm)','+1','e',[],3);
end
end
end
if gener==4
% Define realistic sphere
Pmod = spm_select(1,'^model.*\.mat$','Head model file');
end
% Create things as selected
%==========================
if gener == 1 || gener == 5
% Segment image, and create brain volume
[Pbin,Pinv_sn,flags_bi] = spm_eeg_inv_model('GenBin',Pvol,flag_bi);
if gener == 1
varargout{1} = Pbin;
varargout{2} = Pinv_sn;
varargout{3} = flags_bi;
end
end
if gener==1 || gener==2 || gener==5
% Tessalate predefined binarized volume
[head,cc,flags_te] = spm_eeg_inv_model('GenMesh',Pbin,flag_te); % n,br_only,q_elast_m
model.head = head;
if exist('flags_bi'), model.flags.fl_bin = flags_bi; end
model.flags.fl_tess = flags_te;
model.param = struct('br_only',0,'Nvol',1,'Mtempl',[], ...
'Pinv_sn','','sigma',[.33 .004 .33]);
if exist('Mtempl'), model.param.Mtempl = Mtempl; end
if isfield(flag_te,'br_only'), model.param.br_only = flag_te.br_only; end
if isfield(flag_te,'Nvol'), model.param.Nvol = flag_te.Nvol; end
model.fname = Pmod;
save(Pmod,'model')
if gener==2 || gener==5
varargout{1} = model ;
elseif gener==1
varargout{4} = model ;
end
end
if gener==3 || gener==5
% Project electrodes coord (spher or real) on scalp/brain surface
fname_el = ['el_sphc',num2str(size(el_sphc,2))];
save(fname_el,'el_sphc','el_name');
[electrodes,flags_el] = spm_eeg_inv_model('Elec2Scalp',model.head(end), ...
el_sphc,el_name,flags_el);
model.electrodes = electrodes ;
model.flags.fl_elec = flags_el ;
Pmod_s = [spm_str_manip(Pmod,'s'),'_e', ...
num2str(model.electrodes.nr),'.mat'] ;
save(Pmod_s,'model')
varargout{1} = model ;
end
if gener==4 || gener==5
% Define realistic sphere model
if gener==4, load(Pmod); end
if isfield(model,'br_only')
flags_Rs.br_only = model.flags.fl_tess.br_only;
else
flags_Rs.br_only = 0;
end
[spheres,a,b,c,flags_Rs] = spm_eeg_inv_Rsph(model,[],flags_Rs);
model.spheres = spheres;
model.flags.fl_RealS = flags_Rs;
Pmod_Rs = [spm_str_manip(Pmod,'s'),'_Rs.mat'] ;
save(Pmod_Rs,'model')
varargout{1} = model ;
end
%________________________________________________________________________
case 'genbin'
%------------------------------------------------------------------------
% FORMAT [Pbin,Pinv_sn,flags] = spm_eeg_inv_model('GenBin',Pvol,flag_bi);
%
% Generate the binarised image of the brain (and scalp if the image allows).
%
% Input :
% Pvol : filename of the image used to build the head model.
% flag_bi : useful flags
% * img_type: image type 1=T1 MRI, 2 = PET, 3 = EPI
% * img_norm: flag indicating if the image is normalised (1) or not (0)
% * ne,ng : # iteration for erosion and growing
% * thr_im : threhold applied to binarise image
% NOTE: these flags are not always necessary anymore...
% Output :
% Pbin : file name of the bin images generated, scalp and iskull
% Pinv_sn : file name of mat file containing inverse of the normalisation
% transform.
% flags : all the flags with added file names for original image, brain
% mask and spatial transformation
%------------------------------------------------------------------------
fprintf('\n\n'), fprintf('%c','='*ones(1,80)), fprintf('\n')
fprintf(['\tGenerating binarized volumes from image: Please wait.\n']);
Pvol = varargin{1} ;
def_flags = struct('img_type',1,'img_norm',0,'ne',1,'ng',2,'thr_im',[.5 .1]);
if nargin<3
flags = def_flags;
else
flags = varargin{2};
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));
end
end
end
load('defaults_eeg_mesh.mat');
% 1.Segment image, and estimate the mapping between template and image space.
jobs{1}.spatial{1}.preproc.data = Pvol;
jobs{1}.spatial{1}.preproc.output.biascor = 1;
jobs{1}.spatial{1}.preproc.output.GM = [0 0 1];
jobs{1}.spatial{1}.preproc.output.WM = [0 0 1];
jobs{1}.spatial{1}.preproc.output.CSF = [0 0 1];
jobs{1}.spatial{1}.preproc.output.cleanup = 0;
res = spm_preproc(Pvol);
[sn,isn] = spm_prep2sn(res);
[pth,nam,ext] = spm_fileparts(Pvol);
Pinv_isn = fullfile(pth,[nam '_vbm_inv_sn.mat']);
Pinv_sn = fullfile(pth,[nam '_vbm_sn.mat']);
savefields(Pinv_isn,isn);
savefields(Pinv_sn,sn);
spm_preproc_write(sn,jobs{1}.spatial{1}.preproc.output);
% write the segmented images in native space + bias corrected MRI
% 2.Adds up GM/WM/CSF to produce inner skull surface
Pin = strvcat(fullfile(pth,['c1',nam,ext]), ...
fullfile(pth,['c2',nam,ext]), ...
fullfile(pth,['c3',nam,ext]));
Pisk = fullfile(pth,[nam,'_iskull',ext]);
fl_ic = {[],[],'uint8',[]};
Pisk = spm_imcalc_ui(Pin,Pisk,'i1+i2+i3',fl_ic);
% 3.Use a little bit of erosion/growing to refine the model
% and write the *_iskull img on disk
Parg = strvcat(Pisk,Pisk);
ne = flags.ne(1); ng = flags.ng(1); thr_im = flags.thr_im(1);
[Pout] = spm_eeg_inv_model('ErodeGrow',Parg,ne,ng,thr_im);
if flags.img_type==1
% 4.Generate the outer-scalp volume, if possible
Pvolc = fullfile(pth,['m',nam,ext]);
Vsc = spm_vol(Pvolc);
Vsc.dat = spm_loaduint8(Vsc);
% [mnv,mxv] = spm_minmax(Vsc.dat)
ne = flags.ne(end); ng = flags.ng(end); thr_im = flags.thr_im(end);
Vsc.dat = spm_eeg_inv_model('ErodeGrow',Vsc.dat,ne,ng,thr_im);
% The bottom part of the image needs to be masked out, in MNI space.
% p1 = [0 85 -50]'; % point below on the nose
% p2 = [0 -55 -70]'; % point below the bottom of cerebellum (mm)
p1 = [0 110 -105]'; % point below on the nose
p2 = [0 -55 -110]'; % point below the bottom of cerebellum (mm)
c = [p2(1:2)' ((p1(2)-p2(2))^2+p1(3)^2-p2(3)^2)/(2*(-p2(3)+p1(3)))];
R2 = (p2(3)-c(3))^2;
% center and radius of sphere to chop off bottom of the head
X = (1:Vsc.dim(1))'*ones(1,Vsc.dim(2)); X =X(:)';
Y = ones(Vsc.dim(1),1)*(1:Vsc.dim(2)); Y = Y(:)';
Z = zeros(Vsc.dim(1),Vsc.dim(2)); Z = Z(:)';
Unit = ones(size(Z));
% X,Y,X coordinates in vox in original image
isn_tmp = isn; isn_tmp.Tr = []; % using the simple affine transform should be enough
for pp = 1:Vsc.dim(3)
XYZ = Vsc.mat*[X ; Y ; Z+pp ; Unit]; % coord in mm of voxels of scalp img
XYZ = spm_get_orig_coord(XYZ(1:3,:)', isn_tmp)';
lz = find(((XYZ(1,:)-c(1)).^2+(XYZ(2,:)-c(2)).^2+(XYZ(3,:)-c(3)).^2-R2)>0);
val_pp = Vsc.dat(:,:,pp);
val_pp(lz) = 0;
Vsc.dat(:,:,pp) = val_pp;
end
% Write the file
Vsc.fname = fullfile(pth,[nam,'_scalp',ext]);
Vsc.dt = [2 0];
Vsc.pinfo = [1/255 0 0]';
Vsc = spm_create_vol(Vsc);
spm_progress_bar('Init',Vsc.dim(3),'Writing Outer-scalp','planes completed');
for pp=1:Vsc.dim(3),
Vsc = spm_write_plane(Vsc,double(Vsc.dat(:,:,pp)),pp);
% No need to divide by 255 as output from Erode grow is [0 1].
spm_progress_bar('Set',pp);
end;
spm_progress_bar('Clear');
varargout{1} = strvcat(Pisk,Vsc.fname);
end
Pinv_sn = strvcat(Pinv_isn,Pinv_sn);
varargout{2} = Pinv_sn;
flags.Pinv_sn = Pinv_sn;
flags.Pimg = Pvol;
flags.Pisk = Pisk
varargout{3} = flags;
%________________________________________________________________________
case 'vx2mm'
%------------------------------------------------------------------------
% FORMAT [pt_mm] = spm_eeg_inv_model('vx2mm',pt_vx,M);
% Transforms point(s) 'pt_vx' voxel coordinates into mm coordinates 'pt_mm'
% according to the transformation matrix 'M'.
% 'M' is the 4x4 affine transformation matrix : from vx to mm
%------------------------------------------------------------------------
pt_vx = varargin{1} ;
M = varargin{2} ;
if size(pt_vx,1)==3
Npt = size(pt_vx,2);
elseif size(pt_vx,2)==3;
pt_vx = pt_vx';
Npt = size(pt_vx,2);
else
error('Wrong vectors format !')
end
pt_mm = M*[pt_vx;ones(1,Npt)];
varargout{1} = pt_mm(1:3,:);
%________________________________________________________________________
case 'mm2vx'
%------------------------------------------------------------------------
% FORMAT [pt_vx] = spm_eeg_inv_model('mm2vx',pt_mm,M);
% Transforms point(s) 'pt_mm' mm coordinates into voxel coordinates 'pt_vx'
% according to the transformation matrix 'M'.
% 'M' is the 4x4 affine transformation matrix : from vx to mm
%------------------------------------------------------------------------
pt_mm = varargin{1} ;
M = varargin{2} ;
if size(pt_mm,1)==3
Npt = size(pt_mm,2);
elseif size(pt_mm,2)==3;
pt_mm = pt_mm';
Npt = size(pt_mm,2);
else
error('Wrong vectors format !')
end
pt_vx = M\[pt_mm;ones(1,Npt)];
varargout{1} = pt_vx(1:3,:);
%________________________________________________________________________
case 'ctrbin'
%------------------------------------------------------------------------
% FORMAT [Centre,c_mm]=spm_eeg_inv_model('CtrBin',P);
% Determine the "centre of mass" (vx and mm) of a bin image.
%------------------------------------------------------------------------
if nargin<2
P = spm_select(1,'o*.img','Bin image to use');
else
P = varargin{1};
end
Vp = spm_vol(P) ;
Vp.dat = spm_loaduint8(Vp);
X = (1:Vp.dim(1))'*ones(1,Vp.dim(2)); X =X(:)';
Y = ones(Vp.dim(1),1)*(1:Vp.dim(2)); Y = Y(:)';
Z = zeros(Vp.dim(1),Vp.dim(2)); Z = Z(:)';
Unit = ones(size(Z));
c_mm = zeros(1,3); SI = 0;
for pp=1:Vp.dim(3)
I_pl = double(Vp.dat(:,:,pp)); I_pl = I_pl(:)*ones(1,3);
XYZ = Vp.mat*[X ; Y ; Z+pp ; Unit];
c_mm = c_mm + sum(XYZ(1:3,:)'.*I_pl);
SI = SI+sum(I_pl(:,1));
end
c_mm = c_mm/SI;
Centre = spm_eeg_inv_model('mm2vx',c_mm,Vp.mat)';
varargout{1} = Centre;
varargout{2} = c_mm;
%________________________________________________________________________
case 'elec2scalp'
%------------------------------------------------------------------------
% FORMAT [electrodes,flags] = spm_eeg_inv_model('Elec2Scalp',surf,el_loc,el_name,flags);
%
% Projecting the electrodes (in spherical or realistic coordinates)
% on the realistic head model.
%
% IN :
% - surf : surface on which the electrodes are projected,
% if its the brain surface, then the scalp-brain width is added
% - el_loc : provided electrode coordinates, on a standard sphere or
% real coordinates as measured estimated on the patient's head.
% - el_name : electrode names.
% - flags : various option flags and extra bits of information
% * q_RealLoc : 'el_loc' contains coordinates on a standard sphere (0),
% or as measured on the patient's head (1)
% * q_RealNI : nasion/inion coordinates are from the template (0),
% or as estimated on the patient's image
% * br_only : only the brain surface is available (1),
% or the scalp surface can be used (0)
% * nasion : coordiantes (in mm), on the template (defaults value filled
% * inion : in if left empty) or as estimated on the patient's image
% * scbr_w : scalp-brain surface width, in mm. (Default 20)
% * Mtempl : Affine transform mapping from the patient image space
% into the template space
%
% When dealing with standard electrode locations on a sphere, one uses
% the coordinates of the nasion and inion to estimate the pitch angle, then
% the electrode locations are mapped into the patient space
% When the real (approximate) electrode locations is provided, these are
% simply adjusted on the scalp surface
% If the model is 'brain only' (from a PET or EPI scan), the approximate
% brain-scalp width is required.
%
% The electrodes substructure is created at the end.
%------------------------------------------------------------------------
fprintf('\n'), fprintf('%c','='*ones(1,80)), fprintf('\n')
fprintf(['Placing electrodes on the scalp surface.\n']);
fprintf('%c','='*ones(1,80)), fprintf('\n')
surf = varargin{1};
el_loc = varargin{2};
Nel = size(el_loc,2);
if nargin<4
[set_Nel,set_name] = spm_eeg_inv_electrset;
try
[kk,el_name] = spm_eeg_inv_electrset(find(set_Nel==Nel));
catch
el_name = [];
end
else
el_name = varargin{3};
end
def_flags = struct('q_RealLoc',1,'br_only',0,'nasion',[0 84 -28],'inion',[0 -118 -26], ...
'q_RealNI',0,'scbr_w',[16],'Mtempl',eye(4));
if nargin<5
flags = def_flags;
else
flags = varargin{4};
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));
end
end
end
if ~flags.q_RealLoc
% Standard electrode set location is used here
% and they're provided on a simple sphere
% => need to use nasion and inion to orient them properly.
% Centre translation, scaling factor and pitch angle
% -> afine transformation, correcting for the pitch ONLY!
[na_mm] = flags.nasion;
[in_mm] = flags.inion;
cNI = (na_mm+in_mm)/2 ;
s = norm(cNI-na_mm) ;
theta = acos( (na_mm(2)-cNI(2))/s ) ; % pitch angle to apply
if flags.q_RealNI
Tr = spm_matrix([cNI theta 0 0 s s s]) ; % apply pitch correction
else
Tr = inv(flags.Mtempl) * spm_matrix([cNI theta 0 0 s s s]) ;
% same but takes into account the mapping with template space.
end
% Electrodes: "realistic" sphere coordinates...
el_rsc = Tr * [el_loc ; ones(1,Nel)] ;
el_rsc = el_rsc(1:3,:);
else
el_rsc = el_loc;
cNI = surf.Centre;
end
% figure, plot3(el_rsc(1,:)',el_rsc(2,:)',el_rsc(3,:)','*'), axis equal, xlabel('axe x'),ylabel('axe y')
electrodes.vert = zeros(Nel,1);
electrodes.tri = zeros(Nel,1);
pos_el_mm = zeros(3,Nel);
% projection of the el_rsc on the scalp surface.
% The "closest" point is detemined by the angle between the electrode_i
% and the scalp vertices from the centre
% Then the supporting triangle is found, such that the electrode_i falls
% within the traingle and the "exact" coord of electrode_i is obtained.
XYZmm = surf.XYZmm ;
v_sv = XYZmm-(cNI'*ones(1,size(XYZmm,2))) ;
v_sv = v_sv./( ones(3,1)*sqrt(sum(v_sv.^2)) ) ; % direction of surf vertices from cNI
for ii=1:Nel
v_el = (el_rsc(:,ii)-cNI')/norm(el_rsc(:,ii)-cNI') ;
% orient vect. of electrode_i
% orient vect. of scalp vertices
alpha = acos(v_el'*v_sv) ;
[m_a,ind_v] = min(abs(alpha)) ; % Find the vertex with closest orientation
list_t = find( (surf.tri(1,:)==ind_v) | ...
(surf.tri(2,:)==ind_v) | ...
(surf.tri(3,:)==ind_v) ) ; % Triangles linked to that vertex.
Nlist = length(list_t) ;
is_in = zeros(Nlist,1) ;
proj_el = zeros(3,Nlist) ;
for j=1:Nlist
v1 = XYZmm(:,surf.tri(1,list_t(j))) ;
v2 = XYZmm(:,surf.tri(2,list_t(j))) ;
v3 = XYZmm(:,surf.tri(3,list_t(j))) ;
v13 = v3-v1 ; v12 = v2-v1 ;
A = [v13 v12 v_el] ;
b = el_rsc(:,ii) - v1;
x = A\b ;
proj_el(:,j) = el_rsc(:,ii) - x(3)*v_el ;
% In fact, el_rsc(:,ii) = v1 + v13*x(1) + v12*x(2) + v_el*x(3)
% and proj_el(:,j) = el_rsc(:,i) - x(3)*v_el
% or proj_el(:,j) = v1 + v13*x(1) + v12*x(2)
v1_pel = v1-proj_el(:,j); no(1) = norm(v1_pel);
v2_pel = v2-proj_el(:,j); no(2) = norm(v2_pel);
v3_pel = v3-proj_el(:,j); no(3) = norm(v3_pel);
if all(no>1e-7) % This is in case one electrode falls exactly on the vertex
v1_pel = v1_pel/no(1);
v2_pel = v2_pel/no(2);
v3_pel = v3_pel/no(3);
sum_angle = real(acos(v1_pel'*v2_pel) + ...
acos(v2_pel'*v3_pel) + ...
acos(v3_pel'*v1_pel)) ;
if abs(sum_angle-2*pi)<1e-7
is_in(j)=1 ;
end
else
is_in(j)=1;
end
end
which_tri = find(is_in==1) ;
% if the projected electr. location is exactly on an edge, it is in 2 triangles
% => keep the 1st one
electrodes.vert(ii) = ind_v ;
electrodes.tri(ii) = list_t(which_tri(1)) ;
if flags.br_only
% need to add the br_sc width here
pos_el_mm(:,ii) = proj_el(:,which_tri(1))+v_el*flags.scbr_w;
else
pos_el_mm(:,ii) = proj_el(:,which_tri(1)) ;
end
end
electrodes.XYZmm = pos_el_mm;
electrodes.el_loc = el_loc;
electrodes.nr = Nel ;
if flags.br_only
electrodes.info = ['Electr loc projected on brain surface + ',num2str(flags.scbr_w),' mm'];
else
electrodes.info = 'Electrode location projected on scalp surface' ;
end
electrodes.names = el_name';
varargout{1} = electrodes;
varargout{2} = flags;
%________________________________________________________________________
case 'genmesh'
%------------------------------------------------------------------------
% FORMAT head = spm_eeg_inv_model('GenMesh',Pvol,flags);
%
% Generate the tesselated surface of the 1 to 3 head volumes
% (brain-skull-scalp) from the binarized volumes.
% Input :
% Pvol : filenames of 3 (or 1-2) head volumes 'brain', 'skull' & 'scalp'.
% flags : various flags
% * n : (1x3) provides the number of vertices on each surface
% Npt = n(i)^2*5/4+2
% * br_only : onlyt use the binarised brain volume (1) or scalp (0, default)
% * q_elastm: Correct mesh using an elastic model (1, default), or not (0).
% * q_meased: Measure edges of mesh (1), or not (0, default)
% * q_4thpt : Determine 4th point central of each traingle (1), or not (0, default)
% Output :
% head : head structures with 1 to 3 tesselated surfaces
%------------------------------------------------------------------------
fprintf('\n\n'), fprintf('%c','='*ones(1,80)), fprintf('\n')
fprintf(['\tGenerate surface meshes from binarized volumes\n']);
Pvol = varargin{1};
def_flags = struct('Nvol',1,'n',[32 32 32],'br_only',0, ...
'q_elast_m',1,'q_meased',0,'q_4thpt',0);
if nargin<3
flags = def_flags;
else
flags = varargin{2};
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));
end
end
end
[Centre_vx,Centre_mm]=spm_eeg_inv_model('CtrBin',Pvol(1,:));
Nbin = size(Pvol,1);
if length(flags.n)<Nbin
n = flags.n(1)*ones(1,Nbin);
else
n = flags.n;
end
mesh_labels = strvcat('Tess. outer scalp','Tess. outer skull','Tess. inner skull');
if flags.br_only
head = spm_eeg_inv_model('TesBin',n(1),Centre_mm,Pvol,mesh_labels(3,:));
elseif Nbin==2 % Brain & scalp only, no skull.
head(1) = spm_eeg_inv_model('TesBin',n(1),Centre_mm,Pvol(1,:),mesh_labels(3,:));
head(2) = spm_eeg_inv_model('TesBin',n(2),Centre_mm,Pvol(2,:),mesh_labels(1,:));
else
for ii=Nbin:-1:1
head(ii) = spm_eeg_inv_model('TesBin',n(ii),Centre_mm,Pvol(ii,:),mesh_labels(ii,:));
end
end
if flags.q_elast_m
fprintf(['\t\tCorrect position of vertices\n']);
for ii=Nbin:-1:1
head(ii) = spm_eeg_inv_model('ElastM',head(ii),Pvol(ii,:));
end
end
if flags.q_meased
fprintf(['\t\tMeasure the edges length\n']);
head(1).edges = struct('ed',[],'nr',[]);
for ii=Nbin:-1:1
head(ii) = spm_eeg_inv_model('MeasEd',head(ii));
end
end
if flags.q_4thpt
fprintf(['\t\tDetermine triangle''s "4th point"\n']);
head(1).pt4 = [];
for ii=Nbin:-1:1
head(ii) = spm_eeg_inv_model('Tr4thPt',head(ii),Pvol(ii,:));
end
end
varargout{1} = head;
varargout{2} = Centre_mm;
varargout{3} = flags;
fprintf('%c','='*ones(1,80)), fprintf('\n')
%________________________________________________________________________
case 'tesbin'
%------------------------------------------------------------------------
% FORMAT ts = spm_eeg_inv_model('TesBin',n,ctr_vol,P,info);
%
% Generate a mesh covering a binarized volume
% 1. Generate a simple spherical mesh
% 2. The spherical mesh is projected radially on the bin volume
% Afterwards, "elastic" mesh correction can thus be useful to correct
% some overlong edges.
%
% Input :
% n: number of vertices on each surface Npt = n^2*5/4+2
% ctr_vol:centre of bin volume for the radial projection (mm)
% P: filename of bin volume
% info: information string
%------------------------------------------------------------------------
if nargin==1
n = 32;
P = spm_select(1,'outer*.img','Bin image to tessalate');
[ctr_vol_vx,ctr_vol] = spm_eeg_inv_model('CtrBin',P) ;
info = 'realistic model' ;
elseif nargin==2
n = varargin{1};
P = spm_select(1,'outer*.img','Bin image to tessalate');
[ctr_vol_vx,ctr_vol] = spm_eeg_inv_model('CtrBin',P) ;
info = 'realistic model' ;
elseif nargin==3
n = varargin{1};
ctr_vol = varargin{2};
P = spm_select(1,'outer.img','Bin image to tessalate');
info = 'realistic model' ;
elseif nargin==4
n = varargin{1};
ctr_vol = varargin{2};
P = varargin{3};
info = 'realistic model' ;
elseif nargin==5
n = varargin{1};
ctr_vol = varargin{2};
P = varargin{3};
info = varargin{4} ;
elseif nargin>5
error('Wrong input arguments for ''TesBin''.') ;
end
% Load volume information
%------------------------
Vv = spm_vol(P);
VOX = sqrt(sum(Vv.mat(1:3,1:3).^2));
% A few defintions
%-----------------
ho = 1 ; % Trilinear interpolation shoud be enough
n_div = 1000; % # of sample in the radial direction
trsh_vol = .9; % Thershold for surface detection
rad = round(4/3*max(Vv.dim(1:3).*VOX/2)); % Radius (mm) of original sphere
dr = rad/n_div; % size of sampling step (mm)
d_li = 0:dr:rad; % Sampling location on radius (mm)
nd_li = length(d_li); unit = ones(1,nd_li);
% Create a tessalated sphere
%---------------------------
tsph = spm_eeg_inv_model('TesSph',n,rad); % tesselated sphere of radius rad,
vert = [tsph.vert ; ones(1,tsph.nr(1))] ; % centered around [0 0 0]
vert = spm_matrix([ctr_vol 0 pi/2 0])*vert ;
vert = vert(1:3,:) ;
% Rotate the sphere by 90deg around y axis and centre sphere around the "centre" of the brain,
% All this in mm. Leave them as a 3xNvert matrix.
srf_vert = zeros(3,tsph.nr(1)) ; % vertices at the surface of brain, in vx !
spm_progress_bar('Init',tsph.nr(1), ['Generate ',info ],'Vertices projected');
for i = 1:tsph.nr(1)
or = ctr_vol'-vert(:,i) ; or = or/norm(or) ; % direction from the point toward the centre
line = vert(:,i)*unit + or*d_li;
line_vx = spm_eeg_inv_model('mm2vx',line,Vv.mat);
val_line = spm_sample_vol(Vv,line_vx(1,:),line_vx(2,:),line_vx(3,:),ho) ;
srf_vert(:,i) = line_vx(:,min(find(val_line>trsh_vol))) ;
% first point to intercept the surface
spm_progress_bar('Set',i);
end
spm_progress_bar('Clear');
srf_vert_mm = spm_eeg_inv_model('vx2mm',srf_vert,Vv.mat);
surf.XYZmm = srf_vert_mm(1:3,:);
surf.tri = tsph.tri;
surf.nr = tsph.nr;
surf.M = Vv.mat;
surf.info.str = info;
surf.info.bin_fn = P;
surf.Centre = ctr_vol;
varargout{1} = surf;
%________________________________________________________________________
case 'elastm'
%------------------------------------------------------------------------
% FORMAT ts = spm_eeg_inv_model('ElastM',ts);
%
% Modify the the mesh in order to reduce overlong edges.
% The procedure uses an elastic model :
% At each vertex, the neighbouring triangles and vertices connected directly
% are considered.
% Each edge is considered elastic and can be lengthened or shortened,
% depending on their legnth.
% Refs: G.Taubin, A signal processing approach to fair surface design, 1995
% This is a non-shrinking smoothing algo.
%
% Input :
% ts: tesselated surface
% Output :
% ts: tesselated surface with corrected mesh
%------------------------------------------------------------------------
ts = varargin{1};
M_con = sparse([ts.tri(1,:)';ts.tri(1,:)';ts.tri(2,:)';ts.tri(3,:)';ts.tri(2,:)';ts.tri(3,:)'], ...
[ts.tri(2,:)';ts.tri(3,:)';ts.tri(1,:)';ts.tri(1,:)';ts.tri(3,:)';ts.tri(2,:)'], ...
ones(ts.nr(2)*6,1),ts.nr(1),ts.nr(1));
% Connection vertex-to-vertex
kpb = .1; % Cutt-off frequency
lam = .5; mu = lam/(lam*kpb-1); % Parameters for elasticity.
N = 25; % Number of smoothing steps, the larger, the smoother
XYZmm = ts.XYZmm;
for j=1:N
XYZmm_o = zeros(3,ts.nr(1)) ;
XYZmm_o2 = zeros(3,ts.nr(1)) ;
for i=1:ts.nr(1)
ln = find(M_con(:,i));
d_i = sqrt(sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).^2));
w_i = d_i/sum(d_i);
XYZmm_o(:,i) = XYZmm(:,i) + ...
lam * sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).*(ones(3,1)*w_i),2);
end
for i=1:ts.nr(1)
ln = find(M_con(:,i));
d_i = sqrt(sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).^2));
w_i = d_i/sum(d_i);
XYZmm_o2(:,i) = XYZmm_o(:,i) + ...
mu * sum((XYZmm_o(:,ln)-XYZmm_o(:,i)*ones(1,length(ln))).*(ones(3,1)*w_i),2);
end
XYZmm = XYZmm_o2;
end
varargout{1} = ts;
varargout{1}.XYZmm = XYZmm;
%________________________________________________________________________
case 'meased'
%------------------------------------------------------------------------
% FORMAT ts = spm_eeg_inv_model('MeasEd',ts);
%
% This measures the edges of the mesh.
% Input : ts
% Output : ts with measured edges
%
% Format of the '.edges.' sub-structure :
% ts.edges.ed :
% ed(:,1) = length,
% ed(:,[2 3]) = indexes of 2 points,
% ed(:,[4 5]) = indexes of 2 triangles.
% ts.edges.nr :
% nr(1) : number of edges,
% nr([2 3]) : mean and std of edges length.
%------------------------------------------------------------------------
ts = varargin{1}; XYZmm = ts.XYZmm;
Ned = 3*ts.nr(2)/2; edges = zeros(Ned,5); i_ed = 1 ;
for i=1:ts.nr(2) % Go through all the triangles
e1 = ts.tri(1:2,i); % 3 edges of the ith triangle (counter-clock wise)
e2 = ts.tri(2:3,i);
e3 = ts.tri([3 1],i);
p1 = find((edges(:,2)==e1(2)) && (edges(:,3)==e1(1))); % check if edge was already seen.
p2 = find((edges(:,2)==e2(2)) && (edges(:,3)==e2(1)));
p3 = find((edges(:,2)==e3(2)) && (edges(:,3)==e3(1)));
if isempty(p1) % new edge
edges(i_ed,:) = [norm(XYZmm(:,e1(1))-XYZmm(:,e1(2))) e1' i 0] ;
i_ed = i_ed+1;
else % 2nd triangle for this edge
edges(p1,5) = i;
end
if isempty(p2)
edges(i_ed,:) = [norm(XYZmm(:,e2(1))-XYZmm(:,e2(2))) e2' i 0] ;
i_ed = i_ed+1 ;
else
edges(p2,5) = i;
end
if isempty(p3)
edges(i_ed,:) = [norm(XYZmm(:,e3(1))-XYZmm(:,e3(2))) e3' i 0] ;
i_ed = i_ed+1 ;
else
edges(p3,5) = i;
end
end
ts.edges.ed = edges; ts.edges.nr = [Ned mean(edges(:,1)) std(edges(:,1))];
varargout{1} = ts;
%________________________________________________________________________
case 'tr4thpt'
%------------------------------------------------------------------------
% FORMAT ts = spm_eeg_inv_model('Tr4thPt',ts);
%
% Finds the 4th' point of each triangle:
% a flat triangle is only an approximation of the real underlying volume surface,
% a 4th point taken at the centre of the triangle is found by approximating
% the neighbouring triangles in a sphere, to provide an idea of the local curvature.
% This is used in the BEM solution of the forward problem, to sort out
% the problem of the auto-solid angle.
%
% Input :
% ts: tesselated surface
% Output :
% ts: tesselated surface with 4th point at each triangle
%------------------------------------------------------------------------
if nargin==1
error('Wrong input. You should pass a tess. surface')
end
ts = varargin{1};
T_con = sparse([ts.edges.ed(:,4),ts.edges.ed(:,5)],[ts.edges.ed(:,5),ts.edges.ed(:,4)], ...
ones(ts.edges.nr(1)*2,1),ts.nr(2),ts.nr(2),ts.edges.nr(1)*2);
% Connection Triangle-to-triangle
XYZmm = ts.XYZmm;
ts.pt4.XYZmm = zeros(3,ts.nr(2)) ;
for i=1:ts.nr(2)
l_tr = find(T_con(:,i));
l_vt = ts.tri(:,l_tr); l_vt = sort(l_vt(:));
l_vt = [l_vt(find(diff(l_vt)));l_vt(end)]; % Remov vertices listed twice.
vi = XYZmm(:,l_vt); A = [2*vi' -ones(6,1)]; b = sum(vi.^2)';
x = A\b;
vc = x(1:3);
R = sqrt(norm(vc)^2-x(4));
vct = sum(XYZmm(:,ts.tri(:,i)),2)/3; or = vct-vc; or = or/norm(or);
ts.pt4.XYZmm(:,i) = vc+R*or;
end
varargout{1} = ts;
%________________________________________________________________________
case 'tessph'
%------------------------------------------------------------------------
% FORMAT tsph = spm_eeg_inv_model('TesSph',n,r);
%
% Generate a structure 'tsph' containing a tesselated sphere.
% Input :
% n : number of 'latitude' divisions on the sphere. It MUST be even!
% r : radius of the sphere
% Output :
% tsph .vert : vertices coordinates (3 x Nvert)
% .tri : triangle patches (3 x Ntri)
% .info : info string
% 8 -> 82 points -> 160 triangles
% 10 -> 127 points -> 250 triangles
% 12 -> 182 points -> 360 triangles
% 14 -> 247 points -> 490 triangles
% 16 -> 322 points -> 640 triangles
% 18 -> 407 points -> 810 triangles
% 20 -> 502 points -> 1000 triangles
% 22 -> 607 points -> 1210 triangles
% 24 -> 722 points -> 1440 triangles
% 26 -> 847 points -> 1690 triangles
% 28 -> 982 points -> 1960 triangles
% 30 -> 1127 points -> 2250 triangles
% 32 -> 1282 points -> 2560 triangles
% 34 -> 1447 points -> 2890 triangles
% 36 -> 1622 points -> 3240 triangles
% 40 -> 2002 points -> 4000 triangles
% 42 -> 2207 points -> 4410 triangles
% 44 -> 2422 points -> 4840 triangles
% 46 -> 2647 points -> 5290 triangles
% 48 -> 2882 points -> 5760 triangles
% 54 -> 3647 points -> 7290 triangles
% 56 -> 3922 points -> 7840 triangles
% 58 -> 4207 points -> 8410 triangles
% 60 -> 4502 points -> 9000 triangles
% 62 -> 4807 points -> 9610 triangles
% 64 -> 5122 points -> 10240 triangles.
%------------------------------------------------------------------------
if nargin==1
n = 20 ;
r = 1 ;
disp(['default values : n=',num2str(n),' , r=',num2str(r)]) ;
elseif nargin==2
n = varargin{1}
r = 1 ;
disp(['default value : r=',num2str(r)]) ;
elseif nargin==3
n = varargin{1};
r = varargin{2};
else
error('Wrong input format 2')
end
[X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r) ;
[ind_tr] = tri(npt_tr,npt_qr,npt_sph) ;
tsph.vert = [X_sp ; Y_sp ; Z_sp] ;
tsph.tri = ind_tr ;
tsph.nr = [length(X_sp) size(ind_tr,2)] ;
tsph.info = ['Tes sph : n=',num2str(n),', r=',num2str(r)] ;
varargout{1} = tsph;
%__________________________________________________________________________
case 'erodegrow'
%------------------------------------------------------------------------
%
% FORMAT [Pout/val] = spm_eeg_inv_model('ErodeGrow',P/val,ne,ng,thr_im)
%
% It erodes then grows an image after thresholding it.
% Inputs : P/val,ne,ng,thr_im
% P : file name of image to erode/grow
% val : full volume of image (as loaded by spm_read_vols)
% ne : nr of steps for erosion, default 3
% ng : nr of steps for growing, default 6
% thr_im : threshold value to apply, default .8
% (compared to the maximal value of image)
% Output : Pout/val
% Pout : name of the file generated
% val : full value of eroded-grown image
%
% Notes:
% - if 2 file names are specified in P[input], the 2nd one is used as the name
% of the generated file otherwise the new filename is creted from P as
% [P,'_e',num2str(ne),'g',num2str(ng),'.img']
% - If a file name is passed the output is a filename.
% If a matrix of values is passed, the output is a matrix of values.
%------------------------------------------------------------------------
fl_rvol = 0; % Need to load (1) or not (0) the volume from a file
if nargin<2
P = spm_select(1,'image','Image to erode-grow');
nPin = size(P,1);
Vp = spm_vol(P);
fl_rvol = 1;
dim = V.dim;
cr_file = 1; % Create (1) or not (0) a file at the end of the process.
end
if length(varargin)>=1
if ischar(varargin{1})
P = varargin{1};
nPin = size(P,1);
Vp = spm_vol(P(1,:));
fl_rvol = 1;
dim = Vp.dim;
cr_file = 1;
elseif isa(varargin{1},'uint8')
val = varargin{1};
dim = size(val);
cr_file = 0;
elseif isnumeric(varargin{1})
val = uint8(varargin{1});
dim = size(val);
cr_file = 0;
else
error('Wrong data format');
end
end
if fl_rvol
val = spm_loaduint8(Vp);
end
ne = 1; ng = 1; thr_im = .1 ;
if length(varargin)==4
ne = varargin{2};
ng = varargin{3};
thr_im = varargin{4};
else
disp('Using default erode/grow parameters: ne=1, ng=1, thr=.1 !')
end
p1 = uint8(zeros(1,dim(2),dim(3)));
p2 = uint8(zeros(dim(1),1,dim(3)));
p3 = uint8(zeros(dim(1),dim(2),1));
p1_3 = uint8(zeros(1,dim(2),dim(3)-1));
p2_1 = uint8(zeros(dim(1)-1,1,dim(3)));
p3_2 = uint8(zeros(dim(1),dim(2)-1,1));
% Erosion !
% val = val>thr_im*max(max(max(abs(val)))) ;
val = uint8(val>thr_im*double(max(val(:)))) ;
% added uint8 otherwise is considered as a logical variable
% -> no math operation (addition) possible
Nbin = length(find(val(:)));
fprintf('\tOriginal number of voxels %d .\n',Nbin)
for i=1:ne
temp = val ...
+ cat(1,p1,val(1:end-1,:,:)) + cat(1,val(2:end,:,:),p1) ...
+ cat(2,p2,val(:,1:end-1,:)) + cat(2,val(:,2:end,:),p2) ...
+ cat(3,p3,val(:,:,1:end-1)) + cat(3,val(:,:,2:end),p3) ...
+ cat(1,p1,cat(2,p2_1,val(1:end-1,1:end-1,:))) ...
+ cat(1,p1,cat(2,val(1:end-1,2:end,:),p2_1)) ...
+ cat(1,cat(2,p2_1,val(2:end,1:end-1,:)),p1) ...
+ cat(1,cat(2,val(2:end,2:end,:),p2_1),p1) ...
+ cat(2,p2,cat(3,p3_2,val(:,1:end-1,1:end-1))) ...
+ cat(2,p2,cat(3,val(:,1:end-1,2:end),p3_2)) ...
+ cat(2,cat(3,p3_2,val(:,1:end-1,1:end-1)),p2) ...
+ cat(2,cat(3,val(:,1:end-1,2:end),p3_2),p2) ...
+ cat(3,p3,cat(1,p1_3,val(1:end-1,:,1:end-1))) ...
+ cat(3,p3,cat(1,val(2:end,:,1:end-1),p1_3)) ...
+ cat(3,cat(1,p1_3,val(1:end-1,:,1:end-1)),p3) ...
+ cat(3,cat(1,val(2:end,:,1:end-1),p1_3),p3) ;
val = uint8(temp>17) ;
% val = temp>6 ;
Nbin = length(find(val(:)));
fprintf('\tErosion step %d , %d voxels left.\n',i,Nbin)
end
%Ve = Vp;
%Ve.fname = [spm_str_manip(Vp.fname,'r'),'_e',num2str(ne),'.img']
%Vout_e = spm_write_vol(Ve,val)
% Growing bit !
for i=1:ng
temp = val ...
+ cat(1,p1,val(1:end-1,:,:)) + cat(1,val(2:end,:,:),p1) ...
+ cat(2,p2,val(:,1:end-1,:)) + cat(2,val(:,2:end,:),p2) ...
+ cat(3,p3,val(:,:,1:end-1)) + cat(3,val(:,:,2:end),p3) ...
+ cat(1,p1,cat(2,p2_1,val(1:end-1,1:end-1,:))) ...
+ cat(1,p1,cat(2,val(1:end-1,2:end,:),p2_1)) ...
+ cat(1,cat(2,p2_1,val(2:end,1:end-1,:)),p1) ...
+ cat(1,cat(2,val(2:end,2:end,:),p2_1),p1) ...
+ cat(2,p2,cat(3,p3_2,val(:,1:end-1,1:end-1))) ...
+ cat(2,p2,cat(3,val(:,1:end-1,2:end),p3_2)) ...
+ cat(2,cat(3,p3_2,val(:,1:end-1,1:end-1)),p2) ...
+ cat(2,cat(3,val(:,1:end-1,2:end),p3_2),p2) ...
+ cat(3,p3,cat(1,p1_3,val(1:end-1,:,1:end-1))) ...
+ cat(3,p3,cat(1,val(2:end,:,1:end-1),p1_3)) ...
+ cat(3,cat(1,p1_3,val(1:end-1,:,1:end-1)),p3) ...
+ cat(3,cat(1,val(2:end,:,1:end-1),p1_3),p3) ;
val = uint8(temp>1) ;
Nbin = length(find(val(:)));
fprintf('\tGrowing step %d , %d voxels left.\n',i,Nbin)
end
if cr_file
Vout = Vp;
% val = val.*uint8(255);
Vout.pinfo = [1/255 0 0]';
if nPin==1
Vout.fname = [spm_str_manip(Vp.fname,'r'),'_e',num2str(ne),'g',num2str(ng),'.img'];
else
Vout.fname = P(2,:);
end
spm_write_vol(Vout,val);
varargout{1} = Vout.fname ;
else
varargout{1} = val ;
end
%________________________________________________________________________
otherwise,
warning('Unknown action string')
end;
return;
%________________________________________________________________________
%________________________________________________________________________
%________________________________________________________________________
%________________________________________________________________________
%
% SUBFUNCTIONS
%________________________________________________________________________
%________________________________________________________________________
%________________________________________________________________________
% FORMAT [X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r)
% Generate a set of points on a sphere.
% n = the number of latitudes on the sphere, it MUST be even!
% r = radius of the sphere, 1 by default.
%------------------------------------------------------------------------
function [X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r)
d_r = pi/180; dth = 180/n*d_r ;
X_qr=[] ; Y_qr=[] ; Z_qr=[] ; X_sp=[] ; Y_sp=[] ; Z_sp=[] ;
% Coord of pts on a 5th of sphere WITHOUT the top and bottom points
for i=1:n/2 % Upper part
the = i*dth ;
cth = cos(the) ; sth = sin(the) ;
dphi = 72/i*d_r ;
for j=1:i
phi = (j-1)*dphi ;
cph = cos(phi) ; sph = sin(phi) ;
X_qr = [X_qr sth*cph] ;
Y_qr = [Y_qr sth*sph] ;
Z_qr = [Z_qr cth] ;
end
end
for i=(n/2+1):(n-1) % Lower part
the = i*dth ;
cth = cos(the) ; sth = sin(the) ;
ii = n-i ;
dphi = 72/ii*d_r ;
for j=1:ii
phi = (j-1)*dphi ;
cph = cos(phi) ; sph = sin(phi) ;
X_qr = [X_qr sth*cph] ;
Y_qr = [Y_qr sth*sph] ;
Z_qr = [Z_qr cth] ;
end
end
% Each part is copied with a 72deg shift
dphi=-72*d_r ;
for i=0:4
phi=i*dphi ;
cph=cos(phi) ;
sph=sin(phi) ;
X_sp=[X_sp cph*X_qr+sph*Y_qr] ;
Y_sp=[Y_sp -sph*X_qr+cph*Y_qr] ;
Z_sp=[Z_sp Z_qr] ;
end
% add top and bottom points
X_sp=[0 X_sp 0]*r ;
Y_sp=[0 Y_sp 0]*r ;
Z_sp=[1 Z_sp -1]*r ;
npt_tr = [[0:n/2] [n/2-1:-1:0]]; % Nbr of points on each slice for a 5th of sph.
npt_qr = sum(npt_tr) ; % total nbr of pts per 5th of sphere
npt_sph=5/4*n^2+2 ; % or 5*npt_qr+2 ; % total nbr of pts on sph
return
%________________________________________________________________________
% FORMAT [ind_tr] = tri(npt_tr,npt_qr,npt_sph)
%------------------------------------------------------------------------
% Order the pts created by the function 'point' into triangles
% Each triangle is represented by 3 indices correponding to the XYZ_sp
%
% This works only because I know in wich order the vertices are generated
% in the 'point' function.
%------------------------------------------------------------------------
function [ind_tr] = tri(npt_tr,npt_qr,npt_sph)
n = sqrt(4/5*(npt_sph-2)) ;
% First 5th of sphere only
for i=0:(n/2-1) % upper half
if i==0 % 1st triangle at the top
ind_qr=[1 2 2+npt_qr]' ;
else % other triangles
for j=0:npt_tr(i+1)
if j==npt_tr(i+1)-1 % last but 1 pt on slice
x1=sum(npt_tr(1:i))+j+2 ;
x12=x1+npt_tr(i+1) ;
x13=x12+1 ;
x22=x13 ;
x23=sum(npt_tr(1:i))+2+npt_qr ;
ind_qr=[ind_qr [x1 x12 x13]' [x1 x22 x23]'] ;
elseif j==npt_tr(i+1) % last pt on slice
x1=sum(npt_tr(1:i))+2+npt_qr ;
x2=sum(npt_tr(1:(i+1)))+j+2 ;
x3=x1+npt_tr(i+1) ;
ind_qr=[ind_qr [x1 x2 x3]'] ;
else % other pts on slice
x1=sum(npt_tr(1:i))+j+2 ;
x12=x1+npt_tr(i+1) ;
x13=x12+1 ;
x22=x13 ;
x23=x1+1 ;
ind_qr=[ind_qr [x1 x12 x13]' [x1 x22 x23]'] ;
end
end
end
end
for i=(n/2+1):n % lower half
if i==n % last triangle at the bottom
ind_qr=[ind_qr [5*npt_qr+2 2*npt_qr+1 npt_qr+1]' ] ;
else % other triangles
for j=0:npt_tr(i+1)
if j==npt_tr(i+1)-1 % last but 1 pt on slice
x1=sum(npt_tr(1:i))+j+2 ;
x12=x1-npt_tr(i) ;
x13=x12+1 ;
x22=x13 ;
x23=sum(npt_tr(1:i))+2+npt_qr ;
ind_qr=[ind_qr [x1 x13 x12]' [x1 x23 x22]'] ;
elseif j==npt_tr(i+1) % last pt on slice
x1=sum(npt_tr(1:i))+2+npt_qr ;
x2=sum(npt_tr(1:(i-1)))+j+2 ;
x3=x1-npt_tr(i) ;
ind_qr=[ind_qr [x1 x3 x2]'] ;
else % other pts on slice
x1=sum(npt_tr(1:i))+j+2 ;
x12=x1-npt_tr(i) ;
x13=x12+1 ;
x22=x13 ;
x23=x1+1 ;
ind_qr=[ind_qr [x1 x13 x12]' [x1 x23 x22]'] ;
end
end
end
end
ntr_qr=size(ind_qr,2) ; % nbr of triangle per 5th of sphere
[S_i,S_j]=find(ind_qr==1) ;
[B_i,B_j]=find(ind_qr==npt_sph) ;
[qs_i,qs_j]=find((ind_qr>(npt_qr+1))&(ind_qr<(3*npt_qr))) ;
ind_tr=[] ;
% shift all indices to cover the sphere
for i=0:4
ind_tr = [ind_tr (ind_qr+i*npt_qr)] ;
ind_tr(S_i,S_j+i*ntr_qr) = 1 ;
ind_tr(B_i,B_j+i*ntr_qr) = npt_sph ;
end
for i=1:size(qs_i,1)
ind_tr(qs_i(i),qs_j(i)+4*ntr_qr) = ...
ind_tr(qs_i(i),(qs_j(i)+4*ntr_qr))-5*npt_qr ;
end
ntr_sph = size(ind_tr,2) ;% nbr of triangles on the sphere
% or = 5/2*n^2
return
% %________________________________________________________________________
% % FORMAT [udat] = loaduint8(V)
% %------------------------------------------------------------------------
% % Load data from file indicated by V into an array of unsigned bytes.
% %------------------------------------------------------------------------
%
% function udat = loaduint8(V)
% % Load data from file indicated by V into an array of unsigned bytes.
%
% if size(V.pinfo,2)==1 && V.pinfo(1) == 2,
% mx = 255*V.pinfo(1) + V.pinfo(2);
% mn = V.pinfo(2);
% else,
% spm_progress_bar('Init',V.dim(3),...
% ['Computing max/min of ' spm_str_manip(V.fname,'t')],...
% 'Planes complete');
% mx = -Inf; mn = Inf;
% for p=1:V.dim(3),
% img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
% mx = max([max(img(:))+paccuracy(V,p) mx]);
% mn = min([min(img(:)) mn]);
% spm_progress_bar('Set',p);
% end;
% end;
% spm_progress_bar('Init',V.dim(3),...
% ['Loading ' spm_str_manip(V.fname,'t')],...
% 'Planes loaded');
%
% udat = uint8(0);
% udat(V.dim(1),V.dim(2),V.dim(3))=0;
% rand('state',100);
% for p=1:V.dim(3),
% img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
% acc = paccuracy(V,p);
% if acc==0,
% udat(:,:,p) = uint8(round((img-mn)*(255/(mx-mn))));
% else,
% % Add random numbers before rounding to reduce aliasing artifact
% r = rand(size(img))*acc;
% udat(:,:,p) = uint8(round((img+r-mn)*(255/(mx-mn))));
% end;
% spm_progress_bar('Set',p);
% end;
% spm_progress_bar('Clear');
% return;
%
% function acc = paccuracy(V,p)
% % if ~spm_type(V.dim(4),'intt'),
% 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;
%________________________________________________________________________
% FORMAT savefields(fnam,p)
%------------------------------------------------------------------------
% save the fields of a structure 'p' in a file 'fnam'
%------------------------------------------------------------------------
function savefields(fnam,p)
if length(p)>1, error('Can''t save fields.'); end;
fn = fieldnames(p);
for i=1:length(fn),
eval([fn{i} '= p.' fn{i} ';']);
end;
if spm_matlab_version_chk('7') >= 0,
save(fnam,'-V6',fn{:});
else
save(fnam,fn{:});
end;
return;
|
github
|
spm/spm5-master
|
spm_config_smooth.m
|
.m
|
spm5-master/spm_config_smooth.m
| 3,092 |
utf_8
|
c0bb069adf47cd5270401fdb50cea707
|
function opts = spm_config_smooth
% Configuration file for smoothing jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_smooth.m 471 2006-03-08 17:46:45Z john $
%_______________________________________________________________________
data.type = 'files';
data.name = 'Images to Smooth';
data.tag = 'data';
data.filter = 'image';
data.num = Inf;
data.help = {[...
'Specify the images to smooth. ',...
'The smoothed images are written to the same subdirectories as the ',...
'original *.img and are prefixed with a ''s'' (i.e. s*.img).']};
%------------------------------------------------------------------------
fwhm.type = 'entry';
fwhm.name = 'FWHM';
fwhm.tag = 'fwhm';
fwhm.strtype = 'e';
fwhm.num = [1 3];
fwhm.val = {[8 8 8]};
fwhm.help = {[...
'Specify the full-width at half maximum (FWHM) of the Gaussian smoothing ',...
'kernel in mm. Three values should be entered, denoting the FWHM in the ',...
'x, y and z directions.']};
%------------------------------------------------------------------------
dtype.type = 'menu';
dtype.name = 'Data Type';
dtype.tag = 'dtype';
dtype.labels = {'SAME','UINT8 - unsigned char','INT16 - signed short','INT32 - signed int',...
'FLOAT - single prec. float','DOUBLE - double prec. float'};
dtype.values = {0,spm_type('uint8'),spm_type('int16'),spm_type('int32'),...
spm_type('float32'),spm_type('float64')};
dtype.val = {0};
dtype.help = {'Data-type of output images. SAME indicates the same datatype as the original images.'};
%------------------------------------------------------------------------
opts.type = 'branch';
opts.name = 'Smooth';
opts.tag = 'smooth';
opts.val = {data,fwhm,dtype};
opts.prog = @smooth;
opts.vfiles = @vfiles;
opts.help = {...
['This is for smoothing (or convolving) image volumes ',...
'with a Gaussian kernel of a specified width. ',...
'It is used as a preprocessing step to suppress noise and effects due to residual ',...
'differences in functional and gyral anatomy during inter-subject ',...
'averaging.']};
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function smooth(varargin)
job = varargin{1};
P = strvcat(job.data);
s = job.fwhm;
dtype = job.dtype;
n = size(P,1);
spm_progress_bar('Init',n,'Smoothing','Volumes Complete');
for i = 1:n
Q = deblank(P(i,:));
[pth,nam,xt,nm] = spm_fileparts(deblank(Q));
U = fullfile(pth,['s' nam xt nm]);
spm_smooth(Q,U,s,dtype);
spm_progress_bar('Set',i);
end
spm_progress_bar('Clear');
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles(varargin)
P = varargin{1}.data;
vf = cell(size(P));
for i=1:numel(P),
[pth,nam,ext,num] = spm_fileparts(P{i});
vf{i} = fullfile(pth,['s', nam, ext, num]);
end;
|
github
|
spm/spm5-master
|
spm_config_mkdir.m
|
.m
|
spm5-master/spm_config_mkdir.m
| 1,528 |
utf_8
|
e2e46a42fd29862a7861a58ae2973cf3
|
function opts = spm_config_mkdir
% Configuration file for making directory function
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Darren Gitelman
% $Id: spm_config_mkdir.m 472 2006-03-08 17:48:52Z john $
%_______________________________________________________________________
data.type = 'files';
data.name = 'Select a base directory';
data.tag = 'basedir';
data.filter = 'dir';
data.num = 1;
data.help = {'Select a base directory.'};
name.type = 'entry';
name.name = 'Enter a directory name';
name.tag = 'name';
name.strtype = 's';
name.num = [1 1];
name.help = {'Enter a directory name'};
opts.type = 'branch';
opts.name = 'Make Directory';
opts.tag = 'md';
opts.val = {data,name};
opts.prog = @my_mkdir;
opts.vfiles = @vdirs_mydirs;
opts.help = {[...
'This facilty allows programming a directory change. Directories are ',...
'selected in the right listbox.']};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function my_mkdir(varargin)
job = varargin{1};
if ~isempty(job.basedir) && ~isempty(job.name)
mkdir(job.basedir{:},job.name);
end
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vd = vdirs_mydirs(varargin)
job = varargin{1};
vd = {fullfile(job.basedir{:},[job.name,filesep])};
return;
|
github
|
spm/spm5-master
|
spm_minmax.m
|
.m
|
spm5-master/spm_minmax.m
| 3,722 |
utf_8
|
5b32b4c6d23de573920ccc06d8d2baa0
|
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) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_minmax.m 1746 2008-05-28 17:43:42Z guillaume $
d = [size(g) 1];
mxv = double(max(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;
% 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
|
spm/spm5-master
|
spm_create_vol.m
|
.m
|
spm5-master/spm_create_vol.m
| 4,972 |
utf_8
|
ce1923f47d65ec0e52ab0e5f6e15df7f
|
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) 2005 Wellcome Department of Imaging Neuroscience
% 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
|
spm/spm5-master
|
spm_config_fmri_spec.m
|
.m
|
spm5-master/spm_config_fmri_spec.m
| 45,713 |
utf_8
|
fff311b75229cb7ae87d6691191ed016
|
function conf = spm_config_fmri_spec
% Configuration file for specification of fMRI model
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Darren Gitelman and Will Penny
% $Id: spm_config_fmri_spec.m 1016 2007-12-03 12:51:33Z volkmar $
% Define inline types.
%-----------------------------------------------------------------------
entry = inline(['struct(''type'',''entry'',''name'',name,'...
'''tag'',tag,''strtype'',strtype,''num'',num,''help'',hlp)'],...
'name','tag','strtype','num','hlp');
files = inline(['struct(''type'',''files'',''name'',name,'...
'''tag'',tag,''filter'',fltr,''num'',num,''help'',hlp)'],...
'name','tag','fltr','num','hlp');
mnu = inline(['struct(''type'',''menu'',''name'',name,'...
'''tag'',tag,''labels'',{labels},''values'',{values},''help'',hlp)'],...
'name','tag','labels','values','hlp');
branch = inline(['struct(''type'',''branch'',''name'',name,'...
'''tag'',tag,''val'',{val},''help'',hlp)'],...
'name','tag','val','hlp');
repeat = inline(['struct(''type'',''repeat'',''name'',name,'...
'''tag'',tag,''values'',{values},''help'',hlp)'],...
'name','tag','values','hlp');
choice = inline(['struct(''type'',''choice'',''name'',name,'...
'''tag'',tag,''values'',{values},''help'',hlp)'],...
'name','tag','values','hlp');
%-----------------------------------------------------------------------
sp_text = [' ',...
' '];
%-----------------------------------------------------------------------
onset = entry('Onsets','onset','e',[Inf 1],'Vector of onsets');
p1 = ['Specify a vector of onset times for this condition type. '];
onset.help = {p1};
%-------------------------------------------------------------------------
duration = entry('Durations','duration','e',[Inf 1],'Duration/s');
duration.help = [...
'Specify the event durations. Epoch and event-related ',...
'responses are modeled in exactly the same way but by specifying their ',...
'different durations. Events are ',...
'specified with a duration of 0. If you enter a single number for the ',...
'durations it will be assumed that all trials conform to this duration. ',...
'If you have multiple different durations, then the number must match the ',...
'number of onset times.'];
%-------------------------------------------------------------------------
time_mod = mnu('Time Modulation','tmod',...
{'No Time Modulation','1st order Time Modulation',...
'2nd order Time Modulation','3rd order Time Modulation',...
'4th order Time Modulation','5th order Time Modulation',...
'6th order Time Modulation'},...
{0,1,2,3,4,5,6},'');
time_mod.val = {0};
p1 = [...
'This option allows for the characterisation of linear or nonlinear ',...
'time effects. ',...
'For example, 1st order modulation ',...
'would model the stick functions and a linear change of the stick function ',...
'heights over time. Higher order modulation will introduce further columns that ',...
'contain the stick functions scaled by time squared, time cubed etc.'];
p2 = [...
'Interactions or response modulations can enter at two levels. Firstly ',...
'the stick function itself can be modulated by some parametric variate ',...
'(this can be time or some trial-specific variate like reaction time) ',...
'modeling the interaction between the trial and the variate or, secondly ',...
'interactions among the trials themselves can be modeled using a Volterra ',...
'series formulation that accommodates interactions over time (and therefore ',...
'within and between trial types).'];
time_mod.help = {p1,'',p2};
%-------------------------------------------------------------------------
%ply = mnu('Polynomial Expansion','poly',...
% {'None','1st order','2nd order','3rd order','4th order','5th order','6th order'},...
% {0,1,2,3,4,5,6},'Polynomial Order');
%ply.val = {0};
%-------------------------------------------------------------------------
name = entry('Name','name','s', [1 Inf],'Name of parameter');
name.val = {'Param'};
name.help = {'Enter a name for this parameter.'};
%-------------------------------------------------------------------------
param = entry('Values','param','e',[Inf 1],'Parameter vector');
param.help = {'Enter a vector of values, one for each occurence of the event.'};
%-------------------------------------------------------------------------
ply = mnu('Polynomial Expansion','poly',...
{'1st order','2nd order','3rd order','4th order','5th order','6th order'},...
{1,2,3,4,5,6},'Polynomial Order');
ply.val = {1};
ply.help = {[...
'For example, 1st order modulation ',...
'would model the stick functions and a linear change of the stick function ',...
'heights over different values of the parameter. Higher order modulation will ',...
'introduce further columns that ',...
'contain the stick functions scaled by parameter squared, cubed etc.']};
%-------------------------------------------------------------------------
pother = branch('Parameter','pmod',{name,param,ply},'Custom parameter');
p1 = [...
'Model interractions with user specified parameters. ',...
'This allows nonlinear effects relating to some other measure ',...
'to be modelled in the design matrix.'];
p2 = [...
'Interactions or response modulations can enter at two levels. Firstly ',...
'the stick function itself can be modulated by some parametric variate ',...
'(this can be time or some trial-specific variate like reaction time) ',...
'modeling the interaction between the trial and the variate or, secondly ',...
'interactions among the trials themselves can be modeled using a Volterra ',...
'series formulation that accommodates interactions over time (and therefore ',...
'within and between trial types).'];
pother.help = {p1,'',p2};
%-------------------------------------------------------------------------
pmod = repeat('Parametric Modulations','pmod',{pother},'');
pmod.help = {[...
'The stick function itself can be modulated by some parametric variate ',...
'(this can be time or some trial-specific variate like reaction time) ',...
'modeling the interaction between the trial and the variate. ',...
'The events can be modulated by zero or more parameters.']};
%-------------------------------------------------------------------------
name = entry('Name','name','s',[1 Inf],'Condition Name');
name.val = {'Trial'};
%-------------------------------------------------------------------------
cond = branch('Condition','cond',{name,onset,duration,time_mod,pmod},...
'Condition');
cond.check = @cond_check;
cond.help = {[...
'An array of input functions is contructed, ',...
'specifying occurrence events or epochs (or both). ',...
'These are convolved with a basis set at a later stage to give ',...
'regressors that enter into the design matrix. Interactions of evoked ',...
'responses with some parameter (time or a specified variate) enter at ',...
'this stage as additional columns in the design matrix with each trial multiplied ',...
'by the [expansion of the] trial-specific parameter. ',...
'The 0th order expansion is simply the main effect in the first column.']};
%-------------------------------------------------------------------------
conditions = repeat('Conditions','condrpt',{cond},'Conditions');
conditions.help = {[...
'You are allowed to combine both event- and epoch-related ',...
'responses in the same model and/or regressor. Any number ',...
'of condition (event or epoch) types can be specified. Epoch and event-related ',...
'responses are modeled in exactly the same way by specifying their ',...
'onsets [in terms of onset times] and their durations. Events are ',...
'specified with a duration of 0. If you enter a single number for the ',...
'durations it will be assumed that all trials conform to this duration.',...
'For factorial designs, one can later associate these experimental conditions ',...
'with the appropriate levels of experimental factors. ';]};
%-------------------------------------------------------------------------
multi = files('Multiple conditions','multi','\.mat$',[0 1],'');
p1=['Select the *.mat file containing details of your multiple experimental conditions. '];
p2=['If you have multiple conditions then entering the details a condition ',...
'at a time is very inefficient. This option can be used to load all the ',...
'required information in one go. You will first need to create a *.mat file ',...
'containing the relevant information. '];
p3=['This *.mat file must include the following cell arrays (each 1 x n): ',...
'names, onsets and durations. eg. names=cell(1,5), onsets=cell(1,5), ',...
'durations=cell(1,5), then names{2}=''SSent-DSpeak'', onsets{2}=[3 5 19 222], ',...
'durations{2}=[0 0 0 0], contain the required details of the second condition. ',...
'These cell arrays may be made available by your stimulus delivery program, ',...
'eg. COGENT. The duration vectors can contain a single entry if the durations ',...
'are identical for all events.'];
p4=['Time and Parametric effects can also be included. For time modulation ',...
'include a cell array (1 x n) called tmod. It should have a have a single ',...
'number in each cell. Unused cells may contain either a 0 or be left empty. The number ',...
'specifies the order of time modulation from 0 = No Time Modulation to ',...
'6 = 6th Order Time Modulation. eg. tmod{3} = 1, modulates the 3rd condition ',...
'by a linear time effect.'];
p5=['For parametric modulation include a structure array, which is up to 1 x n in size, ',...
'called pmod. n must be less than or equal to the number of cells in the ',...
'names/onsets/durations cell arrays. The structure array pmod must have the fields: ',...
'name, param and poly. Each of these fields is in turn a cell array to allow the ',...
'inclusion of one or more parametric effects per column of the design. The field ',...
'name must be a cell array containing strings. The field param is a cell array ',...
'containing a vector of parameters. Remember each parameter must be the same length as its ',...
'corresponding onsets vector. The field poly is a cell array (for consistency) ',...
'with each cell containing a single number specifying the order of the polynomial ',...
'expansion from 1 to 6.'];
p6=['Note that each condition is assigned its corresponding ',...
'entry in the structure array (condition 1 parametric modulators are in pmod(1), ',...
'condition 2 parametric modulators are in pmod(2), etc. Within a condition ',...
'multiple parametric modulators are accessed via each fields cell arrays. ',...
'So for condition 1, parametric modulator 1 would be defined in ',...
'pmod(1).name{1}, pmod(1).param{1}, and pmod(1).poly{1}. A second parametric ',...
'modulator for condition 1 would be defined as pmod(1).name{2}, pmod(1).param{2} ',...
'and pmod(1).poly{2}. If there was also a parametric modulator for condition 2, ',...
'then remember the first modulator for that condition is in cell array 1: ',...
'pmod(2).name{1}, pmod(2).param{1}, and pmod(2).poly{1}. If some, but not ',...
'all conditions are parametrically modulated, then the non-modulated indices ',...
'in the pmod structure can be left blank. For example, if conditions 1 and 3 but ',...
'not condition 2 are modulated, then specify pmod(1) and pmod(3). ',...
'Similarly, if conditions 1 and 2 are modulated but there are 3 conditions ',...
'overall, it is only necessary for pmod to be a 1 x 2 structure array.'];
p7=['EXAMPLE:'];
p8=['Make an empty pmod structure: '];
p9=[' pmod = struct(''name'',{''''},''param'',{},''poly'',{});'];
p10=['Specify one parametric regressor for the first condition: '];
p11=[' pmod(1).name{1} = ''regressor1'';'];
p12=[' pmod(1).param{1} = [1 2 4 5 6];'];
p13=[' pmod(1).poly{1} = 1;'];
p14=['Specify 2 parametric regressors for the second condition: '];
p15=[' pmod(2).name{1} = ''regressor2-1'';'];
p16=[' pmod(2).param{1} = [1 3 5 7]; '];
p17=[' pmod(2).poly{1} = 1;'];
p18=[' pmod(2).name{2} = ''regressor2-2'';'];
p19=[' pmod(2).param{2} = [2 4 6 8 10];'];
p20=[' pmod(2).poly{2} = 1;'];
p21=['The parametric modulator should be mean corrected if appropriate. Unused ',...
'structure entries should have all fields left empty.'];
multi.help = {p1,sp_text,p2,sp_text,p3,sp_text,p4,sp_text,p5,sp_text,p6,...
sp_text,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,sp_text,p21};
multi.val={''};
%-------------------------------------------------------------------------
name = entry('Name','name','s',[1 Inf],'');
name.val = {'Regressor'};
p1=['Enter name of regressor eg. First movement parameter'];
name.help={p1};
%-------------------------------------------------------------------------
val = entry('Value','val','e',[Inf 1],'');
val.help={['Enter the vector of regressor values']};
%-------------------------------------------------------------------------
regress = branch('Regressor','regress',{name,val},'regressor');
regressors = repeat('Regressors','regress',{regress},'Regressors');
regressors.help = {[...
'Regressors are additional columns included in the design matrix, ',...
'which may model effects that would not be convolved with the ',...
'haemodynamic response. One such example would be the estimated movement ',...
'parameters, which may confound the data.']};
%-------------------------------------------------------------------------
multi_reg = files('Multiple regressors','multi_reg','.*',[0 1],'');
p1=['Select the *.mat/*.txt file containing details of your multiple regressors. '];
p2=['If you have multiple regressors eg. realignment parameters, then entering the ',...
'details a regressor at a time is very inefficient. ',...
'This option can be used to load all the ',...
'required information in one go. '];
p3=['You will first need to create a *.mat file ',...
'containing a matrix R or a *.txt file containing the regressors. ',...
'Each column of R will contain a different regressor. ',...
'When SPM creates the design matrix the regressors will be named R1, R2, R3, ..etc.'];
multi_reg.help = {p1,sp_text,p2,sp_text,p3};
multi_reg.val={''};
%-------------------------------------------------------------------------
scans = files('Scans','scans','image',[1 Inf],'Select scans');
scans.help = {[...
'Select the fMRI scans for this session. They must all have the same ',...
'image dimensions, orientation, voxel size etc.']};
%-------------------------------------------------------------------------
hpf = entry('High-pass filter','hpf','e',[1 1],'');
hpf.val = {128};
hpf.help = {[...
'The default high-pass filter cutoff is 128 seconds.',...
'Slow signal drifts with a period longer than this will be removed. ',...
'Use ''explore design'' ',...
'to ensure this cut-off is not removing too much experimental variance. ',...
'High-pass filtering is implemented using a residual forming matrix (i.e. ',...
'it is not a convolution) and is simply to a way to remove confounds ',...
'without estimating their parameters explicitly. The constant term ',...
'is also incorporated into this filter matrix.']};
%-------------------------------------------------------------------------
sess = branch('Subject/Session','sess',{scans,conditions,multi,regressors,multi_reg,hpf},'Session');
sess.check = @sess_check;
p1 = [...
'The design matrix for fMRI data consists of one or more separable, ',...
'session-specific partitions. These partitions are usually either one per ',...
'subject, or one per fMRI scanning session for that subject.'];
sess.help = {p1};
%-------------------------------------------------------------------------
block = repeat('Data & Design','blocks',{sess},'');
block.num = [1 Inf];
p1 = [...
'The design matrix defines the experimental design and the nature of ',...
'hypothesis testing to be implemented. The design matrix has one row ',...
'for each scan and one column for each effect or explanatory variable. ',...
'(e.g. regressor or stimulus function). '];
p2 = [...
'This allows you to build design matrices with separable ',...
'session-specific partitions. Each partition may be the same (in which ',...
'case it is only necessary to specify it once) or different. Responses ',...
'can be either event- or epoch related, where the latter model involves prolonged ',...
'and possibly time-varying responses to state-related changes in ',...
'experimental conditions. Event-related response are modelled in terms ',...
'of responses to instantaneous events. Mathematically they are both ',...
'modelled by convolving a series of delta (stick) or box-car functions, ',...
'encoding the input or stimulus function. with a set of hemodynamic ',...
'basis functions.'];
block.help = {p1,'',p2};
% Specification of factorial designs
fname.type = 'entry';
fname.name = 'Name';
fname.tag = 'name';
fname.strtype = 's';
fname.num = [1 1];
fname.help = {'Name of factor, eg. ''Repetition'' '};
levels = entry('Levels','levels','e',[Inf 1],'');
p1=['Enter number of levels for this factor, eg. 2'];
levels.help ={p1};
factor.type = 'branch';
factor.name = 'Factor';
factor.tag = 'fact';
factor.val = {fname,levels};
factor.help = {'Add a new factor to your experimental design'};
factors.type = 'repeat';
factors.name = 'Factorial design';
factors.tag = 'factors';
factors.values = {factor};
p1 = ['If you have a factorial design then SPM can automatically generate ',...
'the contrasts necessary to test for the main effects and interactions. '];
p2 = ['This includes the F-contrasts necessary to test for these effects at ',...
'the within-subject level (first level) and the simple contrasts necessary ',...
'to generate the contrast images for a between-subject (second-level) ',...
'analysis.'];
p3 = ['To use this option, create as many factors as you need and provide a name ',...
'and number of levels for each. ',...
'SPM assumes that the condition numbers of the first factor change slowest, ',...
'the second factor next slowest etc. It is best to write down the contingency ',...
'table for your design to ensure this condition is met. This table relates the ',...
'levels of each factor to the ',...
'conditions. '];
p4= ['For example, if you have 2-by-3 design ',...
' your contingency table has two rows and three columns where the ',...
'the first factor spans the rows, and the second factor the columns. ',...
'The numbers of the conditions are 1,2,3 for the first row and 4,5,6 ',...
'for the second. '];
factors.help ={p1,sp_text,p2,sp_text,p3,sp_text,p4};
%-------------------------------------------------------------------------
glob = mnu('Global normalisation','global',...
{'Scaling','None'},{'Scaling','None'},{'Global intensity normalisation'});
glob.val={'None'};
%-------------------------------------------------------------------------
derivs = mnu('Model derivatives','derivs',...
{'No derivatives', 'Time derivatives', 'Time and Dispersion derivatives'},...
{[0 0],[1 0],[1 1]},'');
derivs.val = {[0 0]};
p1=['Model HRF Derivatives. The canonical HRF combined with time and ',...
'dispersion derivatives comprise an ''informed'' basis set, as ',...
'the shape of the canonical response conforms to the hemodynamic ',...
'response that is commonly observed. The incorporation of the derivate ',...
'terms allow for variations in subject-to-subject and voxel-to-voxel ',...
'responses. The time derivative allows the peak response to vary by plus or ',...
'minus a second and the dispersion derivative allows the width of the response ',...
'to vary. The informed basis set requires an SPM{F} for inference. T-contrasts ',...
'over just the canonical are perfectly valid but assume constant delay/dispersion. ',...
'The informed basis set compares ',...
'favourably with eg. FIR bases on many data sets. '];
derivs.help = {p1};
%-------------------------------------------------------------------------
hrf = branch('Canonical HRF','hrf',{derivs},'Canonical Hemodynamic Response Function');
hrf.help = {[...
'Canonical Hemodynamic Response Function. This is the default option. ',...
'Contrasts of these effects have a physical interpretation ',...
'and represent a parsimonious way of characterising event-related ',...
'responses. This option is also ',...
'useful if you wish to ',...
'look separately at activations and deactivations (this is implemented using a ',...
't-contrast with a +1 or -1 entry over the canonical regressor). ']};
%-------------------------------------------------------------------------
len = entry('Window length','length','e',[1 1],'');
len.help={'Post-stimulus window length (in seconds)'};
order = entry('Order','order','e',[1 1],'');
order.help={'Number of basis functions'};
o1 = branch('Fourier Set','fourier',{len,order},'');
o1.help = {'Fourier basis functions. This option requires an SPM{F} for inference.'};
o2 = branch('Fourier Set (Hanning)','fourier_han',{len,order},'');
o2.help = {'Fourier basis functions with Hanning Window - requires SPM{F} for inference.'};
o3 = branch('Gamma Functions','gamma',{len,order},'');
o3.help = {'Gamma basis functions - requires SPM{F} for inference.'};
o4 = branch('Finite Impulse Response','fir',{len,order},'');
o4.help = {'Finite impulse response - requires SPM{F} for inference.'};
%-------------------------------------------------------------------------
bases = choice('Basis Functions','bases',{hrf,o1,o2,o3,o4},'');
bases.val = {hrf};
bases.help = {[...
'The most common choice of basis function is the Canonical HRF with ',...
'or without time and dispersion derivatives. ']};
%-------------------------------------------------------------------------
volt = mnu('Model Interactions (Volterra)','volt',{'Do not model Interactions','Model Interactions'},{1,2},'');
volt.val = {1};
p1 = ['Generalized convolution of inputs (U) with basis set (bf).'];
p2 = [...
'For first order expansions the causes are simply convolved ',...
'(e.g. stick functions) in U.u by the basis functions in bf to create ',...
'a design matrix X. For second order expansions new entries appear ',...
'in ind, bf and name that correspond to the interaction among the ',...
'orginal causes. The basis functions for these efects are two dimensional ',...
'and are used to assemble the second order kernel. ',...
'Second order effects are computed for only the first column of U.u.'];
p3 = [...
'Interactions or response modulations can enter at two levels. Firstly ',...
'the stick function itself can be modulated by some parametric variate ',...
'(this can be time or some trial-specific variate like reaction time) ',...
'modeling the interaction between the trial and the variate or, secondly ',...
'interactions among the trials themselves can be modeled using a Volterra ',...
'series formulation that accommodates interactions over time (and therefore ',...
'within and between trial types).'];
volt.help = {p1,'',p2,p3};
%-------------------------------------------------------------------------
mask = files('Explicit mask','mask','image',[0 1],'Image mask');
mask.val = {''};
p1=['Specify an image for explicitly masking the analysis. ',...
'A sensible option here is to use a segmention of structural images ',...
'to specify a within-brain mask. If you select that image as an ',...
'explicit mask then only those voxels in the brain will be analysed. ',...
'This both speeds the estimation and restricts SPMs/PPMs to within-brain ',...
'voxels. Alternatively, if such structural images are unavailble or no ',...
'masking is required, then leave this field empty.'];
mask.help={p1};
%-------------------------------------------------------------------------
cdir = files('Directory','dir','dir',1,'');
cdir.help = {[...
'Select a directory where the SPM.mat file containing the ',...
'specified design matrix will be written.']};
%-------------------------------------------------------------------------
fmri_t0 = entry('Microtime onset','fmri_t0','e',[1 1],'');
p1=['The microtime onset, t0, is the first time-bin at which the regressors ',...
'are resampled to coincide ',...
'with data acquisition. If t0 = 1 then the ',...
'regressors will be appropriate for the first slice. If you want to ',...
'temporally realign the regressors so that they match responses in the ',...
'middle slice then make t0 = t/2 ',...
'(assuming there is a negligible gap between ',...
'volume acquisitions). '];
p2=['Do not change the default setting unless you have a long TR. '];
fmri_t0.val={1};
fmri_t0.help={p1,sp_text,p2};
fmri_t = entry('Microtime resolution','fmri_t','e',[1 1],'');
p1=['The microtime resolution, t, is the number of time-bins per ',...
'scan used when building regressors. '];
p2=['Do not change this parameter unless you have a long TR and wish to ',...
'shift regressors so that they are ',...
'aligned to a particular slice. '];
fmri_t.val={16};
fmri_t.help={p1,sp_text,p2};
rt = entry('Interscan interval','RT','e',[1 1],'Interscan interval {secs}');
rt.help = {[...
'Interscan interval, TR, (specified in seconds). This is the time between acquiring a plane of one volume ',...
'and the same plane in the next volume. It is assumed to be constant throughout.']};
%-------------------------------------------------------------------------
units = mnu('Units for design','units',{'Scans','Seconds'},{'scans','secs'},'');
p1=['The onsets of events or blocks can be specified in either scans or seconds.'];
units.help = {p1};
timing = branch('Timing parameters','timing',{units,rt,fmri_t,fmri_t0},'');
p1=['Specify various timing parameters needed to construct the design matrix. ',...
'This includes the units of the design specification and the interscan interval.'];
p2 = ['Also, with longs TRs you may want to shift the regressors so that they are ',...
'aligned to a particular slice. This is effected by changing the ',...
'microtime resolution and onset. '];
timing.help={p1,sp_text,p2};
%-------------------------------------------------------------------------
cvi = mnu('Serial correlations','cvi',{'none','AR(1)'},{'none','AR(1)'},...
{'Correct for serial correlations'});
cvi.val={'AR(1)'};
p1 = [...
'Serial correlations in fMRI time series due to aliased biorhythms and unmodelled ',...
'neuronal activity can be accounted for using an autoregressive AR(1) ',...
'model during Classical (ReML) parameter estimation. '];
p2=['This estimate assumes the same ',...
'correlation structure for each voxel, within each session. ReML ',...
'estimates are then used to correct for non-sphericity during inference ',...
'by adjusting the statistics and degrees of freedom appropriately. The ',...
'discrepancy between estimated and actual intrinsic (i.e. prior to ',...
'filtering) correlations are greatest at low frequencies. Therefore ',...
'specification of the high-pass filter is particularly important. '];
p3=[...
'Serial correlation can be ignored if you choose the ''none'' option. ',...
'Note that the above options only apply if you later specify that your model will be ',...
'estimated using the Classical (ReML) approach. If you choose Bayesian estimation ',...
'these options will be ignored. For Bayesian estimation, the choice of noise',...
'model (AR model order) is made under the estimation options. '];
cvi.help = {p1,sp_text,p2,sp_text,p3};
%-------------------------------------------------------------------------
conf = branch('fMRI model specification','fmri_spec',...
{cdir,timing,block,factors,bases,volt,glob,mask,cvi},'fMRI design');
conf.prog = @run_stats;
conf.vfiles = @vfiles_stats;
% conf.check = @check_dir;
conf.modality = {'FMRI'};
p1=['Statistical analysis of fMRI data uses a mass-univariate approach ',...
'based on General Linear Models (GLMs). It comprises the following ',...
'steps (1) specification of the GLM design matrix, fMRI data files and filtering ',...
'(2) estimation of GLM paramaters using classical or ',...
'Bayesian approaches and (3) interrogation of results using contrast vectors to ',...
'produce Statistical Parametric Maps (SPMs) or Posterior Probability Maps (PPMs).' ];
p2 = [...
'The design matrix defines the experimental design and the nature of ',...
'hypothesis testing to be implemented. The design matrix has one row ',...
'for each scan and one column for each effect or explanatory variable. ',...
'(eg. regressor or stimulus function). ',...
'You can build design matrices with separable ',...
'session-specific partitions. Each partition may be the same (in which ',...
'case it is only necessary to specify it once) or different. '];
p3 = ['Responses ',...
'can be either event- or epoch related, the only distinction is the duration ',...
'of the underlying input or stimulus function. Mathematically they are both ',...
'modeled by convolving a series of delta (stick) or box functions (u), ',...
'indicating the onset of an event or epoch with a set of basis ',...
'functions. These basis functions model the hemodynamic convolution, ',...
'applied by the brain, to the inputs. This convolution can be first-order ',...
'or a generalized convolution modeled to second order (if you specify the ',...
'Volterra option). The same inputs are used by the Hemodynamic model or ',...
'Dynamic Causal Models which model the convolution explicitly in terms of ',...
'hidden state variables. '];
p4=['Basis functions can be used to plot estimated responses to single events ',...
'once the parameters (i.e. basis function coefficients) have ',...
'been estimated. The importance of basis functions is that they provide ',...
'a graceful transition between simple fixed response models (like the ',...
'box-car) and finite impulse response (FIR) models, where there is one ',...
'basis function for each scan following an event or epoch onset. The ',...
'nice thing about basis functions, compared to FIR models, is that data ',...
'sampling and stimulus presentation does not have to be synchronized ',...
'thereby allowing a uniform and unbiased sampling of peri-stimulus time.'];
p5 = [...
'Event-related designs may be stochastic or deterministic. Stochastic ',...
'designs involve one of a number of trial-types occurring with a ',...
'specified probability at successive intervals in time. These ',...
'probabilities can be fixed (stationary designs) or time-dependent ',...
'(modulated or non-stationary designs). The most efficient designs ',...
'obtain when the probabilities of every trial type are equal. ',...
'A critical issue in stochastic designs is whether to include null events ',...
'If you wish to estimate the evoked response to a specific event ',...
'type (as opposed to differential responses) then a null event must be ',...
'included (even if it is not modeled explicitly).'];
p6 = [...
'In SPM, analysis of data from multiple subjects typically proceeds in two stages ',...
'using models at two ''levels''. The ''first level'' models are used to ',...
'implement a within-subject analysis. Typically there will be as many first ',...
'level models as there are subjects. Analysis proceeds as described using the ',...
'''Specify first level'' and ''Estimate'' options. The results of these analyses ',...
'can then be presented as ''case studies''. More often, however, one wishes to ',...
'make inferences about the population from which the subjects were drawn. This is ',...
'an example of a ''Random-Effects (RFX) analysis'' (or, more properly, a mixed-effects ',...
'analysis). In SPM, RFX analysis is implemented using the ''summary-statistic'' ',...
'approach where contrast images from each subject are used as summary ',...
'measures of subject responses. These are then entered as data into a ''second level'' ',...
'model. '];
conf.help = {p1,'',p2,'',p3,'',p4,'',p5,'',p6};
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
% COMMENTED OUT BY DRG. I THINK THIS SUB-FUNCTION WAS A HOLDOVER FROM AN
% EARLY VERSION OF THIS FILE. PLEASE REMOVE IF REALLY NOT USED. ALSO REMOVE
% REFERENCE ON LINE 523 (COMMENTED OUT) TO CHECK_DIR
% function t = check_dir(job)
% t = {};
%d = pwd;
%try,
% cd(job.dir{1});
%catch,
% t = {['Cannot Change to directory "' job.dir{1} '".']};
%end;
%disp('Checking...');
%disp(fullfile(job.dir{1},'SPM.mat'));
% Should really include a check for a "virtual" SPM.mat
%if exist(fullfile(job.dir{1},'SPM.mat'),'file'),
% t = {'SPM files exist in the analysis directory.'};
%end;
%return;
% END COMMENTED OUT BY DRG
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function t = cond_check(job)
t = {};
if (numel(job.onset) ~= numel(job.duration)) && (numel(job.duration)~=1),
t = {sprintf('"%s": Number of event onsets (%d) does not match the number of durations (%d).',...
job.name, numel(job.onset),numel(job.duration))};
end;
for i=1:numel(job.pmod),
if numel(job.onset) ~= numel(job.pmod(i).param),
t = {t{:}, sprintf('"%s" & "%s":Number of event onsets (%d) does not equal the number of parameters (%d).',...
job.name, job.pmod(i).name, numel(job.onset),numel(job.pmod(i).param))};
end;
end;
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function t = sess_check(sess)
t = {};
for i=1:numel(sess.regress),
if numel(sess.scans) ~= numel(sess.regress(i).val),
t = {t{:}, sprintf('Num scans (%d) ~= Num regress[%d] (%d).',numel(sess.scans),i,numel(sess.regress(i).val))};
end;
end;
return;
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function my_cd(varargin)
% jobDir must be the actual directory to change to, NOT the job structure.
jobDir = varargin{1};
if ~isempty(jobDir)
try
cd(char(jobDir));
fprintf('Changing directory to: %s\n',char(jobDir));
catch
error('Failed to change directory. Aborting run.')
end
end
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function run_stats(job)
% Set up the design matrix and run a design.
spm_defaults;
global defaults
defaults.modality='FMRI';
original_dir = pwd;
my_cd(job.dir);
%-Ask about overwriting files from previous analyses...
%-------------------------------------------------------------------
if exist(fullfile(job.dir{1},'SPM.mat'),'file')
str = { 'Current directory contains existing SPM file:',...
'Continuing will overwrite existing file!'};
if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);
fprintf('%-40s: %30s\n\n',...
'Abort... (existing SPM file)',spm('time'));
return
end
end
% If we've gotten to this point we're committed to overwriting files.
% Delete them so we don't get stuck in spm_spm
%------------------------------------------------------------------------
files = {'^mask\..{3}$','^ResMS\..{3}$','^RPV\..{3}$',...
'^beta_.{4}\..{3}$','^con_.{4}\..{3}$','^ResI_.{4}\..{3}$',...
'^ess_.{4}\..{3}$', '^spm\w{1}_.{4}\..{3}$'};
for i=1:length(files)
j = spm_select('List',pwd,files{i});
for k=1:size(j,1)
spm_unlink(deblank(j(k,:)));
end
end
% Variables
%-------------------------------------------------------------
SPM.xY.RT = job.timing.RT;
SPM.xY.P = [];
% Slice timing
defaults.stats.fmri.t=job.timing.fmri_t;
defaults.stats.fmri.t0=job.timing.fmri_t0;
% Basis function variables
%-------------------------------------------------------------
SPM.xBF.UNITS = job.timing.units;
SPM.xBF.dt = job.timing.RT/defaults.stats.fmri.t;
SPM.xBF.T = defaults.stats.fmri.t;
SPM.xBF.T0 = defaults.stats.fmri.t0;
% Basis functions
%-------------------------------------------------------------
if strcmp(fieldnames(job.bases),'hrf')
if all(job.bases.hrf.derivs == [0 0])
SPM.xBF.name = 'hrf';
elseif all(job.bases.hrf.derivs == [1 0])
SPM.xBF.name = 'hrf (with time derivative)';
elseif all(job.bases.hrf.derivs == [1 1])
SPM.xBF.name = 'hrf (with time and dispersion derivatives)';
else
error('Unrecognized hrf derivative choices.')
end
else
nambase = fieldnames(job.bases);
if ischar(nambase)
nam=nambase;
else
nam=nambase{1};
end
switch nam,
case 'fourier',
SPM.xBF.name = 'Fourier set';
case 'fourier_han',
SPM.xBF.name = 'Fourier set (Hanning)';
case 'gamma',
SPM.xBF.name = 'Gamma functions';
case 'fir',
SPM.xBF.name = 'Finite Impulse Response';
otherwise
error('Unrecognized hrf derivative choices.')
end
SPM.xBF.length = job.bases.(nam).length;
SPM.xBF.order = job.bases.(nam).order;
end
SPM.xBF = spm_get_bf(SPM.xBF);
if isempty(job.sess),
SPM.xBF.Volterra = false;
else
SPM.xBF.Volterra = job.volt;
end;
for i = 1:numel(job.sess),
sess = job.sess(i);
% Image filenames
%-------------------------------------------------------------
SPM.nscan(i) = size(sess.scans,1);
SPM.xY.P = strvcat(SPM.xY.P,sess.scans{:});
U = [];
% Augment the singly-specified conditions with the multiple
% conditions specified in a .mat file provided by the user
%------------------------------------------------------------
if ~isempty(sess.multi{1})
try
multicond = load(sess.multi{1});
catch
error('Cannot load %s',sess.multi{1});
end
if ~(isfield(multicond,'names')&&isfield(multicond,'onsets')&&...
isfield(multicond,'durations')) || ...
~all([numel(multicond.names),numel(multicond.onsets), ...
numel(multicond.durations)]==numel(multicond.names))
error(['Multiple conditions MAT-file ''%s'' is invalid.\n',...
'File must contain names, onsets, and durations '...
'cell arrays of equal length.\n'],sess.multi{1});
end
%-contains three cell arrays: names, onsets and durations
for j=1:length(multicond.onsets)
cond.name = multicond.names{j};
cond.onset = multicond.onsets{j};
cond.duration = multicond.durations{j};
% ADDED BY DGITELMAN
% Mutiple Conditions Time Modulation
%------------------------------------------------------
% initialize the variable.
cond.tmod = 0;
if isfield(multicond,'tmod');
try
cond.tmod = multicond.tmod{j};
catch
error('Error specifying time modulation.');
end
end
% Mutiple Conditions Parametric Modulation
%------------------------------------------------------
% initialize the parametric modulation variable.
cond.pmod = [];
if isfield(multicond,'pmod')
% only access existing modulators
try
% check if there is a parametric modulator. this allows
% pmod structures with fewer entries than conditions.
% then check whether any cells are filled in.
if (j <= numel(multicond.pmod)) && ...
~isempty(multicond.pmod(j).name)
% we assume that the number of cells in each
% field of pmod is the same (or should be).
for ii = 1:numel(multicond.pmod(j).name)
cond.pmod(ii).name = multicond.pmod(j).name{ii};
cond.pmod(ii).param = multicond.pmod(j).param{ii};
cond.pmod(ii).poly = multicond.pmod(j).poly{ii};
end
end;
catch
error('Error specifying parametric modulation.');
end
end
sess.cond(end+1) = cond;
end
end
% Configure the input structure array
%-------------------------------------------------------------
for j = 1:length(sess.cond),
cond = sess.cond(j);
U(j).name = {cond.name};
U(j).ons = cond.onset(:);
U(j).dur = cond.duration(:);
if length(U(j).dur) == 1
U(j).dur = U(j).dur*ones(size(U(j).ons));
elseif length(U(j).dur) ~= length(U(j).ons)
error('Mismatch between number of onset and number of durations.')
end
P = [];
q1 = 0;
if cond.tmod>0,
% time effects
P(1).name = 'time';
P(1).P = U(j).ons*job.timing.RT;
P(1).h = cond.tmod;
q1 = 1;
end;
if ~isempty(cond.pmod)
for q = 1:numel(cond.pmod),
% Parametric effects
q1 = q1 + 1;
P(q1).name = cond.pmod(q).name;
P(q1).P = cond.pmod(q).param(:);
P(q1).h = cond.pmod(q).poly;
end;
end
if isempty(P)
P.name = 'none';
P.h = 0;
end
U(j).P = P;
end
SPM.Sess(i).U = U;
% User specified regressors
%-------------------------------------------------------------
C = [];
Cname = cell(1,numel(sess.regress));
for q = 1:numel(sess.regress),
Cname{q} = sess.regress(q).name;
C = [C, sess.regress(q).val(:)];
end
% Augment the singly-specified regressors with the multiple regressors
% specified in the regressors.mat file
%------------------------------------------------------------
if ~strcmp(sess.multi_reg,'')
tmp=load(char(sess.multi_reg{:}));
if isstruct(tmp) && isfield(tmp,'R')
R = tmp.R;
elseif isnumeric(tmp)
% load from e.g. text file
R = tmp;
else
warning('Can''t load user specified regressors in %s', ...
char(sess.multi_reg{:}));
R = [];
end
C=[C, R];
nr=size(R,2);
nq=length(Cname);
for inr=1:nr,
Cname{inr+nq}=['R',int2str(inr)];
end
end
SPM.Sess(i).C.C = C;
SPM.Sess(i).C.name = Cname;
end
% Factorial design
%-------------------------------------------------------------
if isfield(job,'fact')
if ~isempty(job.fact)
NC=length(SPM.Sess(1).U); % Number of conditions
CheckNC=1;
for i=1:length(job.fact)
SPM.factor(i).name=job.fact(i).name;
SPM.factor(i).levels=job.fact(i).levels;
CheckNC=CheckNC*SPM.factor(i).levels;
end
if ~(CheckNC==NC)
disp('Error in fmri_spec job: factors do not match conditions');
return
end
end
else
SPM.factor=[];
end
% Globals
%-------------------------------------------------------------
SPM.xGX.iGXcalc = job.global;
SPM.xGX.sGXcalc = 'mean voxel value';
SPM.xGX.sGMsca = 'session specific';
% High Pass filter
%-------------------------------------------------------------
for i = 1:numel(job.sess),
SPM.xX.K(i).HParam = job.sess(i).hpf;
end
% Autocorrelation
%-------------------------------------------------------------
SPM.xVi.form = job.cvi;
% Let SPM configure the design
%-------------------------------------------------------------
SPM = spm_fmri_spm_ui(SPM);
if ~isempty(job.mask)&&~isempty(job.mask{1})
SPM.xM.VM = spm_vol(job.mask{:});
SPM.xM.xs.Masking = [SPM.xM.xs.Masking, '+explicit mask'];
end
%-Save SPM.mat
%-----------------------------------------------------------------------
fprintf('%-40s: ','Saving SPM configuration') %-#
if spm_matlab_version_chk('7') >= 0
save('SPM','-V6','SPM');
else
save('SPM','SPM');
end;
fprintf('%30s\n','...SPM.mat saved') %-#
my_cd(original_dir); % Change back dir
fprintf('Done\n')
return
%-------------------------------------------------------------------------
%-------------------------------------------------------------------------
function vf = vfiles_stats(job)
direc = job.dir{1};
vf = {spm_select('CPath','SPM.mat',direc)};
|
github
|
spm/spm5-master
|
spm_PEB.m
|
.m
|
spm5-master/spm_PEB.m
| 11,436 |
utf_8
|
678306cbfce6892ef9f126270aaaf5f4
|
function [C,P,F] = spm_PEB(y,P,OPT)
% parametric empirical Bayes (PEB) for hierarchical linear models
% FORMAT [C,P,F] = spm_PEB(y,P,OPT)
%
% y - (n x 1) response variable
%
% MODEL SPECIFICATION
%
% P{i}.X - (n x m) ith level design matrix i.e: constraints on <Eb{i - 1}>
% P{i}.C - {q}(n x n) ith level contraints on Cov{e{i}} = Cov{b{i - 1}}
%
% OPT - enforces positively constraints on the covariance hyperparameters
% by adopting a log-normal [flat] hyperprior. default = 0
%
% POSTERIOR OR CONDITIONAL ESTIMATES
%
% C{i}.E - (n x 1) conditional expectation E{b{i - 1}|y}
% C{i}.C - (n x n) conditional covariance Cov{b{i - 1}|y} = Cov{e{i}|y}
% C{i}.M - (n x n) ML estimate of Cov{b{i - 1}} = Cov{e{i}}
% C{i}.h - (q x 1) ith level ReML hyperparameters for covariance:
% Cov{e{i}} = P{i}.h(1)*P{i}.C{1} + ...
%
% LOG EVIDENCE
%
% F - [-ve] free energy F = log evidence = p(y|X,C)
%
% If P{i}.C is not a cell the covariance at that level is assumed to be kown
% and Cov{e{i}} = P{i}.C (i.e. the hyperparameter is fixed at 1)
%
% If P{n}.C is not a cell this is taken to indicate that a full Bayesian
% estimate is required where P{n}.X is the prior expectation and P{n}.C is
% the known prior covariance. For consistency, with PEB, this is implemented
% by setting b{n} = 1 through appropriate constraints at level {n + 1}.
%
% To implement non-hierarchical Bayes with priors on the parameters use
% a two level model setting the second level design matrix to zeros.
%__________________________________________________________________________
%
% Returns the moments of the posterior p.d.f. of the parameters of a
% hierarchical linear observation model under Gaussian assumptions
%
% y = X{1}*b{1} + e{1}
% b{1} = X{2}*b{2} + e{2}
% ...
%
% b{n - 1} = X{n}*b{n} + e{n}
%
% e{n} ~ N{0,Ce{n}}
%
% using Parametic Emprical Bayes (PEB)
%
% Ref: Dempster A.P., Rubin D.B. and Tsutakawa R.K. (1981) Estimation in
% covariance component models. J. Am. Stat. Assoc. 76;341-353
%__________________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Karl Friston
% $Id: spm_PEB.m 587 2006-08-07 04:38:22Z Darren $
% set default
%--------------------------------------------------------------------------
try
OPT;
catch
OPT = 0;
end
% number of levels (p)
%--------------------------------------------------------------------------
M = 32; % maximum number of iterations
p = length(P);
% check covariance constraints - assume i.i.d. errors conforming to X{i}
%--------------------------------------------------------------------------
for i = 1:p
if ~isfield(P{i},'C')
[n m] = size(P{i}.X);
if i == 1
P{i}.C = {speye(n,n)};
else
for j = 1:m
k = find(P{i}.X(:,j));
P{i}.C{j} = sparse(k,k,1,n,n);
end
end
end
end
% Construct augmented non-hierarchical model
%==========================================================================
% design matrix and indices
%--------------------------------------------------------------------------
I = {0};
J = {0};
K = {0};
XX = [];
X = 1;
for i = 1:p
% design matrix
%----------------------------------------------------------------------
X = X*P{i}.X;
XX = [XX X];
% indices for ith level parameters
%----------------------------------------------------------------------
[n m] = size(P{i}.X);
I{i} = [1:n] + I{end}(end);
J{i} = [1:m] + J{end}(end);
end
% augment design matrix and data
%--------------------------------------------------------------------------
n = size(XX,2);
XX = [XX; speye(n,n)];
y = [y; sparse(n,1)];
% last level constraints
%--------------------------------------------------------------------------
n = size(P{p}.X,2);
I{p + 1} = [1:n] + I{end}(end);
q = I{end}(end);
Cb = sparse(q,q);
if ~iscell(P{end}.C)
% Full Bayes: (i.e. Cov(b) = 0, <b> = 1)
%----------------------------------------------------------------------
y( I{end}) = sparse(1:n,1,1);
else
% Empirical Bayes: uniform priors (i.e. Cov(b) = Inf, <b> = 0)
%----------------------------------------------------------------------
Cb(I{end},I{end}) = sparse(1:n,1:n,exp(32));
end
% assemble augmented constraints Q: Cov{e} = Cb + h(i)*Q{i} + ...
%==========================================================================
if ~isfield(P{1},'Q')
% covariance contraints Q on Cov{e{i}} = Cov{b{i - 1}}
%----------------------------------------------------------------------
h = [];
Q = {};
for i = 1:p
% collect constraints on prior covariances - Cov{e{i}}
%------------------------------------------------------------------
if iscell(P{i}.C)
m = length(P{i}.C);
for j = 1:m
[u v s] = find(P{i}.C{j});
u = u + I{i}(1) - 1;
v = v + I{i}(1) - 1;
Q{end + 1} = sparse(u,v,s,q,q);
end
% indices for ith-level hyperparameters
%--------------------------------------------------------------
try
K{i} = [1:m] + K{end}(end);
catch
K{i} = [1:m];
end
else
% unless they are known - augment Cb
%--------------------------------------------------------------
[u v s] = find(P{i}.C + speye(length(P{i}.C))*1e-6);
u = u + I{i}(1) - 1;
v = v + I{i}(1) - 1;
Cb = Cb + sparse(u,v,s,q,q);
% indices for ith-level hyperparameters
%--------------------------------------------------------------
K{i} = [];
end
end
% note overlapping bases - requiring 2nd order M-Step derivatives
%----------------------------------------------------------------------
m = length(Q);
d = sparse(m,m);
for i = 1:m
XQX{i} = XX'*Q{i}*XX;
end
for i = 1:m
for j = i:m
o = nnz(XQX{i}*XQX{j});
d(i,j) = o;
d(j,i) = o;
end
end
% log-transform and save
%----------------------------------------------------------------------
h = zeros(m,1);
if OPT
hP = speye(m,m)/16;
else
hP = speye(m,m)/exp(16);
for i = 1:m
h(i) = any(diag(Q{i}));
end
end
P{1}.hP = hP;
P{1}.Cb = Cb;
P{1}.Q = Q;
P{1}.h = h;
P{1}.K = K;
P{1}.d = d;
end
hP = P{1}.hP;
Cb = P{1}.Cb;
Q = P{1}.Q;
h = P{1}.h;
K = P{1}.K;
d = P{1}.d;
% Iterative EM
%--------------------------------------------------------------------------
m = length(Q);
dFdh = zeros(m,1);
dFdhh = zeros(m,m);
for k = 1:M
% inv(Cov(e)) - iC(h)
%----------------------------------------------------------------------
Ce = Cb;
for i = 1:m
if OPT
Ce = Ce + Q{i}*exp(h(i));
else
Ce = Ce + Q{i}*h(i);
end
end
iC = spm_inv(Ce);
% E-step: conditional mean E{B|y} and covariance cov(B|y)
%======================================================================
iCX = iC*XX;
Cby = spm_inv(XX'*iCX);
B = Cby*(iCX'*y);
% M-step: ReML estimate of hyperparameters (if m > 0)
%======================================================================
if m == 0, break, end
% Gradient dF/dh (first derivatives)
%----------------------------------------------------------------------
Py = iC*(y - XX*B);
iCXC = iCX*Cby;
for i = 1:m
% dF/dh = -trace(dF/diC*iC*Q{i}*iC)
%------------------------------------------------------------------
PQ{i} = iC*Q{i} - iCXC*(iCX'*Q{i});
if OPT
PQ{i} = PQ{i}*exp(h(i));
end
dFdh(i) = -trace(PQ{i})/2 + y'*PQ{i}*Py/2;
end
% Expected curvature E{ddF/dhh} (second derivatives)
%----------------------------------------------------------------------
for i = 1:m
for j = i:m
if d(i,j)
% ddF/dhh = -trace{P*Q{i}*P*Q{j}}
%----------------------------------------------------------
dFdhh(i,j) = -sum(sum(PQ{i}.*PQ{j}'))/2;
dFdhh(j,i) = dFdhh(i,j);
end
end
end
% add hyperpriors
%----------------------------------------------------------------------
dFdhh = dFdhh - hP;
% Fisher scoring: update dh = -inv(ddF/dhh)*dF/dh
%----------------------------------------------------------------------
dh = -pinv(dFdhh)*dFdh;
h = h + dh;
% Convergence
%======================================================================
w = norm(dh,1);
% fprintf('%-30s: %i %30s%e\n',' PEB Iteration',k,'...',full(w));
% if dF < 0.01
%----------------------------------------------------------------------
if dFdh'*dh < 1e-2, break, end
% if dh^2 < 1e-8
%----------------------------------------------------------------------
if w < 1e-4, break, end
% if log-normal hyperpriors and h < exp(-16)
%----------------------------------------------------------------------
if OPT && h < -16, break, end
end
% place hyperparameters in P{1} and output structure for {n + 1}
%--------------------------------------------------------------------------
P{1}.h = h + exp(-32);
C{p + 1}.E = B(J{p});
C{p + 1}.M = Cb(I{end},I{end});
% recursive computation of conditional means E{b|y}
%--------------------------------------------------------------------------
for i = p:-1:2
C{i}.E = B(J{i - 1}) + P{i}.X*C{i + 1}.E;
end
% hyperpriors - precision
%--------------------------------------------------------------------------
if OPT
h = exp(h);
end
% conditional covariances Cov{b|y} and ReML esimtates of Ce{i) = Cb{i - 1}
%--------------------------------------------------------------------------
for i = 1:p
C{i + 1}.C = Cby(J{i},J{i});
C{i}.M = Ce(I{i},I{i});
C{i}.h = h(K{i});
end
% log evidence = ln p(y|X,C) = F = [-ve] free energy
%--------------------------------------------------------------------------
if nargout > 2
% condotional covariance of h
%----------------------------------------------------------------------
Ph = -dFdhh;
% log evidence = F
%----------------------------------------------------------------------
F = - Py'*Ce*Py/2 ...
- length(I{1})*log(2*pi)/2 ...
- spm_logdet(Ce)/2 ...
- spm_logdet(Ph)/2 ...
+ spm_logdet(hP)/2 ...
+ spm_logdet(Cby)/2;
end
% warning
%--------------------------------------------------------------------------
if k == M, warning('maximum number of iterations exceeded'), end
return
function [C] = spm_inv(C);
% inversion of sparse matrices
%__________________________________________________________________________
C = inv(C + speye(length(C))*exp(-32));
|
github
|
spm/spm5-master
|
spm_eeg_firstlevel.m
|
.m
|
spm5-master/spm_eeg_firstlevel.m
| 15,017 |
utf_8
|
fbadc26bae89a983d0b0adc9205ff7dd
|
function varargout = spm_eeg_firstlevel(varargin)
% SPM_EEG_FIRSTLEVEL M-file for spm_eeg_firstlevel.fig
% SPM_EEG_FIRSTLEVEL, by itself, creates a new SPM_EEG_FIRSTLEVEL or raises the existing
% singleton*.
%
% H = SPM_EEG_FIRSTLEVEL returns the handle to a new SPM_EEG_FIRSTLEVEL or the handle to
% the existing singleton*.
%
% SPM_EEG_FIRSTLEVEL('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SPM_EEG_FIRSTLEVEL.M with the given input arguments.
%
% SPM_EEG_FIRSTLEVEL('Property','Value',...) creates a new SPM_EEG_FIRSTLEVEL or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before spm_eeg_firstlevel_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to spm_eeg_firstlevel_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Copyright 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help spm_eeg_firstlevel
% Last Modified by GUIDE v2.5 02-Feb-2006 16:29:08
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @spm_eeg_firstlevel_OpeningFcn, ...
'gui_OutputFcn', @spm_eeg_firstlevel_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before spm_eeg_firstlevel is made visible.
function spm_eeg_firstlevel_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to spm_eeg_firstlevel (see VARARGIN)
% Choose default command line output for spm_eeg_firstlevel
handles.output = hObject;
handles.con_types = {};
handles.Nt = 0;
set(handles.listbox1, 'String', {});
set(handles.listbox2, 'String', {});
spm_defaults;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes spm_eeg_firstlevel wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = spm_eeg_firstlevel_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (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 listbox1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (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
% --- Executes on selection change in listbox2.
function listbox2_Callback(hObject, eventdata, handles)
% hObject handle to listbox2 (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 listbox2 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox2
% --- Executes during object creation, after setting all properties.
function listbox2_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox2 (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
% --- Executes on button press in addfile.
function addfile_Callback(hObject, eventdata, handles)
% hObject handle to addfile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname, filterindex] = uigetfile('*.img', 'Select an image');
if filename == 0, return, end
[status, Iimg, Limg] = spm_eeg_firstlevel_checkfile(fullfile(pathname, filename), handles.Nt);
if status == 0
errordlg(sprintf('Can''t add: new file has %d time points, selected have %d', Limg, handles.Nt));
return
else
handles.Nt = status;
end
% add image to list
set(handles.listbox1, 'String', [get(handles.listbox1, 'String'); {fullfile(pathname, filename)}]);
set(handles.Dfile, 'Enable', 'on');
% Update handles structure
guidata(hObject, handles);
% --- Executes on button press in removefile.
function removefile_Callback(hObject, eventdata, handles)
% hObject handle to removefile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if length(get(handles.listbox1, 'String')) == 0, return, end
ind = get(handles.listbox1, 'Value');
tmp = get(handles.listbox1, 'String');
tmp(ind) = [];
set(handles.listbox1, 'Value', max(1, ind-1));
set(handles.listbox1, 'String', tmp);
% user removed all files?
if length(get(handles.listbox1, 'String')) == 0
handles.Nt = 0;
set(handles.Dfile, 'Enable', 'off');
set(handles.Dfile, 'String', 'Select SPM M/EEG file');
handles.Dfilename = [];
set(handles.mstext, 'String', []);
end
% Update handles structure
guidata(hObject, handles);
% --- Executes on button press in addcontrast.
function addcontrast_Callback(hObject, eventdata, handles)
% hObject handle to addcontrast (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% averages only (add more options soon)
s = inputdlg({'from', 'to'}, 'Specify peri-stimulus time window for average [ms]');
from = str2num(s{1});
to = str2num(s{2});
strname = sprintf('Average from %d to %d ms', from, to);
% checks
if from < handles.ms(1)
errordlg(sprintf('Start of time window must be later than %d ms.', handles.ms(1)));
return;
end
if to > handles.ms(2)
errordlg(sprintf('End of time window must be earlier than %d ms.', handles.ms(2)));
return;
end
if from > to
errordlg('Start of time window must be earlier than its end.');
return;
end
% add contrast to list
set(handles.listbox2, 'String', [get(handles.listbox2, 'String'); {strname}]);
handles.con_types = cat(1, handles.con_types, {'average', from, to});
set(handles.compute, 'Enable', 'on');
% Update handles structure
guidata(hObject, handles);
% --- Executes on button press in removecontrast.
function removecontrast_Callback(hObject, eventdata, handles)
% hObject handle to removecontrast (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if length(get(handles.listbox2, 'String')) == 0, return, end
ind = get(handles.listbox2, 'Value');
tmp = get(handles.listbox2, 'String');
tmp(ind) = [];
handles.con_types(ind) = [];
set(handles.listbox2, 'Value', max(1, ind-1));
set(handles.listbox2, 'String', tmp);
% user removed all contrasts?
if length(get(handles.listbox2, 'String')) == 0
handles.con_types = {};
set(handles.compute, 'Enable', 'off');
end
% Update handles structure
guidata(hObject, handles);
% --- Executes on button press in compute.
function compute_Callback(hObject, eventdata, handles)
% hObject handle to compute (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% make sure images are not flipped
global defaults
defaults.analyze.flip = 0;
con_types = handles.con_types;
D = handles.D;
ms = 1000/D.Radc*[-D.events.start:D.events.stop];
% assemble contrast vectors into matrix
for i = 1:size(handles.con_types, 1)
c = zeros(handles.Nt, 1);
if strcmp(con_types(i, 1), 'average')
% window in time points
[tmp, tp(1)] = min((ms-con_types{i, 2}).^2);
[tmp, tp(2)] = min((ms-con_types{i, 3}).^2);
c(tp(1):tp(2)) = 1./(tp(2)-tp(1)+1);
C(:,i) = c;
end
end
fnames = get(handles.listbox1, 'String');
spm('Pointer', 'Watch');drawnow
% compute and write contrast images
for j = 1:size(fnames, 1); % over files
% map file
Vbeta = nifti(deblank(fnames{j}));
% cd to target directory
[path, f] = fileparts(fnames{j});
cd(path);
for i = 1:size(C, 2) % over contrasts
% code taken from spm_contrasts
fprintf('\t%-32s: %-10s%20s', sprintf('file %s, contrast %d', fnames{j}, i),...
'(spm_add)','...initialising') %-#
%-Prepare handle for contrast image
%-----------------------------------------------------------
if strcmp(con_types{i, 1}, 'average')
descrip = sprintf('SPM contrast - average from %d to %d ms',...
con_types{i, 2}, con_types{i, 3});
else
descrip = sprintf('SPM contrast - %d: %s', i, con_type{i, 1});
end
% prepare nifti image (the usual spm_add doesn't seem to work for
% many input files under windows)
Vcon = nifti;
Vcon.descrip = descrip;
Dcon = file_array;
Dcon.fname = sprintf('%s_con_%04d.img', f, i);
Dcon.dtype = spm_type('float32');
Dcon.offset = ceil(348/8)*8;
Dcon.dim = Vbeta.dat.dim(1:3);
Vcon.dat = Dcon;
%-Write image
%-----------------------------------------------------------
fprintf('%s%20s', repmat(sprintf('\b'),1,20),'...computing')%-#
% replace loop by one line if possible
d = zeros(Vbeta.dat.dim(1:3));
for k = 1:Vbeta.dat.dim(4)
d = d + Vbeta.dat(:,:,:, k)*C(k,i);
end
if Vbeta.dat.dim(3) == 1
Dcon(:,:) = d;
else
Dcon.dat(:,:,:) = d;
end
Vcon.dat = Dcon;
create(Vcon);
fprintf('%s%30s\n',repmat(sprintf('\b'),1,30),sprintf(...
'...written %s',spm_str_manip(Vcon.dat.fname,'t')))%-#
end
end
spm('Pointer', 'Arrow');
% --- Executes on button press in Dfile.
function Dfile_Callback(hObject, eventdata, handles)
% hObject handle to Dfile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname, filterindex] = uigetfile('*.mat', 'Select a SPM M/EEG file');
try
D = spm_eeg_ldata(fullfile(pathname, filename));
catch
errordlg('Selected file isn''t a valid SPM M/EEG file.')
return;
end
try
D.Nsamples;
catch
errordlg('Selected file isn''t a valid SPM M/EEG file.')
return;
end
if D.Nsamples ~= handles.Nt
errordlg(sprintf('Number of time points (%d) different from images (%d).', D.Nsamples, handles.Nt))
return;
end
% Dfile is valid
handles.Dfilename = fullfile(pathname, filename);
handles.D = D;
set(handles.listbox2, 'Enable', 'on');
set(handles.addcontrast, 'Enable', 'on');
set(handles.removecontrast, 'Enable', 'on');
set(handles.clearcontrasts, 'Enable', 'on');
handles.ms = 1000/D.Radc*[-D.events.start D.events.stop];
set(handles.mstext, 'Enable', 'on');
set(handles.mstext, 'String', ...
sprintf('%d to %d ms, %d time points, %.2f ms steps', ...
handles.ms(1), handles.ms(2), handles.Nt, 1000/D.Radc));
set(handles.Dfile, 'String', handles.Dfilename);
% Update handles structure
guidata(hObject, handles);
% --- Executes on button press in adddir.
function adddir_Callback(hObject, eventdata, handles)
% hObject handle to adddir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
d = uigetdir(pwd, 'Select a directory to search for SPM M/EEG-files');
if d == 0, return, end;
[flist] = spm_eeg_firstlevel_searchdir(d, []);
spm('Pointer', 'Watch'); drawnow;
% check for these files that length (time) is the same
for i = 1:size(flist,1)
[status, Iimg, Limg] = spm_eeg_firstlevel_checkfile(flist(i,:), handles.Nt);
% suppress error warning that file in list is of unequal length
if status ~= 0
% add image to list
set(handles.listbox1, 'String', [get(handles.listbox1, 'String'); {deblank(flist(i, :))}]);
set(handles.Dfile, 'Enable', 'on'); drawnow;
handles.Nt = status;
end
drawnow;
end
spm('Pointer', 'Arrow');
% Update handles structure
guidata(hObject, handles);
% --- Executes on button press in clearfiles.
function clearfiles_Callback(hObject, eventdata, handles)
% hObject handle to clearfiles (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.listbox1, 'String', []);
handles.Nt = 0;
set(handles.Dfile, 'Enable', 'off');
set(handles.Dfile, 'String', 'Select SPM M/EEG file');
handles.Dfilename = [];
set(handles.mstext, 'String', []);
% Update handles structure
guidata(hObject, handles);
% --- Executes on button press in clearcontrasts.
function clearcontrasts_Callback(hObject, eventdata, handles)
% hObject handle to clearcontrasts (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.listbox2, 'String', []);
handles.con_types = {};
set(handles.compute, 'Enable', 'off');
% Update handles structure
guidata(hObject, handles);
|
github
|
spm/spm5-master
|
ctf_read_res4.m
|
.m
|
spm5-master/ctf_read_res4.m
| 17,494 |
utf_8
|
ab874b345fc22ebc68b64b816b438ef9
|
function [ctf] = ctf_read_res4(folder,VERBOSE,COEFS);
% ctf_read_res4 - Read a CTF .res4 file
%
% ctf = ctf_read_res4( [folder], [verbose], [coefs])
%
% This function reads the resource information from a CTF .ds folder. This
% resource information must be read before reading the .meg4 data file.
% All input arguments are optional.
%
% INPUTS
%
% folder: the .ds directory containing the data to be read. With
% no input, it will prompt with a gui folder locator.
%
% verbose: If verbose = 1, display 'ctf.setup' structure (default)
% If verbose = 0, do not display 'ctf.setup' structure
%
% coefs: an option to read the sensory coefficients, which give the
% weights for calculation of synthetic 2nd or 3rd order
% gradiometers.
% If coefs = 1, read the sensor coefficients
% If coefs = 0, do not read the sensor coefficients (default)
%
% OUTPUTS
%
% ctf.folder - path of the .ds folder
%
% ctf.res4.file - data file path/name
% ctf.res4.header - data format header
%
% ctf.setup - a header structure consisting of date, time, run name, run
% title, subject, run description, operator, number of channels, number
% of samples, sample rate, number of trials, duration, pretrigger_samples,
% sensor filename, head zeroing, and number of filters.
%
% ctf.sensor.index - a sensor structure consisting of EEG sensors, MEG
% sensors, reference sensors, and other sensors.
%
% ctf.sensor.info - a structure with gain and offset information consisting
% of proper gain, Q gain, io gain, io offset, and index.
%
% <>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
% < >
% < DISCLAIMER: >
% < >
% < THIS PROGRAM IS INTENDED FOR RESEARCH PURPOSES ONLY. >
% < THIS PROGRAM IS IN NO WAY INTENDED FOR CLINICAL OR >
% < OFFICIAL USE. >
% < >
% <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>
%
% $Revision: 253 $ $Date: 2004/08/19 03:17:10 $
% Copyright (C) 2003 Darren L. Weber
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
% Modified: 11/2003, Darren.Weber_at_radiology.ucsf.edu
% - modified from NIH code readresfile.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ver = '$Revision: 253 $';
fprintf('\nCTF_READ_RES4 [v %s]\n',ver(11:15)); tic;
if ~exist('folder','var'),
ctf = ctf_folder;
else
ctf = ctf_folder(folder);
end
if ~exist('VERBOSE','var'), VERBOSE = true; end
if ~exist('COEFS','var'), COEFS = false; end
[folderPath,folderName,folderExt] = fileparts(ctf.folder);
ctf.res4.file = findres4file(ctf.folder);
%----------------------------------------------------------------
% open the data file
[fid,message] = fopen(ctf.res4.file,'rb','ieee-be.l64');
if fid < 0, error('cannot open .res4 file'); end
%-------------------------------------------------------------
% READ HEADER
fseek(fid,0,-1);
ctf.res4.header = char(fread(fid,8,'char'))';
% check for the right format
if strmatch('MEG41RS',ctf.res4.header),
% OK, we can handle this format
else
msg = sprintf('This function is designed to read MEG41RS format.\nIt may not read "%s" format correctly',ctf.res4.header);
warning(msg);
end
%-------------------------------------------------------------
% READ SETUP
%---DATE/TIME
fseek(fid, 778,-1);
ctf.setup.time = char(fread(fid,255,'char'))';
fseek(fid,1033,-1);
ctf.setup.date = char(fread(fid,255,'char'))';
%---NUMBER OF SAMPLES
fseek(fid,1288,-1);
ctf.setup.number_samples = (fread(fid,1,'int32')');
%---NUMBER OF CHANNELS
fseek(fid,1292,-1);
ctf.setup.number_channels = (fread(fid,1,'int16')');
%---SAMPLE RATE
fseek(fid,1296,-1);
ctf.setup.sample_rate = fread(fid,1,'double')';
ctf.setup.sample_msec = 1000 / ctf.setup.sample_rate;
ctf.setup.sample_sec = 1 / ctf.setup.sample_rate;
%---NUMBER OF TRIALS
fseek(fid,1312,-1);
ctf.setup.number_trials = fread(fid,1,'int16')';
fseek(fid, 776,-1);
ctf.setup.number_trials_averaged = fread(fid,1,'int16');
%---DURATION
fseek(fid,1304,-1);
ctf.setup.duration_total = fread(fid,1,'double');
ctf.setup.duration_trial = ctf.setup.duration_total / ctf.setup.number_trials;
%---PRE_TRIG POINTS
fseek(fid,1316,-1);
ctf.setup.pretrigger_samples = fread(fid,1,'int32');
ctf.setup.pretrigger_msec = (ctf.setup.pretrigger_samples / ctf.setup.sample_rate) * 1000;
%---HEAD ZEROING
fseek(fid,1348,-1);
h_zero = fread(fid,1,'int32')';
no_yes = {'no','yes'};
ctf.setup.head_zero = no_yes{h_zero+1};
%---RUN NAME
fseek(fid,1360,-1);
ctf.setup.run_name = char(fread(fid,32,'char'))';
%---RUN TITLE
fseek(fid,1392,-1);
ctf.setup.run_title = char(fread(fid,256,'char'))';
%---SUBJECT
fseek(fid,1712,-1);
ctf.setup.subject = char(fread(fid,32,'char'))';
%---OPERATOR
fseek(fid,1744,-1);
ctf.setup.operator = char(fread(fid,32,'char'))';
%---SENSOR FILE NAME
fseek(fid,1776,-1);
ctf.setup.sensor_file_name = char(fread(fid,60,'char'))';
%---RUN DESCRIPTION & FILTERS
fseek(fid,1836,-1);
run_size = fread(fid,1,'int32');
fseek(fid,1844,-1);
ctf.setup.run_description = char(fread(fid,run_size,'char'));
ctf.setup.number_filters = fread(fid,1,'int16');
for i = 1:ctf.setup.number_filters,
ctf.setup.filters(i).freq = fread(fid,1,'double');
ctf.setup.filters(i).class = fread(fid,1,'int32');
ctf.setup.filters(i).type = fread(fid,1,'int32');
ctf.setup.filters(i).numparam = fread(fid,1,'int16');
ctf.setup.filters(i).params = fread(fid,ctf.setup.filters(i).numparam,'double');
end
if(COEFS)
b = 1846 + run_size;
if(ctf.setup.number_filters == 0)
np = 0;
else
np = ctf.setup.filters.numparam;
warning('3rd gradient + hardware filter parameters not fully tested! let''s see what happens... :)');
end
nf = ctf.setup.number_filters;
f = ( nf * 18 ) + ( np * 8 );
offset = b + f + ctf.setup.number_channels * 1360;
end
%-------------------------------------------------------------
% CREATE TIME ARRAYS
% the time arrays must be based on increments of the sample_msec
ctf.setup.time_msec = [0:ctf.setup.number_samples - 1]' * ctf.setup.sample_msec;
ctf.setup.time_msec = ctf.setup.time_msec - ctf.setup.pretrigger_msec;
% adjust the sample point closest to zero so that it is zero, if it
% is reasonably close to zero, say within 3 decimal places for msec timing
zero_index = find(abs(ctf.setup.time_msec) == min(abs(ctf.setup.time_msec)));
zero_value = ctf.setup.time_msec(zero_index);
if (-0.0001 < zero_value) & (zero_value < 0.0001),
ctf.setup.time_msec(zero_index) = 0;
end
ctf.setup.start_msec = ctf.setup.time_msec(1);
ctf.setup.end_msec = ctf.setup.time_msec(end);
ctf.setup.time_sec = ctf.setup.time_msec / 1000;
ctf.setup.start_sec = ctf.setup.time_sec(1);
ctf.setup.end_sec = ctf.setup.time_sec(end);
%-------------------------------------------------------------
% PRINT SETUP
if VERBOSE,
ctf_print_setup(ctf);
end
%-------------------------------------------------------------
% READ SENSOR INFORMATION
ctf.sensor.info = struct(...
'proper_gain',[],...
'q_gain',[],...
'io_gain',[],...
'io_offset',[],...
'index',[],...
'extra',[],...
'label',[],...
'grad_order_no',[]);
% read channel names (not trivial!)
for chan = 1:ctf.setup.number_channels,
temp = fread(fid,32,'char');
temp(temp>127) = 0;
temp(temp<0) = 0;
temp = strtok(temp,char(0));
ctf.sensor.info(chan).label = char(temp');
end
for chan = 1:ctf.setup.number_channels,
%ftell(fid);
ctf.sensor.info(chan).index = fread(fid,1,'int16');
ctf.sensor.info(chan).extra = fread(fid,1,'int16');
id = fread(fid,1,'int32')+1;
ctf.sensor.info(chan).proper_gain = fread(fid,1,'double');
ctf.sensor.info(chan).q_gain = fread(fid,1,'double');
ctf.sensor.info(chan).io_gain = fread(fid,1,'double');
ctf.sensor.info(chan).io_offset = fread(fid,1,'double');
fread(fid,1,'int16');
ctf.sensor.info(chan).grad_order_no = fread(fid,1,'int16');
fread(fid,1,'int32');
%fseek(fid,ftell(fid)+6,0);
for pos = 1:8,
ctf.sensor.info(chan).coil(pos).position.x = fread(fid,1,'double');
ctf.sensor.info(chan).coil(pos).position.y = fread(fid,1,'double');
ctf.sensor.info(chan).coil(pos).position.z = fread(fid,1,'double');
fread(fid,1,'double');
ctf.sensor.info(chan).coil(pos).orient.x = fread(fid,1,'double');
ctf.sensor.info(chan).coil(pos).orient.y = fread(fid,1,'double');
ctf.sensor.info(chan).coil(pos).orient.z = fread(fid,1,'double');
fread(fid,1,'double');
fread(fid,1,'int16');
fread(fid,1,'int32');
fread(fid,1,'int16');
fread(fid,1,'double');
%fseek(fid,ftell(fid)+56,0);
%fseek(fid,ftell(fid)-80,0);
end
for pos = 1:8,
ctf.sensor.info(chan).hcoil(pos).position.x = fread(fid,1,'double');
ctf.sensor.info(chan).hcoil(pos).position.y = fread(fid,1,'double');
ctf.sensor.info(chan).hcoil(pos).position.z = fread(fid,1,'double');
fread(fid,1,'double');
ctf.sensor.info(chan).hcoil(pos).orient.x = fread(fid,1,'double');
ctf.sensor.info(chan).hcoil(pos).orient.y = fread(fid,1,'double');
ctf.sensor.info(chan).hcoil(pos).orient.z = fread(fid,1,'double');
fread(fid,1,'double');
fread(fid,1,'int16');
fread(fid,1,'int32');
fread(fid,1,'int16');
fread(fid,1,'double');
%fseek(fid,ftell(fid)+56,0);
%fseek(fid,ftell(fid)+80,0);
end
%fseek(fid,ftell(fid)+1288,-1);
end
%-------------------------------------------------------------
% Find channel types and define channel sets, see the
% System Administrators .pdf, 'Channel Sets Configuration'
ctf = ctf_channel_sets(ctf);
%-------------------------------------------------------------
% Channel coordinates, in centimeters, in subject head space
for chan = 1:ctf.setup.number_channels,
switch ctf.sensor.info(chan).index,
case {0,1,5},
%0=Reference Magnetometers
%1=Reference Gradiometers
%5=MEG Channels
coord = [ctf.sensor.info(chan).hcoil(1:2).position];
ctf.sensor.info(chan).location = [coord.x; coord.y; coord.z];
orient = [ctf.sensor.info(chan).hcoil(1).orient];
ctf.sensor.info(chan).orientation = [orient.x; orient.y; orient.z];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This ensures that the orientation of the sensor is away from the
% center of a sphere. It uses the sign of the dot product between
% the orientation vector and the location vector.
tmp = ctf.sensor.info(chan).orientation' * ctf.sensor.info(chan).location;
tmp = sign(tmp(1));
ctf.sensor.info(chan).orientation = tmp * ctf.sensor.info(chan).orientation;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 9,
%EEG Channels
coord = [ctf.sensor.info(chan).hcoil(1:2).position];
ctf.sensor.info(chan).location = [coord.x; coord.y; coord.z];
ctf.sensor.info(chan).orientation = [];
end
end
%%%%%% Coefficient reading appended by SSD %%%%%%
if(COEFS)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NUMBER OF COEFFICIENTS, byte offset = b+f+nc*1360, byte size = 1
fseek(fid,offset,-1);
ctf.res4.numberCoefficients = fread(fid,1,'int16');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SENSOR COEFFICIENT RECORDS, byte offset = b+f+nc*1360+2, byte size = 1992
if VERBOSE & ctf.res4.numberCoefficients,
fprintf('...reading %d coefficients\n',ctf.res4.numberCoefficients);
end
SENSOR_LABEL = 31;
MAX_NUM_COEFS = 50;
MAX_BALANCING = MAX_NUM_COEFS;
hexadef = {'00000000','47314252','47324252','47334252','47324f49','47334f49'};
strdef = {'NOGRAD','G1BR','G2BR','G3BR','G2OI','G3OI'};
for i = 1:ctf.res4.numberCoefficients,
% read the sensor name (channel label)
temp = fread(fid,[1,32],'char');
temp(temp>127) = 0;
temp(temp<0) = 0;
temp = strtok(temp,char(0));
temp = strtok(temp,'-');
sensorName = char(temp);
sensorIndex = strmatch( sensorName, {ctf.sensor.info.label} );
% read the coefficient type
coefType = fread(fid,1,'bit32');
padding = fread(fid,1,'int32'); % not sure why this is needed???
% read the coefficient record
numberCoefs = fread(fid,1,'int16');
if numberCoefs > MAX_NUM_COEFS,
msg = sprintf('numberCoefs > MAX_NUM_COEFS\n');
warning(msg);
end
sensor_list = char(fread(fid,[SENSOR_LABEL,MAX_BALANCING],'uchar')');
% clean-up the sensor_list
sensor_list = sensor_list(1:numberCoefs,:);
for j=1:numberCoefs,
temp = strtok(sensor_list(j,:),char(0));
temp = strtok(temp,'-');
% check if this sensor is a reference
refLabels = {ctf.sensor.info(ctf.sensor.index.meg_ref).label};
refIndex = strmatch(temp,refLabels);
if refIndex,
% ensure this one has the same label
temp = refLabels{refIndex};
end
new_sensor_list(j) = refIndex;
end
sensor_list = ctf.sensor.index.meg_ref(:,new_sensor_list)';
coefs_list = fread(fid,MAX_BALANCING,'double');
% clean-up the coefs_list
coefs_list = coefs_list(1:numberCoefs,:)';
% allocate the coefficient parameters into the ctf struct
ctf.res4.sensorCoef(i).sensorName = sensorName;
ctf.res4.sensorCoef(i).coefType = coefType;
ctf.res4.sensorCoef(i).coefRec.numberCoefs = numberCoefs;
ctf.res4.sensorCoef(i).coefRec.sensor_list = sensor_list;
ctf.res4.sensorCoef(i).coefRec.coefs_list = coefs_list;
% DLW:
% This is a brainstorm variable, note the use of coefType
% Not clear why this is checked and allocated as such
coefType = find( hex2dec(hexadef) == coefType );
if coefType,
CoefInfo{sensorIndex,coefType-1}.numberCoefs = numberCoefs;
CoefInfo{sensorIndex,coefType-1}.sensor_list = sensor_list;
CoefInfo{sensorIndex,coefType-1}.coefs = coefs_list;
end
end
% Channel Gains
gain_chan = zeros(size(ctf.setup.number_channels,1),1);
gain_chan(ctf.sensor.index.meg_sens) = ([ctf.sensor.info(ctf.sensor.index.meg_sens).proper_gain]'.*[ctf.sensor.info(ctf.sensor.index.meg_sens).q_gain]');
gain_chan(ctf.sensor.index.meg_ref) = ([ctf.sensor.info(ctf.sensor.index.meg_ref).proper_gain]'.*[ctf.sensor.info(ctf.sensor.index.meg_ref).q_gain]');
% gain_chan(ieegsens) = 1./([SensorRes(ieegsens).qGain]'*1e-6);
% gain_chan(ieegsens) = 1./([SensorRes(ieegsens).qGain]');
% gain_chan(iothersens) = ([SensorRes(iothersens).qGain]'); % Don't know exactly which gain to apply here
% Calculus of the matrix for nth-order gradient correction
% Coefficients for unused reference channels are weigthed by zeros in
% the correction matrix.
Gcoef = zeros(length(ctf.sensor.index.meg_sens),length(min(ctf.sensor.index.meg_ref):max(ctf.sensor.index.meg_ref)));
grad_order_no = 3*ones(306,1);
for k = 1:length(ctf.sensor.index.meg_sens)
% Reference coils for channel k
if grad_order_no(ctf.sensor.index.meg_sens(k)) == 0
%Data is saved as RAW
%Save 3rd order gradient sensor-list for subsequent correction if requested later by the user
[refs] = (CoefInfo{ctf.sensor.index.meg_sens(k),3}.sensor_list);
Gcoef(k,refs-min(ctf.sensor.index.meg_ref)+1) = CoefInfo{ctf.sensor.index.meg_sens(k),3}.coefs ...
.* gain_chan(refs)'/gain_chan(ctf.sensor.index.meg_sens(k));
else
[refs] = (CoefInfo{ctf.sensor.index.meg_sens(k),grad_order_no(ctf.sensor.index.meg_sens(k))}.sensor_list);
Gcoef(k,refs-min(ctf.sensor.index.meg_ref)+1) = CoefInfo{ctf.sensor.index.meg_sens(k),grad_order_no(ctf.sensor.index.meg_sens(k))}.coefs ...
.* gain_chan(refs)/gain_chan(ctf.sensor.index.meg_sens(k));
end
ctf.sensor.info(ctf.sensor.index.meg_sens(k)).Gcoef = Gcoef(k,:);
end
end %% end COEF block
fclose(fid);
t = toc; fprintf('...done (%6.2f sec)\n\n',t);
return
% find file name if truncated or with uppercase extension
% added by Arnaud Delorme June 15, 2004
% -------------------------------------------------------
function res4name = findres4file( folder )
res4name = dir([ folder filesep '*.res4' ]);
if isempty(res4name)
res4name = dir([ folder filesep '*.RES4' ]);
end
if isempty(res4name)
error('No file with extension .res4 or .RES4 in selected folder');
else
res4name = [ folder filesep res4name.name ];
end;
return
|
github
|
spm/spm5-master
|
spm_get_bf.m
|
.m
|
spm5-master/spm_get_bf.m
| 5,267 |
utf_8
|
9d28df048561f174ac8f95eae7f50f11
|
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 (secs)
% 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 specifiaction 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) 2005 Wellcome Department of Imaging Neuroscience
% Karl Friston
% $Id: spm_get_bf.m 112 2005-05-04 18:20:52Z john $
%-GUI setup
%-----------------------------------------------------------------------
spm_help('!ContextHelp',mfilename)
% 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 hemodynaic response function
%---------------------------------------------------------------
[bf p] = spm_hrf(dt);
% add time derivative
%---------------------------------------------------------------
if findstr(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 findstr(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
% Orthogonalize 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 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
|
spm/spm5-master
|
spm_resize_gui.m
|
.m
|
spm5-master/spm_resize_gui.m
| 481 |
utf_8
|
fa1e00d8d109dabf503b16c4d1b37fb1
|
% --- Executes when typeAssignmentPanel is resized.
function spm_ResizeFcn(hObject, eventdata, handles)
% hObject handle to typeAssignmentPanel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
children=findall(hObject);
for i=1:length(children)
if children(i)~=hObject
try
set(children(i), 'Position', get(children(i), 'Position'));
end
end
end
|
github
|
spm/spm5-master
|
spm_eeval.m
|
.m
|
spm5-master/spm_eeval.m
| 8,445 |
utf_8
|
26057e63a54232c519c4a78782d28e78
|
function [p,msg] = spm_eeval(str,Type,n,m)
% FORMAT [p,msg] = spm_eeval(str,Type,n,m)
% Expression evaluation
% 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) 2005 Wellcome Department of Imaging Neuroscience
% Andrew Holmes
% $Id: spm_eeval.m 112 2005-05-04 18:20:52Z john $
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(:)),setstr(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,setstr(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
|
spm/spm5-master
|
spm_config_display.m
|
.m
|
spm5-master/spm_config_display.m
| 4,639 |
utf_8
|
121b20a231bfbafa715cf64cdc9a4819
|
function opts = spm_config_display
% Configuration file for display jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_display.m 1032 2007-12-20 14:45:55Z john $
%_______________________________________________________________________
data.type = 'files';
data.name = 'Image to Display';
data.tag = 'data';
data.filter = 'image';
data.num = 1;
data.help = {'Image to display.'};
opts.type = 'branch';
opts.name = 'Display Image';
opts.tag = 'disp';
opts.val = {data};
opts.prog = @dispim;
p1 = [...
'This 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 millimetres 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 cross-hairs'...
' can also be moved by specifying the co-ordinates in millimetres 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 cross-hair position (in mm) to [0 0 0]).'];
p2 = [...
'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.'];
p3 = [...
'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.'];
p4 = [...
'The right panel shows miscellaneous information about the image.'...
' This includes:'];
p5 = [...
'There are also a few options for different resampling modes, zooms'...
' etc. You can also flip between voxel space (as would be displayed'...
' by Analyze) or world space (the orientation that SPM considers the'...
' image to be in). 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.'];
p6 = ['If you have put your images in the correct file format, ',...
'then (possibly after specifying some rigid-body rotations):'];
p7 = [' The top-left image is coronal with the top (superior) ',...
'of the head displayed at the top and the left shown on the left. ',...
'This is as if the subject is viewed from behind.'];
p8 = [' The bottom-left image is axial with the front (anterior) of the ',...
'head at the top and the left shown on the left. ',...
'This is as if the subject is viewed from above.'];
p9 = [' The top-right image is sagittal with the front (anterior) of ',...
'the head at the left and the top of the head shown at the top. ',...
'This is as if the subject is viewed from the left.'];
fg = ['/*',...
'\begin{figure} ',...
'\begin{center} ',...
'\includegraphics[width=150mm]{images/disp1} ',...
'\end{center} ',...
'\caption{The Display routine. \label{disp1}}',...
'\end{figure} */'];
opts.help = {p1,'',p2,'',p3,'',p4,...
' Dimensions - the x, y and z dimensions of the image.',...
' Datatype - the computer representation of each voxel.',...
' Intensity - scale-factors 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.'],...
'',p5,'','',p6,p7,p8,p9,fg};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function dispim(varargin)
job = varargin{1};
spm_image('init',job.data{1});
return;
|
github
|
spm/spm5-master
|
spm_segment.m
|
.m
|
spm5-master/spm_segment.m
| 24,271 |
utf_8
|
156a8af0663ed1ee884a52b0ecc11e1f
|
function [VO,M] = spm_segment(VF,PG,flags)
% Segment an MR image into Gray, White & CSF.
%
% FORMAT VO = spm_segment(PF,PG,flags)
% PF - name(s) of image(s) to segment (must have same dimensions).
% PG - name(s) of template image(s) for realignment.
% - or a 4x4 transformation matrix which maps from the image to
% the set of templates.
% flags - a structure normally based on defaults.segment
% VO - optional output volume
% M - affine transformation between template and image to segment
%
% The algorithm is four step:
%
% 1) Determine the affine transform which best matches the image with a
% template image. If the name of more than one image is passed, then
% the first image is used in this step. This step is not performed if
% no template images are specified.
%
% 2) Perform Cluster Analysis with a modified Mixture Model and a-priori
% information about the likelihoods of each voxel being one of a
% number of different tissue types. If more than one image is passed,
% then they they are all assumed to be in register, and the voxel
% values are fitted to multi-normal distributions.
%
% 3) Perform morphometric operations on the grey and white partitions
% in order to more accurately identify brain tissue. This is then used
% to clean up the grey and white matter segments.
%
% 4) If no or 2 output arguments is/are specified, then the segmented
% images are written to disk. The names of these images have "c1",
% "c2" & "c3" appended to the name of the first image passed. The
% 'brainmask' is also created with "BrMsk_" as an appendix.
%
%_______________________________________________________________________
% Refs:
%
% Ashburner J & Friston KJ (1997) Multimodal Image Coregistration and
% Partitioning - a Unified Framework. NeuroImage 6:209-217
%
%_______________________________________________________________________
%
% The template image, and a-priori likelihood images are modified
% versions of those kindly supplied by Alan Evans, MNI, Canada
% (ICBM, NIH P-20 project, Principal Investigator John Mazziotta).
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_segment.m 946 2007-10-15 16:36:06Z john $
% Create some suitable default values
%-----------------------------------------------------------------------
def_flags.estimate.priors = char(...
fullfile(spm('Dir'),'apriori','grey.nii'),...
fullfile(spm('Dir'),'apriori','white.nii'),...
fullfile(spm('Dir'),'apriori','csf.nii'));
def_flags.estimate.reg = 0.01;
def_flags.estimate.cutoff = 30;
def_flags.estimate.samp = 3;
def_flags.estimate.bb = [[-88 88]' [-122 86]' [-60 95]'];
def_flags.estimate.affreg.smosrc = 8;
def_flags.estimate.affreg.regtype = 'mni';
def_flags.estimate.affreg.weight = '';
def_flags.write.cleanup = 1;
def_flags.write.wrt_cor = 1;
def_flags.write.wrt_brV = 0;
def_flags.graphics = 1;
if nargin<3, flags = def_flags; end;
if ~isfield(flags,'estimate'), flags.estimate = def_flags.estimate; end;
if ~isfield(flags.estimate,'priors'), flags.estimate.priors = def_flags.estimate.priors; end;
if ~isfield(flags.estimate,'reg'), flags.estimate.reg = def_flags.estimate.reg; end;
if ~isfield(flags.estimate,'cutoff'), flags.estimate.cutoff = def_flags.estimate.cutoff; end;
if ~isfield(flags.estimate,'samp'), flags.estimate.samp = def_flags.estimate.samp; end;
if ~isfield(flags.estimate,'bb'), flags.estimate.bb = def_flags.estimate.bb; end;
if ~isfield(flags.estimate,'affreg'), flags.estimate.affreg = def_flags.estimate.affreg; end;
if ~isfield(flags.estimate.affreg,'smosrc'),
flags.estimate.affreg.smosrc = def_flags.estimate.affreg.smosrc;
end;
if ~isfield(flags.estimate.affreg,'regtype'),
flags.estimate.affreg.regtype = def_flags.estimate.affreg.regtype;
end;
if ~isfield(flags.estimate.affreg,'weight'),
flags.estimate.affreg.weight = def_flags.estimate.affreg.weight;
end;
if ~isfield(flags,'write'), flags.write = def_flags.write; end;
if ~isfield(flags.write,'cleanup'), flags.write.cleanup = def_flags.write.cleanup; end;
if ~isfield(flags.write,'wrt_cor'), flags.write.wrt_cor = def_flags.write.wrt_cor; end;
if ~isfield(flags.write,'wrt_brV'), flags.write.wrt_brV = def_flags.write.wrt_brV; end;
if ~isfield(flags,'graphics'), flags.graphics = def_flags.graphics; end;
%-----------------------------------------------------------------------
if ischar(VF), VF= spm_vol(VF); end;
SP = init_sp(flags.estimate,VF,PG);
[x1,x2,x3] = get_sampling(SP.MM,VF,flags.estimate.samp,flags.estimate.bb);
BP = init_bp(VF, flags.estimate.cutoff, flags.estimate.reg);
CP = init_cp(VF,x3);
sums = zeros(8,1);
for pp=1:length(x3),
[raw,msk] = get_raw(VF,x1,x2,x3(pp));
s = get_sp(SP,x1,x2,x3(pp));
CP = update_cp_est(CP,s,raw,msk,pp);
sums = sums + reshape(sum(sum(s,1),2),8,1);
end;
sums = sums/sum(sums);
CP = shake_cp(CP);
[CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3);
%save segmentation_results.mat CP BP SP VF sums
[g,w,c] = get_gwc(VF,BP,SP,CP,sums,flags.write.wrt_cor);
if flags.write.cleanup, [g,w,c,b] = clean_gwc(g,w,c); end;
% Create the segmented images + the brain mask.
%-----------------------------------------------------------------------
%offs = cumsum(repmat(prod(VF(1).dim(1:2)),1,VF(1).dim(3)))-prod(VF(1).dim(1:2));
%pinfo = [repmat([1/255 0]',1,VF(1).dim(3)) ; offs];
[pth,nm,xt] = fileparts(deblank(VF(1).fname));
if flags.write.wrt_brV
Nwrt = 4;
else
Nwrt = 3;
end
for j=1:Nwrt,
tmp = fullfile(pth,['c', num2str(j), nm, xt]);
if j==4, tmp = fullfile(pth,['BrMsk_', nm xt]); end
VO(j) = struct(...
'fname',tmp,...
'dim', VF(1).dim(1:3),...
'dt', [spm_type('uint8'), spm_platform('bigend')],...
'mat', VF(1).mat,...
'pinfo', [1/255 0 0]',...
'descrip','Segmented image');
end;
if nargout==0 || nargout==2,
VO = spm_create_vol(VO);
spm_progress_bar('Init',VF(1).dim(3),'Writing Segmented','planes completed');
for pp=1:VF(1).dim(3),
VO(1) = spm_write_plane(VO(1),double(g(:,:,pp))/255,pp);
VO(2) = spm_write_plane(VO(2),double(w(:,:,pp))/255,pp);
VO(3) = spm_write_plane(VO(3),double(c(:,:,pp))/255,pp);
if flags.write.wrt_brV
VO(4) = spm_write_plane(VO(4),double(b(:,:,pp))/255,pp);
end
spm_progress_bar('Set',pp);
end;
spm_progress_bar('Clear');
end;
VO(1).dat = g; VO(1).pinfo = VO(1).pinfo(1:2,:);
VO(2).dat = w; VO(2).pinfo = VO(2).pinfo(1:2,:);
VO(3).dat = c; VO(3).pinfo = VO(3).pinfo(1:2,:);
if flags.write.wrt_brV
VO(4).dat = b; VO(4).pinfo = VO(4).pinfo(1:2,:);
end
if nargout==2
M = SP.MM/VF(1).mat;
end
if flags.graphics, display_graphics(VF,VO,CP.mn,CP.cv,CP.mg); end;
return;
%=======================================================================
%=======================================================================
function [y1,y2,y3] = affine_transform(x1,x2,x3,M)
y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);
y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);
y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);
return;
%=======================================================================
%=======================================================================
function display_graphics(VF,VS,mn,cv,mg)
% Do the graphics
nb = 3;
spm_figure('Clear','Graphics');
fg = spm_figure('FindWin','Graphics');
if ~isempty(fg),
% Show some text
%-----------------------------------------------------------------------
ax = axes('Position',[0.05 0.8 0.9 0.2],'Visible','off','Parent',fg);
text(0.5,0.80, 'Segmentation','FontSize',16,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
text(0,0.65, ['Image: ' spm_str_manip(VF(1).fname,'k50d')],...
'FontSize',14,'FontWeight','Bold','Parent',ax);
text(0,0.40, 'Means:','FontSize',12,'FontWeight','Bold','Parent',ax);
text(0,0.30, 'Std devs:' ,'FontSize',12,'FontWeight','Bold','Parent',ax);
text(0,0.20, 'N vox:','FontSize',12,'FontWeight','Bold','Parent',ax);
for j=1:nb,
text((j+0.5)/(nb+1),0.40, num2str(mn(1,j)),...
'FontSize',12,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
text((j+0.5)/(nb+1),0.30, num2str(sqrt(cv(1,1,j))),...
'FontSize',12,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
text((j+0.5)/(nb+1),0.20, num2str(mg(1,j)/sum(mg(1,:))),...
'FontSize',12,'FontWeight','Bold',...
'HorizontalAlignment','center','Parent',ax);
end;
if length(VF) > 1,
text(0,0.10,...
'Note: only means and variances for the first image are shown',...
'Parent',ax,'FontSize',12);
end;
M1 = VS(1).mat;
M2 = VF(1).mat;
for i=1:5,
M = spm_matrix([0 0 i*VF(1).dim(3)/6]);
img = spm_slice_vol(VF(1),M,VF(1).dim(1:2),1);
img(1,1) = eps;
ax = axes('Position',...
[0.05 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...
'Visible','off','Parent',fg);
imagesc(rot90(img), 'Parent', ax);
set(ax,'Visible','off','DataAspectRatio',[1 1 1]);
for j=1:3,
img = spm_slice_vol(VS(j),M2\M1*M,VF(1).dim(1:2),1);
ax = axes('Position',...
[0.05+j*0.9/(nb+1) 0.75*(1-i/5)+0.05 0.9/(nb+1) 0.75/5],...
'Visible','off','Parent',fg);
image(rot90(img*64), 'Parent', ax);
set(ax,'Visible','off','DataAspectRatio',[1 1 1]);
end;
end;
spm_print;
drawnow;
end;
return;
%=======================================================================
%=======================================================================
function M = get_affine_mapping(VF,VG,aflags)
if ~isempty(VG) && ischar(VG), VG = spm_vol(VG); end;
if ~isempty(VG) && isstruct(VG),
% Affine registration so that a priori images match the image to
% be segmented.
%-----------------------------------------------------------------------
VFS = spm_smoothto8bit(VF(1),aflags.smosrc);
% Scale all images approximately equally
% ---------------------------------------------------------------
for i=1:length(VG),
VG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i));
end;
VFS(1).pinfo(1:2,:) = VFS(1).pinfo(1:2,:)/spm_global(VFS(1));
spm_chi2_plot('Init','Affine Registration','Mean squared difference','Iteration');
flags = struct('sep',aflags.smosrc, 'regtype',aflags.regtype,'WG',[],'globnorm',0,'debug',0);
M = eye(4);
[M,scal] = spm_affreg(VG, VFS, flags, M);
if ~isempty(aflags.weight), flags.WG = spm_vol(aflags.weight); end;
flags.sep = aflags.smosrc/2;
M = spm_affreg(VG, VFS, flags, M,scal);
spm_chi2_plot('Clear');
elseif all(size(VG) == [4 4])
% Assume that second argument is a matrix that will do the job
%-----------------------------------------------------------------------
M = VG;
else
% Assume that image is normalized
%-----------------------------------------------------------------------
M = eye(4);
end
return;
%=======================================================================
%=======================================================================
function [x1,x2,x3] = get_sampling(MM,VF,samp,bb1)
% Voxels to sample during the cluster analysis
%-----------------------------------------------------------------------
% A bounding box for the brain in Talairach space.
%bb = [ [-88 88]' [-122 86]' [-60 95]'];
%c = [bb(1,1) bb(1,2) bb(1,3) 1
% bb(1,1) bb(1,2) bb(2,3) 1
% bb(1,1) bb(2,2) bb(1,3) 1
% bb(1,1) bb(2,2) bb(2,3) 1
% bb(2,1) bb(1,2) bb(1,3) 1
% bb(2,1) bb(1,2) bb(2,3) 1
% bb(2,1) bb(2,2) bb(1,3) 1
% bb(2,1) bb(2,2) bb(2,3) 1]';
%tc = MM\c;
%tc = tc(1:3,:)';
%mx = max(tc);
%mn = min(tc);
%bb = [mn ; mx];
%vx = sqrt(sum(VF(1).mat(1:3,1:3).^2));
%samp = round(max(abs([4 4 4]./vx), [1 1 1]));
%x1 = bb(1,1):samp(1):bb(2,1);
%x2 = bb(1,2):samp(2):bb(2,2);
%x3 = bb(1,3):samp(3):bb(2,3);
%return;
% A bounding box for the brain in Talairach space.
if nargin<4, bb1 = [ [-88 88]' [-122 86]' [-60 95]']; end;
% A mapping from a unit radius sphere to a hyper-ellipse
% that is just enclosed by the bounding box in Talairach
% space.
M0 = [diag(diff(bb1)/2) mean(bb1)';[0 0 0 1]];
% The mapping from voxels to Talairach space is MM,
% so the ellipse in the space of the image becomes:
M0 = MM\M0;
% So to work out the bounding box in the space of the
% image that just encloses the hyper-ellipse.
tmp = M0(1:3,1:3);
tmp = diag(tmp*tmp'/diag(sqrt(diag(tmp*tmp'))));
bb = round([M0(1:3,4)-tmp M0(1:3,4)+tmp])';
bb = min(max(bb,[1 1 1 ; 1 1 1]),[VF(1).dim(1:3) ; VF(1).dim(1:3)]);
% Want to sample about every 3mm
tmp = sqrt(sum(VF(1).mat(1:3,1:3).^2))';
samp = round(max(abs(tmp.^(-1)*samp), [1 1 1]'));
x1 = bb(1,1):samp(1):bb(2,1);
x2 = bb(1,2):samp(2):bb(2,2);
x3 = bb(1,3):samp(3):bb(2,3);
return;
%=======================================================================
%=======================================================================
function [CP,BP,SP] = run_segment(CP,BP,SP,VF,sums,x1,x2,x3)
oll = -Inf;
spm_chi2_plot('Init','Segmenting','Log-likelihood','Iteration #');
for iter = 1:64,
ll= 0;
for pp = 1:length(x3), % Loop over planes
bf = get_bp(BP,x1,x2,x3(pp));
[raw,msk] = get_raw(VF,x1,x2,x3(pp));
s = get_sp(SP,x1,x2,x3(pp));
cor = bf.*raw;
[P,ll0] = get_p(cor,msk,s,sums,CP,bf);
ll = ll + ll0;
CP = update_cp_est(CP,P,cor,msk,pp);
BP = update_bp_est(BP,P,cor,CP,msk,x1,x2,x3(pp));
end;
BP = update_bp(BP);
if iter>1, spm_chi2_plot('Set',ll); end;
%fprintf('\t%g\n', ll);
% Stopping criterion
%-----------------------------------------------------------------------
if iter == 2,
ll2 = ll;
elseif iter > 2 && abs((ll-oll)/(ll-ll2)) < 0.0001
break;
end;
oll = ll;
end;
spm_chi2_plot('Clear');
return;
%=======================================================================
%=======================================================================
function BP = init_bp(VF,co,reg)
m = length(VF);
tmp = sqrt(sum(VF(1).mat(1:3,1:3).^2));
BP.nbas = max(round((VF(1).dim(1:3).*tmp)/co),[1 1 1]);
BP.B1 = spm_dctmtx(VF(1).dim(1),BP.nbas(1));
BP.B2 = spm_dctmtx(VF(1).dim(2),BP.nbas(2));
BP.B3 = spm_dctmtx(VF(1).dim(3),BP.nbas(3));
nbas = BP.nbas;
if prod(BP.nbas)>1,
% Set up a priori covariance matrix
vx = sqrt(sum(VF(1).mat(1:3,1:3).^2));
kx=(pi*((1:nbas(1))'-1)*pi/vx(1)/VF(1).dim(1)*10).^2;
ky=(pi*((1:nbas(2))'-1)*pi/vx(2)/VF(1).dim(2)*10).^2;
kz=(pi*((1:nbas(3))'-1)*pi/vx(3)/VF(1).dim(3)*10).^2;
% Cost function based on sum of squares of 4th derivatives
IC0 = (1*kron(kz.^4,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^4,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^4)) +...
4*kron(kz.^3,kron(ky.^1,kx.^0)) +...
4*kron(kz.^3,kron(ky.^0,kx.^1)) +...
4*kron(kz.^1,kron(ky.^3,kx.^0)) +...
4*kron(kz.^0,kron(ky.^3,kx.^1)) +...
4*kron(kz.^1,kron(ky.^0,kx.^3)) +...
4*kron(kz.^0,kron(ky.^1,kx.^3)) +...
6*kron(kz.^2,kron(ky.^2,kx.^0)) +...
6*kron(kz.^2,kron(ky.^0,kx.^2)) +...
6*kron(kz.^0,kron(ky.^2,kx.^2)) +...
12*kron(kz.^2,kron(ky.^1,kx.^1)) +...
12*kron(kz.^1,kron(ky.^2,kx.^1)) +...
12*kron(kz.^1,kron(ky.^1,kx.^2)) )*reg;
%IC0(1) = max(IC0);
BP.IC0 = diag(IC0(2:end));
% Initial estimate for intensity modulation field
BP.T = zeros(nbas(1),nbas(2),nbas(3),length(VF));
%-----------------------------------------------------------------------
else
BP.T = zeros([1 1 1 length(VF)]);
BP.IC0 = [];
end;
BP.Alpha = zeros(prod(BP.nbas(1:3)),prod(BP.nbas(1:3)),m);
BP.Beta = zeros(prod(BP.nbas(1:3)),m);
return;
%=======================================================================
%=======================================================================
function BP = update_bp_est(BP,p,cor,CP,msk,x1,x2,x3)
if prod(BP.nbas)<=1, return; end;
B1 = BP.B1(x1,:);
B2 = BP.B2(x2,:);
B3 = BP.B3(x3,:);
for j=1:size(BP.Alpha,3),
cr = cor(:,:,j);
w1 = zeros(size(cr));
w2 = zeros(size(cr));
for i=[1 2 3 4 5 6 7 8],
tmp = p(:,:,i)*CP.cv(j,j,i)^(-1);
w1 = w1 + tmp.*(CP.mn(j,i) - cr);
w2 = w2 + tmp;
end;
wt1 = 1 + cr.*w1;
wt2 = cr.*(cr.*w2 - w1);
wt1(~msk) = 0;
wt2(~msk) = 0;
BP.Beta(:,j) = BP.Beta(:,j) + kron(B3',spm_krutil(wt1,B1,B2,0));
BP.Alpha(:,:,j) = BP.Alpha(:,:,j) + kron(B3'*B3,spm_krutil(wt2,B1,B2,1));
end;
return;
%=======================================================================
%=======================================================================
function BP = update_bp(BP)
if prod(BP.nbas)<=1, return; end;
for j=1:size(BP.Alpha,3),
x = BP.T(:,:,:,j);
x = x(:);
x = x(2:end);
Alpha = BP.Alpha(2:end,2:end,j);
Beta = BP.Beta(2:end,j);
x = (Alpha + BP.IC0)\(Alpha*x + Beta);
BP.T(:,:,:,j) = reshape([0 ; x],BP.nbas(1:3));
BP.Alpha = zeros(size(BP.Alpha));
BP.Beta = zeros(size(BP.Beta));
end;
return;
%=======================================================================
%=======================================================================
function bf = get_bp(BP,x1,x2,x3)
bf = ones(length(x1),length(x2),size(BP.Alpha,3));
if prod(BP.nbas)<=1, return; end;
B1 = BP.B1(x1,:);
B2 = BP.B2(x2,:);
B3 = BP.B3(x3,:);
for i=1:size(BP.Alpha,3),
t = reshape(reshape(BP.T(:,:,:,i),...
BP.nbas(1)*BP.nbas(2),BP.nbas(3))*B3', BP.nbas(1), BP.nbas(2));
bf(:,:,i) = exp(B1*t*B2');
end;
return;
%=======================================================================
%=======================================================================
function [dat,msk] = get_raw(VF,x1,x2,x3)
[X1,X2,X3] = ndgrid(x1,x2,x3);
for i=1:length(VF),
[Y1,Y2,Y3] = affine_transform(X1,X2,X3,VF(i).mat\VF(1).mat);
dat(:,:,i) = spm_sample_vol(VF(i),Y1,Y2,Y3,1);
end;
msk = all(dat,3) & all(isfinite(double(dat)),3);
return;
%=======================================================================
%=======================================================================
function CP = init_cp(VF,x3)
n = 8;
m = length(VF);
p = length(x3);
CP.mom0 = zeros(1,n,p)+eps;
CP.mom1 = zeros(m,n,p);
CP.mom2 = zeros(m,m,n,p)+eps;
% Occasionally the dynamic range of the images is such that many voxels
% all have the same intensity. Adding cv0 is an attempt to improve the
% stability of the algorithm if this occurs. The value 0.083 was obtained
% from var(rand(1000000,1)). It prbably isn't the best way of doing
% things, but it appears to work.
CP.cv0 = zeros(m,m);
for i=1:m,
if spm_type(VF(i).dt(1),'intt'),
CP.cv0(i,i)=0.083*mean(VF(i).pinfo(1,:));
end;
end;
return;
%=======================================================================
%=======================================================================
function CP = shake_cp(CP)
CP.mom0(:,5,:) = CP.mom0(:,1,:);
CP.mom0(:,6,:) = CP.mom0(:,2,:);
CP.mom0(:,7,:) = CP.mom0(:,3,:);
CP.mom1(:,5,:) = CP.mom1(:,1,:);
CP.mom1(:,6,:) = CP.mom1(:,2,:);
CP.mom1(:,7,:) = CP.mom1(:,3,:);
CP.mom1(:,8,:) = 0;
CP.mom2(:,:,5,:) = CP.mom2(:,:,1,:);
CP.mom2(:,:,6,:) = CP.mom2(:,:,2,:);
CP.mom2(:,:,7,:) = CP.mom2(:,:,3,:);
return;
%=======================================================================
%=======================================================================
function CP = update_cp_est(CP,P,dat,msk,p)
m = size(dat,3);
d = size(P);
P = reshape(P,[d(1)*d(2),d(3)]);
dat = reshape(dat,[d(1)*d(2),m]);
P(~msk(:),:) = [];
dat(~msk(:),:) = [];
for i=1:size(CP.mom0,2),
CP.mom0(1,i,p) = sum(P(:,i));
CP.mom1(:,i,p) = sum((P(:,i)*ones(1,m)).*dat)';
CP.mom2(:,:,i,p) = ((P(:,i)*ones(1,m)).*dat)'*dat;
end;
for i=1:size(CP.mom0,2),
CP.mg(1,i) = sum(CP.mom0(1,i,:),3);
CP.mn(:,i) = sum(CP.mom1(:,i,:),3)/CP.mg(1,i);
tmp = (CP.mg(1,i).*CP.mn(:,i))*CP.mn(:,i)';
tmp = tmp-eye(size(tmp))*eps*1e6;
CP.cv(:,:,i) = (sum(CP.mom2(:,:,i,:),4) - tmp)/CP.mg(1,i) + CP.cv0;
end;
CP.mg = CP.mg/sum(CP.mg);
return;
%=======================================================================
%=======================================================================
function [p,ll] = get_p(cor,msk,s,sums,CP,bf)
d = [size(cor) 1 1];
n = size(CP.mg,2);
cor = reshape(cor,d(1)*d(2),d(3));
cor = cor(msk,:);
p = zeros(d(1)*d(2),n);
if ~any(msk), p = reshape(p,d(1),d(2),n); ll=0; return; end;
for i=1:n,
amp = 1/sqrt((2*pi)^d(3) * det(CP.cv(:,:,i)));
dst = (cor-ones(size(cor,1),1)*CP.mn(:,i)')/sqrtm(CP.cv(:,:,i));
dst = sum(dst.*dst,2);
tmp = s(:,:,i);
p(msk,i) = (amp*CP.mg(1,i)/sums(i))*exp(-0.5*dst).*tmp(msk) +eps;
end;
sp = sum(p,2);
ll = sum(log(sp(msk).*bf(msk)+eps));
sp(~msk) = Inf;
for i=1:n, p(:,i) = p(:,i)./sp; end;
p = reshape(p,d(1),d(2),n);
return;
%=======================================================================
%=======================================================================
function SP = init_sp(flags,VF,PG)
SP.VB = spm_vol(flags.priors);
MM = get_affine_mapping(VF,PG,flags.affreg);
%VF = spm_vol(PF);
SP.MM = MM*VF(1).mat;
SP.w = 0.98;
return;
%=======================================================================
%=======================================================================
function s = get_sp(SP,x1,x2,x3)
[X1,X2,X3] = ndgrid(x1,x2,x3);
[Y1,Y2,Y3] = affine_transform(X1,X2,X3,SP.VB(1).mat\SP.MM);
w1 = SP.w;
w2 = (1-w1)/2;
s = zeros([size(Y1),4]);
for i=1:3,
s(:,:,i) = spm_sample_vol(SP.VB(i),Y1,Y2,Y3,1)*w1+w2;
end;
s(:,:,4:8) = repmat(abs(1-sum(s(:,:,1:3),3))/5,[1 1 5]);
return;
%=======================================================================
%=======================================================================
function [g,w,c] = get_gwc(VF,BP,SP,CP,sums,wc)
if wc,
VC = VF;
for j=1:length(VF),
[pth,nm,xt,vr] = spm_fileparts(deblank(VF(j).fname));
VC(j).fname = fullfile(pth,['m' nm xt vr]);
VC(j).descrip = 'Bias corrected image';
end;
VC = spm_create_vol(VC);
end;
spm_progress_bar('Init',VF(1).dim(3),'Creating Segmented','planes completed');
x1 = 1:VF(1).dim(1);
x2 = 1:VF(1).dim(2);
x3 = 1:VF(1).dim(3);
g = uint8(0); g(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;
w = uint8(0); w(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;
c = uint8(0); c(VF(1).dim(1),VF(1).dim(2),VF(1).dim(3)) = 0;
for pp=1:length(x3),
bf = get_bp(BP,x1,x2,x3(pp));
[raw,msk] = get_raw(VF,x1,x2,x3(pp));
cor = raw.*bf;
if wc,
for j=1:length(VC),
VC(j) = spm_write_plane(VC(j),cor(:,:,j),pp);
end;
end;
s = get_sp(SP,x1,x2,x3(pp));
p = get_p(cor,msk,s,sums,CP,bf);
g(:,:,pp) = uint8(round(p(:,:,1)*255));
w(:,:,pp) = uint8(round(p(:,:,2)*255));
c(:,:,pp) = uint8(round(p(:,:,3)*255));
spm_progress_bar('Set',pp);
end;
spm_progress_bar('Clear');
return;
%=======================================================================
%=======================================================================
function [g,w,c,b] = clean_gwc(g,w,c)
b = w;
b(1) = w(1);
% Build a 3x3x3 seperable smoothing kernel
%-----------------------------------------------------------------------
kx=[0.75 1 0.75];
ky=[0.75 1 0.75];
kz=[0.75 1 0.75];
sm=sum(kron(kron(kz,ky),kx))^(1/3);
kx=kx/sm; ky=ky/sm; kz=kz/sm;
% Erosions and conditional dilations
%-----------------------------------------------------------------------
niter = 32;
spm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');
for j=1:niter,
if j>2, th=0.15; else th=0.6; end; % Dilate after two its of erosion.
for i=1:size(b,3),
gp = double(g(:,:,i));
wp = double(w(:,:,i));
bp = double(b(:,:,i))/255;
bp = (bp>th).*(wp+gp);
b(:,:,i) = uint8(round(bp));
end;
spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);
spm_progress_bar('Set',j);
end;
th = 0.05;
for i=1:size(b,3),
gp = double(g(:,:,i))/255;
wp = double(w(:,:,i))/255;
cp = double(c(:,:,i))/255;
bp = double(b(:,:,i))/255;
bp = ((bp>th).*(wp+gp))>th;
g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));
w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));
c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));
b(:,:,i) = uint8(round(255*bp));
end;
spm_progress_bar('Clear');
return;
|
github
|
spm/spm5-master
|
spm_config_cd.m
|
.m
|
spm5-master/spm_config_cd.m
| 1,166 |
utf_8
|
87ed5d6149a086f5d922fb7be08d85d3
|
function opts = spm_config_cd
% Configuration file for changing directory function
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Darren Gitelman
% $Id: spm_config_cd.m 587 2006-08-07 04:38:22Z Darren $
data.type = 'files';
data.name = 'Select a directory';
data.tag = 'directory';
data.filter = 'dir';
data.num = 1;
data.help = {'Select a directory to change to.'};
opts.type = 'branch';
opts.name = 'Change Directory';
opts.tag = 'cdir';
opts.val = {data};
opts.prog = @my_job_cd;
p1 = [...
'This facilty allows programming a directory change. Directories are ',...
'selected in the right listbox.'];
opts.help = {p1};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function my_job_cd(varargin)
% job can be a job structure or the directory to change to.
job = varargin{1};
if isstruct(job)
jobDir = job.directory;
else
jobDir = job;
end
if ~isempty(jobDir),
cd(char(jobDir));
fprintf('New working directory: %s\n', char(jobDir));
end;
return;
|
github
|
spm/spm5-master
|
spm_bias_estimate.m
|
.m
|
spm5-master/spm_bias_estimate.m
| 6,359 |
utf_8
|
418562b13c25a375ce47e36d439200a8
|
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) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_bias_estimate.m 184 2005-05-31 13:23:32Z john $
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
|
spm/spm5-master
|
spm_eeg_conman.m
|
.m
|
spm5-master/spm_eeg_conman.m
| 25,044 |
utf_8
|
05a1b8c0a88b56c840fba328224b016f
|
function varargout = spm_eeg_conman(varargin)
% internal function that allows to enter componentwise contrast weights.
% FORMAT varargout = spm_eeg_conman(varargin)
%
%_______________________________________________________________________
%
% The following comments are generated by the matlab guide-system:
% SPM_EEG_CONMAN M-file for spm_eeg_conman.fig
% SPM_EEG_CONMAN, by itself, creates a new SPM_EEG_CONMAN or raises the existing
% singleton*.
%
% H = SPM_EEG_CONMAN returns the handle to a new SPM_EEG_CONMAN or the handle to
% the existing singleton*.
%
% SPM_EEG_CONMAN('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SPM_EEG_CONMAN.M with the given input arguments.
%
% SPM_EEG_CONMAN('Property','Value',...) creates a new SPM_EEG_CONMAN or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before spm_eeg_conman_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to spm_eeg_conman_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help spm_eeg_conman
% Last Modified by GUIDE v2.5 18-Dec-2003 14:21:19
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Stefan Kiebel
% $Id: spm_eeg_conman.m 539 2006-05-19 17:59:30Z Darren $
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @spm_eeg_conman_OpeningFcn, ...
'gui_OutputFcn', @spm_eeg_conman_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin & isstr(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before spm_eeg_conman is made visible.
function spm_eeg_conman_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to spm_eeg_conman (see VARARGIN)
% Choose default command line output for spm_eeg_conman
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% start of own code
if length(varargin) == 0
try
% called from contrast manager?
h = findobj('Tag','ConMan');
SPM = get(h, 'UserData');
catch
P = spm_select(1,'^SPM\.mat$','Select SPM.mat');
load(P);
end
else
SPM = varargin{1};
end
% SPM colour scheme:
% background: [0.7 0.7 0.7]
% edit window background [0.8 0.8 1]
% buttons: blue: [0 0 1]
% red: [1 0 0]
% green: [0 1 0]
% magenta: [1 0 1]
colour.background = [0.7 0.7 0.7];
set(handles.conman_eeg, 'Color', colour.background);
% code for re-sizing to actual screen size
WS = spm('WinScale'); %-Window scaling factors
FS = spm('FontSizes'); %-Scaled font sizes
PF = spm_platform('fonts'); %-Font names (for this platform)
if spm_matlab_version_chk('7') >= 0 %-Screen size
S0 = get(0, 'MonitorPosition');
S0 = S0(1,:);
else
S0 = get(0,'ScreenSize');
end;
names = fieldnames(handles);
for i = 1:length(names)
if ~strcmpi(names{i}, 'output')
h = eval(sprintf('handles.%s;', names{i}));
if length(h) == 1 & isnumeric(h)
set(h, 'Position', get(h, 'Position').*WS);
if ~strcmpi(get(h, 'Type'), 'figure')
if strcmpi(get(h, 'Style'), 'Edit') | strcmpi(get(h, 'Style'), 'PushButton') | strcmpi(get(h, 'Style'), 'RadioButton')
eval(sprintf('set(handles.%s, ''FontSize'', FS(9));', names{i}));
else
eval(sprintf('set(handles.%s, ''FontSize'', FS(10));', names{i}));
end
end
end
end
end
if ~isfield(SPM, 'eeg')
error('No design components found. Use the EEG model setup.');
return;
end
handles.current_data = SPM;
guidata(hObject, handles);
% find out whether user wants t- or F-contrast weights
if get(findobj('Tag', 'D_TF', 'String', 't-contrast'), 'Value')
STAT = 'T';
elseif get(findobj('Tag', 'D_TF', 'String', 'F-contrast'), 'Value')
STAT = 'F';
else
error('Could not identify STAT');
end
Mfactor = 8;
if SPM.eeg.Nfactors > Mfactor
error('The component editor cannot handle more than 8 factors');
end
% adjust appearance to number of factors
%-----------------------------------------
% Hide uicontrols
s = [1:SPM.eeg.Nfactors];
for i = 1:Mfactor
if ~ismember(i, s)
eval(sprintf('set(handles.factor%d, ''Visible'', ''off'')', i))
eval(sprintf('set(handles.factor%d_title, ''Visible'', ''off'')', i))
eval(sprintf('set(handles.project%d, ''Visible'', ''off'')', i))
eval(sprintf('set(handles.Generate%d, ''Visible'', ''off'')', i))
else
if strcmpi(STAT, 'T')
eval(sprintf('set(handles.factor%d, ''Max'', 1)', i))
else
eval(sprintf('set(handles.factor%d, ''Max'', 2)', i))
end
% 'project' radiobuttons
if strcmpi(SPM.eeg.factor{i}, 'time')
eval(sprintf('set(handles.project%d, ''Value'', get(handles.project%d, ''Max''))', i, i))
end
% make buttons invisible, if design component identity or constant
% exception for identity compoment which is titled 'time', i.e.
% time factor in conventional design
if strcmpi(SPM.xBF.name_d{1, i}, 'Identity') | strcmpi(SPM.xBF.name_d{1, i}, 'Constant')
eval(sprintf('set(handles.project%d, ''Visible'', ''off'')', i))
if ~strcmpi(SPM.eeg.factor{i}, 'time')
eval(sprintf('set(handles.Generate%d, ''Visible'', ''off'')', i))
end
end
end
end
eval(sprintf('pos1 = get(handles.factor%d, ''Position'');', Mfactor));
eval(sprintf('pos3 = get(handles.factor%d, ''Position'');', SPM.eeg.Nfactors));
dy = pos3(2) - pos1(2);
if dy > 0
% adjust axes and uicontrols
% figure
pos = get(handles.conman_eeg, 'Position');
pos(4) = pos(4) - dy;
set(handles.conman_eeg, 'Position', pos);
% contrast input windows
for i = 1:SPM.eeg.Nfactors
eval(sprintf('pos = get(handles.factor%d, ''Position'');', i));
pos(2) = pos(2) - dy;
eval(sprintf('set(handles.factor%d, ''Position'', [%f %f %f %f]);', i, pos(1), pos(2), pos(3), pos(4)))
eval(sprintf('pos = get(handles.factor%d_title, ''Position'');', i));
pos(2) = pos(2) - dy;
eval(sprintf('set(handles.factor%d_title, ''Position'', [%f %f %f %f]);', i, pos(1), pos(2), pos(3), pos(4)))
eval(sprintf('pos = get(handles.project%d, ''Position'');', i));
pos(2) = pos(2) - dy;
eval(sprintf('set(handles.project%d, ''Position'', [%f %f %f %f]);', i, pos(1), pos(2), pos(3), pos(4)))
eval(sprintf('pos = get(handles.Generate%d, ''Position'');', i));
pos(2) = pos(2) - dy;
eval(sprintf('set(handles.Generate%d, ''Position'', [%f %f %f %f]);', i, pos(1), pos(2), pos(3), pos(4)))
end
end
for i = 1:SPM.eeg.Nfactors
% rename factor titles and set tooltipstrings
eval(sprintf('set(handles.factor%d_title, ''String'', '' %s'');', i, SPM.eeg.factor{i}));
eval(sprintf('set(handles.factor%d, ''ToolTipString'', ''Enter contrast vector/matrix for factor %s'');', i, SPM.eeg.factor{i}));
end
% switch off contrast weights editor of conventional conman
set(findobj('Tag', 'D_ConMtx'), 'Enable', 'off');
% UIWAIT makes spm_eeg_conman wait for user response (see UIRESUME)
% uiwait(handles.conman_eeg);
% --- Outputs from this function are returned to the command line.
function varargout = spm_eeg_conman_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes during object creation, after setting all properties.
function factor1_CreateFcn(hObject, eventdata, handles)
% hObject handle to factor1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function factor1_Callback(hObject, eventdata, handles)
% hObject handle to factor1 (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 factor1 as text
% str2double(get(hObject,'String')) returns contents of factor1 as a double
% --- Executes during object creation, after setting all properties.
function factor2_CreateFcn(hObject, eventdata, handles)
% hObject handle to factor2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function factor2_Callback(hObject, eventdata, handles)
% hObject handle to factor2 (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 factor2 as text
% str2double(get(hObject,'String')) returns contents of factor2 as a double
% --- Executes during object creation, after setting all properties.
function factor3_CreateFcn(hObject, eventdata, handles)
% hObject handle to factor3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function factor3_Callback(hObject, eventdata, handles)
% hObject handle to factor3 (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 factor3 as text
% str2double(get(hObject,'String')) returns contents of factor3 as a double
% --- Executes during object creation, after setting all properties.
function factor4_CreateFcn(hObject, eventdata, handles)
% hObject handle to factor4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function factor4_Callback(hObject, eventdata, handles)
% hObject handle to factor4 (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 factor4 as text
% str2double(get(hObject,'String')) returns contents of factor4 as a double
% --- Executes during object creation, after setting all properties.
function factor5_CreateFcn(hObject, eventdata, handles)
% hObject handle to factor5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function factor5_Callback(hObject, eventdata, handles)
% hObject handle to factor5 (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 factor5 as text
% str2double(get(hObject,'String')) returns contents of factor5 as a double
% --- Executes during object creation, after setting all properties.
function factor6_CreateFcn(hObject, eventdata, handles)
% hObject handle to factor6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function factor6_Callback(hObject, eventdata, handles)
% hObject handle to factor6 (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 factor6 as text
% str2double(get(hObject,'String')) returns contents of factor6 as a double
% --- Executes during object creation, after setting all properties.
function factor7_CreateFcn(hObject, eventdata, handles)
% hObject handle to factor7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function factor7_Callback(hObject, eventdata, handles)
% hObject handle to factor7 (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 factor7 as text
% str2double(get(hObject,'String')) returns contents of factor7 as a double
% --- Executes during object creation, after setting all properties.
function factor8_CreateFcn(hObject, eventdata, handles)
% hObject handle to factor8 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
function factor8_Callback(hObject, eventdata, handles)
% hObject handle to factor8 (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 factor8 as text
% str2double(get(hObject,'String')) returns contents of factor8 as a double
% --- Executes on button press in compute.
function compute_Callback(hObject, eventdata, handles)
% hObject handle to compute (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% check lengths of all vectors/matrices and compute output
SPM = handles.current_data;
% get the contrast component vectors/matrices
for i = 1:SPM.eeg.Nfactors
eval(sprintf('c{%d} = getappdata(handles.Generate%d, ''c'');', i, i));
if isempty(c{i})
eval(sprintf('str = get(handles.factor%d, ''String'');', i, i));
for j = 1:size(str, 1)
tmp{j} = str2num(str(j,:));
end
ml = 0;
for j = 1:length(tmp)
ml = max(ml, length(tmp{j}));
end
if ml == 0
spm('alert*', sprintf('Input weights for factor %s', SPM.eeg.factor{i}))
return;
end
c{i} = zeros(size(str, 1), ml);
for j = 1:size(str, 1)
c{i}(j, 1:length(tmp{j})) = tmp{j};
end
end
end
% check them
w = 0;
for i = 1:SPM.eeg.Nfactors
eval(sprintf('Sp = get(handles.project%d, ''Value'');', i));
if Sp
c{i} = spm_eeg_contrast_project(SPM, i, c{i});
elseif size(c{i}, 2) < size(SPM.eeg.X_d{1, i}, 2)
c{i} = [c{i} zeros(size(c,1), size(SPM.eeg.X_d{1, i}, 2) - size(c{i}, 2))];
eval(sprintf('set(handles.factor%d, ''String'', num2str(c{%d}));', i, i));
elseif size(c{i}, 2) > size(SPM.eeg.X_d{1, i}, 2)
warning('Wrong contrast vector length for factor %s', SPM.eeg.factor{i});
w = 1;
end
end
if ~w
xCon = [];
for i = 1:SPM.eeg.Nfactors
xCon.eeg.Con{1, i} = c{i};
end
c_out = spm_eeg_contrast(SPM, xCon);
% output
handles.output.c_out = c_out;
handles.output.c = c; % components
% look for edit window of contrast manager
h = findobj('Tag', 'D_ConMtx');
if ~isempty(h)
set(h, 'String', num2str(c_out));
setappdata(handles.conman_eeg, 'c', c_out)
spm_conman('D_ConMtx_CB')
end
else
handles.output = {};
end
% --- Executes on button press in reset.
function reset_Callback(hObject, eventdata, handles)
% hObject handle to reset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SPM = handles.current_data;
for i = 1:SPM.eeg.Nfactors
% remove strings from all factor windows
eval(sprintf('set(handles.factor%d, ''String'', '''');', i));
% remove components from Generate pushbuttons
eval(sprintf('h = handles.Generate%d;', i));
if isappdata(h, 'c')
rmappdata(h, 'c');
end
end
% --- Executes on button press in cancel.
function cancel_Callback(hObject, eventdata, handles)
% hObject handle to cancel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
delete(handles.conman_eeg);
set(findobj('Tag', 'D_ConMtx'), 'Enable', 'on');
% --- Executes on key press over conman_eeg with no controls selected.
function conman_eeg_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to conman_eeg (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 project1.
function project1_Callback(hObject, eventdata, handles)
% hObject handle to project1 (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 project2.
function project2_Callback(hObject, eventdata, handles)
% hObject handle to project2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of project2
% --- Executes on button press in radiobutton2.
function radiobutton2_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton2
% --- Executes on button press in project3.
function project3_Callback(hObject, eventdata, handles)
% hObject handle to project3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of project3
% --- Executes on button press in project6.
function project6_Callback(hObject, eventdata, handles)
% hObject handle to project6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of project6
% --- Executes on button press in project5.
function project5_Callback(hObject, eventdata, handles)
% hObject handle to project5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of project5
% --- Executes on button press in project7.
function project7_Callback(hObject, eventdata, handles)
% hObject handle to project7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of project7
% --- Executes on button press in project8.
function project8_Callback(hObject, eventdata, handles)
% hObject handle to project8 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of project8
% --- Executes on button press in project4.
function project4_Callback(hObject, eventdata, handles)
% hObject handle to project4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of project4
% --- Executes on button press in Generate1.
function Generate1_Callback(hObject, eventdata, handles)
% hObject handle to Generate1 (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 Generate2.
function Generate2_Callback(hObject, eventdata, handles)
% hObject handle to Generate2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
SPM = handles.current_data;
[c, xCon] = spm_eeg_contrast_generate(SPM);
set(handles.factor2, 'String', num2str(c));
setappdata(hObject, 'c', c);
set(handles.project2, 'Value', get(handles.project2, 'Max'));
% --- Executes on button press in Generate4.
function Generate4_Callback(hObject, eventdata, handles)
% hObject handle to Generate4 (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 Generate6.
function Generate6_Callback(hObject, eventdata, handles)
% hObject handle to Generate6 (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 Generate8.
function Generate8_Callback(hObject, eventdata, handles)
% hObject handle to Generate8 (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 Generate3.
function Generate3_Callback(hObject, eventdata, handles)
% hObject handle to Generate3 (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 Generate5.
function Generate5_Callback(hObject, eventdata, handles)
% hObject handle to Generate5 (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 Generate7.
function Generate7_Callback(hObject, eventdata, handles)
% hObject handle to Generate7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
|
github
|
spm/spm5-master
|
spm_config_reorient.m
|
.m
|
spm5-master/spm_config_reorient.m
| 3,415 |
utf_8
|
d67a3c54751637e0e021b309b433f528
|
function opts = spm_config_reorient
% Configuration file for reorient images
% Apply a given transformation matrix or reorientation parameters by
% left-multiplying the original image orientation with it.
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Volkmar Glauche
% $Id: spm_config_movefile.m 549 2006-06-07 12:37:29Z volkmar $
%_______________________________________________________________________
srcfiles.type = 'files';
srcfiles.name = 'Images to reorient';
srcfiles.tag = 'srcfiles';
srcfiles.filter = 'image';
srcfiles.num = [0 Inf];
srcfiles.help = {'Select images to reorient.'};
transM.type = 'entry';
transM.name = 'Reorientation matrix';
transM.tag = 'transM';
transM.strtype = 'e';
transM.num = [4 4];
p1 = 'Enter a valid 4x4 matrix for reorientation.';
p2 = 'Example: This will L-R flip the images.';
p3 = ' -1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1';
transM.help = {p1,'',p2,'',p3};
transprm.type = 'entry';
transprm.name = 'Reorientation parameters';
transprm.tag = 'transprm';
transprm.strtype = 'e';
transprm.num = [1 12];
p0 = 'Enter 12 reorientation parameters.';
p1 = 'P(1) - x translation';
p2 = 'P(2) - y translation';
p3 = 'P(3) - z translation';
p4 = 'P(4) - x rotation about - {pitch} (radians)';
p5 = 'P(5) - y rotation about - {roll} (radians)';
p6 = 'P(6) - z rotation about - {yaw} (radians)';
p7 = 'P(7) - x scaling';
p8 = 'P(8) - y scaling';
p9 = 'P(9) - z scaling';
p10 = 'P(10) - x affine';
p11 = 'P(11) - y affine';
p12 = 'P(12) - z affine';
p13 = 'Parameters are entered as listed above and then processed by spm_matrix.';
p14 = ['Example: This will L-R flip the images (extra spaces are inserted between ',...
'each group for illustration purposes).'];
p15 = ' 0 0 0 0 0 0 -1 0 0 0 0 0';
transprm.help = {p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,'',p14,'',p15,''};
transform.type = 'choice';
transform.name = 'Reorient by';
transform.tag = 'transform';
transform.values = {transM, transprm};
transform.help = {'Specify reorientation method.'};
opts.type = 'branch';
opts.name = 'Reorient images';
opts.tag = 'reorient';
opts.val = {srcfiles,transform};
opts.prog = @my_reorient;
opts.vfiles = @vfiles_reorient;
opts.help = {[...
'This facility allows to reorient images in a batch. The reorientation parameters ' ...
'can be given either as a 4x4 matrix or as parameters as defined for spm_matrix.m. ' ...
'The new image orientation will be computed by PRE-multiplying the original '...
'orientation matrix with the supplied matrix.']};
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function my_reorient(varargin)
job = varargin{1};
if isfield(job.transform,'transprm')
job.transform.transM = spm_matrix(job.transform.transprm);
end;
spm_progress_bar('Init', numel(job.srcfiles), 'Reorient', 'Images completed');
for k = 1:numel(job.srcfiles)
M = spm_get_space(job.srcfiles{k});
spm_get_space(job.srcfiles{k},job.transform.transM*M);
spm_progress_bar('Set',k);
end;
spm_progress_bar('Clear');
return;
%-------------------------------------------------------------------------
function vf = vfiles_reorient(job)
srcfiles = job.srcfiles{1};
vf = {spm_select('CPath','image',srcfiles)};
|
github
|
spm/spm5-master
|
spm_latex.m
|
.m
|
spm5-master/spm_latex.m
| 5,190 |
utf_8
|
a6cbdb66e672ce5b277533b297bb6370
|
function spm_latex(c)
% Convert a job configuration structure into a series of LaTeX documents
%
% Note that this function works rather better in Matlab 7.x, than it
% does under Matlab 6.x. This is primarily because of the slightly
% different usage of the 'regexp' function.
%____________________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_latex.m 949 2007-10-16 08:19:45Z volkmar $
if nargin==0, c = spm_config; end;
fp = fopen('spm_manual.tex','w');
fprintf(fp,'\\documentclass[a4paper,titlepage]{book}\n');
fprintf(fp,'\\usepackage{epsfig,amsmath,pifont,moreverb,minitoc}\n');
fprintf(fp,'%s\n%s\n%s\n%s\n%s\n%s\n%s\n',...
'\usepackage[colorlinks=true,',...
'pdfpagemode=UseOutlines,',...
'pdftitle={SPM5 Manual},','pdfauthor={The SPM Team},',...
'pdfsubject={Statistical Parametric Mapping},',...
'pdfkeywords={neuroimaging, MRI, PET, EEG, MEG, SPM}',...
']{hyperref}');
fprintf(fp,'\\pagestyle{headings}\n\\bibliographystyle{plain}\n\n');
fprintf(fp,'\\hoffset=15mm\n\\voffset=-5mm\n');
fprintf(fp,'\\oddsidemargin=0mm\n\\evensidemargin=0mm\n\\topmargin=0mm\n');
fprintf(fp,'\\headheight=12pt\n\\headsep=10mm\n\\textheight=240mm\n\\textwidth=148mm\n');
fprintf(fp,'\\marginparsep=5mm\n\\marginparwidth=21mm\n\\footskip=10mm\n\n');
fprintf(fp,'\\title{\\huge{SPM5 Manual}}\n');
fprintf(fp,'\\author{The FIL Methods Group (and honorary members)}\n');
fprintf(fp,'\\begin{document}\n');
fprintf(fp,'\\maketitle\n');
fprintf(fp,'\\dominitoc\\tableofcontents\n\n');
fprintf(fp,'\\newpage\n\\section*{The SPM5 User Interface}\n');
write_help(c,fp);
for i=1:numel(c.values),
if isfield(c.values{i},'tag'),
part(c.values{i},fp);
end;
end;
%fprintf(fp,'\\parskip=0mm\n\\bibliography{methods_macros,methods_group,external}\n\\end{document}\n\n');
fprintf(fp,'\\parskip=0mm\n');
bibcstr = get_bib(fullfile(spm('dir'),'man','biblio'));
tbxlist = dir(fullfile(spm('dir'),'toolbox'));
for k = 1:numel(tbxlist)
if tbxlist(k).isdir,
bibcstr=[bibcstr(:); get_bib(fullfile(spm('dir'),'toolbox', ...
tbxlist(k).name))];
end;
end;
bibcstr = strcat(bibcstr,',');
bibstr = strcat(bibcstr{:});
fprintf(fp,'\\bibliography{%s}\n',bibstr(1:end-1));
fprintf(fp,'\\end{document}\n\n');
fclose(fp);
return;
function part(c,fp)
if isstruct(c) && isfield(c,'tag'),
fprintf(fp,'\\part{%s}\n',texify(c.name));
% write_help(c,fp);
if isfield(c,'values'),
for i=1:numel(c.values),
if isfield(c.values{i},'tag'),
fprintf(fp,'\\include{%s}\n',c.values{i}.tag);
chapter(c.values{i});
end;
end;
end;
if isfield(c,'val'),
for i=1:numel(c.val),
if isfield(c.val{i},'tag'),
if chapter(c.val{i}),
fprintf(fp,'\\include{%s}\n',c.val{i}.tag);
end;
end;
end;
end;
end;
return;
function sts = chapter(c)
fp = fopen([c.tag '.tex'],'w');
if fp==-1, sts = false; return; end;
fprintf(fp,'\\chapter{%s \\label{Chap:%s}}\n\\minitoc\n\n\\vskip 1.5cm\n\n',texify(c.name),c.tag);
write_help(c,fp);
switch c.type,
case {'branch'},
for i=1:numel(c.val),
section(c.val{i},fp);
end;
case {'repeat','choice'},
for i=1:numel(c.values),
section(c.values{i},fp);
end;
end;
fclose(fp);
sts = true;
return;
function section(c,fp,lev)
if nargin<3, lev = 1; end;
sec = {'section','subsection','subsubsection','paragraph','subparagraph'};
if lev<=5,
fprintf(fp,'\n\\%s{%s}\n',sec{lev},texify(c.name));
write_help(c,fp);
switch c.type,
case {'branch'},
for i=1:numel(c.val),
section(c.val{i},fp,lev+1);
end;
case {'repeat','choice'},
for i=1:numel(c.values),
section(c.values{i},fp,lev+1);
end;
end;
else
warning(['Too many nested levels... ' c.name]);
end;
return;
function write_help(hlp,fp)
if isstruct(hlp),
if isfield(hlp,'help'),
hlp = hlp.help;
else
return;
end;
end;
if iscell(hlp),
for i=1:numel(hlp),
write_help(hlp{i},fp);
end;
return;
end;
str = texify(hlp);
fprintf(fp,'%s\n\n',str);
return;
function str = texify(str0)
st1 = findstr(str0,'/*');
en1 = findstr(str0,'*/');
st = [];
en = [];
for i=1:numel(st1),
en1 = en1(en1>st1(i));
if ~isempty(en1),
st = [st st1(i)];
en = [en en1(1)];
en1 = en1(2:end);
end;
end;
str = [];
pen = 1;
for i=1:numel(st),
str = [str clean_latex(str0(pen:st(i)-1)) str0(st(i)+2:en(i)-1)];
pen = en(i)+2;
end;
str = [str clean_latex(str0(pen:numel(str0)))];
return;
function str = clean_latex(str)
str = strrep(str,'$','\$');
str = strrep(str,'&','\&');
str = strrep(str,'_','\_');
%str = strrep(str,'\','$\\$');
str = strrep(str,'|','$|$');
str = strrep(str,'>','$>$');
str = strrep(str,'<','$<$');
return;
function bibcstr = get_bib(bibdir)
biblist = dir(fullfile(bibdir,'*.bib'));
bibcstr={};
for k = 1:numel(biblist)
[p n e v] = fileparts(biblist(k).name);
bibcstr{k} = fullfile(bibdir,n);
end;
|
github
|
spm/spm5-master
|
spm_coreg.m
|
.m
|
spm5-master/spm_coreg.m
| 13,725 |
utf_8
|
443ab4fbbd6c152d6d0f0d385d72356f
|
function x = spm_coreg(varargin)
% Between modality coregistration using information theory
% FORMAT x = spm_coreg(VG,VF,params)
% VG - handle for first image (see spm_vol).
% VF - handle for second image.
% 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
% 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]
%
% 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.
%
% 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
% -------------------------------
% F Maes, A Collignon, D Vandermeulen, G Marchal & P 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.
%
% 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.
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_coreg.m 1007 2007-11-21 12:37:33Z john $
if nargin>=4,
x = optfun(varargin{:});
return;
end;
def_flags = struct('sep',[4 2],'params',[0 0 0 0 0 0], 'cost_fun','nmi','fwhm',[7 7],...
'tol',[0.02 0.02 0.02 0.001 0.001 0.001 0.01 0.01 0.01 0.001 0.001 0.001],'graphics',1);
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;
%disp(flags)
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(strvcat(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);
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;
return;
%_______________________________________________________________________
%_______________________________________________________________________
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;
return;
%_______________________________________________________________________
%_______________________________________________________________________
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)));
if spm_matlab_version_chk('7.0')>=0,
h = h + accumarray(img,1,[nh 1]);
else
h = h + full(sparse(img,1,1,nh,1));
end
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);
spm_progress_bar('Init',V.dim(3),...
['Loading ' spm_str_manip(V.fname,'t')],...
'Planes loaded');
%udat = zeros(V.dim,'uint8'); Needs MATLAB 7 onwards
udat = uint8(0);
udat(V.dim(1),V.dim(2),V.dim(3)) = 0;
rand('state',100);
for p=1:V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1);
acc = paccuracy(V,p);
if acc==0,
udat(:,:,p) = uint8(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');
return;
function acc = paccuracy(V,p)
if ~spm_type(V.dt(1),'intt'),
acc = 0;
else
if size(V.pinfo,2)==1,
acc = abs(V.pinfo(1,1));
else
acc = abs(V.pinfo(1,p));
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
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]);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function krn = smoothing_kernel(fwhm,x)
% Variance from FWHM
s = (fwhm/sqrt(8*log(2)))^2+eps;
% The simple way to do it. Not good for small FWHM
% krn = (1/sqrt(2*pi*s))*exp(-(x.^2)/(2*s));
% For smoothing images, one should really convolve a Gaussian
% with a sinc function. For smoothing histograms, the
% kernel should be a Gaussian convolved with the histogram
% basis function used. This function returns a Gaussian
% convolved with a triangular (1st degree B-spline) basis
% function.
% Gaussian convolved with 0th degree B-spline
% int(exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= -0.5..0.5)
% w1 = 1/sqrt(2*s);
% krn = 0.5*(erf(w1*(x+0.5))-erf(w1*(x-0.5)));
% Gaussian convolved with 1st degree B-spline
% int((1-t)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= 0..1)
% +int((t+1)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t=-1..0)
w1 = 0.5*sqrt(2/s);
w2 = -0.5/s;
w3 = sqrt(s/2/pi);
krn = 0.5*(erf(w1*(x+1)).*(x+1) + erf(w1*(x-1)).*(x-1) - 2*erf(w1*x ).* x)...
+w3*(exp(w2*(x+1).^2) + exp(w2*(x-1).^2) - 2*exp(w2*x.^2));
krn(krn<0) = 0;
return;
%_______________________________________________________________________
%_______________________________________________________________________
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
return;
|
github
|
spm/spm5-master
|
spm_config_surf.m
|
.m
|
spm5-master/spm_config_surf.m
| 2,252 |
utf_8
|
46cc9f45a635a68da38466624b0ec0d5
|
function opts = spm_config_surf
% Configuration file for surface extraction jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Volkmar Glauche
% $Id: spm_config_surf.m 775 2007-03-26 16:57:01Z john $
data.type = 'files';
data.name = 'Grey+white matter image';
data.tag = 'data';
data.filter = 'image';
data.num = [1 Inf];
data.help = {'Images to create rendering/surface from (grey and white matter segments).'};
mode.type = 'menu';
mode.name = 'Output';
mode.tag = 'mode';
mode.labels = {'Save Rendering', 'Save Extracted Surface',...
'Save Rendering and Surface', 'Save Surface as OBJ format'};
mode.values = {1, 2, 3, 4};
mode.val = {3};
thresh.type = 'entry';
thresh.name = 'Surface isovalue(s)';
thresh.tag = 'thresh';
thresh.num = [1 Inf];
thresh.val = {.5};
thresh.strtype = 'e';
thresh.help = {['Enter one or more values at which isosurfaces through ' ...
'the input images will be computed.']};
opts.type = 'branch';
opts.name = 'Create Rendering/Surface';
opts.tag = 'spm_surf';
opts.val = {data,mode,thresh};
opts.vfiles = @filessurf;
opts.prog = @runsurf;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function runsurf(varargin)
spm_surf(strvcat(varargin{1}.data),varargin{1}.mode,varargin{1}.thresh);
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vfiles=filessurf(varargin)
vfiles={};
[pth,nam,ext] = fileparts(varargin{1}.data{1});
if any(varargin{1}.mode==[1 3]),
vfiles{1} = fullfile(pth,['render_' nam '.mat']);
end;
if any(varargin{1}.mode==[2 3 4]),
for k=1:numel(varargin{1}.thresh)
if numel(varargin{1}.thresh) == 1
nam1 = nam;
else
nam1 = sprintf('%s-%d', nam, k);
end;
if any(varargin{1}.mode==[2 3]),
vfiles{end+1} = fullfile(pth,['surf_' nam1 '.mat']);
end;
if any(varargin{1}.mode==[4]),
vfiles{end+1} = fullfile(pth,[nam1 '.obj']);
end;
end;
end
return;
|
github
|
spm/spm5-master
|
spm_eeg_scalp_dlg.m
|
.m
|
spm5-master/spm_eeg_scalp_dlg.m
| 5,509 |
utf_8
|
7cd9ad7846616f2c1e168eac831221ee
|
function varargout = spm_eeg_scalp_dlg(varargin)
% SPM_EEG_SCALP_DLG M-file for spm_eeg_scalp_dlg.fig
% SPM_EEG_SCALP_DLG, by itself, creates a new SPM_EEG_SCALP_DLG or raises the existing
% singleton*.
%
% H = SPM_EEG_SCALP_DLG returns the handle to a new SPM_EEG_SCALP_DLG or the handle to
% the existing singleton*.
%
% SPM_EEG_SCALP_DLG('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SPM_EEG_SCALP_DLG.M with the given input arguments.
%
% SPM_EEG_SCALP_DLG('Property','Value',...) creates a new SPM_EEG_SCALP_DLG or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before spm_eeg_scalp_dlg_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to spm_eeg_scalp_dlg_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Copyright 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help spm_eeg_scalp_dlg
% Last Modified by GUIDE v2.5 21-Nov-2005 18:51:44
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @spm_eeg_scalp_dlg_OpeningFcn, ...
'gui_OutputFcn', @spm_eeg_scalp_dlg_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before spm_eeg_scalp_dlg is made visible.
function spm_eeg_scalp_dlg_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to spm_eeg_scalp_dlg (see VARARGIN)
% Choose default command line output for spm_eeg_scalp_dlg
handles.output = hObject;
handles.T = 100;
handles.dim = '2D';
guidata(hObject, handles);
% UIWAIT makes spm_eeg_scalp_dlg wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = spm_eeg_scalp_dlg_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
if isfield(handles, 'T')
handles.output = {handles.T handles.dim};
varargout{1} = handles.output;
close(handles.figure1);
end
function time_Callback(hObject, eventdata, handles)
% hObject handle to time (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 time as text
% str2double(get(hObject,'String')) returns contents of time as a double
handles.T = str2num(get(handles.time, 'String'));
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function time_CreateFcn(hObject, eventdata, handles)
% hObject handle to time (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit 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
% --- Executes on selection change in select.
function select_Callback(hObject, eventdata, handles)
% hObject handle to select (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 select contents as cell array
% contents{get(hObject,'Value')} returns selected item from select
S = {'2D', '3D'};
handles.dim = S{get(handles.select, 'Value')};
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function select_CreateFcn(hObject, eventdata, handles)
% hObject handle to select (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
% --- Executes on button press in ok.
function ok_Callback(hObject, eventdata, handles)
% hObject handle to ok (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
uiresume(handles.figure1);
|
github
|
spm/spm5-master
|
spm_uw_estimate.m
|
.m
|
spm5-master/spm_uw_estimate.m
| 33,867 |
utf_8
|
17b02c89f832b000c9cce52c1529fb6a
|
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) 2005 Wellcome Department of Imaging Neuroscience
% Jesper Andersson
% $Id: spm_uw_estimate.m 471 2006-03-08 17:46:45Z john $
global defaults
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('order', [12 12],...
'sfP', [],...
'M', P(1).mat,...
'regorder', 1,...
'lambda', 1e5,...
'jm', 0,...
'fot', [4 5],...
'sot', [],...
'fwhm', 4,...
'rem', 1,...
'exp_round', 'Average',...
'noi', 5,...
'hold', [1 1 1 0 1 0]);
defnames = fieldnames(defpar);
%
% Replace hardcoded defaults with spm_defaults
% when exist and defined.
%
if exist('defaults','var') & isfield(defaults,'unwarp') & isfield(defaults.unwarp,'estimate')
ud = 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
end
%
% 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(getfield(par,defnames{i}))
ds = setfield(ds,defnames{i},getfield(par,defnames{i}));
else
ds = setfield(ds,defnames{i},getfield(defpar,defnames{i}));
end
end
parnames = fieldnames(par);
for i=1:length(parnames)
if ~isfield(defpar,parnames{i})
warning(sprintf('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 strcmp(lower(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 strcmp(lower(exp_round),'first');
mT = eye(4);
elseif strcmp(lower(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(spm_atranspa(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)<=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;
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
|
spm/spm5-master
|
spm_prep2sn.m
|
.m
|
spm5-master/spm_prep2sn.m
| 7,396 |
utf_8
|
61eb57b5fb967c417d75aa0e5761501b
|
function [po,pin] = spm_prep2sn(p)
% Convert the output from spm_preproc into an sn.mat
% 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.
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_prep2sn.m 946 2007-10-15 16:36:06Z john $
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);
if nargout==0,
[pth,nam,ext] = fileparts(VF.fname);
fnam = fullfile(pth,[nam '_seg_sn.mat']);
if spm_matlab_version_chk('7') >= 0,
save(fnam,'-V6','VG','VF','Tr','Affine','flags');
else
save(fnam,'VG','VF','Tr','Affine','flags');
end;
else
po = struct(...
'VG', VG,...
'VF', VF,...
'Tr', Tr,...
'Affine', Affine,...
'flags', flags);
end;
if nargout>=2,
% Parameterisation for the inverse
pin = struct(...
'VG', p.image,...
'VF', p.tpm(1),...
'Tr', p.Twarp,...
'Affine', p.tpm(1).mat\p.Affine*p.image.mat,...
'flags', flags);
% VG = p.image;
% VF = p.tpm(1);
% Tr = p.Twarp;
% Affine = p.tpm(1).mat\p.Affine*p.image.mat;
% save('junk_sn.mat','VG','VF','Tr','Affine');
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');
mx = [0 0 0];
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]); drawnow;
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,ext] = 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)); drawnow;
t1 = reshape(t1*B3', d2(1), d2(2)); drawnow;
t = B1*t1*B2';
return;
%=======================================================================
|
github
|
spm/spm5-master
|
spm_eeg_inv_TesSph.m
|
.m
|
spm5-master/spm_eeg_inv_TesSph.m
| 5,477 |
utf_8
|
b524de0b479cac1e72ad958508ad4ad2
|
function tsph = spm_eeg_inv_TesSph(r,n);
%=======================================================================
% FORMAT tsph = spm_eeg_inv)TesSph(r,n);
%
% Generate a structure 'tsph' containing a tesselated sphere.
%
% Input :
% r - radius of the sphere
% n - number of 'latitude' divisions on the sphere. It MUST be even!
% ( Nvert = 5/4 * n^2 + 2 )
%
% Output :
% tsph .vert - vertices coordinates (3 x Nvert)
% .tri - triangle patches (3 x Ntri)
% .info - info string
%=======================================================================
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Christophe Phillips & Jeremie Mattout
% $Id: spm_eeg_inv_TesSph.m 716 2007-01-16 21:13:50Z karl $
if nargin == 0
n = 40;
r = 1;
elseif nargin == 1
n = 40;
elseif nargin == 2
n = round( sqrt(4*(n - 2)/5) );
else
error('Error: wrong input format')
end
[X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r) ;
[ind_tr] = tri(npt_tr,npt_qr,npt_sph) ;
tsph.vert = [X_sp ; Y_sp ; Z_sp] ;
tsph.tri = ind_tr ;
tsph.nr = [length(X_sp) size(ind_tr,2)] ;
tsph.info = ['Tes sph : n=',num2str(n),', r=',num2str(r)] ;
varargout{1} = tsph;
%________________________________________________________________________
% FORMAT [X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r)
% Generate a set of points on a sphere.
% n = the number of latitudes on the sphere, it MUST be even!
% r = radius of the sphere, 1 by default.
%------------------------------------------------------------------------
function [X_sp,Y_sp,Z_sp,npt_tr,npt_qr,npt_sph] = point(n,r)
d_r = pi/180; dth = 180/n*d_r ;
X_qr=[] ; Y_qr=[] ; Z_qr=[] ; X_sp=[] ; Y_sp=[] ; Z_sp=[] ;
% Coord of pts on a 5th of sphere WITHOUT the top and bottom points
for i=1:n/2 % Upper part
the = i*dth ;
cth = cos(the) ; sth = sin(the) ;
dphi = 72/i*d_r ;
for j=1:i
phi = (j-1)*dphi ;
cph = cos(phi) ; sph = sin(phi) ;
X_qr = [X_qr sth*cph] ;
Y_qr = [Y_qr sth*sph] ;
Z_qr = [Z_qr cth] ;
end
end
for i=(n/2+1):(n-1) % Lower part
the = i*dth ;
cth = cos(the) ; sth = sin(the) ;
ii = n-i ;
dphi = 72/ii*d_r ;
for j=1:ii
phi = (j-1)*dphi ;
cph = cos(phi) ; sph = sin(phi) ;
X_qr = [X_qr sth*cph] ;
Y_qr = [Y_qr sth*sph] ;
Z_qr = [Z_qr cth] ;
end
end
% Each part is copied with a 72deg shift
dphi=-72*d_r ;
for i=0:4
phi=i*dphi ;
cph=cos(phi) ;
sph=sin(phi) ;
X_sp=[X_sp cph*X_qr+sph*Y_qr] ;
Y_sp=[Y_sp -sph*X_qr+cph*Y_qr] ;
Z_sp=[Z_sp Z_qr] ;
end
% add top and bottom points
X_sp=[0 X_sp 0]*r ;
Y_sp=[0 Y_sp 0]*r ;
Z_sp=[1 Z_sp -1]*r ;
npt_tr = [[0:n/2] [n/2-1:-1:0]]; % Nbr of points on each slice for a 5th of sph.
npt_qr = sum(npt_tr) ; % total nbr of pts per 5th of sphere
npt_sph=5/4*n^2+2 ; % or 5*npt_qr+2 ; % total nbr of pts on sph
return
%________________________________________________________________________
% FORMAT [ind_tr] = tri(npt_tr,npt_qr,npt_sph)
% Order the pts created by the function 'point' into triangles
% Each triangle is represented by 3 indices correponding to the XYZ_sp
%
% This works only because I know in wich order the vertices are generated
% in the 'point' function.
%------------------------------------------------------------------------
function [ind_tr] = tri(npt_tr,npt_qr,npt_sph)
n = sqrt(4/5*(npt_sph-2)) ;
% First 5th of sphere only
for i=0:(n/2-1) % upper half
if i==0 % 1st triangle at the top
ind_qr=[1 2 2+npt_qr]' ;
else % other triangles
for j=0:npt_tr(i+1)
if j==npt_tr(i+1)-1 % last but 1 pt on slice
x1=sum(npt_tr(1:i))+j+2 ;
x12=x1+npt_tr(i+1) ;
x13=x12+1 ;
x22=x13 ;
x23=sum(npt_tr(1:i))+2+npt_qr ;
ind_qr=[ind_qr [x1 x12 x13]' [x1 x22 x23]'] ;
elseif j==npt_tr(i+1) % last pt on slice
x1=sum(npt_tr(1:i))+2+npt_qr ;
x2=sum(npt_tr(1:(i+1)))+j+2 ;
x3=x1+npt_tr(i+1) ;
ind_qr=[ind_qr [x1 x2 x3]'] ;
else % other pts on slice
x1=sum(npt_tr(1:i))+j+2 ;
x12=x1+npt_tr(i+1) ;
x13=x12+1 ;
x22=x13 ;
x23=x1+1 ;
ind_qr=[ind_qr [x1 x12 x13]' [x1 x22 x23]'] ;
end
end
end
end
for i=(n/2+1):n % lower half
if i==n % last triangle at the bottom
ind_qr=[ind_qr [5*npt_qr+2 2*npt_qr+1 npt_qr+1]' ] ;
else % other triangles
for j=0:npt_tr(i+1)
if j==npt_tr(i+1)-1 % last but 1 pt on slice
x1=sum(npt_tr(1:i))+j+2 ;
x12=x1-npt_tr(i) ;
x13=x12+1 ;
x22=x13 ;
x23=sum(npt_tr(1:i))+2+npt_qr ;
ind_qr=[ind_qr [x1 x13 x12]' [x1 x23 x22]'] ;
elseif j==npt_tr(i+1) % last pt on slice
x1=sum(npt_tr(1:i))+2+npt_qr ;
x2=sum(npt_tr(1:(i-1)))+j+2 ;
x3=x1-npt_tr(i) ;
ind_qr=[ind_qr [x1 x3 x2]'] ;
else % other pts on slice
x1=sum(npt_tr(1:i))+j+2 ;
x12=x1-npt_tr(i) ;
x13=x12+1 ;
x22=x13 ;
x23=x1+1 ;
ind_qr=[ind_qr [x1 x13 x12]' [x1 x23 x22]'] ;
end
end
end
end
ntr_qr =size(ind_qr,2) ; % nbr of triangle per 5th of sphere
[S_i,S_j]=find(ind_qr==1) ;
[B_i,B_j]=find(ind_qr==npt_sph) ;
[qs_i,qs_j]=find((ind_qr>(npt_qr+1))&(ind_qr<(3*npt_qr))) ;
ind_tr=[] ;
% shift all indices to cover the sphere
for i=0:4
ind_tr = [ind_tr (ind_qr+i*npt_qr)] ;
ind_tr(S_i,S_j+i*ntr_qr) = 1 ;
ind_tr(B_i,B_j+i*ntr_qr) = npt_sph ;
end
for i=1:size(qs_i,1)
ind_tr(qs_i(i),qs_j(i)+4*ntr_qr) = ...
ind_tr(qs_i(i),(qs_j(i)+4*ntr_qr))-5*npt_qr ;
end
ntr_sph = size(ind_tr,2) ;% nbr of triangles on the sphere
% or = 5/2*n^2
return
|
github
|
spm/spm5-master
|
spm_ovhelper_3Dreg.m
|
.m
|
spm5-master/spm_orthviews/spm_ovhelper_3Dreg.m
| 2,312 |
utf_8
|
50f2f405f2da022944b80781d2e481a6
|
function spm_ovhelper_3Dreg(cmd, varargin)
if ishandle(varargin{1})
h = varargin{1};
elseif ischar(varargin{1})
h = findobj(0, 'Tag',varargin{1});
if ~ishandle(h)
warning([mfilename ':InvalidHandle'], ...
'No valid graphics handle found');
return;
else
h = get(h(ishandle(h)),'parent');
end;
end;
switch lower(cmd)
case 'register'
register(h,varargin{2:end});
return;
case 'setcoords'
setcoords(varargin{1:end});
return;
case 'unregister',
unregister(h,varargin{2:end});
return;
case 'xhairson'
xhairs(h,'on',varargin{2:end});
return;
case 'xhairsoff'
xhairs(h,'off',varargin{2:end});
return;
end;
function register(h,V,varargin)
try
global st;
if isstruct(st)
xyz=spm_orthviews('pos');
if isfield(st,'registry')
hreg = st.registry.hReg;
else
[hreg xyz]=spm_XYZreg('InitReg', h, V.mat, ...
V.dim(1:3)',xyz);
spm_orthviews('register',hreg);
end;
spm_XYZreg('Add2Reg',hreg,h,mfilename);
feval(mfilename,'setcoords',xyz,h);
set(h, 'DeleteFcn', ...
sprintf('%s(''unregister'',%f);', mfilename, h));
end;
catch
warning([mfilename ':XYZreg'],...
'Unable to register to spm_orthviews display');
disp(lasterr);
end;
return;
function setcoords(xyz,h,varargin)
spm('pointer','watch');
Xh = findobj(h,'Tag', 'Xhairs');
if ishandle(Xh)
vis = get(Xh(1),'Visible');
delete(Xh);
else
vis = 'on';
end;
axes(findobj(h,'Type','axes'));
lim = axis;
Xh = line([xyz(1), xyz(1), lim(1);...
xyz(1), xyz(1), lim(2)],...
[lim(3), xyz(2), xyz(2);...
lim(4), xyz(2), xyz(2)],...
[xyz(3), lim(5), xyz(3);...
xyz(3), lim(6), xyz(3)],...
'Color','b', 'Tag','Xhairs', 'Visible',vis,...
'Linewidth',2, 'HitTest','off');
spm('pointer','arrow');
return;
function xhairs(h,val,varargin)
Xh = findobj(h, 'Tag', 'Xhairs');
if ~isempty(Xh)
set(Xh,'Visible',val);
end;
function unregister(h,varargin)
try
global st;
if isfield(st,'registry')
hreg = st.registry.hReg;
else
hreg = findobj(0,'Tag','hReg');
end;
if h == hreg
spm_XYZreg('UnInitReg',hreg);
st = rmfield(st, 'registry');
else
spm_XYZreg('Del2Reg',hreg,h);
end;
catch
warning([mfilename ':XYZreg'],...
'Unable to unregister');
disp(lasterr);
end;
return;
|
github
|
spm/spm5-master
|
spm_ov_roi.m
|
.m
|
spm5-master/spm_orthviews/spm_ov_roi.m
| 29,856 |
utf_8
|
0297a491107f32f68e456f0584fa5a5e
|
function ret = spm_ov_roi(varargin)
% ROI tool - plugin for spm_orthviews
%
% With ROI tool it is possible to create new or modify existing mask images
% interactively. ROI tool can be launched via the spm_orthviews image
% context menu.
% While ROI tool is active, mouse buttons have the following functions:
% left Reposition crosshairs
% middle Perform ROI tool box selection according to selected edit mode at
% crosshair position
% right context menu
%
% Menu options and prompts explained:
% Launch Initialise ROI tool in current image
% 'Load existing ROI image? (yes/no)'
% If you want to modify an existing mask image (e.g. mask.img from
% a fMRI analysis), press 'yes'. You will then be prompted to
% 'Select ROI image'
% This is the image that will be loaded as initial ROI.
% If you want to create a new ROI image, you will first be
% prompted to
% 'Select image defining ROI space'
% The image dimensions, voxel sizes and slice orientation will
% be read from this image. Thus you can edit a ROI based on a
% image with a resolution and slice orientation different from
% the underlying displayed image.
%
% Once ROI tool is active, the menu consists of three parts: settings,
% edit operations and load/save operations.
% Settings
% --------
% Selection Operation performed when pressing the middle mouse button or
% mode by clustering operations.
% 'Set selection'
% The selection made with the following commands will
% be included in your ROI.
% 'Clear selection'
% The selection made with the following commands will
% be excluded from your ROI.
% Box size Set size of box to be (de)selected when pressing the
% middle mouse button.
% Polygon Set number of adjacent slices selected by one polygon
% slices drawing.
% Cluster Set minimum cluster size for "Cleanup clusters" and
% size "Connected cluster" operations.
% Erosion/ During erosion/dilation operations, the binary mask will be
% dilation smoothed. At boundaries, this will result in mask values
% threshold that are not exactly zero or one, but somewhere in
% between. Whether a mask will be eroded (i.e. be smaller than
% the original) or dilated (i.e. grow) depends on this
% threshold. A threshold below 0.5 dilates, above 0.5 erodes a
% mask.
% Edit actions
% ------------
% Polygon Draw an outline on one of the 3 section images. Voxels
% within the outline will be added to the ROI. The same
% outline can be applied to a user-defined number of
% consecutive slices around the current crosshair position.
% Threshold You will be prompted to enter a [min max] threshold. Only
% those voxels in the ROI image where the intensities of the
% underlying image are within the [min max] range will survive
% this operation.
% Connected Select only voxels that are connected to the voxel at
% cluster current crosshair position through the ROI.
% Cleanup Keep only clusters that are larger than a specified cluster
% clusters size.
% Erode/ Erode or dilate a mask, using the current erosion/dilation
% Dilate threshold.
% Invert Invert currently defined ROI
% Clear Clear ROI, but keep ROI space information
% Add ROI from file(s)
% Add ROIs from file(s) into current ROI set. According to the
% current edit mode voxels unequal zero will be set or
% cleared. The image files will be resampled and thus do not
% need to have the same orientation or voxel size as the
% original ROI.
% Save actions
% ------------
% Save Save ROI image
% Save As Save ROI image under a new file name
% Quit Quit ROI tool
%
% This routine is a plugin to spm_orthviews for SPM5. For general help about
% spm_orthviews and plugins type
% help spm_orthviews
% at the matlab prompt.
%_____________________________________________________________________________
% $Id: spm_ov_roi.m 2672 2009-01-30 13:32:08Z volkmar $
% Note: This plugin depends on the blobs set by spm_orthviews('addblobs',...)
% They should not be removed while ROI tool is active and no other blobs be
% added. This restriction may be removed when switching to MATLAB 6.x and
% using the 'alpha' property to overlay blobs onto images.
rev = '$Revision: 2672 $';
global st;
if isempty(st)
error('roi: This routine can only be called as a plugin for spm_orthviews!');
end;
if nargin < 2
error('roi: Wrong number of arguments. Usage: spm_orthviews(''roi'', cmd, volhandle, varargin)');
end;
cmd = lower(varargin{1});
volhandle = varargin{2};
toset = [];
toclear = [];
tochange = [];
update_roi = 0;
switch cmd
case 'init'
spm('pointer','watch');
Vroi = spm_vol(varargin{3});
switch varargin{4} % loadasroi
case 1,
roi = spm_read_vols(Vroi)>0;
[x y z] = ndgrid(1:Vroi.dim(1),1:Vroi.dim(2),1:Vroi.dim(3));
xyz = [x(roi(:))'; y(roi(:))'; z(roi(:))'];
case {0,2} % ROI space image or SPM mat
Vroi = rmfield(Vroi,'private');
roi = zeros(Vroi.dim(1:3));
Vroi.fname = fileparts(Vroi.fname); % save path
Vroi.dt(1) = spm_type('uint8');
xyz = varargin{5};
if ~isempty(xyz)
ind = sub2ind(Vroi.dim(1:3),xyz(1,:),xyz(2,:),xyz(3,:));
roi(ind) = 1;
end;
end;
Vroi.pinfo(1:2) = Inf;
clear x y z
% draw a frame only if ROI volume different from underlying GM volume
if any(Vroi.dim(1:3)-st.vols{volhandle}.dim(1:3))| ...
any(Vroi.mat(:)-st.vols{volhandle}.mat(:))
[xx1 yx1 zx1] = ndgrid(1 , 1:Vroi.dim(2), 1:Vroi.dim(3));
[xx2 yx2 zx2] = ndgrid(Vroi.dim(1) , 1:Vroi.dim(2), 1:Vroi.dim(3));
[xy1 yy1 zy1] = ndgrid(1:Vroi.dim(1), 1 , 1:Vroi.dim(3));
[xy2 yy2 zy2] = ndgrid(1:Vroi.dim(1), Vroi.dim(2) , 1:Vroi.dim(3));
[xz1 yz1 zz1] = ndgrid(1:Vroi.dim(1), 1:Vroi.dim(2), 1);
[xz2 yz2 zz2] = ndgrid(1:Vroi.dim(1), 1:Vroi.dim(2), Vroi.dim(3));
fxyz = [xx1(:)' xx2(:)' xy1(:)' xy2(:)' xz1(:)' xz2(:)'; ...
yx1(:)' yx2(:)' yy1(:)' yy2(:)' yz1(:)' yz2(:)'; ...
zx1(:)' zx2(:)' zy1(:)' zy2(:)' zz1(:)' zz2(:)'];
clear xx1 yx1 zx1 xx2 yx2 zx2 xy1 yy1 zy1 xy2 yy2 zy2 xz1 yz1 zz1 xz2 yz2 zz2
hframe = 1;
else
hframe = [];
fxyz = [];
end;
for k=1:3
cb{k}=get(st.vols{volhandle}.ax{k}.ax,'ButtonDownFcn');
set(st.vols{volhandle}.ax{k}.ax,...
'ButtonDownFcn',...
['switch get(gcf,''SelectionType'')',...
'case ''normal'', spm_orthviews(''Reposition'');',...
'case ''extend'', spm_orthviews(''roi'',''edit'',', ...
num2str(volhandle), ');',...
'case ''alt'', spm_orthviews(''context_menu'',''ts'',1);',...
'end;']);
end;
st.vols{volhandle}.roi = struct('Vroi',Vroi, 'xyz',xyz, 'roi',roi,...
'hroi',1, 'fxyz',fxyz,...
'hframe',hframe, 'mode','set',...
'tool', 'box', ...
'thresh',[60 140], 'box',[4 4 4],...
'cb',[], 'polyslices',1, 'csize',5,...
'erothresh',.5);
st.vols{volhandle}.roi.cb = cb;
if ~isempty(st.vols{volhandle}.roi.fxyz)
if isfield(st.vols{volhandle}, 'blobs')
st.vols{volhandle}.roi.hframe = prod(size(st.vols{volhandle}.blobs))+1;
end;
spm_orthviews('addcolouredblobs',volhandle, ...
st.vols{volhandle}.roi.fxyz,...
ones(size(st.vols{volhandle}.roi.fxyz,2),1), ...
st.vols{volhandle}.roi.Vroi.mat,[1 .5 .5]);
st.vols{volhandle}.blobs{st.vols{volhandle}.roi.hframe}.max=1.3;
end;
update_roi=1;
case 'edit'
switch st.vols{volhandle}.roi.tool
case 'box'
spm('pointer','watch');
pos = round(inv(st.vols{volhandle}.roi.Vroi.mat)* ...
[spm_orthviews('pos'); 1]);
tmp = round((st.vols{volhandle}.roi.box-1)/2);
[sx sy sz] = meshgrid(-tmp(1):tmp(1), -tmp(2):tmp(2), -tmp(3):tmp(3));
sel = [sx(:)';sy(:)';sz(:)']+repmat(pos(1:3), 1,prod(2*tmp+1));
tochange = sel(:, (all(sel>0) &...
sel(1,:)<=st.vols{volhandle}.roi.Vroi.dim(1) & ...
sel(2,:)<=st.vols{volhandle}.roi.Vroi.dim(2) & ...
sel(3,:)<=st.vols{volhandle}.roi.Vroi.dim(3)));
update_roi = 1;
case 'poly'
% @COPYRIGHT :
% Copyright 1993,1994 Mark Wolforth and Greg Ward, McConnell
% Brain Imaging Centre, Montreal Neurological Institute, McGill
% University.
% Permission to use, copy, modify, and distribute this software
% and its documentation for any purpose and without fee is
% hereby granted, provided that the above copyright notice
% appear in all copies. The authors and McGill University make
% no representations about the suitability of this software for
% any purpose. It is provided "as is" without express or
% implied warranty.
for k = 1:3
if st.vols{volhandle}.ax{k}.ax == gca
axhandle = k;
break;
end;
end;
line_color = [1 1 0];
axes(st.vols{volhandle}.ax{axhandle}.ax);
hold on;
Xlimits = get (st.vols{volhandle}.ax{axhandle}.ax,'XLim');
Ylimits = get (st.vols{volhandle}.ax{axhandle}.ax,'YLim');
XLimMode = get(st.vols{volhandle}.ax{axhandle}.ax,'XLimMode');
set(st.vols{volhandle}.ax{axhandle}.ax,'XLimMode','manual');
YLimMode = get(st.vols{volhandle}.ax{axhandle}.ax,'YLimMode');
set(st.vols{volhandle}.ax{axhandle}.ax,'YLimMode','manual');
ButtonDownFcn = get(st.vols{volhandle}.ax{axhandle}.ax,'ButtonDownFcn');
set(st.vols{volhandle}.ax{axhandle}.ax,'ButtonDownFcn','');
UIContextMenu = get(st.vols{volhandle}.ax{axhandle}.ax,'UIContextMenu');
set(st.vols{volhandle}.ax{axhandle}.ax,'UIContextMenu',[]);
set(st.vols{volhandle}.ax{axhandle}.ax,'Selected','on');
disp (['Please mark the ROI outline in the highlighted image' ...
' display.']);
disp ('Points outside the ROI image area will be clipped to');
disp ('the image boundaries.');
disp ('Left-Click on the vertices of the ROI...');
disp ('Middle-Click to finish ROI selection...');
disp ('Right-Click to cancel...');
x=Xlimits(1);
y=Ylimits(1);
i=1;
lineHandle = [];
xc = 0; yc = 0; bc = 0;
while ~isempty(bc)
[xc,yc,bc] = ginput(1);
if isempty(xc) | bc > 1
if bc == 3
x = []; y=[];
end;
if bc == 2 | bc == 3
bc = [];
break;
end;
else
if xc > Xlimits(2)
xc = Xlimits(2);
elseif xc < Xlimits(1)
xc = Xlimits(1);
end;
if yc > Ylimits(2)
yc = Ylimits(2);
elseif yc < Ylimits(1)
yc = Ylimits(1);
end;
x(i) = xc;
y(i) = yc;
i=i+1;
if ishandle(lineHandle)
delete(lineHandle);
end;
lineHandle = line (x,y,ones(1,length(x)), ...
'Color',line_color,...
'parent',st.vols{volhandle}.ax{axhandle}.ax,...
'HitTest','off');
end;
end
if ishandle(lineHandle)
delete(lineHandle);
end;
if ~isempty(x)
spm('pointer','watch');
x(i)=x(1);
y(i)=y(1);
prms=spm_imatrix(st.vols{volhandle}.roi.Vroi.mat);
% Code from spm_orthviews('redraw') for determining image
% positions
is = inv(st.Space);
cent = is(1:3,1:3)*st.centre(:) + is(1:3,4);
polyoff = [0 0 0];
switch axhandle
case 1,
M0 = [ 1 0 0 -st.bb(1,1)+1
0 1 0 -st.bb(1,2)+1
0 0 1 -cent(3)
0 0 0 1];
polyoff(3) = st.vols{volhandle}.roi.polyslices/2;
polythick = prms(9);
case 2,
M0 = [ 1 0 0 -st.bb(1,1)+1
0 0 1 -st.bb(1,3)+1
0 1 0 -cent(2)
0 0 0 1];
polyoff(2) = st.vols{volhandle}.roi.polyslices/2;
polythick = prms(8);
case 3,
if st.mode ==0,
M0 = [ 0 0 1 -st.bb(1,3)+1
0 1 0 -st.bb(1,2)+1
1 0 0 -cent(1)
0 0 0 1];
else,
M0 = [ 0 -1 0 +st.bb(2,2)+1
0 0 1 -st.bb(1,3)+1
1 0 0 -cent(1)
0 0 0 1];
end;
polyoff(1) = st.vols{volhandle}.roi.polyslices/2;
polythick = abs(prms(7));
end;
polvx = inv(st.vols{volhandle}.roi.Vroi.mat)*st.Space*inv(M0)*...
[x(:)';y(:)'; zeros(size(x(:)')); ones(size(x(:)'))];
% Bounding volume for polygon in ROI voxel space
[xbox ybox zbox] = ndgrid(max(min(floor(polvx(1,:)-polyoff(1))),1):...
min(max(ceil(polvx(1,:)+polyoff(1))),...
st.vols{volhandle}.roi.Vroi.dim(1)),...
max(min(floor(polvx(2,:)-polyoff(2))),1):...
min(max(ceil(polvx(2,:)+polyoff(2))),...
st.vols{volhandle}.roi.Vroi.dim(2)),...
max(min(floor(polvx(3,:)-polyoff(3))),1):...
min(max(ceil(polvx(3,:)+polyoff(3))),...
st.vols{volhandle}.roi.Vroi.dim(3)));
% re-transform in polygon plane
xyzbox = M0*is*st.vols{volhandle}.roi.Vroi.mat*[xbox(:)';ybox(:)';zbox(:)';...
ones(size(xbox(:)'))];
xyzbox = xyzbox(:,abs(xyzbox(3,:))<=.6*polythick*...
st.vols{volhandle}.roi.polyslices); % nearest neighbour to polygon
sel = logical(inpolygon(xyzbox(1,:),xyzbox(2,:),x,y));
xyz = inv(st.vols{volhandle}.roi.Vroi.mat)*st.Space*inv(M0)*xyzbox(:,sel);
if ~isempty(xyz)
tochange = round(xyz(1:3,:));
update_roi = 1;
end;
end;
set(st.vols{volhandle}.ax{axhandle}.ax,...
'Selected','off', 'XLimMode',XLimMode, 'YLimMode',YLimMode,...
'ButtonDownFcn',ButtonDownFcn, 'UIContextMenu',UIContextMenu);
end;
case 'thresh'
spm('pointer','watch');
rind = find(st.vols{volhandle}.roi.roi);
[x y z]=ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),rind);
tmp = round(inv(st.vols{volhandle}.mat) * ...
st.vols{volhandle}.roi.Vroi.mat*[x'; y'; z'; ones(size(x'))]);
dat = spm_sample_vol(st.vols{volhandle}, ...
tmp(1,:), tmp(2,:), tmp(3,:), 0);
sel = ~((st.vols{volhandle}.roi.thresh(1) < dat) & ...
(dat < st.vols{volhandle}.roi.thresh(2)));
if strcmp(st.vols{volhandle}.roi.mode,'set')
toclear = [x(sel)'; y(sel)'; z(sel)'];
else
toset = [x(sel)'; y(sel)'; z(sel)'];
toclear = st.vols{volhandle}.roi.xyz;
end;
update_roi = 1;
case 'erodilate'
spm('pointer','watch');
V = zeros(size(st.vols{volhandle}.roi.roi));
spm_smooth(double(st.vols{volhandle}.roi.roi), V, 2);
[ero(1,:) ero(2,:) ero(3,:)] = ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),...
find(V(:)>st.vols{volhandle}.roi.erothresh));
if strcmp(st.vols{volhandle}.roi.mode,'set')
toset = ero;
toclear = st.vols{volhandle}.roi.xyz;
else
toclear = ero;
end;
update_roi = 1;
case {'connect', 'cleanup'}
spm('pointer','watch');
[V L] = spm_bwlabel(double(st.vols{volhandle}.roi.roi),6);
sel = [];
switch cmd
case 'connect'
pos = round(inv(st.vols{volhandle}.roi.Vroi.mat)* ...
[spm_orthviews('pos'); 1]);
sel = V(pos(1),pos(2),pos(3));
if sel == 0
sel = [];
end;
case 'cleanup'
for k = 1:L
numV(k) = sum(V(:)==k);
end;
sel = find(numV>st.vols{volhandle}.roi.csize);
end;
if ~isempty(sel)
ind = [];
for k=1:numel(sel)
ind = [ind; find(V(:) == sel(k))];
end;
conn = zeros(3,numel(ind));
[conn(1,:) conn(2,:) conn(3,:)] = ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),ind);
if strcmp(st.vols{volhandle}.roi.mode,'set')
toset = conn;
toclear = st.vols{volhandle}.roi.xyz;
else
toclear = conn;
end;
end;
update_roi = 1;
case 'invert'
spm('pointer','watch');
toclear = st.vols{volhandle}.roi.xyz;
[x y z] = ndgrid(1:st.vols{volhandle}.roi.Vroi.dim(1),...
1:st.vols{volhandle}.roi.Vroi.dim(2),...
1:st.vols{volhandle}.roi.Vroi.dim(3));
if ~isempty(toclear)
toset = setdiff([x(:)'; y(:)'; z(:)']', toclear', 'rows')';
else
toset = [x(:)'; y(:)'; z(:)'];
end;
update_roi = 1;
clear x y z;
case 'clear'
spm('pointer','watch');
st.vols{volhandle}.roi.roi = zeros(size(st.vols{volhandle}.roi.roi));
st.vols{volhandle}.roi.xyz=[];
update_roi = 1;
case 'addfile'
V = spm_vol(spm_select([1 Inf],'image','Image(s) to add'));
[x y z] = ndgrid(1:st.vols{volhandle}.roi.Vroi.dim(1),...
1:st.vols{volhandle}.roi.Vroi.dim(2),...
1:st.vols{volhandle}.roi.Vroi.dim(3));
xyzmm = st.vols{volhandle}.roi.Vroi.mat*[x(:)';y(:)';z(:)'; ...
ones(1, prod(st.vols{volhandle}.roi.Vroi.dim(1:3)))];
msk = zeros(1,prod(st.vols{volhandle}.roi.Vroi.dim(1:3)));
for k = 1:numel(V)
xyzvx = inv(V(k).mat)*xyzmm;
msk = msk | spm_sample_vol(V(k), xyzvx(1,:), xyzvx(2,:), xyzvx(3,:), 0);
end;
[tochange(1,:) tochange(2,:) tochange(3,:)] = ind2sub(st.vols{volhandle}.roi.Vroi.dim(1:3),find(msk));
clear xyzmm xyzvx msk
update_roi = 1;
case {'save','saveas'}
if strcmp(cmd,'saveas') | ...
exist(st.vols{volhandle}.roi.Vroi.fname)==7
flt = {'*.nii','NIfTI (1 file)';'*.img','NIfTI (2 files)'};
[name pth idx] = uiputfile(flt, 'Output image');
if ~ischar(pth)
warning('Save cancelled');
return;
end;
[p n e v] = spm_fileparts(fullfile(pth,name));
if isempty(e)
e = flt{idx,1}(2:end);
end;
st.vols{volhandle}.roi.Vroi.fname = fullfile(p, [n e v]);
end;
spm('pointer','watch');
spm_write_vol(st.vols{volhandle}.roi.Vroi, ...
st.vols{volhandle}.roi.roi);
spm('pointer','arrow');
return;
case 'redraw'
% do nothing
return;
%-------------------------------------------------------------------------
% Context menu and callbacks
case 'context_menu'
item0 = uimenu(varargin{3}, 'Label', 'ROI tool');
item1 = uimenu(item0, 'Label', 'Launch', 'Callback', ...
['feval(''spm_ov_roi'',''context_init'', ', ...
num2str(volhandle), ');'], 'Tag', ['ROI_0_', num2str(volhandle)]);
item2 = uimenu(item0, 'Label', 'Selection mode', ...
'Visible', 'off', 'Tag', ['ROI_1_', num2str(volhandle)]);
item2_1a = uimenu(item2, 'Label', 'Set selection', 'Callback', ...
['feval(''spm_ov_roi'',''context_selection'',', ...
num2str(volhandle), ',''set'');'], ...
'Tag', ['ROI_SELECTION_', num2str(volhandle)], 'Checked','on');
item2_1b = uimenu(item2, 'Label', 'Clear selection', 'Callback', ...
['feval(''spm_ov_roi'',''context_selection'',', ...
num2str(volhandle), ',''clear'');'], ...
'Tag', ['ROI_SELECTION_', num2str(volhandle)]);
item3 = uimenu(item0, 'Label', 'Box size', 'Callback', ...
['feval(''spm_ov_roi'',''context_box'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item4 = uimenu(item0, 'Label', 'Polygon slices', 'Callback', ...
['feval(''spm_ov_roi'',''context_polyslices'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item5 = uimenu(item0, 'Label', 'Cluster size', 'Callback', ...
['feval(''spm_ov_roi'',''context_csize'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item6 = uimenu(item0, 'Label', 'Erosion/Dilation threshold', 'Callback', ...
['feval(''spm_ov_roi'',''context_erothresh'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item7 = uimenu(item0, 'Label', 'Edit tool', ...
'Visible', 'off', 'Tag', ['ROI_1_', num2str(volhandle)],...
'Separator','on');
item7_1a = uimenu(item7, 'Label', 'Box tool', 'Callback', ...
['feval(''spm_ov_roi'',''context_edit'',', ...
num2str(volhandle), ',''box'');'], ...
'Tag', ['ROI_EDIT_', num2str(volhandle)], 'Checked','on');
item7_1b = uimenu(item7, 'Label', 'Polygon tool', 'Callback', ...
['feval(''spm_ov_roi'',''context_edit'',', ...
num2str(volhandle), ',''poly'');'], ...
'Tag', ['ROI_EDIT_', num2str(volhandle)]);
item8 = uimenu(item0, 'Label', 'Threshold', 'Callback', ...
['feval(''spm_ov_roi'',''context_thresh'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item9 = uimenu(item0, 'Label', 'Connected cluster', 'Callback', ...
['feval(''spm_ov_roi'',''connect'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item10 = uimenu(item0, 'Label', 'Cleanup clusters', 'Callback', ...
['feval(''spm_ov_roi'',''cleanup'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item11 = uimenu(item0, 'Label', 'Erode/Dilate', 'Callback', ...
['feval(''spm_ov_roi'',''erodilate'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item12 = uimenu(item0, 'Label', 'Invert', 'Callback', ...
['feval(''spm_ov_roi'',''invert'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item13 = uimenu(item0, 'Label', 'Clear', 'Callback', ...
['feval(''spm_ov_roi'',''clear'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item14 = uimenu(item0, 'Label', 'Add ROI from file(s)', 'Callback', ...
['feval(''spm_ov_roi'',''addfile'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item15 = uimenu(item0, 'Label', 'Save', 'Callback', ...
['feval(''spm_ov_roi'',''save'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)],...
'Separator','on');
item16 = uimenu(item0, 'Label', 'Save As', 'Callback', ...
['feval(''spm_ov_roi'',''saveas'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item17 = uimenu(item0, 'Label', 'Quit', 'Callback', ...
['feval(''spm_ov_roi'',''context_quit'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
item18 = uimenu(item0, 'Label', 'Help', 'Callback', ...
['feval(''spm_help'',''' mfilename ''');']);
% add some stuff outside ROI tool menu
iorient = findobj(st.vols{volhandle}.ax{1}.cm, 'Label', 'Orientation');
item19 = uimenu(iorient, 'Label', 'ROI Space', 'Callback', ...
['feval(''spm_ov_roi'',''context_space'', ', ...
num2str(volhandle), ');'], 'Visible', 'off', ...
'Tag', ['ROI_1_', num2str(volhandle)]);
return;
case 'context_init'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
loadasroi = spm_input('Initial ROI','!+1','m',{'ROI image',...
'ROI space definition', 'SPM result'},[1 0 2],1);
xyz = [];
switch loadasroi
case 1,
imfname = spm_select(1, 'image', 'Select ROI image');
case 0,
imfname = spm_select(1, 'image', 'Select image defining ROI space');
[p n e v] = fileparts(imfname);
case 2,
[SPM, xSPM] = spm_getSPM;
xyz = xSPM.XYZ;
imfname = SPM.Vbeta(1).fname;
end;
feval('spm_ov_roi','init',volhandle,imfname,loadasroi,xyz);
obj = findobj(0, 'Tag', ['ROI_1_', num2str(volhandle)]);
set(obj, 'Visible', 'on');
obj = findobj(0, 'Tag', ['ROI_0_', num2str(volhandle)]);
set(obj, 'Visible', 'off');
spm_input('!DeleteInputObj',Finter);
return;
case 'context_selection'
st.vols{volhandle}.roi.mode = varargin{3};
obj = findobj(0, 'Tag', ['ROI_SELECTION_', num2str(volhandle)]);
set(obj, 'Checked', 'off');
set(gcbo, 'Checked', 'on');
return;
case 'context_edit'
st.vols{volhandle}.roi.tool = varargin{3};
obj = findobj(0, 'Tag', ['ROI_EDIT_', num2str(volhandle)]);
set(obj, 'Checked', 'off');
set(gcbo, 'Checked', 'on');
return;
case 'context_box'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
box = spm_input('Selection size {vx vy vz}','!+1','e', ...
num2str(st.vols{volhandle}.roi.box), [1 3]);
spm_input('!DeleteInputObj',Finter);
st.vols{volhandle}.roi.box = box;
return;
case 'context_polyslices'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
polyslices = spm_input('Polygon: slices around current slice','!+1','e', ...
num2str(st.vols{volhandle}.roi.polyslices), [1 1]);
spm_input('!DeleteInputObj',Finter);
st.vols{volhandle}.roi.polyslices = polyslices;
return;
case 'context_csize'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
csize = spm_input('Minimum cluster size (#vx)','!+1','e', ...
num2str(st.vols{volhandle}.roi.csize), [1 1]);
spm_input('!DeleteInputObj',Finter);
st.vols{volhandle}.roi.csize = csize;
return;
case 'context_erothresh'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
erothresh = spm_input('Erosion/Dilation threshold','!+1','e', ...
num2str(st.vols{volhandle}.roi.erothresh), [1 1]);
spm_input('!DeleteInputObj',Finter);
st.vols{volhandle}.roi.erothresh = erothresh;
return;
case 'context_space'
spm_orthviews('space', volhandle, ...
st.vols{volhandle}.roi.Vroi.mat, ...
st.vols{volhandle}.roi.Vroi.dim(1:3));
iorient = get(findobj(0,'Label','Orientation'),'children');
if iscell(iorient)
iorient = cell2mat(iorient);
end;
set(iorient, 'Checked', 'Off');
ioroi = findobj(iorient, 'Label','ROI space');
set(ioroi, 'Checked', 'On');
return;
case 'context_thresh'
Finter = spm_figure('FindWin', 'Interactive');
spm_input('!DeleteInputObj',Finter);
thresh = spm_input('Threshold {min max}','!+1','e', ...
num2str(st.vols{volhandle}.roi.thresh), [1 2]);
spm_input('!DeleteInputObj',Finter);
st.vols{volhandle}.roi.thresh = thresh;
feval('spm_ov_roi', 'thresh', volhandle);
return;
case 'context_quit'
obj = findobj(0, 'Tag', ['ROI_1_', num2str(volhandle)]);
set(obj, 'Visible', 'off');
obj = findobj(0, 'Tag', ['ROI_0_', num2str(volhandle)]);
set(obj, 'Visible', 'on');
spm_orthviews('rmblobs', volhandle);
for k=1:3
set(st.vols{volhandle}.ax{k}.ax,'ButtonDownFcn', st.vols{volhandle}.roi.cb{k});
end;
st.vols{volhandle} = rmfield(st.vols{volhandle}, 'roi');
spm_orthviews('redraw');
return;
otherwise
fprintf('spm_orthviews(''roi'', ...): Unknown action %s', cmd);
return;
end;
if update_roi
if ~isempty(tochange) % change state according to mode
if strcmp(st.vols{volhandle}.roi.mode,'set')
toset = tochange;
else
toclear = tochange;
end;
end;
% clear first, then set (needed for connect operation)
if ~isempty(toclear)
itoclear = sub2ind(st.vols{volhandle}.roi.Vroi.dim(1:3), ...
toclear(1,:), toclear(2,:), toclear(3,:));
st.vols{volhandle}.roi.roi(itoclear) = 0;
if ~isempty(st.vols{volhandle}.roi.xyz)
st.vols{volhandle}.roi.xyz = setdiff(st.vols{volhandle}.roi.xyz',toclear','rows')';
else
st.vols{volhandle}.roi.xyz = [];
end;
end;
if ~isempty(toset)
% why do we need this round()?? I don't know, but Matlab thinks
% it is necessary
itoset = round(sub2ind(st.vols{volhandle}.roi.Vroi.dim(1:3), ...
toset(1,:), toset(2,:), toset(3,:)));
st.vols{volhandle}.roi.roi(itoset) = 1;
if ~isempty(st.vols{volhandle}.roi.xyz)
st.vols{volhandle}.roi.xyz = union(st.vols{volhandle}.roi.xyz',toset','rows')';
else
st.vols{volhandle}.roi.xyz = toset;
end;
end;
if isfield(st.vols{volhandle}, 'blobs')
nblobs=length(st.vols{volhandle}.blobs);
if nblobs>1
blobstmp(1:st.vols{volhandle}.roi.hroi-1) = st.vols{volhandle}.blobs(1:st.vols{volhandle}.roi.hroi-1);
blobstmp(st.vols{volhandle}.roi.hroi:nblobs-1) = st.vols{volhandle}.blobs(st.vols{volhandle}.roi.hroi+1:nblobs);
st.vols{volhandle}.blobs=blobstmp;
else
if isempty(st.vols{volhandle}.roi.hframe) % save frame
st.vols{volhandle}=rmfield(st.vols{volhandle},'blobs');
end;
end;
end;
if isfield(st.vols{volhandle}, 'blobs')
st.vols{volhandle}.roi.hroi = prod(size(st.vols{volhandle}.blobs))+1;
else
st.vols{volhandle}.roi.hroi = 1;
end;
if isempty(st.vols{volhandle}.roi.xyz) % initialised with empty roi
spm_orthviews('addcolouredblobs', volhandle, ...
[1; 1; 1], 0, st.vols{volhandle}.roi.Vroi.mat,[1 3 1]);
else
spm_orthviews('addcolouredblobs', volhandle, ...
st.vols{volhandle}.roi.xyz, ones(size(st.vols{volhandle}.roi.xyz,2),1), ...
st.vols{volhandle}.roi.Vroi.mat,[1 3 1]); % use color that is more intense than standard rgb range
end;
st.vols{volhandle}.blobs{st.vols{volhandle}.roi.hroi}.max=2;
spm_orthviews('redraw');
end;
spm('pointer','arrow');
function varargout = stack(cmd, varargin)
switch cmd
case 'init'
varargout{1}.st = cell(varargin{1},1);
varargout{1}.top= 0;
case 'isempty'
varargout{1} = (varargin{1}.top==0);
case 'push'
stck = varargin{1};
if (stck.top < size(stck.st,1))
stck.top = stck.top + 1;
stck.st{stck.top} = varargin{2};
varargout{1}=stck;
else
error('Stack overflow\n');
end;
case 'pop'
if stack('isempty',varargin{1})
error('Stack underflow\n');
else
varargout{2} = varargin{1}.st{varargin{1}.top};
varargin{1}.top = varargin{1}.top - 1;
varargout{1} = varargin{1};
end;
end;
|
github
|
spm/spm5-master
|
spm_config_3Dto4D.m
|
.m
|
spm5-master/toolbox/spm_config_3Dto4D.m
| 1,523 |
utf_8
|
c5d8981c24f5a268e730a354d1c1658d
|
function c = spm_config_3Dto4D(varargin)
% Configuration file for concatenation jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_3Dto4D.m 946 2007-10-15 16:36:06Z john $
vols.type = 'files';
vols.name = '3D Volumes';
vols.tag = 'vols';
vols.num = [1 Inf];
vols.filter = 'image';
vols.help = {'Select the volumes to concatenate'};
c.type = 'branch';
c.name = '3D to 4D';
c.tag = 'cat';
c.val = {vols};
c.prog = @spm_3Dto4D;
c.help = {'Concatenate a number of 3D volumes into a single 4D file.',...
'Note that output time series are stored as big-endian int16.'};
%_______________________________________________________________________
%_______________________________________________________________________
function spm_3Dto4D(job)
V = spm_vol(strvcat(job.vols{:}));
ind = cat(1,V.n);
N = cat(1,V.private);
mx = -Inf;
mn = Inf;
for i=1:numel(V),
dat = V(i).private.dat(:,:,:,ind(i,1),ind(i,2));
dat = dat(isfinite(dat));
mx = max(mx,max(dat(:)));
mn = min(mn,min(dat(:)));
end;
sf = max(mx,-mn)/32767;
ni = nifti;
ni.dat = file_array('4D.nii',[V(1).dim numel(V)],'INT16-BE',0,sf,0);
ni.mat = N(1).mat;
ni.mat0 = N(1).mat;
ni.descrip = '4D image';
create(ni);
for i=1:size(ni.dat,4),
ni.dat(:,:,:,i) = N(i).dat(:,:,:,ind(i,1),ind(i,2));
spm_get_space([ni.dat.fname ',' num2str(i)], V(i).mat);
end;
|
github
|
spm/spm5-master
|
spm_config_segment_old.m
|
.m
|
spm5-master/toolbox/spm_config_segment_old.m
| 16,323 |
utf_8
|
22130641d1f2170a0451396959a3254c
|
function opts = spm_config_segment_old
% Configuration file for segment jobs
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: spm_config_segment_old.m 184 2005-05-31 13:23:32Z john $
%_______________________________________________________________________
scans.type = 'files';
scans.tag = 'scans';
scans.tag = 'multispec';
scans.name = 'Subject';
p1 = [...
'If more than one volume is specified (eg T1 & T2), then they must be ',...
'in register (same position, size, voxel dims etc..).'];
scans.help = {'Select scans for this subject.',p1};
scans.filter = 'image';
scans.num = [1 Inf];
%------------------------------------------------------------------------
scans2.type = 'repeat';
scans2.name = 'Multi-spectral images';
scans2.values = {scans};
scans2.help = {...
'Multispectral tissue classification'};
%------------------------------------------------------------------------
scans.type = 'files';
scans.tag = 'scans';
scans.tag = 'singlespec';
scans.name = 'Single-channel images';
scans.help = {...
'Select scans for classification. ',...
'This assumes that there is one scan for each subject'};
scans.filter = 'image';
scans.num = [1 Inf];
%------------------------------------------------------------------------
data = struct('type','choice','name','Data','tag','data','values',{{scans,scans2}});
data.help = {[...
'Classification can be done on either a single image for each subject ',...
'(single channel) or can be based on two or more registered images ',...
'(multispectral).']};
%------------------------------------------------------------------------
template.type = 'files';
template.tag = 'template';
template.name = 'Template image(s)';
template.num = [1 5];
template.filter = 'image';
template.val = {{fullfile(spm('Dir'),'templates','T1.nii')}};
template.help = {[...
'Select one or more template images, which will be used for affine matching. ',...
'Matching involves minimising the mean squared difference between the image and ',...
'template, so the tamplate should have the same contrast, or be of the same ',...
'modality as the image you want to register with it. ',...
'Note that for multi-spectral classification, the affine transform is only ',...
'determined from the first image specified for each subject.']};
%------------------------------------------------------------------------
regtype.type = 'menu';
regtype.name = 'Regularisation';
regtype.tag = 'regtype';
regtype.labels = {'ICBM space template', 'Average sized template','No regularisation'};
regtype.values = {'mni','subj','none'};
regtype.def = 'segment.estimate.affreg.regtype';
regtype.help = {[...
'Affine registration into a standard space can be made more robust by ',...
'regularisation (penalising excessive stretching or shrinking). The ',...
'best solutions can be obtained by knowing the approximate amount of ',...
'stretching that is needed (e.g. ICBM templates are slightly bigger ',...
'than typical brains, so greater zooms are likely to be needed). ',...
'If registering to an image in ICBM/MNI space, then choose the first ',...
'option. If registering to a template that is close in size, then ',...
'select the second option. If you do not want to regularise, then ',...
'choose the third.']};
%------------------------------------------------------------------------
weight.type = 'files';
weight.name = 'Weighting image';
weight.tag = 'weight';
weight.filter = 'image';
weight.num = [0 1];
weight.def = 'segment.estimate.affreg.weight';
weight.help = {[...
'The affine registration can be weighted by an image that conforms to ',...
'the same space as the template image. If an image is selected, then ',...
'it must match the template(s) voxel-for voxel, and have the same ',...
'voxel-to-world mapping.']};
%------------------------------------------------------------------------
smosrc.type = 'entry';
smosrc.name = 'Smoothing FWHM (mm)';
smosrc.tag = 'smosrc';
smosrc.strtype = 'e';
smosrc.num = [1 1];
smosrc.def = 'segment.estimate.affreg.smosrc';
smosrc.help = {[...
'This is the full width at half maximum (FWHM - in mm) of the Gaussian ',...
'smoothing kernel applied to the source image before doing the affine ',...
'registration. Templates released with SPM are usually smoothed by 8mm ',...
'so 8mm would normally be the best value to use.']};
%------------------------------------------------------------------------
affreg.type = 'branch';
affreg.name = 'Affine register';
affreg.tag = 'affreg';
affreg.val = {template,weight,regtype,smosrc};
affreg.help = {'An affine registration needs to be done for non spatially normalised images.'};
%------------------------------------------------------------------------
unnecessary.type = 'const';
unnecessary.tag = 'unnecessary';
unnecessary.val = {[]};
unnecessary.name = 'Already spatially normalised';
unnecessary.help = {[...
'If the data are already spatially normalised, then no affine registration ',...
'is needed in order to overlay the prior probability images.']};
%------------------------------------------------------------------------
%affreg1.type = 'menu';
%affreg1.tag = 'template';
%affreg1.name = 'Predefined template';
%affreg1.labels = {'Register T1 MRI ',...
%'Register T2 MRI','Register PD MRI','Register EPI MR'};
%affreg1.values = {...
%fullfile(spm('Dir'),'templates ', T1.nii'),...
%fullfile(spm('Dir'),'templates ', T2.nii'),...
%fullfile(spm('Dir'),'templates ', PD.nii'),...
%fullfile(spm('Dir'),'templates','EPI.nii')};
%affreg1.help = {...
%'Select one of the template images, which will be used for affine matching. ',...
%'Note that for multi-spectral classification, the affine transform is only ',...
%'determined from the first image specified for each subject.'};
%------------------------------------------------------------------------
overlay.type = 'choice';
overlay.tag = 'overlay';
overlay.name = 'Prior overlay';
overlay.values = {unnecessary,affreg};
overlay.help = {'How should the priors be overlayed over the image to segment.'};
%------------------------------------------------------------------------
priors.type = 'files';
priors.name = 'Prior probability maps';
priors.tag = 'priors';
priors.filter = 'image';
priors.num = 3;
priors.def = 'segment.estimate.priors';
priors.help = {[...
'Prior probability images that are overlayed on the images to segment. ',...
'These should be prior probability maps of grey matter, white matter ',...
'and cerebro-spinal fluid.']};
%------------------------------------------------------------------------
samp.type = 'entry';
samp.name = 'Sampling distance';
samp.tag = 'samp';
samp.num = [1 1];
samp.strtype = 'e';
samp.def = 'segment.estimate.samp';
samp.help = {[...
'The approximate distance between sampled points when estimating the ',...
'segmentation parameters.']};
%------------------------------------------------------------------------
bb.type = 'entry';
bb.name = 'Bounding box';
bb.tag = 'bb';
bb.num = [2 3];
bb.strtype = 'e';
bb.def = 'segment.estimate.bb';
bb.help = {[...
'Bounding box defining the region in which the segmentation parameters ',...
'are estimated']};
%------------------------------------------------------------------------
custom.type = 'branch';
custom.name = 'Custom';
custom.tag = 'custom';
custom.val = {priors,bb,samp};
custom.help = {'Tweekable things'};
%------------------------------------------------------------------------
reg.tag = 'reg';
reg.type = 'menu';
reg.name = 'Bias regularisation';
reg.help = {[...
'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).']};
reg.labels = {'no regularisation (0) ','extremely light regularisation (0.00001)',...
'very light regularisation (0.0001) ','light regularisation (0.001)',...
'medium regularisation (0.01) ','heavy regularisation (0.1)',...
'very heavy regularisation (1)','extremely heavy regularisation (10)'};
reg.values = {0, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1.0, 10};
reg.def = 'segment.estimate.reg';
%------------------------------------------------------------------------
cutoff.tag = 'cutoff';
cutoff.type = 'menu';
cutoff.name = 'Bias cutoff';
cutoff.help = {[...
'Cutoff of DCT bases. Only DCT bases of periods longer than the ',...
'cutoff are used to describe the bias. The number used will ',...
'depend on the cutoff and the field of view of the image.']};
cutoff.labels = {'20mm cutoff','25mm cutoff','30mm cutoff','35mm cutoff',...
'40mm cutoff','45mm cutoff','50mm cutoff','60mm cutoff','70mm cutoff',...
'80mm cutoff','90mm cutoff','100mm cutoff','No correction'};
cutoff.values = {20,25,30,35,40,45,50,60,70,80,90,100,Inf};
cutoff.def = 'segment.estimate.cutoff';
%------------------------------------------------------------------------
cleanup.tag = 'cleanup';
cleanup.type = 'menu';
cleanup.name = 'Clean up the partitions';
cleanup.help = {[...
'This uses a crude routine for extracting the brain from segmented ',...
'images. It begins by taking the white matter, and eroding it a ',...
'couple of times to get rid of any odd voxels. The algorithm ',...
'continues on to do conditional dilations for several iterations, ',...
'where the condition is based upon grey or white matter being present. ',...
'This identified region is then used to clean up the grey and white ',...
'matter partitions, and has a slight influences on the CSF partition.']};
cleanup.labels = {'Clean up the partitions','Dont do cleanup'};
cleanup.values = {1 0};
cleanup.def = 'segment.write.cleanup';
%------------------------------------------------------------------------
wrt_cor.tag = 'wrt_cor';
wrt_cor.type = 'menu';
wrt_cor.name = 'Write bias correted image';
wrt_cor.help = {'Write bias correted versions of the images to disk'};
wrt_cor.labels = {'Write bias corrected','Dont write bias corrected'};
wrt_cor.values = {1 0};
wrt_cor.def = 'segment.write.wrt_cor';
%------------------------------------------------------------------------
bias = struct('type','branch','name','Bias correction','tag','bias',...
'dim', Inf ,'val',{{reg,cutoff,wrt_cor}});
bias.help = {[...
'This 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).']};
%------------------------------------------------------------------------
opts.type = 'branch';
opts.tag = 'oldsegment';
opts.name = 'Old Segment';
opts.prog = @execute;
opts.vfiles = @vfiles;
opts.dim = Inf;
opts.val = {data,overlay,bias,custom,cleanup};
opts.help = {...
'Segment an MR image into Grey, White & CSF.',...
'',...
'The algorithm is four step:',...
[...
'1) Determine the affine transform which best matches the image with a ',...
' template image. If the name of more than one image is passed, then ',...
' the first image is used in this step. This step is not performed if ',...
' no template images are specified.'],...
[...
'2) Perform Cluster Analysis with a modified Mixture Model and a-priori ',...
' information about the likelihoods of each voxel being one of a ',...
' number of different tissue types. If more than one image is passed, ',...
' then they they are all assumed to be in register, and the voxel ',...
' values are fitted to multi-normal distributions.'],...
[...
'3) Do a "cleanup" of the partitions, analagous to what <Xtract Brain> ',...
' followed by <ImCalc> with "i1.*i4./(i1+i2+i3+eps)" did with SPM99.'],...
[...
'4) Write the segmented image. The names of these images have ',...
' "c1", "c2" & "c3" prepended to the name of the ',...
' first image passed.'],...
'',...
' _______________________________________________________________________ ',...
' Refs: ',...
'',...
[' Ashburner J & Friston KJ (1997) Multimodal Image Coregistration and ',...
' Partitioning - a Unified Framework. NeuroImage 6:209-217'],...
'',...
[' Ashburner J & Friston KJ (2000) Voxel-Based Morphometry - The Methods. ',...
' NeuroImage 11(6):805-821'],...
'',...
[' Ashburner J (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.'],...
'',...
' _______________________________________________________________________ ',...
};
return;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function execute(varargin)
job = varargin{1};
flags.estimate.priors = strvcat(job.custom.priors);
flags.estimate.reg = job.bias.reg;
flags.estimate.cutoff = job.bias.cutoff;
flags.estimate.samp = job.custom.samp;
flags.estimate.bb = job.custom.bb;
flags.write.cleanup = job.cleanup;
flags.write.wrt_cor = job.bias.wrt_cor;
data = {{}};
if isfield(job.data,'singlespec'),
data = {};
singlespec = job.data.singlespec;
for i=1:length(singlespec),
data = {data{:},deblank(singlespec{i})};
end;
elseif isfield(job.data,'multispec'),
data = {};
for i=1:length(job.data.multispec),
data = {data{:},strvcat(job.data.multispec{i})};
end;
end;
if isfield(job.overlay,'unnecessary'),
VG = eye(4);
else
VG = spm_vol(strvcat(job.overlay.affreg.template));
flags.estimate.affreg.smosrc = job.overlay.affreg.smosrc;
flags.estimate.affreg.regtype = job.overlay.affreg.regtype;
flags.estimate.affreg.weight = strvcat(job.overlay.affreg.weight);
end;
for i=1:length(data),
spm_segment(data{i},VG,flags);
end;
%------------------------------------------------------------------------
%------------------------------------------------------------------------
function vf = vfiles(varargin)
job = varargin{1};
vf = {};
if job.bias.wrt_cor, n=4; else n=3; end;
if isfield(job.data,'singlespec'),
vf = cell(n,numel(job.data.singlespec));
for i=1:numel(job.data.singlespec),
[pth,nam,ext,num] = spm_fileparts(job.data.singlespec{i});
sub = {...
fullfile(pth,['c1', nam, ext, num]),...
fullfile(pth,['c2', nam, ext, num]),...
fullfile(pth,['c3', nam, ext, num]),...
fullfile(pth,['m', nam, ext, num])};
for j=1:n,
vf{j,i} = sub{j};
end;
end;
elseif isfield(job.data,'multispec'),
vf = cell(n,numel(job.data.multispec));
for i=1:numel(job.data.multispec),
[pth,nam,ext,num] = spm_fileparts(job.data.multispec{i}{1});
sub = {...
fullfile(pth,['c1', nam, ext, num]),...
fullfile(pth,['c2', nam, ext, num]),...
fullfile(pth,['c3', nam, ext, num]),...
fullfile(pth,['m', nam, ext, num])};
for j=1:n,
vf{j,i} = sub{j};
end;
end;
end;
|
github
|
spm/spm5-master
|
spm_config_sendmail.m
|
.m
|
spm5-master/toolbox/spm_config_sendmail.m
| 3,827 |
utf_8
|
4f38b83b5b997bf9f13b735dd2b316d7
|
function c = spm_config_sendmail(varargin)
% Configuration file for sending emails
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Guillaume Flandin
% $Id: spm_config_sendmail.m 302 2005-11-16 21:42:45Z guillaume $
to.type = 'entry';
to.name = 'Recipient';
to.tag = 'recipient';
to.strtype = 's';
to.num = [1 1];
to.help = {'User to receive mail.'};
subject.type = 'entry';
subject.name = 'Subject';
subject.tag = 'subject';
subject.strtype = 's';
subject.num = [1 1];
subject.val = {['[SPM] [%DATE%] On behalf of ' spm('Ver')]};
subject.help = {['The subject line of the message. %DATE% will be ',...
'replaced by a string containing the time and date when the email is sent.']};
message.type = 'entry';
message.name = 'Message';
message.tag = 'message';
message.strtype = 's';
message.num = [1 1];
message.val = {'Hello from SPM!'};
message.help = {'A string containing the message to send.'};
attachments.type = 'files';
attachments.name = 'Attachments';
attachments.tag = 'attachments';
attachments.filter = '.*';
attachments.num = [0 Inf];
attachments.val = {{}};
attachments.help = {'List of files to attach and send along with the message.'};
smtpserver.type = 'entry';
smtpserver.name = 'SMTP Server';
smtpserver.tag = 'smtp';
smtpserver.strtype = 's';
smtpserver.num = [1 1];
try
smtpserver.val = {getpref('Internet','SMTP_Server')};
end
smtpserver.help = {'Your SMTP server. If not specified, look for sendmail help.'};
email.type = 'entry';
email.name = 'E-mail';
email.tag = 'email';
email.strtype = 's';
email.num = [1 1];
try
email.val = {getpref('Internet','E_mail')};
end
email.help = {'Your e-mail address. Look in sendmail help how to store it.'};
zipattach.type = 'menu';
zipattach.name = 'Zip attachments';
zipattach.tag = 'zip';
zipattach.labels = {'Yes' 'No'};
zipattach.values = {'Yes' 'No'};
zipattach.val = {'No'};
zipattach.help = {'Zip attachments before being sent along with the message.'};
parameters.type = 'branch';
parameters.name = 'Parameters';
parameters.tag = 'params';
parameters.val = {smtpserver,email,zipattach};
parameters.help = {['Preferences for your e-mail server (Internet SMTP ',...
'server) and your e-mail address. MATLAB tries to read the SMTP mail ',...
'server from your system registry. This should work flawlessly. If you '...
'encounter any error, identify the outgoing mail server for your ',...
'electronic mail application, which is usually listed in the ',...
'application''s preferences, or, consult your e-mail system administrator, ',...
'and update the parameters. Note that this function does not support ',...
'e-mail servers that require authentication.']};
c.type = 'branch';
c.name = 'Sendmail';
c.tag = 'sendmail';
c.val = {to,subject,message,attachments,parameters};
c.prog = @spm_sendmail;
c.help = {['Send a mail message (attachments optionals) to an ',...
'address.']};
%_______________________________________________________________________
%_______________________________________________________________________
function spm_sendmail(job)
try
setpref('Internet','SMTP_Server',job.params.smtp);
setpref('Internet','E_mail',job.params.email);
subj = strrep(job.subject,'%DATE%',datestr(now));
mesg = strrep(job.message,'%DATE%',datestr(now));
mesg = [mesg 10 10 '-- ' 10 10 'Statistical Parametric Mapping'];
if ~isempty(job.attachments)
if strcmpi(job.params.zip,'Yes')
zipfile = fullfile(tempdir,'spm_sendmail.zip');
zip(zipfile,job.attachments);
job.attachments = {zipfile};
end
sendmail(job.recipient,subj,mesg,job.attachments);
else
sendmail(job.recipient,subj,mesg);
end
catch
%- not an error to prevent an analysis to crash because of just that...
fprintf('Sendmail failed...\n');
end
|
github
|
spm/spm5-master
|
spm_eeg_inv_ecd_DrawDip.m
|
.m
|
spm5-master/toolbox/api_erp/spm_eeg_inv_ecd_DrawDip.m
| 19,904 |
utf_8
|
6c7ec83ef98b13ced7d98a3fc621b2ab
|
function varargout = spm_eeg_inv_ecd_DrawDip(action,varargin)
%___________________________________________________________________
%
% spm_eeg_inv_ecd_DrawDip
%
% Function to display the dipoles as obtained from the optim routine.
%
% Use it with arguments or not:
% - spm_eeg_inv_ecd_DrawDip('Init')
% The routine asks for the dipoles file and image to display
% - spm_eeg_inv_ecd_DrawDip('Init',sdip)
% The routine will use the avg152T1 canonical image
% - spm_eeg_inv_ecd_DrawDip('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
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% Christophe Phillips,
% $Id: spm_eeg_inv_ecd_DrawDip.m 1040 2007-12-21 20:28:30Z karl $
global st
global defaults
Fig = spm_figure('FindWin');
colors = strvcat('y','b','g','r','c','m'); % 6 possible colors
marker = strvcat('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_ecd_DrawDip('Init',sdip,P)
% Initialise the variables with GUI
% e.g. spm_eeg_inv_ecd_DrawDip('Init')
%------------------------------------------------------------------------
spm('Clear')
if nargin<2
load(spm_select(1,'^.*S.*dip.*\.mat$','Select dipole file'));
if ~exist('sdip') & exist('result')
sdip = result;
end
else
sdip = varargin{1};
end
% 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
Pcanonical = fullfile(spm('dir'),'canonical','avg152T1.nii');
if nargin<3
if ~isstruct(st)
% P = spm_select(1,'image','Image to display dipoles on');
P = Pcanonical;
elseif isempty(st.vols{1})
% P = spm_select(1,'image','Image to display dipoles on');
P = Pcanonical;
end
else
P = varargin{2};
end
if ischar(P), P = spm_vol(P); end;
spm_orthviews('Reset');
spm_orthviews('Image', P, [0.0 0.45 1 0.55]);
spm_orthviews('MaxBB');
st.callback = 'spm_image(''shopos'');';
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','Crosshair Position');
uicontrol(Fig,'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(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','edit', 'Position',[110 295 135 020].*WS,'String','','Callback','spm_image(''setposmm'')','ToolTipString','move crosshairs to mm coordinates');
st.vp = uicontrol(Fig,'Style','edit', 'Position',[110 275 135 020].*WS,'String','','Callback','spm_image(''setposvx'')','ToolTipString','move crosshairs to voxel coordinates');
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_ecd_DrawDip(''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_ecd_DrawDip(''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_ecd_DrawDip(''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','vn_x_y_z:');
uicontrol(Fig,'Style','Text', 'Position',[75 145 75 020].*WS,'String','theta, phi:');
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_ecd_DrawDip('DrawDip',l_conv,1)
set(sdip.hdl.hseed(l_conv),'Value',1); % toggle all buttons
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)
%________________________________________________________________________
case 'drawdip'
%------------------------------------------------------------------------
% FORMAT spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip,sdip)
% e.g. spm_eeg_inv_ecd_DrawDip('DrawDip',1,1,sdip)
% e.g. spm_eeg_inv_ecd_DrawDip('DrawDip',[1:5],1,sdip)
% when displaying a set of 'close' dipoles
% this defines the limit between 'close' and 'far'
% lim_cl = 10; %mm
% No more limit. All source displayed as projected on mean 3D cut.
if nargin<2
error('At least i_seed')
end
i_seed = varargin{1};
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_ecd_DrawDip');
end
% Note if i_dip==(sdip.n_dip+1) all dipoles are displayed simultaneously
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(find(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.loc{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.loc{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
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% % 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
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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.j{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(6,size(tabl_seed_dip,1),1);
% each dipole displayed has 6 handles:
% 2 per view (2*3): one for the line, the other for the circle
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.loc{tabl_seed_dip(ii,1)}(:,tabl_seed_dip(ii,2));
js = sdip.j{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,sdip.Mtb);
dip_h(:,ii) = add1dip(loc_pl,js/(eps+Mn_j*20),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.loc{tabl_seed_dip(ii,1)}(:,jj);
js = sdip.j{tabl_seed_dip(ii,1)}(jj*3+l3,sdip.Mtb);
js_m = js_m+js;
dip_h(:,ii+(jj-1)*pi_dip(1)) = ...
add1dip(loc_pl,js/Mn_j*20,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'/(eps+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_ecd_DrawDip('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 length(l_seed)==0
% 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(find(i_seed==prev_seeds)) = [];
% Remove the dipole & change the button colour
spm_eeg_inv_ecd_DrawDip('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_ecd_DrawDip('ClearDip');
if ~isempty(i_seed)
spm_eeg_inv_ecd_DrawDip('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_ecd_DrawDip('ClearDip')
spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip);
end
%________________________________________________________________________
case 'cleardip'
%------------------------------------------------------------------------
% FORMAT spm_eeg_inv_ecd_DrawDip('ClearDip',seed_i)
% e.g. spm_eeg_inv_ecd_DrawDip('ClearDip')
% clears all displayed dipoles
% e.g. spm_eeg_inv_ecd_DrawDip('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:6
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:6
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;
%________________________________________________________________________
otherwise,
warning('Unknown action string')
end;
return;
%________________________________________________________________________
%________________________________________________________________________
%________________________________________________________________________
%________________________________________________________________________
%
% SUBFUNCTIONS
%________________________________________________________________________
%________________________________________________________________________
function dh = add1dip(loc,js,mark,col,ax,Fig,bb)
% Plots the dipoles on the 3 views
% Then returns the handle to the plots
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
dh = zeros(6,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',2);
dh(2) = plot(loc(1)+[0 js(1)],loc(2)+[0 js(2)],col,'LineWidth',2);
set(ax{1}.ax,'NextPlot','replace')
% Coronal slice, # 2
set(Fig,'CurrentAxes',ax{2}.ax)
set(ax{2}.ax,'NextPlot','add')
dh(3) = plot(loc(1),loc(3),[mark,col],'LineWidth',2);
dh(4) = plot(loc(1)+[0 js(1)],loc(3)+[0 js(3)],col,'LineWidth',2);
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(5) = plot(bb(2,2)-bb(1,2)-loc(2),loc(3),[mark,col],'LineWidth',2);
dh(6) = plot(bb(2,2)-bb(1,2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2);
set(ax{3}.ax,'NextPlot','replace')
return
%________________________________________________________________________
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
|
github
|
spm/spm5-master
|
eeglab_fastif.m
|
.m
|
spm5-master/toolbox/api_erp/eeglab_fastif.m
| 1,367 |
utf_8
|
4d8780482e0ea0bb45ea3e4ea85261cd
|
% fastif() - fast if function.
%
% Usage:
% >> res = fastif(test, s1, s2);
%
% Input:
% test - logical test with result 0 or 1
% s1 - result if 1
% s2 - result if 0
%
% Output:
% res - s1 or s2 depending on the value of the test
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% $Log: fastif.m,v $
% Revision 1.1 2002/04/05 17:39:45 jorn
% Initial revision
%
% 01-25-02 reformated help & license -ad
function res = eeglab_fastif(s1, s2, s3);
if s1
res = s2;
else
res = s3;
end;
return;
|
github
|
spm/spm5-master
|
spm_api_erp.m
|
.m
|
spm5-master/toolbox/api_erp/spm_api_erp.m
| 29,617 |
utf_8
|
14876864a53a1a4695dd23e6782d44cd
|
function varargout = spm_api_erp(varargin)
% SPM_API_ERP Application M-file for spm_api_erp.fig
% FIG = SPM_API_ERP launch spm_api_erp GUI.
% SPM_API_ERP('callback_name', ...) invoke the named callback.
%__________________________________________________________________________
% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_api_erp.m 1106 2008-01-17 16:57:56Z guillaume $
if nargin == 0 || nargin == 1 % LAUNCH GUI
fig = openfig(mfilename,'reuse');
Fgraph = spm_figure('GetWin','Graphics');
% Use system color scheme for figure:
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
% Generate a structure of handles to pass to callbacks, and store it.
handles = guihandles(fig);
handles.Fgraph = Fgraph;
guidata(fig, handles);
if nargin == 1
load_Callback(fig, [], handles, varargin{1})
end
if nargout > 0
varargout{1} = fig;
end
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
try
if (nargout)
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
catch
disp(lasterr);
end
end
% Callbacks
%==========================================================================
%-DCM files and directories: Load and save
%==========================================================================
% --- Executes on button press in load.
% -------------------------------------------------------------------------
function varargout = load_Callback(hObject, eventdata, handles, varargin)
try
DCM = varargin{1};
[p,f] = fileparts(DCM.name);
catch
[f,p] = uigetfile('*.mat','please select DCM file');
cd(p)
name = fullfile(p,f);
DCM = load(name,'-mat');
DCM = DCM.DCM;
DCM.name = name;
handles.DCM = DCM;
guidata(hObject,handles);
end
% Type of model
%--------------------------------------------------------------------------
% 'ERP' - (linear NMM slow)
% 'SEP' - (linear NMM fast)
% 'NMM' - (bilinear NMM)
% 'MFM' - (bilinear MFM)
% 'Induced - (linear NMM)
try
model = DCM.options.model;
catch
model = get(handles.ERP,'String');
model = model{get(handles.ERP,'Value')};
end
switch model
case{'ERP'}, set(handles.ERP,'Value',1);
case{'SEP'}, set(handles.ERP,'Value',2);
case{'NMM'}, set(handles.ERP,'Value',3);
case{'MFM'}, set(handles.ERP,'Value',4);
case{'Induced'}, set(handles.ERP,'Value',5);
otherwise
end
handles = ERP_Callback(hObject, eventdata, handles);
% Filename
%--------------------------------------------------------------------------
try, set(handles.name,'String',f); end
% Source locations
%--------------------------------------------------------------------------
try, DCM.Lpos = DCM.M.dipfit.L.pos; end
% enter options from saved options and execute data_ok and spatial_ok
%--------------------------------------------------------------------------
try, set(handles.Y1, 'String', num2str(DCM.options.trials,'%7.0f')); end
try, set(handles.T1, 'String', num2str(DCM.options.Tdcm(1))); end
try, set(handles.T2, 'String', num2str(DCM.options.Tdcm(2))); end
try, set(handles.Hz1,'String', num2str(DCM.options.Fdcm(1))); end
try, set(handles.Hz2,'String', num2str(DCM.options.Fdcm(2))); end
try, set(handles.Rft,'String', num2str(DCM.options.Rft)); end
try, set(handles.Spatial_type,'Value', DCM.options.type); end
try, set(handles.Nmodes, 'Value', DCM.options.Nmodes); end
try, set(handles.h, 'Value', DCM.options.h); end
try, set(handles.han, 'Value', DCM.options.han); end
try, set(handles.D, 'Value', DCM.options.D); end
try, set(handles.lock, 'Value', DCM.options.lock); end
try, set(handles.design, 'String',num2str(DCM.xU.X','%7.2f')); end
try, set(handles.Uname, 'String',DCM.xU.name); end
try, set(handles.onset, 'String',num2str(DCM.options.onset)); end
try, set(handles.Sname, 'String',strvcat(DCM.Sname)); end
try, set(handles.Slocation, 'String',num2str(DCM.Lpos','%4.0f')); end
% catch for backwards compatibility
%--------------------------------------------------------------------------
if get(handles.Spatial_type,'Value') > length(get(handles.Spatial_type,'String'))
set(handles.Spatial_type,'Value',1);
end
if get(handles.Spatial_type,'Value') == 2
set(handles.render, 'Enable','on' )
set(handles.Imaging,'Enable','on' )
else
set(handles.render, 'Enable','off' )
set(handles.Imaging,'Enable','off' )
end
set(handles.data_ok,'enable','on')
handles.DCM = DCM;
guidata(hObject, handles);
% data specification
%--------------------------------------------------------------------------
try
handles = data_ok_Callback(hObject, eventdata, handles);
guidata(hObject, handles);
catch
return
end
% spatial model specification
%--------------------------------------------------------------------------
try
handles = spatial_ok_Callback(hObject, eventdata, handles);
guidata(hObject, handles);
catch
return
end
% connections specification
%--------------------------------------------------------------------------
try
connections_Callback(hObject, eventdata, handles);
set(handles.estimate, 'Enable', 'on');
set(handles.initialise, 'Enable', 'on');
guidata(hObject, handles);
catch
return
end
% estimation and results
%--------------------------------------------------------------------------
try
handles.DCM.F;
set(handles.results, 'Enable','on');
if handles.DCM.options.type == 2
set(handles.render, 'Enable','on');
set(handles.Imaging,'Enable','on');
end
catch
set(handles.results, 'Enable','off');
end
% --- Executes on button press in save.
% -------------------------------------------------------------------------
function handles = save_Callback(hObject, eventdata, handles)
handles = reset_Callback(hObject, eventdata, handles);
try
[p,f] = fileparts(handles.DCM.name);
catch
try
[p,f] = fileparts(handles.DCM.xY.Dfile);
f = ['DCM_' f];
catch
f = ['DCM' date];
end
end
[f,p] = uiputfile(['DCM*.mat'],'DCM file to save',f);
if p
handles.DCM.name = fullfile(p,f);
set(handles.name,'String',f);
DCM = handles.DCM;
save(DCM.name,'DCM')
set(handles.estimate, 'Enable', 'on')
set(handles.initialise, 'Enable', 'on');
end
% assign in base
%--------------------------------------------------------------------------
assignin('base','DCM',handles.DCM)
guidata(hObject,handles);
% store selections in DCM
% -------------------------------------------------------------------------
function handles = reset_Callback(hObject, eventdata, handles)
handles.DCM.options.trials = str2num(get(handles.Y1, 'String'));
handles.DCM.options.Tdcm(1) = str2num(get(handles.T1, 'String'));
handles.DCM.options.Tdcm(2) = str2num(get(handles.T2, 'String'));
handles.DCM.options.Fdcm(1) = str2num(get(handles.Hz1, 'String'));
handles.DCM.options.Fdcm(2) = str2num(get(handles.Hz2, 'String'));
handles.DCM.options.Rft = str2num(get(handles.Rft, 'String'));
handles.DCM.options.onset = str2num(get(handles.onset, 'String'));
handles.DCM.options.Nmodes = get(handles.Nmodes, 'Value');
handles.DCM.options.h = get(handles.h, 'Value');
handles.DCM.options.han = get(handles.han, 'Value');
handles.DCM.options.D = get(handles.D, 'Value');
handles.DCM.options.type = get(handles.Spatial_type, 'Value');
handles.DCM.options.lock = get(handles.lock, 'Value');
% save model
%--------------------------------------------------------------------------
model = get(handles.ERP, 'String');
model = model{get(handles.ERP,'Value')};
handles.DCM.options.model = model;
guidata(hObject,handles);
% Data selection and design
%==========================================================================
%-Get trials and data
%--------------------------------------------------------------------------
function Y1_Callback(hObject, eventdata, handles)
try
trials = str2num(get(handles.Y1,'String'));
handles.DCM.options.trials = trials;
set(handles.Y1,'String',num2str(trials,'%7.0f'))
m = length(handles.DCM.options.trials);
catch
m = 1;
set(handles.Y1,'String','1')
end
handles = Xdefault(hObject,handles,m);
%-Get new trial data from file
%--------------------------------------------------------------------------
try
spm_eeg_ldata(handles.DCM.xY.Dfile);
catch
[f,p] = uigetfile({'*.mat'}, 'please select data file');
handles.DCM.xY.Dfile = fullfile(p,f);
end
% Assemble and display data
%--------------------------------------------------------------------------
handles = reset_Callback(hObject, eventdata, handles);
handles.DCM = spm_dcm_erp_data(handles.DCM,handles.DCM.options.h);
set(handles.design,'enable', 'on')
set(handles.Uname, 'enable', 'on')
set(handles.Y, 'enable', 'on')
guidata(hObject,handles);
warndlg({'Your design matrix has been re-set'})
% --- Executes on button press in Y to display data
%--------------------------------------------------------------------------
function Y_Callback(hObject, eventdata, handles)
handles = reset_Callback(hObject, eventdata, handles);
try
handles.DCM = spm_dcm_erp_data(handles.DCM,handles.DCM.options.h);
spm_dcm_erp_results(handles.DCM,'Data');
set(handles.dt, 'String',sprintf('bins: %.1fms',handles.DCM.xY.dt*1000))
set(handles.dt, 'Visible','on')
catch
warndlg('please specify data and trials');
end
guidata(hObject,handles);
% --- Executes on button press in Uname.
%--------------------------------------------------------------------------
function Uname_Callback(hObject, eventdata, handles)
try
m = length(handles.DCM.options.trials);
catch
warndlg('please select trials')
handles = Xdefault(hObject,handles,1);
return
end
Str = get(handles.Uname,'String');
n = size(handles.DCM.xU.X,2);
for i = 1:n
try
Uname{i} = Str{i};
catch
Uname{i} = sprintf('effect %i',i);
end
end
set(handles.Uname,'string',Uname(:))
handles.DCM.xU.name = Uname;
guidata(hObject,handles);
% --- Executes on button press in design.
%--------------------------------------------------------------------------
function design_Callback(hObject, eventdata, handles)
try
m = length(handles.DCM.options.trials);
catch
handles = Xdefault(hObject,handles,1);
warndlg('please select trials')
return
end
try
X = str2num(get(handles.design,'String'))';
handles.DCM.xU.X = X(1:m,:);
set(handles.design, 'String',num2str(handles.DCM.xU.X','%7.2f'));
catch
handles = Xdefault(hObject,handles,m);
end
n = size(handles.DCM.xU.X,2);
Uname = {};
for i = 1:n
try
Uname{i} = handles.DCM.xU.name{i};
catch
Uname{i} = sprintf('effect %i',i);
end
end
set(handles.Uname,'string',Uname(:))
handles.DCM.xU.name = Uname;
guidata(hObject,handles);
% Spatial model specification
%==========================================================================
function handles = spatial_ok_Callback(hObject, eventdata, handles)
handles = reset_Callback(hObject, eventdata, handles);
% spatial model
%--------------------------------------------------------------------------
DCM = handles.DCM;
tmp = deblank(get(handles.Sname, 'String'));
if size(tmp,1) == 0
errordlg('Please specify the source names');
return
end
k = 1;
for i = 1:size(tmp, 1)
if ~isempty(deblank(tmp(i,:)))
Sname{k} = deblank(tmp(i,:));
k = k + 1;
end
end
Nareas = length(Sname);
Nmodes = get(handles.Nmodes,'Value');
DCM.Sname = Sname;
% switch for spatial forward model
%--------------------------------------------------------------------------
DCM.options.type = get(handles.Spatial_type,'Value');
% read location coordinates
%--------------------------------------------------------------------------
Slocation = zeros(Nareas, 3);
tmp = get(handles.Slocation, 'String');
if ~isempty(tmp) & size(tmp,1) == Nareas
for i = 1:Nareas
tmp2 = str2num(tmp(i, :));
if length(tmp2) ~= 3
errordlg(sprintf('coordinates of area %d not valid',i));
return;
else
Slocation(i, :) = tmp2;
end
end
if size(Slocation, 1) ~= Nareas
errordlg('Number of source names and locations must correspond');
return;
end
else
errordlg(sprintf('Please specify %d source locations.', Nareas));
return
end
% set prior expectations about locations
%--------------------------------------------------------------------------
DCM.Lpos = Slocation';
% forward model (spatial)
%--------------------------------------------------------------------------
DCM = spm_dcm_erp_dipfit(DCM);
handles.DCM = DCM;
set(handles.Spatial_type, 'Enable', 'off');
set(handles.spatial_ok, 'Enable', 'off');
set(handles.onset, 'Enable', 'off');
set(handles.Sname, 'Enable', 'off');
set(handles.Slocation, 'Enable', 'off');
set(handles.spatial_back, 'Enable', 'off');
set(handles.con_reset, 'Enable', 'on');
set(handles.connectivity_back,'Enable', 'on');
set(handles.Hz1, 'Enable', 'on');
set(handles.Hz2, 'Enable', 'on');
set(handles.Rft, 'Enable', 'on');
% [re]-set connections
%--------------------------------------------------------------------------
handles = connections_Callback(hObject, eventdata, handles);
guidata(hObject,handles);
% --- Executes on button press in pos.
%--------------------------------------------------------------------------
function pos_Callback(hObject, eventdata, handles)
[f,p] = uigetfile('*.mat','source (n x 3) location file');
Slocation = load(fullfile(p,f));
name = fieldnames(Slocation);
Slocation = getfield(Slocation, name{1});
set(handles.Slocation,'String',num2str(Slocation,'%4.0f'));
%-Executes on button press in data_ok.
%--------------------------------------------------------------------------
function handles = data_ok_Callback(hObject, eventdata, handles)
handles = reset_Callback(hObject, eventdata, handles);
handles.DCM = spm_dcm_erp_data(handles.DCM,handles.DCM.options.h);
% enable next stage, disable data specification
%--------------------------------------------------------------------------
set(handles.Y1, 'Enable', 'off');
set(handles.T1, 'Enable', 'off');
set(handles.T2, 'Enable', 'off');
set(handles.Nmodes, 'Enable', 'off');
set(handles.h, 'Enable', 'off');
set(handles.D, 'Enable', 'off');
set(handles.design, 'Enable', 'off');
set(handles.Uname, 'Enable', 'off');
set(handles.data_ok, 'Enable', 'off');
set(handles.Spatial_type, 'Enable', 'on');
set(handles.plot_dipoles, 'Enable', 'on');
set(handles.onset, 'Enable', 'on');
set(handles.Sname, 'Enable', 'on');
set(handles.Slocation, 'Enable', 'on');
set(handles.spatial_back, 'Enable', 'on');
set(handles.spatial_ok, 'Enable', 'on');
guidata(hObject, handles);
% --- Executes on button press in spatial_back.
%----------------------------------------------------------------------
function spatial_back_Callback(hObject, eventdata, handles)
set(handles.Spatial_type, 'Enable', 'off');
set(handles.spatial_ok, 'Enable', 'off');
set(handles.onset, 'Enable', 'off');
set(handles.Sname, 'Enable', 'off');
set(handles.Slocation, 'Enable', 'off');
set(handles.spatial_back, 'Enable', 'off');
set(handles.Y, 'Enable', 'on');
set(handles.Y1, 'Enable', 'on');
set(handles.T1, 'Enable', 'on');
set(handles.T2, 'Enable', 'on');
set(handles.Nmodes, 'Enable', 'on');
set(handles.h, 'Enable', 'on');
set(handles.D, 'Enable', 'on');
set(handles.design, 'Enable', 'on');
set(handles.Uname, 'Enable', 'on');
set(handles.data_ok, 'Enable', 'on');
guidata(hObject, handles);
% --- Executes on button press in plot_dipoles.
%--------------------------------------------------------------------------
function plot_dipoles_Callback(hObject, eventdata, handles)
% read location coordinates
tmp = get(handles.Slocation, 'String');
Slocation = [];
if ~isempty(tmp)
for i = 1:size(tmp, 1)
tmp2 = str2num(tmp(i, :))';
if length(tmp2) == 3
Slocation = [Slocation tmp2];
end
end
end
Nlocations = size(Slocation, 2);
sdip.n_seeds = 1;
sdip.n_dip = Nlocations;
sdip.Mtb = 1;
sdip.j{1} = zeros(3*Nlocations, 1);
sdip.loc{1} = Slocation;
spm_eeg_inv_ecd_DrawDip('Init', sdip)
%-Connectivity
%==========================================================================
% Draw buttons
%--------------------------------------------------------------------------
function handles = connections_Callback(hObject, eventdata, handles)
handles = reset_Callback(hObject, eventdata, handles);
DCM = handles.DCM;
n = length(DCM.Sname); % number of sources
m = size(DCM.xU.X,2); % number of experimental inputs
l = length(DCM.options.onset); % number of peristimulus inputs
% remove previous objects
%--------------------------------------------------------------------------
h = get(handles.SPM,'Children');
for i = 1:length(h)
if strcmp(get(h(i),'Tag'),'tmp')
delete(h(i));
end
end
% no changes in coupling
%--------------------------------------------------------------------------
if ~m, B = {}; DCM.B = {}; end
% check DCM.A, DCM.B, ...
%--------------------------------------------------------------------------
try
if length(DCM.A{1}) ~= n, DCM = rmfield(DCM,'A'); end
if length(DCM.B) ~= m, DCM = rmfield(DCM,'B'); end
if size(DCM.C,1) ~= n, DCM = rmfield(DCM,'C'); end
if size(DCM.C,2) ~= l, DCM = rmfield(DCM,'C'); end
end
% connection buttons
%--------------------------------------------------------------------------
set(handles.con_reset,'Units','Normalized')
p = get(handles.con_reset,'Position');
x0 = p(1);
y0 = p(2);
sx = 1/32;
sy = 1/64;
for i = 1:n
for j = 1:n
for k = 1:3
x = x0 + (j - 1)*sx + (k - 1)*(n + 1)*sx;
y = y0 - (i + 4)*sy;
str = sprintf('data.DCM.A{%i}(%i,%i)',k,i,j);
str = ['data=guidata(gcbo);' str '=get(gcbo,''Value'');guidata(gcbo,data)'];
A{k}(i,j) = uicontrol(handles.SPM,...
'Units','Normalized',...
'Position',[x y sx sy],...
'Style','radiobutton',...
'Tag','tmp',...
'Callback',str);
% within region, between frequency coupling for 'Induced'
%--------------------------------------------------------------
if i == j
set(A{k}(i,j),'Enable','off')
end
% allow nonlinear self-connections (induced responses)
%--------------------------------------------------------------
if get(handles.ERP,'value') == 5 && k == 2
set(A{k}(i,j),'Enable','on')
end
try
set(A{k}(i,j),'Value',DCM.A{k}(i,j));
catch
DCM.A{k}(i,j) = get(A{k}(i,j),'Value');
end
end
for k = 1:m
x = x0 + (j - 1)*sx + (k - 1)*(n + 1)*sx;
y = y0 - (i + 4)*sy - (n + 1)*sy;
str = sprintf('data.DCM.B{%i}(%i,%i)',k,i,j);
str = ['data=guidata(gcbo);' str '=get(gcbo,''Value'');guidata(gcbo,data)'];
B{k}(i,j) = uicontrol(handles.SPM,...
'Units','Normalized',...
'Position',[x y sx sy],...
'Style','radiobutton',...
'Tag','tmp',...
'Callback',str);
% intrinsic modulation of H_e
%--------------------------------------------------------------
if i == j
set(B{k}(i,j),'Enable','on')
end
try
set(B{k}(i,j),'Value',DCM.B{k}(i,j));
catch
DCM.B{k}(i,j) = get(B{k}(i,j),'Value');
end
end
end
end
for i = 1:n
for j = 1:l
x = x0 + (4 - 1)*(n + 1)*sx +(j - 1)*sx;
y = y0 - (i + 4)*sy;
str = sprintf('data.DCM.C(%i,%i)',i,j);
str = ['data=guidata(gcbo);' str '=get(gcbo,''Value'');guidata(gcbo,data)'];
C(i,j) = uicontrol(handles.SPM,...
'Units','Normalized',...
'Position',[x y sx sy],...
'Style','radiobutton',...
'Tag','tmp',...
'Callback',str);
try
set(C(i,j),'Value',DCM.C(i,j));
catch
DCM.C(i,j) = get(C(i,j),'Value');
end
end
end
% string labels
%--------------------------------------------------------------------------
if get(handles.ERP,'Value') ~= 5
constr = {'A forward' 'A backward' 'A lateral' 'C input'};
else
constr = {'A linear' 'A nonlinear' '(not used)' 'C input'};
end
nsx = (n + 1)*sx;
nsy = 2*sy;
for k = 1:4
x = x0 + (k - 1)*nsx;
y = y0 - 3*sy;
str = constr{k};
S(k) = uicontrol(handles.SPM,...
'Units','Normalized',...
'Position',[x y nsx nsy],...
'HorizontalAlignment','left',...
'Style','text',...
'String',str,...
'Tag','tmp',...
'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
constr = DCM.xU.name;
for k = 1:m
x = x0 + (k - 1)*nsx;
y = y0 - 6*sy - 2*(n + 1)*sy;
str = ['B ' constr{k}];
S(4 + k) = uicontrol(handles.SPM,...
'Units','Normalized',...
'Position',[x y nsx nsy],...
'HorizontalAlignment','left',...
'Style','text',...
'String',str,...
'Tag','tmp',...
'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
handles.S = S;
handles.A = A;
handles.B = B;
handles.C = C;
handles.DCM = DCM;
set(handles.estimate, 'Enable','on');
set(handles.initialise, 'Enable','on');
guidata(hObject,handles)
% remove existing buttons and set DCM.A,.. to zero
%--------------------------------------------------------------------------
function con_reset_Callback(hObject, eventdata, handles)
h = get(handles.SPM,'Children');
for i = 1:length(h)
if strcmp(get(h(i),'Tag'),'tmp')
delete(h(i));
end
end
try
for i = 1:length(handles.DCM.A)
handles.DCM.A{i}(:) = 0;
end
for i = 1:length(handles.DCM.B)
handles.DCM.B{i}(:) = 0;
end
handles.DCM.C(:) = 0;
end
handles = connections_Callback(hObject, eventdata, handles);
guidata(hObject,handles)
% --- Executes on button press in connectivity_back.
%--------------------------------------------------------------------------
function connectivity_back_Callback(hObject, eventdata, handles)
set(handles.con_reset, 'Enable', 'off');
set(handles.connectivity_back, 'Enable', 'off');
set(handles.Hz1, 'Enable', 'off');
set(handles.Hz2, 'Enable', 'off');
set(handles.Rft, 'Enable', 'off');
set(handles.Spatial_type, 'Enable', 'on');
set(handles.spatial_ok, 'Enable', 'on');
set(handles.onset, 'Enable', 'on');
set(handles.Sname, 'Enable', 'on');
set(handles.Slocation, 'Enable', 'on');
set(handles.spatial_back, 'Enable', 'on');
% connection buttons
%--------------------------------------------------------------------------
try
for i = 1:length(handles.A)
for j = 1:length(handles.A{i})
for k = 1:length(handles.A{i})
set(handles.A{i}(j,k), 'Enable', 'off');
end
end
end
for i = 1:length(handles.B)
for j = 1:length(handles.B{i})
for k = 1:length(handles.B{i})
set(handles.B{i}(j,k), 'Enable', 'off');
end
end
end
for i = 1:length(handles.C)
set(handles.C(i), 'Enable', 'off');
end
end
%-Estimate, initalise and review
%==========================================================================
% --- Executes on button press in estimate.
% -------------------------------------------------------------------------
function varargout = estimate_Callback(hObject, eventdata, handles, varargin)
set(handles.estimate,'String','Estimating','Foregroundcolor',[1 0 0])
handles = reset_Callback(hObject, eventdata, handles);
% initialise if required
% -------------------------------------------------------------------------
try
Ep = handles.DCM.Ep;
Str = questdlg('initialize with previous estimates');
if strcmp(Str,'Yes')
handles.DCM.M.P = Ep;
elseif strcmp(Str,'No')
handles.DCM.M.P = [];
elseif strcmp(Str,'Cancel')
return
end
end
% invert and save
% -------------------------------------------------------------------------
if get(handles.ERP,'Value') == 5
handles.DCM = spm_dcm_ind(handles.DCM);
else
handles.DCM = spm_dcm_erp(handles.DCM);
end
guidata(hObject, handles);
set(handles.results, 'Enable','on' )
set(handles.save, 'Enable','on')
set(handles.estimate, 'String','Estimated','Foregroundcolor',[0 0 0])
if get(handles.Spatial_type,'Value') == 2
set(handles.render, 'Enable','on' )
set(handles.Imaging,'Enable','on' )
end
% --- Executes on button press in results.
% -------------------------------------------------------------------------
function varargout = results_Callback(hObject, eventdata, handles, varargin)
Action = get(handles.results, 'String');
Action = Action{get(handles.results, 'Value')};
if get(handles.ERP,'Value') == 5
spm_dcm_ind_results(handles.DCM, Action);
else
spm_dcm_erp_results(handles.DCM, Action);
end
% --- Executes on button press in initialise.
% -------------------------------------------------------------------------
function initialise_Callback(hObject, eventdata, handles)
[f,p] = uigetfile('DCM*.mat','please select estimated DCM');
DCM = load(fullfile(p,f), '-mat');
handles.DCM.M.P = DCM.DCM.Ep;
guidata(hObject, handles);
% --- Executes on button press in render.
% -------------------------------------------------------------------------
function render_Callback(hObject, eventdata, handles)
spm_eeg_inv_visu3D_api(handles.DCM.xY.Dfile)
% --- Executes on button press in Imaging.
% -------------------------------------------------------------------------
function Imaging_Callback(hObject, eventdata, handles)
spm_eeg_inv_imag_api(handles.DCM.xY.Dfile)
%==========================================================================
function handles = Xdefault(hObject,handles,m)
% default design matix
% m - number of trials
X = eye(m);
X(:,1) = [];
name = {};
for i = 1:size(X,2)
name{i,1} = sprintf('effect %i',i);
end
handles.DCM.xU.X = X;
handles.DCM.xU.name = name;
set(handles.design,'String',num2str(handles.DCM.xU.X','%7.2f'));
set(handles.Uname, 'String',handles.DCM.xU.name);
return
% --- Executes on button press in BMC.
%--------------------------------------------------------------------------
function BMC_Callback(hObject, eventdata, handles)
spm_api_bmc
% --- Executes on selection change in ERP.
%--------------------------------------------------------------------------
function handles = ERP_Callback(hObject, eventdata, handles)
% get model type
%--------------------------------------------------------------------------
if get(handles.ERP,'Value') ~= 5
Action = {
'ERPs (mode)',
'ERPs (sources)',
'coupling (A)',
'coupling (B)',
'coupling (C)',
'trial-specific effects',
'Input',
'Response',
'Response (image)',
'Dipoles',
'Spatial overview'};
try
set(handles.Nmodes, 'Value', handles.DCM.options.Nmodes);
catch
set(handles.Nmodes, 'Value', 8);
end
set(handles.Spatial_type, 'String', {'ECD','Imaging'});
set(handles.Wavelet, 'Enable','off');
else
Action = {
'Frequency modes'
'Time-modes'
'Time-frequency'
'Coupling (A - Hz)'
'Coupling (B - Hz)'
'Coupling (A - modes)'
'Coupling (B - modes)'
'Input (C - Hz)'
'Input (u - ms)'
'Dipoles'};
try
set(handles.Nmodes, 'Value', handles.DCM.options.Nmodes);
catch
set(handles.Nmodes, 'Value', 4);
end
set(handles.Spatial_type, 'Value', 1);
set(handles.Spatial_type, 'String', {'ECD'});
set(handles.Wavelet, 'Enable','on');
end
set(handles.results,'String',Action);
handles = reset_Callback(hObject, eventdata, handles);
guidata(hObject,handles);
% --- Executes on button press in Wavelet.
function Wavelet_Callback(hObject, eventdata, handles)
% get transform
%--------------------------------------------------------------------------
handles = reset_Callback(hObject, eventdata, handles);
handles.DCM = spm_dcm_ind_data(handles.DCM);
% and display
%--------------------------------------------------------------------------
spm_dcm_ind_results(handles.DCM,'Wavelet');
guidata(hObject,handles);
|
github
|
spm/spm5-master
|
spm_ind_u.m
|
.m
|
spm5-master/toolbox/api_erp/spm_ind_u.m
| 1,213 |
utf_8
|
4f09a9302079213c9fb56f5f28760353
|
function [U] = spm_ind_u(t,P,M)
% returns the [scalar] input for EEG models
% FORMAT [U] = spm_ind_u(t,P,M)
%
% P - parameter structure
% P.R - input parameters
%
% t - PST (seconds)
%
% U - stimulus-related (subcortical) input
% B - non-specifc background fluctuations
%
% See spm_fx_ind.m and spm_ind_priors.m
%__________________________________________________________________________
%
% David O, Friston KJ (2003) A neural mass model for MEG/EEG: coupling and
% neuronal dynamics. NeuroImage 20: 1743-1755
%__________________________________________________________________________
% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id$
% stimulus - subcortical impulse - a gamma function
%--------------------------------------------------------------------------
ons = M.ons(:);
dur = M.dur*1000;
t = t(:)';
j = 1:length(t);
for i = 1:length(ons)
m = exp(P.R(i,1))* ons(i);
v = exp(P.R(i,2))*(dur/16)^2;
U(i,:) = Gpdf(t*1000,m*m/v,m/v);
end
function f = Gpdf(x,h,l)
%--------------------------------------------------------------------------
Q = find(x > 0);
f = x*0;
f(Q) = x(Q).^(h - 1).*exp(-l*x(Q))*(l^h)/gamma(h);
|
github
|
spm/spm5-master
|
spm_dcm_erp_viewspatial.m
|
.m
|
spm5-master/toolbox/api_erp/spm_dcm_erp_viewspatial.m
| 10,583 |
utf_8
|
5715dfb79931731bfacb87b4aec2ac32
|
function varargout = spm_dcm_erp_viewspatial(varargin)
% SPM_DCM_ERP_VIEWSPATIAL M-file for spm_dcm_erp_viewspatial.fig
% SPM_DCM_ERP_VIEWSPATIAL, by itself, creates a new SPM_DCM_ERP_VIEWSPATIAL or raises the existing
% singleton*.
%
% H = SPM_DCM_ERP_VIEWSPATIAL returns the handle to a new SPM_DCM_ERP_VIEWSPATIAL or the handle to
% the existing singleton*.
%
% SPM_DCM_ERP_VIEWSPATIAL('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SPM_DCM_ERP_VIEWSPATIAL.M with the given input arguments.
%
% SPM_DCM_ERP_VIEWSPATIAL('Property','Value',...) creates a new SPM_DCM_ERP_VIEWSPATIAL or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before spm_dcm_erp_viewspatial_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to spm_dcm_erp_viewspatial_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help spm_dcm_erp_viewspatial
% Last Modified by GUIDE v2.5 12-Jul-2006 11:06:13
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @spm_dcm_erp_viewspatial_OpeningFcn, ...
'gui_OutputFcn', @spm_dcm_erp_viewspatial_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before spm_dcm_erp_viewspatial is made visible.
function spm_dcm_erp_viewspatial_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to spm_dcm_erp_viewspatial (see VARARGIN)
% Choose default command line output for spm_dcm_erp_viewspatial
handles.output = hObject;
DCM = varargin{1};
handles.DCM = DCM;
handles.ms = DCM.xY.Time;
handles.T = 1;
M = DCM.M;
load(DCM.xY.Dfile); % ----> returns SPM/EEG struct D
handles.D = D;
% locations for plotting
CTF = load(fullfile(spm('dir'), 'EEGtemplates', D.channels.ctf));
CTF.Cpos = CTF.Cpos(:, D.channels.order(D.channels.eeg));
handles.x = min(CTF.Cpos(1,:)):0.01:max(CTF.Cpos(1,:));
handles.y = min(CTF.Cpos(2,:)):0.01:max(CTF.Cpos(2,:));
[handles.x1, handles.y1] = meshgrid(handles.x, handles.y);
handles.xp = CTF.Cpos(1,:)';
handles.yp = CTF.Cpos(2,:)';
Nchannels = size(CTF.Cpos, 2);
handles.Nchannels = Nchannels;
handles.y_proj = DCM.xY.y*DCM.M.E;
handles.CLim1_yp = min(min(handles.y_proj));
handles.CLim2_yp = max(max(handles.y_proj));
handles.Nt = size(handles.y_proj, 1);
% data and model fit
handles.yd = NaN*ones(handles.Nt, Nchannels);
handles.ym = NaN*ones(handles.Nt, Nchannels);
handles.yd(:, DCM.M.dipfit.Ic) = handles.y_proj*DCM.M.E'; % data (back-projected to channel space)
handles.ym(:, DCM.M.dipfit.Ic) = cat(1,DCM.H{:})*DCM.M.E'; % model fit
handles.CLim1 = min(min([handles.yd handles.ym]));
handles.CLim2 = max(max([handles.yd handles.ym]));
% set slider's range and initial value
set(handles.slider1, 'min', 1);
set(handles.slider1, 'max', handles.Nt);
set(handles.slider1, 'Value', 1);
set(handles.slider1, 'Sliderstep', [1/(handles.Nt-1) 10/(handles.Nt-1)]); % moves slider in dt and 10*dt steps
plot_images(hObject, handles);
plot_modes(hObject, handles);
plot_dipoles(hObject, handles);
plot_components_space(hObject, handles);
try
plot_components_time(hObject, handles);
end
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes spm_dcm_erp_viewspatial wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = spm_dcm_erp_viewspatial_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject handle to slider1 (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,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles.T = round(get(handles.slider1, 'Value'));
plot_images(hObject, handles);
plot_modes(hObject, handles);
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function slider1_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
%--------------------------------------------------------------------
function plot_images(hObject, handles)
T = handles.T;
axes(handles.axes1); cla
z = griddata(handles.xp, handles.yp, handles.yd(T,:), handles.x1, handles.y1);
surface(handles.x, handles.y, z);
axis off
axis square
shading('interp')
hold on
plot3(handles.xp, handles.yp, handles.yd, 'k.');
set(handles.axes1, 'CLim', [handles.CLim1 handles.CLim2])
title('data', 'FontSize', 16);
axes(handles.axes2); cla
z = griddata(handles.xp, handles.yp, handles.ym(T,:), handles.x1, handles.y1);
surface(handles.x, handles.y, z);
axis off
axis square
shading('interp')
hold on
plot3(handles.xp, handles.yp, handles.ym, 'k.');
set(handles.axes2, 'CLim', [handles.CLim1 handles.CLim2])
title('model', 'FontSize', 16);
guidata(hObject, handles);
drawnow
%--------------------------------------------------------------------
function plot_modes(hObject, handles)
% plot temporal expression of modes
DCM = handles.DCM;
Nt = size(DCM.xY.xy{1}, 1);
Ntrials = length(DCM.H);
ms_all = kron(ones(1, Ntrials), handles.ms);
% data and model prediction, cond 1
axes(handles.axes3); cla
plot(ms_all, handles.y_proj);
hold on
plot(ms_all, cat(1, DCM.H{:}), '--');
plot([ms_all(handles.T) ms_all(handles.T)], [handles.CLim1_yp handles.CLim2_yp], 'k', 'LineWidth', 3);
% set(handles.axes3, 'XLim', [0 handles.ms(end)]);
set(handles.axes3, 'YLim', [handles.CLim1_yp handles.CLim2_yp]);
xlabel('ms');
title('Temporal expressions of modes', 'FontSize', 16);
grid on
%--------------------------------------------------------------------
function plot_dipoles(hObject, handles)
DCM = handles.DCM;
Nsources = length(DCM.M.pE.A{1});
% ECD
%--------------------------------------------------------------------
try
Lpos = handles.DCM.Eg.Lpos;
Lmom = handles.DCM.Eg.Lmom;
% Imaging
%--------------------------------------------------------------------
catch
Lpos = handles.DCM.M.dipfit.L.pos;
Lmom = Lpos*0;
end
try
elc = handles.DCM.M.dipfit.elc;
% transform sensor locations to MNI-space
iMt = inv(DCM.M.dipfit.Mmni2polsphere);
elc = iMt*[elc'; ones(1, size(elc, 1))];
elc = elc(1:3, :)';
catch
elc = sparse(0,3);
end
axes(handles.axes5);
for j = 1:Nsources
% plot dipoles using small ellipsoids
[x, y, z] = ellipsoid(handles.axes5,Lpos(1,j), Lpos(2,j), Lpos(3,j), 4, 4,4);
surf(x, y, z, 'EdgeColor', 'none', 'FaceColor', 'g');
hold on
% plot dipole moments
plot3([Lpos(1, j) Lpos(1, j) + 5*Lmom(1, j)],...
[Lpos(2, j) Lpos(2, j) + 5*Lmom(2, j)],...
[Lpos(3, j) Lpos(3, j) + 5*Lmom(3, j)], 'b', 'LineWidth', 4);
plot3(elc(:,1), elc(:,2), elc(:,3), 'r.','MarkerSize',18);
end
xlabel('x'); ylabel('y');
rotate3d(handles.axes5);
axis equal
%--------------------------------------------------------------------
function plot_components_space(hObject, handles)
% plots spatial expression of each dipole
DCM = handles.DCM;
Nsources = length(DCM.M.pE.A{1});
lf = NaN*ones(handles.Nchannels, Nsources);
lfo = NaN*ones(handles.Nchannels, Nsources);
x = [0 kron([zeros(1, 8) 1], ones(1, Nsources))];
% unprojected and projected leadfield
%--------------------------------------------------------------------
lfo(DCM.M.dipfit.Ic,:) = spm_erp_L(DCM.Ep,DCM.M);
lf = DCM.M.E*DCM.M.E'*lfo;
% use subplots in new figure
h = figure;
set(h, 'Name', 'Spatial expression of sources');
for j = 1:2
for i = 1:Nsources
if j == 1
% projected
handles.hcomponents{i} = subplot(2,Nsources, i);
z = griddata(handles.xp, handles.yp, lf(:, i), handles.x1, handles.y1);
title(DCM.Sname{i}, 'FontSize', 16);
else
% not projected
handles.hcomponents{i} = subplot(2,Nsources, i+Nsources);
z = griddata(handles.xp, handles.yp, lfo(:, i), handles.x1, handles.y1);
end
surface(handles.x, handles.y, z);
axis off
axis square
shading('interp')
% set(handles.axes1, 'CLim', [handles.CLim1 handles.CLim2])
end
end
drawnow
function plot_components_time(hObject, handles)
DCM = handles.DCM;
Lmom = sqrt(sum(DCM.Eg.Lmom).^2);
Nsources = length(DCM.M.pE.A{1});
h = figure;
set(h, 'Name', 'Effective source amplitudes');
% multiply with dipole amplitudes
for i = 1:Nsources
handles.hcomponents_time{2*(i-1)+1} = subplot(Nsources, 2, 2*(i-1)+1);
plot(handles.ms, Lmom(i)*DCM.K{1}(:, i));
title([handles.DCM.Sname{i} ', ERP 1'], 'FontSize', 16);
try
handles.hcomponents_time{2*(i-1)+2} = subplot(Nsources, 2, 2*(i-1)+2);
plot(handles.ms, Lmom(i)*DCM.K{2}(:, i));
title([handles.DCM.Sname{i} ', ERP 2'], 'FontSize', 16);
end
end
|
github
|
spm/spm5-master
|
fieldtrip_meg_leadfield1.m
|
.m
|
spm5-master/toolbox/api_erp/fieldtrip_meg_leadfield1.m
| 1,920 |
utf_8
|
1c068e18288e3095a3effb886c2fb352
|
function [lf] = meg_leadfield1(R, Rm, Um);
% MEG_LEADFIELD1 magnetic leadfield for a dipole in a homogenous sphere
%
% [lf] = meg_leadfield1(R, pos, ori)
%
% with input arguments
% R position dipole
% pos position magnetometers
% ori orientation magnetometers
%
% The center of the homogenous sphere is in the origin, the field
% of the dipole is not dependent on the sphere radius.
%
% This function is also implemented as MEX file.
% adapted from Luetkenhoener, Habilschrift '92
% optimized for speed using temporary variables
% the mex implementation is a literary copy of this
% Copyright (C) 2002, Robert Oostenveld
%
% $Log: meg_leadfield1.m,v $
% Revision 1.5 2003/03/28 10:01:15 roberto
% created mex implementation, updated help and comments
%
% Revision 1.4 2003/03/28 09:01:55 roberto
% fixed important bug (incorrect use of a temporary variable)
%
% Revision 1.3 2003/03/12 08:19:45 roberto
% improved help
%
% Revision 1.2 2003/03/11 14:45:37 roberto
% updated help and copyrights
%
Nchans = size(Rm, 1);
lf = zeros(Nchans,3);
tmp2 = norm(R);
for i=1:Nchans
r = Rm(i,:);
u = Um(i,:);
tmp1 = norm(r);
% tmp2 = norm(R);
tmp3 = norm(r-R);
tmp4 = dot(r,R);
tmp5 = dot(r,r-R);
tmp6 = dot(R,r-R);
tmp7 = (tmp1*tmp2)^2 - tmp4^2; % cross(r,R)^2
alpha = 1 / (-tmp3 * (tmp1*tmp3+tmp5));
A = 1/tmp3 - 2*alpha*tmp2^2 - 1/tmp1;
B = 2*alpha*tmp4;
C = -tmp6/(tmp3^3);
if tmp7<eps
beta = 0;
else
beta = dot(A*r + B*R + C*(r-R), u)/tmp7;
end
lf(i,:) = cross(alpha*u + beta*r, R);
end
lf = 1e-7*lf; % multiply with u0/4pi
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fast cross product
function [c] = cross(a,b);
c = [a(2)*b(3)-a(3)*b(2) a(3)*b(1)-a(1)*b(3) a(1)*b(2)-a(2)*b(1)];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fast dot product
function [c] = dot(a,b);
c = sum(a.*b);
|
github
|
spm/spm5-master
|
spm_dcm_erp_dipfit.m
|
.m
|
spm5-master/toolbox/api_erp/spm_dcm_erp_dipfit.m
| 10,804 |
utf_8
|
359dc005629e0fd5c8e7f095f07b622f
|
function DCM = spm_dcm_erp_dipfit(DCM)
% prepares structures for ECD forward model (both EEG and MEG)
% FORMAT DCM = spm_dcm_erp_dipfit(DCM)
% requires:
%
% needs:
% DCM.xY.Dfile
% DCM.xY.Ic
% DCM.Lpos
% DCM.options.type
% DCM.M.dipfit.sensorfile - 'ECD'
%
% fills in:
%
% DCM.M.dipfit.type - 'ECD (EEG)','ECD (MEG)','Imaging','LFP'
% DCM.M.dipfit. ...
%__________________________________________________________________________
% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_dcm_erp_dipfit.m 1058 2008-01-03 15:58:02Z guillaume $
% Get data filename and good channels
%--------------------------------------------------------------------------
try
DCM.xY.Dfile;
DCM.M.dipfit.Ic = DCM.xY.Ic;
catch
errordlg('Please specify data');
error('')
end
% Get source locations
%--------------------------------------------------------------------------
try
DCM.M.dipfit.L.pos = DCM.Lpos;
catch
try
DCM.Lpos = DCM.M.dipfit.L.pos;
catch
errordlg({'Please specify source locations',...
'in DCM.Lpos'})
end
end
% Polhemus file skip
%==========================================================================
try
Pol_skip = DCM.options.Pol_skip;
catch
Pol_skip = 2;
DCM.options.Pol_skip = Pol_skip;
end
%==========================================================================
% D - SPM data structure
%==========================================================================
D = spm_eeg_ldata(DCM.xY.Dfile);
switch DCM.options.type
% EEG - ECD
%----------------------------------------------------------------------
case 1
if strcmp(D.modality,'EEG')
% try to get sen_reg and fid_reg from D.inv
%------------------------------------------------------------------
try
sen_reg = D.inv{1}.datareg.sens_coreg;
fid_reg = D.inv{1}.datareg.fid_coreg;
catch
% Get sensor file
%--------------------------------------------------------------
try
sensorfile = DCM.M.dipfit.sensorfile;
catch
[f,p] = uigetfile({'*.mat;*.pol'},'select sensor file');
sensorfile = fullfile(p,f);
DCM.M.dipfit.sensorfile = sensorfile;
end
% Polyhmus file
%--------------------------------------------------------------
if strcmpi('pol', spm_str_manip(sensorfile, 'e'))
% returns coordinates of fiducials and sensors (filenames)
% coordinates are in CTF coordinate system
%----------------------------------------------------------
[fid, sens] = spm_eeg_inv_ReadPolhemus(sensorfile, Pol_skip);
else
% mat-file must contain 2 matrices with fid and sensor coordinates
%----------------------------------------------------------
tmp = load(sensorfile, '-mat');
fid = tmp.fid;
sens = tmp.sens;
end
% Use approximated MRI fiducials (MNI space)... for now
%--------------------------------------------------------------
mni_fid = [[0 86 -42];...
[-84 -18 -55];...
[ 84 -18 -55]];
% EEG coordinates in MNI space
% coregistration between EEG and MRI fiducials
%--------------------------------------------------------------
[eeg2mri,sen_reg,fid_reg] = spm_eeg_inv_datareg(sens, fid, mni_fid);
try
Ic = DCM.M.dipfit.Ic;
catch
D = spm_eeg_ldata(DCM.xY.Dfile);
Ic = setdiff(D.channels.eeg, D.channels.Bad);
DCM.M.dipfit.Ic = Ic;
end
sen_reg = sen_reg(Ic, :);
end
% evaluate dipfit and save in M
%------------------------------------------------------------------
DCM.M.dipfit = spm_dipfit(DCM.M.dipfit,sen_reg,fid_reg);
DCM.M.dipfit.type = 'ECD (EEG)';
% MEG - ECD
%----------------------------------------------------------------------
else
% not much to do because the sensors location/orientations were
% already read at the time of conversion.
%------------------------------------------------------------------
DCM.M.dipfit.vol.r = [85];
DCM.M.dipfit.vol.o = [0 0 0];
% done by coreg during source reconstruction
%------------------------------------------------------------------
try
DCM.M.grad = D.inv{1}.datareg.grad_coreg;
catch
DCM.M.grad = D.channels.grad;
end
DCM.M.dipfit.type = 'ECD (MEG)';
end
% Imaging (distributed source reconstruction)
%----------------------------------------------------------------------
case 2
% Load Gain or Lead field matrix
%------------------------------------------------------------------
try
DCM.val = D.val;
gainmat = D.inv{D.val}.forward.gainmat;
try
L = load(gainmat);
catch
[p,f] = fileparts(gainmat);
L = load(f);
gainmat = fullfile(pwd,f);
end
name = fieldnames(L);
L = sparse(getfield(L, name{1}));
L = spm_cond_units(L);
catch
errordlg({'Please create and save a foward model',...
'using spm_eeg_inv_imag_api'})
error('')
end
% centers
%------------------------------------------------------------------
xyz = DCM.M.dipfit.L.pos;
Np = size(xyz,2);
% parameters
%==================================================================
% defaults: Nm = 8; number of modes per region
%------------------------------------------------------------------
try, rad = DCM.M.dipfit.radius; catch, rad = 16; end
try, Nm = DCM.M.dipfit.Nm; catch, Nm = 8; end
% Compute spatial basis (eigenmodes of lead field)
%==================================================================
% create MSP spatial basis set in source space
%------------------------------------------------------------------
vert = D.inv{D.val}.mesh.tess_mni.vert;
for i = 1:Np
Dp = sum([vert(:,1) - xyz(1,i), ...
vert(:,2) - xyz(2,i), ...
vert(:,3) - xyz(3,i)].^2,2);
% nearest mesh points
%--------------------------------------------------------------
Ip = find(Dp < rad^2);
if length(Ip) < Nm;
[y,Ip] = sort(Dp);
Ip = Ip(1:Nm);
end
% left hemisphere
%--------------------------------------------------------------
U = spm_svd(L(:,Ip)',0);
U = U(:,1:Nm);
DCM.M.dipfit.G{i} = L(:,Ip)*U;
DCM.M.dipfit.U{i} = U;
DCM.M.dipfit.Ip{i} = Ip;
end
% Save results
%==================================================================
DCM.M.dipfit.radius = rad; % VOI (XYZ, Radius)
DCM.M.dipfit.Nm = Nm; % modes per region
DCM.M.dipfit.Nd = length(vert); % number of dipoles
DCM.M.dipfit.gainmat = gainmat; % Lead field filename
DCM.M.dipfit.type = 'Imaging';
end
return
function dipfit = spm_dipfit(dipfit,sen_reg,fid_reg)
%==========================================================================
% computes dipfit model for ECD, DCM
% fit origin of outer sphere, with fixed radius, to electrodes
%--------------------------------------------------------------------------
dipfit.vol.r = [71 72 79 85];
dipfit.vol.c = [0.3300 1 0.0042 0.3300];
dipfit.vol.o = [0 0 0]; % origin is always zero (forward model can't handle non-zero origin)
% origin of best fitting sphere (in MNI space)
%--------------------------------------------------------------------------
dipfit.vol.o_sphere = fminsearch(@(x) d_elc_sphere(x, sen_reg, dipfit.vol.r(4)),[0 0 0]);
% compute POL->MNI coordinate transformation, following definition of
% CTF origin, and axes
%--------------------------------------------------------------------------
% origin in MNI space
%--------------------------------------------------------------------------
POLorigin = mean(fid_reg(2:3, :));
POLvx = (fid_reg(1, :) - POLorigin)/norm((fid_reg(1, :) - POLorigin));
POLvz = cross(POLvx, fid_reg(2, :) - fid_reg(3, :));
POLvz = POLvz/norm(POLvz); % Vector normal to the NLR plane, pointing upwards
POLvy = cross(POLvz,POLvx); POLvy = POLvy/norm(POLvy);
% transformation POL->MNI. Must be the same as computed by registration
% (file RT).
%--------------------------------------------------------------------------
dipfit.Mpol2mni = [[POLvx' POLvy' POLvz' POLorigin']; [0 0 0 1]];
dipfit.MNIelc = sen_reg;
% original coordinates
%--------------------------------------------------------------------------
elc = inv(dipfit.Mpol2mni)*[dipfit.MNIelc'; ones(1, size(dipfit.MNIelc, 1))];
elc = elc(1:3,:)';
% centre of sphere in POL space
%--------------------------------------------------------------------------
o = inv(dipfit.Mpol2mni)*[dipfit.vol.o_sphere'; 1];
elc = elc - kron(ones(size(elc, 1), 1), o(1:3)');
% transformation matrix from MNI-space to sphere in POL space
%--------------------------------------------------------------------------
Msphere = eye(4);
Msphere(1:3,4) = -o(1:3);
dipfit.Mpol2sphere = Msphere; % in pol-space: translation of origin to zero
dipfit.Mmni2polsphere = Msphere*inv(dipfit.Mpol2mni); % from MNI-space to pol space (plus translation to origin)
% projecting channels to outer sphere
%--------------------------------------------------------------------------
dist = sqrt(sum((elc).^2,2));
dipfit.elc = dipfit.vol.r(4) * elc ./[dist dist dist];
return
% used for fitting sphere to sensors
%==========================================================================
function x = d_elc_sphere(x, elc, r)
% returns sum of squares of distances between sensors elc and sphere.
Nelc = size(elc, 1);
d = sqrt(sum((elc - repmat(x, Nelc, 1)).^2, 2));
x = sum((d - r).^2);
return
|
github
|
spm/spm5-master
|
eeglab_dipplot.m
|
.m
|
spm5-master/toolbox/api_erp/eeglab_dipplot.m
| 58,861 |
utf_8
|
c21091d730be6500d90bec825a97515b
|
% dipplot() - Visualize EEG equivalent-dipole locations and orientations
% in the MNI average MRI head or in the BESA spherical head model.
% Usage:
% >> dipplot( sources, 'key', 'val', ...);
% >> [sources X Y Z XE YE ZE] = dipplot( sources, 'key', 'val', ...);
%
% Inputs:
% sources - structure array of dipole information: can contain
% either BESA or DIPFIT dipole information
% besaexent: BESA eccentricity of the dipole
% besathloc: BESA azimuth angle of the dipole
% besaphloc: BESA horizontal angle of the dipole
% besathori: BESA azimuth angle of the dipole orientation
% besaphori: BESA horiz. angle of the dipole orientation
% posxyz: DIPFIT dipole 3-D Cartesian position in mm
% momxyz: DIPFIT dipole 3-D Cartesian orientation
% optional fields for BESA and DIPFIT dipole info
% component: component number
% rv: residual variance
% Optional input:
% 'rvrange' - [min max] Only plot dipoles with residual variace within the
% given range. Default: plot all dipoles.
% 'summary' - Build a summary plot with three views (top, back, side)
% 'image' - ['besa'|'mri'] Background image.
% 'mri' (or 'fullmri') uses mean-MRI brain images from the Montreal
% Neurological Institute. This option can also contain a 3-D MRI
% volume (dim 1: left to right; dim 2: anterior-posterior; dim 3:
% superior-inferior). Use 'coregist' to coregister electrodes
% with the MRI. {default: 'mri'}
% 'coreg' - [cx cy cz scale pitch roll yaw] the electrodes coordinates are
% rotated in 3-D using pitch (x plane), rool (y plane) and yaw
% (z plane). They are then scaled using 'scale' and recentered to
% 3-D coordinates [cx cy cz].
%
% Plotting options:
% 'color' - [cell array of color strings or (1,3) color arrays]. For
% exemple { 'b' 'g' [1 0 0] } gives blue, green and red.
% Dipole colors will rotate through the given colors if
% the number given is less than the number of dipoles to plot.
% A single number will be used as color index in the jet colormap.
% 'view' - 3-D viewing angle in cartesian coords.,
% [0 0 1] gives a sagittal view, [0 -1 0] a view from the rear;
% [1 0 0] gives a view from the side of the head.
% 'mesh' - ['on'|'off'] Display spherical mesh. {Default is 'on'}
% 'axistight' - ['on'|'off'] For MRI only, display the closest MRI
% slide. {Default is 'off'}
% 'gui' - ['on'|'off'] Display controls. {Default is 'on'} If gui 'off',
% a new figure is not created. Useful for incomporating a dipplot
% into a complex figure.
% 'num' - ['on'|'off'] Display component number. Take into account
% dipole size. {Default: 'off'}
% 'cornermri' - ['on'|'off'] force MRI images to the corner of the MRI volume
% (usefull when background is not black). Default: 'off'.
% 'drawedges' - ['on'|'off'] draw edges of the 3-D MRI (black in axistight,
% white otherwise.) Default is 'off'.
% 'projimg' - ['on'|'off'] Project dipole(s) onto the 2-D images, for use
% in making 3-D plots {Default 'off'}
% 'projlines' - ['on'|'off'] Plot lines connecting dipole with 2-D projection.
% Color is dashed black for BESA head and dashed black for the
% MNI brain {Default 'off'}
% 'projcol' - [color] color for the projected line {Default is same as dipole}
% 'dipolesize' - Size of the dipole sphere(s) {Default: 30}
% 'dipolelength' - Length of the dipole bar(s) {Default: 1}
% 'pointout' - ['on'|'off'] Point the dipoles outward. {Default: 'off'}
% 'sphere' - [float] radius of sphere corresponding to the skin. Default is 1.
% 'spheres' - ['on'|'off'] {default: 'off'} plot dipole markers as 3-D spheres.
% Does not yet interact with gui buttons, produces non-gui mode.
% 'spheresize' - [real>0] size of spheres (if 'on'). {default: 5}
% 'normlen' - ['on'|'off'] Normalize length of all dipoles. {Default: 'off'}
% 'std' - [cell array] plot standard deviation of dipoles. i.e.
% { [1:6] [7:12] } plot two elipsoids that best fit all the dipoles
% from 1 to 6 and 7 to 12 with radius 1 standard deviation.
% { { [1:6] 2 'linewidth' 2 } [7:12] } do the same but now the
% first elipsoid is 2 standard-dev and the lines are thicker.
% 'dipnames' - [cell array] cell array of string with a name for each dipole (or
% pair of dipole).
% Outputs:
% sources - EEG.source structure with updated 'X', 'Y' and 'Z' fields
% X,Y,Z - Locations of dipole heads (Cartesian coordinates). If there is
% more than one dipole per components, the last dipole is returned.
% XE,YE,ZE - Locations of dipole ends (Cartesian coordinates). The same
% remark as above applies.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 1st July 2002
%
% Notes: Visualized locations are not exactly the same as in BESA (because of
% manual tuning of the size of the head textures). Because of a bug in the
% Matlab warp() function, the side-view texture cannot be displayed.
% To diplay head textures, the files 'besarear.pcx' and 'besasagittal.pcx'
% are required. The Matlab image processing toolbox is also required.
%
% Example:
% % position and orientation of the first dipole
% sources(1).besaexent= 69.036;
% sources(1).besathloc= -26.71;
% sources(1).besaphloc= 19.702;
% sources(1).besathori= -80.02;
% sources(1).besaphori= 87.575;
% sources(1).rv = 0.1;
% % position and orientation of the second dipole
% sources(2).besaexent= 69.036;
% sources(2).besathloc= 46;
% sources(2).besaphloc= 39;
% sources(2).besathori= 150;
% sources(2).besaphori= -3;
% sources(2).rv = 0.05;
% % plot of the two dipoles (first in green, second in blue)
% dipplot( sources, 'color', { 'g' 'b' });
%
% % To make a stereographic plot
% figure;
% subplot(1,2,1); dipplot( sources, 'view', [43 10], 'gui', 'off');
% subplot(1,2,2); dipplot( sources, 'view', [37 10], 'gui', 'off');
%
% % To make a summary plot
% dipplot( sources, 'summary', 'on', 'dipolesize', 15, 'mesh', 'off');
%
% See also: eeglab(), dipfit()
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2002 Arnaud Delorme
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% README -- Plotting strategy:
% - All buttons have a tag 'tmp' so they can be removed
% - The component-number buttons have 'userdata' equal to 'editor' and
% can be found easily by other buttons find('userdata', 'editor')
% - All dipoles have a tag 'dipoleX' (X=their number) and can be made
% visible/invisible
% - The gcf object 'userdat' field stores the handle of the dipole that
% is currently being modified
% - Gca 'userdata' stores imqge names and position
%$Log: dipplot.m,v $
%Revision 1.104 2004/11/20 02:32:43 scott
%help msg edits: carthesian -> Cartesian
%
%Revision 1.103 2004/11/11 02:34:15 arno
%fixing dipnames
%
%Revision 1.102 2004/11/11 02:11:16 arno
%dipname -> dipnames
%
%Revision 1.101 2004/11/11 01:40:39 arno
%new dipnames option
%
%Revision 1.100 2004/06/15 17:57:06 arno
%do not know
%
%Revision 1.99 2004/06/11 00:16:12 arno
%change light
%
%Revision 1.98 2004/06/09 21:15:01 arno
%debug projcol
%
%Revision 1.97 2004/06/09 21:12:34 arno
%fixing projcolor
%
%Revision 1.96 2004/06/09 16:27:11 arno
%color debug
%
%Revision 1.95 2004/06/02 22:47:38 arno
%debug color
%
%Revision 1.94 2004/06/02 22:44:03 arno
%projection color decoding
%
%Revision 1.93 2004/06/02 22:15:42 arno
%debug color problem
%
%Revision 1.92 2004/06/01 20:37:01 arno
%fixing projection color
%
%Revision 1.91 2004/06/01 18:48:31 arno
%fixing spheres
%
%Revision 1.90 2004/06/01 16:53:35 scott
%spherecolor now works (undocumented) but gives weird color palette ??
%
%Revision 1.89 2004/06/01 15:48:50 scott
%sphere colors
%
%Revision 1.88 2004/06/01 05:03:41 scott
%sphere color
%
%Revision 1.87 2004/06/01 01:06:28 scott
%still puzzling about spheres colors ...
%
%Revision 1.86 2004/05/13 18:57:48 arno
%plot middle of two dipoles
%
%Revision 1.85 2004/05/10 14:37:59 arno
%image type
%
%Revision 1.84 2004/05/05 15:25:41 scott
%typo
%
%Revision 1.83 2004/05/05 15:24:50 scott
%typo
%,
%
%Revision 1.82 2004/05/05 15:24:00 scott
%working on sphere coloring -> ????????
%
%Revision 1.81 2004/05/05 01:17:27 scott
%added spheresize
%
%Revision 1.80 2004/05/05 00:52:11 scott
%dipole length 0 + 'spheres' again...
%
%Revision 1.79 2004/05/04 17:04:22 scott
%test for s1, p1 if spheres on
%
%Revision 1.78 2004/05/04 05:37:26 scott
%turn off 'spheres' cylinder plotting if g.dipolelenth == 0
%
%Revision 1.77 2004/04/30 18:48:53 scott
%made default image 'mri' - debugged spheres/cylinders
%
%Revision 1.76 2004/04/29 15:35:32 scott
%adding cylinders for spheres pointers
%
%Revision 1.75 2004/04/14 01:40:32 scott
%hid 'spheres' option
%
%Revision 1.74 2004/04/13 18:24:58 scott
%nothing
%
%Revision 1.73 2004/04/12 23:40:50 arno
%nothing
%
%Revision 1.72 2004/03/26 01:39:04 arno
%only plotting active dipoles
%
%Revision 1.71 2004/03/26 01:22:20 arno
%mricorner with tightview
%
%Revision 1.70 2004/03/26 00:57:17 arno
%read custom mri
%
%Revision 1.69 2004/02/27 19:13:25 arno
%nothing
%
%Revision 1.68 2004/02/23 19:17:00 arno
%remove debug msg
%
%Revision 1.67 2004/02/23 19:16:16 arno
%fixing 2 dipole problem
%
%Revision 1.66 2004/02/23 19:09:05 arno
%*** empty log message ***
%
%Revision 1.65 2004/01/28 15:26:14 arno
%detecting empty dipoles
%
%Revision 1.64 2003/11/05 20:30:51 arno
%nothing
%
%Revision 1.63 2003/11/05 18:50:28 arno
%nothing
%
%Revision 1.62 2003/10/31 23:29:29 arno
%dicreases dipole size for summary mode
%
%Revision 1.61 2003/10/31 19:50:38 arno
%reordering 2 dipoles, delete old edges
%
%Revision 1.60 2003/10/31 18:59:41 arno
%divide rvrange by 100
%
%Revision 1.59 2003/10/30 03:25:17 arno
%adding projection lines
%
%Revision 1.58 2003/10/29 23:44:38 arno
%don't know
%
%Revision 1.57 2003/10/27 18:50:06 arno
%adding edges
%
%Revision 1.56 2003/10/09 01:02:12 arno
%nothing
%
%Revision 1.55 2003/09/11 00:53:04 arno
%same
%
%Revision 1.54 2003/09/11 00:52:38 arno
%documenting new arg cornermri\
%
%Revision 1.53 2003/09/11 00:51:19 arno
%adding new param cornermri
%
%Revision 1.52 2003/08/13 00:46:07 arno
%*** empty log message ***
%
%Revision 1.51 2003/08/04 21:29:06 arno
%scale besa for summary plot
%
%Revision 1.50 2003/08/04 21:15:54 arno
%num color on MRI
%
%Revision 1.49 2003/08/04 19:08:09 arno
%[Afixing normlen in summarize mode
%
%Revision 1.48 2003/07/31 23:37:07 arno
%adding property to structure attatched to dipole
%
%Revision 1.47 2003/07/31 23:30:05 arno
%*** empty log message ***
%
%Revision 1.46 2003/07/24 17:08:03 arno
%making component number for dipfit
%
%Revision 1.45 2003/07/22 01:10:06 arno
%*** empty log message ***
%
%Revision 1.44 2003/07/21 22:04:09 arno
%debug for Matlab 5.3
%
%Revision 1.43 2003/07/21 21:55:14 arno
%fixing MNI brain for distribution
%
%Revision 1.42 2003/07/16 18:39:14 arno
%nothing
%
%Revision 1.41 2003/07/03 00:02:43 arno
%undo last change
%
%Revision 1.40 2003/07/02 23:48:56 arno
%changing outputs
%
%Revision 1.39 2003/07/02 23:38:58 arno
%debuging projections and summary
%
%Revision 1.38 2003/07/01 23:52:50 arno
%test for sphere 1 before renormalizing
%
%Revision 1.37 2003/07/01 23:49:21 arno
%try to implement contextual menu: does not work in 3-D
%
%Revision 1.36 2003/07/01 22:10:14 arno
%debuging for 2 dipoles/component
%
%Revision 1.35 2003/07/01 19:04:13 arno
%fixing view problem
%
%Revision 1.34 2003/07/01 00:21:18 arno
%implementing 3-D MNI volume
%
%Revision 1.33 2003/06/12 23:49:56 arno
%dipplot normalization
%
%Revision 1.32 2003/06/10 19:04:11 arno
%nothing
%
%Revision 1.31 2003/06/03 16:37:16 arno
%tag images
%
%Revision 1.30 2003/05/30 17:16:22 arno
%nothing
%
%Revision 1.29 2003/05/30 17:09:00 arno
%for index = 1:size(x, 2);
% dipstruct(index).posxyz = [x(index) y(index) z(index)];
% %dipstruct(index).posxyz = tmp(index).posxyz;
% dipstruct(index).momxyz = [1 1 1];
% dipstruct(index).component = index;
% dipstruct(index).rv = 0.1;
%end;
%dipplot(dipstruct);
%making xyz output compatible
%
%Revision 1.28 2003/05/30 16:06:27 arno
%nothing
%
%Revision 1.27 2003/05/14 21:36:36 arno
%nothing
%
%Revision 1.26 2003/04/30 18:42:07 arno
%calibrating roughtly the slice selection
%
%Revision 1.25 2003/04/30 16:19:28 arno
%calibrating infants
%
%Revision 1.24 2003/04/30 02:05:24 arno
%changing axis properties for images
%
%Revision 1.23 2003/04/30 01:31:53 arno
%infant option
%
%Revision 1.22 2003/04/23 18:35:11 arno
%allow to plot elipses
%
%Revision 1.21 2003/04/22 21:18:44 arno
%standard dev
%
%Revision 1.20 2003/04/19 01:15:07 arno
%debugging 2 besa dipoles
%
%Revision 1.19 2003/04/19 00:55:53 arno
%correct normalized dipole length
%
%Revision 1.18 2003/04/19 00:46:41 arno
%correcting projection
%
%Revision 1.17 2003/04/19 00:37:43 arno
%changing dipole size for BESA
%
%Revision 1.16 2003/04/11 17:26:45 arno
%accurate plotting in fullMRI
%
%Revision 1.15 2003/04/10 17:37:18 arno
%multi layer MRI plot
%
%Revision 1.14 2003/03/14 17:06:42 arno
%adding error message if plotting non-BESA dipoles on the BESA head model
%
%Revision 1.13 2003/03/14 02:11:33 arno
%automatic scaling for dipfit
%
%Revision 1.12 2003/03/11 23:33:27 arno
%typo
%
%Revision 1.11 2003/03/11 23:27:09 arno
%adding normlen parameter
%
%Revision 1.10 2003/03/11 01:20:32 arno
%updating default besaextori, debuging summary
%
%Revision 1.9 2003/03/07 00:32:53 arno
%debugging textforgui
%
%Revision 1.8 2003/03/06 17:01:10 arno
%textgui -> textforgui
%
%Revision 1.7 2003/03/06 16:50:08 arno
%adding log message
%
function [outsources, XX, YY, ZZ, XO, YO, ZO] = dipplot( sourcesori, varargin )
DEFAULTVIEW = [0 0 1];
if nargin < 1
help dipplot;
return;
end;
% reading and testing arguments
% -----------------------------
sources = sourcesori;
if ~isstruct(sources)
updatedipplot(sources(1));
% sources countain the figure handler
return
end;
% key type range default
g = finputcheck( varargin, { 'color' '' [] [];
'axistight' 'string' { 'on' 'off' } 'off';
'coreg' 'real' [] [];
'drawedges' 'string' { 'on' 'off' } 'off';
'mesh' 'string' { 'on' 'off' } 'off';
'gui' 'string' { 'on' 'off' } 'on';
'summary' 'string' { 'on' 'off' } 'off';
'view' 'real' [] [0 0 1];
'rvrange' 'real' [0 Inf] [];
'normlen' 'string' { 'on' 'off' } 'off';
'num' 'string' { 'on' 'off' } 'off';
'cornermri' 'string' { 'on' 'off' } 'off';
'std' 'cell' [] {};
'dipnames' 'cell' [] {};
'projimg' 'string' { 'on' 'off' } 'off';
'projcol' '' [] [];
'projlines' 'string' { 'on' 'off' } 'off';
'pointout' 'string' { 'on' 'off' } 'off';
'dipolesize' 'real' [0 Inf] 30;
'dipolelength' 'real' [0 Inf] 1;
'sphere' 'real' [0 Inf] 1;
'spheres' 'string' {'on' 'off'} 'off';
'links' 'real' [] [];
'image' { 'string' 'real'} [] 'mri' }, ...
'dipplot');
if isstr(g), error(g); end;
g.zoom = 1500;
% axis image and limits
% ---------------------
dat.mode = g.image;
dat.maxcoord = [ 90 100 100 ]; % location of images in 3-D, Z then Y then X
dat.axistight = strcmpi(g.axistight, 'on');
dat.drawedges = g.drawedges;
dat.coreg = g.coreg;
dat.cornermri = strcmpi(g.cornermri, 'on');
radius = 85;
if isstr(g.image) & strcmpi(g.image, 'besa')
scaling = 1.05;
% read besa images
% ----------------
warning off; imgt = double(imread('besatop.pcx' ))/255; warning on;
warning off; imgc = double(imread('besarear.pcx'))/255; warning on;
warning off; imgs = double(imread('besaside.pcx'))/255; warning on;
dat.imgs = { imgt imgc imgs };
allcoords1 = ([-1.12 1.12]*size(imgt,2)/200+0.01)*radius;
allcoords2 = ([-1.12 1.12]*size(imgt,1)/200+0.08)*radius;
allcoords3 = [-1.12 1.12]*size(imgs,1)/200*radius;
dat.imgcoords = { allcoords3 allcoords2 allcoords1 };
valinion = [ 1 0 0 ]*radius;
valnasion = [-1 0 0 ]*radius;
vallear = [ 0 -1 0 ]*radius;
valrear = [ 0 1 0 ]*radius;
valvertex = [ 0 0 1 ]*radius;
dat.tcparams = { valinion valnasion vallear valrear valvertex 0 };
%dat.imageaxis = { -1 1 -1 };
%dat.imageoffset = { [0.0 0.08 NaN ] [0.01 NaN -0.01] [ NaN -0.01 -0.025 ] };
%dat.imagemult = { 1.01 1.06 0.96 };
%dat.axislim = [-1.2 1.2 -1.2 1.2 -1.2 1.2];
COLORMESH = [.5 .5 .5];
BACKCOLOR = 'w';
elseif isstr(g.image)
fid = fopen('VolumeMNI.bin', 'rb', 'ieee-le');
if fid == -1
error('Cannot find MRI data file');
end;
V = double(fread(fid, [108 129*129], 'uint8'))/255;
V = reshape(V, 108, 129, 129);
fclose(fid);
%V = floatread('VolumeMNI.fdt');
%load('/home/arno/matlab/MNI/VolumeMNI.mat');
dat.imgs = V; %smooth3(V,'gaussian', [3 3 3]);
coordinc = 2; % 2 mm
allcoords1 = [0.5:coordinc:size(V,1)*coordinc]-size(V,1)/2*coordinc;
allcoords2 = [0.5:coordinc:size(V,2)*coordinc]-size(V,2)/2*coordinc;
allcoords3 = [0.5:coordinc:size(V,3)*coordinc]-size(V,3)/2*coordinc;
dat.imgcoords = { allcoords3 allcoords2 allcoords1 };
if strcmpi(g.cornermri, 'on') % make the corner of the MRI volume match
dat.maxcoord = [max(dat.imgcoords{1}) max(dat.imgcoords{2}) max(dat.imgcoords{3})];
end;
COLORMESH = 'w';
BACKCOLOR = 'k';
%valinion = [ 58.5413 -10.5000 -30.8419 ]*2;
%valnasion = [-56.8767 -10.5000 -30.9566 ]*2;
%vallear = [ 0.1040 -59.0000 -30.9000 ]*2;
%valrear = [ 0.1040 38.0000 -30.9000 ]*2;
%valvertex = [ 0.0238 -10.5000 49.8341 ]*2;
valinion = [ 52.5413 -10.5000 -30.8419 ]*2;
valnasion = [-50.8767 -10.5000 -30.9566 ]*2;
vallear = [ 0.1040 -51.0000 -30.9000 ]*2;
valrear = [ 0.1040 31.0000 -30.9000 ]*2;
valvertex = [ 0.0238 -10.5000 40.8341 ]*2;
zoffset = 27.1190/(27.1190+radius) * (valvertex(3)-vallear(3));
dat.tcparams = { valinion valnasion vallear valrear valvertex zoffset };
%plotimgs(IMAGESLOC, IMAGESOFFSET, IMAGESMULT, IMAGESAXIS, AXISLIM, [57 85 65]);
%view(30, 45); axis equal; return;
else % custom MRI
V = -g.image;
dat.imgs = -g.image; %smooth3(V,'gaussian', [3 3 3]);
valinion = [ 56.5413 0.000 -20.8419 ]*3.5;
valnasion = [-52.8767 0.000 -20.9566 ]*3.5;
vallear = [ -3.1040 -53.0000 -20.9000 ]*3.5;
valrear = [ -3.1040 33.0000 -20.9000 ]*3.5;
valvertex = [ 0.0238 -10.5000 50.8341 ]*3.5;
zoffset = 27.1190/(27.1190+radius) * (valvertex(3)-vallear(3));
dat.tcparams = { valinion valnasion vallear valrear valvertex zoffset };
dat.coreg = [];
coordinc = 2; % 2 mm
allcoords1 = [0.5:coordinc:size(V,1)*coordinc]-size(V,1)/2*coordinc;
allcoords2 = [0.5:coordinc:size(V,2)*coordinc]-size(V,2)/2*coordinc;
allcoords3 = [0.5:coordinc:size(V,3)*coordinc]-size(V,3)/2*coordinc;
dat.imgcoords = { allcoords3 allcoords2 allcoords1 };
if strcmpi(g.cornermri, 'on') % make the corner of the MRI volume match
dat.maxcoord = [max(dat.imgcoords{1}) max(dat.imgcoords{2}) max(dat.imgcoords{3})];
end;
COLORMESH = 'w';
BACKCOLOR = 'k';
end;
% point 0
% -------
[xx yy zz] = transcoords(0,0,0, dat.tcparams, dat.coreg);
dat.zeroloc = [ xx yy zz ];
% conversion
% ----------
if strcmpi(g.normlen, 'on')
if isfield(sources, 'besaextori')
sources = rmfield(sources, 'besaextori');
end;
end;
if ~isfield(sources, 'besathloc') & strcmpi(g.image, 'besa') & ~is_sccn
error(['For copyright reasons, it is not possible to use the BESA ' ...
'head model to plot non-BESA dipoles']);
end;
if isfield(sources, 'besathloc')
sources = convertbesaoldformat(sources);
end;
if ~isfield(sources, 'posxyz')
sources = computexyzforbesa(sources);
end;
if ~isfield(sources, 'component')
disp('No component indices, making incremental ones...');
for index = 1:length(sources)
sources(index).component = index;
end;
end;
% normalize position to unit sphere
% ---------------------------------
maxi = 0;
for index = 1:length(sources)
maxi = max(maxi,max(abs(sources(index).posxyz(:))));
end;
if maxi > 1.01 & g.sphere == 1
disp('Non-normalized dipole positions, normalizing by standard head radius 85 mm');
g.sphere = 85;
fact = 0.1;
else
fact = 1;
end;
% find non-empty sources
% ----------------------
noempt = cellfun('isempty', { sources.posxyz } );
sources = sources( find(~noempt) );
% transform coordinates
% ---------------------
outsources = sources;
for index = 1:length(sources)
sources(index).posxyz = sources(index).posxyz/g.sphere;
tmp = sources(index).posxyz(:,1);
sources(index).posxyz(:,1) = sources(index).posxyz(:,2);
sources(index).posxyz(:,2) = -tmp;
sources(index).momxyz = sources(index).momxyz/g.sphere*0.05*fact;
tmp = sources(index).momxyz(:,1);
sources(index).momxyz(:,1) = sources(index).momxyz(:,2);
sources(index).momxyz(:,2) = -tmp;
if isfield(sources, 'stdX')
tmp = sources(index).stdX;
sources(index).stdX = sources(index).stdY;
sources(index).stdY = -tmp;
end;
if strcmpi(g.normlen, 'on')
warning off;
sources(index).momxyz(1,:) = 0.2*sources(index).momxyz(1,:)/ norm(abs(sources(index).momxyz(1,:)));
if size(sources(index).momxyz,1) > 1 & sources(index).momxyz(1) ~= 0
sources(index).momxyz(2,:) = 0.2*sources(index).momxyz(2,:)/ norm(abs(sources(index).momxyz(2,:)));
end;
warning on;
end;
end;
% remove sources with out of bound Residual variance
% --------------------------------------------------
if isfield(sources, 'rv') & ~isempty(g.rvrange)
for index = length(sources):-1:1
if sources(index).rv < g.rvrange(1)/100 | sources(index).rv > g.rvrange(2)/100
sources(index) = [];
end;
end;
end;
% color array
% -----------
if isempty(g.color)
g.color = { 'g' 'b' 'r' 'm' 'c' 'y' };
if strcmp(BACKCOLOR, 'w'), g.color = { g.color{:} 'k' }; end;
end;
g.color = g.color(mod(0:length(sources)-1, length(g.color)) +1);
if ~isempty(g.color)
g.color = strcol2real( g.color, jet(64) );
end;
if ~isempty(g.projcol)
g.projcol = strcol2real( g.projcol, jet(64) );
g.projcol = g.projcol(mod(0:length(sources)-1, length(g.projcol)) +1);
else
g.projcol = g.color;
for index = 1:length(g.color)
g.projcol{index} = g.projcol{index}/2;
end;
end;
% build summarized figure
% -----------------------
if strcmp(g.summary, 'on')
figure;
options = { 'gui', 'off', 'dipolesize', g.dipolesize/1.5,'dipolelength', g.dipolelength, 'sphere', g.sphere ...
'color', g.color, 'mesh', g.mesh, 'num', g.num, 'image', g.image 'normlen' g.normlen };
axes('position', [0 0 0.5 0.5]); dipplot(sourcesori, 'view', [1 0 0] , options{:}); axis off; if strcmpi(g.image, 'besa'), scalegca(0.1); end;
axes('position', [0 0.5 0.5 .5]); dipplot(sourcesori, 'view', [0 0 1] , options{:}); axis off; if strcmpi(g.image, 'besa'), scalegca(0.1); end;
axes('position', [.5 .5 0.5 .5]); dipplot(sourcesori, 'view', [0 -1 0], options{:}); axis off; if strcmpi(g.image, 'besa'), scalegca(0.1); end;
axes('position', [0.5 0 0.5 0.5]);
%p = get(gcf, 'position');
%p(2) = p(2)+p(4)-800;
%p(4) = 800;
%p(3) = 800;
%set(gcf, 'position', p);
colorcount = 1;
if isfield(sources, 'component')
for index = 1:length(sources)
if index~=1
if sources(index).component ~= sources(index-1).component
if isempty(g.dipnames)
textforgui(colorcount) = { sprintf('Component %d (R.V. %3.2f)', ...
sources(index).component, 100*sources(index).rv) };
else
textforgui(colorcount) = { sprintf('%s (R.V. %3.2f)', ...
g.dipnames{index}, 100*sources(index).rv) };
end;
colorcount = colorcount+1;
end;
else
if isempty(g.dipnames)
textforgui(colorcount) = { sprintf( 'Component %d (R.V. %3.2f)', ...
sources(index).component, 100*sources(index).rv) };
else
textforgui(colorcount) = { sprintf('%s (R.V. %3.2f)', ...
g.dipnames{index}, 100*sources(index).rv) };
end;
colorcount = colorcount+1;
end;
end;
colorcount = colorcount-1;
allstr = strvcat(textforgui{:});
h = text(0,0.5, allstr);
if colorcount >= 15, set(h, 'fontsize', 8);end;
if colorcount >= 20, set(h, 'fontsize', 6);end;
if strcmp(BACKCOLOR, 'k'), set(h, 'color', 'w'); end;
end;
axis off;
return;
end;
% plot head graph in 3D
% ---------------------
if strcmp(g.gui, 'on')
figure;
pos = get(gca, 'position');
set(gca, 'position', [pos(1)+0.05 pos(2:end)]);
end;
plotimgs( dat, [1 1 1]);
set(gca, 'color', BACKCOLOR);
%warning off; a = imread('besaside.pcx'); warning on;
% BECAUSE OF A BUG IN THE WARP FUNCTION, THIS DOES NOT WORK (11/02)
%hold on; warp([], wy, wz, a);
% set camera target
% -----------------
% format axis (BESA or MRI)
axis equal;
set(gca, 'cameraviewanglemode', 'manual'); % disable change size
camzoom(1.2^2);
view(g.view);
%set(gca, 'cameratarget', dat.zeroloc); % disable change size
%set(gca, 'cameraposition', dat.zeroloc+g.view*g.zoom); % disable change size
axis off;
% plot sphere mesh and nose
% -------------------------
SPHEREGRAIN = 20; % 20 is Matlab default
[x y z] = sphere(SPHEREGRAIN);
hold on;
[xx yy zz] = transcoords(x, y, z, dat.tcparams, dat.coreg);
if strcmpi(COLORMESH, 'w')
hh = mesh(xx, yy, zz, 'cdata', ones(21,21,3), 'tag', 'mesh'); hidden off;
else
hh = mesh(xx, yy, zz, 'cdata', zeros(21,21,3), 'tag', 'mesh'); hidden off;
end;
%x = x*100*scaling; y = y*100*scaling; z=z*100*scaling;
%h = line(xx,yy,zz); set(h, 'color', COLORMESH, 'linestyle', '--', 'tag', 'mesh');
%h = line(xx,zz,yy); set(h, 'color', COLORMESH, 'linestyle', '--', 'tag', 'mesh');
%h = line([0 0;0 0],[-1 -1.2; -1.2 -1], [-0.3 -0.7; -0.7 -0.7]);
%set(h, 'color', COLORMESH, 'linewidth', 3, 'tag', 'noze');
% determine max length if besatextori exist
% -----------------------------------------
sizedip = [];
for index = 1:length(sources)
sizedip = [ sizedip sources(index).momxyz(3) ];
end;
maxlength = max(sizedip);
% diph = gca; % DEBUG
% colormap('jet');
% cbar
% axes(diph);
for index = 1:length(sources)
nbdip = 1;
if size(sources(index).posxyz, 1) > 1 & any(sources(index).posxyz(2,:)) nbdip = 2; end;
% reorder dipoles for plotting
if nbdip == 2
if sources(index).posxyz(1,1) > sources(index).posxyz(2,1)
tmp = sources(index).posxyz(2,:);
sources(index).posxyz(2,:) = sources(index).posxyz(1,:);
sources(index).posxyz(1,:) = tmp;
tmp = sources(index).momxyz(2,:);
sources(index).momxyz(2,:) = sources(index).momxyz(1,:);
sources(index).momxyz(1,:) = tmp;
end;
if isfield(sources, 'active'),
nbdip = length(sources(index).active);
end;
end;
for dip = 1:nbdip
x = sources(index).posxyz(dip,1);
y = sources(index).posxyz(dip,2);
z = sources(index).posxyz(dip,3);
xo = sources(index).momxyz(dip,1)*g.dipolelength;
yo = sources(index).momxyz(dip,2)*g.dipolelength;
zo = sources(index).momxyz(dip,3)*g.dipolelength;
% copy for output
% ---------------
XX(index) = -y;
YY(index) = x;
ZZ(index) = z;
XO(index) = -yo;
YO(index) = xo;
ZO(index) = zo;
if abs([x+xo,y+yo,z+zo]) >= abs([x,y,z])
xo1 = x+xo;
yo1 = y+yo;
zo1 = z+zo;
elseif strcmpi(g.pointout,'on')
xo1 = x-xo; % make dipole point outward from head center
yo1 = y-yo;
zo1 = z-zo;
else
xo1 = x+xo;
yo1 = y+yo;
zo1 = z+zo;
end
x = -x; xo1 = -xo1;
y = -y; yo1 = -yo1;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw dipole bar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
tag = [ 'dipole' num2str(index) ];
[xx yy zz] = transcoords(x, y, z, dat.tcparams, dat.coreg);
[xxo1 yyo1 zzo1] = transcoords(xo1, yo1, zo1, dat.tcparams, dat.coreg);
if ~strcmpi(g.spheres,'on') % plot dipole direction lines
h1 = line( [xx xxo1]', [yy yyo1]', [zz zzo1]');
elseif g.dipolelength>0 % plot dipole direction cylinders with end cap patch
disp('Cannot plot bar with sphere');
%thetas = 180/pi*atan(sqrt((xxo1-xx).^2+(yyo1-yy).^2)./(zzo1-zz));
%for k=1:length(xx)
% [cx cy cz] = cylinder([1 1 1],SPHEREGRAIN);
% % rotate(h1,[yy(k)-yyo1(k) xxo1(k)-xx(k) 0],thetas(k));
% cx = cx*g.spheresize/3 + xx(k);
% cy = cy*g.spheresize/3 + yy(k);
% cz = cz*g.dipolelength + zz(k);
% caxis([0 33])
% cax =caxis;
% s1 = surf(cx,cy,cz); % draw the 3-D cylinder
% set(s1,'cdatamapping','direct','FaceColor','r'); % tries to make cylinder red - doesnt work!?!
% p1 = patch(cx(end,:),cy(end,:),cz(end,:),cax(2)*ones(size(cz(end,:))));
%end
end
dipstruct.pos3d = [xx yy zz]; % value used for fitting MRI
dipstruct.posxyz = sources(index).posxyz; % value used for other purposes
if isempty(g.dipnames)
dipstruct.rv = sprintf('C %d (%3.2f)',sources(index).component,...
sources(index).rv*100);
else
dipstruct.rv = sprintf('%s (%3.2f)',g.dipnames{index}, sources(index).rv*100);
end;
if ~strcmpi(g.spheres,'on') % plot disk markers
set(h1,'userdata',dipstruct,'tag',tag,'color','k','linewidth',g.dipolesize/7.5);
if strcmp(BACKCOLOR, 'k'), set(h1, 'color', g.color{index}); end;
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw sphere or disk marker %%%%%%%%%%%%%%%%%%%%%%%%%
%
hold on;
if strcmpi(g.spheres,'on') % plot spheres
if strcmpi(g.projimg, 'on')
tmpcolor = g.color{index} / 2;
h = plotsphere([xx yy zz], g.dipolesize/6, 'color', g.color{index}, 'proj', ...
[-dat.maxcoord(3) dat.maxcoord(2) -dat.maxcoord(1)]*97/100, 'projcol', tmpcolor);
set(h(2:end), 'userdata', 'proj', 'tag', tag);
else
h = plotsphere([xx yy zz], g.dipolesize/6, 'color', g.color{index});
end;
set(h(1), 'userdata', dipstruct, 'tag', tag);
else % plot dipole markers
h = plot3(xx, yy, zz);
set(h, 'userdata', dipstruct, 'tag', tag, ...
'marker', '.', 'markersize', g.dipolesize, 'color', g.color{index});
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% project onto images %%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(g.projimg, 'on') & strcmpi(g.spheres, 'off')
tmpcolor = g.projcol{index};
% project onto z axis
tag = [ 'dipole' num2str(index) ];
if ~strcmpi(g.image, 'besa')
h = line( [xx xxo1]', [yy yyo1]', [-1 -1]'*dat.maxcoord(1));
set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize/7.5);
end;
if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;
h = plot3(xx, yy, -dat.maxcoord(1));
set(h, 'userdata', 'proj', 'tag', tag, ...
'marker', '.', 'markersize', g.dipolesize, 'color', tmpcolor);
% project onto x axis
tag = [ 'dipole' num2str(index) ];
if ~strcmpi(g.image, 'besa')
h = line( [xx xxo1]', [1 1]'*dat.maxcoord(2), [zz zzo1]');
set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize/7.5);
end;
if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;
h = plot3(xx, dat.maxcoord(2), zz);
set(h, 'userdata', 'proj', 'tag', tag, ...
'marker', '.', 'markersize', g.dipolesize, 'color', tmpcolor);
% project onto y axis
tag = [ 'dipole' num2str(index) ];
if ~strcmpi(g.image, 'besa')
h = line( [-1 -1]'*dat.maxcoord(3), [yy yyo1]', [zz zzo1]');
set(h, 'userdata', 'proj', 'tag', tag, 'color','k', 'linewidth', g.dipolesize/7.5);
end;
if strcmp(BACKCOLOR, 'k'), set(h, 'color', tmpcolor); end;
h = plot3(-dat.maxcoord(3), yy, zz);
set(h, 'userdata', 'proj', 'tag', tag, ...
'marker', '.', 'markersize', g.dipolesize, 'color', tmpcolor);
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% project onto axes %%%%%%%%%%%%%%%%%%%%%%%%%
%
if strcmpi(g.projlines, 'on')
clear h;
% project onto z axis
tag = [ 'dipole' num2str(index) ];
h(1) = line( [xx xx]', [yy yy]', [zz -dat.maxcoord(1)]');
set(h(1), 'userdata', 'proj', 'linestyle', '--', ...
'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize/7.5/5);
% project onto x axis
tag = [ 'dipole' num2str(index) ];
h(2) = line( [xx xx]', [yy dat.maxcoord(2)]', [zz zz]');
set(h(2), 'userdata', 'proj', 'linestyle', '--', ...
'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize/7.5/5);
% project onto y axis
tag = [ 'dipole' num2str(index) ];
h(3) = line( [xx -dat.maxcoord(3)]', [yy yy]', [zz zz]');
set(h(3), 'userdata', 'proj', 'linestyle', '--', ...
'tag', tag, 'color', g.color{index}, 'linewidth', g.dipolesize/7.5/5);
if ~isempty(g.projcol)
set(h, 'color', g.projcol{index});
end;
end;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw text %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
if isfield(sources, 'component')
if strcmp(g.num, 'on')
h = text(xx, yy, zz, [ ' ' int2str(sources(index).component)]);
set(h, 'userdata', dipstruct, 'tag', tag, 'fontsize', g.dipolesize/2 );
if ~strcmpi(g.image, 'besa'), set(h, 'color', 'w'); end;
end;
end;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 3-D settings
if strcmpi(g.spheres, 'on')
lighting phong;
material shiny;
camlight left;
camlight right;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% draw elipse for group of dipoles %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(g.std)
for index = 1:length(g.std)
if ~iscell(g.std{index})
plotellipse(sources, g.std{index}, 1, dat.tcparams, dat.coreg);
else
sc = plotellipse(sources, g.std{index}{1}, g.std{index}{2}, dat.tcparams, dat.coreg);
if length( g.std{index} ) > 2
set(sc, g.std{index}{3:end});
end;
end;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% buttons %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nbsrc = int2str(length(sources));
cbmesh = [ 'if get(gcbo, ''userdata''), ' ...
' set(findobj(''parent'', gca, ''tag'', ''mesh''), ''visible'', ''off'');' ...
' set(gcbo, ''string'', ''Mesh on'');' ...
' set(gcbo, ''userdata'', 0);' ...
'else,' ...
' set(findobj(''parent'', gca, ''tag'', ''mesh''), ''visible'', ''on'');' ...
' set(gcbo, ''string'', ''Mesh off'');' ...
' set(gcbo, ''userdata'', 1);' ...
'end;' ];
cbview = [ 'tmpuserdat = get(gca, ''userdata'');' ...
'if tmpuserdat.axistight, ' ...
' set(gcbo, ''string'', ''Tight view'');' ...
'else,' ...
' set(gcbo, ''string'', ''Loose view'');' ...
'end;' ...
'tmpuserdat.axistight = ~tmpuserdat.axistight;' ...
'set(gca, ''userdata'', tmpuserdat);' ...
'clear tmpuserdat;' ...
'dipplot(gcbf);' ];
viewstyle = eeglab_fastif(strcmpi(dat.mode, 'besa'), 'text', 'pushbutton');
viewstring = eeglab_fastif(dat.axistight, 'Loose view', 'Tight view');
h = uicontrol( 'unit', 'normalized', 'position', [0 0 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Top view', 'callback', 'view([0 0 1]);');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.05 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Coronal view', 'callback', 'view([0 -1 0]);');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.1 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Sagital view', 'callback', 'view([1 0 0]);');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.15 .15 .05], 'tag', 'tmp', ...
'style', 'text', 'string', '');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.2 .15 .05], 'tag', 'tmp', ...
'style', viewstyle , 'string', viewstring, 'callback', cbview);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.25 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Mesh on', 'userdata', 0, 'callback', cbmesh);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.3 .15 .05], 'tag', 'tmp', ...
'style', 'text', 'string', 'Display:','fontweight', 'bold' );
h = uicontrol( 'unit', 'normalized', 'position', [0 0.35 .15 .05], 'tag', 'tmp', ...
'style', 'text', 'string', '');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.4 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'fontweight', 'bold', 'string', 'No controls', 'callback', ...
'set(findobj(''parent'', gcbf, ''tag'', ''tmp''), ''visible'', ''off'');');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.45 .15 .05], 'tag', 'tmp', ...
'style', 'text', 'string', '');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.50 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Keep|Prev', 'callback', ...
[ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...
'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))-1));' ...
'tmpobj = get(gcf, ''userdata'');' ...
'eval(get(editobj, ''callback''));' ...
'set(tmpobj, ''visible'', ''on'');' ...
'clear editobj tmpobj;' ]);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.55 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Prev', 'callback', ...
[ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...
'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))-1));' ...
'eval(get(editobj, ''callback''));' ...
'clear editobj;' ]);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.6 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Next', 'callback', ...
[ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...
'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))+1));' ...
'dipplot(gcbf);' ...
'clear editobj;' ]);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.65 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Keep|Next', 'callback', ...
[ 'editobj = findobj(''parent'', gcf, ''userdata'', ''editor'');' ...
'set(editobj, ''string'', num2str(str2num(get(editobj, ''string''))+1));' ...
'tmpobj = get(gcf, ''userdata'');' ...
'dipplot(gcbf);' ...
'set(tmpobj, ''visible'', ''on'');' ...
'clear editobj tmpobj;' ]);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.7 .15 .05], 'tag', 'tmp', 'userdata', 'rv', ...
'style', 'text', 'string', '');
h = uicontrol( 'unit', 'normalized', 'position', [0 0.75 .15 .05], 'tag', 'tmp', 'userdata', 'editor', ...
'style', 'edit', 'string', '1', 'callback', ...
[ 'dipplot(gcbf);' ] );
h = uicontrol( 'unit', 'normalized', 'position', [0 0.8 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Plot one', 'callback', ...
[ 'for tmpi = 1:' nbsrc ',' ...
' set(findobj(''parent'', gca, ''tag'', [ ''dipole'' int2str(tmpi) ]), ''visible'', ''off'');' ...
'end; clear tmpi;' ...
'dipplot(gcbf);' ]);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.85 .15 .05], 'tag', 'tmp', ...
'style', 'pushbutton', 'string', 'Plot All', 'callback', ...
[ 'for tmpi = 1:' nbsrc ',' ...
' set(findobj(''parent'', gca, ''tag'', [ ''dipole'' int2str(tmpi) ]), ''visible'', ''on'');' ...
'end; clear tmpi;' ]);
h = uicontrol( 'unit', 'normalized', 'position', [0 0.9 .15 .05], 'tag', 'tmp', ...
'style', 'text', 'string', [num2str(length(sources)) ' dipoles:'], 'fontweight', 'bold' );
h = uicontrol( 'unit', 'normalized', 'position', [0 0.95 .15 .05], 'tag', 'tmp', ...
'style', 'text', 'string', ' ' );
set(gcf, 'userdata', findobj('parent', gca, 'tag', 'dipole1'));
dat.nbsources = length(sources);
set(gca, 'userdata', dat ); % last param=1 for MRI view tight/loose
set(gcf, 'color', BACKCOLOR);
if strcmp(g.gui, 'off')
set(findobj('parent', gcf, 'tag', 'tmp'), 'visible', 'off');
end;
if strcmp(g.mesh, 'off')
set(findobj('parent', gca, 'tag', 'mesh'), 'visible', 'off');
end;
updatedipplot(gcf);
rotate3d on;
return;
function [xx,yy,zz] = transcoords(x, y, z, TCPARAMS, coreg);
if nargin > 4 & ~isempty(coreg) % custom MRI co-registration
% rotation scale center
newcoords = transformcoords( [x(:) y(:) z(:)], coreg(5:7), coreg(4), coreg(1:3) );
xx = newcoords(:,1); xx = reshape(xx, size(x));
yy = newcoords(:,2); yy = reshape(yy, size(y));
zz = newcoords(:,3); zz = reshape(zz, size(z));
return;
end;
if iscell(TCPARAMS) % coregistration for MRI template
valinion = TCPARAMS{1};
valnasion = TCPARAMS{2};
vallear = TCPARAMS{3};
valrear = TCPARAMS{4};
valvertex = TCPARAMS{5};
zoffset = TCPARAMS{6};
% scale axis
% ----------
y = y/2*( valinion(1) - valnasion(1) );
x = x/2*( valrear(2) - vallear(2) );
z = z* ( valvertex(3) - vallear(3) - zoffset );
% recenter
% --------
yy = y + (vallear (1) + valrear (1))/2;
xx = x + (valinion(2) + valnasion(2))/2;
zz = z + (vallear (3) + valrear (3))/2 + zoffset;
return;
elseif isnumeric(TCPARAMS)
yy = y*TCPARAMS;
xx = x*TCPARAMS;
zz = z*TCPARAMS;
end;
function sc = plotellipse(sources, ind, nstd, TCPARAMS, coreg);
for i = 1:length(ind)
tmpval(1,i) = -sources(ind(i)).posxyz(1);
tmpval(2,i) = -sources(ind(i)).posxyz(2);
tmpval(3,i) = sources(ind(i)).posxyz(3);
[tmpval(1,i) tmpval(2,i) tmpval(3,i)] = transcoords(tmpval(1,i), tmpval(2,i), tmpval(3,i), TCPARAMS, coreg);
end;
% mean and covariance
C = cov(tmpval');
M = mean(tmpval,2);
[U,L] = eig(C);
% For N standard deviations spread of data, the radii of the eliipsoid will
% be given by N*SQRT(eigenvalues).
radii = nstd*sqrt(diag(L));
% generate data for "unrotated" ellipsoid
[xc,yc,zc] = ellipsoid(0,0,0,radii(1),radii(2),radii(3), 10);
% rotate data with orientation matrix U and center M
a = kron(U(:,1),xc); b = kron(U(:,2),yc); c = kron(U(:,3),zc);
data = a+b+c; n = size(data,2);
x = data(1:n,:)+M(1); y = data(n+1:2*n,:)+M(2); z = data(2*n+1:end,:)+M(3);
% now plot the rotated ellipse
c = ones(size(z));
sc = mesh(x,y,z);
alpha(0.5)
function newsrc = convertbesaoldformat(src);
newsrc = [];
count = 1;
countdip = 1;
if ~isfield(src, 'besaextori'), src(1).besaextori = []; end;
for index = 1:length(src)
% convert format
% --------------
if isempty(src(index).besaextori), src(index).besaextori = 300; end; % 20 mm
newsrc(count).possph(countdip,:) = [ src(index).besathloc src(index).besaphloc src(index).besaexent];
newsrc(count).momsph(countdip,:) = [ src(index).besathori src(index).besaphori src(index).besaextori/300];
% copy other fields
% -----------------
if isfield(src, 'stdX')
newsrc(count).stdX = -src(index).stdY;
newsrc(count).stdY = src(index).stdX;
newsrc(count).stdZ = src(index).stdZ;
end;
if isfield(src, 'rv')
newsrc(count).rv = src(index).rv;
end;
if isfield(src, 'elecrv')
newsrc(count).rvelec = src(index).elecrv;
end;
if isfield(src, 'component')
newsrc(count).component = src(index).component;
if index ~= length(src) & src(index).component == src(index+1).component
countdip = countdip + 1;
else
count = count + 1; countdip = 1;
end;
else
count = count + 1; countdip = 1;
end;
end;
function src = computexyzforbesa(src);
for index = 1:length( src )
for index2 = 1:size( src(index).possph, 1 )
% compute coordinates
% -------------------
postmp = src(index).possph(index2,:);
momtmp = src(index).momsph(index2,:);
phi = postmp(1)+90; %% %%%%%%%%%%%%%%% USE BESA COORDINATES %%%%%
theta = postmp(2); %% %%%%%%%%%%%%%%% USE BESA COORDINATES %%%%%
phiori = momtmp(1)+90; %% %%%%%%%%%%%% USE BESA COORDINATES %%%%%
thetaori = momtmp(2); %% %%%%%%%%%%%% USE BESA COORDINATES %%%%%
% exentricities are in % of the radius of the head sphere
[x y z] = sph2cart(theta/180*pi, phi/180*pi, postmp(3)/100);
[xo yo zo] = sph2cart(thetaori/180*pi, phiori/180*pi, momtmp(3)*5); % exentricity scaled for compatibility with DIPFIT
src(index).posxyz(index2,:) = [-y x z];
src(index).momxyz(index2,:) = [-yo xo zo];
end;
end;
% update dipplot (callback call)
% ------------------------------
function updatedipplot(fig)
% find current dipole index and test for authorized range
% -------------------------------------------------------
dat = get(gca, 'userdata');
editobj = findobj('parent', fig, 'userdata', 'editor');
tmpnum = str2num(get(editobj(end), 'string'));
if tmpnum < 1, tmpnum = 1; end;
if tmpnum > dat.nbsources, tmpnum = dat.nbsources; end;
set(editobj(end), 'string', num2str(tmpnum));
% hide current dipole, find next dipole and show it
% -------------------------------------------------
set(get(gcf, 'userdata'), 'visible', 'off');
newdip = findobj('parent', gca, 'tag', [ 'dipole' get(editobj(end), 'string')]);
set(newdip, 'visible', 'on');
set(gcf, 'userdata', newdip);
% find all dipolar structures
% ---------------------------
tmprvobj = findobj('parent', fig, 'userdata', 'rv');
index = 1;
count = 1;
for index = 1:length(newdip)
if isstruct( get(newdip(index), 'userdata') )
allpos3d(count,:) = getfield(get(newdip(index), 'userdata'), 'pos3d');
count = count+1;
foundind = index;
end;
end;
% get residual variance
% ---------------------
if exist('foundind')
rv = getfield(get(newdip(foundind), 'userdata'), 'rv');
set( tmprvobj(end), 'string', rv);
end
% adapt the MRI to the dipole depth
% ---------------------------------
%if ~strcmpi(dat.mode, 'besa') % not besa mode
delete(findobj('parent', gca, 'tag', 'img'));
tmpdiv = 1;
if ~dat.axistight
[xx yy zz] = transcoords(0,0,0, dat.tcparams, dat.coreg);
indx = minpos(dat.imgcoords{1}-zz);
indy = minpos(dat.imgcoords{2}-yy);
indz = minpos(dat.imgcoords{3}-xx);
else
if ~dat.cornermri
indx = minpos(dat.imgcoords{1} - mean(allpos3d(:,3)) + 4/tmpdiv);
indy = minpos(dat.imgcoords{2} - mean(allpos3d(:,2)) - 4/tmpdiv);
indz = minpos(dat.imgcoords{3} - mean(allpos3d(:,1)) + 4/tmpdiv);
else % no need to shift slice if not ploted close to the dipole
indx = minpos(dat.imgcoords{1} - mean(allpos3d(:,3)));
indy = minpos(dat.imgcoords{2} - mean(allpos3d(:,2)));
indz = minpos(dat.imgcoords{3} - mean(allpos3d(:,1)));
end;
end;
plotimgs( dat, [indx indy indz]);
%end;
% plot images
% -----------
function plotimgs(dat, index);
% loading images
% --------------
if strcmpi(dat.mode, 'besa')
imgt = dat.imgs{1};
imgc = dat.imgs{2};
imgs = dat.imgs{3};
else
imgt = rot90(squeeze(dat.imgs(:,:,index(1))));
imgc = rot90(squeeze(dat.imgs(:,index(2),:)));
imgs = rot90(squeeze(dat.imgs(index(3),:,:)));
end;
if ndims(imgt) == 2, imgt(:,:,3) = imgt; imgt(:,:,2) = imgt(:,:,1); end;
if ndims(imgc) == 2, imgc(:,:,3) = imgc; imgc(:,:,2) = imgc(:,:,1); end;
if ndims(imgs) == 2, imgs(:,:,3) = imgs; imgs(:,:,2) = imgs(:,:,1); end;
% computing coordinates for planes
% --------------------------------
wxt = [min(dat.imgcoords{3}) max(dat.imgcoords{3}); min(dat.imgcoords{3}) max(dat.imgcoords{3})];
wyt = [min(dat.imgcoords{2}) min(dat.imgcoords{2}); max(dat.imgcoords{2}) max(dat.imgcoords{2})];
wxc = [min(dat.imgcoords{3}) max(dat.imgcoords{3}); min(dat.imgcoords{3}) max(dat.imgcoords{3})];
wzc = [max(dat.imgcoords{1}) max(dat.imgcoords{1}); min(dat.imgcoords{1}) min(dat.imgcoords{1})];
wys = [min(dat.imgcoords{2}) max(dat.imgcoords{2}); min(dat.imgcoords{2}) max(dat.imgcoords{2})];
wzs = [max(dat.imgcoords{1}) max(dat.imgcoords{1}); min(dat.imgcoords{1}) min(dat.imgcoords{1})];
if dat.axistight & ~dat.cornermri
wzt = [ 1 1; 1 1]*dat.imgcoords{1}(index(1));
wyc = [ 1 1; 1 1]*dat.imgcoords{2}(index(2));
wxs = [ 1 1; 1 1]*dat.imgcoords{3}(index(3));
else
wzt = -[ 1 1; 1 1]*dat.maxcoord(1);
wyc = [ 1 1; 1 1]*dat.maxcoord(2);
wxs = -[ 1 1; 1 1]*dat.maxcoord(3);
end;
% ploting surfaces
% ----------------
options = { 'FaceColor','texturemap', 'EdgeColor','none', 'CDataMapping', ...
'direct','tag','img', 'facelighting', 'none' };
hold on;
surface(wxt, wyt, wzt, imgt(end:-1:1,:,:), options{:});
surface(wxc, wyc, wzc, imgc , options{:});
surface(wxs, wys, wzs, imgs , options{:});
if strcmpi(dat.drawedges, 'on')
% removing old edges if any
delete(findobj( gcf, 'tag', 'edges'));
if dat.axistight & ~dat.cornermri, col = 'k'; else col = [0.5 0.5 0.5]; end;
h(1) = line([wxs(1) wxs(2)]', [wys(1) wyc(1)]', [wzt(1) wzt(2)]'); % sagital-transverse
h(2) = line([wxs(1) wxc(3)]', [wyc(1) wyc(2)]', [wzt(1) wzt(2)]'); % coronal-tranverse
h(3) = line([wxs(1) wxs(2)]', [wyc(1) wyc(2)]', [wzs(1) wzt(1)]'); % sagital-coronal
set(h, 'color', col, 'linewidth', 2, 'tag', 'edges');
end;
%%fill3([-2 -2 2 2], [-2 2 2 -2], wz(:)-1, BACKCOLOR);
%%fill3([-2 -2 2 2], wy(:)-1, [-2 2 2 -2], BACKCOLOR);
rotate3d on
function index = minpos(vals);
vals(find(vals < 0)) = inf;
[tmp index] = min(vals);
function scalegca(factor)
xl = xlim; xf = ( xl(2) - xl(1) ) * factor;
yl = ylim; yf = ( yl(2) - yl(1) ) * factor;
zl = zlim; zf = ( zl(2) - zl(1) ) * factor;
xlim( [ xl(1)-xf xl(2)+xf ]);
ylim( [ yl(1)-yf yl(2)+yf ]);
zlim( [ zl(1)-zf zl(2)+zf ]);
function color = strcol2real(colorin, colmap)
if ~iscell(colorin)
for index = 1:length(colorin)
color{index} = colmap(colorin(index),:);
end;
else
color = colorin;
for index = 1:length(colorin)
if isstr(colorin{index})
switch colorin{index}
case 'r', color{index} = [1 0 0];
case 'g', color{index} = [0 1 0];
case 'b', color{index} = [0 0 1];
case 'c', color{index} = [0 1 1];
case 'm', color{index} = [1 0 1];
case 'y', color{index} = [1 1 0];
case 'k', color{index} = [0 0 0];
case 'w', color{index} = [1 1 1];
otherwise, error('Unknown color');
end;
end;
end;
end;
|
github
|
spm/spm5-master
|
DEM_demo.m
|
.m
|
spm5-master/toolbox/DEM/DEM_demo.m
| 5,159 |
utf_8
|
2358430b0491bf5053bcbf59718a6a8f
|
function varargout = DEM_demo(varargin)
% DEM_DEMO M-file for DEM_demo.fig
% DEM_DEMO, by itself, creates a new DEM_DEMO or raises the existing
% singleton*.
%
% H = DEM_DEMO returns the handle to a new DEM_DEMO or the handle to
% the existing singleton*.
%
% DEM_DEMO('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in DEM_DEMO.M with the given input arguments.
%
% DEM_DEMO('Property','Value',...) creates a new DEM_DEMO or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before DEM_demo_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to DEM_demo_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help DEM_demo
% Last Modified by GUIDE v2.5 23-Aug-2007 15:32:20
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @DEM_demo_OpeningFcn, ...
'gui_OutputFcn', @DEM_demo_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before DEM_demo is made visible.
function DEM_demo_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to DEM_demo (see VARARGIN)
% Choose default command line output for DEM_demo
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes DEM_demo wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = DEM_demo_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function run_demo_Callback(hObject, handles, file)
h = help(file);
str{1} = [file ':'];
str{2} = '______________________________________________________________ ';
str{2} = ' ';
str{3} = h;
set(handles.help,'String',str);
eval(file)
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_GLM')
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_PEB')
% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_factor_analysis')
% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_OU')
% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_convolution')
% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_EM')
% --- Executes on button press in pushbutton8.
function pushbutton8_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_DEM')
% --- Executes on button press in pushbutton9.
function pushbutton9_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_filtering')
% --- Executes on button press in pushbutton10.
function pushbutton10_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_Lorenz')
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_DFP')
% --- Executes on button press in pushbutton11.
function pushbutton11_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_hdm')
% --- Executes on button press in pushbutton12.
function pushbutton12_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DEM_demo_double_well')
% --- Executes on button press in pushbutton14.
function pushbutton14_Callback(hObject, eventdata, handles)
run_demo_Callback(hObject, handles, 'DFP_demo_double_well')
|
github
|
spm/spm5-master
|
spm_sextract.m
|
.m
|
spm5-master/toolbox/SRender/spm_sextract.m
| 1,949 |
utf_8
|
cece4536d3e43573a233c340010cc490
|
function spm_sextract(job)
% Surface extraction
%_______________________________________________________________________
% Copyright (C) 2007 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id$
images = job.images;
Vi = spm_vol(strvcat(images));
n = numel(Vi); %-#images
if n==0, error('no input images specified'), end
[pth,nam,ext] = fileparts(images{1});
for k=1:numel(job.surface),
expression = job.surface(k).expression;
thresh = job.surface(k).thresh;
y = zeros(Vi(1).dim(1:3),'single');
spm_progress_bar('Init',Vi(1).dim(3),expression,'planes completed');
for p = 1:Vi(1).dim(3),
B = spm_matrix([0 0 -p 0 0 0 1 1 1]);
im = cell(1,n);
for i=1:n,
M = inv(B*inv(Vi(1).mat)*Vi(i).mat);
im{i} = spm_slice_vol(Vi(i),M,Vi(1).dim(1:2),[0,NaN]);
end
try,
y(:,:,p) = real(single(efun(im,expression)));
catch,
error(['Can not evaluate "' expression '".']);
end
spm_progress_bar('Set',p);
end
spm_smooth(y,y,[1.5,1.5,1.5]);
[faces,vertices] = isosurface(y,thresh);
% Swap around x and y because isosurface does for some
% wierd and wonderful reason.
Mat = Vi(1).mat(1:3,:)*[0 1 0 0;1 0 0 0;0 0 1 0; 0 0 0 1];
vertices = (Mat*[vertices' ; ones(1,size(vertices,1))])';
matname = fullfile(pth,sprintf('surf_%s_%.3d.mat',nam,k));
if spm_matlab_version_chk('7.0') >=0,
save(matname,'-V6','faces','vertices','expression','thresh','images');
else
save(matname,'faces','vertices','expression','thresh','images');
end;
spm_progress_bar('Clear');
end
return
%_______________________________________________________________________
%_______________________________________________________________________
function y = efun(im,f)
for i=1:numel(im),
eval(['i' num2str(i) '= im{i};']);
end
y = eval(f);
return
|
github
|
spm/spm5-master
|
spm_config_srender.m
|
.m
|
spm5-master/toolbox/SRender/spm_config_srender.m
| 8,254 |
utf_8
|
de6b1f8858310acf32bb826b24f5fee6
|
function c = spm_config_render
% Configuration file for surface visualisation
%_______________________________________________________________________
% Copyright (C) 2007 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id$
entry = inline(['struct(''type'',''entry'',''name'',name,'...
'''tag'',tag,''strtype'',strtype,''num'',num,''help'',{{}})'],...
'name','tag','strtype','num');
files = inline(['struct(''type'',''files'',''name'',name,'...
'''tag'',tag,''filter'',fltr,''num'',num,''help'',{{}})'],...
'name','tag','fltr','num');
mnu = inline(['struct(''type'',''menu'',''name'',name,'...
'''tag'',tag,''labels'',{labels},''values'',{values},''help'',{{}})'],...
'name','tag','labels','values');
branch = inline(['struct(''type'',''branch'',''name'',name,'...
'''tag'',tag,''val'',{val},''help'',{{}})'],...
'name','tag','val');
repeat = inline(['struct(''type'',''repeat'',''name'',name,''tag'',tag,'...
'''values'',{values})'],'name','tag','values');
Red = mnu('Red','Red',...
{'0.0','0.2','0.4','0.6','0.8','1.0'},...
{0,0.2,0.4,0.6,0.8,1});
Red.val = {1};
Red.help = {['The intensity of the red colouring (0 to 1).']};
Green = mnu('Green','Green',...
{'0.0','0.2','0.4','0.6','0.8','1.0'},...
{0,0.2,0.4,0.6,0.8,1});
Green.val = {1};
Green.help = {['The intensity of the green colouring (0 to 1).']};
Blue = mnu('Blue','Blue',...
{'0.0','0.2','0.4','0.6','0.8','1.0'},...
{0,0.2,0.4,0.6,0.8,1});
Blue.val = {1};
Blue.help = {['The intensity of the blue colouring (0 to 1).']};
Color = branch('Color','Color',{Red,Green,Blue});
Color.help = {[...
'Specify the colour using a mixture of red, green and blue. '...
'For example, white is specified by 1,1,1, black is by 0,0,0 and '...
'purple by 1,0,1.']};
AmbientStrength = mnu('Ambient Strength','AmbientStrength',...
{'0.0','0.2','0.4','0.6','0.8','1.0'},...
{0,0.2,0.4,0.6,0.8,1});
AmbientStrength.val = {0.2};
AmbientStrength.help = {[...
'The strength with which the object reflects ambient '...
'(non-directional) lighting.']};
DiffuseStrength = mnu('Diffuse Strength','DiffuseStrength',...
{'0.0','0.2','0.4','0.6','0.8','1.0'},...
{0,0.2,0.4,0.6,0.8,1});
DiffuseStrength.val = {0.8};
DiffuseStrength.help = {[...
'The strength with which the object diffusely reflects '...
'light. Mat surfaces reflect light diffusely, whereas '...
'shiny surfaces reflect speculatively.']};
SpecularStrength = mnu('Specular Strength','SpecularStrength',...
{'0.0','0.2','0.4','0.6','0.8','1.0'},...
{0,0.2,0.4,0.6,0.8,1});
SpecularStrength.val = {0.2};
SpecularStrength.help = {[...
'The strength with which the object specularly reflects '...
'light (i.e. how shiny it is). '...
'Mat surfaces reflect light diffusely, whereas '...
'shiny surfaces reflect speculatively.']};
SpecularExponent = mnu('Specular Exponent','SpecularExponent',...
{'0.01','0.1','10','100'},{0.01,0.1,10,100});
SpecularExponent.val = {10};
SpecularExponent.help = {[...
'A parameter describing the specular reflectance behaviour. '...
'It relates to the size of the high-lights.']};
SpecularColorReflectance = mnu('Specular Color Reflectance',...
'SpecularColorReflectance',...
{'0.0','0.2','0.4','0.6','0.8','1.0'},...
{0,0.2,0.4,0.6,0.8,1});
SpecularColorReflectance.val = {0.8};
SpecularColorReflectance.help = {[...
'Another parameter describing the specular reflectance behaviour.']};
FaceAlpha = mnu('Face Alpha','FaceAlpha',...
{'0.0','0.2','0.4','0.6','0.8','1.0'},...
{0,0.2,0.4,0.6,0.8,1});
FaceAlpha.val = {1};
FaceAlpha.help = {[...
'The opaqueness of the surface. A value of 1 means it is '...
'opaque, whereas a value of 0 means it is transparent.']};
fname = files('Surface File','SurfaceFile','mat',1);
fname.ufilter = '^surf_.*\.mat';
fname.help = {[...
'Filename of the surf_*.mat file containing the rendering information. '...
'This can be generated via the surface extraction routine in SPM. '...
'Normally, a surface is extracted from grey and white matter tissue class '...
'images, but it is also possible to threshold e.g. an spmT image so that '...
'activations can be displayed.']};
Object = branch('Object','Object',...
{fname,Color,DiffuseStrength,AmbientStrength,SpecularStrength,SpecularExponent,SpecularColorReflectance,FaceAlpha});
Object.help = {[...
'Each object is a surface (from a surf_*.mat file), which may have a '...
'number of light-reflecting qualities, such as colour and shinyness.']};
Objects = repeat('Objects','Objects',{Object});
Objects.help = {[...
'Several surface objects can be displayed together in different colours '...
'and with different reflective properties.']};
Position = entry('Position','Position','e',[1 3]);
Position.val = {[100 100 100]};
Position.help = {'The position of the light in 3D.'};
Light = branch('Light','Light',{Position,Color});
Light.help = {'Specification of a light source in terms of position and colour.'};
Lights = repeat('Lights','Lights',{Light});
Lights.help = {[...
'There should be at least one light specified so that the objects '...
'can be clearly seen.']};
sren = branch('Surface Rendering','SRender',{Objects,Lights});
sren.prog = @spm_srender;
sren.help = {[...
'This utility is for visualising surfaces. Surfaces first need to be '...
'extracted and saved in surf_*.mat files using the surface extraction '...
'routine.']};
expr.type = 'entry';
expr.name = 'Expression';
expr.tag = 'expression';
expr.strtype = 's';
expr.num = [2 Inf];
expr.val = {'i1'};
expr.help = {...
'Example expressions (f):',...
' * Mean of six images (select six images)',...
' f = ''(i1+i2+i3+i4+i5+i6)/6''',...
' * Make a binary mask image at threshold of 100',...
' f = ''i1>100''',...
' * Make a mask from one image and apply to another',...
' f = ''i2.*(i1>100)''',[...
' - here the first image is used to make the mask, which is applied to the second image'],...
' * Sum of n images',...
' f = ''i1 + i2 + i3 + i4 + i5 + ...'''};
thresh.type = 'entry';
thresh.name = 'Surface isovalue(s)';
thresh.tag = 'thresh';
thresh.num = [1 1];
thresh.val = {.5};
thresh.strtype = 'e';
thresh.help = {['Enter the value at which isosurfaces through ' ...
'the resulting image is to be computed.']};
surf = branch('Surface','surface',{expr,thresh});
surf.help = {[...
'An expression and threshold for each of the surfaces to be generated.']};
surfaces = repeat('Surfaces','Surfaces',{surf});
surfaces.help = {'Multiple surfaces can be created from the same image data.'};
inpt.type = 'files';
inpt.name = 'Input Images';
inpt.tag = 'images';
inpt.filter = 'image';
inpt.num = [1 Inf];
inpt.help = {[...
'These are the images that are used by the calculator. They ',...
'are referred to as i1, i2, i3, etc in the order that they are ',...
'specified.']};
opts.type = 'branch';
opts.name = 'Surface Extraction';
opts.tag = 'SExtract';
opts.val = {inpt,surfaces};
opts.prog = @spm_sextract;
opts.vfiles = @filessurf;
opts.help = {[...
'User-specified ',...
'algebraic manipulations are performed on a set of images, with the result being ',...
'used to generate a surface file. The user is prompted to supply images to ',...
'work on and a number of expressions to ',...
'evaluate, along with some thresholds. The expression should be a standard matlab expression, ',...
'within which the images should be referred to as i1, i2, i3,... etc. '...
'An isosurface file is created from the results at the user-specified threshold.']};
c = repeat('Rendering','render',{opts,sren});
c.help = {[...
'This is a toolbox that provides a limited range '...
'of surface rendering options. The idea is to first extract surfaces from '...
'image data, which are saved in rend_*.mat files. '...
'These can then be loaded and displayed as surfaces. '...
'Note that OpenGL rendering is used, which can be problematic '...
'on some computers. The tools are limited - and they do what they do.']};
return;
function vfiles=filessurf(job)
vfiles={};
[pth,nam,ext] = fileparts(job.images{1});
for k=1:numel(job.surface),
vfiles{k} = fullfile(pth,sprintf('surf_%s_%.3d.mat',nam,k));
end;
return;
|
github
|
spm/spm5-master
|
pm_segment.m
|
.m
|
spm5-master/toolbox/FieldMap/pm_segment.m
| 3,379 |
utf_8
|
10c91142a779c74dc0aff191dd254b7c
|
function dat = pm_segment(fname)
% Segment an MR image into Gray, White & CSF.
%
% FORMAT dat = pm_segment(fname)
% fname - name of image to segment.
% dat - matrix of size MxNxPx3 containing the resulting tissue probabilities
%_______________________________________________________________________
% Refs:
%
% Ashburner J & Friston KJ (1997) Multimodal Image Coregistration and
% Partitioning - a Unified Framework. NeuroImage 6:209-217
%_______________________________________________________________________
% Copyright (C) 2005 Wellcome Department of Imaging Neuroscience
% John Ashburner
% $Id: pm_segment.m 1914 2008-07-14 14:40:34Z chloe $
if nargin<1, fname = spm_select(1,'image'); end
opts.tpm = strvcat(fullfile(spm('dir'),'apriori','grey.nii'),...
fullfile(spm('dir'),'apriori','white.nii'),...
fullfile(spm('dir'),'apriori','csf.nii'));
opts.ngaus = [1 1 1 4];
opts.regtype = 'mni';
opts.warpreg = 1;
opts.warpco = 40;
opts.biasreg = 1.0000e-04;
opts.biasfwhm = 80;
opts.samp = 6;
opts.msk = '';
p = spm_preproc(fname,opts); % RUN THE SEGMENTATION
T = p.Twarp;
bsol = p.Tbias;
d2 = [size(T) 1];
d = p.image.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.mg;
mn = p.mn;
vr = p.vr;
K = length(mg);
Kb = length(p.ngaus);
lkp = []; for k=1:Kb, lkp = [lkp ones(1,p.ngaus(k))*k]; end;
M = p.tpm(1).mat\p.Affine*p.image.mat;
b0 = spm_load_priors(p.tpm);
for z=1:length(x3),
f = spm_sample_vol(p.image,x1,x2,o*x3(z),0);
cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*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]);
b = zeros([d(1:2) K ]);
for k1=1:Kb, bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb); end;
for k=1:K, b(:,:,k ) = bt(:,:,lkp(k))*mg(k); end;
s = sum(b,3)+eps;
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;
s = sum(q,3)+eps;
for k1=1:3,
dat(:,:,z,k1) = uint8(round(255 * q(:,:,k1)./s));
end;
end;
%=======================================================================
%=======================================================================
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;
%=======================================================================
|
github
|
spm/spm5-master
|
pm_brain_mask.m
|
.m
|
spm5-master/toolbox/FieldMap/pm_brain_mask.m
| 4,190 |
utf_8
|
e569fc153b4b8c018cc3964a37661614
|
function bmask = pm_brain_mask(P,flags)
% Calculate a brain mask
% FORMAT bmask = pm_brain_mask(P,flags)
%
% P - is a single pointer to a single image
%
% flags - structure containing various options
% template - which template for segmentation
% fwhm - fwhm of smoothing kernel for generating mask
% nerode - number of erosions
% thresh - threshold for smoothed mask
% ndilate - number of dilations
%
%__________________________________________________________________________
%
% Inputs
% A single *.img conforming to SPM data format (see 'Data Format').
%
% Outputs
% Brain mask in a matrix
%__________________________________________________________________________
%
% The brain mask is generated by segmenting the image into GM, WM and CSF,
% adding these components together then thresholding above zero.
% A morphological opening is performed to get rid of stuff left outside of
% the brain. Any leftover holes are filled.
%
%__________________________________________________________________________
% @(#)pm_brain_mask.m 1.0 Chloe Hutton 05/02/26
if nargin < 2 | isempty(flags)
%flags.template=fullfile(spm('Dir'),'templates','T1.nii');
flags.fwhm=5;
flags.nerode=1;
flags.ndilate=2;
flags.thresh=0.5;
%flags.reg = 0.02;
%flags.graphics=0;
end
disp('Segmenting and extracting brain...');
%seg_flags.estimate.reg=flags.reg;
%seg_flags.graphics = flags.graphics;
%VO=spm_segment(P.fname,flags.template,seg_flags);
%bmask=double(VO(1).dat)+double(VO(2).dat)+double(VO(3).dat)>0;
dat = pm_segment(P.fname);
bmask=double(dat(:,:,:,1))+double(dat(:,:,:,2))+double(dat(:,:,:,3))>0;
bmask=open_it(bmask,flags.nerode,flags.ndilate); % Do opening to get rid of scalp
% Calculate kernel in voxels:
vxs = sqrt(sum(P.mat(1:3,1:3).^2));
fwhm = repmat(flags.fwhm,1,3)./vxs;
bmask=fill_it(bmask,fwhm,flags.thresh); % Do fill to fill holes
OP=P;
brain_mask = [spm_str_manip(P.fname,'h') '/bmask',...
spm_str_manip(P.fname,'t')];
OP.fname=brain_mask;
OP.descrip=sprintf('Mask:erode=%d,dilate=%d,fwhm=%d,thresh=%1.1f',flags.nerode,flags.ndilate,flags.fwhm,flags.thresh);
spm_write_vol(OP,bmask);
%__________________________________________________________________________
%__________________________________________________________________________
function ovol=open_it(vol,ne,nd)
% Do a morphological opening. This consists of an erosion, followed by
% finding the largest connected component, followed by a dilation.
for i=1:ne
% Do an erosion then a connected components then a dilation
% to get rid of stuff outside brain.
evol=spm_erode(double(vol));
evol=connect_it(evol);
vol=spm_dilate(double(evol));
end
% Do some dilations to extend the mask outside the brain
for i=1:nd
vol=spm_dilate(double(vol));
end
ovol=vol;
%__________________________________________________________________________
%__________________________________________________________________________
function ovol=fill_it(vol,k,thresh)
% Do morpholigical fill. This consists of finding the largest connected
% component and assuming that is outside of the head. All the other
% components are set to 1 (in the mask). The result is then smoothed by k
% and thresholded by thresh.
ovol=vol;
% Need to find connected components of negative volume
vol=~vol;
[vol,NUM]=ip_bwlabel(double(vol),26);
% Now get biggest component and assume this is outside head..
pnc=0;
maxnc=1;
for i=1:NUM
nc=size(find(vol==i),1);
if nc>pnc
maxnc=i;
pnc=nc;
end
end
% We know maxnc is largest cluster outside brain, so lets make all the
% others = 1.
for i=1:NUM
if i~=maxnc
nc=find(vol==i);
ovol(nc)=1;
end
end
spm_smooth(ovol,ovol,k);
ovol=ovol>thresh;
%_______________________________________________________________________
%_______________________________________________________________________
function ovol=connect_it(vol)
% Find connected components and return the largest one.
[vol,NUM]=ip_bwlabel(double(vol),26);
% Get biggest component
pnc=0;
maxnc=1;
for i=1:NUM
nc=size(find(vol==i),1);
if nc>pnc
maxnc=i;
pnc=nc;
end
end
ovol=(vol==maxnc);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.