-------------------------------------------
 The SessionsTools -> Calculate 3D Fourier Stats
 sets up and calculates Fourier-based statistics
 on 3D volume data sets
-------------------------------------------
When FOURIER is clicked, the program "fourier"
runs FFT's on the time course at each 3D voxel,
and then calculates phase and significance of the
periodic activation.  When PAINT is clicked, the
3D data is sampled to the surface using the
current register.dat and sampling distance (from
Setup Align/Funct panel).

This panel normally remains "Unset" for a pseudo
scan directory that contains statistics generated
by averaging statistics across multiple scans
with Combine 3D Phase Statistics (there is no raw
time series data in such a dir).

The Image Name Format

This is automatically entered from the Setup
Functional panel.  To refresh this field, go back
to the corresponding Setup Functional Scan
Parameters scandir, re-select the correct Image
File, and click READ HEADER.

Stimulus Program Notes

An arbitrary length string of ASCII characters
(can include carriage returns) for informational
purposes.

"cp prev" Button

This button copies parameter values from the
previously selected scandir (left column) into
the current scandir.  All parameter values from
"Stim Cycles per Scan" and below are copied.

Stim Cycles Per Scan

This is the most important parameter on the
panel.  To analyze a polar angle mapping stimulus
(rotating wedge) with 8 cycles, enter 8.  You
would also enter 8 if there were 8 ON blocks and
8 OFF blocks.  This number does *not* have to be
a power of two, but it *does* have to be an
integer.

Use Slice Timing

The "UseSliceOrd" and "UseTAXIS" ticks turn on
alternate methods for correcting the fourier
domain output phase of voxels in individual
slices.

If "UseSliceOrd" is clicked (-slicetiming option
for the "fourier" program), the "Slice Ord:"
buttons are used specify the slice order.  This
method does NOT work for multiband > 1.

If "UseTAXIS" is clicked (-taxisoffsets option
for the "fourier" program), slice-by-slice time
offsets from "Slice Time Offsets List" (in the
Setup Functional Scans Parameters panel) will be
used for the correction.

If either method is used, be sure to verify that
the slice order specification matches reality.
The effects of this correction are quite subtle
for standard short-TR multiband acquisitions.

Since the slice time corrections (for non-sparse
scans) will, on average, retard the output phase
by 1/2 the duration of TR, after the corrections
are applied, all phases are advanced by the same
amount (TR/2).  This allows direct blink
comparison between corrected and uncorrected
scans.

TR

The TR must be entered, but it is only used by
the optional slice timing correction.

Pre-Smoothing Steps

3D spatial smoothing can be applied to AFNI raw
time series data sets before calculating Fourier
statistics (uses AFNI 3dmerge).  The default is
no smoothing (=0.0).  Use gingerly since this is
3D smoothing.  It is *much* more effective to
instead smooth the complex statistics in 2D on
the surface (e.g., 20 steps ~= 4 mm FWHM 2D
kernel) than it is to smooth the raw data with a
similar sized 4 mm FWHM *3D* kernel before
calculating the phase of the response.

Low-Freq Cutoff (cyc/scan)

Frequencies below this cutoff (default: 3 cycles
per scan) are ignored for when calculating
signal-to-noise as the ratio of amplitude at the
stimulus frequency to amplitudes of other (noise)
frequencies.  Very low frequencies are dominated
by movement artifacts, and this procedure is
similar to regressing out signals correlated with
movement (N.B. the "fourier" program removes the
linear term from the time series *before*
calculating the FT).

Hi-Freq Cutoff

Frequencies above this cutoff are ignored in the
same way as just described.  In this case, the
default value is -1, which is a flag to allow
noise frequencies up to the Nyguist limit (1/2
the sampling rate) -- that is, no high frequency
cutoff.

Omit Freq

Frequency (cycles per scan) of an additional
periodic nuisance signal to discard when
calculating signal-to-noise.  Typically, this is
used to ignore a periodic activation due to a
regularly performed task during a phase-encoded
mapping experiment (e.g., a periodic auditory
cue).  The default value is -1, which is to
disable this option.

Permute Test Count (0=off)

If the number in this entry is bigger than zero,
a permutation test is used to directly estimate
the p-value of the F-ratio.

This test permutes the labels of the frequencies
in the fourier transform of the timecourse and
recalculates F the requested number of times.

The estimated p-value is the fraction of times
that permuted frequencies result in an F-ratio
larger than the non-frequency-permuted F-ratio
calculation.

