
Basic retinotopy HOWTO -- Martin Sereno 2015

======================================
1) Update to Latest Csurf
======================================

The latest tarfiles for the UCSD/UCL
retinotopy-enabled csurf are here:

  http://www.cogsci.ucsd.edu/~sereno/.tmp/dist/csurf

On Mac, make sure XQuartz (X11) is installed
(e.g., version 2.7.7).

To update to most recent csurf distribution, open
a Terminal, move aside previous csurf directory
(if any), and download and unpack appropriate
tarfile (which unpacks to just "csurf").  For
example:

  mv csurf csurf-150601
  cd ~
  tar xvfz ~/Downloads/csurf0.8-mac-150922.tgz

Make sure MGH freesurfer (e.g., version 5.3) is
installed and licensed, for example:

  cp ~/csurf/.license /Applications/freesurfer

======================================
2) Setup Paths and Start csurf 
======================================

Decide on default directories for subjects and
sessions (these directories must exist), and tell
csurf where MGH freesurfer is installed.  For
example:

  [csh/tcsh]
  mkdir ~/subjects ~/sessions
  setenv SUBJECTS_DIR ~/subjects
  setenv FUNCTIONALS_DIR ~/sessions
  setenv FSURF_DIR /Applications/freesurfer
      *or*
  [sh/bash]
  mkdir ~/subjects ~/sessions
  export SUBJECTS_DIR=/bigdisk/subjects
  export FUNCTIONALS_DIR=/bigdisk/sessions
  export FSURF_DIR /usr/local/freesurfer

Next, setup your path:

  cd ~/csurf
  source FreeSurferEnv.csh

and finally, start the csurf interface:

  csurf

The 5 setup lines (before "csurf") should be put
into an alias in .cshrc or .bash_profile.  Here
are examples for csh and bash:

[csh/tcsh]
alias fs \
  "setenv FSURF_DIR /Applications/freesurfer; \
   setenv SUBJECTS_DIR ~/subjects; \
   setenv FUNCTIONALS_DIR ~/sessions; \
   pushd ~/csurf; \
   source FreeSurferEnv.csh; \
   popd"

[sh/bash]
alias fs="\
  export FSURF_DIR=/Applications/freesurfer; \
  export SUBJECTS_DIR=~/subjects; \
  export FUNCTIONALS_DIR=~/sessions; \
  pushd ~/csurf; \
  source FreeSurferEnv.sh; \
  popd"

That way, for a new terminal/xterm, you will only
need to type:

  fs
  csurf

======================================
3) Get Structural Scan(s) and Reconstruct Surfaces
======================================

Collect a high-resolution T1-weighted scan or two
(see example scan parameters in Help -> Run
Recon-all).  Convert the scan(s) to nifti or to
AFNI BRIK(s).

  MGHTools -> Run Recon-all

  type new subj name in "new/redo subject"
  <Return> to verify no name overlap
  click FIND for browser to select files
    expand directories in left browser column by double-clk
    select *.nii or *.BRIK file in right browser column
  if more than one scan, do ADD SCAN, FIND again
  click RECON-ALL => wait 8 hours

When done, examine surfaces by selecting the
newly made subject from the "subject:" dropdown,
and clicking SURFACE.

You can look at other data sets for this subject
by clicking one of them from dropdowns (e.g.,
"orig", "T1", "brain" for VOLUME, or "folded",
"inflated" for SURFACE).

Optionally, cut and flatten surfaces:

  MGHTools -> Make Full Surface Cuts
  MGHTools -> Make Occip Surface Cuts

and then:

  MGHTools -> Flatten Surface Patch

For details on how to make cuts, see:

  Help -> Make Relaxation Cuts

======================================
4) Collect Functional Scans
======================================

Mac and linux X11/OpenGL stimulus software,
mapper, for generating these and other stimuli,
can be found here:

  http://www.cogsci.ucsd.edu/~sereno/.tmp/dist/mapper

A typical retinotopy run might have two polar
angle scans and one eccentricity scan.  For
example, multiband accel=4, 2.3mm^3, TR=1, 512
repetitions.  The two polar angle scans should be
counter-clockwise starting at right and
clockwise, starting at right.  The eccentricity
scan should be expanding.

For ease of alignment, you should collect a short
T1-weighted scan collected with the same block
center and block orientation (e.g., 1x1x2mm
MPRAGE) as the functional scans.

Convert the functional scan DICOMs to AFNI BRIKs
(e.g., using AFNI to3d or the csurf to3d-runner
script, ima2brik).

======================================
5) Import Functional Data into csurf
======================================

First, create a new empty Functional scan:

  File -> New Functional

This queries you for subject name (N.B.: must
already be reconstructed).  Name the functional
session so that it sorts chronologically, for
example, year/month/day/initials:

  150901MS

