---------------------------------------------
 The CrossSessTools -> Cross Sess Spherical Avg
 menu creates cross-session, cross-subject
 complex- or real-valued averages and stats using
 spherical morph surfaces.  Can also perform
 *volume* avg/stats on complex-valued data.
---------------------------------------------
Before running these commands, use File -> New
Spherical Avg to create a new empty cross-session
session.

The SPHEREAVG button samples complex-valued data
(real and imaginary) from each individual
subject's morphed sphere ($hemi.sphere.reg) to
the canonical icosahedral sphere (7th icosahedral
sub-tessellation) surface.  It then averages the
components in this common coordinate system and
calculates a dispersion index.  Finally, it
calculates a (scalar) cross-subject F-ratio from
the complex data.

The AVGSURF button generates an fsaverage-like
average surface from the current set of subjects.
This button can be skipped if you only intend to
display average data back on individual subjects,
or the standard MGH average surface, fsaverage.

The SAMP2SUBJ button resamples all the cross-subj
average data back onto an individual subject's
morphed sphere (sphere.reg, which allows that
data to be displayed on any of that subject's
surfaces).  The sample-back display subject can
also be set to "fsaverage" (the MGH average
surface), or to an average of the current
subjects make with AVGSURF.

The SAMP2SUBJ button also runs a surface-based
cluster exclusion mask to correct for multiple
comparisons (see description of "F:" and "mm^2:"
fields below).

It can also average and sample-back
single-component (real-valued) data.  In this
case, the only output is the mean and tstat.

The VOLAVG button averages Fourier-analyzed
upsampled stat BRIK's and calculates the
cross-subject F-ratio from the complex data (same
calculation as above).  This requires that (1)
each subject has been first hand-aligned to the
same single structural underlay target, and (2)
registered upsampled real and imaginary stat
BRIKs have been written out using tkmedit (see
below).

This provides a low-level-controllable method of
obtaining complex-valued averages for visualizing
small maps in subcortical structures from high
resolution data (e.g., pulvinar).


--------------------------------------------------
SPHEREAVG -- complex-valued surface avg/stats
--------------------------------------------------
Spherical surface averages (or volume averages)
are performed within a scandir (e.g., "polar12")
inside a session dir (e.g., "130325XS-pol").

Create Average Scandir

Decide upon an informative scandir name, enter it
at the top of the panel, and click Make SphereAvg
Dir to create it.  Currently, there can only be
one cross-session scandir per cross-average
session (don't use "image/prf").

Select data to average

Click the ADD SESS button one or more times to
create blank session configuration lines.  The
DEL LAST button deletes the most recently added
line, whether or not you have altered it.

Then on each line, select Session, Scandir, and
VtListPref in that order from the dropdowns to
select the files to average.  Complex-valued
files typically have _r and _i infixes, which
won't be visible in the dropdown, but which will
be used.

To average single-component, real-valued data
instead, select phasetype "w" at the far right
(instead of the complex-valued ecc/pol/2cn
options).  In this case, only the .w suffix will
be stripped (if this directory contains complex
valued data, the _r and _i infixes of each wfile
will now be visible).

If phasetype is changed to "w" or from "w" in the
middle of configuring the panel, re-select each
Scandir and VtxListPref dropdown to make sure
that valid file choices are shown (single and
double-component data can't be averaged within
one panel).

Normally, each scan to average should be
the same kind of scan (though they may all
have different names).  There is currently no
procedure for reversing the phase (e.g., for
counter-clockwise scans versus clockwise scans),
so the phase direction should be the same for
all subjects (any reversed phase scans should
be first averaged within subjects using one of
the following:

  SessionTools -> Combine 3D Phase Stats
  SessionTools -> Combine Surface Stats

Adjustable parms -- Hemispheres ("hemi:")

First select the hemisphere(s) on which to
operate (right, left or both).  This choice is
saved after the average runs to completion.

Adjustable parms -- Smooth Steps ("smooth2ico:")

This is the number of smoothing steps during the
initial morphed-sphere to icosahedral-sphere
sampling.  The default is 1.  This smoothing is
done *after* resampling (on the isocohedral
surface: -nsmooth-out as opposed to -nsmooth-in).

There is no smoothing on the way back to a single
subject (SAMP2SUBJ) (that is, no additional
smoothing beyond that implied by nearest neighbor
resampling -- see next).  The data can be further
smoothed interactively during display on the
individual subject surface.

Adjustable parms -- Sample Method ("nnfr/nnf")

To sample data onto the target surface, for each
target vertex, the closest vertex in the source
surface is found (this is the forward map).  If
the sample method is set to "nnf" (nearest
neighbor, forward), the sampling is now done.
This, however, can leave some source vertices
unrepresented in target (i.e., 'holes').

If "nnfr" (nearest neighbor, forward and reverse)
is chosen, then each hole is assigned to the
closest target vertex. If a target vertex has
multiple source vertices, then the source values
are averaged together.

The default sampling method is "nnfr".  This
applies in both directions (individual subject ->
icosahedral, and icosadedral average -> display
subject).  This choice does not make much
difference for standard fMRI data.

Adjustable parms -- Phasetype/Colscale

Finally, select the phasetype ("ecc/pol/2cn") at
the far right.  This presets the correct color
scale in the View SphereAvg Data panel ("2cn"
refers to two condition data analyzed by fourier
methods).

If the last option, "w" is selected, all of the
*.w files in the current scandir are shown in
the VtxListPref dropdowns.  This contrasts with
the default situation (ecc/pol/2cn selected)
where only complex-valued data files are shown,
and only one entry is shown per pair of files
(i.e., the the _r and _i infixes are stripped).
Select this option to average single-component
real-valued data.

Adjustable parameters -- t-test comparison value

Numerical value that the sample mean will be
tested/compared against with a 1-sample t-test
("tcp").  The sample mean is typically the
complex amplitude:

  _a = hypot(_r,_i)

which is usually the sqrt() of the single subject
F-ratio.  The default "tcp" value is 0.0

Run Sphere Average

Once every empty scan line is configured, click
SPHEREAVG at the top right to sample each
subject's data onto the spherical (7th
icosahedral sub-tessellation) surface, average it
(complex valued vector average), and calculate
cross-subject (2nd level) statistics.

All the fields on each configured line have to be
filled in before SPHEREAVG will run.  The subject
field can't be edited (it is looked up from what
is found in each $session/image/name file).  The
morphed surface can't be edited either, so the
surfaces $hemi.sphere.reg must exist for every
subject (first run SubjectTools -> Register
Surface for each subject).  The existence of the
8 potential input files for each line are
rechecked (in case they have changed after the
last panel configure):

  $prefix-vreg+orig{_r,_i,_x,_y}-{rh,lh}.w

