#! /bin/csh -f

#
# mkanalysis-sess -- sets up post-processing environment for 
# functional analysis
#
# Original Author: Doug Greve
# CVS Revision Info:
#    $Author: greve $
#    $Date: 2010/07/30 16:51:11 $
#    $Revision: 1.49.2.3 $
#
# Copyright (C) 2002-2007,
# The General Hospital Corporation (Boston, MA). 
# All rights reserved.
#
# Distribution, usage and copying of this software is covered under the
# terms found in the License Agreement file named 'COPYING' found in the
# FreeSurfer source code root directory, and duplicated here:
# https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferOpenSourceLicense
#
# General inquiries: freesurfer@nmr.mgh.harvard.edu
# Bug reports: analysis-bugs@nmr.mgh.harvard.edu
#

set VERSION = '$Id: mkanalysis-sess,v 1.49.2.3 2010/07/30 16:51:11 greve Exp $';

set analysis = ();
set TR = ();
set DesignType = ();
set Period = ();
set ParName = ();
set StimulusDelay = 0;
set RawSpaceType = ();
set RawSpace = ();
set RawHemi = ();
set RawRes = ();
set RawFWHM = ();
set RawSTC = none;
set ExpKey = ();
set mcstem = ();
set funcstem = ();
set maskstem = brain;
set fsd = bold;
set RunListFile = ();
set NConditions = ();
set PreStim = ();
set PostStim = ();
set IdealTimeWindow = 40;
set TimeWindow = ();
set IdealTER = .050;
set TER = ();
set HRFModel = ();
set RefEventDur = ();
set GammaDelta = ();
set GammaTau = ();
set GammaAlpha = 2;
set nGammaDeriv = 0;
set nSPMHRF = ();
set TaskRegList = ();
set nTaskRegList = ();
set PolyFit = 2;
set HPFCutoffHz = 0;
set TPExcludeFile = ();
set NSkip = 0;
set NuisRegList = ();
set nNuisRegList = ();
set ACFBins = 30;
set ACFFWHM = 20;
set FixACF = 1;
set ACFSVD = 0;
set DoInorm = 1;
set RescaleTarget = 100;
set eventrelated = 0;
set abblocked = 0;
set retinotopy = 0;
set notask = 0;
set PrintHelp = 0;
set RegDOF = 6;
set DoMCExtReg = 0;

set force = 0;
set UseGUI = 0;