Now import/rename the functional data scans
into csurf using:

  SessionTools -> File Make Scandirs, Find/Copy Raw

This provides a spreadsheet like interface to
specify the raw scan filenames (use FIND), their
(one hopes, more informative) imported filenames,
and how many throw-away TR's to strip from the
beginning of each run.

Make sure to expose the directory containing the
NIFTI's or AFNI BRIK's (raw 3D) scans in the
column at the left of the file chooser.

Take time picking good scandir names (e.g., use
stimulus program script name).  These names will
be what you will see from now on.  As you add
more empty lines, they will be auto-numbered, so
scans sort in order they were performed (auto
numbers can be removed if you insist).  When
first three columns are all filled in, follow
instructions on panel:

  click MAKE SCANDIRS
  click STRIP/COPY-RAW

======================================
6) Align Functional Data with Surface Scan
======================================

Now open first panel in SessionTools:

  SessionTools -> Setup Align/Funct Scans

select the alignment scan (from the list at the
left), and declare it to be one with "Align Scan
Dir" button at the top of the panel, then fill in
panel:

  click READ HEADER
  [verify parmeters auto-filled-in parms]
  click INIT/FLIP to initialize transform

Now start up tkregister to manually/interactively
rotate and translate the alignment scan to bring
it into register with the original scans the
surface was made from using the button:

  ALIGN=>SUBJ

After tkregister comes up, click COMPARE to blink
between TARGET and MOVEABLE, change "fmov:"
(up/down arrows) to make brightness of MOVEABLE
match TARGET, click in troughs of sliders for
TRANSLATE BRAIN and ROTATE BRAIN to get small
movements, and click CORONAL, SAGITTAL, and
HORIZONTAL to change planes (good to do this
often).

Though window can be enlarged (type 1,2,3),
registering is easiest with the smallest window.
For more help:

  Help -> tkregister

When done with the manual alignment, hit SAVE REG
on tkregister (saves 4x4 transformation matrix,
register.dat, to current scandir) and quit the
tkregister application

Now configure all functional scans by selecting
each one in the left column, and declaring it to
be a "Funct Scan Dir" (button at top), and then
click:

  READ HEADER

to fill in the panel (check if correct).

After all scans configured, run AFNI motion
correction (3dvolreg) on the functional scans.
It's best to align all functional scans to a
single target functional scan that was closest in
time to the T1 alignment scan.  For each scan:

  select "Targ:" scan from dropdown (at middle)

When all selected, click the button:

   ALL=>T    (takes a few min)

which aligns every TR from every scan to the
selected TR (right) from the "Targ:" scan.

Now go back to the Align Scan directory and copy
the transformation matrix into all the functional
directories (automatically accounting for the
difference in voxel size) with the button:

  COPY ALIGN TO ALL FUNCTS

You may want to touch up the transformation
matrix using the functional scans themselves
by starting tkregister in one of the functional
scan directories with the button:

  FUNCT=>SUBJ

To propagate that touched-up transformation, you
can use the button:

  CP TO OTHERS

======================================
7) Raw Average of Unreversed+Reversed Scans
======================================

To combine oppositely phase-encoded scans that
start at the same point in a periodic stimulus
(e.g., counter-clockwise and clockwise rotating
wedges that both start at the right), use:

  SessionTools -> Combine 3D Raw Images

First, make a new scandir to contain the average.
Type in an informative name at the top by
appending to the default suggestion, which will
be "image/rawavg".  For example, use at least
something like "image/rawavg-polar".  Then click
the button:

  Make Avg/Concat Dir

Select scans to combine using the "Select to Add:"
dropdown (at middle).  

To time-reverse one or more scans, select one in
"Rev--ScansToCombine" and hit a <Return>.

Timeshift is in TRs, and should estimate time to
hemodynamic delay peak (e.g., 2 or 3).

To average click COMBINE at top right.

======================================
8) Fourier Analysis
======================================

Now, run the Fourier analysis:

  SessionTools -> Calculate 3D Fourier Stats

Default for most panel entries are fine.

  Enter num stimulus cycles (e.g., 8)
  Enter TR (e.g., 2)
  Choose "eccen" or "polar" phase encode type

To run Fourier transforms and calculate
statistics (3D data), click FOURIER.  This
generates a set of BRIKs (viewable with the AFNI
button, top right).

To sample the data to the surface and filter the
stats using surface-based cluster exclusion, use
PAINT.

The parameters controlling the sample-to-surface
process are at the bottom of the panel:

  SessionTools -> Setup Align/Funct Scans

for the corresponding scandir on the "NormSearch
line.  By default, the data is sampled using the
"white" surface with no normal search.  This is
convervative but can miss stronger responses
higher up in the cortical column.