These include the left and right hemisphere files
for raw real and imaginary Fourier coefficients
at the stimulus frequency (filename infixes: _r,
_i), and the left and right hemisphere files for
the real and imaginary components of complex
significance signal at the stimulus frequency
(filename infixes: _x, _y; phase is same as raw
Fourier coefficients, but amplitude is
sqrt of F-ratio).

If a file is missing, go back to the
Calculate/Paint Fourier Statistics panel and run
FOURIER and PAINT for that scan.

If everything is there, a progress window pops
up, noting when the processing for each input
file has been completed.  The progress window is
reset during each of the 3 passes through the
data described below.

The first pass samples data for each subject onto
the icosahedral spherical coordinate system using
the sphere.reg surface of each subject and
reformats it as a pseudo-image for later
calculations using AFNI utilities.

The second pass calculates component-wise,
cross-subject averages (vector averages) of the
complex-valued data (_r,_i and _x,_y).  It also
calculates a dispersion index (using the _r,_i
data), which is saved as left and right
hemisphere wfiles (paintfiles) with the infix
"_d".  This index is:

          amplitude of vector average
d  =   ----------------------------------
       average amplitude of indiv vectors

This index is 1.0 in the limit of perfectly
aligned vectors, independent of their amplitude
(the _d file is not generated for real-only
data).  It can distinguish a vector average that
was generated by a set of large but inconsistent
signals (lower d) from a same-sized vector
average that was generated by a set of smaller
but more consistent signals (higher d).

The third pass through the data calculates a
cross-subject F-ratio based on the complex
coefficients at the stimulus frequency from each
subject (infixes: _x,_y).

The calculation of the complex F is as follows:

            [xav^2 + yav^2]/2
 ------------------------------------------------
 [Sum(_x-xav)^2)/n + Sum(_y-yav)^2/n] / [2*n-2]

where _x and _y are the raw Fourier coefficients
at the stimulus frequency, xav and yav are the
average of them, and n is the number of subjects.
This is described and demonstrated in Hagler,
Riecke, and Sereno (2007).

Here is an F table for DF-numerator=2 (real,
imaginary) for p<0.05 and p<0.01 with different
DF-denominators (subjects):

	F for	F for
 df	p<0.05	p<0.01
