Home > marsbar > marsbar.m

marsbar

PURPOSE ^

Startup, callback and utility routine for Marsbar

SYNOPSIS ^

function varargout=marsbar(varargin)

DESCRIPTION ^

 Startup, callback and utility routine for Marsbar

 MarsBaR: Marseille Boite a Regions d'interet 
          Marseille Region of Interest Toolbox 

 MarsBaR (the collection of files listed by contents.m) is copyright under
 the GNU general public license.  Please see mars_licence.man for details.
 
 Marsbar written by 
 Jean-Luc Anton, Matthew Brett, Jean-Baptiste Poline, Romain Valabregue 

 Portions of the code rely heavily on (or are copied from) SPM99 and SPM2
 (http://www.fil.ion.ucl.ac.uk/spm), which is also released under the GNU
 public licence.  Many thanks the SPM authors: (John Ashburner, Karl
 Friston, Andrew Holmes et al, and of course our own Jean-Baptiste).

 This software is MarsBaRWare. It is written in the hope that it is
 helpful; if you find it so, please let us know by sending a Mars bar to:
 The Jean-Luc confectionery collection, Centre IRMf, CHU La Timone, 264,
 Rue Saint Pierre 13385 Marseille Cedex 05, France
 
 If you find that it actively hinders your work, do send an
 elderly sardine to the same address.

 Please visit our friends at The Visible Mars Bar project:
 http://totl.net/VisibleMars

 $Id$

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

SOURCE CODE ^

0001 function varargout=marsbar(varargin) 
0002 % Startup, callback and utility routine for Marsbar
0003 %
0004 % MarsBaR: Marseille Boite a Regions d'interet
0005 %          Marseille Region of Interest Toolbox
0006 %
0007 % MarsBaR (the collection of files listed by contents.m) is copyright under
0008 % the GNU general public license.  Please see mars_licence.man for details.
0009 %
0010 % Marsbar written by
0011 % Jean-Luc Anton, Matthew Brett, Jean-Baptiste Poline, Romain Valabregue
0012 %
0013 % Portions of the code rely heavily on (or are copied from) SPM99 and SPM2
0014 % (http://www.fil.ion.ucl.ac.uk/spm), which is also released under the GNU
0015 % public licence.  Many thanks the SPM authors: (John Ashburner, Karl
0016 % Friston, Andrew Holmes et al, and of course our own Jean-Baptiste).
0017 %
0018 % This software is MarsBaRWare. It is written in the hope that it is
0019 % helpful; if you find it so, please let us know by sending a Mars bar to:
0020 % The Jean-Luc confectionery collection, Centre IRMf, CHU La Timone, 264,
0021 % Rue Saint Pierre 13385 Marseille Cedex 05, France
0022 %
0023 % If you find that it actively hinders your work, do send an
0024 % elderly sardine to the same address.
0025 %
0026 % Please visit our friends at The Visible Mars Bar project:
0027 % http://totl.net/VisibleMars
0028 %
0029 % $Id$
0030 
0031 % Programmer's help
0032 % -----------------
0033 % For a list of the functions implemented here, try
0034 % grep "^case " marsbar.m
0035   
0036 % Marsbar version
0037 MBver = '0.42';  % SPM8 first release
0038 
0039 % Various working variables in global variable structure
0040 global MARS;
0041 
0042 %-Format arguments
0043 %-----------------------------------------------------------------------
0044 if nargin == 0, Action='Startup'; else, Action = varargin{1}; end
0045 
0046 %=======================================================================
0047 switch lower(Action), case 'startup'                     %-Start marsbar
0048 %=======================================================================
0049 
0050 %-Turn on warning messages for debugging
0051 warning backtrace
0052 
0053 % splash screen once per session
0054 splashf = ~marsbar('is_started');
0055 
0056 % promote spm directory to top of path, read defaults
0057 marsbar('on');
0058 
0059 % Workaround for bizarre linux uigetfile problem: see
0060 % http://www.mathworks.com/support/bugreports/details.html?rp=259878
0061 % (or search Mathworks support for uigetfile linux
0062 mlv = version; mlv = str2num(mlv(1:3));
0063 if mlv >= 7 & strcmp(computer, 'GLNX86')
0064   if usejava('jvm')
0065     setappdata(0,'UseNativeSystemDialogs',false)
0066   else
0067     warning(['Matlab 7, linux, no java, please see FAQ for '...
0068          'information on problems with file selection dialogs']);
0069   end
0070 end
0071 
0072 %-Open startup window, set window defaults
0073 %-----------------------------------------------------------------------
0074 S = get(0,'ScreenSize');
0075 if all(S==1), error('Can''t open any graphics windows...'), end
0076 PF = spm_platform('fonts');
0077 
0078 % Splash screen
0079 %------------------------------------------
0080 if splashf
0081   marsbar('splash');
0082 end
0083 
0084 %-Draw marsbar window
0085 %-----------------------------------------------------------------------
0086 Fmenu = marsbar('CreateMenuWin','off');
0087 
0088 %-Reveal windows
0089 %-----------------------------------------------------------------------
0090 set([Fmenu],'Visible','on')
0091 
0092 %=======================================================================
0093 case 'on'                                           %-Initialise MarsBaR
0094 %=======================================================================
0095 
0096 % promote spm replacement directory
0097 % remove incorrect spm replacement directories
0098 mbpath = fileparts(which('marsbar.m'));
0099 spmV = mars_utils('spm_version');
0100 m_spm_paths = {'spm99', 'spm2', 'spm5'};
0101 v_path = lower(spmV);
0102 % spm8 is effectively identical to spm5 for marsbar
0103 if strcmp(v_path, 'spm8')
0104     v_path = 'spm5';
0105 end
0106 w_s = warning;
0107 warning off
0108 for p = m_spm_paths(~ismember(m_spm_paths, v_path))
0109   rmpath(fullfile(mbpath, char(p)))
0110 end
0111 warning(w_s)
0112 MARS.ADDPATHS = {fullfile(mbpath, v_path)};
0113 addpath(MARS.ADDPATHS{:}, '-begin');
0114 fprintf('MarsBaR analysis functions prepended to path\n');
0115 
0116 % check SPM defaults are loaded
0117 mars_veropts('defaults');
0118 
0119 % set up the ARMOIRE stuff
0120 % see marmoire help for details
0121 if isfield(MARS, 'ARMOIRE')
0122   o = MARS.ARMOIRE; 
0123 else
0124   o = marmoire;
0125 end
0126 
0127 spm_design_filter = mars_veropts('design_filter_spec');
0128 filter_specs  = {[spm_design_filter(1,:);...
0129           {'*_mdes.mat','MarsBaR: *_mdes.mat'}; ...
0130           spm_design_filter(2:end,:)], ...
0131          {'*_mdata.mat','MarsBaR data file (*_mdata.mat)'},...
0132          {'*_mres.mat', 'MarsBaR results (*_mres.mat)'}};
0133 
0134 o = add_if_absent(o, 'def_design', ...
0135           struct('default_file_name', 'untitled_mdes.mat',...      
0136              'filter_spec', {filter_specs{1}},...
0137              'title', 'Default design',...
0138              'set_action','mars_arm_call(''set_design'',o,item,old_o)'));
0139 o = add_if_absent(o, 'roi_data',...
0140           struct('default_file_name', 'untitled_mdata.mat',...
0141              'filter_spec', {filter_specs{2}},...
0142              'title', 'ROI data',...
0143              'set_action','mars_arm_call(''set_data'',o,item,old_o)'));
0144 o = add_if_absent(o, 'est_design',...
0145           struct('default_file_name', 'untitled_mres.mat',...
0146              'filter_spec', {filter_specs{3}},...
0147              'title', 'MarsBaR estimated design',...
0148              'set_action', 'mars_arm_call(''set_results'',o,item,old_o)'));
0149 MARS.ARMOIRE = o;
0150 
0151 % and workspace
0152 if ~isfield(MARS, 'WORKSPACE'), MARS.WORKSPACE = []; end
0153 
0154 % read any necessary defaults
0155 if ~mars_struct('isthere', MARS, 'OPTIONS')
0156   loadf = 1;
0157   MARS.OPTIONS = [];
0158 else
0159   loadf = 0;
0160 end
0161 [mbdefs sourcestr] = mars_options('Defaults');
0162 MARS.OPTIONS = mars_options('fill',MARS.OPTIONS, mbdefs);
0163 mars_options('put');
0164 if loadf
0165   fprintf('Loaded MarsBaR defaults from %s\n',sourcestr);
0166 end
0167 
0168 % Add very very odd fix for maroi object path problem
0169 % and matlab 7.1 (at least)
0170 % Don't ask why this is needed - I don't know.
0171 maroi;
0172 
0173 %=======================================================================
0174 case 'off'                                              %-Unload MarsBaR
0175 %=======================================================================
0176 % res = marsbar('Off')
0177 %-----------------------------------------------------------------------
0178 varargout = {0};
0179 
0180 % leave if no signs of marsbar
0181 if ~marsbar('is_started'), return, end
0182 
0183 % save outstanding information
0184 btn = mars_arm('save_ui', 'all', struct('ync', 1, 'no_no_save', 1));
0185 if btn == -1, varargout = {-1}; return, end % cancel
0186 
0187 % remove marsbar added directories
0188 rmpath(MARS.ADDPATHS{:});
0189 fprintf('MarsBaR analysis functions removed from path\n');
0190 
0191 %=======================================================================
0192 case 'quit'                                        %-Quit MarsBaR window
0193 %=======================================================================
0194 % marsbar('Quit')
0195 %-----------------------------------------------------------------------
0196 
0197 % do path stuff, save any pending changes
0198 if marsbar('off') == -1, return, end % check for cancel
0199 
0200 % leave if no signs of MARSBAR
0201 if ~marsbar('is_started'), return, end
0202 
0203 %-Close any existing 'MarsBaR' 'Tag'ged windows
0204 delete(spm_figure('FindWin','MarsBaR'))
0205 fprintf('Au revoir...\n\n')
0206 
0207 %=======================================================================
0208 case 'is_started'        %-returns 1 if MarsBaR GUI has been initialized
0209 %=======================================================================
0210 % tf  = marsbar('is_started')
0211 varargout = {~isempty(MARS)};
0212 
0213 %=======================================================================
0214 case 'cfgfile'                                  %-finds MarsBaR cfg file
0215 %=======================================================================
0216 % cfgfn  = marsbar('cfgfile')
0217 cfgfile = 'marsbarcfg.mat';
0218 varargout = {which(cfgfile), cfgfile}; 
0219 
0220 %=======================================================================
0221 case 'createmenuwin'                          %-Draw MarsBaR menu window
0222 %=======================================================================
0223 % Fmenu = marsbar('CreateMenuWin',Vis)
0224 if nargin<2, Vis='on'; else, Vis=varargin{2}; end
0225 
0226 %-Close any existing 'MarsBaR' 'Tag'ged windows
0227 delete(spm_figure('FindWin','MarsBaR'))
0228 
0229 % Version etc info
0230 [MBver,MBc] = marsbar('Ver');
0231 
0232 %-Get size and scalings and create Menu window
0233 %-----------------------------------------------------------------------
0234 WS   = spm('WinScale');                %-Window scaling factors
0235 FS   = spm('FontSizes');            %-Scaled font sizes
0236 PF   = spm_platform('fonts');            %-Font names (for this platform)
0237 Rect = [50 600 300 275];               %-Raw size menu window rectangle
0238 bno = 6; bgno = bno+1;
0239 bgapr = 0.25;
0240 bh = Rect(4) / (bno + bgno*bgapr);      % Button height
0241 gh = bh * bgapr;                        % Button gap
0242 by = fliplr(cumsum([0 ones(1, bno-1)*(bh+gh)])+gh);
0243 bx = Rect(3)*0.1;
0244 bw = Rect(3)*0.8;
0245 Fmenu = figure('IntegerHandle','off',...
0246     'Name',sprintf('%s',MBc),...
0247     'NumberTitle','off',...
0248     'Tag','MarsBaR',...
0249     'Position',Rect.*WS,...
0250     'Resize','off',...
0251     'Color',[1 1 1]*.8,...
0252     'UserData',struct('MBver',MBver,'MBc',MBc),...
0253     'MenuBar','none',...
0254     'DefaultTextFontName',PF.helvetica,...
0255     'DefaultTextFontSize',FS(12),...
0256     'DefaultUicontrolFontName',PF.helvetica,...
0257     'DefaultUicontrolFontSize',FS(12),...
0258     'DefaultUicontrolInterruptible','on',...
0259     'Renderer','painters',...
0260     'Visible','off');
0261 
0262 %-Objects with Callbacks - main MarsBaR routines
0263 %=======================================================================
0264 
0265 funcs = {'mars_display_roi(''display'');',...
0266      'mars_blob_ui;',...
0267      'marsbar(''buildroi'');',...
0268      'marsbar(''transform'');',...
0269      'marsbar(''import_rois'');',...
0270      'marsbar(''export_rois'');'};
0271 
0272 uicontrol(Fmenu,'Style','PopUp',...
0273       'String',['ROI definition',...
0274             '|View...'...
0275             '|Get SPM cluster(s)...'...
0276             '|Build...',...
0277             '|Transform...',...
0278             '|Import...',...
0279             '|Export...'],...
0280       'Position',[bx by(1) bw bh].*WS,...
0281       'ToolTipString','Draw / build / combine ROIs...',...
0282       'CallBack','spm(''PopUpCB'',gcbo)',...
0283       'UserData',funcs);
0284 
0285 % Design menu
0286 fw_st = 'struct(''force'', 1, ''warn_empty'', 1)';
0287 funcs = {...
0288     'marsbar(''make_design'', ''pet'');',...
0289     'marsbar(''make_design'', ''fmri'');',...
0290     'marsbar(''make_design'', ''basic'');',...
0291     'marsbar(''design_report'')',...
0292     'marsbar(''design_filter'')',...
0293     'marsbar(''add_images'')',...
0294     'marsbar(''edit_filter'')',...
0295     'marsbar(''check_images'')',...
0296     'marsbar(''list_images'')',...
0297     'marsbar(''ana_cd'')',...
0298     'marsbar(''ana_desmooth'')',...
0299     'marsbar(''def_from_est'')',...
0300     'marsbar(''set_def'')',...
0301     ['mars_arm(''save_ui'', ''def_design'', ' fw_st ');'],...
0302     'mars_arm(''show_summary'', ''def_design'')'};
0303 
0304 uicontrol(Fmenu,'Style','PopUp',...
0305       'String',['Design...'...
0306             '|PET models',...
0307             '|FMRI models',...
0308             '|Basic models',...
0309             '|Explore',...
0310             '|Frequencies (event+data)',...
0311             '|Add images to FMRI design',...
0312             '|Add/edit filter for FMRI design',...    
0313             '|Check image names in design',...
0314             '|List image names to console',...
0315             '|Change design path to images',...
0316             '|Convert to unsmoothed',...
0317             '|Set design from estimated',...
0318             '|Set design from file',...
0319             '|Save design to file',...
0320             '|Show default design summary'],...
0321       'Position',[bx by(2) bw bh].*WS,...
0322       'ToolTipString','Set/specify design...',...
0323       'CallBack','spm(''PopUpCB'',gcbo)',...
0324       'UserData',funcs);
0325 
0326 % Data menu
0327 funcs = {'marsbar(''extract_data'', ''default'');',...
0328      'marsbar(''extract_data'', ''full'');',...
0329      'marsbar(''set_defregion'');',...
0330      'marsbar(''plot_data'', ''raw'');',...
0331      'marsbar(''plot_data'', ''full'');',...
0332      'marsbar(''import_data'');',...
0333      'marsbar(''export_data'');',...
0334      'marsbar(''split_data'');',...
0335      'marsbar(''join_data'');',...
0336      'mars_arm(''set_ui'', ''roi_data'');',...
0337      ['mars_arm(''save_ui'', ''roi_data'', ' fw_st ');'],...
0338      'mars_arm(''show_summary'', ''roi_data'')'};
0339 
0340 uicontrol(Fmenu,'Style','PopUp',...
0341       'String',['Data...'...
0342             '|Extract ROI data (default)',...
0343             '|Extract ROI data (full options)',...
0344             '|Default region...',...
0345             '|Plot data (simple)',...
0346             '|Plot data (full)',...            
0347             '|Import data',...
0348             '|Export data',...
0349             '|Split regions into files',...
0350             '|Merge data files',...
0351             '|Set data from file',...
0352             '|Save data to file',...
0353             '|Show data summary'],...
0354       'Position',[bx by(3) bw bh].*WS,...
0355       'ToolTipString','Extract/set/save data...',...
0356       'CallBack','spm(''PopUpCB'',gcbo)',...
0357       'UserData',funcs);
0358 
0359 % results menu
0360 funcs = {...
0361     'marsbar(''estimate'');',...
0362     'marsbar(''merge_contrasts'');',...
0363     'marsbar(''add_trial_f'');',...
0364     'marsbar(''set_defcon'');',...
0365     'marsbar(''set_defregion'');',...
0366     'marsbar(''plot_residuals'');',...
0367     'marsbar(''spm_graph'');',...
0368     'marsbar(''stat_table'');',...
0369     'marsbar(''signal_change'');',...
0370     'marsbar(''fitted_events'');',...
0371     'marsbar(''fir_events'');',...
0372     'marsbar(''add_events_by_name'');',...
0373     'marsbar(''set_results'');',...
0374     ['mars_arm(''save_ui'', ''est_design'', ' fw_st ');'],...
0375     'mars_arm(''show_summary'', ''est_design'')'};
0376 
0377 uicontrol(Fmenu,'Style','PopUp',...
0378       'String',['Results...'...
0379             '|Estimate results',...
0380             '|Import contrasts',...
0381             '|Add trial-specific F',...
0382             '|Default contrast...',...
0383             '|Default region...',...
0384             '|Plot residuals',...
0385             '|MarsBaR SPM graph',...
0386             '|Statistic table',...
0387             '|% signal change',...
0388             '|Fitted event time course',...
0389             '|FIR event time course',...            
0390             '|Add event types by name',...
0391             '|Set results from file',...
0392             '|Save results to file',...
0393             '|Show estimated design summary'],...
0394       'Position',[bx by(4) bw bh].*WS,...
0395       'ToolTipString','Write/display contrasts...',...
0396       'CallBack','spm(''PopUpCB'',gcbo)',...
0397       'UserData',funcs);
0398 
0399 % options menu
0400 funcs = {['global MARS; '...
0401      'MARS.OPTIONS=mars_options(''edit'');mars_options(''put'');'],...
0402      ['global MARS; '...
0403       '[MARS.OPTIONS str]=mars_options(''defaults'');' ...
0404       'mars_options(''put''); '...
0405       'fprintf(''Defaults loaded from %s\n'', str)'],...
0406      ['global MARS; '...
0407       '[MARS.OPTIONS str]=mars_options(''basedefaults'');' ...
0408       'mars_options(''put''); '...
0409       'fprintf(''Defaults loaded from %s\n'', str)'],...
0410      ['global MARS; '...
0411       'MARS.OPTIONS=mars_options(''load'');mars_options(''put'');'],...
0412      'mars_options(''save'');'...
0413     };
0414      
0415 uicontrol(Fmenu,'Style','PopUp',...
0416       'String',['Options...'...
0417             '|Edit options'...
0418             '|Restore defaults'...
0419             '|Base defaults',...
0420             '|Set options from file'...
0421             '|Save options to file'],...
0422       'Position',[bx by(5) bw bh].*WS,...
0423       'ToolTipString','Load/save/edit MarsBaR options',...
0424       'CallBack','spm(''PopUpCB'',gcbo)',...
0425       'UserData',funcs);
0426 
0427 % quit button
0428 uicontrol(Fmenu,'String','Quit',...
0429       'Position',[bx by(6) bw bh].*WS,...
0430       'ToolTipString','exit MarsBaR',...
0431       'ForeGroundColor','r',...
0432       'Interruptible','off',...
0433       'CallBack','marsbar(''Quit'')');
0434 
0435 % Set quit action if MarsBaR window is closed
0436 %-----------------------------------------------------------------------
0437 set(Fmenu,'CloseRequestFcn','marsbar(''Quit'')')
0438 set(Fmenu,'Visible',Vis)
0439 
0440 varargout = {Fmenu};
0441 
0442 %=======================================================================
0443 case {'ver', 'version'}                         %-Return MarsBaR version
0444 %=======================================================================
0445 % [v [,banner]] = marsbar('Ver')
0446 %-----------------------------------------------------------------------
0447 varargout = {MBver, 'MarsBaR - Marseille ROI toolbox'};
0448 
0449 %=======================================================================
0450 case 'splash'                                       %-show splash screen
0451 %=======================================================================
0452 % marsbar('splash')
0453 %-----------------------------------------------------------------------
0454 % Shows splash screen
0455 WS   = spm('WinScale');        %-Window scaling factors
0456 [X,map] = imread('marsbar.jpg');
0457 aspct = size(X,1) / size(X,2);
0458 ww = 400;
0459 srect = [200 300 ww ww*aspct] .* WS;   %-Scaled size splash rectangle
0460 h = figure('visible','off',...
0461        'menubar','none',...
0462        'numbertitle','off',...
0463        'name','Welcome to MarsBaR',...
0464        'pos',srect);
0465 im = image(X);
0466 colormap(map);
0467 ax = get(im, 'Parent');
0468 axis off;
0469 axis image;
0470 axis tight;
0471 set(ax,'plotboxaspectratiomode','manual',...
0472        'unit','pixels',...
0473        'pos',[0 0 srect(3:4)]);
0474 set(h,'visible','on');
0475 pause(3);
0476 close(h);
0477  
0478 %=======================================================================
0479 case 'buildroi'                                     %-build and save ROI
0480 %=======================================================================
0481 % o = marsbar('buildroi')
0482 %-----------------------------------------------------------------------
0483 % build and save object
0484 varargout = {[]};
0485 o = mars_build_roi;
0486 if ~isempty(o)
0487   varargout = {marsbar('saveroi', o)};
0488 end
0489 
0490 %=======================================================================
0491 case 'transform'                                        %-transform ROIs
0492 %=======================================================================
0493 % marsbar('transform')
0494 %-----------------------------------------------------------------------
0495 marsbar('mars_menu', 'Transform ROI', 'Transform:', ...
0496     {{'combinerois'},{'flip_lr'}},...
0497     {'Combine ROIs','Flip L/R'});
0498 
0499 %=======================================================================
0500 case 'import_rois'                                       %- import ROIs!
0501 %=======================================================================
0502 % marsbar('import_rois')
0503 %-----------------------------------------------------------------------
0504 
0505 marsbar('mars_menu', 'Import ROIs', 'Import ROIs from:',...
0506     {{'img2rois','c'},...
0507      {'img2rois','i'}},...
0508     {'cluster image',...
0509      'number labelled ROI image'});
0510 
0511 %=======================================================================
0512 case 'export_rois'                                         %-export ROIs
0513 %=======================================================================
0514 % marsbar('export_rois')
0515 %-----------------------------------------------------------------------
0516 
0517 marsbar('mars_menu', 'Export ROI(s)', 'Export ROI(s) to:',...
0518     {{'roi_as_image'},...
0519      {'rois2img', 'c'},...
0520      {'rois2img', 'i'}},...
0521     {'image', 'cluster image',...
0522     'number labelled ROI image'});
0523 
0524 %=======================================================================
0525 case 'img2rois'                                       %-import ROI image
0526 %=======================================================================
0527 %  marsbar('img2rois', roi_type)
0528 %-----------------------------------------------------------------------
0529 
0530 if nargin < 2
0531   roi_type = 'c'; % default is cluster image
0532 else
0533   roi_type = varargin{2};
0534 end
0535 mars_img2rois('','','',roi_type);
0536 
0537 %=======================================================================
0538 case 'rois2img'                                       %-export ROI image
0539 %=======================================================================
0540 %  marsbar('roi2img', roi_type)
0541 %-----------------------------------------------------------------------
0542 
0543 if nargin < 2
0544   roi_type = 'c'; % default is cluster image
0545 else
0546   roi_type = varargin{2};
0547 end
0548 mars_rois2img('','','',roi_type);
0549 
0550 %=======================================================================
0551 case 'saveroi'                                                %-save ROI
0552 %=======================================================================
0553 % o = marsbar('saveroi', obj, flags)
0554 %-----------------------------------------------------------------------
0555 % flags will usually be empty, or one or more characters from
0556 % 'n'   do not ask for label or description
0557 % 'l'   use label to make filename, rather than source field
0558 
0559 if nargin < 2 | isempty(varargin{2})
0560   return
0561 end
0562 if nargin < 3
0563   flags = '';
0564 else
0565   flags = varargin{3};
0566 end
0567 if isempty(flags), flags = ' '; end
0568 o = varargin{2};
0569 varargout = {[]};
0570 
0571 % Label, description
0572 if ~any(flags=='n')
0573   d = spm_input('Description of ROI', '+1', 's', descrip(o));
0574   o = descrip(o,d);
0575   l = spm_input('Label for ROI', '+1', 's', label(o));
0576   o = label(o,l);
0577 end
0578 
0579 fn = source(o);
0580 if isempty(fn) | any(flags=='l')
0581   fn = maroi('filename', mars_utils('str2fname', label(o)));
0582 end
0583 
0584 f_f = ['*' maroi('classdata', 'fileend')];
0585 [f p] = mars_uifile('put', ...
0586             {f_f, ['ROI files (' f_f ')']},...
0587             'File name for ROI', fn);
0588 if any(f~=0)
0589   roi_fname = maroi('filename', fullfile(p, f));
0590   try
0591     varargout = {saveroi(o, roi_fname)};
0592   catch
0593     warning([lasterr ' Error saving ROI to file ' roi_fname])
0594   end
0595 end
0596 
0597 %=======================================================================
0598 case 'combinerois'                                        %-combine ROIs
0599 %=======================================================================
0600 % marsbar('combinerois')
0601 %-----------------------------------------------------------------------
0602 roilist = spm_get(Inf,['*' maroi('classdata', 'fileend')], ...
0603           'Select ROI(s) to combine');
0604 if isempty(roilist)
0605   return
0606 end
0607 roilist = maroi('load_cell', roilist);
0608 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Combine ROIs');
0609 spm_input('(r1 & r2) & ~r3',1,'d','Example function:');
0610 func = spm_input('Function to combine ROIs', '+1', 's', '');
0611 if isempty(func), retnrn, end
0612 for i = 1:length(roilist)
0613   eval(sprintf('r%d = roilist{%d};', i, i));
0614 end
0615 try
0616   eval(['o=' func ';']);
0617 catch
0618   warning(['Hmm, probem with function ' func ': ' lasterr]);
0619   return
0620 end
0621 if isempty(o)
0622   warning('Empty object resulted');
0623   return
0624 end
0625 if is_empty_roi(o)
0626   warning('No volume resulted for ROI');
0627   return
0628 end
0629 
0630 % save ROI
0631 if isa(o, 'maroi')
0632   o = label(o, func);
0633   o = marsbar('saveroi', o); 
0634   fprintf('\nSaved ROI as %s\n', source(o));
0635 else
0636   warning(sprintf('\nNo ROI resulted from function %s...\n', func));
0637 end
0638 
0639 %=======================================================================
0640 case 'flip_lr'                                          %-flip roi L<->R
0641 %=======================================================================
0642 % marsbar('flip_lr')
0643 %-----------------------------------------------------------------------
0644 roilist = spm_get([0 1],['*' maroi('classdata', 'fileend')],...
0645           'Select ROI to flip L/R');
0646 if isempty(roilist)
0647   return
0648 end
0649 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Flip ROI L<->R');
0650 o = maroi('load', roilist);
0651 o = flip_lr(o);
0652 
0653 % save ROI
0654 o = marsbar('saveroi', o, 'l'); 
0655 fprintf('\nSaved ROI as %s\n', source(o));
0656 
0657 %=======================================================================
0658 case 'show_volume'                  %- shows ROI volume in mm to console
0659 %=======================================================================
0660 % marsbar('show_volume')
0661 %-----------------------------------------------------------------------
0662 roi_names = spm_get([0 Inf], '*roi.mat', 'Select ROIs tp get volume');
0663 if isempty(roi_names),return,end
0664 rois = maroi('load_cell', roi_names);
0665 for i = 1:size(rois, 1)
0666   fprintf('Volume of %s: %6.2f\n', source(rois{i}), volume(rois{i}));
0667 end
0668 return
0669 
0670 %=======================================================================
0671 case 'roi_as_image'                               %- writes ROI as image
0672 %=======================================================================
0673 % marsbar('roi_as_image')
0674 %-----------------------------------------------------------------------
0675 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Write ROI to image');
0676 
0677 roi = spm_get([0 1], '*roi.mat', 'Select ROI to write');
0678 if isempty(roi),return,end
0679 [pn fn ext] = fileparts(roi);
0680 roi = maroi('load', roi);
0681 
0682 % space of object
0683 spopts = {'spacebase','image'};
0684 splabs =  {'Base space for ROIs','From image'};
0685 if has_space(roi)
0686   spopts = {spopts{:} 'native'};
0687   splabs = {splabs{:} 'ROI native space'};
0688 end
0689 spo = spm_input('Space for ROI image', '+1', 'm',splabs,...
0690         spopts, 1);
0691 switch char(spo)
0692  case 'spacebase'
0693    sp = maroi('classdata', 'spacebase');
0694  case 'image'
0695   img = spm_get([0 1], mars_veropts('get_img_ext'), 'Image defining space');
0696   if isempty(img),return,end
0697   sp = mars_space(img);
0698  case 'native'
0699   sp = [];
0700 end
0701 
0702 % remove ROI file ending
0703 gend = maroi('classdata', 'fileend');
0704 lg = length(gend);
0705 f2 = [fn ext];
0706 if length(f2)>=lg & strcmp(gend, [f2(end - lg +1 : end)])
0707   f2 = f2(1:end-lg);
0708 else
0709   f2 = fn;
0710 end
0711 
0712 fname = mars_utils('get_img_name', f2);
0713 if isempty(fname), return, end
0714 save_as_image(roi, fname, sp);
0715 fprintf('Saved ROI as %s\n',fname);
0716 
0717 %=======================================================================
0718 case 'attach_image'                          %- attaches image to ROI(s)
0719 %=======================================================================
0720 % marsbar('attach_image' [,img [,roilist]])
0721 %-----------------------------------------------------------------------
0722 if nargin < 2
0723   V = spm_get([0 1], mars_veropts('get_img_ext'), 'Image to attach');
0724   if isempty(V), return, end
0725 else
0726   V = varargin{1};
0727 end
0728 if nargin < 3
0729   rois = spm_get([0 Inf], ['*' maroi('classdata', 'fileend')], ...
0730          'Select ROIs to attach image to');
0731   
0732   if isempty(rois), return, end
0733 else
0734   rois = varargin{2};
0735 end
0736 if ischar(V), V = spm_vol(V); end
0737 for i = 1:size(rois, 1)
0738   n = deblank(rois(i,:));
0739   try 
0740     r = maroi('load', n);
0741   catch
0742     r = []
0743     if ~strmatch(lasterr, 'Cant map image file.')
0744       error(lasterr);
0745     end
0746   end
0747   if isempty(r)
0748     continue
0749   end
0750   if ~isa(r, 'maroi_image')
0751     fprintf('ROI %s is not an image ROI - ignored\n', n);
0752     continue
0753   end
0754 
0755   r = vol(r, V);
0756   saveroi(r, n);
0757   fprintf('Saved ROI %s, attached to image %s\n',...
0758       n, V.fname)
0759 end
0760 return
0761 
0762 %=======================================================================
0763 case 'make_design'                       %-runs design creation routines
0764 %=======================================================================
0765 % marsbar('make_design', des_type)
0766 %-----------------------------------------------------------------------
0767 if nargin < 2
0768   des_type = 'basic';
0769 else
0770   des_type = varargin{2};
0771 end
0772 if sf_prev_save('def_design') == -1, return, end
0773 D = ui_build(mars_veropts('default_design'), des_type);
0774 mars_arm('set', 'def_design', D);
0775 marsbar('design_report');
0776 
0777 %=======================================================================
0778 case 'list_images'                     %-lists image files in SPM design
0779 %=======================================================================
0780 % marsbar('list_images')
0781 %-----------------------------------------------------------------------
0782 marsD = mars_arm('get', 'def_design');
0783 if isempty(marsD), return, end;
0784 if has_images(marsD)
0785   P = image_names(marsD);
0786   strvcat(P{:})
0787 else
0788   disp('Design does not contain images');
0789 end
0790 
0791 %=======================================================================
0792 case 'check_images'                   %-checks image files in SPM design
0793 %=======================================================================
0794 % marsbar('check_images')
0795 %-----------------------------------------------------------------------
0796 marsD = mars_arm('get', 'def_design');
0797 if isempty(marsD), return, end;
0798 if ~has_images(marsD)
0799   disp('Design does not contain images');
0800   return
0801 end
0802 
0803 P = image_names(marsD);
0804 P = strvcat(P{:});
0805 ok_f = 1;
0806 for i = 1:size(P, 1)
0807   fname = deblank(P(i,:));
0808   if ~exist(fname, 'file');
0809     fprintf('Image %d: %s does not exist\n', i, fname);
0810     ok_f = 0;
0811   end
0812 end
0813 if ok_f
0814   disp('All images in design appear to exist');
0815 end
0816 
0817 %=======================================================================
0818 case 'ana_cd'                      %-changes path to files in SPM design
0819 %=======================================================================
0820 % marsbar('ana_cd')
0821 %-----------------------------------------------------------------------
0822 marsD = mars_arm('get', 'def_design');
0823 if isempty(marsD), return, end;
0824 
0825 % Setup input window
0826 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Change image path in design', 0);
0827 
0828 % root path shown in output window
0829 P = image_names(marsD);
0830 P = strvcat(P{:});
0831 root_names = spm_str_manip(P, 'H');
0832 spm_input(deblank(root_names(1,:)),1,'d','Common path is:');
0833 
0834 % new root
0835 newpath = spm_get([-1 0], '', 'New directory root for files');
0836 if isempty(newpath), return, end
0837 
0838 % do
0839 marsD = cd_images(marsD, newpath);
0840 mars_arm('set', 'def_design', marsD);
0841 
0842 %=======================================================================
0843 case 'ana_desmooth'           %-makes new SPM design for unsmoothed data
0844 %=======================================================================
0845 % marsbar('ana_desmooth')
0846 %-----------------------------------------------------------------------
0847 marsD = mars_arm('get', 'def_design');
0848 if isempty(marsD), return, end;
0849 marsD = prefix_images(marsD, 'remove', 's');
0850 mars_arm('set', 'def_design', marsD);
0851 disp('Done');
0852 
0853 %=======================================================================
0854 case 'add_images'                            %-add images to FMRI design
0855 %=======================================================================
0856 % marsbar('add_images')
0857 %-----------------------------------------------------------------------
0858 marsD = mars_arm('get', 'def_design');
0859 if isempty(marsD), return, end
0860 if ~is_fmri(marsD), return, end
0861 marsD = fill(marsD, {'images'});
0862 mars_arm('update', 'def_design', marsD);
0863 mars_arm('set_param', 'def_design', 'file_name', '');
0864 mars_arm('show_summary', 'def_design');
0865 
0866 %=======================================================================
0867 case 'edit_filter'                   %-add / edit filter for FMRI design
0868 %=======================================================================
0869 % marsbar('edit_filter')
0870 %-----------------------------------------------------------------------
0871 marsD = mars_arm('get', 'def_design');
0872 if isempty(marsD), return, end
0873 if ~is_fmri(marsD), return, end
0874 tmp = {'filter'};
0875 if ~strcmp(type(marsD), 'SPM99'), tmp = [tmp {'autocorr'}]; end
0876 marsD = fill(marsD, tmp);
0877 mars_arm('update', 'def_design', marsD);
0878 mars_arm('set_param', 'def_design', 'file_name', '');
0879 mars_arm('show_summary', 'def_design');
0880 
0881 %=======================================================================
0882 case 'def_from_est'          %-sets default design from estimated design
0883 %=======================================================================
0884 % marsbar('def_from_est')
0885 %-----------------------------------------------------------------------
0886 marsE = mars_arm('get', 'est_design');
0887 if isempty(marsE), return, end;
0888 errf = mars_arm('set', 'def_design', marsE);
0889 if ~errf, marsbar('design_report'); end
0890 
0891 %=======================================================================
0892 case 'set_def'                           %-sets default design using GUI
0893 %=======================================================================
0894 % marsbar('set_def')
0895 %-----------------------------------------------------------------------
0896 if mars_arm('set_ui', 'def_design'), return, end
0897 marsbar('design_report');
0898 
0899 %=======================================================================
0900 case 'design_report'                         %-does explore design thing
0901 %=======================================================================
0902 % marsbar('design_report')
0903 %-----------------------------------------------------------------------
0904 marsD = mars_arm('get', 'def_design');
0905 if isempty(marsD), return, end;
0906 spm('FnUIsetup','Explore design', 0);
0907 
0908 fprintf('%-40s: ','Design reporting');
0909 ui_report(marsD, 'DesMtx');
0910 ui_report(marsD, 'DesRepUI');
0911 fprintf('%30s\n','...done');
0912 
0913 %=======================================================================
0914 case 'design_filter'                      %-shows FFT of data and design
0915 %=======================================================================
0916 % marsbar('design_filter')
0917 %-----------------------------------------------------------------------
0918 marsD = mars_arm('get', 'def_design');
0919 if isempty(marsD), return, end;
0920 marsY = mars_arm('get', 'roi_data');
0921 if isempty(marsY), return, end
0922 % If the design and data didn't match, the design will have been cleared
0923 if mars_arm('isempty', 'def_design')
0924   error('Need data and design with matching number of rows');
0925 end
0926 ui_ft_design_data(marsD, marsY);
0927 
0928 %=======================================================================
0929 case 'extract_data'                       % gets data maybe using design
0930 %=======================================================================
0931 % marsY = marsbar('extract_data'[, roi_list [, 'full'|'default']]);
0932 
0933 if nargin < 2
0934   etype = 'default';
0935 else
0936   etype = varargin{2};
0937 end
0938 if nargin < 3
0939   roi_list = '';
0940 else
0941   roi_list = varargin{3};
0942 end
0943 
0944 varargout = {[]};
0945 
0946 % Check for save of current data
0947 if sf_prev_save('roi_data') == -1, return, end
0948 if isempty(roi_list)
0949   roi_list = spm_get(Inf,'*roi.mat','Select ROI(s) to extract data for');
0950 end
0951 if isempty(roi_list), return, end
0952 
0953 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Extract data', 0);
0954 
0955 if strcmp(etype, 'default')
0956   marsD = mars_arm('get', 'def_design');
0957   if isempty(marsD), return, end;
0958   if ~has_images(marsD),
0959     marsD = fill(marsD, 'images');
0960     mars_arm('update', 'def_design', marsD);
0961   end
0962   VY = marsD;
0963   row = block_rows(marsD);
0964 else  % full options extraction
0965   % question for design
0966   
0967   marsD = [];
0968   if spm_input('Use SPM design?', '+1', 'b', 'Yes|No', [1 0], 1)
0969     marsD = mars_arm('get', 'def_design');
0970     if ~has_images(marsD),
0971       marsD = fill(marsD, 'images');
0972       mars_arm('update', 'def_design', marsD);
0973     end
0974   end
0975   [VY row] = mars_image_scaling(marsD);
0976 end
0977 
0978 % Summary function
0979 sumfunc = sf_get_sumfunc(MARS.OPTIONS.statistics.sumfunc);
0980 
0981 % ROI names to objects
0982 o = maroi('load_cell', roi_list);
0983 
0984 % Do data extraction
0985 marsY = get_marsy(o{:}, VY, sumfunc, 'v');
0986 marsY = block_rows(marsY, row);
0987 if ~n_regions(marsY)
0988   msgbox('No data returned','Data extraction', 'warn');
0989   return
0990 end
0991 
0992 % set into armoire, and display
0993 mars_arm('set', 'roi_data', marsY);
0994 mars_arm('show_summary', 'roi_data');
0995 
0996 varargout = {marsY};
0997 
0998 %=======================================================================
0999 case 'plot_data'                                       %- it plots data!
1000 %=======================================================================
1001 % marsbar('plot_data', p_type)
1002 %-----------------------------------------------------------------------
1003 % p_type     - plot type: one of 'raw','acf','fft','all' or 'full'
1004 % where 'full' results in a options to filter and choice of plot
1005 
1006 if nargin < 2
1007   p_type = [];
1008 else
1009   p_type = varargin{2};
1010 end
1011 if isempty(p_type)
1012   p_type = 'full';
1013 end
1014 marsY = mars_arm('get', 'roi_data');
1015 if isempty(marsY), return, end
1016 
1017 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Plot data', 0);
1018 if strcmp(p_type, 'full')
1019   if ~mars_arm('isempty', 'def_design')
1020     D = mars_arm('get', 'def_design');
1021     if isempty(D), return, end
1022     if has_filter(D)
1023       if spm_input('Use design filter?', '+1', 'y/n', [1 0], 1)
1024     flags = {};
1025     if has_whitener(D) 
1026       if ~spm_input('Use whitening filter?', '+1', 'y/n', [1 0], 1)
1027         flags = 'no_whitening';
1028       end
1029     end
1030     marsY = apply_filter(D, marsY, flags);
1031       end
1032     end
1033   end
1034   p_type = char(spm_input('Type of plot', '+1', 'm', ...
1035              'All|Time course|FFT|ACF', ...
1036              {'all','raw','fft','acf'}));
1037 end
1038 
1039 ns  = region_name(marsY);
1040 rno = mars_struct('getifthere', MARS, 'WORKSPACE', 'default_region');
1041 if ~isempty(rno)
1042   fprintf('Using default region: %s\n', ns{rno});
1043 end
1044 ui_plot(marsY, struct('types', p_type, 'r_nos', rno));
1045 
1046 %=======================================================================
1047 case 'import_data'                                    %- it imports data
1048 %=======================================================================
1049 % marsbar('import_data')
1050 %-----------------------------------------------------------------------
1051 
1052 % Check for save of current dataa
1053 if sf_prev_save('roi_data') == -1, return, end
1054 
1055 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Import data', 0);
1056 
1057 r_f = spm_input('Import what?', '+1', 'm', ...
1058         ['Sample time courses for one region'...
1059          '|Summary time course(s) for region(s)'],...
1060         [1 0], 2);
1061 
1062 Ls =         ['Matlab workspace' ...
1063          '|Text file',...
1064          '|Lotus spreadsheet'];,...
1065 Os =            {'matlab','txt','wk1'};
1066 
1067 if ~isempty(which('xlsread'))
1068   Ls = [Ls  '|Excel spreadsheet'];
1069   Os = [Os {'xls'}];
1070 end
1071 
1072 src = spm_input('Import fron?', '+1', 'm', Ls, Os, 1);
1073   
1074 switch src{1}
1075  case 'matlab'
1076   Y = spm_input('Matlab expression', '+1', 'e');
1077   fn = 'Matlab input';
1078   pn_fn = lower(fn);
1079  case 'txt'
1080   [fn, pn] = mars_uifile('get',  ...
1081       {'*.txt;*.dat;*.csv', 'Text files (*.txt, *.dat, *.csv)'; ...
1082        '*.*',                   'All Files (*.*)'}, ...
1083       'Select a text file');
1084   if isequal(fn,0), return, end
1085   pn_fn = fullfile(pn, fn);
1086   Y = spm_load(pn_fn);
1087  case 'wk1'
1088   [fn, pn] = mars_uifile('get',  ...
1089       {'*.wk1', 'Lotus spreadsheet files (*.wk1)'; ...
1090        '*.*',                   'All Files (*.*)'}, ...
1091       'Select a Lotus file');
1092   if isequal(fn,0), return, end
1093   pn_fn = fullfile(pn, fn);
1094   Y = wk1read(pn_fn);
1095  case 'xls'
1096   [fn, pn] = mars_uifile('get',  ...
1097       {'*.xls', 'Excel spreadsheet files (*.xls)'; ...
1098        '*.*',                   'All Files (*.*)'}, ...
1099       'Select an Excel file');
1100   if isequal(fn,0), return, end
1101   pn_fn = fullfile(pn, fn);
1102   Y = xlsread(pn_fn);
1103  otherwise
1104   error('Strange source');
1105 end
1106 if r_f   % region data
1107   s_f = sf_get_sumfunc(MARS.OPTIONS.statistics.sumfunc);
1108   r_st = struct('name', fn,...
1109         'descrip', pn_fn);
1110   s_st = struct('descrip', ['Region data loaded from ' pn_fn],...
1111         'sumfunc', s_f);
1112   marsY = marsy({Y},r_st, s_st);
1113   pref = '';  % Region name prefix not used, as names are set
1114 else     % summary data
1115   s_st = struct('descrip', ['Summary data loaded from ' pn_fn]);
1116   marsY = marsy(Y, '', s_st);
1117   pref = spm_input('Prefix for region names', '+1', 's', [fn '_']);
1118 end
1119 
1120 % Names
1121 stop_f = 0;
1122 ns = region_name(marsY, [], [], pref);
1123 spm_input('Return name with spaces only to abort entry','+1','d');
1124 for r = 1:length(ns)
1125   ns{r} = spm_input(...
1126       sprintf('Name for region %d', r),...
1127       '+1', 's', ns{r});
1128   if all(ns{r}==' '), stop_f = 1; break, end
1129 end
1130 if ~stop_f
1131   marsY = region_name(marsY, [], ns);
1132 end
1133 
1134 mars_arm('set', 'roi_data', marsY);
1135 mars_arm('show_summary', 'roi_data');
1136 disp(['Data loaded from ' pn_fn]);
1137 
1138 %=======================================================================
1139 case 'export_data'                                            %- exports
1140 %=======================================================================
1141 % marsbar('export_data')
1142 %-----------------------------------------------------------------------
1143 marsY = mars_arm('get', 'roi_data');
1144 if isempty(marsY), return, end
1145 
1146 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Export data', 0);
1147 
1148 r_f = spm_input('Export what?', '+1', 'm', ...
1149         ['Sample time courses for one region'...
1150          '|Summary time course(s) for region(s)'],...
1151         [1 0], 2);
1152 
1153 Ls =         ['Matlab workspace' ...
1154          '|Text file',...
1155          '|Lotus spreadsheet'];,...
1156 Os =            {'matlab','txt','wk1'};
1157 
1158 if ~isempty(which('xlswrite'))
1159   xls_write = 1;
1160 elseif ~isempty(which('xlswrite5'))
1161   xls_write = 2;
1162 else
1163   xls_write = 0;
1164 end
1165 
1166 if xls_write
1167   Ls = [Ls  '|Excel spreadsheet'];
1168   Os = [Os {'xls'}];
1169 end
1170 
1171 src = spm_input('Export to?', '+1', 'm', Ls, Os, 1);
1172 
1173 if r_f
1174   rno = marsbar('get_region', region_name(marsY));
1175   Y = region_data(marsY, rno);
1176   Y = Y{1};
1177 else
1178   Y = summary_data(marsY);
1179 end
1180 
1181 switch src{1}
1182  case 'matlab'
1183   str = '';
1184   while ~mars_utils('is_valid_varname', str)
1185     str = spm_input('Matlab variable name', '+1', 's');
1186     if isempty(str), return, end
1187   end
1188   assignin('base', str, Y);
1189   fn = ['Matlab variable: ' str];
1190  case 'txt'
1191   [fn, pn] = mars_uifile('put',  ...
1192       {'*.txt;*.dat;*.csv', 'Text files (*.txt, *.dat, *.csv)'; ...
1193        '*.*',                   'All Files (*.*)'}, ...
1194       'Text file name');
1195   if isequal(fn,0), return, end
1196   save(fullfile(pn,fn), 'Y', '-ascii');
1197  case 'wk1'
1198   [fn, pn] = mars_uifile('put',  ...
1199       {'*.wk1', 'Lotus spreadsheet files (*.wk1)'; ...
1200        '*.*',                   'All Files (*.*)'}, ...
1201       'Lotus spreadsheet file');
1202   if isequal(fn,0), return, end
1203   wk1write(fullfile(pn,fn), Y);
1204  case 'xls'
1205   [fn, pn] = mars_uifile('put',  ...
1206       {'*.xls', 'Excel spreadsheet files (*.wk1)'; ...
1207        '*.*',                   'All Files (*.*)'}, ...
1208       'Excel spreadsheet file');
1209   if isequal(fn,0), return, end
1210   if xls_write == 1
1211     xlswrite(fullfile(pn,fn), Y);
1212   else
1213     xlswrite5(fullfile(pn,fn), Y);
1214   end
1215  otherwise
1216   error('Strange source');
1217 end
1218 disp(['Data saved to ' fn]);
1219 
1220 %=======================================================================
1221 case 'split_data'                %- splits data into one file per region
1222 %=======================================================================
1223 % marsbar('split_data')
1224 %-----------------------------------------------------------------------
1225 marsY = mars_arm('get', 'roi_data');
1226 if isempty(marsY), return, end
1227 if n_regions(marsY) == 1
1228   disp('Only one region in ROI data');
1229   return
1230 end
1231 
1232 % Setup input window
1233 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Split regions to files', 0);
1234 
1235 d = spm_get([-1 0], '', 'New directory root for files');
1236 if isempty(d), return, end
1237 
1238 def_f = summary_descrip(marsY);
1239 if ~isempty(def_f)
1240   def_f = mars_utils('str2fname', def_f);
1241 end
1242 f = spm_input('Root filename for regions', '+1', 's', def_f);
1243 f = mars_utils('str2fname', f);
1244 mYarr = split(marsY);
1245 for i = 1:length(mYarr)
1246   fname = fullfile(d, sprintf('%s_region_%d_mdata.mat', f, i));
1247   savestruct(mYarr(i), fname);
1248   fprintf('Saved region %d as %s\n', i, fname);
1249 end
1250 
1251 %=======================================================================
1252 case 'join_data'                %- joins many data files into one object
1253 %=======================================================================
1254 % marsbar('join_data')
1255 %-----------------------------------------------------------------------
1256 
1257 % Check save of current data first
1258 if sf_prev_save('roi_data') == -1, return, end
1259 
1260 P = spm_get([0 Inf], '*_mdata.mat', 'Select data files to join');
1261 
1262 if isempty(P), return, end
1263 for i = 1:size(P,1)
1264   d_o{i} = marsy(deblank(P(i,:)));
1265 end
1266 marsY = join(d_o{:});
1267 mars_arm('set', 'roi_data', marsY);
1268 mars_arm('show_summary', 'roi_data');
1269 disp(P)
1270 disp('Files merged and set as current data')
1271 
1272 %=======================================================================
1273 case 'estimate'                                       %-Estimates design
1274 %=======================================================================
1275 % marsbar('estimate')
1276 %-----------------------------------------------------------------------
1277 % Sequence is bit complex here, as setting the design may clear the ROI
1278 % data, and setting the ROI data may clear the default design, if they
1279 % have different numbers of rows
1280 marsD= mars_arm('get', 'def_design');
1281 if isempty(marsD), return, end
1282 marsY = mars_arm('get', 'roi_data');
1283 if isempty(marsY), return, end
1284 if mars_arm('isempty', 'def_design')
1285   error('Need design and data with matching number of rows');
1286 end
1287 if sf_prev_save('est_design') == -1, return, end
1288 if ~can_mars_estimate(marsD)
1289   marsD = fill(marsD, 'for_estimation');
1290   mars_arm('update', 'def_design', marsD);
1291 end
1292 marsRes = estimate(marsD, marsY, struct(...
1293     'redo_covar', 1, 'redo_whitening', 1));
1294 mars_arm('set', 'est_design', marsRes);
1295 mars_arm('show_summary', 'est_design');
1296 
1297 %=======================================================================
1298 case 'set_results'          %-sets estimated design into global stucture
1299 %=======================================================================
1300 % donef = marsbar('set_results')
1301 %-----------------------------------------------------------------------
1302 % Set results, put results ROI data into roi_data container
1303 
1304 varargout = {0};
1305 
1306 % Check if there's anything we don't want to write over
1307 if sf_prev_save('est_design') == -1, return, end
1308 if sf_prev_save('roi_data') == -1, return, end
1309 
1310 % Do set
1311 mars_arm('set_ui', 'est_design');
1312 if mars_arm('isempty', 'est_design'), return, end
1313 
1314 % Get design, set ROI data
1315 marsRes = mars_arm('get', 'est_design');
1316 mars_arm('set', 'roi_data', get_data(marsRes));
1317 
1318 % Clear default contrast
1319 if mars_struct('isthere', MARS, 'WORKSPACE', 'default_contrast')
1320   MARS.WORKSPACE.default_contrast = [];
1321   fprintf('Reset of estimated design, cleared default contrast...\n');
1322 end
1323 
1324 % Report on design
1325 fprintf('%-40s: ','Design reporting');
1326 ui_report(marsRes, 'DesMtx');
1327 ui_report(marsRes, 'DesRepUI');
1328 fprintf('%30s\n','...done');
1329 
1330 varargout = {1};
1331 return
1332 
1333 %=======================================================================
1334 case 'plot_residuals'                  %-plots residuals from estimation
1335 %=======================================================================
1336 % marsbar('plot_residuals')
1337 %-----------------------------------------------------------------------
1338 marsRes = mars_arm('get', 'est_design');
1339 if isempty(marsRes), return, end
1340 Y = residuals(marsRes);
1341 ns  = region_name(Y);
1342 rno = mars_struct('getifthere', MARS, 'WORKSPACE', 'default_region');
1343 if ~isempty(rno)
1344   fprintf('Using default region: %s\n', ns{rno});
1345 end
1346 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Plot residuals', 1);
1347 p_type = char(spm_input('Type of plot', '+1', 'm', ...
1348             'All|Time course|FFT|ACF', ...
1349             {'all','raw','fft','acf'}));
1350 ui_plot(Y, struct('types', p_type, 'r_nos', rno));
1351 
1352 %=======================================================================
1353 case 'set_defcon'                                 %-set default contrast
1354 %=======================================================================
1355 % Ic = marsbar('set_defcon')
1356 %-----------------------------------------------------------------------
1357 varargout = {[]};
1358 marsRes = mars_arm('get', 'est_design');
1359 if isempty(marsRes), return, end
1360 
1361 % Setup input window
1362 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Default contrast', 0);
1363 Ic = mars_struct('getifthere',MARS, 'WORKSPACE', 'default_contrast');
1364 if isempty(Ic)
1365   cname = '[Not set]';
1366 else 
1367   xCon = get_contrasts(marsRes);
1368   cname = xCon(Ic).name; 
1369 end
1370 spm_input(cname, 1, 'd', 'Default contrast');
1371 opts = {'Quit', 'Set new default'};
1372 if ~isempty(Ic), opts = [opts {'Clear default contrast'}]; end
1373 switch spm_input('What to do?', '+1', 'm', opts, [1:length(opts)], 1);
1374  case 1
1375  case 2
1376   [Ic marsRes changef] = ui_get_contrasts(marsRes, 'T|F',1,...
1377              'Select default contrast','',1);
1378   if changef
1379     mars_arm('update', 'est_design', marsRes);
1380   end
1381  case 3
1382   Ic = [];
1383 end
1384 MARS.WORKSPACE.default_contrast = Ic;
1385 varargout = {Ic};
1386 
1387 %=======================================================================
1388 case 'set_defregion'                                %-set default region
1389 %=======================================================================
1390 % rno = marsbar('set_defregion')
1391 %-----------------------------------------------------------------------
1392 varargout = {[]};
1393 marsY = mars_arm('get', 'roi_data');
1394 if isempty(marsY), return, end
1395 ns = region_name(marsY);
1396 if length(ns) == 1
1397   disp('Only one region in data');
1398   MARS.WORKSPACE.default_region = 1;
1399   varargout = {1};
1400   return
1401 end
1402 
1403 % Setup input window
1404 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Default region', 0);
1405 rno = mars_struct('getifthere',MARS, 'WORKSPACE', 'default_region');
1406 if isempty(rno), rname = '[Not set]'; else rname = ns{rno}; end
1407 spm_input(rname, 1, 'd', 'Default region:');
1408 opts = {'Quit', 'Set new default'};
1409 if ~isempty(rno), opts = [opts {'Clear default region'}]; end
1410 switch spm_input('What to do?', '+1', 'm', opts, [1:length(opts)], 1);
1411  case 1
1412  case 2
1413   rno = marsbar('get_region', ns);
1414   disp(['Default region set to: ' ns{rno}]); 
1415  case 3
1416   rno = [];
1417 end
1418 MARS.WORKSPACE.default_region = rno;
1419 varargout = {rno};
1420 
1421 %=======================================================================
1422 case 'get_region'                                  %-ui to select region
1423 %=======================================================================
1424 % select region from list box / input
1425 % rno = marsbar('get_region', names, prompt)
1426 % names is cell array of strings identifying regions
1427 % prompt is prompt string
1428 %-----------------------------------------------------------------------
1429 
1430 if nargin < 2
1431   error('Need region names to select from');
1432 else
1433   names = varargin{2};
1434 end
1435 if nargin < 3
1436   prompt = 'Select region';
1437 else
1438   prompt = varargin{3};
1439 end
1440 
1441 % maximum no of items in list box
1442 maxlist = 200;
1443 if length(names) > maxlist
1444   % text input, maybe
1445   error('Too many regions');
1446 end
1447 if length(names) == 1
1448   rno = 1;
1449 elseif isempty(names)
1450   rno = []
1451 else
1452   % listbox
1453   rno = spm_input(prompt, '+1', 'm', names);  
1454 end
1455 varargout = {rno};
1456 
1457 %=======================================================================
1458 case 'spm_graph'                                         %-run spm_graph
1459 %=======================================================================
1460 % marsbar('spm_graph')
1461 %-----------------------------------------------------------------------
1462 marsRes = mars_arm('get', 'est_design');
1463 if isempty(marsRes), return, end
1464 
1465 % Setup input window
1466 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Mars SPM graph', 1);
1467 
1468 ns  = region_name(get_data(marsRes));
1469 rno = mars_struct('getifthere', MARS, 'WORKSPACE', 'default_region');
1470 if ~isempty(rno)
1471   fprintf('Using default region: %s\n', ns{rno});
1472 else
1473   rno = marsbar('get_region', ns, 'Select region to plot');
1474 end
1475 
1476 Ic = mars_struct('getifthere', MARS, 'WORKSPACE', 'default_contrast');
1477 if ~isempty(Ic)
1478   xCon = get_contrasts(marsRes);
1479   fprintf('Using default contrast: %s\n', xCon(Ic).name);
1480 end
1481 
1482 % Variables returned in field names to allow differences
1483 % in return variables between versions of spm_graph
1484 [r_st marsRes changef] = mars_spm_graph(marsRes, rno, Ic);
1485 
1486 % Dump field names to global workspace as variables
1487 fns = fieldnames(r_st);
1488 for f = 1:length(fns)
1489   assignin('base', fns{f}, getfield(r_st, fns{f}));
1490 end
1491 
1492 % Store if changed
1493 if changef
1494   mars_arm('update', 'est_design', marsRes); 
1495 end
1496 
1497 %=======================================================================
1498 case 'stat_table'                                       %-run stat_table
1499 %=======================================================================
1500 % marsbar('stat_table')
1501 %-----------------------------------------------------------------------
1502 marsRes = mars_arm('get', 'est_design');
1503 if isempty(marsRes), return, end
1504 Ic = mars_struct('getifthere', MARS, 'WORKSPACE', 'default_contrast');
1505 if ~isempty(Ic)
1506   xCon = get_contrasts(marsRes);
1507   fprintf('Using default contrast: %s\n', xCon(Ic).name);
1508 end
1509 [strs marsS marsRes changef] = ... 
1510     stat_table(marsRes, Ic);
1511 disp(char(strs));
1512 assignin('base', 'marsS', marsS);
1513 if changef
1514   mars_arm('update', 'est_design', marsRes); 
1515 end
1516 
1517 %=======================================================================
1518 case 'signal_change'                             % percent signal change
1519 %=======================================================================
1520 % marsbar('signal_change')
1521 %-----------------------------------------------------------------------
1522 marsRes = mars_arm('get', 'est_design');
1523 if isempty(marsRes), return, end
1524 if ~is_fmri(marsRes)
1525   fprintf('Need FMRI design for %% signal change\n');
1526   return
1527 end
1528 
1529 % Setup input window
1530 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Percent signal change', 0);
1531 
1532 [marsRes ic status] = ui_event_types(marsRes);
1533 if (status==0), return, end
1534 if (status>1), mars_arm('update', 'est_design', marsRes); end
1535 if isempty(ic), return, end
1536 
1537 dur       = spm_input('Event duration', '+1', 'e', 0);
1538 
1539 % Choose event difference function
1540 diff_func = mars_struct('getifthere', MARS, 'OPTIONS', ...
1541             'events', 'diff_func');
1542 if isempty(diff_func), diff_func = 'max abs'; 
1543 elseif strcmp(diff_func, 'window')
1544   spm_input('Event signal change window...', '+1','d', mfilename);
1545   times = spm_input('Mean signal between times', ...
1546             '+1', 'r', [4 6], 2, [0 dur+32]);
1547   other_args = {times, bf_dt(marsRes)};
1548 else
1549   other_args = {};
1550 end
1551 
1552 ic_len    = length(ic);
1553 et = event_types(marsRes);
1554 for i = 1:ic_len
1555   pc(i,:) = event_signal(marsRes, et(ic(i)).e_spec, dur,  ...
1556              diff_func, ...
1557              other_args{:});
1558 end
1559 rns       = region_name(get_data(marsRes));
1560 disp('Sort-of % signal change');
1561 disp(sprintf('Duration: %3.2f seconds', dur));
1562 for i = 1:ic_len
1563   disp(['Event: ' et(ic(i)).name]);
1564   for r = 1:length(rns)
1565     disp(sprintf('Region: %40s; %5.3f', rns{r}, pc(i, r)));
1566   end
1567 end
1568 assignin('base', 'pc', pc);
1569 
1570 %=======================================================================
1571 case 'fitted_events'                    % show fitted event time courses
1572 %=======================================================================
1573 % marsbar('fitted_events')
1574 %-----------------------------------------------------------------------
1575 marsRes = mars_arm('get', 'est_design');
1576 if isempty(marsRes), return, end
1577 if ~is_fmri(marsRes)
1578   fprintf('Need FMRI design for fitted event time courses\n');
1579   return
1580 end
1581 
1582 % Setup input window
1583 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Fitted events', 1);
1584 
1585 [marsRes ic status] = ui_event_types(marsRes);
1586 if (status==0), return, end
1587 if (status>1), mars_arm('update', 'est_design', marsRes); end
1588 if isempty(ic), return, end
1589 
1590 dur       = spm_input('Event duration', '+1', 'e', 0);
1591 ic_len    = length(ic);
1592 et = event_types(marsRes);
1593 for i = 1:ic_len
1594   [tc{i} dt] = event_fitted(marsRes, et(ic(i)).e_spec, dur);
1595 end
1596 
1597 if ic_len > 8
1598   warning('Too many event types to plot, plotting first 8');
1599   ic_len = 8;
1600 end
1601 
1602 figure(Fgraph);
1603 if ic_len > 1, p_cols = 2; else p_cols = 1; end
1604 p_rows = ceil(ic_len / p_cols);
1605 last_row_starts = (p_rows-1) * p_cols + 1;
1606 for i = 1:ic_len
1607   t = tc{i};
1608   secs = ([1:size(t, 1)]-1) * dt;
1609   subplot(p_rows, p_cols, i);
1610   plot(secs, t);
1611   title(et(ic(i)).name);
1612   if i >= last_row_starts, xlabel('Seconds'); end
1613   if rem(i-1, p_cols)==0, ylabel('Signal change'); end
1614 end
1615 
1616 legend(region_name(get_data(marsRes)));
1617 
1618 assignin('base', 'time_courses', tc);
1619 assignin('base', 'dt', dt);
1620 
1621 %=======================================================================
1622 case 'fir_events'                                  % show FIR for events
1623 %=======================================================================
1624 % marsbar('fir_events')
1625 %-----------------------------------------------------------------------
1626 marsRes = mars_arm('get', 'est_design');
1627 if isempty(marsRes), return, end
1628 if ~is_fmri(marsRes)
1629   fprintf('Need FMRI design for FIR event time courses\n');
1630   return
1631 end
1632 
1633 % Setup input window
1634 [Finter,Fgraph,CmdLine] = spm('FnUIsetup','FIR for events', 1);
1635 
1636 [marsRes ic status] = ui_event_types(marsRes);
1637 if (status==0), return, end
1638 if (status>1), mars_arm('update', 'est_design', marsRes); end
1639 if isempty(ic), return, end
1640 
1641 et = event_types(marsRes);
1642 ic_len = length(ic);
1643 
1644 % Single or stacked?
1645 % If all the events have zero duration, the model is already single, and
1646 % there is no point in asking.  If any of the durations are different
1647 % across events, then the single model is invalid.
1648 d_a = []; opts = []; 
1649 for i = 1:ic_len
1650   e_spec = et(ic(i)).e_spec;
1651   for j = 1:size(e_spec, 2)
1652     [o d] = event_onsets(marsRes, e_spec(:, j));
1653     d_a = [d_a; d];
1654   end
1655 end
1656 if any(d_a) & ~any(diff(d_a))
1657   if spm_input('FIR type', '+1','m',...
1658            'Single|Stacked', [1 0], 1)
1659     opts.single = 1;
1660   end
1661 end
1662 if spm_input('Signal units', '+1','m',...
1663          'Percent|Beta units', [1 0], 1)
1664   opts.percent = 1;
1665 end
1666 
1667 bin_length = spm_input('Bin length (secs)', '+1', 'e', tr(marsRes));
1668 def_bin_no = round(25/bin_length);
1669 bin_no     = spm_input('No of bins', '+1', 'e', def_bin_no);
1670 
1671 for i = 1:ic_len
1672   tc{i} = event_fitted_fir(marsRes, ...
1673                et(ic(i)).e_spec, ...
1674                bin_length, ...
1675                bin_no, ...
1676                opts);
1677 end
1678 
1679 if ic_len > 8
1680   warning('Too many event types to plot, plotting first 8');
1681   ic_len = 8;
1682 end
1683 
1684 figure(Fgraph);
1685 if ic_len > 1, p_cols = 2; else p_cols = 1; end
1686 p_rows = ceil(ic_len / p_cols);
1687 last_row_starts = (p_rows-1) * p_cols + 1;
1688 secs = ([1:bin_no]-1) * bin_length + bin_length/2;
1689 for i = 1:ic_len
1690   t = tc{i};
1691   subplot(p_rows, p_cols, i);
1692   plot(secs, t);
1693   title(et(ic(i)).name);
1694   if i >= last_row_starts, xlabel('Seconds'); end
1695   if rem(i-1, p_cols)==0, ylabel('Signal change'); end
1696 end
1697 legend(region_name(get_data(marsRes)));
1698 
1699 assignin('base', 'time_courses', tc);
1700 assignin('base', 'bin_length', bin_length);
1701 assignin('base', 'bin_no', bin_no);
1702 
1703 %=======================================================================
1704 case 'add_events_by_name'  %-make event types from events with same name
1705 %=======================================================================
1706 % marsbar(''add_events_by_name')
1707 %-----------------------------------------------------------------------
1708 D = mars_arm('get', 'est_design');
1709 if isempty(D), return, end
1710 if ~is_fmri(D)
1711   disp('Can only add event types to FMRI designs');
1712   return
1713 end
1714 et = event_types(D);
1715 et = [et event_types_named(D)];
1716 D  = event_types(D, et);
1717 mars_arm('update', 'est_design', D);
1718  
1719 %=======================================================================
1720 case 'merge_contrasts'                                %-import contrasts
1721 %=======================================================================
1722 % marsbar('merge_contrasts')
1723 %-----------------------------------------------------------------------
1724 D = mars_arm('get', 'est_design');
1725 if isempty(D), return, end
1726 filter_spec = {...
1727     'SPM.mat','SPM: SPM.mat';...
1728     '*_mres.mat','MarsBaR: *_mres.mat';...
1729     '*x?on.mat','xCon.mat file'};
1730 [fn pn] = mars_uifile('get', ...
1731     filter_spec, ...
1732     'Source design/contrast file...');
1733 if isequal(fn,0) | isequal(pn,0), return, end
1734 fname = fullfile(pn, fn);
1735 D2 = mardo(fname);
1736 
1737 % has this got contrasts?
1738 if ~has_contrasts(D2)
1739   error(['Cannot find contrasts in design/contrast file ' fname]);
1740 end
1741   
1742 % now try to trap case of contrast only file
1743 if ~is_valid(D2)
1744   D2 = get_contrasts(D2);
1745 end
1746 
1747 [D Ic changef] = add_contrasts(D, D2, 'ui');
1748 disp('Done');
1749 if changef
1750   mars_arm('update', 'est_design', D);
1751 end
1752 
1753 %=======================================================================
1754 case 'add_trial_f'            %-add trial-specific F contrasts to design
1755 %=======================================================================
1756 % marsbar('add_trial_f')
1757 %-----------------------------------------------------------------------
1758 D = mars_arm('get', 'est_design');
1759 if isempty(D), return, end
1760 if ~is_fmri(D)
1761   disp('Can only add trial specific F contrasts for FMRI designs');
1762   return
1763 end
1764 [D changef] = add_trial_f(D);
1765 disp('Done');
1766 if changef
1767   mars_arm('update', 'est_design', D);
1768 end
1769  
1770 %=======================================================================
1771 case 'error_log'                  %- makes file to help debugging errors
1772 %=======================================================================
1773 % fname = marsbar('error_log', fname);
1774 %-----------------------------------------------------------------------
1775 if nargin < 2
1776   fname = 'error_log.mat';
1777 else
1778   fname = varargin{2};
1779 end
1780 
1781 e_log = struct('last_error', lasterr, ...
1782            'm_ver', marsbar('ver'),...
1783            'mars', MARS);
1784 savestruct(fname, e_log);
1785 if ~isempty(which('zip'))
1786   zip([fname '.zip'], fname);
1787   fname = [fname '.zip'];
1788 end
1789 disp(['Saved error log as ' fname]);
1790 
1791 %=======================================================================
1792 case 'mars_menu'                     %-menu selection of marsbar actions
1793 %=======================================================================
1794 % marsbar('mars_menu',tstr,pstr,tasks_str,tasks)
1795 %-----------------------------------------------------------------------
1796 
1797 [tstr pstr optfields optlabs] = deal(varargin{2:5}); 
1798 if nargin < 6
1799   optargs = cell(1, length(optfields));
1800 else
1801   optargs = varargin{6};
1802 end
1803 
1804 [Finter,Fgraph,CmdLine] = spm('FnUIsetup',tstr);
1805 of_end = length(optfields)+1;
1806 my_task = spm_input(pstr, '+1', 'm',...
1807           {optlabs{:} 'Quit'},...
1808           [1:of_end],of_end);
1809 if my_task == of_end, return, end
1810 marsbar(optfields{my_task}{:});
1811 
1812 %=======================================================================
1813 otherwise                                        %-Unknown action string
1814 %=======================================================================
1815 error('Unknown action string')
1816 
1817 %=======================================================================
1818 end
1819 return
1820 
1821 % subfunctions
1822 function sum_func = sf_get_sumfunc(sum_func)
1823 if strcmp(sum_func, 'ask')
1824   sum_func = char(spm_input('Summary function', '+1','m',...
1825                'Mean|Weighted mean|Median|1st eigenvector',...
1826                {'mean','wtmean','median','eigen1'}, 1));
1827 end
1828 
1829 function btn = sf_prev_save(obj_name)
1830 btn = mars_arm('save_ui', obj_name, ...
1831            struct('ync', 1, ...
1832               'no_no_save', 1, ...
1833               'prompt_prefix', 'previous '));
1834 % If answer is 'No', then flag that we don't need to save
1835 if btn == 0
1836   mars_arm('set_param', obj_name, 'has_changed', 0);
1837 end
1838 return
1839

Generated on Tue 21-Jul-2009 00:29:30 by m2html © 2003