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 and copyright claimed by 
 Jean-Luc Anton, Matthew Brett, Jean-Baptiste Poline, Romain Valabregue 

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

Generated on Wed 11-May-2022 16:26:09 by m2html © 2003-2019