------------------------------
 3	9.55	30.82
 4	6.94	18.00
 5	5.79	13.27
 6	5.14	10.93
 7	4.74	9.55
 8	4.46	8.65
 9	4.26	8.02
 10	4.10	7.56
 11	3.98	7.21
 12	3.89	6.93
 13	3.81	6.70
 14	3.74	6.52
 15	3.68	6.36
 16	3.63	6.23
 17	3.59	6.11
 18	3.56	6.01
 19	3.52	5.93
 20	3.49	5.85
------------------------------

The third pass also calculates a cross-subject
p-value for the null hypothesis that the cross
subject distribution of phases is a uniform
circular distribution, using a Rayleigh test.

The per-vertex calculation of the Rayleigh p from
the Rayleigh R is as follows:

  p = exp(sqrt(1 + 4*n + 4*(n^2-R^2)) - (1+2n))

where R is n times the complex amplitude of the
vector average of the normalized phase angle for
each subject (r/a, i/a).

For convenience, the p value is converted to
-log10(p) so that fthresh is in units of positive
p exponents (i.e., fthresh=2 means p >= 10^-2).

Interrupt

Clicking the purple QuitSPHER button once will
interrupt the process.  This will take a moment,
since the processing (sampling, averaging, format
conversion) for the current file will continue
until it is complete.

Here is a schematic overview of the commands
that are run by SPHEREAVG (minus all the error
checking):

  ## pass1: for each member of average
  foreach subject/hemisphere/_r,_i,_x,_y
    mri_surf2surf -- sample wfile to ico bfloat
    bresize   -- wrap 1D ico bfloat to '2D'
    to3d      -- convert pseudo 2D to BRIK
    3dcalc    -- calc subj-wise sig ampl, _a

  ## pass2: mean-sigF/tstat-sigF/dispersion
  3dttest     -- xsubj avg,ttest (_x,_y,_r,_i,_a)
  3dcalc      -- calculate dispersion index, _d
  brik2bfloat -- conv to folded bfloats
  bresize     -- unfold bfloats

  ## pass3: cmplx-F (_x,_y)(_r,_i), Ray-p (_r,_i)
  3dcalc      -- calculate numerator
  foreach (subject,hemisphere,real/imaginary)
    3dcalc    -- add sq resids to running tots
    3dcalc    -- add normalized _r,_i to run tots
  3dcalc      -- calc complex cross subj F-rat
  brik2bfloat -- conv to folded bfloat
  bresize     -- unfold bfloat
  3dcalc      -- calc Rayleigh p value
  brik2bfloat -- conv to folded bfloat
  bresize     -- unfold bfloat

To see the detailed arguments to and verbose
output of each of these programs, click the
SPHEREAVG button, let if finish, quit csurf, and
then look in the csurf.log file (which is
generated in the current session scripts dir on
quitting).

Output files