This test is computationally expensive (see
Preferences -> View/Hide Logs for progress and
elapsed time).  It is written multi-threaded so
it will run faster with more cores.   The minimum
number of permutations for reasonable results is
about 1000 (maximum possible significance
p=0.001) but 5000 is best (about about 30 min
computation on 4 cores).

Since this test generates p-values directly, if
you enter a number of permutations and hit
<Return> the "Phase Stat Type" (see below) will
be changed to "p-val" (from default "sqrt-F").
The resulting complex-valued output statfiles
(infixes: _r,_i) will contain vectors whose
length is -log10(p) and whose phase is the phase
of the signal at the stimulation frequency.
Thus, the units of fthresh and fmid will be
-log10(p), for example (with 256 or 512 TRs):

   fthresh/fmid=1.3  => p < 0.05
   fthresh/fmid=2.0  => p < 0.01
   fthresh/fmid=3.0  => p < 0.001

The p-value (in the form of -log10(p)) is also
written out directly into a BRIK with a _p infix.

If no smoothing is done at surface render time, a
hard amplitude threshold ($fthresh, single or
leftmost threshold entry) on the _r,_i files will
be equivalent to a hard stats threshold
($sfthresh, rightmost threshold entry) on the
_r,_i files using _p file as a mask (with a
permissive $fthresh).

However, if surface smoothing has been done at
render time, the results of those two procedures
will differ since complex-valued smoothing of the
_r,_i values will reduce the complex amplitude as
a function of the phase dispersion of adjacent
vertices.  Smoothing the real-valued _p file
ignores phase and results in no amplitude
reduction from phase dispersion (preferred).

3D/Surf Cluster: PreThr (F/p)

The "PreThr" parameter sets the hard,
pre-clustering threshold for *both* the 2D
surface-based (surfclust) cluster exclusion
filter as well as the 3D (AFNI 3dmerge) cluster
exclusion filters.  Note, however, that the final
output of 3D and surface-based clustering will
differ (see below).

The units of PreThr are usually F, but may also
be -log10(p) in the case where a permutation test
has been run.  Use an F table (see table at end
of Help -> View Functional Data) to determine the
F value to enter for the desired p-value (e.g.,
0.05), or enter -log10(p) directly if permutation
test.  This parameter is passed as:

  surfclust ... -thresh <prethr> ...
  3dmerge ... -1clip <prethr> ...

3DClust (units=vox):  connected=___  and minvol=___

After FOURIER has generated the 3D _r,_i BRIK's
(phase w/sqrt F inserted as amplitude), and the
_x,_y BRIK's (phase w/raw Fourier amplitude at
stimulus frequency), and _f BRIK (F calculated
from stimulus frequency vs.  noise frequencies),
the F-stats BRIK is run through a 3D cluster
filter using AFNI 3dmerge for cluster-filtered
statistical masking (e.g., for maps in brainstem
structures.

These two parameters control the minumum cluster
size for the separate 3D cluster filter output
(BRIK with a _h infix).  These parameters are
passed as:

  3dmerge ... -dxyz=1 -1clust_order <connectdist> <minvol> ...

The first option means that units are one voxel
width and one voxel volume (*not* mm and mm^3).
The first argument to -1clust_order is the
minimum Euclidean distance between voxels for
them to be considered to be in the same cluster
during region growing (units are one voxel
width).  For standard region growing with no gaps
during cluster growth, use 1 (meaning the
distance of one voxel width).  To allow voxels
that separated by one subthreshold voxel to be
added to the same cluster, use 2, and so on.

The second parameter clips off clusters that are
below this volume (units are one voxel volume,
*not* mm^3).  For example, using the default of
40 with 3x3x3 mm voxels results in a minimum
cluster volume of 1080 mm^3 (about 1 cm^3).

Note that the parameters have opposite polarity:
increasing the first makes the filter *less*
stringent while increasing the second makes it
*more* stringent.

The -1clust_order option (in the family of
-1clust options, where -1clust is the basic
option to just clip) numbers the clusters in
order of size.

N.B.: 3D, Surface-Based Clusters NOT the Same!

The *output* of the 3D cluster filter is ignored
during the independently calculated surface-based
clustering (see next), and in general, the
results will be somewhat different, This can be
seen if 3D clustered stats from the _h BRIK are
sampled to the surface, or surface-clustered
stats from _h vertex list files (wfiles) are
mapped back to 3D voxels.

SurfCluster: min area (mm^2)

When PAINT is clicked, after the five 3D data
sets (with infixes: _r,_i and _x,_y and _f), have
been resampled to the surfaces of each
hemisphere, a surface-based cluster filter is run
on the surface-sampled F-statistic using
surfclust (Hagler, Saygin, and Sereno, 2006,
Neuroimage 33: 1093-1103).  This generates a
sixth set of surface files for each hemisphere
that have _h infixes.

The "SurfCluster: min area" entry sets the the
minimum area of a surface-based cluster that will
be passed by the filter and written into the left
and right hemisphere output files with an _h
infix.  The default of 150 mm^2 is roughly the
surface area of 16 standard 3x3x3 mm fMRI voxels.
If you smooth your data less, this will need to
be reduced to avoid removing significant
activations.

This parameter is passed as:

  surfclust ... -minarea <prethr> ...

See Help -> Cross Session Spherical Average for
more details on how to run randsurfclust to
determine cluster area thresholds for non-default
amounts of smoothing.

HOWTO disable 3D/Surf Clustering

Set 3DClust "minvol" to 0 to disable 3D
clustering.

Set SurfCluster "min area" to 0.0 to disable
surface clustering.

Phase Stat Type

This switch controls which value is inserted as
the amplitude (modulus) of the complex-valued
statistics generated when FOURIER is clicked.
The statistics are output as a real/imaginary
pair of files with infixes, _r and _i.  The phase
of this complex number, atan2(y,x)), is the phase
at the stimulus frequency taken from the Fourier
transform of the time course.