To turn on normal search, select either the "mm"
switch will update the "mn/mx:" fields (min/max
search along surface normal).  The defaults
(adjustable after defaulting) are:

  mm: search 0.0 mm to 2.0 mm in steps of 0.25 mm
  frac: search 0.0-0.8 (1.0=pial) in steps of 0.1

The default operation is "mx" (max complex
amplitude found).

Details of StatFile Outputs, Cluster Exclusion

The FOURIER button runs the program fourier,
which generates 6 different statistical BRIKs:

  ### complex pair: phase angle w/amp stimfreq power
  <stem>_x+orig.BRIK
  <stem>_y+orig.BRIK

  ### complex pair: phase angle w/amp sqrt(F)
  <stem>_r+orig.BRIK
  <stem>_i+orig.BRIK

  ### real-valued F stat
  <stem>_f+orig.BRIK

  ### optional real-valued 3D cluster-filtered F stat
  <stem>_h+orig.BRIK

The Fourier panel parameter:

  "3D  and Surf Clust: PreThre (F/p):"

is the hard statistical threshold before the
cluster filters are applied.  This threshold
applies to both volume (3D) and surface-based
(2D) cluster filters.

The volume (3D) cluster filter is implemented by
AFNI 3dmerge, and is controlled by the paramters:

  "3DCluster: min rad (mm)":
              "min vol (mm^3)":

After 5 of the 3D stats files (_r,_i and _x,_y
and _f) have been sampled to the surface by
PAINT, the PAINT button will then also optionally
run a surface-based 2D cluster filter implemented
by surfclust (runs if following parameter is
bigger than 0.0):

  "SurfCLuster: min area (mm^2)"

Surfclust filters out surface clusters smaller
than this from the already-sampled-to-surface
vertex list wfile:

  <stem>_f-$hemi.w

to generate a second surface file:

  <stem>_h-$hemi.w

See Help -> Cross Session Spherical Average for
details on using the cmdline line program,
randsurfclust, to estimate this parameter.

======================================
9) Optional Fieldsign
======================================

If both polar and eccentricity data are
available, optionally calculate visual field sign
(or find borders where visual field is
duplicated) with:

  SessionTools -> Calc Visual Fieldsign, Borders

Select one polar and one eccentricity scan (these
can be averages) from dropdowns and click
FIELDSIGN and/or GROWBORD (takes much longer).

======================================
10) Render Data on Surface
======================================

Open the rendering panel:

  SessionTools -> View Functional Data

The row of "ResetToDefault:" buttons
will reset the many parameters in this
panel to sane values for several main
types of scans (e.g., "polar", "eccen").

Minimally, you have to:

  select hemi (upper left)
  select surface or patch (dropdowns)
  select stat to view ("Paintfile:" dropdown)
  SURFACE-STATS -> starts tksurfer

Any changes made to the parameters on the
tksurfer panel that opens when SURFACE-STATS is
clicked will *not* be saved.  To save parameters
for next time, enter them on the View Functional
Data panel and click Save or Save/Close.

Stats Files

The data displayed on the surface is typically a
<stem>_<infixletter>-$hemi.w file, which is a
list of values to display at each numbered
surface vertex for one hemisphere.  The file
content type is indicated by the underscore infix
near the end.  Some typical ones are:

  _x  real comp. Fourier transform at stim freq
  _y  [imaginary comp. same]

  _r  as above, but amplitude replaced by sqrt(F)
  _i  [imaginary comp. same]

  _f  F-ratio (not sqrt)
  _h  surface-based cluster-filtered F-ratio

Color Scales for Complex-Valued Data

There are many different color scales.  With
complex valued data, color is usually used to
indicate response phase (angle of complex
vector), not response amplitude.  Response
amplitude (length of complex vector) is indicated
by color saturation, which fades into the
background gray below the set threshold.

The two main thresholding parameters that control
the saturation are "fthresh:" (hard cutoff if
amplitude at vertex is below entry), and "fmid:"
(soft cutoff, same units).  For fourier-analyzed
data, the amplitude will be the complex
amplitude.  The "fslope:" entry controls the
sharpness of the "fmid:" threshold.

Optional Stat Mask

If a real-valued statistical mask has also been
read in (e.g., _f or _h infix), and "mask" is
ticked, it can secondarily be used to modulate
color saturation.  In this case, the "fthresh:",
"fmid:" and "fslope:" entries will each be
replaced by a pair of entries.

The first (leftmost) entry of each set controls
color saturation using the amplitude as before.
The second (rightmost) entry is a second control
on color saturation.  If the *statistic* at this
vertex is below the setting in the entry, the
color saturation will roll off to background.

Surface Smoothing

Data and stats can be smoothed on the surface
with the SMOOTH button (lower left).  10 steps of
surface smoothing is very nearly identical to
convolution with a 3 mm full-width half maximum
Gaussian.