The vertex-wise output files (paintfiles, wfiles)
for a SphereAvg directory named "avg", for one
hemisphere, are as follows:

  ### cross-subject means
  avg-mean-sph-sm1_r-lh.w  (sqrtF real)
  avg-mean-sph-sm1_i-lh.w  (sqrtF imag)
  avg-mean-sph-sm1_a-lh.w  (amplitude _r,_i)
  avg-mean-sph-sm1_x-lh.w  (raw Fourier real)
  avg-mean-sph-sm1_y-lh.w  (raw Fourier imag

  ### cross-subject 1-samp t-stat vs. tcp
  avg-tstat-sph-sm1_a-lh.w

  ### cross-subject complex F-stat (Hagler)
  avg-stat-sph-sm1_g-lh.w  (from _r,_i)
  avg-stat-sph-sm1_f-lh.w  (from _x,_y)

  ### cross-subject Rayleigh pos p-exponent
  avg-stat-sph-sm1_e-lh.w  (from _r,_i)

  ### cross subject dispersion
  avg-stat-sph-sm1_d-lh.w

  ### cross subject t (phasetype="w")
  avg-tstat-sph-sm1-rh.w  (no _infix)


--------------------------------------------------
AVGSURF -- Make Average Surf from Current Subjects
--------------------------------------------------

Click AVGSURF to make an average surface for the
current set of subjects analogous to the
fsaverage surface.  This uses Doug Greve's
script, make_average_subject, from standard MGH
freesurfer, and requires that the environment
variable FSURF_DIR is pointing to a separate full
MGH freesurfer installation when csurf starts.

The first step is to pick a new name for the
average surface subject directory, which (1) must
not yet exist (e.g., fsavg-polar1), and (2) must
be in the same SUBJECTS_DIR that contains the
individual subjects.

When AVGSURF finishes, it will offer to reset the
display subject (used by SAMP2SUBJ) to the
newly-made average surface.  Run time is about 3
min per subject.

After finishing the average, small regions
containing giant triangles in the north and south
'poles' of the inflated_avg surface will be
auto-fixed.  This step uses the following label
files:

 $CSURF_DIR/fsaverage-ADDITIONS/label/rh-FIX-POLES.label
 $CSURF_DIR/fsaverage-ADDITIONS/label/lh-FIX-POLES.label

The same operation can be performed on a surface
average generated outside of csurf using the
csurf shell script:

  fixinflatedavg <average_subject>

Surface Areas of Different Average Surfaces

The idiosyncratic pattern of secondary folding in
different brains means that any average of folded
surfaces (e.g., fsaverage $hemi.orig) will have a
simpler folding pattern than any of the
individual subject surfaces that went into it.
This in turn means that the surface area of the
average surface will be less than than the
surface area of any individual surface (about 1/3
less).  An area-preserving inflation of the
average surface will be similar, which explains
why the width and height of fsaverage
$hemi.inflated is smaller than any individual
inflated surface.

One way to avoid this loss of area in an average
surface is to construct it from individually
already-inflated surfaces.  For cross-subject
averages computed on the morphed sphere
(CrossSessTools), the average of the inflated
surfaces ($hemi.inflated_avg) is the preferred
display subject, since absolute measures of area
on it will much more closely resemble
measurements on an individual brain.

For analyses in which 3D data has been combined
across subjects before being sampled onto the
2/3-of-full-area fsaverage folded surface, it
makes more sense to use corresponding shrunken
inflated surface ($hemi.inflated) for display.
In general, that analysis procedure -- though
simpler to adapt to existing 3D processing
pipelines -- generates inferior results to a
thoroughgoing surface-based average approach,
where individual subject statistics are sampled
to each individual's surface, and then to the
morphed sphere before averaging across subjects
(as implemented here).


--------------------------------------------------
SAMP2SUBJ -- Sample to Single Subject Surface
--------------------------------------------------
To sample the average and dispersion index onto
the surfaces of a single subject and write out
the result as a displayable wfile, click
SAMP2SUBJ. To change the display subject, select
a different subject from the "display subject"
dropdown.  This will edit the name file for the
current cross session average scandir.

The display subject can be "fsaverage" (or any
other subject, including subjects not in
average).

The SAMP2SUBJ button also runs a surface-based
cluster exclusion filter (Hagler, Saygin, and
Sereno, 2006, Neuroimage 33:1093-1103) on the
cross-subject _f file (after it has been sampled
back to a display surface) to correct for
multiple comparisons (binary: surfclust).

Taking the left hemisphere as an example, the
vertex list input file (_f infix):

  avg-stat-sph-sm1_f-lh.w    (orig cross-sub F)

is filtered and using the display subject surface
to generate an output file (_h infix):

  avg-stat-sph-sm1_h-lh.w  (cluster-filtered _f)

The cluster filter is also applied to cross
subject t-stats from real-valued data if they
have been generated with phasetype "w"

N.B.: an input t-stats wfile without an
underscore infix (e.g., avg-tstat-sph-sm1-rh.w)
generates a cluster filtered file with the same
_h infix (e.g., avg-tstat-sph-sm1_h-rh.w).

The two parameters controlling the cluster filter
are located at the extreme right near the top of
the panel -- "F:" and "mm^2:".  The value in "F:"
sets the pre-cluster stat threshold (actually t
for real-valued phasetype="w" stats).  Use an F
table (see above) to determine the F value to
enter for the desired p-value (e.g., 0.01).  The
minimum area of the surface-based cluster passed
by the filter is set by the value in "mm^2:"

To determine the proper surface area to enter
based on pre-cluster threshold, smoothing, and
desired corrected prob value, run randsurfclust
on the command line:

 Usage: randsurfclust -subj name [options]

  Required parameter:
    -subj <name>		(can be ico)

  Optional parameters:
    -hemi <rh,lh>		default is rh
    -surf <suff>		for area calc (smoothwm)
    -niter <num>		iterations (100)
    -pval <val>		prob value (0.001)
    -smooth <num>		smoothing steps (10)
    -alpha <val>		corrected prob value (0.05)
    -egfw		est. gauss filterwidth (no)
    -quiet		suppress messages

For -pval, use the p-value for the uncorrected
hard threshold.  For -alpha, use the desired
corrected p-value.  If there is an error
complaining about not enough iterations, increase
-niter from the default 100.

To view and mask the average data, and to save
bitmaps, use CrossSessTools -> View SphereAvg
Data, which brings up a copy of the SessionTools
-> View Functional Data, and which has an almost
identical layout and function to it.


--------------------------------------------------
VOLAVG -- complex-valued volume avg/stats
--------------------------------------------------
This 'manual Talairach' procedure is designed
only for focal averages of brainstem retinotopy
data (not cortical retinotopy data, which is
better analyzed on the surface).

There is currently no facility in VOLAVG for
reversing phase, so all analyzed scans must have
the same phase order (i.e., all counter-clockwise
pol1 *or* all clockwise pol2).  A scan can be
reversed by using SessionTools -> Combine 3D Raw
Images (this works even on a single scan).

Before proceding, first make a copy of each of
the single-subject session intended for the
average so the initial native analyses and
register.dat files are not overwritten using:

  File -> Copy Functional

Then, for each subject, hand-register the
functional data to a single structural underlay.
To do this replace the native subjectdir name in
this file:

  $FUNCTIONALS_DIR/$session/image/name

with the name of the single target subject (e.g.,
one of the subjects in the average) using:

  Preferences -> Change Subj for Curr Session

Note that is is considerably easier to manually
align small brainstem structures with a single
subject target than it is to align them with an
average (blurry) target.

Opening the functional scandir in tkregister
using SessionTools -> Setup Align/Funct ->
FUNCT=>SUBJ now allows you to align this
subject's functional data with the target subject
structural scan (the underlay subject).  This
'manual Talaiarching' may require scaling in
addition to rotation and translation.

Next, display the complex-valued re-registered
data using SessionTools -> View Functional Data
-> VOLUME-STATS.  This reads the 3D native
resolution Fourier stats (by default, the _r,_i
pair) and upsamples them to the resolution of the
structural.

By default the surface Paintfile for retinotopic
data will be the _r/_i pair of sqrt(F) stats.
This will load the corresponding 3D native
resolution stat files and upsample them.  Smooth
these to taste with tkmedit SMOOTH STATS.

Then write out the upsampled complex-valued files
for averaging.  To write out the first pair,
click the tkmedit "valn:" entry label ("n" stands
for native resolution) and it will change to
"valup:" ("up" stands for upsampled).  Write out
the pair of upsampled stat BRIKs using the "W"
button to the right of the tkmedit "val:" entry.
The name in the entry is auto-generated but can
be changed as long as it ends in "_r+orig.BRIK".

To write out the second pair, click "valup:" to
toggle back to the "valn:" and read in and auto
upsample the native raw Fourier amplitude files
(_x,_y infixes).   Smooth these the same way and
then write them out by clicking "valn:" again to
go back to "valup:" and click "W".  The name in
the entry is auto-generated by can be changed as
long as it ends in "_x+orig.BRIK".

Finally, create and setup a cross session panel
with:

  File -> New Spherical Avg
  CrossSessTools -> Cross Sess SphereAvg

For each new line created with ADD SESS, select
Session, Scandir, and StatBrikStem in that order
from the dropdowns to select the files to
average.  Complex-valued files typically have _x
and _y infixes, which won't be visible in the
dropdown, but which will be used (the VtxListPref
and MorphSurf columns are ignored).

Now, click the VOLAVG button at the upper right.
This generates the following files for a
SphereAvg directory named "avg":

  ### 2-BRIK volumes: avg, t-stat
  avg-stats-vol_r+orig.BRIK
  avg-stats-vol_i+orig.BRIK
  avg-stats-vol_x+orig.BRIK
  avg-stats-vol_y+orig.BRIK

  ### 1-BRIK volume: complex-F
  avg-stat-vol_f+orig.BRIK

Here are the commands run by VOLAVG (minus error
checking):

  ## pass1: mean/tstat
  3dttest     -- xsubj 3D avg,ttest (_x,_y,_r,_i)

  ## pass2: cmplx-F from (_x,_y)
  3dcalc      -- calculate numerator
  foreach (subject,real/imaginary)
    3dcalc      -- add sq resids to running tots
  3dcalc      -- calc complex cross subj F-rat

The first pass can also be performed on
real-valued (no infix) stat files.  In that case,
the second pass is skipped.

Finally, view results in tkmedit with
CrossSessTools -> View SphereAvg Data ->
VOLUME-STATS.  This should automatically read in
complex-valued overlay files with names like
$stem-stat-vol{_x,_y}+orig.BRIK as well as the
appropriate statistical mask file.