The first button, sqrt-F, tells the "fourier"
program to generate a vector whose amplitude is
the square root of the F-ratio calculated by
comparing the signal amplitude at the stimulus
frequency to the signal at other noise
frequencies.

Low frequencies, the second and third harmonics
of the stimulus frequency, one frequency to
either side of the 1st, 2nd, and 3rd harmonics,
and the optional "Omit Freq" are discarded as
neither signal nor noise.  If the "harm23" button
is clicked, harmonics 2 annd 3 are included as
part of the signal.

The p-val button calculates a p-value saved as a
negative of power of 10: -log10(p) -- thus,
p=0.01 will be saved as 2.0) from the F ratio by
taking into consideration the number of degrees
of freedom.

The p-FA calculated the probability of false
acceptance (also saved as -log10(p)).

In every case, the real and imaginary
coefficients of the Fourier transform at the
stimulus frequency are in addition saved as a
pair of files with infixes, _x and _y.

Finally, the coherence is saved as a file with
infix _c.  The coherence is defined as:

  stimfreq_amp / sqrt(sum(noisefreq_amps^2))

Stat Format, full FT, rm full FT

The original FOURIER program generated stats in
the form of bfloat slices.  The new default is to
generate AFNI BRIKs, which are more convenient to
view.  PAINT and phase COMBINE now accept AFNI
BRIK stats in addition to bfloat slices stats.
Here are the new standard outputs:

  <stem>_r+orig.BRIK -> real, sig/amp=sqrt(F)
  <stem>_i+orig.BRIK -> imaginary, sig/amp=sqrt(F)
  <stem>_x+orig.BRIK -> real, power at stim freq
  <stem>_y+orig.BRIK -> imaginary, power at stim freq
  <stem>_f+orig.BRIK -> F-stat -- N.B.: F not sqrt(F)
  <stem>_p+orig.BRIK -> if permutation test, -log10(p)
 <stem>_c+orig.BRIK->coher:stimfreq/sqrt(sum(noisefreqs^2))

The "full FT" check box in the middle causes the
entire Fourier transform to be dumped out in the
form of three additional (large!) float BRIKS:

  <stem>_xf+orig.BRIK -> real, all freqs
  <stem>_yf+orig.BRIK -> imaginary, all freqs
  <stem>_af+orig.BRIK -> amplitude, all freqs

Note that full FT files occupy a total of 6x as
much space as the original raw time-series data
(short->float times real+imaginary+amplitude).
They can be viewed in AFNI; "Index" (normally for
time points) can be used to scroll through
frequencies, and "Graph" can be used to see the
full (symmetric) Fourier spectrum (lowfreq ->
highfreq -> highfreq -> lowfreq).