set cmdargs = ($argv);
#### If no arguments, print usage and exit ####
if($#argv == 0) goto usage_exit;
set n = `echo $argv | grep -e -help | wc -l` 
if($n != 0) then
  set PrintHelp = 1;
  goto usage_exit;
  exit 1;
endif

##### Print out version info, if needed ####
set n = `echo $argv | grep version | wc -l` 
if($n != 0) then
  echo $VERSION
  exit 0;
endif

set GSPArgs = ();
set sxacfg = "analysis.cfg"

# Don't require Session Arguments #
set SessList = `getsesspath $argv`;
if($status || $#SessList == 0) set SessList = ();

goto parse_args;
parse_args_return:

goto check_params;
check_params_return:

#-----------------------------------------
if($UseGUI) then
setenv FSF_PROC_GUI_BUG 1
if($#mfile == 0) set mfile = /tmp/mkanalysis-sess.gui.m
rm -f $mfile
tee $mfile > /dev/null <<EOF
monly = $monly;
global MkAnalysisName;
global MkAnalysisClone;
MkAnalysisName = '$analysis';
MkAnalysisClone = '$cloneanalysis';
h = mkanalysis_gui;
uiwait(h);
if(~monly) quit; end
EOF
if(! $monly) then
  cat $mfile | matlab
endif
exit 0;
endif
#-----------------------------------------

mkdir -p $analysis
set flac = $analysis/analysis.info
rm -f $flac

# -------- Bookkeeping -------------
echo "# FSBUILD `cat $FREESURFER_HOME/build-stamp.txt`" | tee -a $flac
echo "# MKAVERSION $VERSION" | tee -a $flac
echo "# MKACMD $0 $cmdargs"| tee -a $flac
echo "# DATE `date`"| tee -a $flac
echo "" | tee -a $flac
# -------- Raw data info -------------
echo "analysis $analysis" | tee -a $flac
echo "mcstem $mcstem" | tee -a $flac
if($#funcstem) echo "funcstem $funcstem" | tee -a $flac
echo "fsd $fsd" | tee -a $flac
if($#RunListFile) echo "runlistfile $RunListFile" | tee -a $flac
echo "TR $TR" | tee -a $flac
echo "RegDOF $RegDOF" | tee -a $flac
if($RawSpace == native)      echo "RawSpace volume native" | tee -a $flac
if($RawSpace == mni305)      echo "RawSpace volume mni305 $RawRes" | tee -a $flac
if($RawSpaceType == surface) echo "RawSpace surface $RawSpace $RawHemi" | tee -a $flac
echo "mask $maskstem" | tee -a $flac
echo "RawFWHM $RawFWHM" | tee -a $flac
if($#RawSTC) echo "RawSTC $RawSTC" | tee -a $flac
if($#ExpKey) echo "ExpKey $ExpKey" | tee -a $flac
echo "inorm $RescaleTarget" | tee -a $flac
# -- Noise and drift modeling, temporal filtering ------
echo "acfbins $ACFBins" | tee -a $flac
echo "fixacf  $FixACF" | tee -a $flac
echo "acffwhm $ACFFWHM" | tee -a $flac
echo "acfsvd  $ACFSVD" | tee -a $flac
echo "designtype $DesignType" | tee -a $flac
if($#TPExcludeFile) echo "tpexclude $TPExcludeFile" | tee -a $flac
echo "nskip $NSkip" | tee -a $flac
if($#PolyFit) echo "polyfit $PolyFit" | tee -a $flac
echo "HPFCutoffHz $HPFCutoffHz" | tee -a $flac
# ------------ Event Task Modeling -----------
if($eventrelated) then
  echo "nconditions $NConditions"  | tee -a $flac
  echo "parname $ParName" | tee -a $flac
  if($#RefEventDur) echo "RefEventDur $RefEventDur" | tee -a $flac
  echo "timewindow $TimeWindow"| tee -a $flac
  echo "prestim $PreStim"| tee -a $flac
  echo "TER $TER" | tee -a $flac
  if($HRFModel == "gamma")  echo "gamma $GammaDelta $GammaTau $GammaAlpha $nGammaDeriv"| tee -a $flac
  if($HRFModel == "spmhrf") echo "spmhrf $nSPMHRF" | tee -a $flac
  echo "stimulusdelay $StimulusDelay" | tee -a $flac
  @ nthc = 1
  while($nthc <= $NConditions)
    printf "Condition $nthc Condition%02d\n" $nthc | tee -a $flac
    @ nthc = $nthc + 1
  end
endif
# ------------ Retinotopy -----------------
if($retinotopy) then
  echo "parname $ParName" | tee -a $flac
  echo "period $Period" | tee -a $flac
endif
# ------------ AB Blocked -----------------
if($abblocked) then
  echo "period $Period" | tee -a $flac
endif
# ------------ Task External Regressors -----------------
if($#TaskRegList) then
  @ nth = 1;
  foreach reg ($TaskRegList)
    echo "taskreg $reg $nTaskRegList[$nth]" | tee -a $flac
    @ nth = $nth + 1;
  end
endif
# ------------ Nuisance External Regressors -----------------
if($DoMCExtReg) then
  if($RawSpace == native) then
    set NuisRegList  = ($NuisRegList mcextreg);
  else
    set NuisRegList  = ($NuisRegList mcprextreg);
  endif
  set nNuisRegList = ($nNuisRegList 3);
endif
if($#NuisRegList) then
  @ nth = 1;
  foreach reg ($NuisRegList)
    echo "nuisreg $reg $nNuisRegList[$nth]" | tee -a $flac
    @ nth = $nth + 1;
  end
endif

echo "mkanalysis-sess done"

exit 0;
###############################################


############--------------##################
parse_args:

set cmdline = "$argv";
while( $#argv != 0 )

  set flag = $argv[1]; shift;
  
  switch($flag)

    case "-a":
    case "-analysis":
      if($#argv < 1) goto arg1err;
      if($#analysis) then
        echo "ERROR: you have specified the analysis twice"
        exit 1
      endif
      set analysis = $1; shift;
      breaksw

    case "-p":
    case "-par":
    case "-paradigm":
      if($#argv < 1) goto arg1err;
      set ParName = $1; shift;
      breaksw

    case "-fsd":
      if($#argv < 1) goto arg1err;
      set fsd = $1; shift;
      breaksw

    case "-funcstem":
      if($#argv < 1) goto arg1err;
      set funcstem = $1; shift;
      breaksw

    case "-runlistfile":
    case "-rlf":
      if($#argv < 1) goto arg1err;
      set RunListFile = $1; shift;
      breaksw

    case "-nconditions":
    case "-nc":
      if($#argv < 1) goto arg1err;
      set NConditions = $argv[1]; shift;
      breaksw

    case "-tpexclude":
    case "-tpef":
    case "-tpex":
      if($#argv < 1) goto arg1err;
      set TPExcludeFile = $argv[1]; shift;
      breaksw

    case "-timewindow":
    case "-tw":
      if($#argv < 1) goto arg1err;
      set IdealFIRTimeWindow = $argv[1]; shift;
      breaksw

    case "-delay":
    case "-timeoffset":
      if($#argv < 1) goto arg1err;
      set StimulusDelay = $argv[1]; shift;
      breaksw

    case "-acfbins":
    case "-acf-bins":
      if($#argv < 1) goto arg1err;
      set ACFBins = $argv[1]; shift;
      breaksw

    case "-acffwhm":
    case "-acf-fwhm":
      if($#argv < 1) goto arg1err;
      set ACFFWHM = $argv[1]; shift;
      breaksw

    case "-no-fix-acf":
    case "-no-acf-fix":
      set FixACF = 0;
      breaksw

    case "-acf-svd":
    case "-acfsvd":
      if($#argv < 1) goto arg1err;
      set ACFSVD = $argv[1]; shift;
      breaksw

    case "-no-whiten":
    case "-nowhiten":
      set ACFBins = 0;
      breaksw

    case "-mask":
      if ( $#argv < 0) goto arg1err;
      set maskstem = $argv[1]; shift;
      breaksw

    case "-ter":
    case "-TER":
      if($#argv < 1) goto arg1err;
      set TER = $argv[1]; shift;
      breaksw

    case "-tr":
    case "-TR":
      if($#argv < 1) goto arg1err;
      set TR = $argv[1]; shift;
      breaksw

    case "-nuisreg": # External regressor file
      if($#argv < 2) goto arg2err;
      set NuisRegList  = ($NuisRegList $argv[1]); shift;
      set nNuisRegList = ($nNuisRegList $argv[1]); shift;
      breaksw

    case "-mcextreg": # MotionCor External regressor file
      set DoMCExtReg = 1;
      breaksw

    case "-taskreg": # External regressor file
      if($#argv < 2) goto arg2err;
      set TaskRegList  = ($TaskRegList $argv[1]); shift;
      set nTaskRegList = ($nTaskRegList $argv[1]); shift;
      breaksw

    case "-fir":
      if($#argv < 2) goto arg2err;
      set PreStim = $argv[1]; shift;
      set TimeWindow = $argv[1]; shift;
      set HRFModel = "fir";
      breaksw

    case "-gamma":
    case "-gammafit":
      if ( $#argv < 2) goto arg2err;
      set GammaDelta = $argv[1]; shift;
      set GammaTau   = $argv[1]; shift;
      set TimeWindow = $IdealTimeWindow;
      set PreStim = 0;
      set HRFModel = "gamma";
      breaksw

    case "-gammaexp":
      if ( $#argv < 1) goto arg1err;
      set GammaAlpha = $argv[1]; shift;
      breaksw

    case "-ngammaderiv":
      if ( $#argv < 1) goto arg1err;
      set nGammaDeriv = $argv[1]; shift;
      breaksw

    case "-spmhrf":
      if ( $#argv < 1) goto arg1err;
      set nSPMHRF = $argv[1]; shift;
      set TimeWindow = $IdealTimeWindow;
      set PreStim = 0;
      set HRFModel = "spmhrf";
      breaksw

    case "-red":
    case "-refeventdur":
      if($#argv < 1) goto arg1err;
      set RefEventDur = $argv[1]; shift;
      breaksw

    case "-fwhm":
      if($#argv < 1) goto arg1err;
      set RawFWHM = $argv[1]; shift;
      breaksw

    case "-reg-dof":
      if($#argv < 1) goto arg1err;
      set RegDOF = $argv[1]; shift;
      breaksw

    case "-slice-time-cor":
    case "-stc":
      if($#argv < 1) goto arg1err;
      set RawSTC = $argv[1]; shift;
      if($RawSTC != siemens && $RawSTC != up && $RawSTC != down && \
         $RawSTC != odd && $RawSTC != even && $RawSTC != none) then
         echo "ERROR: -stc is $RawSTC, must be siemens, up, down, odd, even, or none"
         exit 1;
      endif
      breaksw

    case "-nskip":
      if($#argv < 1) goto arg1err;
      set NSkip = $argv[1]; shift;
      breaksw

    case "-period":
      if($#argv < 1) goto arg1err;
      set Period = $argv[1]; shift;
      breaksw

    case "-surface":
    case "-surf":
      if($#argv < 2) goto arg2err;
      set RawSpace = $argv[1]; shift; # subjectname
      set RawHemi = $argv[1]; shift;
      set RawSpaceType = surface
      set mcstem = fmcpr
      breaksw

    case "-mni305":
      if($#argv < 1) goto arg1err;
      set RawRes = $argv[1]; shift;
      set RawSpaceType = volume;
      set RawSpace = mni305;
      set mcstem = fmcpr
      breaksw

    case "-native":
      set RawSpaceType = volume
      set RawSpace = native
      set mcstem = fmc
      breaksw

    case "-expkey":
      if($#argv < 1) goto arg1err;
      set ExpKey = $argv[1]; shift; # prepend a dot later
      breaksw

    case "-notask":
      set DesignType = "notask"
      set notask = 1;
      set eventrelated = 0;
      set abblocked = 0;
      set retinotopy = 0;
      breaksw

    case "-event-related":
    case "-er":
      set DesignType = "event-related"
      set eventrelated = 1;
      set abblocked = 0;
      set retinotopy = 0;
      breaksw

    case "-abblocked":
      if($#argv < 1) goto arg1err;
      set Period = $argv[1]; shift;
      set DesignType = "abblocked"
      set abblocked = 1;
      set PolyFitOrder = 1;
      #set HPFCutoffHz = `echo ".5/$Period" | bc -l`
      set HPFCutoffHz = 0;
      set ACFBins = 0;
      set eventrelated = 0;
      set retinotopy = 0;
      breaksw

    case "-retinotopy":
    case "-rtopy":
    case "-ret":
      if($#argv < 1) goto arg1err;
      set Period = $argv[1]; shift;
      set DesignType  = "retinotopy"
      set retinotopy = 1;
      set PolyFitOrder = 1;
      #set HPFCutoffHz = `echo ".5/$Period" | bc -l`
      set HPFCutoffHz = 0;
      set ACFBins = 0;
      set eventrelated = 0;
      set abblocked = 0;
      breaksw

    case "-polyfit":
    case "-pf":
      if ( $#argv < 1) goto arg1err;
      set PolyFit = $argv[1]; shift;
      breaksw

    case "-hpf":
      if ( $#argv < 1) goto arg1err;
      set HPFCutoffHz = $argv[1]; shift;
      breaksw

    case "-no-hpf":
      set HPFCutoffHz = 0;
      breaksw

    case "-overwrite":
    case "-force":
      set force = 1;
      breaksw

    case "-noinorm":
    case "-no-inorm":
      set DoInorm = 0;
      breaksw

    case "-inorm":
      set DoInorm = 1;
      breaksw

    case "-rescale-target":
      if($#argv < 1) goto arg1err;
      set RescaleTarget = $argv[1]; shift;
      set DoInorm = 1;
      breaksw

    case "-fsv3":
      set FSV3whiten = 1;
      set RescaleTarget = 1000;
      breaksw

    case "-fsv3-whiten":
      set FSV3whiten = 1;
      breaksw

    case "-debug":
      set verbose = 1;
      set echo = 1;
      breaksw

    case "-gui": 
      set UseGUI = 1;
      set force = 1;
      breaksw

    default:
      echo ERROR: Flag $flag unrecognized.
      echo $cmdline
      exit 1
      breaksw
  endsw

end
goto parse_args_return;
############--------------##################

############--------------##################
check_params:

  if($#analysis == 0) then
    echo "ERROR: must specify an analysis name"
    exit 1;
  endif
  if(-e $analysis && ! $force) then
    echo "ERROR: analysis $analysis already exists. You have three options"
    echo "  1. Give this analysis a different name"
    echo "  2. Give delete analysis $analysis and re-run mkanalysis-sess"
    echo "  3. Re-run mkanalysis-sess with a -force option to overwrite"
    exit 1;
  endif
  if(-e $analysis && $force) then
    echo "INFO:  analysis $analysis exists, but overwrite forced by user."
  endif

  if($#TR == 0) then
    echo "ERROR: must specify TR"
    exit 1;
  endif
  if($#DesignType == 0) then
    echo "ERROR: must specify design type. Choose "
    echo " either -event-related, -abblocked, or -retinotopy" 
    exit 1;
  endif
  if($#RawSpaceType == 0) then
    echo "ERROR: must specify -native, -surface, or -mni305"
    exit 1;
  endif
  if($#RawFWHM == 0) then
    echo "ERROR: you must set a FWHM with -fwhm. If you do not want"
    echo "to smooth, use -fwhm 0"
    exit 1;
  endif

  if($eventrelated) then
    if($#ParName == 0) then
      echo "ERROR: must specify a paradigm file name with event-related "
      echo "  and blocked designs. Use the -paradigm option."
      exit 1;
    endif
    if($#NConditions == 0) then
      echo "ERROR: you must specify number of conditions with event-related "
      echo "  and blocked designs. Use the -nc option."
      exit 1;
    endif
    if($#HRFModel == 0) then
      echo "ERROR: you must specify an HRF model with event-related and blocked designs."
      echo " Choose one of the following models: -fir, -gamma, -spmhrf."
      exit 1;
    endif
    if($#RefEventDur == 0 && $HRFModel != fir) then
      echo "ERROR: you must specify a reference event duration with non-fir"
      echo "  event-related and blocked designs. Use the -refeventdur flag."
      exit 1;
    endif
    if($#TER == 0 && $HRFModel == "fir") set TER = $TR;
    if($#TER == 0 && $HRFModel != "fir") then
      set TER = `perl -e "print sprintf('%f',$TR/int($TR/$IdealTER+0.5))"`
    endif
    echo "Setting TER to $TER"
    set Nh  = `echo "($TimeWindow/$TER)" | bc`;
    set TimeWindow  = `echo "$TER*$Nh" | bc -l`;
    set Nps  = `echo "($PreStim/$TER)" | bc`;
    set PreStim  = `echo "$TER*$Nps" | bc -l`;
    set PostStim = `echo "$TimeWindow - $PreStim" | bc -l`
    echo "Setting TimeWindow to $TimeWindow"
    echo "Setting PreStim    to $PreStim"
    echo "Setting PostStim   to $PostStim"
  endif

  if($retinotopy && $#ParName == 0) then
    echo "ERROR: must specify a paradigm file name with retinotopy designs"
    echo "  and blocked designs. Use the -paradigm option."
    exit 1;
  endif
  if($abblocked && $#ParName != 0) then
    echo "ERROR: cannot specify a paradigm file with abblocked designs"
    exit 1;
  endif

goto check_params_return;
############--------------##################

############--------------##################
arg1err:
  echo "ERROR: flag $flag requires one argument"
  exit 1
############--------------##################

############--------------##################
arg2err:
  echo "ERROR: flag $flag requires two arguments"
  exit 1
############--------------##################

############--------------##################
usage_exit:
  echo ""
  echo "mkanalysis-sess : configure a first-level FSFAST analysis"
  echo ""
  echo "  -analysis  analysisname : name of analysis configuration";
  echo ""
  echo "Preprocessing"
  echo "  -surface subject hemi : sample raw data onto the hemi.subject surface"
  echo "  -mni305 <resMM>       : sample raw in mni305 with resolution resMM (1 or 2)"
  echo "  -native               : leave raw data in native functional space"
  echo "  -fwhm FWHMmm : spatially smooth input by FWHM (in mm) in proper space"
  echo "  -stc SliceOrder : slice-time correct using the name of the SliceOrder (default none)"
  echo "  -reg-dof DOF : use given DOF when performing registration (default is $RegDOF)"
  echo ""
  echo "Basic Design Arguments"
  echo "  -event-related          : event-related or blocked design"
  echo "  -retinotopy periodSec   : retinotopy design with period (sec)"
  echo "  -abblocked  periodSec   : abblocked design with period (sec)"
  echo "  -notask : use external and/or nuisance regressors only"
  echo "  -paradigm  ParName      : name of paradigm file (needed for ER and ret)"
  echo "  -TR   TR                : TR value in seconds"
  echo ""
  echo "Event-Related and Blocked Design Arguments "
  echo "   -nconditions Nc      : number of conditions (excluding fixation)"
  echo "   -delay Delay : delay (add) Delay sec to time in each paradigm file"
  echo "        ------------- FIR - do not assume a shape ----------------"
  echo "   -fir PreStim TimeWindow : event prestimulus and total time window (sec) for FIR designs"
  echo "   -TER TER             : temporal estimation resolution (sec)"
  echo "        ------------- Assume a shape ----------------"
  echo "   -spmhrf nderiv    : assume SPM HRF with nderiv derivatives"
  echo "   -gammafit gfDelta gfTau : assume IRF is a gamma function"
  echo "   -gammaexp gfAlpha : gamma exponent (default is 2) "
  echo "   -ngammaderiv N   : number of derivatives to gamma function "
  echo "   -refeventdur Duration : duration (sec) of reference event for scaling"
  echo "        ------------- Other Options ----------------"
  echo "   -taskreg extreg N : external task regressor file and number of regressors to include"
  echo ""
  echo "Noise, drift, and temporal filtering options"
  echo "   -polyfit N          : fit trend with polynomial of order N (default is 2)"
  echo "   -hpf CutoffHz       : High-pass filtering with Cuttoff in Hz"
  echo "   -tpexclude filename : time-point (in seconds) exclude file name"
  echo "   -nskip  N           : skip the first N time points in each run"
  echo "   -nuisreg extreg n : external nuisance regressor file and number of regressors to include"
  echo "   -mcextreg      : use motion parameters as external nuissance regressors (sets n=3)"
  echo "   -nowhiten      : turn off temporal whitening (same as -acfbins 0)"
  echo "   -acfbins nbins : spatially segment autocorrelation into nbins (def 10)"
  echo "   -acffwhm fwhm  : spatially smooth ACF before binning (def 20)"
  echo "   -no-fix-acf    : do NOT compensate for resdualized ACF"
  echo "   -acf-svd N     : set number of components to remove before computing AR1/ACF (default is 0)"
  echo "   -fsv3-whiten   : perform whitening like FreeSurfer Version 3 (and -no-)"
  echo ""
  echo "Other Optional Arguments"
  echo "  -fsd FSD              : functional subdirectory (default is bold)"
  echo "  -runlistfile filename : file with list of runs to include in analysis"
  echo "  -funcstem stem  : override default"
  echo "  -mask  maskid : use masks/maskid to compute autocor and whitening"
  echo "  -no-inorm              : do not intensity normalize data"
  echo "  -rescale-target value  : intensity normalize to value"
  echo "  -version        : print version and exit"
  echo "  -help           : some help, the first place to check"
  echo ""
#  echo "   -fsv3 : set all fsv3 flags (FreeSurfer Version 3) (and -no-)"
#  echo "   -fsv3-st2fir : generate design matrix like FreeSurfer Version 3 (and -no-)"

  if( ! $PrintHelp) exit 1;

  echo $VERSION

  cat $0 | awk 'BEGIN{prt=0}{if(prt) print $0; if($1 == "BEGINHELP") prt = 1 }'

exit 1;

#---- Everything below here is printed out as part of help -----#
BEGINHELP

This program creates an 'analysis'. An analysis is a concept within the 
FS-FAST processing stream framework. The analysis is meant to be a 
placeholder for all the within-session processing options (eg, motion 
correction, spatial smoothing, event-type definition, etc). As such, 
the parameters apply to ALL sessions (ie, it does not need to be run 
separately for each session), and does not depend upon the data in any 
one session. This program should be run from your FS-FAST Study 
Directory. This program only configures the analysis; it does not 
analyze the data (see selxavg3-sess). 

 
ARGUMENTS AND FLAGS: 

-analysis analysisname (Shortcut: -a) 

This is the name given to the analysis. A folder called analysisname
will be created in the Study Directory. A file called analysis.info
will be created in this directory. The analysis parameters will be
stored in this file. Contrast matrices (created by mkcontrast-sess)
will also be stored in this directory. When the session data are
analyzed with selxavg3-sess, a folder called analysisname will be
created in the functional subdirectory (FSD), and the results of the
analysis will be placed there.

PREPROCESSING PARAMETERS

Note: by default, motion correction is assumed to be on. In this
section, you will set the space in which the analysis will be
performed, slice timing correction (if desired), and spatial smoothing
if desired. 

The space can be either surface, mni305, or native.

-surface subject hemi

When performing surface-based analyses, this will cause the raw 4D
data to be resampled onto the surface of the given subject. Usually
this is the surface-based atlas defined by fsaverage. You can also
specify 'self' to map to each individuals surface. Any smoothing will
be performed on the surface after resampling.

-mni305 resolutionMM

When performing volume-based analysis, this will cause the raw 4D data
to be resampled onto the MNI305 space with the given resolution. You
can only choose 1 (1mm) or 2 (2mm). WARNING: if you choose 1mm, it
will take a very long time and use lots of disk space. Any smoothing will
be performed in the volume after resampling.

-native

Perform analysis in the native functional space. This also means that
motion correction and registration will use the first time point
of the first run as the target. Any smoothing will be performed 
in this space.

-fwhm FWHMmm

Smooth in the target space by the given full-width/half-max (FWHM). 
If you do not want smoothing, you must still specify 0.

-stc SliceOrder

Perform slice-timing correction using FSLs slicetimer. Options for 
Slice Order are siemens, up, down, odd, even. By default, no
slice timing correction is done.

BASIC DESIGN ARGUMENTS

There are four types of design supported: event-related/blocked, 
retinotopy, abblocked, and notask. 

-event-related

Design is event-related or blocked. You will be required to specify
a paradigm file.

-retinotopy PeriodSec

Design is retinotopy. Specify the period  of stimuluation in seconds 
(NOTE: in previous versions you had to specify the number of
cycles). You will be required to specify a paradigm file.

-abblocked PeriodSec

Design is AB-Blocked (ie, periodic, two condition). Specify the period
of stimuluation in seconds (NOTE: in previous versions you had to
specify the number of cycles). No paradigm file is required.

-notask

Uses only external regressors (either nuisance or task). This can also 
be used to perform seed-based functional connectivity.

-paradigm ParName (Shortcut: -p) 
 
This is the name of the paradigm file as found in each functional run 
directory. For blocked and event-related designs, the paradigm file 
defines which event type was presented when. For periodic designs 
(retinotopy and AB blocked), it defines the phase and period of 
stimulation for each run. The name of the paradigm file must be the 
same across runs and sessions, though its contents can change. 
If event types are redefined (eg, post-hoc event sorting), then a 
new paradigm file (with a different name) should be created followed 
by creating a new analysis. For event and blocked designs, time=0 
is relative to the time of acquisition of the first stored image. 
 
-TR TR 
 
This is the TR in seconds. It will be checked against the TR in each 
session when selxavg3-sess is run. 

Event-related and Blocked Design Options

-nconditions Nc (Shortcut: -nc) 
 
(For blocked and event-related designs). This is the number of 
conditions as found in the paradigm files. When selxavg-sess runs, it 
checks the number of conditions found the paradigm files against Nc 
and returns an error if they differ. 
 
-delay DelaySec

Value to add to stimulus onset times in the paradigm file. 

-fir PreStim TimeWindow 

Use a Finit Impulse Response (FIR) model to model the hemodynamic
response. PreStim is the amount of time (sec) prior to stimulus
onset to start estimation (eg, 4 for 4 sec prior). TimeWindow is
the total time window including any PreStim.

-TER TER

Set the Temporal Estimation Resolution (TER, sec). For FIR, this is
the TR by default. For non-FIR, this is approximately 50ms. It is 
best to know what you are doing if you are going to change this.

-spmhrf nderiv

Assume that the hemodynamic response takes the shape of a the SPM HRF
function (see www.fil.ion.ucl.ac.uk/spm). This is a difference of two
gamma functions which includes an post-stimulus undershoot.

-gammafit gfDelta gfTau 

(For blocked and event-related designs). Assume that the hemodynamic 
response takes the shape of a gamma function. gfDelta is the hemodynamic 
delay (ie, the time until the onset of the response), and gfTau is the 
dispersion, which controls the rise and fall times. Both are specified 
in seconds. gfAlpha is the exponent for the gamma function (see
-gammaexp); for BOLD, alpha=2. The gamma function takes the form:  

         f(t) = ((t-delta)/tau)^alpha * exp(-(t-delta)/tau) 

-gammaexp gfAlpha

Exponent for the gamma function. Default is 2, which tends to fit the 
BOLD hemodynamic response better.

-refeventdur RefEvDuration

Duration of the "reference event" in sec. This is used only for
scaling of the hemodynamic response output. The scale is defined as
the amplitude that results when the assumed shape is convolved with a
boxcar of the duration of the reference event. If you have events of
fixed duration, you should set this to the duration of your event.

-taskreg extregname N

Load N "external regressors" from a file by the name of
extregname. This should be a text file with a row for each time point
and at least N columns.  Use N = -1 to load all. All external task
regressors will be concatenated across run in the design matrix and
will be tested using a t or an F, which ever is appopriate. The
contrast will be named extregname.

NOISE MODELING OPTIONS

-polyfit PolyOrder

Add a set of polynomial regressors upto the given order (default is 2).

-hpf CutoffHz

Use high-pass filtering with the given cutoff in Hz. Implemented as 
a discrete cosine transform. The default is 0 (no filtering). 

-tpexclude tpxfilename 

This is the name of a time point exclude file (TPEF) used for removing
outliers in the time series. The TPEF stores a list of times (in
seconds) of time points to exclude from the analysis. The TPEF must be
found in the run directory with the functional data to which it
applies. Like paradigm files, the TPEFs must have the same name across
subjects and runs though their contents can differ.  Unlike paradigm
files, it is not necessary to have a TPEF in each run; if no TPEF is
found, no time points are excluded.

-nskip N 

Skip the first N time points in each functional run. It may be
necessary to eliminate the first 4 or 5 time points in a functional
run because the sample has not reached magnetic equilibrium. This is
usually not necessary if the sample was scanned with discarded
acquisitions (DISTACQS or DDAs). Note: the nskip does not affect the
definition of time=0 in the paradigm file (see -paradigm). This
functionality can also be implemented using a time-point exclude file.

-nuisreg extregname N

Load N external nuisance regressors from a file by the name of
extregname. This should be a text file with a row for each time point
and at least N columns.  Use N = -1 to load all. All external nuisance
regressors will have separate elements across run and are not tesed.

-mcextreg 

Use motion correction parameters of nuisance regressors. Same as
-nuisreg mcextreg 3. Note that 3 is used because they are
orthogonalized when created.

-nowhiten 

Turn off temporal whitening.

OTHER OPTIONS


-fsd FSD 
 
Functional subdirectory (FSD). This is the folder under the sessions 
directory in which the runs of raw functional data will be found 
(default is bold). 
 
-funcstem stem 
 
This is the bshort/bfloat stem of the functional volume to process. This 
volume must exist in each functional run. By default, the stem is f. 
If the -motioncor flag is included, then the stem fmc is used (this is 
the default output of mc-sess). 
 
-runlistfile filename (Shortcut: -rlf) 

This is a file that should exist in each FSD that lists the runs to be 
processed in that session. The name must be the same across sessions 
but the contents of each file can vary. If an RLF is not specified, 
all runs found in the FSD will be processed. 
 
-acfbins nbins 

Spatially segment the brain into nbins within the mask for the
purposes of computing separate autocorrelation/whitening functions. 
Default is 10. This only affects to selxavg3-sess. Set to 0 to
turn off whitening (or use -no-whiten).

-no-fix-acf

Do not correct the autocorrelation function because of the estimation 
from residuals.