When smoothing stats, it is advantageous to use
the stat mask plus complex data rather than only
the complex data with 'built-in' statistic (i.e.,
_r,_i, which has complex amplitude substituted by
sqrt(F)).  This is because phase differences in
the _r,_i vectors for nearby vertices will cause
the 'built-in' significance to be reduced more
quickly during complex-valued vector smoothing
than will smoothing of the *real-valued* _f mask.

======================================
11) Render Retinotopy Data in the Volume
======================================

Retinotopy responses/stats calcuated by the
fourier program in 3D at the functional image
resolution can also be *viewed* in 3D, using many
of the same phase color scales available for the
surface display:

  SessionTools -> View Functional Data
  VOLUME-STATS -> starts tkmedit in overlay mode

The high-resolution structural underlay is the
"orig" data set (typically 1x1x1 mm).  The lower
resolution funct/stat data is registered and
upsampled to structural resolution on the fly
using register.dat.  The matrix in register.dat
transforms 3D vertex or hi-res structural
coordinates to funct/stat voxel indices.

There are three different classes of 3D overlay
files:

  val -- real or complex values (e.g., _r,_i or _x,_y)
  msk -- real-valued statistical mask (e.g., _f,_h)
  roi -- binary label (tkmedit FILL, tksurfer conv label)

The bold labels of the three entry dropdowns
in the middle of the tkmedit panel (val, msk,
roi) can be toggled between two states:

  "valn:"  <==>  "valup:"
  "mskn:"  <==>  "mskup:"
  "roin:"  <==>  "roiup:"

The "n" suffix means "native" (i.e., original
functional resolution), while the "up" suffix
means "upsampled" (upsampled to structural
resolution).

In the "native" state (valn, mskn, roin), the "R"
button on the line will read, register, and
upsample the file to structural resolution.  In
the "upsample" state (valup, mskup, roiup), the
already upsampled file is merely read.  The "W"
button (only available in the "upsample" state)
allows writing the upsampled file for later use.

The "val" line "R" buttons will automatically
attempt to read the other member of a pair of
complex data sets (e.g., _r,_i or _x,_y).

View (complex) Values Directly

The value files can be viewed directly and
thresholded by (complex) amplitude using
"fthresh" and "fmid" ("fslope" controls the
sharpness of the soft threshold, fmid).  As on
the surface, hue is used to indicate phase, while
color saturation indicates amplitude.

Statistical Mask

A separate statistical mask can be read in (e.g.,
<stem>_f+orig.BRIK) using "R" on the "msk" line
and used to independently modulate the
saturation.

To toggle the effect of the mask, use the
unmarked tickbox at the left of the "msk" line.
When the mask is engaged, there will be two
entries each for fthresh, fmid, and fslope; the
first is in value units (e.g., complex amplitude
of sqrt(F) for _r,_i files) and the second is in
statistic units (e.g., F-ratio for _f files).

3D Gaussian Smoothing

When smoothing (SMOOTH STATS button), it is
advantageous to use a real-valued statistical
mask instead of directly vector-smoothing the
complex-valued data because local phase
differences in the first case will cause
significance to reduce more rapidly.

ROI labels

A third kind of 3D file is an ROI label, which is
conceptually parallel to a surface label.  An
upsampled ROI can be generated by using the
tkmedit FILL button to fill regions in 3D up to a
threshold specified by "fthresh" and optionally
subject to a maximum radius specified by the
entry next to FILL (if that number is bigger than
0.0).

A native resolution ROI can also be generated
from a surface label (see help for tksurfer
"label:" line "D" button).

To toggle the visibility of an ROI label as a
white overlay, use the "roi" tickbox above the
FILL button.  To toggle the effect of the same
ROI label as a mask on the overlay data (data
only shown where ROI label is 1), use the
adjoining "m" tickbox instead.

======================================
12) Batch Redo
======================================

If you redo your registration done back at the
beginning, you need to re-paint and re-render
everything.  If you want to redo your
registration and then re-paint and re-render,
run:

  SessionTools -> Run Batch Process

select Run All Paint Surfaces and Run All
Rendering Panels, and hit Start.  This will open
all the panels of currently configured scans (as
configured when you hit Save or Save/Close for
each panel), run the PAINT button in each one,
and then run the SURFACE-STATS button in each
one.

In addition, it will save bitmaps for any folded
or flat views you have configured on View
Functional Data panels.

======================================
13) More Help
======================================

The Help -> ... menu items have more detailed
information for all the extra panels. You can
never leave too many ASCII notes in:

  File -> Open Subject NOTES
    (in $subject/scripts/NOTES)

  File -> Open Functional NOTES
    (in $session/image/scripts/NOTES)

Most buttons and entries and tickboxes in csurf,
tksurface, tkmedit, and tkregister have pop up
help on right-click (over 300 pop-up panels).