The full FT's can be averaged across scans within
one session using the "Combine 3D Phase Stats"
panel (Combine Operation: "vect avg full FT's, do
sig"), which subsequently performs the same
significance calculation done here, but on the
average FT (programs: "rcxcombine -fullFT ..."
and "fourier" -juststats ...).

To save space, they can safely be removed with
the far right "rm full FT" button when the
combine operations are done.

Phase Encode Type

The radio button chosen specifies which set of
rendering defaults (color map type, color map
parameter settings, tcl scripts) to use when the
View Functional Data panel is first opened to
render surface images.  All the default values
can be overridden there.  The setting here also
tells the Fieldsign panel what kind of scan this
is (polar vs. eccen, or neither).

Truncphase

If Truncphase is checked, some phase angles will
be set to zero during the PAINT operation which
associates 3D statistics with each surface
vertex.  Generally, it is easier to do this
interactively in tksurfer, and save settings in
the View Functional Data panel.  The default
settings reflect the fact that stimuli typically
start on the horizontal meridian, which is
halfway through the right hemifield.

Fourier Format (minus infixes)

This is the tcl variable $bfloatpatt, which is
used to construct the stems of later files.  This
*omits* the infixes which would be situated in
the position of "$infix" in bfloat files and
BRIKs as follows:

  <stem>-vreg+orig{$infix}_%03d.bfloat
  <stem>-vreg+orig{$infix}+orig.BRIK

This should normally be set automatically and is
exposed here for debugging purposes.

Surface for Sampling 3D Data

This is the inner surface that the PAINT button
uses to sample 3D data onto the surface.  The
default is "orig".  In the original freesurfer,
the orig surface was the faces of the 1x1x1 cubes
classified as white matter.  In current
freesurfer distributions, the orig surface is a
smoother surface with better behaved surface
normals.

Painted Vertex List Files

These fields merely provide user feedback for the
names of the vertex list files (wfiles) generated
when PAINT is run to sample the 3D stats
calculated here onto the surface.

Action Button--FOURIER

When FOURIER is run, the panel will check whether
the number of repetitions in the corresponding
Setup Functional panels are powers of 2.  FOURIER
will not run unless this is the case (typically
128, 256, or 512 repetitions).

Action Button--PAINT

This button samples the Fourier analyzed data
onto the surface specified in "Surface for
Sampling 3D Data".  The result is 14 (or 16 if
permuation test) files, whose names appear
schematically in the bottom two entries on the
fourier panel.

There are seven (or seven) vertex-wise PAINT
output files for each hemisphere.  These consist
of the real and imaginary components of the
Fourier transform at the stimulus frequency
(infixes: _x,_y), the real and imaginary
components where the complex amplitude has been
replaced by a significance statistic (infixes:
_r,_i, where amplitude equals square root of the
F-ratio, or -log10(p) if a permutation test has
been run to calculate significance), the F-ratio
and the surface-based cluster-filtered F-ratio
(infixes: _f,_h), and the coherence (infix: _c).
Finally, if a permutation test has been run, the
-log10(p) is also output as a single file:

  <stem>-vreg+orig_x-{lh,rh}.w
  <stem>-vreg+orig_y-{lh,rh}.w

  <stem>-vreg+orig_r-{lh,rh}.w  # amp: sqrt(F) or -log10(p)
  <stem>-vreg+orig_i-{lh,rh}.w  # amp: sqrt(F) or -log10(p)

  <stem>-vreg+orig_f-{lh,rh}.w  # F (not sqrt(F))
  <stem>-vreg+orig_h-{lh,rh}.w  # cluster filtered F
  <stem>-vreg+orig_c-{lh,rh}.w  # coherence
  <stem>-vreg+orig_p-{lh,rh}.w  # if permutation test

See Help -> Register for details of how the
register.dat file generated by tkregister is used
to sample 3D statistics to the surface, including
code examples.

N.B.: the _f paint file is normally generated by
paint.c by squaring the amplitude of the
complex-valued _r and _i paint files (which is
sqrt(F)), as opposed to running a separate
instance of paint.c to sample the equivalent 3D
_f file onto the surface.

N.B.: the 3D _p file is only generated and
painted when a permutation test has been
performed.  In this case, the '_f' paintfile
mentioned above (made from complex-valued _r and
_i paint files) is overwritten by sampling the 3D
_f file (for subsequent cluster filter).

Action Button--AFNI

View raw and possibly smoothed timeseries BRIKs
(no infix), full Fourier transforms (infixes:
_xf, _yf, _af), and complex valued statistics
(infixes: {_r,_i}, _{x,_y}, _a) in the current
scan dir.

View 3D Stats overlaid on structural images

Use the VOLUME-STATS button on the View
Functional Data panel, which allows viewing
complex-valued statistics in 3D using the same
color scales as used for the surface display.

VOLUME-STATS supercedes the unsupported,
IRIX-only tkanalyse, which used to be startable
(in the Paleolithic) from this panel with Alt-v.
