All AFNI program -help files

This page auto-generated on Thu Nov 5 23:06:13 EST 2009



AFNI program: 1dAstrip
Usage: 1dAstrip < input > output

This very simple program strips non-numeric characters
from a file, so that it can be processed by other AFNI
1d programs.  For example, if your input is
  x=3.6 y=21.6 z=14.2
then your output would be
    3.6   21.6   14.2

* Non-numeric characters are replaced with blanks.
* The letter 'e' is preserved if it is preceeded
  or followed by a numeric character.  This is
  to allow for numbers like '1.2e-3'.
* Numeric characters, for the purpose of this
  program, are defined as the digits '0'..'9',
  and '.', '+', '-'.
* The program is simple and can easily end up leaving
  undesired junk characters in the output.  Sorry.
* This help string is longer than the rest of the
  source code to this program!



AFNI program: 1dBandpass
Usage: 1dBandpass [options] fbot ftop infile

 * infile is an AFNI *.1D file; each column is processed
 * fbot = lowest frequency in the passband, in Hz
          [can be 0 if you want to do a lowpass filter only,]
           but the mean and Nyquist freq are always removed ]
 * ftop = highest frequency in the passband (must be > fbot)
          [if ftop > Nyquist freq, then we have a highpass filter only]
 * You cannot construct a 'notch' filter with this program!
 * Output vectors appear on stdout; redirect as desired
 * Program will fail if fbot and ftop are too close for comfort
 * The actual FFT length used will be printed, and may be larger
   than the input time series length for the sake of efficiency.

Options:
  -dt dd     = set time step to 'dd' sec [default = 1.0]
  -ort f.1D  = Also orthogonalize input to columns in f.1D
               [only one '-ort' option is allowed]
  -nodetrend = Skip the quadratic detrending of the input
  -norm      = Make output time series have L2 norm = 1

Example:
  1deval -num 1000 -expr 'gran(0,1)' > r1000.1D
  1dBandpass 0.025 0.20 r1000.1D  > f1000.1D
  1dfft f1000.1D - | 1dplot -del 0.000977 -stdin -plabel 'Filtered |FFT|'

Goal:
 * Mostly to test the functions in thd_bandpass.c -- RWCox -- May 2009

++ Compile date = Nov  5 2009




AFNI program: 1dcat
Usage: 1dcat [-form option] a.1D b.1D ...
  where each file a.1D, b.1D, etc. is a 1D file.
  In the simplest form, a 1D file is an ASCII file of numbers
  arranged in rows and columns.
The row-by-row concatenation of the columns included in these  
files is written to stdout.

1dcat takes as input one or more 1D files, and writes out a 1D file
containing the side-by-side concatenation of all or a subset of the
columns from the input files.
All files must have the same number of rows.
For help on -form's usage, see ccalc's help for the option of the same name.
Example:
  Input file 1:
   1
   2
   3
   4
  Input file 2:
   5
   6
   7
   8

  1dcat data1.1D data2.1D > catout.1D
  Output file: 
   1 5
   2 6
   3 7
   4 8

For generic 1D file usage help, see '1dplot -help'

++ Compile date = Nov  5 2009




AFNI program: 1ddot
Usage: 1ddot [options] 1Dfile 1Dfile ...
- Prints out correlation matrix of the 1D files and
  their inverse correlation matrix.
- Output appears on stdout.

Options:
 -one  =  Make 1st vector be all 1's.
 -dem  =  Remove mean from all vectors (conflicts with '-one')
 -cov  =  Compute with covariance matrix instead of correlation
 -inn  =  Computed with inner product matrix instead
 -terse=  Output only the correlation or covariance matrix
          and without any of the garnish. 
 -okzero= Do not quit if a vector is all zeros.
          The correlation matrix will have 0 where NaNs ought to go.
          Expect rubbish in the inverse matrices if all zero 
          vectors exist.

++ Compile date = Nov  5 2009




AFNI program: 1deval
Usage: 1deval [options] -expr 'expression'
Evaluates an expression that may include columns of data
from one or more text files and writes the result to stdout.

** Only a single column can be used for each input 1D file. **
*  Simple multiple column operations (e.g., addition, scaling)
    can be done with program 1dmatcalc.
*  Any single letter from a-z can be used as the independent
    variable in the expression.
*  Unless specified using the '[]' notation (cf. 1dplot -help),
    only the first column of an input 1D file is used, and other
    columns are ignored.
*  Only one column of output will be produced -- if you want to
    calculate a multi-column output file, you'll have to run 1deval
    separately for each column, and then glue the results together
    using program 1dcat.  [However, see the 1dcat example combined
    with the '-1D:' option, infra.]

Options:
--------
  -del d   = Use 'd' as the step for a single undetermined variable
               in the expression [default = 1.0]
               SYNONYMS: '-dx' and '-dt'
  -start s = Start at value 's' for a single undetermined variable
               in the expression [default = 0.0]
               That is, for the indeterminate variable in the expression
               (if any), the i-th value will be s+i*d for i=0, 1, ....
               SYNONYMS: '-xzero' and '-tzero'
  -num n   = Evaluate the expression 'n' times.
               If -num is not used, then the length of an
               input time series is used.  If there are no
               time series input, then -num is required.
  -a q.1D  = Read time series file q.1D and assign it
               to the symbol 'a' (as in 3dcalc).
             * Letters 'a' to 'z' may be used as symbols.
             * You can use the filename 'stdin:' to indicate that
               the data for 1 symbol comes from standard input:
     1dTsort q.1D stdout: | 1deval -a stdin: -expr 'sqrt(a)' | 1dplot stdin:
  -index i.1D = Read index column from file i.1D and
                 write it out as 1st column of output.
                 This option is useful when working with
                 surface data.
  -1D:     = Write output in the form of a single '1D:'
               string suitable for input on the command
               line of another program.
               [-1D: is incompatible with the -index option!]
               [This won't work if the output string is very long,]
               [since the maximum command line length is limited. ]
Examples:
---------
 * 't' is the indeterminate variable in the expression below:
     1deval -expr 'sin(2*PI*t)' -del 0.01 -num 101 > sin.1D
 * Multiply two columns of data (no indeterminate variable):
     1deval -expr 'a*b' -a fred.1D -b ethel.1D > ab.1D
 * Compute and plot the F-statistic corresponding to p=0.001 for
   varying degrees of freedom given by the indeterminate variable 'n':
     1deval -start 10 -num 90 -expr 'fift_p2t(0.001,n,2*n)' | 1dplot -xzero 10 -stdin
 * Compute the square root of some numbers given in '1D:' form
   directly on the command line:
     1deval -x '1D: 1 4 9 16' -expr 'sqrt(x)'

Examples using '-1D:' as the output format:
-------------------------------------------
 1dplot `1deval -1D: -num 71 -expr 'cos(t/2)*exp(-t/19)'`
 1dcat `1deval -1D: -num 100 -expr 'cos(t/5)'` \
       `1deval -1D: -num 100 -expr 'sin(t/5)'` > sincos.1D
 3dTfitter -quiet -prefix -                                     \
           -RHS `1deval -1D: -num 30 -expr 'cos(t)*exp(-t/7)'`  \
           -LHS `1deval -1D: -num 30 -expr 'cos(t)'`            \
                `1deval -1D: -num 30 -expr 'sin(t)'`              

Notes:
------
* Program 3dcalc operates on 3D and 3D+time datasets in a similar way.
* Program ccalc can be used to evaluate a single numeric expression.
* If I had any sense, THIS program would have been called 1dcalc!
* For generic 1D file usage help, see '1dplot -help'
* For help with expression format, see '3dcalc -help', or type
   'help' when using ccalc in interactive mode.
* 1deval only produces a single column of output.  3dcalc can be
   tricked into doing multi-column 1D format output by treating
   a 1D file as a 3D dataset and auto-transposing it with \'
   For example:
     3dcalc -a '1D: 3 4 5 | 1 2 3'\' -expr 'cbrt(a)' -prefix -
   The input has 2 'columns' and so does the output.
   Note that the 1D 'file' is transposed on input to 3dcalc!
   This is essential, or 3dcalc will not treat the 1D file as
   a dataset, and the results will be very different.  Recall that
   when a 1D file is read as an 3D AFNI dataset, the row direction
   corresponds to the sub-brick (e.g., time) direction, and the
   column direction corresponds to the voxel direction.

A Dastardly Trick:
-----------------
If you use some other letter than 'z' as the indeterminate variable
in the calculation, and if 'z' is not assigned to any input 1D file,
then 'z' in the expression will be the previous value computed.
This trick can be used to create 1 point recursions, as in the
following command for creating a AR(1) noise time series:
   1deval -num 500 -expr 'gran(0,1)+(i-i)+0.7*z' > g07.1D
Note the use of '(i-i)' to intoduce the variable 'i' so that 'z'
would be used as the previous output value, rather than as the
indeterminate variable generated by '-del' and '-start'.
The initial value of 'z' is 0 (for the first evaluation).

-- RW Cox --

++ Compile date = Nov  5 2009




AFNI program: 1dfft
Usage: 1dfft [options] infile outfile
where infile is an AFNI *.1D file (ASCII list of numbers arranged
in columns); outfile will be a similar file, with the absolute
value of the FFT of the input columns.  The length of the file
will be 1+(FFT length)/2.

Options:
  -ignore sss = Skip the first 'sss' lines in the input file.
                [default = no skipping]
  -use uuu    = Use only 'uuu' lines of the input file.
                [default = use them all, Frank]
  -nfft nnn   = Set FFT length to 'nnn'.
                [default = length of data (# of lines used)]
  -tocx       = Save Re and Im parts of transform in 2 columns.
  -fromcx     = Convert 2 column complex input into 1 column
                  real output.
  -hilbert    = When -fromcx is used, the inverse FFT will
                  do the Hilbert transform instead.
  -nodetrend  = Skip the detrending of the input.

Nota Bene:
 * Each input time series has any quadratic trend of the
     form 'a+b*t+c*t*t' removed before the FFT, where 't'
     is the line number.
 * The FFT length will be a power-of-2 times at most one
     factor of 3 and one factor of 5.  The smallest such
     length >= to the specified FFT length will be used.
 * If the FFT length is longer than the file length, the
     data is zero-padded to make up the difference.
 * Do NOT call the output of this program the Power Spectrum!
     That is something else entirely.
 * If 'outfile' is '-', the output appears on stdout.

++ Compile date = Nov  5 2009




AFNI program: 1dFlagMotion
Usage: 1dFlagMotion [options] MotionParamsFile 

   Produces an list of time points that have more than a 
   user specified amount of motion relative to the previous 
   time point. 
 Options:
  -MaxTrans    maximum translation allowed in any direction 
                 [defaults to 1.5mm]
  -MaxRot      maximum rotation allowed in any direction 
                  [defaults to 1.25 degrees]

** The input file must have EXACTLY 6 columns of input, in the order:
     roll pitch yaw delta-SI delta-LR delta-AP
   (angles in degrees first, then translations in mm)

** The program does NOT accept column '[...]' selectors on the input
   file name, or comments in the file itself.  As a palliative, if the
   input file name is '-', then the input numbers are read from stdin,
   so you could do something like the following:
     1dcat mfile.1D'[1..6]' | 1dFlagMotion -
   e.g., to work with the output from 3dvolreg's '-dfile' option
   (where the first column is just the time index).

** The output is in a 1D format, with comments on '#' comment lines,
   and the list of points exceeding the motion bounds listed being
   intercalated on normal (non-comment) lines.

++ Compile date = Nov  5 2009




AFNI program: 1dgenARMA11
Program to generate an ARMA(1,1) time series, for simulation studies.
Results are written to stdout.

Usage: 1dgenARMA11 [options]

Options:
========
 -num N  }  These equivalent options specify the length of the time
 -len N  }  series vector to generate.

 -nvec M  = The number of time series vectors to generate;
            if this option is not given, defaults to 1.

 -a a     = Specify ARMA(1,1) parameters 'a'.
 -b b     = Specify ARMA(1,1) parameter 'b' directly.
 -lam lam = Specify ARMA(1,1) parameter 'b' indirectly.
 -sig ss  = Set standard deviation of results [default=1].
 -norm    = Normalize time series so sum of squares is 1.
 -seed dd = Set random number seed.

  * The correlation coefficient r(k) of noise samples k units apart in time,
     for k >= 1, is given by r(k) = lam * a^(k-1)
     where                   lam  = (b+a)(1+a*b)/(1+2*a*b+b*b)
     (N.B.: lam=a when b=0 -- AR(1) noise has r(k)=a^k for k >= 0)
     (N.B.: lam=b when a=0 -- MA(1) noise has r(k)=b for k=1, r(k)=0 for k>1)
  * lam can be bigger or smaller than a, depending on the sign of b:
     b > 0 means lam > a;  b < 0 means lam < a.
  * What I call (a,b) here is sometimes called (p,q) in the ARMA literature.
  * For a noise model which is the sum of AR(1) and white noise, 0 < lam < a
     (i.e., a > 0  and  -a < b < 0 ).

 -CORcut cc = The exact ARMA(1,1) correlation matrix (for a != 0)
              has no non-zero entries.  The calculations in this
              program set correlations below a cutoff to zero.
              The default cutoff is 0.00010, but can be altered with
              this option.  The usual reason to use this option is
              to test the sensitivity of the results to the cutoff.

Author: RWCox [for his own demented purposes]

Examples:
  1dgenARMA11 -num 200 -a .8 -lam 0.7 | 1dplot -stdin
  1dgenARMA11 -num 2000 -a .8 -lam 0.7 | 1dfft -nodetrend stdin: stdout: | 1dplot -stdin




AFNI program: 1dgrayplot
Usage: 1dgrayplot [options] tsfile
Graphs the columns of a *.1D type time series file to the screen,
sort of like 1dplot, but in grayscale.

Options:
 -install   = Install a new X11 colormap (for X11 PseudoColor)
 -ignore nn = Skip first 'nn' rows in the input file
                [default = 0]
 -flip      = Plot x and y axes interchanged.
                [default: data columns plotted DOWN the screen]
 -sep       = Separate scales for each column.
 -use mm    = Plot 'mm' points
                [default: all of them]
 -ps        = Don't draw plot in a window; instead, write it
              to stdout in PostScript format.
              N.B.: If you view this result in 'gv', you should
                    turn 'anti-alias' off, and switch to
                    landscape mode.

++ Compile date = Nov  5 2009




AFNI program: 1dMarry
Usage: 1dMarry [options] file1 file2 ...

  Joins together 2 (or more) ragged-right .1D files, for use with
    3dDeconvolve -stim_times_AM2.
 **_OR_**
  Breaks up 1 married file into 2 (or more) single-valued files.

OPTIONS:
=======
 -sep abc  == Use the first character (e.g., 'a') as the separator
              between values 1 and 2, the second character (e.g., 'b')
              as the separator between values 2 and 3, etc.
            * These characters CANNOT be a blank, a tab, a digit,
              or a non-printable control character!
            * Default separator string is '*,' which will result
              in output similar to '3*4,5,6'

 -divorce  == Instead of marrying the files, assume that file1
              is already a married file: split time*value*value... tuples
              into separate files, and name them in the pattern
              'file2_A.1D' 'file2_B.1D' et cetera.

If not divorcing, the 'married' file is written to stdout, and
probably should be captured using a redirection such as '>'.

NOTES:
=====
* You cannot use column [...] or row {...} selectors on
    ragged-right .1D files, so don't even think about trying!
* The maximum number of values that can be married is 26.
    (No polygamy or polyandry jokes here, please.)
* For debugging purposes, with '-divorce', if 'file2' is '-',
    then all the divorcees are written directly to stdout.

-- RWCox -- written hastily in March 2007 -- hope I don't repent
         -- modified to deal with multiple marriages -- December 2008

++ Compile date = Nov  5 2009




AFNI program: 1dmatcalc
Usage: 1dmatcalc [-verb] expression

Evaluate a space delimited RPN matrix-valued expression:

 * The operations are on a stack, each element of which is a
     real-valued matrix.
   * N.B.: This is a computer-science stack of separate matrices.
           If you want to join two matrices in separate files
           into one 'stacked' matrix, then you must use program
           1dcat to join them as columns, or the system program
           cat to join them as rows.
 * You can also save matrices by name in an internal buffer
     using the '=NAME' operation and then retrieve them later
     using just the same NAME.
 * You can read and write matrices from files stored in ASCII
     columns (.1D format) using the &read and &write operations.
 * The following 5 operations, input as a single string,
     '&read(V.1D) &read(U.1D) &transp * &write(VUT.1D)'
   - reads matrices V and U from disk (separately),
   - transposes U (on top of the stack) into U',
   - multiplies V and U' (the two matrices on top of the stack),
   - and writes matrix VU' out (the matrix left on the stack by '*').
 * Calculations are carried out in single precision ('float').
 * Operations mostly contain characters such as '&' and '*' that
   are special to Unix shells, so you'll probably need to put
   the arguments to this program in 'single quotes'.

 STACK OPERATIONS
 -----------------
 number     == push scalar value (1x1 matrix) on stack;
                 a number starts with a digit or a minus sign
 =NAME      == save matrix on top of stack as 'NAME'
 NAME       == push NAME-ed matrix onto top of stack;
                 names start with an alphabetic character
 &clear     == erase all named matrices (to save memory)
 &read(FF)  == read ASCII (.1D) file onto top of stack from file 'FF'
 &write(FF) == write top matrix to ASCII file to file 'FF';
                 if 'FF' == '-', writes to stdout
 &transp    == replace top matrix with its transpose
 &ident(N)  == push square identity matrix of order N onto stack
                 N is an fixed integer, OR
                 &R to indicate the row dimension of the
                    current top matrix, OR
                 &C to indicate the column dimension of the
                    current top matrix, OR
                 =X to indicate the (1,1) element of the
                    matrix named X
 &Psinv     == replace top matrix with its pseudo-inverse
                 [computed via SVD, not via inv(A'*A)*A']
 &Sqrt      == replace top matrix with its square root
                 [computed via Denman & Beavers iteration]
               N.B.: not all real matrices have real square
                 roots, and &Sqrt will fail if you push it
               N.B.: the matrix must be square!
 &Pproj     == replace top matrix with the projection onto
                 its column space; Input=A; Output = A*Psinv(A)
               N.B.: result P is symmetric and P*P=P
 &Qproj     == replace top matrix with the projection onto
                 the orthogonal complement of its column space
                 Input=A; Output=I-Pproj(A)
 *          == replace top 2 matrices with their product;
                   stack = [ ... C A B ] (where B = top) goes to
                   stack = [ ... C AB ]
                 if either of the top matrices is a 1x1 scalar,
                 then the result is the scalar multiplication of
                 the other matrix; otherwise, matrices must conform
 +          == replace top 2 matrices with sum A+B
 -          == replace top 2 matrices with difference A-B
 &dup       == push duplicate of top matrix onto stack
 &pop       == discard top matrix
 &swap      == swap top two matrices (A <-> B)

SIMPLE EXAMPLES
---------------
* Multiply each element of an input 1D file
  by a constant factor and write to disk.
    1dmatcalc "read(in.1D) 3.1416 * write(out.1D)"

* Subtract two 1D files
    1dmatcalc "read(a.1D) read(b.1D) - write(c.1D)"



AFNI program: 1dnorm
Usage: 1dnorm [options] infile outfile
where infile is an AFNI *.1D file (ASCII list of numbers arranged
in columns); outfile will be a similar file, with each column being
L_2 normalized (sum of squares = 1).
* If 'infile'  is '-', it will be read from stdin.
* If 'outfile' is '-', it will be written to stdout.

Options:
--------
 -norm1  = Normalize so sum of absolute values is 1 (L_1 norm)
 -normx  = So that max absolute value is 1 (L_infinity norm)

 -demean = Subtract each column's mean before normalizing
 -demed  = Subtract each column's median before normalizing
            [-demean and -demed are mutually exclusive!]

++ Compile date = Nov  5 2009




AFNI program: 1dplot
Usage: 1dplot [options] tsfile ...
Graphs the columns of a *.1D time series file to the X11 screen.

Options:
 -install   = Install a new X11 colormap.
 -sep       = Plot each column in a separate sub-graph.
 -one       = Plot all columns together in one big graph.
                [default = -sep]
 -sepscl    = Plot each column in a separate sub-graph
              and allow each sub-graph to have a different
              y-scale.  -sepscl is meaningless with -one!

           ** The '-norm' options below can be useful for
               plotting data with different value ranges on
               top of each other using '-one':
 -norm2     = Independently scale each time series plotted to
              have L_2 norm = 1 (sum of squares).
 -normx     = Independently scale each time series plotted to
              have max absolute value = 1 (L_infinity norm).
 -norm1     = Independently scale each time series plotted to
              have max sum of absolute values = 1 (L_1 norm).

 -x  X.1D   = Use for X axis the data in X.1D.
              Note that X.1D should have one column
              of the same length as the columns in tsfile. 
 N.B.: -x will override -dx and -xzero; -xaxis still has effects
 -xl10 X.1D = Use log10(X.1D) as the X axis.

 -dx xx     = Spacing between points on the x-axis is 'xx'
                [default = 1] SYNONYMS: '-dt' and '-del'
 -xzero zz  = Initial x coordinate is 'zz' [default = 0]
                SYNONYMS: '-tzero' and '-start'
 -nopush    = Don't 'push' axes ranges outwards.
 -ignore nn = Skip first 'nn' rows in the input file
                [default = 0]
 -use mm    = Plot 'mm' points [default = all of them]
 -xlabel aa = Put string 'aa' below the x-axis
                [default = no axis label]
 -ylabel aa = Put string 'aa' to the left of the y-axis
                [default = no axis label]
 -plabel pp = Put string 'pp' atop the plot.
              Some characters, such as '_' have
              special formatting effects. You 
              can escape that with ''. For example:
        echo 2 4.5 -1 | 1dplot -plabel 'test_underscore' -stdin
              versus
        echo 2 4.5 -1 | 1dplot -plabel 'test\_underscore' -stdin
 -title pp = Same as -plabel, but only works with -ps/-png/-jpg options.
 -wintitle pp = Set string 'pp' as the title of the frame 
                containing the plot. Default is based on input.

 -stdin     = Don't read from tsfile; instead, read from
              stdin and plot it. You cannot combine input
              from stdin and tsfile(s).  If you want to do so,
              use program 1dcat first.

 -ps        = Don't draw plot in a window; instead, write it
              to stdout in PostScript format.
             * If you view the result in 'gv', you should turn
               'anti-alias' off, and switch to landscape mode.
             * You can use the 'gs' program to convert PostScript
               to other formats; for example, a .bmp file:
            1dplot -ps ~/data/verbal/cosall.1D | 
             gs -r100 -sOutputFile=fred.bmp -sDEVICE=bmp256 -q -dBATCH -

 -jpg fname  } = Render plot to an image and save to a file named
 -jpeg fname } = 'fname', in JPEG mode or in PNG mode.
 -png fname  } = The default image width is 1024 pixels; to change
                 this value to 2000 pixels (say), do
                   setenv AFNI_1DPLOT_IMSIZE 2000
                 before running 1dplot.  Widths over 2000 may start
                 to look odd, and will run more slowly.
               * PNG files will be smaller than JPEG, and are
                 compressed without loss.
               * PNG output requires that the netpbm program
                 pnmtopng be installed somewhere in your PATH.

-ytran 'expr'    = Transform the data along the y-axis by
                   applying the expression to each input value.
                   For example:
                     -ytran 'log10(z)'
                   will take log10 of each input time series value
                   before plotting it.
                 * The expression should have one variable (any letter
                   from a-z will do), which stands for the time series
                   data to be transformed.
                 * An expression such as 'sqrt(x*x+i)' will use 'x'
                   for the time series value and use 'i' for the time
                   index (starting at 0) -- in this way, you can use
                   time-dependent transformations, if needed.
                 * This transformation applies to all input time series
                   (at present, there is no way to transform different
                   time series in distinct ways inside 1dplot).
                 * '-ytran' is applied BEFORE the various '-norm' options.

 -xaxis b:t:n:m  = Set the x-axis to run from value 'b' to
                   value 't', with 'n' major divisions and
                   'm' minor tic marks per major division.
                   For example:
                     -xaxis 0:100:5:20
                   Setting 'n' to 0 means no tic marks or labels.

 -yaxis b:t:n:m  = Similar to above, for the y-axis.  These
                   options override the normal autoscaling
                   of their respective axes.

 -ynames a b ... = Use the strings 'a', 'b', etc., as
                   labels to the right of the graphs,
                   corresponding to each input column.
                   These strings CANNOT start with the
                   '-' character.
             N.B.: Each separate string after '-ynames'
                   is taken to be a new label, until the
                   end of the command line or until some
                   string starts with a '-'.  In particular,
                   This means you CANNOT do something like
                     1dplot -ynames a b c file.1D
                   since the input filename 'file.1D' will
                   be used as a label string, not a filename.
                   Instead, you must put another option between
                   the end of the '-ynames' label list, OR you
                   can put a single '-' at the end of the label
                   list to signal its end:
                     1dplot -ynames a b c - file.1D

 -volreg         = Makes the 'ynames' be the same as the
                   6 labels used in plug_volreg for
                   Roll, Pitch, Yaw, I-S, R-L, and A-P
                   movements, in that order.

 -thick          = Each time you give this, it makes the line
                   thickness used for plotting a little larger.
                   [An alternative to using '-DAFNI_1DPLOT_THIK=...']

 -Dname=val      = Set environment variable 'name' to 'val'
                   for this run of the program only:
 1dplot -DAFNI_1DPLOT_THIK=0.01 -DAFNI_1DPLOT_COLOR_01=blue '1D:3 4 5 3 1 0'

You may also select a subset of columns to display using
a tsfile specification like 'fred.1D[0,3,5]', indicating
that columns #0, #3, and #5 will be the only ones plotted.
For more details on this selection scheme, see the output
of '3dcalc -help'.

Example: graphing a 'dfile' output by 3dvolreg, when TR=5:
   1dplot -volreg -dx 5 -xlabel Time 'dfile[1..6]'

You can also input more than one tsfile, in which case the files
will all be plotted.  However, if the files have different column
lengths, the shortest one will rule.

The colors for the line graphs cycle between black, red, green, and
blue.  You can alter these colors by setting Unix environment
variables of the form AFNI_1DPLOT_COLOR_xx -- cf. README.environment.
You can alter the thickness of the lines by setting the variable
AFNI_1DPLOT_THIK to a value between 0.00 and 0.05 -- the units are
fractions of the page size.

LABELS
------
Besides normal alphabetic text, the various labels can include some
special characters, using TeX-like escapes starting with '\'.
Also, the '^' and '_' characters denote super- and sub-scripts,
respectively.  The following command shows many of the escapes:
 1deval -num 100 -expr 'J0(t/4)' | 1dplot -stdin -thick \
 -xlabel '\alpha\beta\gamma\delta\epsilon\zeta\eta^{\oplus\dagger}\times c' \
 -ylabel 'Bessel Function \green J_0(t/4)'     \
 -plabel '\Upsilon\Phi\Chi\Psi\Omega\red\leftrightarrow\blue\partial^{2}f/\partial x^2'

TIMESERIES (1D) INPUT
---------------------
A timeseries file is in the form of a 1D or 2D table of ASCII numbers;
for example:   3 5 7
               2 4 6
               0 3 3
               7 2 9
This example has 4 rows and 3 columns.  Each column is considered as
a timeseries in AFNI.  The convention is to store this type of data
in a filename ending in '.1D'.

** COLUMN SELECTION WITH [] **
When specifying a timeseries file to an command-line AFNI program, you
can select a subset of columns using the '[...]' notation:
  'fred.1D[5]'            ==> use only column #5
  'fred.1D[5,9,17]'       ==> use columns #5, #9, and #17
  'fred.1D[5..8]'         ==> use columns #5, #6, #7, and #8
  'fred.1D[5..13(2)]'     ==> use columns #5, #7, #9, #11, and #13
Column indices start at 0.  You can use the character '$'
to indicate the last column in a 1D file; for example, you
can select every third column in a 1D file by using the selection list
  'fred.1D[0..$(3)]'      ==> use columns #0, #3, #6, #9, ....

** ROW SELECTION WITH {} **
Similarly, you select a subset of the rows using the '{...}' notation:
  'fred.1D{0..$(2)}'      ==> use rows #0, #2, #4, ....
You can also use both notations together, as in
  'fred.1D[1,3]{1..$(2)}' ==> columns #1 and #3; rows #1, #3, #5, ....

** DIRECT INPUT OF DATA ON THE COMMAND LINE WITH 1D: **
You can also input a 1D time series 'dataset' directly on the command
line, without an external file. The 'filename' for such input has the
general format
  '1D:n_1@val_1,n_2@val_2,n_3@val_3,...'
where each 'n_i' is an integer and each 'val_i' is a float.  For
example
   -a '1D:5@0,10@1,5@0,10@1,5@0'
specifies that variable 'a' be assigned to a 1D time series of 35,
alternating in blocks between values 0 and value 1.
 * Spaces or commas can be used to separate values.
 * A '|' character can be used to start a new input "line":
   Try 1dplot '1D: 3 4 3 5 | 3 5 4 3'

** TRANSPOSITION WITH \' **
Finally, you can force most AFNI programs to tranpose a 1D file on
input by appending a single ' character at the end of the filename.
N.B.: Since the ' character is also special to the shell, you'll
      probably have to put a \ character before it. Examples:
       1dplot '1D: 3 2 3 4 | 2 3 4 3'   and
       1dplot '1D: 3 2 3 4 | 2 3 4 3'\'
When you have reached this level of understanding, you are ready to
take the AFNI Jedi Master test.  I won't insult you by telling you
where to find this examination.

++ Compile date = Nov  5 2009




AFNI program: 1dSEM
Usage: 1dSEM [options] -theta 1dfile -C 1dfile -psi 1dfile -DF nn.n
Computes path coefficients for connection matrix in Structural Equation
    Modeling (SEM)
 The program takes as input :
    1. A 1D file with an initial representation of the connection matrix
       with a 1 for each interaction component to be modeled and a 0 if
       if it is not to be modeled. This matrix should be PxP rows and column
    2. A 1D file of the C, correlation matrix, also with dimensions PxP
    3. A 1D file of the residual variance vector, psi
    4. The degrees of freedom, DF

    Output is printed to the terminal and may be redirected to a 1D file
    The path coefficient matrix is printed for each matrix computed
 Options:
   -theta file.1D = connection matrix 1D file with initial representation
   -C file.1D = correlation matrix 1D file
   -psi file.1D = residual variance vector 1D file
   -DF nn.n = degrees of freedom
   -max_iter n = maximum number of iterations for convergence (Default=10000).
    Values can range from 1 to any positive integer less than 10000.
   -nrand n = number of random trials before optimization (Default = 100)
   -limits m.mmm n.nnn = lower and upper limits for connection coefficients
    (Default = -1.0 to 1.0)
   -calccost = no modeling at all, just calculate the cost function for the
    coefficients as given in the theta file. This may be useful for verifying
    published results
   -verbose nnnnn = print info every nnnnn steps

 Model search options:
 Look for best model. The initial connection matrix file must follow these
   specifications. Each entry must be 0 for entries excluded from the model,
   1 for each required entry in the minimum model, 2 for each possible path
   to try.
   -tree_growth or 
   -model_search = search for best model by growing a model for one additional
    coefficient from the previous model for n-1 coefficients. If the initial
    theta matrix has no required coefficients, the initial model will grow from
    the best model for a single coefficient
   -max_paths n = maximum number of paths to include (Default = 1000)
   -stop_cost n.nnn = stop searching for paths when cost function is below
    this value (Default = 0.1)
   -forest_growth or 
   -grow_all = search over all possible models by comparing models at
    incrementally increasing number of path coefficients. This
    algorithm searches all possible combinations; for the number of coeffs
    this method can be exceptionally slow, especially as the number of
    coefficients gets larger, for example at n>=9.
   -leafpicker = relevant only for forest growth searches. Expands the search
    optimization to look at multiple paths to avoid local minimum. This method
    is the default technique for tree growth and standard coefficient searches
 This program uses a Powell optimization algorithm to find the connection
   coefficients for any particular model.

 References:
   Powell, MJD, "The NEWUOA software for unconstrained optimization without
    derivatives", Technical report DAMTP 2004/NA08, Cambridge University
    Numerical Analysis Group -- http://www.damtp.cam.ac.uk/user/na/reports.html

   Bullmore, ET, Horwitz, B, Honey, GD, Brammer, MJ, Williams, SCR, Sharma, T,
    How Good is Good Enough in Path Analysis of fMRI Data?
    NeuroImage 11, 289-301 (2000)

   Stein, JL, et al., A validated network of effective amygdala connectivity,
    NeuroImage (2007), doi:10.1016/j.neuroimage.2007.03.022

 The initial representation in the theta file is non-zero for each element
   to be modeled. The 1D file can have leading columns for labels that will
   be used in the output. Label rows must be commented with the # symbol
 If using any of the model search options, the theta file should have a '1' for
   each required coefficient, '0' for each excluded coefficient, '2' for an
   optional coefficient. Excluded coefficients are not modeled. Required
   coefficients are included in every computed model.

 N.B. - Connection directionality in the path connection matrices is from 
   column to row of the output connection coefficient matrices.

   Be very careful when interpreting those path coefficients.
   First of all, they are not correlation coefficients. Suppose we have a
   network with a path connecting from region A to region B. The meaning
   of the coefficient theta (e.g., 0.81) is this: if region A increases by 
   one standard deviation from its mean, region B would be expected to increase
   by 0.81 its own standard deviations from its own mean while holding all other
   relevant regional connections constant. With a path coefficient of -0.16, 
   when region A increases by one standard deviation from its mean, region B 
   would be expected to decrease by 0.16 its own standard deviations from its
   own mean while holding all other relevant regional connections constant.

   So theoretically speaking the range of the path coefficients can be anything,
   but most of the time they range from -1 to 1. To save running time, the
   default values for -limits are set with -1 and 1, but if the result hits
   the boundary, increase them and re-run the analysis.

 Examples:
   To confirm a specific model:
    1dSEM -theta inittheta.1D -C SEMCorr.1D -psi SEMvar.1D -DF 30
   To search models by growing from the best single coefficient model
     up to 12 coefficients
    1dSEM -theta testthetas_ms.1D -C testcorr.1D -psi testpsi.1D \ 
    -limits -2 2 -nrand 100 -DF 30 -model_search -max_paths 12
   To search all possible models up to 8 coefficients:
    1dSEM -theta testthetas_ms.1D -C testcorr.1D -psi testpsi.1D \ 
    -nrand 10 -DF 30 -stop_cost 0.1 -grow_all -max_paths 8 | & tee testgrow.txt

   For more information, see http://afni.nimh.nih.gov/sscc/gangc/PathAna.html
    and our HBM 2007 poster at
   http://afni.nimh.nih.gov/sscc/posters/file.2007-06-07.0771819246
 If you find this program useful, please cite:
   G Chen, DR Glen, JL Stein, AS Meyer-Lindenberg, ZS Saad, RW Cox,
   Model Validation and Automated Search in FMRI Path Analysis:
   A Fast Open-Source Tool for Structural Equation Modeling,
   Human Brain Mapping Conference, 2007




AFNI program: 1dsum
Usage: 1dsum [options] a.1D b.1D ...
where each file a.1D, b.1D, etc. is an ASCII file of numbers arranged
in rows and columns. The sum of each column is written to stdout.

Options:
  -ignore nn = skip the first nn rows of each file
  -use    mm = use only mm rows from each file

++ Compile date = Nov  5 2009




AFNI program: 1dsvd
Usage: 1dsvd [options] 1Dfile 1Dfile ...
- Computes SVD of the matrix formed by the 1D file(s).
- Output appears on stdout; to save it, use '>' redirection.

OPTIONS:
 -one    = Make 1st vector be all 1's.
 -vmean  = Remove mean from each vector (can't be used with -one).
 -vnorm  = Make L2-norm of each vector = 1 before SVD.
           * The above 2 options mirror those in 3dpc.
 -cond   = Only print condition number (ratio of extremes)
 -sing   = Only print singular values
 -sort   = Sort singular values (descending) [the default]
 -nosort = Don't bother to sort the singular values
 -asort  = Sort singular values (ascending)
 -1Dleft = Only output left eigenvectors, in a .1D format
           This might be useful for reducing the number of
           columns in a design matrix.  The singular values
           are printed at the top of each vector column,
           as a '#...' comment line.
 -nev n  = If -1Dleft is used, '-nev' specifies only to output
           the first 'n' eigenvectors, rather than all of them.
EXAMPLE:
 1dsvd -vmean -vnorm -1Dleft fred.1D'[1..6]' | 1dplot -stdin
NOTES:
* Call the input n X m matrix [A] (n rows, m columns).  The SVD
  is the factorization [A] = [U] [S] [V]' ('=transpose), where
  - [U] is an n x m matrix (whose columns are the 'Left vectors')
  - [S] is a diagonal m x m matrix (the 'singular values')
  - [V] is an m x m matrix (whose columns are the 'Right vectors')
* The default output of the program is
  - An echo of the input [A]
  - The [U] matrix, each column headed by its singular value
  - The [V] matrix, each column headed by its singular value
    (please note that [V] is output, not [V]')
  - The pseudo-inverse of [A]
* This program was written simply for some testing purposes,
  but is distributed with AFNI because it might be useful-ish.
* Recall that you can transpose a .1D file on input by putting
  an escaped ' character after the filename.  For example,
    1dsvd fred.1D\'
  You can use this feature to get around the fact that there
  is no '-1Dright' option.  If you understand.
* For more information on the SVD, you can start at
  http://en.wikipedia.org/wiki/Singular_value_decomposition
* Author: Zhark the Algebraical (Linear).

++ Compile date = Nov  5 2009




AFNI program: 1d_tool.py

=============================================================================
1d_tool.py      - for manipulating and evaluating 1D files

   This program is meant to read/manipulate/write/diagnose 1D datasets.
   Input can be specified using AFNI sub-brick[]/time{} selectors.

---------------------------------------------------------------------------
examples (very basic for now):

   1.  Select by rows and columns, akin to 1dcat.

         1d_tool.py -infile 'data/X.xmat.1D[0..3]{0..5}' -write t1.1D

   2.  Compare with selection by separate options.

         1d_tool.py -infile data/X.xmat.1D                  \
                    -select_cols '0..3' -select_rows '0..5' \
                    -write t2.1D
         diff t1.1D t2.1D

   3.  Transpose a dataset, akin to 1dtranspose.

         1d_tool.py -infile t3.1D -transpose -write ttr.1D

   4a. Pad a file of regressors for a single run (#2) with zeros, so
       that it becomes run 2 of 7 (runs are 1-based).

         1d_tool.py -infile ricor_r02.1D -pad_into_many_runs 2 7 \
                    -write ricor_r02_all.1D

   4b. Similar to 4a, but specify varying TRs per run.  The number of
       runs must match the number of run_lengths parameters.

         1d_tool.py -infile ricor_r02.1D -pad_into_many_runs 2 7 \
                    -set_run_lengths 64 61 67 61 67 61 67        \
                    -write ricor_r02_all.1D

   5.  Display rows and columns for a 1D dataset.

         1d_tool.py -infile ricor_r02.1D -show_rows_cols

   6.  Show correlation matrix warnings for this matrix.

         1d_tool.py -infile X.xmat.1D -show_cormat_warnings

   7a. Output temporal derivative of motion regressors.  There are 9 runs in
       dfile.rall.1D, and derivatives are applied per run.

         1d_tool.py -infile dfile.rall.1D -set_nruns 9 \
                    -derivative -write motion.deriv.1D

   7b. Similar to 7a, but let the run lengths vary.  The sum of run lengths
       should equal the number of time points.

         1d_tool.py -infile dfile.rall.1D                       \
                    -set_run_lengths 64 64 64 64 64 64 64 64 64 \
                    -derivative -write motion.deriv.rlens.1D

   8.  Verify whether labels show slice-major ordering (where all slice0
       regressors come first, then all slice1 regressors, etc).  Either
       show the labels and verify visually, or print whether it is true.

         1d_tool.py -infile scan_2.slibase.1D'[0..12]' -show_labels
         1d_tool.py -infile scan_2.slibase.1D -show_labels
         1d_tool.py -infile scan_2.slibase.1D -show_label_ordering

   9a. Given motion.1D, take the derivative (ignoring run breaks) and the
       Euclidean Norm, and write as e.norm.1D.  This might be plotted to show
       show sudden motion as a single time series.

         1d_tool.py -infile motion.1D -set_nruns 9              \
                    -derivative  -collapse_cols euclidean_norm  \
                    -write e.norm.1D

   9b. Similar to 9a, but supposing the run lengths vary (still 576 TRs).

         1d_tool.py -infile motion.1D                           \
                    -set_run_lengths 64 61 67 61 67 61 67 61 67 \
                    -derivative  -collapse_cols euclidean_norm  \
                    -write e.norm.rlens.1D

  10.  Given motion.1D, create censor files to use in 3dDeconvolve, where a
       TR is censored if the derivative values have a Euclidean Norm above 1.2.

       The file created by -write_censor can be used with 3dD's -censor option.
       The file created by -write_CENSORTR can be used with -CENSORTR.  They
       should have the same effect in 3dDeconvolve.  The CENSORTR file is more
       readable, but the censor file is better for plotting against the data.
 
       a. general example

          1d_tool.py -infile motion.1D -set_nruns 9 -set_tr 3.0     \
                     -derivative -collapse_cols euclidean_norm      \
                     -extreme_mask -1.2 1.2                         \
                     -show_censor_count                             \
                     -write_censor subjA_censor.1D                  \
                     -write_CENSORTR subjA_CENSORTR.txt

       b. using -censor_motion

          The -censor_motion option is available, which implies '-derivative',
          '-collapse_cols euclidean_norm', 'extreme_mask -LIMIT LIMIT', and the
          prefix for '-write_censor' and '-write_CENSORTR' output files.  This
          option will also result in subjA_enorm.1D being written, which is the
          euclidean norm of the derivative, before the extreme mask is applied.

          1d_tool.py -infile motion.1D -set_nruns 9 -set_tr 3.0  \
                     -show_censor_count                          \
                     -censor_motion 1.2 subjA

       c. allow the run lengths to vary

          1d_tool.py -infile motion.1D -set_tr 3.0               \
                     -set_run_lengths 64 61 67 61 67 61 67 61 67 \
                     -show_censor_count                          \
                     -censor_motion 1.2 subjA_rlens

       Consider also '-censor_prev_TR'.

  11.  Demean the data.  Use motion parameters as an example.

       The demean operation is done per run (default is 1 when 1d_tool.py
       does not otherwise know).

       a. across all runs (if runs are not known from input file)

         1d_tool.py -infile dfile.rall.1D -demean -write motion.demean.a.1D

       b. per run, over 9 runs of equal length

         1d_tool.py -infile dfile.rall.1D -set_nruns 9      \
                -demean -write motion.demean.b.1D

       c. per run, over 9 runs of varying length

         1d_tool.py -infile dfile.rall.1D                   \
                -set_run_lengths 64 61 67 61 67 61 67 61 67 \
                -demean -write motion.demean.c.1D

  12.  "Uncensor" the data, zero-padding previously censored TRs.

       Note that an X-matrix output by 3dDeconvolve contains censor
       information in GoodList, which is the list of uncensored TRs.

       a. if the input dataset has censor information

         1d_tool.py -infile X.xmat.1D -censor_fill -write X.uncensored.1D

       b. if censor information needs to come from a parent

         1d_tool.py -infile sum.ideal.1D -censor_fill_parent X.xmat.1D \
                    -write sum.ideal.uncensored.1D

---------------------------------------------------------------------------
basic informational options:

   -help                        : show this help
   -hist                        : show the module history
   -show_valid_opts             : show all valid options
   -ver                         : show the version number

----------------------------------------
required input:

   -infile DATASET.1D           : specify input 1D file

----------------------------------------
general options:

   -add_cols NEW_DSET.1D        : extend dset to include these columns
   -collapse_cols METHOD        : collapse multiple columns into one, where

        METHOD is one of: min, max, minabs, maxabs, euclidean_norm.

   -censor_motion LIMIT PREFIX  : create censor files

        This option implies '-derivative', '-collapse_cols euclidean_norm',
        'extreme_mask -LIMIT LIMIT' and applies PREFIX for '-write_censor'
        and '-write_CENSORTR' output files.  It also outputs the derivative
        of the euclidean norm, before the limit it applied.

        The temporal derivative is taken with run breaks applied (derivative
        of the first run of a TR is 0), then the columns are collapsed into
        one via each TR's vector length (Euclidean Norm: sqrt(sum of squares)).
        After that, a mask time series is made from TRs with values outside
        (-LIMIT,LIMIT), i.e. if >= LIMIT or <= LIMIT, result is 1.

        This binary time series is then written out in -CENSORTR format, with
        the moderate TRs written in -censor format (either can be applied in
        3dDeconvolve).  The output files will be named PREFIX_censor.1D,
        PREFIX_CENSORTR.txt and PREFIX_enorm.1D (e.g. subj123_censor.1D,
        subj123_CENSORTR.txt and subj123_enorm.1D).

        The other information necessary besides an input motion file (-infile)
        is the number of runs (-set_nruns or -set_run_lengths) and the TR
        (-set_tr).

        Consider also '-censor_prev_TR'.
        See example 10.

   -censor_fill                 : expand data, filling censored TRs with zeros
   -censor_fill_parent PARENT   : similar, but get censor info from a parent

        The output of these operation is a longer dataset.  Each TR that had
        previously been censored is re-inserted as a zero.

        The purpose of this is to make 1D time series data properly align
        with the all_runs dataset, for example.  Otherwise, the ideal 1D data
        might have missing TRs, and so will align worse with responses over
        the duration of all runs (it might start aligned, but drift earlier
        and earlier as more TRs are censored).

        See example 12.

   -censor_prev_TR              : for each censored TR, also censor previous
   -cormat_cutoff CUTOFF        : set cutoff for cormat warnings (in [0,1])
   -demean                      : demean each run (new mean of each run = 0.0)
   -derivative                  : take the temporal derivative of each vector
   -extreme_mask MIN MAX        : mask extreme values

        Convert to a 0/1 mask, where 1 means the given value is in [MIN,MAX],
        and 0 means otherwise.  This is useful for censoring motion outliers.

   -overwrite                   : allow overwriting of any output dataset
   -reverse                     : reverse data over time
   -select_cols SELECTOR        : apply AFNI column selectors, [] is optional
                                  e.g. '[5,0,7..21(2)]'
   -select_rows SELECTOR        : apply AFNI row selectors, {} is optional
                                  e.g. '{5,0,7..21(2)}'
   -set_nruns NRUNS             : treat the input data as if it has nruns
                                  (e.g. applies to -derivative and -demean)

        See examples 7a, 10a and b.

   -set_run_lengths N1 N2 ...   : treat as if data has run lengths N1, N2, etc.
                                  (applies to -derivative, for example)

        Notes:  o  option -set_nruns is not allowed with -set_run_lengths
                o  the sum of run lengths must equal NT

        See examples 7b and 10c.

   -set_tr TR                   : set the TR (in seconds) for the data
   -show_censor_count           : display the total number of censored TRs
   -show_cormat_warnings        : display correlation matrix warnings
   -show_label_ordering         : display the labels
   -show_labels                 : display the labels
   -show_rows_cols              : display the number of rows and columns
   -sort                        : sort data over time (smallest to largest)
                                  - sorts EVERY vector
                                  - consider the -reverse option
   -transpose                   : transpose the matrix (rows for columns)
   -write FILE                  : write the current 1D data to FILE
   -write_censor FILE           : write as boolean censor.1D

        e.g. -write_censor subjA_censor.1D

        This file can be given to 3dDeconvolve to censor TRs with excessive
        motion, applied with the -censor option.

            e.g. 3dDeconvolve -censor subjA_censor.1D

        This file works well for plotting against the data, where the 0 entries
        are removed from the regression of 3dDeconvolve.  Alternatively, the
        file created with -write_CENSORTR is probably more human readable.

   -write_CENSORTR FILE         : write censor times as CENSORTR string

        e.g. -write_CENSORTR subjA_CENSORTR.txt

        This file can be given to 3dDeconvolve to censor TRs with excessive
        motion, applied with the -CENSORTR option.

            e.g. 3dDeconvolve -CENSORTR `cat subjA_CENSORTR.txt`

        Which might expand to:

                 3dDeconvolve -CENSORTR '1:16..19,44 3:28 4:19,37..39'

        Note that the -CENSORTR option requires the text on the command line.

        This file is in the easily readable format applied with -CENSORTR.
        It has the same effect on 3dDeconvolve as the sister file from
        -write_censor, above.

   -verb LEVEL                  : set the verbosity level

-----------------------------------------------------------------------------
R Reynolds    March 2009
=============================================================================




AFNI program: 1dtranspose
Usage: 1dtranspose infile outfile
where infile is an AFNI *.1D file (ASCII list of numbers arranged
in columns); outfile will be a similar file, but transposed.
You can use a column subvector selector list on infile, as in
  1dtranspose 'fred.1D[0,3,7]' ethel.1D

* This program may produce files with lines longer than a
   text editor can handle.
* If 'outfile' is '-' (or missing entirely), output goes to stdout.

++ Compile date = Nov  5 2009




AFNI program: 1dTsort
Usage: 1dTsort [options] file.1D
Sorts each column of the input 1D file and writes result to stdout.

Options
-------
 -inc     = sort into increasing order [default]
 -dec     = sort into decreasing order
 -flip    = transpose the file before OUTPUT
            * the INPUT can be transposed using file.1D\'
            * thus, to sort each ROW, do something like
               1dTsort -flip file.1D\' > sfile.1D

N.B.: Data will be read from standard input if the filename IS stdin,
      and will also be row/column transposed if the filename is stdin\'
      For example:
        1deval -num 100 -expr 'uran(1)' | 1dTsort stdin | 1dplot stdin


++ Compile date = Nov  5 2009




AFNI program: 1dUpsample
Program 1dUpsample:
Upsamples a 1D time series (along the column direction)
to a finer time grid.
Usage:  1dUpsample [options] n fred.1D > ethel.1D

Where 'n' is the upsample factor (integer from 2..32)

NOTES:
------
* Interpolation is done with 7th order polynomials.
   (Why 7? It's a nice number, and the code already existed.)
* The only option is '-1' or '-one', to use 1st order
   polynomials instead (i.e., linear interpolation).
* Output is written to stdout.
* If you want to interpolate along the row direction,
   transpose before input, then transpose the output.
* Example:
   1dUpsample 5 '1D: 4 5 4 3 4' | 1dplot -stdin -dx 0.2 
* If the input has M time points, the output will
   have n*M time points.  The last n-1 of them
   will be past the end of the original time series.
* This program is a quick hack for Gang Chen.
   Where are my Twizzlers?




AFNI program: 24swap
Usage: 24swap [options] file ...
Swaps bytes pairs and/or quadruples on the files listed.
Options:
 -q            Operate quietly
 -pattern pat  'pat' determines the pattern of 2 and 4
                 byte swaps.  Each element is of the form
                 2xN or 4xN, where N is the number of
                 bytes to swap as pairs (for 2x) or
                 as quadruples (for 4x).  For 2x, N must
                 be divisible by 2; for 4x, N must be
                 divisible by 4.  The whole pattern is
                 made up of elements separated by colons,
                 as in '-pattern 4x39984:2x0'.  If bytes
                 are left over after the pattern is used
                 up, the pattern starts over.  However,
                 if a byte count N is zero, as in the
                 example below, then it means to continue
                 until the end of file.

 N.B.: You can also use 1xN as a pattern, indicating to
         skip N bytes without any swapping.
 N.B.: A default pattern can be stored in the Unix
         environment variable AFNI_24SWAP_PATTERN.
         If no -pattern option is given, the default
         will be used.  If there is no default, then
         nothing will be done.
 N.B.: If there are bytes 'left over' at the end of the file,
         they are written out unswapped.  This will happen
         if the file is an odd number of bytes long.
 N.B.: If you just want to swap pairs, see program 2swap.
         For quadruples only, see program 4swap.
 N.B.: This program will overwrite the input file!
         You might want to test it first.

 Example: 24swap -pat 4x8:2x0 fred
          If fred contains 'abcdabcdabcdabcdabcd' on input,
          then fred has    'dcbadcbabadcbadcbadc' on output.



AFNI program: 2dImReg
++ 2dImReg: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
This program performs 2d image registration.  Image alignment is      
performed on a slice-by-slice basis for the input 3d+time dataset,    
relative to a user specified base image.                              
                                                                      
Usage:                                                                
2dImReg                                                               
-input fname           Filename of input 3d+time dataset to process   
-basefile fname        Filename of 3d+time dataset for base image     
                         (default = current input dataset)            
-base num              Time index for base image  (0 <= num)          
                         (default:  num = 3)                          
-nofine                Deactivate fine fit phase of image registration
                         (default:  fine fit is active)               
-fine blur dxy dphi    Set fine fit parameters                        
   where:                                                             
     blur = FWHM of blurring prior to registration (in pixels)        
               (default:  blur = 1.0)                                 
     dxy  = Convergence tolerance for translations (in pixels)        
               (default:  dxy  = 0.07)                                
     dphi = Convergence tolerance for rotations (in degrees)          
               (default:  dphi = 0.21)                                
                                                                      
-prefix pname     Prefix name for output 3d+time dataset              
                                                                      
-dprefix dname    Write files 'dname'.dx, 'dname'.dy, 'dname'.psi     
                    containing the registration parameters for each   
                    slice in chronological order.                     
                    File formats:                                     
                      'dname'.dx:    time(sec)   dx(pixels)           
                      'dname'.dy:    time(sec)   dy(pixels)           
                      'dname'.psi:   time(sec)   psi(degrees)         
-dmm              Change dx and dy output format from pixels to mm    
                                                                      
-rprefix rname    Write files 'rname'.oldrms and 'rname'.newrms       
                    containing the volume RMS error for the original  
                    and the registered datasets, respectively.        
                    File formats:                                     
                      'rname'.oldrms:   volume(number)   rms_error    
                      'rname'.newrms:   volume(number)   rms_error    
                                                                      
-debug            Lots of additional output to screen                 



AFNI program: 2swap
Usage: 2swap [-q] file ...
-- Swaps byte pairs on the files listed.
   The -q option means to work quietly.



AFNI program: 3dABoverlap
Usage: 3dABoverlap [options] A B
Output (to screen) is a count of various things about how
the automasks of datasets A and B overlap or don't overlap.

* Dataset B will be resampled to match dataset A, if necessary,
   which will be slow if A is high resolution.  In such a case,
   you should only use one sub-brick from dataset B.
  ++ The resampling of B is done before the automask is generated.
* The values output are labeled thusly:
    #A         = number of voxels in the A mask
    #B         = number of voxels in the B mask
    #(A uni B) = number of voxels in the either or both masks (set union)
    #(A int B) = number of voxels present in BOTH masks (set intesection)
    #(A \ B)   = number of voxels in A mask that aren't in B mask
    #(B \ A)   = number of voxels in B mask that arent' in A mask
    %(A \ B)   = percentage of voxels from A mask that aren't in B mask
    %(B \ A)   = percentage of voxels from B mask that aren't in A mask
    Rx(B/A)    = radius of gyration of B mask / A mask, in x direction
    Ry(B/A)    = radius of gyration of B mask / A mask, in y direction
    Rz(B/A)    = radius of gyration of B mask / A mask, in z direction
* If B is an EPI dataset sub-brick, and A is a skull stripped anatomical
   dataset, then %(B \ A) might be useful for assessing if the EPI
   brick B is grossly misaligned with respect to the anatomical brick A.
* The radius of gyration ratios might be useful for determining if one
   dataset is grossly larger or smaller than the other.

OPTIONS
-------
 -verb  = print out some progress reports (to stderr)
 -quiet = be as quiet as possible (without being entirely mute)

NOTES
-----
 * If an input dataset is comprised of bytes and contains only one
   sub-brick, then this program assumes it is already an automask-
   generated dataset and the automask operation will be skipped.

++ Compile date = Nov  5 2009




AFNI program: 3dAcost

  *** Program 3dAcost is no longer available.
  *** Use '3dAllineate -allcostX' instead;
  *** See the output of '3dAllineate -HELP' for more information.




AFNI program: 3dAFNIto3D
Usage: 3dAFNIto3D [options] dataset
Reads in an AFNI dataset, and writes it out as a 3D file.

OPTIONS:
 -prefix ppp  = Write result into file ppp.3D;
                  default prefix is same as AFNI dataset's.
 -bin         = Write data in binary format, not text.
 -txt         = Write data in text format, not binary.

NOTES:
* At present, all bricks are written out in float format.

++ Compile date = Nov  5 2009




AFNI program: 3dAFNItoANALYZE
Usage: 3dAFNItoANALYZE [-4D] [-orient code] aname dset
Writes AFNI dataset 'dset' to 1 or more ANALYZE 7.5 format
.hdr/.img file pairs (one pair for each sub-brick in the
AFNI dataset).  The ANALYZE files will be named
  aname_0000.hdr aname_0000.img   for sub-brick #0
  aname_0001.hdr aname_0001.img   for sub-brick #1
and so forth.  Each file pair will contain a single 3D array.

* If the AFNI dataset does not include sub-brick scale
  factors, then the ANALYZE files will be written in the
  datum type of the AFNI dataset.
* If the AFNI dataset does have sub-brick scale factors,
  then each sub-brick will be scaled to floating format
  and the ANALYZE files will be written as floats.
* The .hdr and .img files are written in the native byte
  order of the computer on which this program is executed.

Options
-------
-4D [30 Sep 2002]:
 If you use this option, then all the data will be written to
 one big ANALYZE file pair named aname.hdr/aname.img, rather
 than a series of 3D files.  Even if you only have 1 sub-brick,
 you may prefer this option, since the filenames won't have
 the '_0000' appended to 'aname'.

-orient code [19 Mar 2003]:
 This option lets you flip the dataset to a different orientation
 when it is written to the ANALYZE files.  The orientation code is
 formed as follows:
   The code must be 3 letters, one each from the
   pairs {R,L} {A,P} {I,S}.  The first letter gives
   the orientation of the x-axis, the second the
   orientation of the y-axis, the third the z-axis:
      R = Right-to-Left          L = Left-to-Right
      A = Anterior-to-Posterior  P = Posterior-to-Anterior
      I = Inferior-to-Superior   S = Superior-to-Inferior
   For example, 'LPI' means
      -x = Left       +x = Right
      -y = Posterior  +y = Anterior
      -z = Inferior   +z = Superior
 * For display in SPM, 'LPI' or 'RPI' seem to work OK.
    Be careful with this: you don't want to confuse L and R
    in the SPM display!
 * If you DON'T use this option, the dataset will be written
    out in the orientation in which it is stored in AFNI
    (e.g., the output of '3dinfo dset' will tell you this.)
 * The dataset orientation is NOT stored in the .hdr file.
 * AFNI and ANALYZE data are stored in files with the x-axis
    varying most rapidly and the z-axis most slowly.
 * Note that if you read an ANALYZE dataset into AFNI for
    display, AFNI assumes the LPI orientation, unless you
    set environment variable AFNI_ANALYZE_ORIENT.

++ Compile date = Nov  5 2009




AFNI program: 3dAFNItoMINC
Usage: 3dAFNItoMINC [options] dataset
Reads in an AFNI dataset, and writes it out as a MINC file.

OPTIONS:
 -prefix ppp  = Write result into file ppp.mnc;
                  default prefix is same as AFNI dataset's.
 -floatize    = Write MINC file in float format.
 -swap        = Swap bytes when passing data to rawtominc

NOTES:
* Multi-brick datasets are written as 4D (x,y,z,t) MINC
   files.
* If the dataset has complex-valued sub-bricks, then this
   program won't write the MINC file.
* If any of the sub-bricks have floating point scale
   factors attached, then the output will be in float
   format (regardless of the presence of -floatize).
* This program uses the MNI program 'rawtominc' to create
   the MINC file; rawtominc must be in your path.  If you
   don't have rawtominc, you must install the MINC tools
   software package from MNI.  (But if you don't have the
   MINC tools already, why do you want to convert to MINC
   format anyway?)
* At this time, you can find the MINC tools at
     ftp://ftp.bic.mni.mcgill.ca/pub/minc/
   You need the latest version of minc-*.tar.gz and also
   of netcdf-*.tar.gz.

-- RWCox - April 2002

++ Compile date = Nov  5 2009




AFNI program: 3dAFNItoNIFTI
++ 3dAFNItoNIFTI: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
Usage: 3dAFNItoNIFTI [options] dataset
Reads an AFNI dataset, writes it out as a NIfTI-1.1 file.

NOTES:
* The nifti_tool program can be used to manipulate
   the contents of a NIfTI-1.1 file.
* The input dataset can actually be in any input format
   that AFNI can read directly (e.g., MINC-1).
* There is no 3dNIFTItoAFNI program, since AFNI programs
   can directly read .nii files.  If you wish to make such
   a conversion anyway, one way to do so is like so:
     3dcalc -a ppp.nii -prefix ppp -expr 'a'

OPTIONS:
  -prefix ppp = Write the NIfTI-1.1 file as 'ppp.nii'.
                  Default: the dataset's prefix is used.
                * You can use 'ppp.hdr' to output a 2-file
                  NIfTI-1.1 file pair 'ppp.hdr' & 'ppp.img'.
                * If you want a compressed file, try
                  using a prefix like 'ppp.nii.gz'.
                * Setting the Unix environment variable
                  AFNI_AUTOGZIP to YES will result in
                  all output .nii files being gzip-ed.
  -verb       = Be verbose = print progress messages.
                  Repeating this increases the verbosity
                  (maximum setting is 3 '-verb' options).
  -float      = Force the output dataset to be 32-bit
                  floats.  This option should be used when
                  the input AFNI dataset has different
                  float scale factors for different sub-bricks,
                  an option that NIfTI-1.1 does not support.

The following options affect the contents of the AFNI extension
field that is written by default into the NIfTI-1.1 header:

  -pure       = Do NOT write an AFNI extension field into
                  the output file.  Only use this option if
                  needed.  You can also use the 'nifti_tool'
                  program to strip extensions from a file.
  -denote     = When writing the AFNI extension field, remove
                  text notes that might contain subject
                  identifying information.
  -oldid      = Give the new dataset the input dataset's
                  AFNI ID code.
  -newid      = Give the new dataset a new AFNI ID code, to
                  distinguish it from the input dataset.
     **** N.B.:  -newid is now the default action.

++ Compile date = Nov  5 2009




AFNI program: 3dAFNItoNIML
Usage: 3dAFNItoNIML [options] dset
 Dumps AFNI dataset header information to stdout in NIML format.
 Mostly for debugging and testing purposes!

 OPTIONS:
  -data          == Also put the data into the output (will be huge).
  -ascii         == Format in ASCII, not binary (even huger).
  -tcp:host:port == Instead of stdout, send the dataset to a socket.
                    (implies '-data' as well)

-- RWCox - Mar 2005

++ Compile date = Nov  5 2009




AFNI program: 3dAFNItoRaw
Usage: 3dAFNItoRaw [options] dataset
Convert an AFNI brik file with multiple sub-briks to a raw file with
  each sub-brik voxel concatenated voxel-wise.
For example, a dataset with 3 sub-briks X,Y,Z with elements x1,x2,x3,...,xn,
  y1,y2,y3,...,yn and z1,z2,z3,...,zn will be converted to a raw dataset with
  elements x1,y1,z1, x2,y2,z2, x3,y3,z3, ..., xn,yn,zn 
The dataset is kept in the original data format (float/short/int)
Options:
  -output / -prefix = name of the output file (not an AFNI dataset prefix)
    the default output name will be rawxyz.dat

  -datum float = force floating point output. Floating point forced if any
    sub-brik scale factors not equal to 1.


INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dAllineate
Usage: 3dAllineate [options] sourcedataset

Program to align one dataset (the 'source') to a base dataset.
Options are available to control:
 ++ How the matching between the source and the base is computed
    (i.e., the 'cost functional' measuring image mismatch).
 ++ How the resliced source is interpolated to the base space.
 ++ The complexity of the spatial transformation ('warp') used.
 ++ And many technical options to control the process in detail,
    if you know what you are doing (or just like to play around).

====
NOTE: If you want to align EPI volumes to a T1-weighted structural
====  volume, the script align_epi_anat.py is recommended.  It will
      use 3dAllineate in the recommended way for this type of problem.
 -->> In particular, using 3dAllineate with the 'lpc' cost functional
      requires using a '-weight' volume to get good results, and the
      align_epi_anat.py script will automagically generate such a
      weight dataset that works well for EPI-to-structural alignment.
 -->> This script can also be used for other alignment purposes, such
      as T1-weighted alignment between field strengths using the
      '-lpa' cost functional.  Investigate align_epi_anat.py to
      see if it will do what you need -- you might make your life
      a little easier and nicer and happier.

OPTIONS:
=======
 -base bbb   = Set the base dataset to be the #0 sub-brick of 'bbb'.
               If no -base option is given, then the base volume is
               taken to be the #0 sub-brick of the source dataset.
               (Base must be stored as floats, shorts, or bytes.)

 -source ttt = Read the source dataset from 'ttt'.  If no -source
   *OR*        (or -input) option is given, then the source dataset
 -input ttt    is the last argument on the command line.
               (Source must be stored as floats, shorts, or bytes.)

  * NOTA BENE: The base and source dataset do NOT have to be defined *
  *            on the same 3D grids; the alignment process uses the  *
  *            coordinate systems defined in the dataset headers to  *
  *            make the match between spatial locations.             *
  *       -->> However, this coordinate-based matching requires that *
  *            image volumes be defined on roughly the same patch of *
  *            of (x,y,z) space, in order to find a decent starting  *
  *            point for the transformation.  You might need to use  *
  *            the script @Align_Centers to do this, if the 3D       *
  *            spaces occupied by the images do not overlap much.    *
  *       -->> Or the '-cmass' option to this program might be       *
  *            sufficient to solve this problem, maybe.              *

 -prefix ppp = Output the resulting dataset to file 'ppp'.  If this
   *OR*        option is NOT given, no dataset will be output!  The
 -out ppp      transformation matrix to align the source to the base will
               be estimated, but not applied.  You can save the matrix
               for later use using the '-1Dmatrix_save' option.
        *N.B.: By default, the new dataset is computed on the grid of the
                base dataset; see the '-master' and/or the '-mast_dxyz'
                options to change this grid.
        *N.B.: If 'ppp' is 'NULL', then no output dataset will be produced.
                This option is for compatibility with 3dvolreg.

 -floatize   = Write result dataset as floats.  Internal calculations
 -float        are all done on float copies of the input datasets.
               [Default=convert output dataset to data format of  ]
               [        source dataset; if the source dataset was ]
               [        shorts with a scale factor, then the new  ]
               [        dataset will get a scale factor as well;  ]
               [        if the source dataset was shorts with no  ]
               [        scale factor, the result will be unscaled.]

 -1Dparam_save ff   = Save the warp parameters in ASCII (.1D) format into
                      file 'ff' (1 row per sub-brick in source).
               *N.B.: A historical synonym for this option is '-1Dfile'.

 -1Dparam_apply aa  = Read warp parameters from file 'aa', apply them to 
                      the source dataset, and produce a new dataset.
                      (Must also use the '-prefix' option for this to work!  )
                      (In this mode of operation, there is no optimization of)
                      (the cost functional by changing the warp parameters;  )
                      (previously computed parameters are applied directly.  )
               *N.B.: A historical synonym for this is '-1Dapply'.
               *N.B.: If you use -1Dparam_apply, you may also want to use
                       -master to control the grid on which the new
                       dataset is written -- the base dataset from the
                       original 3dAllineate run would be a good possibility.
                       Otherwise, the new dataset will be written out on the
                       3D grid coverage of the source dataset, and this
                       might result in clipping off part of the image.
               *N.B.: Each row in the 'aa' file contains the parameters for
                       transforming one sub-brick in the source dataset.
                       If there are more sub-bricks in the source dataset
                       than there are rows in the 'aa' file, then the last
                       row is used repeatedly.
               *N.B.: A trick to use 3dAllineate to resample a dataset to
                       a finer grid spacing:
                         3dAllineate -input dataset+orig         \
                                     -master template+orig       \
                                     -prefix newdataset          \
                                     -final quintic              \
                                     -1Dparam_apply '1D: 12@0'\'  
                       Here, the identity transformation is specified
                       by giving all 12 affine parameters as 0 (note
                       the extra \' at the end of the '1D: 12@0' input!).

 -1Dmatrix_save ff  = Save the transformation matrix for each sub-brick into
                      file 'ff' (1 row per sub-brick in the source dataset).
                      If 'ff' does NOT end in '.1D', then the program will
                      append '.aff12.1D' to 'ff' to make the output filename.
               *N.B.: This matrix is the coordinate transformation from base
                       to source DICOM coordinates. In other terms:
                          Xin = Xsource = M Xout = M Xbase
                                   or
                          Xout = Xbase = inv(M) Xin = inv(M) Xsource
                       where Xin or Xsource is the 4x1 coordinates of a
                       location in the input volume. Xout is the 
                       coordinate of that same location in the output volume.
                       Xbase is the coordinate of the corresponding location
                       in the base dataset. M is ff augmented by a 4th row of
                       [0 0 0 1], X. is an augmented column vector [x,y,z,1]'
                       To get the inverse matrix inv(M)
                       (source to base), use the cat_matvec program, as in
                         cat_matvec fred.aff12.1D -I

 -1Dmatrix_apply aa = Use the matrices in file 'aa' to define the spatial
                      transformations to be applied.  Also see program
                      cat_matvec for ways to manipulate these matrix files.
               *N.B.: You probably want to use either -base or -master
                      with either *_apply option, so that the coordinate
                      system that the matrix refers to is correctly loaded.

  * The -1Dmatrix_* options can be used to save and re-use the transformation *
  * matrices.  In combination with the program cat_matvec, which can multiply *
  * saved transformation matrices, you can also adjust these matrices to      *
  * other alignments.                                                         *

  * The script 'align_epi_anat.py' uses 3dAllineate and 3dvolreg to align EPI *
  * datasets to T1-weighted anatomical datasets, using saved matrices between *
  * the two programs.  This script is our currently recommended method for    *
  * doing such intra-subject alignments.                                      *

 -cost ccc   = Defines the 'cost' function that defines the matching
               between the source and the base; 'ccc' is one of
                ls   *OR*  leastsq         = Least Squares [Pearson Correlation]
                mi   *OR*  mutualinfo      = Mutual Information [H(b)+H(s)-H(b,s)]
                crM  *OR*  corratio_mul    = Correlation Ratio (Symmetrized*)
                nmi  *OR*  norm_mutualinfo = Normalized MI [H(b,s)/(H(b)+H(s))]
                hel  *OR*  hellinger       = Hellinger metric
                crA  *OR*  corratio_add    = Correlation Ratio (Symmetrized+)
                crU  *OR*  corratio_uns    = Correlation Ratio (Unsym)
               You can also specify the cost functional using an option
               of the form '-mi' rather than '-cost mi', if you like
               to keep things terse and cryptic (as I do).
               [Default == '-hel' (for no good reason).]

 -interp iii = Defines interpolation method to use during matching
               process, where 'iii' is one of
                 NN      *OR* nearestneighbour *OR nearestneighbor
                 linear  *OR* trilinear
                 cubic   *OR* tricubic
                 quintic *OR* triquintic
               Using '-NN' instead of '-interp NN' is allowed (e.g.).
               Note that using cubic or quintic interpolation during
               the matching process will slow the program down a lot.
               Use '-final' to affect the interpolation method used
               to produce the output dataset, once the final registration
               parameters are determined.  [Default method == 'linear'.]
            ** N.B.: Linear interpolation is used during the coarse
                     alignment pass; the selection here only affects
                     the interpolation method used during the second
                     (fine) alignment pass.

 -final iii  = Defines the interpolation mode used to create the
               output dataset.  [Default == 'cubic']
            ** N.B.: For '-final' ONLY, you can use 'wsinc5' to specify
                       that the final interpolation be done using a
                       weighted sinc interpolation method.  This method
                       is so SLOW that you aren't allowed to use it for
                       the registration itself.
                  ++ wsinc5 interpolation is highly accurate and should
                       reduce the smoothing artifacts from lower
                       order interpolation methods (which are most
                       visible if you interpolate an EPI time series
                       to high resolution and then make an image of
                       the voxel-wise variance).
                  ++ On my Intel-based Mac, it takes about 2.5 s to do
                       wsinc5 interpolation, per 1 million voxels output.
                       For comparison, quintic interpolation takes about
                       0.3 s per 1 million voxels: 8 times faster than wsinc5.
                  ++ The '5' refers to the width of the sinc interpolation
                       weights: plus/minus 5 grid points in each direction
                       (this is a tensor product interpolation, for speed).

TECHNICAL OPTIONS (used for fine control of the program):
=================
 -nmatch nnn = Use at most 'nnn' scattered points to match the
               datasets.  The smaller nnn is, the faster the matching
               algorithm will run; however, accuracy may be bad if
               nnn is too small.  If you end the 'nnn' value with the
               '%' character, then that percentage of the base's
               voxels will be used.
               [Default == 47% of voxels in the weight mask]

 -nopad      = Do not use zero-padding on the base image.
               [Default == zero-pad, if needed; -verb shows how much]

 -conv mmm   = Convergence test is set to 'mmm' millimeters.
               This doesn't mean that the results will be accurate
               to 'mmm' millimeters!  It just means that the program
               stops trying to improve the alignment when the optimizer
               (NEWUOA) reports it has narrowed the search radius
               down to this level.  [Default == 0.05 mm]

 -verb       = Print out verbose progress reports.
               [Using '-VERB' will give even more prolix reports.]
 -quiet      = Don't print out verbose stuff.
 -usetemp    = Write intermediate stuff to disk, to economize on RAM.
               Using this will slow the program down, but may make it
               possible to register datasets that need lots of space.
       **N.B.: Temporary files are written to the directory given
               in environment variable TMPDIR, or in /tmp, or in ./
               (preference in that order).  If the program crashes,
               these files are named TIM_somethingrandom, and you
               may have to delete them manually. (TIM=Temporary IMage)
       **N.B.: If the program fails with a 'malloc failure' type of
               message, then try '-usetemp' (malloc=memory allocator).
       **N.B.: If you use '-verb', then memory usage is printed out
               at various points along the way.
 -nousetemp  = Don't use temporary workspace on disk [the default].

 -check kkk  = After cost functional optimization is done, start at the
               final parameters and RE-optimize using the new cost
               function 'kkk'.  If the results are too different, a
               warning message will be printed.  However, the final
               parameters from the original optimization will be
               used to create the output dataset. Using '-check'
               increases the CPU time, but can help you feel sure
               that the alignment process did not go wild and crazy.
               [Default == no check == don't worry, be happy!]
       **N.B.: You can put more than one function after '-check', as in
                 -nmi -check mi hel crU crM
               to register with Normalized Mutual Information, and
               then check the results against 4 other cost functionals.
       **N.B.: On the other hand, some cost functionals give better
               results than others for specific problems, and so
               a warning that 'mi' was significantly different than
               'hel' might not actually mean anything (e.g.).

 ** PARAMETERS THAT AFFECT THE COST OPTIMIZATION STRATEGY **
 -onepass    = Use only the refining pass -- do not try a coarse
               resolution pass first.  Useful if you know that only
               small amounts of image alignment are needed.
               [The default is to use both passes.]
 -twopass    = Use a two pass alignment strategy, first searching for
               a large rotation+shift and then refining the alignment.
               [Two passes are used by default for the first sub-brick]
               [in the source dataset, and then one pass for the others.]
               ['-twopass' will do two passes for ALL source sub-bricks.]
 -twoblur rr = Set the blurring radius for the first pass to 'rr'
               millimeters.  [Default == 11 mm]
       **N.B.: You may want to change this from the default if
               your voxels are unusually small or unusually large
               (e.g., outside the range 1-4 mm on each axis).
 -twofirst   = Use -twopass on the first image to be registered, and
               then on all subsequent images from the source dataset,
               use results from the first image's coarse pass to start
               the fine pass.
               (Useful when there may be large motions between the   )
               (source and the base, but only small motions within   )
               (the source dataset itself; since the coarse pass can )
               (be slow, doing it only once makes sense in this case.)
       **N.B.: [-twofirst is on by default; '-twopass' turns it off.]
 -twobest bb = In the coarse pass, use the best 'bb' set of initial
               points to search for the starting point for the fine
               pass.  If bb==0, then no search is made for the best
               starting point, and the identity transformation is
               used as the starting point.  [Default=4; min=0 max=7]
       **N.B.: Setting bb=0 will make things run faster, but less reliably.
 -fineblur x = Set the blurring radius to use in the fine resolution
               pass to 'x' mm.  A small amount (1-2 mm?) of blurring at
               the fine step may help with convergence, if there is
               some problem.  [Default == 0 mm]
   **NOTES ON
   **STRATEGY: * If you expect only small-ish (< 2 voxels?) image movement,
                 then using '-onepass' or '-twobest 0' makes sense.
               * If you expect large-ish image movements, then do not
                 use '-onepass' or '-twobest 0'; the purpose of the
                 '-twobest' parameter is to search for large initial
                 rotations/shifts with which to start the coarse
                 optimization round.
               * If you have multiple sub-bricks in the source dataset,
                 then the default '-twofirst' makes sense if you don't expect
                 large movements WITHIN the source, but expect large motions
                 between the source and base.

 -cmass        = Use the center-of-mass calculation to bracket the shifts.
                   [This option is OFF by default]
                 If given in the form '-cmass+xy' (for example), means to
                 do the CoM calculation in the x- and y-directions, but
                 not the z-direction.
 -nocmass      = Don't use the center-of-mass calculation. [The default]
                  (You would not want to use the C-o-M calculation if the  )
                  (source sub-bricks have very different spatial locations,)
                  (since the source C-o-M is calculated from all sub-bricks)
 **EXAMPLE: You have a limited coverage set of axial EPI slices you want to
            register into a larger head volume (after 3dSkullStrip, of course).
            In this case, '-cmass+xy' makes sense, allowing CoM adjustment
            along the x = R-L and y = A-P directions, but not along the
            z = I-S direction, since the EPI doesn't cover the whole brain
            along that axis.

 -autoweight = Compute a weight function using the 3dAutomask
               algorithm plus some blurring of the base image.
       **N.B.: '-autoweight+100' means to zero out all voxels
                 with values below 100 before computing the weight.
               '-autoweight**1.5' means to compute the autoweight
                 and then raise it to the 1.5-th power (e.g., to
                 increase the weight of high-intensity regions).
               These two processing steps can be combined, as in
                 '-autoweight+100**1.5'
       **N.B.: Some cost functionals do not allow -autoweight, and
               will use -automask instead.  A warning message
               will be printed if you run into this situation.
               If a clip level '+xxx' is appended to '-autoweight',
               then the conversion into '-automask' will NOT happen.
               Thus, using a small positive '+xxx' can be used trick
               -autoweight into working on any cost functional.
 -automask   = Compute a mask function, which is like -autoweight,
               but the weight for a voxel is set to either 0 or 1.
       **N.B.: '-automask+3' means to compute the mask function, and
               then dilate it outwards by 3 voxels (e.g.).
 -autobox    = Expand the -automask function to enclose a rectangular
               box that holds the irregular mask.
       **N.B.: This is the default mode of operation!
               For intra-modality registration, '-autoweight' may be better!
             * If the cost functional is 'ls', then '-autoweight' will be
               the default, instead of '-autobox'.
 -nomask     = Don't compute the autoweight/mask; if -weight is not
               also used, then every voxel will be counted equally.
 -weight www = Set the weighting for each voxel in the base dataset;
               larger weights mean that voxel counts more in the cost
               function.
       **N.B.: The weight dataset must be defined on the same grid as
               the base dataset.
       **N.B.: Even if a method does not allow -autoweight, you CAN
               use a weight dataset that is not 0/1 valued.  The
               risk is yours, of course (!*! as always in AFNI !*!).
 -wtprefix p = Write the weight volume to disk as a dataset with
               prefix name 'p'.  Used with '-autoweight/mask', this option
               lets you see what voxels were important in the algorithm.

    Method  Allows -autoweight
    ------  ------------------
     ls     YES
     mi     NO
     crM    YES
     nmi    NO
     hel    NO
     crA    YES
     crU    YES

 -source_mask sss = Mask the source (input) dataset, using 'sss'.
 -source_automask = Automatically mask the source dataset.
                      [By default, all voxels in the source]
                      [dataset are used in the matching.   ]
            **N.B.: You can also use '-source_automask+3' to dilate
                    the default source automask outward by 3 voxels.

 -warp xxx   = Set the warp type to 'xxx', which is one of
                 shift_only         *OR* sho =  3 parameters
                 shift_rotate       *OR* shr =  6 parameters
                 shift_rotate_scale *OR* srs =  9 parameters
                 affine_general     *OR* aff = 12 parameters
               [Default = affine_general, which includes image]
               [      shifts, rotations, scaling, and shearing]

 -warpfreeze = Freeze the non-rigid body parameters (those past #6)
               after doing the first sub-brick.  Subsequent volumes
               will have the same spatial distortions as sub-brick #0,
               plus rigid body motions only.

 -replacebase   = If the source has more than one sub-brick, and this
                  option is turned on, then after the #0 sub-brick is
                  aligned to the base, the aligned #0 sub-brick is used
                  as the base image for subsequent source sub-bricks.

 -replacemeth m = After sub-brick #0 is aligned, switch to method 'm'
                  for later sub-bricks.  For use with '-replacebase'.

 -EPI        = Treat the source dataset as being composed of warped
               EPI slices, and the base as comprising anatomically
               'true' images.  Only phase-encoding direction image
               shearing and scaling will be allowed with this option.
       **N.B.: For most people, the base dataset will be a 3dSkullStrip-ed
               T1-weighted anatomy (MPRAGE or SPGR).  If you don't remove
               the skull first, the EPI images (which have little skull
               visible due to fat-suppression) might expand to fit EPI
               brain over T1-weighted skull.
       **N.B.: Usually, EPI datasets don't have as complete slice coverage
               of the brain as do T1-weighted datasets.  If you don't use
               some option (like '-EPI') to suppress scaling in the slice-
               direction, the EPI dataset is likely to stretch the slice
               thicknesss to better 'match' the T1-weighted brain coverage.
       **N.B.: '-EPI' turns on '-warpfreeze -replacebase'.
               You can use '-nowarpfreeze' and/or '-noreplacebase' AFTER the
               '-EPI' on the command line if you do not want these options used.

 -parfix n v   = Fix parameter #n to be exactly at value 'v'.
 -parang n b t = Allow parameter #n to range only between 'b' and 't'.
                 If not given, default ranges are used.
 -parini n v   = Initialize parameter #n to value 'v', but then
                 allow the algorithm to adjust it.
         **N.B.: Multiple '-par...' options can be used, to constrain
                 multiple parameters.
         **N.B.: -parini has no effect if -twopass is used, since
                 the -twopass algorithm carries out its own search
                 for initial parameters.

 -maxrot dd    = Allow maximum rotation of 'dd' degrees.  Equivalent
                 to '-parang 4 -dd dd -parang 5 -dd dd -parang 6 -dd dd'
                 [Default=30 degrees]
 -maxshf dd    = Allow maximum shift of 'dd' millimeters.  Equivalent
                 to '-parang 1 -dd dd -parang 2 -dd dd -parang 3 -dd dd'
                 [Default=33% of the size of the base image]
         **N.B.: This max shift setting is relative to the center-of-mass
                 shift, if the '-cmass' option is used.
 -maxscl dd    = Allow maximum scaling factor to be 'dd'.  Equivalent
                 to '-parang 7 1/dd dd -parang 8 1/dd dd -paran2 9 1/dd dd'
                 [Default=1.2=image can go up or down 20% in size]

 -master mmm = Write the output dataset on the same grid as dataset
               'mmm'.  If this option is NOT given, the base dataset
               is the master.
       **N.B.: 3dAllineate transforms the source dataset to be 'similar'
               to the base image.  Therefore, the coordinate system
               of the master dataset is interpreted as being in the
               reference system of the base image.  It is thus vital
               that these finite 3D volumes overlap, or you will lose data!
       **N.B.: If 'mmm' is the string 'SOURCE', then the source dataset
               is used as the master for the output dataset grid.
               You can also use 'BASE', which is of course the default.

 -mast_dxyz del = Write the output dataset using grid spacings of
  *OR*            'del' mm.  If this option is NOT given, then the
 -newgrid del     grid spacings in the master dataset will be used.
                  This option is useful when registering low resolution
                  data (e.g., EPI time series) to high resolution
                  datasets (e.g., MPRAGE) where you don't want to
                  consume vast amounts of disk space interpolating
                  the low resolution data to some artificially fine
                  (and meaningless) spatial grid.

----------------------------------------------
DEFINITION OF AFFINE TRANSFORMATION PARAMETERS
----------------------------------------------
The 3x3 spatial transformation matrix is calculated as [S][D][U],
where [S] is the shear matrix,
      [D] is the scaling matrix, and
      [U] is the rotation (proper orthogonal) matrix.
Thes matrices are specified in DICOM-ordered (x=-R+L,y=-A+P,z=-I+S)
coordinates as:

  [U] = [Rotate_y(param#6)] [Rotate_x(param#5)] [Rotate_z(param #4)]
        (angles are in degrees)

  [D] = diag( param#7 , param#8 , param#9 )

        [    1        0     0 ]        [ 1 param#10 param#11 ]
  [S] = [ param#10    1     0 ]   OR   [ 0    1     param#12 ]
        [ param#11 param#12 1 ]        [ 0    0        1     ]

The shift vector comprises parameters #1, #2, and #3.

The goal of the program is to find the warp parameters such that
   I([x]_warped) 'is similar to' J([x]_in)
as closely as possible in some sense of 'similar', where J(x) is the
base image, and I(x) is the source image.

Using '-parfix', you can specify that some of these parameters
are fixed.  For example, '-shift_rotate_scale' is equivalent
'-affine_general -parfix 10 0 -parfix 11 0 -parfix 12 0'.
Don't even think of using the '-parfix' option unless you grok
this example!

----------- Special Note for the '-EPI' Option's Coordinates -----------
In this case, the parameters above are with reference to coordinates
  x = frequency encoding direction (by default, first axis of dataset)
  y = phase encoding direction     (by default, second axis of dataset)
  z = slice encoding direction     (by default, third axis of dataset)
This option lets you freeze some of the warping parameters in ways that
make physical sense, considering how echo-planar images are acquired.
The x- and z-scaling parameters are disabled, and shears will only affect
the y-axis.  Thus, there will be only 9 free parameters when '-EPI' is
used.  If desired, you can use a '-parang' option to allow the scaling
fixed parameters to vary (put these after the '-EPI' option):
  -parang 7 0.833 1.20     to allow x-scaling
  -parang 9 0.833 1.20     to allow z-scaling
You could also fix some of the other parameters, if that makes sense
in your situation; for example, to disable out of slice rotations:
  -parfix 5 0  -parfix 6 0
and to disable out of slice translation:
  -parfix 3 0
NOTE WELL: If you use '-EPI', then the output warp parameters (e.g., in
           '-1Dparam_save') apply to the (freq,phase,slice) xyz coordinates,
           NOT to the DICOM xyz coordinates, so equivalent transformations
           will be expressed with different sets of parameters entirely
           than if you don't use '-EPI'!  This comment does NOT apply
           to the output of '-1Dmatrix_save', since that matrix is
           defined relative to the RAI (DICOM) spatial coordinates.

*********** CHANGING THE ORDER OF MATRIX APPLICATION ***********

  -SDU or -SUD }= Set the order of the matrix multiplication
  -DSU or -DUS }= for the affine transformations:
  -USD or -UDS }=   S = triangular shear (params #10-12)
                    D = diagonal scaling matrix (params #7-9)
                    U = rotation matrix (params #4-6)
                  Default order is '-SDU', which means that
                  the U matrix is applied first, then the
                  D matrix, then the S matrix.

  -Supper      }= Set the S matrix to be upper or lower
  -Slower      }= triangular [Default=lower triangular]

  -ashift OR   }= Apply the shift parameters (#1-3) after OR
  -bshift      }= before the matrix transformation. [Default=after]

            ==================================================
        ===== RWCox - September 2006 - Live Long and Prosper =====
            ==================================================

         ********************************************************
        *** From Webster's Dictionary: Allineate == 'to align' ***
         ********************************************************

===========================================================================
                TOP SECRET HIDDEN OPTIONS (-HELP or -POMOC)
---------------------------------------------------------------------------
                ** N.B.: Most of these are experimental! **
===========================================================================

 -num_rtb n  = At the beginning of the fine pass, the best set of results
               from the coarse pass are 'refined' a little by further
               optimization, before the single best one is chosen for
               for the final fine optimization.
              * This option sets the maximum number of cost functional
                evaluations to be used (for each set of parameters)
                in this step.
              * The default is 99; a larger value will take more CPU
                time but may give more robust results.
              * If you want to skip this step entirely, use '-num_rtb 0'.
                then, the best of the coarse pass results is taken
                straight to the final optimization passes.
       **N.B.: If you use '-VERB', you will see that one extra case
               is involved in this initial fine refinement step; that
               case is starting with the identity transformation, which
               helps insure against the chance that the coarse pass
               optimizations ran totally amok.
 -nocast     = By default, parameter vectors that are too close to the
               best one are cast out at the end of the coarse pass
               refinement process. Use this option if you want to keep
               them all for the fine resolution pass.
 -norefinal  = Do NOT re-start the fine iteration step after it
               has converged.  The default is to re-start it, which
               usually results in a small improvement to the result
               (at the cost of CPU time).  This re-start step is an
               an attempt to avoid a local minimum trap.  It is usually
               not necessary, but sometimes helps.

 -savehist sss = Save start and final 2D histograms as PGM
                 files, with prefix 'sss' (cost: cr mi nmi hel).
                * if filename contains 'FF', floats is written
                * these are the weighted histograms!
                * -savehist will also save histogram files when
                  the -allcost evaluations takes place
                * this option is mostly useless unless '-histbin' is
                  also used
 -median       = Smooth with median filter instead of Gaussian blur.
                 (Somewhat slower, and not obviously useful.)
 -powell m a   = Set the Powell NEWUOA dimensional parameters to
                 'm' and 'a' (cf. source code in powell_int.c).
                 The number of points used for approximating the
                 cost functional is m*N+a, where N is the number
                 of parameters being optimized.  The default values
                 are m=2 and a=3.  Larger values will probably slow
                 the program down for no good reason.
 -target ttt   = Same as '-source ttt'.  In the earliest versions,
                 what I now call the 'source' dataset was called the
                 'target' dataset:
                    Try to remember the kind of September (2006)
                    When life was slow and oh so mellow
                    Try to remember the kind of September
                    When grass was green and source was target.
 -Xwarp       =} Change the warp/matrix setup so that only the x-, y-, or z-
 -Ywarp       =} axis is stretched & sheared.  Useful for EPI, where 'X',
 -Zwarp       =} 'Y', or 'Z' corresponds to the phase encoding direction.
 -FPS fps      = Generalizes -EPI to arbitrary permutation of directions.
 -histpow pp   = By default, the number of bins in the histogram used
                 for calculating the Hellinger, Mutual Information, and
                 Correlation Ratio statistics is n^(1/3), where n is
                 the number of data points.  You can change that exponent
                 to 'pp' with this option.
 -histbin nn   = Or you can just set the number of bins directly to 'nn'.
 -eqbin   nn   = Use equalized marginal histograms with 'nn' bins.
 -clbin   nn   = Use 'nn' equal-spaced bins except for the bot and top,
                 which will be clipped (thus the 'cl').  If nn is 0, the
                 program will pick the number of bins for you.
                 **N.B.: '-clbin 0' is now the default [25 Jul 2007];
                         if you want the old all-equal-spaced bins, use
                         '-histbin 0'.
                 **N.B.: '-clbin' only works when the datasets are
                         non-negative; any negative voxels in either
                         the input or source volumes will force a switch
                         to all equal-spaced bins.
 -wtmrad  mm   = Set autoweight/mask median filter radius to 'mm' voxels.
 -wtgrad  gg   = Set autoweight/mask Gaussian filter radius to 'gg' voxels.
 -nmsetup nn   = Use 'nn' points for the setup matching [default=98756]
 -ignout       = Ignore voxels outside the warped source dataset.

 -blok bbb     = Blok definition for the 'lp?' (Local Pearson) cost
                 functions: 'bbb' is one of
                   'BALL(r)' or 'CUBE(r)' or 'RHDD(r)' or 'TOHD(r)'
                 corresponding to
                   spheres or cubes or rhombic dodecahedra or
                   truncated octahedra
                 where 'r' is the size parameter in mm.
                 [Default is 'RHDD(6.54321)' (rhombic dodecahedron)]

 -allcost        = Compute ALL available cost functionals and print them
                   at various points.
 -allcostX       = Compute and print ALL available cost functionals for the
                   un-warped inputs, and then quit.
 -allcostX1D p q = Compute ALL available cost functionals for the set of
                   parameters given in the 1D file 'p' (12 values per row),
                   write them to the 1D file 'q', then exit. (For you, Zman)
                  * N.B.: If -fineblur is used, that amount of smoothing
                          will be applied prior to the -allcostX evaluations.

===========================================================================

 Hidden experimental cost functionals:
   sp   *OR*  spearman        = Spearman [rank] Correlation
   je   *OR*  jointentropy    = Joint Entropy [H(b,s)]
   lss  *OR*  signedPcor      = Signed Pearson Correlation
   lpc  *OR*  localPcorSigned = Local Pearson Correlation Signed
   lpa  *OR*  localPcorAbs    = Local Pearson Correlation Abs
   ncd  *OR*  NormCompDist    = Normalized Compression Distance

 Cost functional descriptions (for use with -allcost output):
   ls  :: 1 - abs(Pearson correlation coefficient)
   sp  :: 1 - abs(Spearman correlation coefficient)
   mi  :: - Mutual Information = H(base,source)-H(base)-H(source)
   crM :: 1 - abs[ CR(base,source) * CR(source,base) ]
   nmi :: 1/Normalized MI = H(base,source)/[H(base)+H(source)]
   je  :: H(base,source) = joint entropy of image pair
   hel :: - Hellinger distance(base,source)
   crA :: 1 - abs[ CR(base,source) + CR(source,base) ]
   crU :: CR(source,base) = Var(source|base) / Var(source)
   lss :: Pearson correlation coefficient between image pair
   lpc :: nonlinear average of Pearson cc over local neighborhoods
   lpa :: 1 - abs(lpc)
   ncd :: mutual compressibility (via zlib) -- doesn't work yet

 * N.B.: Some cost functional values (as printed out herein)
   are negated (e.g., 'hel', 'mi'), so that the best image
   alignment will be found when the cost is minimized.  See
   the descriptions above and the references below for more
   details for each functional.

 * For more information about the 'lpc' functional, see
     ZS Saad, DR Glen, G Chen, MS Beauchamp, R Desai, RW Cox.
       A new method for improving functional-to-structural
       MRI alignment using local Pearson correlation.
       NeuroImage 44: 839-848, 2009.
     http://dx.doi.org/10.1016/j.neuroimage.2008.09.037
     http://afni.nimh.nih.gov/sscc/rwcox/papers/LocalPearson2009.pdf
   The '-blok' option can be used to control the regions
   (size and shape) used to compute the local correlations.
 *** Using the 'lpc' functional wisely requires the use of
     a proper weight volume.  We HIGHLY recommend you use
     the align_epi_anat.py script if you want to use this
     cost functional!  Otherwise, you are likely to get
     less than optimal results (and then swear at us unjustly).

 * For more information about the 'cr' functionals, see
     http://en.wikipedia.org/wiki/Correlation_ratio
   Note that CR(x,y) is not the same as CR(y,x), which
   is why there are symmetrized versions of it available.

 * For more information about the 'mi', 'nmi', and 'je'
   cost functionals, see
     http://en.wikipedia.org/wiki/Mutual_information
     http://en.wikipedia.org/wiki/Joint_entropy
     http://www.cs.jhu.edu/~cis/cista/746/papers/mutual_info_survey.pdf

 * For more information about the 'hel' functional, see
     http://en.wikipedia.org/wiki/Hellinger_distance

 * Some cost functionals (e.g., 'mi', 'cr', 'hel') are
   computed by creating a 2D joint histogram of the
   base and source image pair.  Various options above
   (e.g., '-histbin', etc.) can be used to control the
   number of bins used in the histogram on each axis.
   (If you care to control the program in such detail!)

 * Minimization of the chosen cost functional is done via
   the NEWUOA software, described in detail in
     MJD Powell. 'The NEWUOA software for unconstrained
       optimization without derivatives.' In: GD Pillo,
       M Roma (Eds), Large-Scale Nonlinear Optimization.
       Springer, 2006.
     http://www.damtp.cam.ac.uk/user/na/NA_papers/NA2004_08.pdf

===========================================================================

 -nwarp type = Experimental nonlinear warp:
              * At present, the only 'type' is 'bilinear',
                as in 3dWarpDrive, with 39 parameters.
              * I plan to implement more complicated nonlinear
                warps in the future, someday ....
              * -nwarp can only be applied to a source dataset
                that has a single sub-brick!
              * -1Dparam_save and -1Dparam_apply work with
                bilinear warps; see the Notes for more information.
-nwarp NOTES:
-------------
* -nwarp is slow!
* Check the results to make sure the optimizer didn't run amok!
   (You should always do this with any registration software.)
* If you use -1Dparam_save, then you can apply the bilinear
   warp to another dataset using -1Dparam_apply in a later
   3dAllineate run. To do so, use '-nwarp bilinear' in both
   runs, so that the program knows what the extra parameters
   in the file are to be used for.
  ++ 43 values are saved in 1 row of the param file.
  ++ The first 12 are the affine parameters
  ++ The next 27 are the D1,D2,D3 matrix parameters.
  ++ The final 'extra' 4 values are used to specify
      the center of coordinates (vector Xc below), and a
      pre-computed scaling factor applied to parameters #13..39.
* Bilinear warp formula:
   Xout = inv[ I + {D1 (Xin-Xc) | D2 (Xin-Xc) | D3 (Xin-Xc)} ] [ A Xin ]
  where Xin  = input vector  (base dataset coordinates)
        Xout = output vector (source dataset coordinates)
        Xc   = center of coordinates used for nonlinearity
               (will be the center of the base dataset volume)
        A    = matrix representing affine transformation (12 params)
        I    = 3x3 identity matrix
    D1,D2,D3 = three 3x3 matrices (the 27 'new' parameters)
               * when all 27 parameters == 0, warp is purely affine
     {P|Q|R} = 3x3 matrix formed by adjoining the 3-vectors P,Q,R
    inv[...] = inverse 3x3 matrix of stuff inside '[...]'
* The inverse of a bilinear transformation is another bilinear
   transformation.  Someday, I may write a program that will let
   you compute that inverse transformation, so you can use it for
   some cunning and devious purpose.
* If you expand the inv[...] part of the above formula in a 1st
   order Taylor series, you'll see that a bilinear warp is basically
   a quadratic warp, with the additional feature that its inverse
   is directly computable (unlike a pure quadratic warp).
* Is '-nwarp bilinear' useful?  Try it and tell me!

===========================================================================

 =========================================================================
* This binary version of 3dAllineate is NOT compiled using OpenMP, a
   semi-automatic parallelizer software toolkit, which splits the work
   across multiple CPUs/cores on the same shared memory computer.
* However, the source code is modified for OpenMP, and can be compiled
   with an OpenMP-capable compiler, such as gcc 4.2, Intel's icc, and
   Sun Studio.
* If you wish to compile this program with OpenMP, see the man page for
   your C compiler, and (if needed) consult the AFNI message board, and
    http://afni.nimh.nih.gov/pub/dist/doc/misc/OpenMP.html

++ Compile date = Nov  5 2009




AFNI program: 3dANALYZEtoAFNI
** DON'T USE THIS PROGRAM!  REALLY!
USE 3dcopy OR to3d INSTEAD.

IF YOU CHOOSE TO USE IT ANYWAY, PERHAPS
BECAUSE IT WORKS BETTER ON YOUR 12th
CENTURY PLANTAGENET ANALYZE FILES,
ADD THE OPTION -OK TO YOUR COMMAND
LINE.

Usage: 3dANALYZEtoAFNI [options] file1.hdr file2.hdr ...
This program constructs a 'volumes' stored AFNI dataset
from the ANALYZE-75 files file1.img file2.img ....
In this type of dataset, there is only a .HEAD file; the
.BRIK file is replaced by the collection of .img files.
- Other AFNI programs can read (but not write) this type
  of dataset.
- The advantage of using this type of dataset vs. one created
   with to3d is that you don't have to duplicate the image data
   into a .BRIK file, thus saving disk space.
- The disadvantage of using 'volumes' for a multi-brick dataset
   is that all the .img files must be kept with the .HEAD file
   if you move the dataset around.
- The .img files must be in the same directory as the .HEAD file.
- Note that you put the .hdr files on the command line, but it is
   the .img files that will be named in the .HEAD file.
- After this program is run, you must keep the .img files with
   the output .HEAD file.  AFNI doesn't need the .hdr files, but
   other programs (e.g., FSL, SPM) will want them as well.

Options:
 -prefix ppp   = Save the dataset with the prefix name 'ppp'.
                  [default='a2a']
 -view vvv     = Save the dataset in the 'vvv' view, where
                  'vvv' is one of 'orig', 'acpc', or 'tlrc'.
                  [default='orig']

 -TR ttt       = For multi-volume datasets, create it as a
                  3D+time dataset with TR set to 'ttt'.
 -fbuc         = For multi-volume datasets, create it as a
                  functional bucket dataset.
 -abuc         = For multi-volume datasets, create it as an
                  anatomical bucket dataset.
   ** If more than one ANALYZE file is input, and none of the
       above options is given, the default is as if '-TR 1s'
       was used.
   ** For single volume datasets (1 ANALYZE file input), the
       default is '-abuc'.

 -geomparent g = Use the .HEAD file from dataset 'g' to set
                  the geometry of this dataset.
   ** If you don't use -geomparent, then the following options
       can be used to specify the geometry of this dataset:
 -orient code  = Tells the orientation of the 3D volumes.  The code
                  must be 3 letters, one each from the pairs {R,L}
                  {A,P} {I,S}.  The first letter gives the orientation
                  of the x-axis, the second the orientation of the
                  y-axis, the third the z-axis:
                   R = right-to-left         L = left-to-right
                   A = anterior-to-posterior P = posterior-to-anterior
                   I = inferior-to-superior  S = superior-to-inferior
 -zorigin dz   = Puts the center of the 1st slice off at the
                  given distance ('dz' in mm).  This distance
                  is in the direction given by the corresponding
                  letter in the -orient code.  For example,
                    -orient RAI -zorigin 30
                  would set the center of the first slice at
                  30 mm Inferior.
   ** If the above options are NOT used to specify the geometry
       of the dataset, then the default is '-orient RAI', and the
       z origin is set to center the slices about z=0.

 It is likely that you will want to patch up the .HEAD file using
 program 3drefit.

 -- RWCox - June 2002.


** DON'T USE THIS PROGRAM!  REALLY!
USE 3dcopy OR to3d INSTEAD.

IF YOU CHOOSE TO USE IT ANYWAY, PERHAPS
BECAUSE IT WORKS BETTER ON YOUR 12th
CENTURY PLANTAGENET ANALYZE FILES,
ADD THE OPTION -OK TO YOUR COMMAND
LINE.-- KRH - April 2005.




AFNI program: 3dAnatNudge
Usage: 3dAnatNudge [options]
Moves the anat dataset around to best overlap the epi dataset.

OPTIONS:
 -anat aaa   = aaa is an 'scalped' (3dIntracranial) high-resolution
                anatomical dataset [a mandatory option]
 -epi eee    = eee is an EPI dataset [a mandatory option]
                The first [0] sub-brick from each dataset is used,
                unless otherwise specified on the command line.
 -prefix ppp = ppp is the prefix of the output dataset;
                this dataset will differ from the input only
                in its name and its xyz-axes origin
                [default=don't write new dataset]
 -step sss   = set the step size to be sss times the voxel size
                in the anat dataset [default=1.0]
 -x nx       = search plus and minus nx steps along the EPI
 -y ny          dataset's x-axis; similarly for ny and the
 -z nz          y-axis, and for nz and the z-axis
                [default: nx=1 ny=5 nz=0]
 -verb       = print progress reports (this is a slow program)

NOTES
*Systematically moves the anat dataset around and find the shift
  that maximizes overlap between the anat dataset and the EPI
  dataset.  No rotations are done.
*Note that if you use -prefix, a new dataset will be created that
  is a copy of the anat, except that it's origin will be shifted
  and it will have a different ID code than the anat.  If you want
  to use this new dataset as the anatomy parent for the EPI
  datasets, you'll have to use
    3drefit -apar ppp+orig eee1+orig eee2+orig ...
*If no new dataset is written (no -prefix option), then you
  can use the 3drefit command emitted at the end to modify
  the origin of the anat dataset.  (Assuming you trust the
  results - visual inspection is recommended!)
*The reason the default search grid is mostly along the EPI y-axis
  is that axis is usually the phase-encoding direction, which is
  most subject to displacement due to off-resonance effects.
*Note that the time this program takes will be proportional to
  (2*nx+1)*(2*ny+1)*(2*nz+1), so using a very large search grid
  will result in a very large usage of CPU time.
*Recommended usage:
 + Make a 1-brick function volume from a typical EPI dataset:
     3dbucket -fbuc -prefix epi_fb epi+orig
 + Use 3dIntracranial to scalp a T1-weighted volume:
     3dIntracranial -anat spgr+orig -prefix spgr_st
 + Use 3dAnatNudge to produce a shifted anat dataset
     3dAnatNudge -anat spgr_st+orig -epi epi_fb+orig -prefix spgr_nudge
 + Start AFNI and look at epi_fb overlaid in color on the
    anat datasets spgr_st+orig and spgr_nudge+orig, to see if the
    nudged dataset seems like a better fit.
 + Delete the nudged dataset spgr_nudge.
 + If the nudged dataset DOES look better, then apply the
    3drefit command output by 3dAnatNudge to spgr+orig.
*Note that the x-, y-, and z-axes for the epi and anat datasets
  may point in different directions (e.g., axial SPGR and
  coronal EPI).  The 3drefit command applies to the anat
  dataset, NOT to the EPI dataset.
*If the program runs successfully, the only thing set to stdout
  will be the 3drefit command string; all other messages go to
  stderr.  This can be useful if you want to capture the command
  to a shell variable and then execute it, as in the following
  csh fragment:
     set cvar = `3dAnatNudge ...`
     if( $cvar[1] == "3drefit" ) $cvar
  The test on the first sub-string in cvar allows for the
  possibility that the program fails, or that the optimal
  nudge is zero.

++ Compile date = Nov  5 2009




AFNI program: 3dAnhist
Usage: 3dAnhist [options] dataset
Input dataset is a T1-weighted high-res of the brain (shorts only).
Output is a list of peaks in the histogram, to stdout, in the form
  ( datasetname #peaks peak1 peak2 ... )
In the C-shell, for example, you could do
  set anhist = `3dAnhist -q -w1 dset+orig`
Then the number of peaks found is in the shell variable $anhist[2].

Options:
  -q  = be quiet (don't print progress reports)
  -h  = dump histogram data to Anhist.1D and plot to Anhist.ps
  -F  = DON'T fit histogram with stupid curves.
  -w  = apply a Winsorizing filter prior to histogram scan
         (or -w7 to Winsorize 7 times, etc.)
  -2  = Analyze top 2 peaks only, for overlap etc.

  -label xxx = Use 'xxx' for a label on the Anhist.ps plot file
                instead of the input dataset filename.
  -fname fff = Use 'fff' for the filename instead of 'Anhist'.

If the '-2' option is used, AND if 2 peaks are detected, AND if
the -h option is also given, then stdout will be of the form
  ( datasetname 2 peak1 peak2 thresh CER CJV count1 count2 count1/count2)
where 2      = number of peaks
      thresh = threshold between peak1 and peak2 for decision-making
      CER    = classification error rate of thresh
      CJV    = coefficient of joint variation
      count1 = area under fitted PDF for peak1
      count2 = area under fitted PDF for peak2
      count1/count2 = ratio of the above quantities
NOTA BENE
---------
* If the input is a T1-weighted MRI dataset (the usual case), then
   peak 1 should be the gray matter (GM) peak and peak 2 the white
   matter (WM) peak.
* For the definitions of CER and CJV, see the paper
   Method for Bias Field Correction of Brain T1-Weighted Magnetic
   Resonance Images Minimizing Segmentation Error
   JD Gispert, S Reig, J Pascau, JJ Vaquero, P Garcia-Barreno,
   and M Desco, Human Brain Mapping 22:133-144 (2004).
* Roughly speaking, CER is the ratio of the overlapping area of the
   2 peak fitted PDFs to the total area of the fitted PDFS.  CJV is
   (sigma_GM+sigma_WM)/(mean_WM-mean_GM), and is a different, ad hoc,
   measurement of how much the two PDF overlap.
* The fitted PDFs are NOT Gaussians.  They are of the form
   f(x) = b((x-p)/w,a), where p=location of peak, w=width, 'a' is
   a skewness parameter between -1 and 1; the basic distribution
   is defined by b(x)=(1-x^2)^2*(1+a*x*abs(x)) for -1 < x < 1.

-- RWCox - November 2004

++ Compile date = Nov  5 2009




AFNI program: 3danisosmooth
Usage: 3danisosmooth [options] dataset
Smooths a dataset using an anisotropic smoothing technique.

The output dataset is preferentially smoothed to preserve edges.

Options :
  -prefix pname = Use 'pname' for output dataset prefix name.
  -iters nnn = compute nnn iterations (default=10)
  -2D = smooth a slice at a time (default)
  -3D = smooth through slices. Can not be combined with 2D option
  -mask dset = use dset as mask to include/exclude voxels
  -automask = automatically compute mask for dataset
    Can not be combined with -mask
  -viewer = show central axial slice image every iteration.
    Starts aiv program internally.
  -nosmooth = do not do intermediate smoothing of gradients
  -sigma1 n.nnn = assign Gaussian smoothing sigma before
    gradient computation for calculation of structure tensor.
    Default = 0.5
  -sigma2 n.nnn = assign Gaussian smoothing sigma after
    gradient matrix computation for calculation of structure tensor.
    Default = 1.0
  -deltat n.nnn = assign pseudotime step. Default = 0.25
  -savetempdata = save temporary datasets each iteration.
    Dataset prefixes are Gradient, Eigens, phi, Dtensor.
    Ematrix, Flux and Gmatrix are also stored for the first sub-brick.
    Each is overwritten each iteration
  -phiding = use Ding method for computing phi (default)
  -phiexp = use exponential method for computing phi
  -noneg = set negative voxels to 0
  -edgefraction n.nnn = adjust the fraction of the anisotropic
    component to be added to the original image. Can vary between
    0 and 1. Default =0.5
  -datum type = Coerce the output data to be stored as the given type
    which may be byte, short or float. [default=float]
  -matchorig - match datum type and clip min and max to match input data
  -help = print this help screen

References:
  Z Ding, JC Gore, AW Anderson, Reduction of Noise in Diffusion
   Tensor Images Using Anisotropic Smoothing, Mag. Res. Med.,
   53:485-490, 2005
  J Weickert, H Scharr, A Scheme for Coherence-Enhancing
   Diffusion Filtering with Optimized Rotation Invariance,
   CVGPR Group Technical Report at the Department of Mathematics
   and Computer Science,University of Mannheim,Germany,TR 4/2000.
  J.Weickert,H.Scharr. A scheme for coherence-enhancing diffusion
   filtering with optimized rotation invariance. J Visual
   Communication and Image Representation, Special Issue On
   Partial Differential Equations In Image Processing,Comp Vision
   Computer Graphics, pages 103-118, 2002.
  Gerig, G., Kubler, O., Kikinis, R., Jolesz, F., Nonlinear
   anisotropic filtering of MRI data, IEEE Trans. Med. Imaging 11
   (2), 221-232, 1992.


INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dANOVA
++ 3dANOVA: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward
This program performs single factor Analysis of Variance (ANOVA)
on 3D datasets

---------------------------------------------------------------

Usage:
-----

3dANOVA
   -levels r                   : r = number of factor levels

   -dset 1 filename            : data set for factor level 1
         . . .. . .
   -dset 1 filename              data set for factor level 1
         . . .. . .
   -dset r filename              data set for factor level r
         . . .. . .
   -dset r filename              data set for factor level r

  [-voxel num]                 : screen output for voxel # num

  [-diskspace]                 : print out disk space required for
                                 program execution

  [-mask mset]                 : use sub-brick #0 of dataset 'mset'
                                 to define which voxels to process

  [-debug level]               : request extra output

The following commands generate individual AFNI 2-sub-brick datasets:
  (In each case, output is written to the file with the specified
   prefix file name.)

  [-ftr prefix]                : F-statistic for treatment effect

  [-mean i prefix]             : estimate of factor level i mean

  [-diff i j prefix]           : difference between factor levels

  [-contr c1...cr prefix]      : contrast in factor levels

Modified ANOVA computation options:    (December, 2005)

     ** For details, see http://afni.nimh.nih.gov/sscc/gangc/ANOVA_Mod.html

[-old_method]       request to perform ANOVA using the previous
                    functionality (requires -OK, also)

[-OK]               confirm you understand that contrasts that
                    do not sum to zero have inflated t-stats, and
                    contrasts that do sum to zero assume sphericity
                    (to be used with -old_method)

[-assume_sph]       assume sphericity (zero-sum contrasts, only)

                    This allows use of the old_method for
                    computing contrasts which sum to zero (this
                    includes diffs, for instance).  Any contrast
                    that does not sum to zero is invalid, and
                    cannot be used with this option (such as
                    ameans).

The following command generates one AFNI 'bucket' type dataset:

  [-bucket prefix]             : create one AFNI 'bucket' dataset whose
                                 sub-bricks are obtained by
                                 concatenating the above output files;
                                 the output 'bucket' is written to file
                                 with prefix file name

N.B.: For this program, the user must specify 1 and only 1 sub-brick
      with each -dset command. That is, if an input dataset contains
      more than 1 sub-brick, a sub-brick selector must be used,
      e.g., -dset 2 'fred+orig[3]'

Example of 3dANOVA:
------------------

 Example is based on a study with one factor (independent variable)
 called 'Pictures', with 3 levels:
        (1) Faces, (2) Houses, and (3) Donuts

 The ANOVA is being conducted on the data of subjects Fred and Ethel:

 3dANOVA -levels 3                     \
         -dset 1 fred_Faces+tlrc       \
         -dset 1 ethel_Faces+tlrc      \
                                       \
         -dset 2 fred_Houses+tlrc      \
         -dset 2 ethel_Houses+tlrc     \
                                       \
         -dset 3 fred_Donuts+tlrc      \
         -dset 3 ethel_Donuts+tlrc     \
                                       \
         -ftr Pictures                 \
         -mean 1 Faces                 \
         -mean 2 Houses                \
         -mean 3 Donuts                \
         -diff 1 2 FvsH                \
         -diff 2 3 HvsD                \
         -diff 1 3 FvsD                \
         -contr  1  1 -1 FHvsD         \
         -contr -1  1  1 FvsHD         \
         -contr  1 -1  1 FDvsH         \
         -bucket fred_n_ethel_ANOVA

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.
---------------------------------------------------
Also see HowTo#5 - Group Analysis on the AFNI website:
http://afni.nimh.nih.gov/pub/dist/HOWTO/howto/ht05_group/html/index.shtml

-------------------------------------------------------------------------
STORAGE FORMAT:
---------------
The default output format is to store the results as scaled short
(16-bit) integers.  This truncantion might cause significant errors.
If you receive warnings that look like this:
  *+ WARNING: TvsF[0] scale to shorts misfit = 8.09% -- *** Beware
then you can force the results to be saved in float format by
defining the environment variable AFNI_FLOATIZE to be YES
before running the program.  For convenience, you can do this
on the command line, as in
  3dANOVA -DAFNI_FLOATIZE=YES ... other options ... 
Also see the following links:
 http://afni.nimh.nih.gov/pub/dist/doc/program_help/common_options.html
 http://afni.nimh.nih.gov/pub/dist/doc/program_help/README.environment.html

++ Compile date = Nov  5 2009




AFNI program: 3dANOVA2
++ 3dANOVA: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward
This program performs a two-factor Analysis of Variance (ANOVA)
on 3D datasets

-----------------------------------------------------------

Usage:

   3dANOVA2
      -type k              : type of ANOVA model to be used:
                              k=1  fixed effects model  (A and B fixed)    
                              k=2  random effects model (A and B random)   
                              k=3  mixed effects model  (A fixed, B random)

      -alevels a           : a = number of levels of factor A

      -blevels b           : b = number of levels of factor B

      -dset 1 1 filename   : data set for level 1 of factor A
                                      and level 1 of factor B
            . . .                           . . .
      -dset i j filename   : data set for level i of factor A
                                      and level j of factor B
            . . .                           . . .
      -dset a b filename   : data set for level a of factor A
                                      and level b of factor B

     [-voxel num]          : screen output for voxel # num

     [-diskspace]          : print out disk space required for
                             program execution

     [-mask mset]          : use sub-brick #0 of dataset 'mset'
                             to define which voxels to process


   The following commands generate individual AFNI 2-sub-brick datasets:
  (In each case, output is written to the file with the specified
   prefix file name.)

     [-ftr prefix]         : F-statistic for treatment effect

     [-fa prefix]          : F-statistic for factor A effect

     [-fb prefix]          : F-statistic for factor B effect

     [-fab prefix]         : F-statistic for interaction

     [-amean i prefix]     : estimate mean of factor A level i

     [-bmean j prefix]     : estimate mean of factor B level j

     [-xmean i j prefix]   : estimate mean of cell at level i of factor A,
                                                      level j of factor B

     [-adiff i j prefix]   : difference between levels i and j of factor A

     [-bdiff i j prefix]   : difference between levels i and j of factor B

     [-xdiff i j k l prefix]     : difference between cell mean at A=i,B=j
                                                  and cell mean at A=k,B=l

     [-acontr c1 ... ca prefix]  : contrast in factor A levels

     [-bcontr c1 ... cb prefix]  : contrast in factor B levels

     [-xcontr c11 ... c1b c21 ... c2b  ...  ca1 ... cab  prefix]
                                 : contrast in cell means


The following command generates one AFNI 'bucket' type dataset:

     [-bucket prefix]      : create one AFNI 'bucket' dataset whose
                             sub-bricks are obtained by concatenating
                             the above output files; the output 'bucket'
                             is written to file with prefix file name

Modified ANOVA computation options:    (December, 2005)

     ** These options apply to model type 3, only.
        For details, see http://afni.nimh.nih.gov/sscc/gangc/ANOVA_Mod.html

     [-old_method]        : request to perform ANOVA using the previous
                            functionality (requires -OK, also)

     [-OK]                : confirm you understand that contrasts that
                            do not sum to zero have inflated t-stats, and
                            contrasts that do sum to zero assume sphericity
                            (to be used with -old_method)

     [-assume_sph]        : assume sphericity (zero-sum contrasts, only)

                            This allows use of the old_method for
                            computing contrasts which sum to zero (this
                            includes diffs, for instance).  Any contrast
                            that does not sum to zero is invalid, and
                            cannot be used with this option (such as
                            ameans).

----------------------------------------------------------

 Example of 3dANOVA2:

      Example is based on a study with a 3 x 4 mixed factorial design:

              Factor 1 - DONUTS has 3 levels:
                         (1) chocolate, (2) glazed, (3) sugar

              Factor 2 - SUBJECTS, of which there are 4 in this analysis:
                         (1) fred, (2) ethel, (3) lucy, (4) ricky

 3dANOVA2 -type 3 -alevels 3 -blevels 4   \
          -dset 1 1 fred_choc+tlrc        \
          -dset 2 1 fred_glaz+tlrc        \
          -dset 3 1 fred_sugr+tlrc        \
          -dset 1 2 ethel_choc+tlrc       \
          -dset 2 2 ethel_glaz+tlrc       \
          -dset 3 2 ethel_sugr+tlrc       \
          -dset 1 3 lucy_choc+tlrc        \
          -dset 2 3 lucy_glaz+tlrc        \
          -dset 3 3 lucy_sugr+tlrc        \
          -dset 1 3 ricky_choc+tlrc       \
          -dset 2 3 ricky_glaz+tlrc       \
          -dset 3 3 ricky_sugr+tlrc       \
          -amean 1 Chocolate              \
          -amean 2 Glazed                 \
          -amean 3 Sugar                  \
          -adiff 1 2 CvsG                 \
          -adiff 2 3 GvsS                 \
          -adiff 1 3 CvsS                 \
          -acontr 1 1 -2 CGvsS            \
          -acontr -2 1 1 CvsGS            \
          -acontr 1 -2 1 CSvsG            \
          -fa Donuts                      \
          -bucket ANOVA_results

 The -bucket option will place all of the 3dANOVA2 results (i.e., main
 effect of DONUTS, means for each of the 3 levels of DONUTS, and
 contrasts between the 3 levels of DONUTS) into one big dataset with
 multiple sub-bricks called ANOVA_results+tlrc.

-----------------------------------------------------------


N.B.: For this program, the user must specify 1 and only 1 sub-brick
      with each -dset command. That is, if an input dataset contains
      more than 1 sub-brick, a sub-brick selector must be used, e.g.:
      -dset 2 4 'fred+orig[3]'

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

Also see HowTo #5: Group Analysis on the AFNI website:
 http://afni.nimh.gov/pub/dist/HOWTO/howto/ht05_group/html/index.shtml

-------------------------------------------------------------------------
STORAGE FORMAT:
---------------
The default output format is to store the results as scaled short
(16-bit) integers.  This truncantion might cause significant errors.
If you receive warnings that look like this:
  *+ WARNING: TvsF[0] scale to shorts misfit = 8.09% -- *** Beware
then you can force the results to be saved in float format by
defining the environment variable AFNI_FLOATIZE to be YES
before running the program.  For convenience, you can do this
on the command line, as in
  3dANOVA -DAFNI_FLOATIZE=YES ... other options ... 
Also see the following links:
 http://afni.nimh.nih.gov/pub/dist/doc/program_help/common_options.html
 http://afni.nimh.nih.gov/pub/dist/doc/program_help/README.environment.html

++ Compile date = Nov  5 2009




AFNI program: 3dANOVA3
This program performs three-factor ANOVA on 3D data sets.           

Usage: 
3dANOVA3 
-type  k          type of ANOVA model to be used:
                         k = 1   A,B,C fixed;          AxBxC
                         k = 2   A,B,C random;         AxBxC
                         k = 3   A fixed; B,C random;  AxBxC
                         k = 4   A,B fixed; C random;  AxBxC
                         k = 5   A,B fixed; C random;  AxB,BxC,C(A)

-alevels a                     a = number of levels of factor A
-blevels b                     b = number of levels of factor B
-clevels c                     c = number of levels of factor C
-dset 1 1 1 filename           data set for level 1 of factor A
                                        and level 1 of factor B
                                        and level 1 of factor C
 . . .                           . . .

-dset i j k filename           data set for level i of factor A
                                        and level j of factor B
                                        and level k of factor C
 . . .                           . . .

-dset a b c filename           data set for level a of factor A
                                        and level b of factor B
                                        and level c of factor C

[-voxel num]                   screen output for voxel # num
[-diskspace]                   print out disk space required for
                                  program execution

[-mask mset]                   use sub-brick #0 of dataset 'mset'
                               to define which voxels to process


The following commands generate individual AFNI 2 sub-brick datasets:
  (In each case, output is written to the file with the specified
   prefix file name.)

[-fa prefix]                F-statistic for factor A effect
[-fb prefix]                F-statistic for factor B effect
[-fc prefix]                F-statistic for factor C effect
[-fab prefix]               F-statistic for A*B interaction
[-fac prefix]               F-statistic for A*C interaction
[-fbc prefix]               F-statistic for B*C interaction
[-fabc prefix]              F-statistic for A*B*C interaction

[-amean i prefix]           estimate of factor A level i mean
[-bmean i prefix]           estimate of factor B level i mean
[-cmean i prefix]           estimate of factor C level i mean
[-xmean i j k prefix]       estimate mean of cell at factor A level i,
                               factor B level j, factor C level k

[-adiff i j prefix]         difference between factor A levels i and j
                               (with factors B and C collapsed)
[-bdiff i j prefix]         difference between factor B levels i and j
                               (with factors A and C collapsed)
[-cdiff i j prefix]         difference between factor C levels i and j
                               (with factors A and B collapsed)
[-xdiff i j k l m n prefix] difference between cell mean at A=i,B=j,
                               C=k, and cell mean at A=l,B=m,C=n

[-acontr c1...ca prefix]    contrast in factor A levels
                               (with factors B and C collapsed)
[-bcontr c1...cb prefix]    contrast in factor B levels
                               (with factors A and C collapsed)
[-ccontr c1...cc prefix]    contrast in factor C levels
                               (with factors A and B collapsed)

[-aBcontr c1 ... ca : j prefix]   2nd order contrast in A, at fixed
                                     B level j (collapsed across C)
[-Abcontr i : c1 ... cb prefix]   2nd order contrast in B, at fixed
                                     A level i (collapsed across C)

[-aBdiff i_1 i_2 : j prefix] difference between levels i_1 and i_2 of
                               factor A, with factor B fixed at level j

[-Abdiff i : j_1 j_2 prefix] difference between levels j_1 and j_2 of
                               factor B, with factor A fixed at level i

[-abmean i j prefix]         mean effect at factor A level i and
                               factor B level j

The following command generates one AFNI 'bucket' type dataset:

[-bucket prefix]         create one AFNI 'bucket' dataset whose
                           sub-bricks are obtained by concatenating
                           the above output files; the output 'bucket'
                           is written to file with prefix file name

Modified ANOVA computation options:    (December, 2005)

     ** These options apply to model types 4 and 5, only.
        For details, see http://afni.nimh.nih.gov/sscc/gangc/ANOVA_Mod.html

[-old_method]       request to perform ANOVA using the previous
                    functionality (requires -OK, also)

[-OK]               confirm you understand that contrasts that
                    do not sum to zero have inflated t-stats, and
                    contrasts that do sum to zero assume sphericity
                    (to be used with -old_method)

[-assume_sph]       assume sphericity (zero-sum contrasts, only)

                    This allows use of the old_method for
                    computing contrasts which sum to zero (this
                    includes diffs, for instance).  Any contrast
                    that does not sum to zero is invalid, and
                    cannot be used with this option (such as
                    ameans).

-----------------------------------------------------------------
example: "classic" houses/faces/donuts for 4 subjects (2 genders)
         (level sets are gender (M/W), image (H/F/D), and subject)

    Note: factor C is really subject within gender (since it is
          nested).  There are 4 subjects in this example, and 2
          subjects per gender.  So clevels is 2.

    3dANOVA3 -type 5                            \
        -alevels 2                              \
        -blevels 3                              \
        -clevels 2                              \
        -dset 1 1 1 man1_houses+tlrc            \
        -dset 1 2 1 man1_faces+tlrc             \
        -dset 1 3 1 man1_donuts+tlrc            \
        -dset 1 1 2 man2_houses+tlrc            \
        -dset 1 2 2 man2_faces+tlrc             \
        -dset 1 3 2 man2_donuts+tlrc            \
        -dset 2 1 1 woman1_houses+tlrc          \
        -dset 2 2 1 woman1_faces+tlrc           \
        -dset 2 3 1 woman1_donuts+tlrc          \
        -dset 2 1 2 woman2_houses+tlrc          \
        -dset 2 2 2 woman2_faces+tlrc           \
        -dset 2 3 2 woman2_donuts+tlrc          \
        -adiff   1 2           MvsW             \
        -bdiff   2 3           FvsD             \
        -bcontr -0.5 1 -0.5    FvsHD            \
        -aBcontr 1 -1 : 1      MHvsWH           \
        -aBdiff  1  2 : 1      same_as_MHvsWH   \
        -Abcontr 2 : 0 1 -1    WFvsWD           \
        -Abdiff  2 : 2 3       same_as_WFvsWD   \
        -Abcontr 2 : 1 7 -4.2  goofy_example    \
        -bucket donut_anova


N.B.: For this program, the user must specify 1 and only 1 sub-brick
      with each -dset command. That is, if an input dataset contains
      more than 1 sub-brick, a sub-brick selector must be used, e.g.:
      -dset 2 4 5 'fred+orig[3]'

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.
-------------------------------------------------------------------------
STORAGE FORMAT:
---------------
The default output format is to store the results as scaled short
(16-bit) integers.  This truncantion might cause significant errors.
If you receive warnings that look like this:
  *+ WARNING: TvsF[0] scale to shorts misfit = 8.09% -- *** Beware
then you can force the results to be saved in float format by
defining the environment variable AFNI_FLOATIZE to be YES
before running the program.  For convenience, you can do this
on the command line, as in
  3dANOVA -DAFNI_FLOATIZE=YES ... other options ... 
Also see the following links:
 http://afni.nimh.nih.gov/pub/dist/doc/program_help/common_options.html
 http://afni.nimh.nih.gov/pub/dist/doc/program_help/README.environment.html

++ Compile date = Nov  5 2009




AFNI program: 3dAttribute
Usage: 3dAttribute [options] aname dset
Prints (to stdout) the value of the attribute 'aname' from
the header of dataset 'dset'.  If the attribute doesn't exist,
prints nothing and sets the exit status to 1.

Options:
  -name = Include attribute name in printout
  -all  = Print all attributes [don't put aname on command line]
          Also implies '-name'.  Attributes print in whatever order
          they are in the .HEAD file, one per line.  You may want
          to do '3dAttribute -all elvis+orig | sort' to get them
          in alphabetical order.
  -center = Center of volume in RAI coordinates.
            Note that center is not itself an attribute in the 
           .HEAD file. It is calculated from other attributes.
  Special options for string attributes:
    -ssep SSEP    Use string SSEP as a separator between strings for
                  multiple sub-bricks. The default is '~', which is what
                  is used internally in AFNI's .HEAD file. For tcsh,
                  I recommend ' ' which makes parsing easy, assuming each
                  individual string contains no spaces to begin with.
                  Try -ssep 'NUM'
    -sprep SPREP  Use string SPREP to replace blank space in string 
                  attributes.
    -quote        Use single quote around each string.
    Examples:
       3dAttribute -quote -ssep ' '  BRICK_LABS SomeStatDset+tlrc.BRIK
       3dAttribute -quote -ssep 'NUM' -sprep '+' BRICK_LABS SomeStatDset+tlrc.BRIK

++ Compile date = Nov  5 2009




AFNI program: 3dAutobox
Usage: 3dAutobox [options] DATASET
Computes size of a box that fits around the volume.
Also can be used to crop the volume to that box.
Optional parameters are:
-prefix PREFIX: Crop the input dataset to the size of the box.
                If left empty no new volume is written out.
-input DATASET: An alternate way to specify the input dataset.
                The default method is to pass DATASET as
                the last parameter on the command line.
-noclust      : Don't do any clustering to find box. Any non-zero
                voxel will be preserved in cropped volume.
                The default uses some clustering to find cropping


++ Compile date = Nov  5 2009




AFNI program: 3dAutomask
Usage: 3dAutomask [options] dataset
Input dataset is EPI 3D+time, or a skull-stripped anatomical.
Output dataset is a brain-only mask dataset.
Method:
 + Uses 3dClipLevel algorithm to find clipping level.
 + Keeps only the largest connected component of the
   supra-threshold voxels, after an erosion/dilation step.
 + Writes result as a 'fim' type of functional dataset,
   which will be 1 inside the mask and 0 outside the mask.
Options:
  -prefix ppp = Write mask into dataset with prefix 'ppp'.
                 [Default == 'automask']
  -clfrac cc  = Set the 'clip level fraction' to 'cc', which
                 must be a number between 0.1 and 0.9.
                 A small 'cc' means to make the initial threshold
                 for clipping (a la 3dClipLevel) smaller, which
                 will tend to make the mask larger.  [default=0.5]
  -nograd     = The program uses a 'gradual' clip level by default.
                 To use a fixed clip level, use '-nograd'.
                 [Change to gradual clip level made 24 Oct 2006.]
  -peels pp   = Peel the mask 'pp' times, then unpeel.  Designed
                 to clip off protuberances less than 2*pp voxels
                 thick. [Default == 1]
  -nbhrs nn   = Define the number of neighbors needed for a voxel
                 NOT to be peeled.  The 18 nearest neighbors in
                 the 3D lattice are used, so 'nn' should be between
                 9 and 18.  [Default == 17]
  -q          = Don't write progress messages (i.e., be quiet).
  -eclip      = After creating the mask, remove exterior
                 voxels below the clip threshold.
  -dilate nd  = Dilate the mask outwards 'nd' times.
  -erode ne   = Erode the mask inwards 'ne' times.
  -SI hh      = After creating the mask, find the most superior
                 voxel, then zero out everything more than 'hh'
                 millimeters inferior to that.  hh=130 seems to
                 be decent (i.e., for Homo Sapiens brains).
--------------------------------------------------------------------
How to make an edge-of-brain mask:
* 3dSkullStrip to create a brain-only dataset; say, Astrip+orig
* 3dAutomask -prefix Amask Astrip+orig
* Create a mask of edge-only voxels via
   3dcalc -a Amask+orig -b a+i -c a-i -d a+j -e a-j -f a+k -g a-k \
          -expr 'ispositive(a)*amongst(0,b,c,d,e,f,g)' -prefix Aedge
  which will be 1 at all voxels in the brain mask that have a
  nearest neighbor that is NOT in the brain mask.
* cf. '3dcalc -help' DIFFERENTIAL SUBSCRIPTS for information
  on the 'a+i' et cetera inputs used above.
* In regions where the brain mask is 'stair-stepping', then the
  voxels buried inside the corner of the steps probably won't
  show up in this edge mask:
     ...00000000...
     ...aaa00000...
     ...bbbaa000...
     ...bbbbbaa0...
  Only the 'a' voxels are in this edge mask, and the 'b' voxels
  down in the corners won't show up, because they only touch a
  0 voxel on a corner, not face-on.  Depending on your use for
  the edge mask, this effect may or may not be a problem.
--------------------------------------------------------------------

++ Compile date = Nov  5 2009




AFNI program: 3dAutoTcorrelate
Usage: 3dAutoTcorrelate [options] dset
Computes the correlation coefficient between each pair of
voxels in the input dataset, and stores the output into
a new anatomical bucket dataset.

Options:
  -pearson  = Correlation is the normal Pearson (product moment)
                correlation coefficient [default].
  -spearman = Correlation is the Spearman (rank) correlation
                coefficient.
  -quadrant = Correlation is the quadrant correlation coefficient.

  -polort m = Remove polynomical trend of order 'm', for m=-1..3.
                [default is m=1; removal is by least squares].
                Using m=-1 means no detrending; this is only useful
                for data/information that has been pre-processed.

  -autoclip = Clip off low-intensity regions in the dataset,
  -automask =  so that the correlation is only computed between
               high-intensity (presumably brain) voxels.  The
               intensity level is determined the same way that
               3dClipLevel works.

  -prefix p = Save output into dataset with prefix 'p'
               [default prefix is 'ATcorr'].

  -time     = Save output as a 3D+time dataset instead
               of a anat bucket.

Notes:
 * The output dataset is anatomical bucket type of shorts.
 * The output file might be gigantic and you might run out
    of memory running this program.  Use at your own risk!
 * The program prints out an estimate of its memory usage
    when it starts.  It also prints out a progress 'meter'
    of 1 dot per 10 output sub-bricks.
 * This is a quick hack for Peter Bandettini. Now pay up.

-- RWCox - Jan 31 2002

++ Compile date = Nov  5 2009




AFNI program: 3daxialize
Usage: 3daxialize [options] dataset
Purpose: Read in a dataset and write it out as a new dataset
         with the data brick oriented as axial slices.
         The input dataset must have a .BRIK file.
         One application is to create a dataset that can
         be used with the AFNI volume rendering plugin.

Options:
 -prefix ppp  = Use 'ppp' as the prefix for the new dataset.
               [default = 'axialize']
 -verb        = Print out a progress report.

The following options determine the order/orientation
in which the slices will be written to the dataset:
 -sagittal    = Do sagittal slice order [-orient ASL]
 -coronal     = Do coronal slice order  [-orient RSA]
 -axial       = Do axial slice order    [-orient RAI]
                 This is the default AFNI axial order, and
                 is the one currently required by the
                 volume rendering plugin; this is also
                 the default orientation output by this
                 program (hence the program's name).

 -orient code = Orientation code for output.
                The code must be 3 letters, one each from the
                pairs {R,L} {A,P} {I,S}.  The first letter gives
                the orientation of the x-axis, the second the
                orientation of the y-axis, the third the z-axis:
                 R = Right-to-left         L = Left-to-right
                 A = Anterior-to-posterior P = Posterior-to-anterior
                 I = Inferior-to-superior  S = Superior-to-inferior
                If you give an illegal code (e.g., 'LPR'), then
                the program will print a message and stop.
          N.B.: 'Neurological order' is -orient LPI
 -frugal      = Write out data as it is rotated, a sub-brick at
                a time. This saves a little memory and was the
                previous behavior.
                Note the frugal option is not available with NIFTI
                datasets

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dBlurInMask
Usage: 3dBlurInMask [options]
Blurs a dataset spatially inside a mask.  That's all.  Experimental.

OPTIONS
-------
 -input  ddd = This required 'option' specifies the dataset
               that will be smoothed and output.
 -FWHM   f   = Add this amount of smoothness to the dataset.
              **N.B.: This is also a required 'option'.
 -mask   mmm = Mask dataset, if desired.  Blurring will
               occur only within the mask.  Voxels NOT in
               the mask will be set to zero in the output.
 -Mmask  mmm = Multi-mask dataset -- each distinct nonzero
               value in dataset 'mmm' will be treated as
               a separate mask for blurring purposes.
              **N.B.: 'mmm' must be byte- or short-valued!
 -automask   = Create an automask from the input dataset.
              **N.B.: only 1 masking option can be used!
 -preserve   = Normally, voxels not in the mask will be
               set to zero in the output.  If you want the
               original values in the dataset to be preserved
               in the output, use this option.
 -prefix ppp = Prefix for output dataset will be 'ppp'.
              **N.B.: Output dataset is always in float format.
 -quiet      = Don't be verbose with the progress reports.
 -float      = Save dataset as floats, no matter what the
               input data type is.
              **N.B.: If the input dataset is unscaled shorts, then
                      the default is to save the output in short
                      format as well.  In EVERY other case, the
                      program saves the output as floats. Thus,
                      the ONLY purpose of the '-float' option is to
                      force an all-shorts input dataset to be saved
                      as all-floats after blurring.

NOTES
-----
 * If you don't provide a mask, then all voxels will be included
     in the blurring.  (But then why are you using this program?)
 * Note that voxels inside the mask that are not contiguous with
     any other voxels inside the mask will not be modified at all!
 * Works iteratively, similarly to 3dBlurToFWHM, but without
     the extensive overhead of monitoring the smoothness.
 * But this program will be faster than 3dBlurToFWHM, and probably
     slower than 3dmerge.
 * Since the blurring is done iteratively, rather than all-at-once as
     in 3dmerge, the results will be slightly different than 3dmerge's,
     even if no mask is used here (3dmerge, of course, doesn't take a mask).
 * If the original FWHM of the dataset was 'S' and you input a value
     'F' with the '-FWHM' option, then the output dataset's smoothness
     will be about sqrt(S*S+F*F).  The number of iterations will be
     about (F*F/d*d) where d=grid spacing; this means that a large value
     of F might take a lot of CPU time!
 * The spatial smoothness of a 3D+time dataset can be estimated with a
     command similar to the following:
          3dFWHMx -detrend -mask mmm+orig -input ddd+orig
 * The minimum number of voxels in the mask is 9
 * Isolated voxels will be removed from the mask!

 =========================================================================
* This binary version of 3dBlurInMask is NOT compiled using OpenMP, a
   semi-automatic parallelizer software toolkit, which splits the work
   across multiple CPUs/cores on the same shared memory computer.
* However, the source code is modified for OpenMP, and can be compiled
   with an OpenMP-capable compiler, such as gcc 4.2, Intel's icc, and
   Sun Studio.
* If you wish to compile this program with OpenMP, see the man page for
   your C compiler, and (if needed) consult the AFNI message board, and
    http://afni.nimh.nih.gov/pub/dist/doc/misc/OpenMP.html

++ Compile date = Nov  5 2009




AFNI program: 3dBlurToFWHM
Usage: 3dBlurToFWHM [options]
Blurs a 'master' dataset until it reaches a specified FWHM
smoothness (approximately).  The same blurring schedule is
applied to the input dataset to produce the output.  The goal
is to make the output dataset have the given smoothness, no
matter what smoothness it had on input (however, the program
cannot 'unsmooth' a dataset!).  See below for the method used.

OPTIONS
-------
 -input      ddd = This required 'option' specifies the dataset
                   that will be smoothed and output.
 -blurmaster bbb = This option specifies the dataset whose
                   whose smoothness controls the process.
                  **N.B.: If not given, the input dataset is used.
                  **N.B.: This should be one continuous run.
                          Do not input catenated runs!
 -prefix     ppp = Prefix for output dataset will be 'ppp'.
                  **N.B.: Output dataset is always in float format.
 -mask       mmm = Mask dataset, if desired.  Blurring will
                   occur only within the mask.  Voxels NOT in
                   the mask will be set to zero in the output.
 -automask       = Create an automask from the input dataset.
                  **N.B.: Not useful if the input dataset has
                          been detrended before input!
 -FWHM       f   = Blur until the 3D FWHM is 'f'.
 -FWHMxy     f   = Blur until the 2D (x,y)-plane FWHM is 'f'.
                   No blurring is done along the z-axis.
                  **N.B.: Note that you can't REDUCE the smoothness
                          of a dataset.
                  **N.B.: Here, 'x', 'y', and 'z' refer to the
                          grid/slice order as stored in the dataset,
                          not DICOM ordered coordinates!
                  **N.B.: With -FWHMxy, smoothing is done only in the
                          dataset xy-plane.  With -FWHM, smoothing
                          is done in 3D.
                  **N.B.: The actual goal is reached when
                            -FHWM  :  cbrt(FWHMx*FWHMy*FWHMz) >= f
                            -FWHMxy:  sqrt(FWHMx*FWHMy)       >= f
                          That is, when the area or volume of a
                          'resolution element' goes past a threshold.
 -quiet            Shut up the verbose progress reports.
                  **N.B.: This should be the first option, to stifle
                          any verbosity from the option processing code.

FILE RECOMMENDATIONS for -blurmaster:
For FMRI statistical purposes, you DO NOT want the FWHM to reflect
  the spatial structure of the underlying anatomy.  Rather, you want
  the FWHM to reflect the spatial structure of the noise.  This means
  that the -blurmaster dataset should not have anatomical structure.  One
  good form of input is the output of '3dDeconvolve -errts', which is
  the residuals left over after the GLM fitted signal model is subtracted
  out from each voxel's time series.
You CAN give a multi-brick EPI dataset as the -blurmaster dataset; the
  dataset will be detrended in time (like the -detrend option in 3dFWHMx)
  which will tend to remove the spatial structure.  This makes it
  practicable to make the input and blurmaster datasets be the same,
  without having to create a detrended or residual dataset beforehand.
  Considering the accuracy of blurring estimates, this is probably good
  enough for government work [that is an insider's joke]. 
  N.B.: Do not use catenated runs as blurmasters. There 
  should be no discontinuities in the time axis of blurmaster.

ALSO SEE:
 * 3dFWHMx, which estimates smoothness globally
 * 3dLocalstat -stat FHWM, which estimates smoothness locally
 * This paper, which discusses the need for a fixed level of smoothness
   when combining FMRI datasets from different scanner platforms:
     Friedman L, Glover GH, Krenz D, Magnotta V; The FIRST BIRN. 
     Reducing inter-scanner variability of activation in a multicenter
     fMRI study: role of smoothness equalization.
     Neuroimage. 2006 Oct 1;32(4):1656-68.

METHOD:
The blurring is done by a conservative finite difference approximation
to the diffusion equation:
  du/dt = d/dx[ D_x(x,y,z) du/dx ] + d/dy[ D_y(x,y,z) du/dy ]
                                   + d/dz[ D_z(x,y,z) du/dz ]
        = div[ D(x,y,z) grad[u(x,y,z)] ]
where diffusion tensor D() is diagonal, Euler time-stepping is used, and
with Neumann (reflecting) boundary conditions at the edges of the mask
(which ensures that voxel data inside and outside the mask don't mix).
* At each pseudo-time step, the FWHM is estimated globally (like '3dFWHMx')
  and locally (like '3dLocalstat -stat FWHM'). Voxels where the local FWHM
  goes past the goal will not be smoothed any more (D gets set to zero).
* When the global smoothness estimate gets close to the goal, the blurring
  rate (pseudo-time step) will be reduced, to avoid over-smoothing.
* When an individual direction's smoothness (e.g., FWHMz) goes past the goal,
  all smoothing in that direction stops, but the other directions continue
  to be smoothed until the overall resolution element goal is achieved.
* When the global FWHM estimate reaches the goal, the program is done.
  It will also stop if progress stalls for some reason, or if the maximum
  iteration count is reached (infinite loops being unpopular).
* The output dataset will NOT have exactly the smoothness you ask for, but
  it will be close (fondly we do hope).  In our Imperial experiments, the
  results (measured via 3dFWHMx) are within 10% of the goal (usually better).
* 2D blurring via -FWHMxy may increase the smoothness in the z-direction
  reported by 3dFHWMx, even though there is no inter-slice processing.
  At this moment, I'm not sure why.  It may be an estimation artifact due
  to increased correlation in the xy-plane that biases the variance estimates
  used to calculate FWHMz.

ADVANCED OPTIONS:
 -maxite  ccc = Set maximum number of iterations to 'ccc' [Default=variable].
 -rate    rrr = The value of 'rrr' should be a number between
                0.05 and 3.5, inclusive.  It is a factor to change
                the overall blurring rate (slower for rrr < 1) and thus
                require more or less blurring steps.  This option should only
                be needed to slow down the program if the it over-smooths
                significantly (e.g., it overshoots the desired FWHM in
                Iteration #1 or #2).  You can increase the speed by using
                rrr > 1, but be careful and examine the output.
 -nbhd    nnn = As in 3dLocalstat, specifies the neighborhood
                used to compute local smoothness.
                [Default = 'SPHERE(-4)' in 3D, 'SPHERE(-6)' in 2D]
               ** N.B.: For the 2D -FWHMxy, a 'SPHERE()' nbhd
                        is really a circle in the xy-plane.
               ** N.B.: If you do NOT want to estimate local
                        smoothness, use '-nbhd NULL'.
 -bsave   bbb = Save the local smoothness estimates at each iteration
                with dataset prefix 'bbb' [for debugging purposes].
 -bmall       = Use all blurmaster sub-bricks.
                [Default: a subset will be chosen, for speed]
 -unif        = Uniformize the voxel-wise MAD in the blurmaster AND
                input datasets prior to blurring.  Will be restored
                in the output dataset.
 -detrend     = Detrend blurmaster dataset to order NT/30 before starting.
 -nodetrend   = Turn off detrending of blurmaster.
               ** N.B.: '-detrend' is the new default [05 Jun 2007]!
 -detin       = Also detrend input before blurring it, then retrend
                it afterwards. [Off by default]
 -temper      = Try harder to make the smoothness spatially uniform.

-- Author: The Dreaded Emperor Zhark - Nov 2006

++ Compile date = Nov  5 2009




AFNI program: 3dBRAIN_VOYAGERtoAFNI

Usage: 3dBRAIN_VOYAGERtoAFNI <-input BV_VOLUME.vmr> 
                             [-bs] [-qx] [-tlrc|-acpc|-orig] [<-prefix PREFIX>]
 
 Converts a BrainVoyager vmr dataset to AFNI's BRIK format
 The conversion is based on information from BrainVoyager's
 website: www.brainvoyager.com. 
 Sample data and information provided by 
  Adam Greenberg and Nikolaus Kriegeskorte.

  If you get error messages about the number of
 voxels and file size, try the options below.
 I hope to automate these options once I have
 a better description of the BrainVoyager QX format.

  Optional Parameters:
  -bs: Force byte swapping.
  -qx: .vmr file is from BrainVoyager QX
  -tlrc: dset in tlrc space
  -acpc: dset in acpc-aligned space
  -orig: dset in orig space
  If unspecified, the program attempts to guess the view from
  the name of the input.
   [-novolreg|-noxform]: Ignore any Rotate, Volreg, Tagalign, 
                or WarpDrive transformations present in 
                the Surface Volume.
  Common Debugging Options:
   [-trace]: Turns on In/Out debug and Memory tracing.
             For speeding up the tracing log, I recommend 
             you redirect stdout to a file when using this option.
             For example, if you were running suma you would use:
             suma -spec lh.spec -sv ... > TraceFile
             This option replaces the old -iodbg and -memdbg.
   [-TRACE]: Turns on extreme tracing.
   [-nomall]: Turn off memory tracing.
   [-yesmall]: Turn on memory tracing (default).
  NOTE: For programs that output results to stdout
    (that is to your shell/screen), the debugging info
    might get mixed up with your results.
 

++ SUMA version 2006_7_3

CVS tag:
   SUMA_2005_04_29_1733

Compile Date:
   Nov  5 2009

       Ziad S. Saad SSCC/NIMH/NIH saadz@mail.nih.gov     



AFNI program: 3dBrickStat
Usage: 3dBrickStat [options] dataset
Compute maximum and/or minimum voxel values of an input dataset

The output is a number to the console.  The input dataset
may use a sub-brick selection list, as in program 3dcalc.

Note: If you don't specify one sub-brick, the parameter you get
----- back is computed from all the sub-bricks in dataset.
Options :
  -quick = get the information from the header only (default)
  -slow = read the whole dataset to find the min and max values
         all other options except min and max imply slow
  -min = print the minimum value in dataset
  -max = print the minimum value in dataset (default)
  -mean = print the mean value in dataset 
  -var = print the variance in the dataset 
  -count = print the number of voxels included
  -volume = print the volume of voxels included in microliters
  -positive = include only positive voxel values 
  -negative = include only negative voxel values 
  -zero = include only zero voxel values 
  -non-positive = include only voxel values 0 or negative 
  -non-negative = include only voxel values 0 or greater 
  -non-zero = include only voxel values not equal to 0 
  -nan = include only voxel values that are not numbers (NaN, inf, -if,
       implies slow)
  -nonan =exclude voxel values that are not numbers
  -mask dset = use dset as mask to include/exclude voxels
  -automask = automatically compute mask for dataset
    Can not be combined with -mask
  -percentile p0 ps p1 write the percentile values starting
              at p0% and ending at p1% at a step of ps%
              Output is of the form p% value   p% value ...
              Percentile values are output first. Only one sub-brick
              is accepted as input with this option.
              Write the author if you REALLY need this option
              to work with multiple sub-bricks.
  -median a shortcut for -percentile 50 1 50
  -ver = print author and version info
  -help = print this help screen

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dbuc2fim
This program converts bucket sub-bricks to fim (fico, fitt, fift, ...)
type dataset.                                                       

Usage:                                                              

3dbuc2fim  -prefix pname  d1+orig[index]                              
     This produces a fim dataset.                                   

 -or-                                                               

3dbuc2fim  -prefix pname  d1+orig[index1]  d2+orig[index2]            
     This produces a fico (fitt, fift, ...) dataset,                  
     depending on the statistic type of the 2nd subbrick,             
     with   d1+orig[index1] -> intensity sub-brick of pname           
            d2+orig[index2] -> threshold sub-brick of pname         

 -or-                                                               

3dbuc2fim  -prefix pname  d1+orig[index1,index2]                      
     This produces a fico (fitt, fift, ...) dataset,                  
     depending on the statistic type of the 2nd subbrick,             
     with   d1+orig[index1] -> intensity sub-brick of pname           
            d1+orig[index2] -> threshold sub-brick of pname         

where the options are:
     -prefix pname = Use 'pname' for the output dataset prefix name.
 OR  -output pname     [default='buc2fim']

     -session dir  = Use 'dir' for the output dataset session directory.
                       [default='./'=current working directory]
     -verb         = Print out some verbose output as the program
                       proceeds 

Command line arguments after the above are taken as input datasets.  
A dataset is specified using one of these forms:
   'prefix+view', 'prefix+view.HEAD', or 'prefix+view.BRIK'.
Sub-brick indexes start at 0. 

N.B.: The sub-bricks are output in the order specified, which may
 not be the order in the original datasets.  For example, using
           fred+orig[5,3]
 will cause the sub-brick #5 in fred+orig to be output as the intensity
 sub-brick, and sub-brick #3 to be output as the threshold sub-brick 
 in the new dataset.

N.B.: The '$', '(', ')', '[', and ']' characters are special to
 the shell, so you will have to escape them.  This is most easily
 done by putting the entire dataset plus selection list inside
 single quotes, as in 'fred+orig[5,9]'.


++ Compile date = Nov  5 2009




AFNI program: 3dbucket
Concatenate sub-bricks from input datasets into one big
'bucket' dataset.
Usage: 3dbucket options
where the options are:
     -prefix pname = Use 'pname' for the output dataset prefix name.
 OR  -output pname     [default='buck']

     -session dir  = Use 'dir' for the output dataset session directory.
                       [default='./'=current working directory]
     -glueto fname = Append bricks to the end of the 'fname' dataset.
                       This command is an alternative to the -prefix 
                       and -session commands.                        
     -dry          = Execute a 'dry run'; that is, only print out
                       what would be done.  This is useful when
                       combining sub-bricks from multiple inputs.
     -verb         = Print out some verbose output as the program
                       proceeds (-dry implies -verb).
     -fbuc         = Create a functional bucket.
     -abuc         = Create an anatomical bucket.  If neither of
                       these options is given, the output type is
                       determined from the first input type.

Command line arguments after the above are taken as input datasets.
A dataset is specified using one of these forms:
   'prefix+view', 'prefix+view.HEAD', or 'prefix+view.BRIK'.
You can also add a sub-brick selection list after the end of the
dataset name.  This allows only a subset of the sub-bricks to be
included into the output (by default, all of the input dataset
is copied into the output).  A sub-brick selection list looks like
one of the following forms:
  fred+orig[5]                     ==> use only sub-brick #5
  fred+orig[5,9,17]                ==> use #5, #9, and #17
  fred+orig[5..8]     or [5-8]     ==> use #5, #6, #7, and #8
  fred+orig[5..13(2)] or [5-13(2)] ==> use #5, #7, #9, #11, and #13
Sub-brick indexes start at 0.  You can use the character '$'
to indicate the last sub-brick in a dataset; for example, you
can select every third sub-brick by using the selection list
  fred+orig[0..$(3)]

N.B.: The sub-bricks are output in the order specified, which may
 not be the order in the original datasets.  For example, using
  fred+orig[0..$(2),1..$(2)]
 will cause the sub-bricks in fred+orig to be output into the
 new dataset in an interleaved fashion.  Using
  fred+orig[$..0]
 will reverse the order of the sub-bricks in the output.

N.B.: Bucket datasets have multiple sub-bricks, but do NOT have
 a time dimension.  You can input sub-bricks from a 3D+time dataset
 into a bucket dataset.  You can use the '3dinfo' program to see
 how many sub-bricks a 3D+time or a bucket dataset contains.

N.B.: The '$', '(', ')', '[', and ']' characters are special to
 the shell, so you will have to escape them.  This is most easily
 done by putting the entire dataset plus selection list inside
 single quotes, as in 'fred+orig[5..7,9]'.

N.B.: In non-bucket functional datasets (like the 'fico' datasets
 output by FIM, or the 'fitt' datasets output by 3dttest), sub-brick
 [0] is the 'intensity' and sub-brick [1] is the statistical parameter
 used as a threshold.  Thus, to create a bucket dataset using the
 intensity from dataset A and the threshold from dataset B, and
 calling the output dataset C, you would type
    3dbucket -prefix C -fbuc 'A+orig[0]' -fbuc 'B+orig[1]'

WARNING: using this program, it is possible to create a dataset that
         has different basic datum types for different sub-bricks
         (e.g., shorts for brick 0, floats for brick 1).
         Do NOT do this!  Very few AFNI programs will work correctly
         with such datasets!

++ Compile date = Nov  5 2009




AFNI program: 3dcalc
Program: 3dcalc                                                         
Author:  RW Cox et al                                                   
                                                                        
3dcalc - AFNI's calculator program                                      
                                                                        
     This program does voxel-by-voxel arithmetic on 3D datasets         
     (only limited inter-voxel computations are possible).              
                                                                        
     The program assumes that the voxel-by-voxel computations are being 
     performed on datasets that occupy the same space and have the same 
     orientations.                                                      
                                                                        
------------------------------------------------------------------------
Usage:                                                                  
-----                                                                   
       3dcalc -a dsetA [-b dsetB...] \                                 
              -expr EXPRESSION       \                                 
              [options]                                                 
                                                                        
Examples:                                                               
--------                                                                
1. Average datasets together, on a voxel-by-voxel basis:                
                                                                        
     3dcalc -a fred+tlrc -b ethel+tlrc -c lucy+tlrc \                  
            -expr '(a+b+c)/3' -prefix subjects_mean                     
                                                                        
   Averaging datasets can also be done by programs 3dMean and 3dmerge.  
   Use 3dTstat to averaging across sub-bricks in a single dataset.      
                                                                        
2. Perform arithmetic calculations between the sub-bricks of a single   
   dataset by noting the sub-brick number on the command line:          
                                                                        
     3dcalc -a 'func+orig[2]' -b 'func+orig[4]' -expr 'sqrt(a*b)'       
                                                                        
3. Create a simple mask that consists only of values in sub-brick #0    
   that are greater than 3.14159:                                       
                                                                        
     3dcalc -a 'func+orig[0]' -expr 'ispositive(a-3.14159)' \          
            -prefix mask                                                
                                                                        
4. Normalize subjects' time series datasets to percent change values in 
   preparation for group analysis:                                      
                                                                        
   Voxel-by-voxel, the example below divides each intensity value in    
   the time series (epi_r1+orig) with the voxel's mean value (mean+orig)
   to get a percent change value. The 'ispositive' command will ignore  
   voxels with mean values less than 167 (i.e., they are labeled as     
  'zero' in the output file 'percent_change+orig') and are most likely  
   background/noncortical voxels.                                       
                                                                        
     3dcalc -a epi_run1+orig -b mean+orig     \                        
            -expr '100 * a/b * ispositive(b-167)' -prefix percent_chng  
                                                                        
5. Create a compound mask from a statistical dataset, where 3 stimuli   
   show activation.                                                     
      NOTE: 'step' and 'ispositive' are identical expressions that can  
            be used interchangeably:                                    
                                                                        
     3dcalc -a 'func+orig[12]' -b 'func+orig[15]' -c 'func+orig[18]' \ 
            -expr 'step(a-4.2)*step(b-2.9)*step(c-3.1)'              \ 
            -prefix compound_mask                                       
                                                                        
   In this example, all 3 statistical criteria must be met at once for  
   a voxel to be selected (value of 1) in this mask.                    
                                                                        
6. Same as example #5, but this time create a mask of 8 different values
   showing all combinations of activations (i.e., not only where        
   everything is active, but also each stimulus individually, and all   
   combinations).  The output mask dataset labels voxel values as such: 
                                                                        
        0 = none active    1 = A only active    2 = B only active       
        3 = A and B only   4 = C only active    5 = A and C only        
        6 = B and C only   7 = all A, B, and C active                   
                                                                        
     3dcalc -a 'func+orig[12]' -b 'func+orig[15]' -c 'func+orig[18]' \ 
            -expr 'step(a-4.2)+2*step(b-2.9)+4*step(c-3.1)'          \ 
            -prefix mask_8                                              
                                                                        
   In displaying such a binary-encoded mask in AFNI, you would probably 
   set the color display to have 8 discrete levels (the '#' menu).      
                                                                        
7. Create a region-of-interest mask comprised of a 3-dimensional sphere.
   Values within the ROI sphere will be labeled as '1' while values     
   outside the mask will be labeled as '0'. Statistical analyses can    
   then be done on the voxels within the ROI sphere.                    
                                                                        
   The example below puts a solid ball (sphere) of radius 3=sqrt(9)     
   about the point with coordinates (x,y,z)=(20,30,70):                 
                                                                        
     3dcalc -a anat+tlrc                                              \
            -expr 'step(9-(x-20)*(x-20)-(y-30)*(y-30)-(z-70)*(z-70))' \
            -prefix ball                                                
                                                                        
   The spatial meaning of (x,y,z) is discussed in the 'COORDINATES'     
   section of this help listing (far below).                            
                                                                        
8. Some datsets are 'short' (16 bit) integers with a scalar attached,   
   which allow them to be smaller than float datasets and to contain    
   fractional values.                                                   
                                                                        
   Dataset 'a' is always used as a template for the output dataset. For 
   the examples below, assume that datasets d1+orig and d2+orig consist 
   of small integers.                                                   
                                                                        
   a) When dividing 'a' by 'b', the result should be scaled, so that a  
      value of 2.4 is not truncated to '2'. To avoid this truncation,   
      force scaling with the -fscale option:                            
                                                                        
        3dcalc -a d1+orig -b d2+orig -expr 'a/b' -prefix quot -fscale   
                                                                        
   b) If it is preferable that the result is of type 'float', then set  
      the output data type (datum) to float:                            
                                                                        
        3dcalc -a d1+orig -b d2+orig -expr 'a/b' -prefix quot \        
                -datum float                                            
                                                                        
   c) Perhaps an integral division is desired, so that 9/4=2, not 2.24. 
      Force the results not to be scaled (opposite of example 8a) using 
      the -nscale option:                                               
                                                                        
        3dcalc -a d1+orig -b d2+orig -expr 'a/b' -prefix quot -nscale   
                                                                        
9. Compare the left and right amygdala between the Talairach atlas,     
   and the CA_N27_ML atlas.  The result will be 1 if TT only, 2 if CA   
   only, and 3 where they overlap.                                      
                                                                        
     3dcalc -a 'TT_Daemon::amygdala' -b 'CA_N27_ML::amygdala' \        
            -expr 'step(a)+2*step(b)'  -prefix compare.maps             
                                                                        
   (see 'whereami -help' for more information on atlases)               
                                                                        
10. Convert a dataset from AFNI short format storage to NIfTI-1 floating
    point (perhaps for input to an non-AFNI program that requires this):
                                                                        
      3dcalc -a zork+orig -prefix zfloat.nii -datum float -expr 'a'     
                                                                        
    This operation could also be performed with program 3dAFNItoNIFTI.  
                                                                        
11. Compute the edge voxels of a mask dataset.  An edge voxel is one    
    that shares some face with a non-masked voxel.  This computation    
    assumes 'a' is a binary mask (particularly for 'amongst').          
                                                                        
      3dcalc -a mask+orig -prefix edge                     \           
             -b a+i -c a-i -d a+j -e a-j -f a+k -g a-k     \           
             -expr 'a*amongst(0,b,c,d,e,f,g)'                           
                                                                        
    consider similar erosion or dilation operations:                    
        erosion:  -expr 'a*(1-amongst(0,b,c,d,e,f,g))'                  
        dilation: -expr 'amongst(1,a,b,c,d,e,f,g)'                      
                                                                        
------------------------------------------------------------------------
ARGUMENTS for 3dcalc (must be included on command line):                
---------                                                               
                                                                        
 -a dname    = Read dataset 'dname' and call the voxel values 'a' in the
               expression (-expr) that is input below. Up to 26 dnames  
               (-a, -b, -c, ... -z) can be included in a single 3dcalc  
               calculation/expression.                                  
               ** If some letter name is used in the expression, but    
                  not present in one of the dataset options here, then  
                  that variable is set to 0.                            
               ** If the letter is followed by a number, then that      
                  number is used to select the sub-brick of the dataset 
                  which will be used in the calculations.               
                     E.g., '-b3 dname' specifies that the variable 'b'  
                     refers to sub-brick '3' of that dataset            
                     (indexes in AFNI start at 0).                      
               ** However, it is better to use the subscript '[]' method
                  to select sub-bricks of datasets, as in               
                     -b dname+orig'[3]'                                 
                  rather than the older notation                        
                     -b3 dname+orig                                     
                  The subscript notation is more flexible, as it can    
                  be used to select a collection of sub-bricks.         
                                                                        
 -expr       = Apply the expression - within quotes - to the input      
               datasets (dnames), one voxel at time, to produce the     
               output dataset.                                          
                                                                        
 NOTE: If you want to average or sum up a lot of datasets, programs     
       3dTstat and/or 3dMean and/or 3dmerge are better suited for these 
       purposes.  A common request is to increase the number of input   
       datasets beyond 26, but in almost all cases such users simply    
       want to do simple addition!                                      
                                                                        
 NOTE: If you want to include shell variables in the expression (or in  
       the dataset sub-brick selection), then you should use double     
       "quotes" and the '$' notation for the shell variables; this    
       example uses csh notation to set the shell variable 'z':         
                                                                        
         set z = 3.5                                                    
         3dcalc -a moose.nii -prefix goose.nii -expr "a*$z"           
                                                                        
       The shell will not expand variables inside single 'quotes',      
       and 3dcalc's parser will not understand the '$' character.       
                                                                        
 NOTE: You can use the ccalc program to play with the expression        
       evaluator, in order to get a feel for how it works and           
       what it accepts.                                                 
                                                                        
------------------------------------------------------------------------
 OPTIONS for 3dcalc:                                                    
 -------                                                                
                                                                        
  -verbose   = Makes the program print out various information as it    
               progresses.                                              
                                                                        
  -datum type= Coerce the output data to be stored as the given type,   
               which may be byte, short, or float.                      
               [default = datum of first input dataset]                 
  -float }                                                              
  -short }   = Alternative options to specify output data format.       
  -byte  }                                                              
                                                                        
  -fscale    = Force scaling of the output to the maximum integer       
               range. This only has effect if the output datum is byte  
               or short (either forced or defaulted). This option is    
               often necessary to eliminate unpleasant truncation       
               artifacts.                                               
                 [The default is to scale only if the computed values   
                  seem to need it -- are all <= 1.0 or there is at      
                  least one value beyond the integer upper limit.]      
                                                                        
                ** In earlier versions of 3dcalc, scaling (if used) was 
                   applied to all sub-bricks equally -- a common scale  
                   factor was used.  This would cause trouble if the    
                   values in different sub-bricks were in vastly        
                   different scales. In this version, each sub-brick    
                   gets its own scale factor. To override this behavior,
                   use the '-gscale' option.                            
                                                                        
  -gscale    = Same as '-fscale', but also forces each output sub-brick 
               to get the same scaling factor.  This may be desirable   
               for 3D+time datasets, for example.                       
            ** N.B.: -usetemp and -gscale are incompatible!!            
                                                                        
  -nscale    = Don't do any scaling on output to byte or short datasets.
               This may be especially useful when operating on mask     
               datasets whose output values are only 0's and 1's.       
               ** Another way to achieve the effect of '-b3' is described
                  below in the dataset 'INPUT' specification section.   
                                                                        
  -prefix pname = Use 'pname' for the output dataset prefix name.       
                  [default='calc']                                      
                                                                        
  -session dir  = Use 'dir' for the output dataset session directory.   
                  [default='./'=current working directory]              
                  You can also include the output directory in the      
                  'pname' parameter to the -prefix option.              
                                                                        
  -usetemp      = With this option, a temporary file will be created to 
                  hold intermediate results.  This will make the program
                  run slower, but can be useful when creating huge      
                  datasets that won't all fit in memory at once.        
                * The program prints out the name of the temporary      
                  file; if 3dcalc crashes, you might have to delete     
                  this file manually.                                   
               ** N.B.: -usetemp and -gscale are incompatible!!         
                                                                        
  -dt tstep     = Use 'tstep' as the TR for "manufactured" 3D+time    
    *OR*          datasets.                                             
  -TR tstep     = If not given, defaults to 1 second.                   
                                                                        
  -taxis N      = If only 3D datasets are input (no 3D+time or .1D files),
    *OR*          then normally only a 3D dataset is calculated.  With  
  -taxis N:tstep: this option, you can force the creation of a time axis
                  of length 'N', optionally using time step 'tstep'.  In
                  such a case, you will probably want to use the pre-   
                  defined time variables 't' and/or 'k' in your         
                  expression, or each resulting sub-brick will be       
                  identical. For example:                               
                  '-taxis 121:0.1' will produce 121 points in time,     
                  spaced with TR 0.1.                                   
                                                                        
            N.B.: You can also specify the TR using the -dt option.     
            N.B.: You can specify 1D input datasets using the           
                  '1D:n@val,n@val' notation to get a similar effect.    
                  For example:                                          
                     -dt 0.1 -w '1D:121@0'                              
                  will have pretty much the same effect as              
                     -taxis 121:0.1
            N.B.: For both '-dt' and '-taxis', the 'tstep' value is in 
                  seconds.  You can suffix it with 'ms' to specify that
                  the value is in milliseconds instead; e.g., '-dt 2000ms'.
                                                                        
  -rgbfac A B C = For RGB input datasets, the 3 channels (r,g,b) are    
                  collapsed to one for the purposes of 3dcalc, using the
                  formula value = A*r + B*g + C*b                       
                                                                        
                  The default values are A=0.299 B=0.587 C=0.114, which 
                  gives the grayscale intensity.  To pick out the Green 
                  channel only, use '-rgbfac 0 1 0', for example.  Note 
                  that each channel in an RGB dataset is a byte in the  
                  range 0..255.  Thus, '-rgbfac 0.001173 0.002302 0.000447'
                  will compute the intensity rescaled to the range 0..1.0
                  (i.e., 0.001173=0.299/255, etc.)                      
                                                                        
  -cx2r METHOD  = For complex input datasets, the 2 channels must be    
                  converted to 1 real number for calculation.  The      
                  methods available are:  REAL  IMAG  ABS  PHASE        
                * The default method is ABS = sqrt(REAL^2+IMAG^2)       
                * PHASE = atan2(IMAG,REAL)                              
                * Multiple '-cx2r' options can be given:                
                    when a complex dataset is given on the command line,
                    the most recent previous method will govern.        
                * If a complex dataset is used in a differential        
                    subscript, then the most recent previous -cx2r      
                    method applies to the extraction; for example       
                      -cx2r REAL -a cx+orig -cx2r IMAG -b 'a[0,0,0,0]'  
                    means that variable 'a' refers to the real part     
                    of the input dataset and variable 'b' to the        
                    imaginary part of the input dataset.                
                * 3dcalc cannot be used to CREATE a complex dataset!    
                    [See program 3dTwotoComplex for that purpose.]      
                                                                        
  -sort         = Sort each output brick separately, before output:     
  -SORT           'sort' ==> increasing order, 'SORT' ==> decreasing.   
                  [This is useful only under unusual circumstances!]    
                  [Sorting is done in spatial indexes, not in time.]    
                  [Program 3dTsort will sort voxels along time axis]    
                                                                        
------------------------------------------------------------------------
DATASET TYPES:                                                          
-------------                                                           
                                                                        
 The most common AFNI dataset types are 'byte', 'short', and 'float'.   
                                                                        
 A byte value is an 8-bit signed integer (0..255), a short value ia a   
 16-bit signed integer (-32768..32767), and a float value is a 32-bit   
 real number.  A byte value has almost 3 decimals of accuracy, a short  
 has almost 5, and a float has approximately 7 (from a 23+1 bit         
 mantissa).                                                             
                                                                        
 Datasets can also have a scalar attached to each sub-brick. The main   
 use of this is allowing a short type dataset to take on non-integral   
 values, while being half the size of a float dataset.                  
                                                                        
 As an example, consider a short dataset with a scalar of 0.0001. This  
 could represent values between -32.768 and +32.767, at a resolution of 
 0.001.  One could represnt the difference between 4.916 and 4.917, for 
 instance, but not 4.9165. Each number has 15 bits of accuracy, plus a  
 sign bit, which gives 4-5 decimal places of accuracy. If this is not   
 enough, then it makes sense to use the larger type, float.             
                                                                        
------------------------------------------------------------------------
3D+TIME DATASETS:                                                       
----------------                                                        
                                                                        
 This version of 3dcalc can operate on 3D+time datasets.  Each input    
 dataset will be in one of these conditions:                            
                                                                        
    (A) Is a regular 3D (no time) dataset; or                           
    (B) Is a 3D+time dataset with a sub-brick index specified ('-b3'); or
    (C) Is a 3D+time dataset with no sub-brick index specified ('-b').  
                                                                        
 If there is at least one case (C) dataset, then the output dataset will
 also be 3D+time; otherwise it will be a 3D dataset with one sub-brick. 
 When producing a 3D+time dataset, datasets in case (A) or (B) will be  
 treated as if the particular brick being used has the same value at each
 point in time.                                                         
                                                                        
 Multi-brick 'bucket' datasets may also be used.  Note that if multi-brick
 (bucket or 3D+time) datasets are used, the lowest letter dataset will  
 serve as the template for the output; that is, '-b fred+tlrc' takes    
 precedence over '-c wilma+tlrc'.  (The program 3drefit can be used to  
 alter the .HEAD parameters of the output dataset, if desired.)         
                                                                        
------------------------------------------------------------------------
INPUT DATASET NAMES
-------------------
 An input dataset is specified using one of these forms:
    'prefix+view', 'prefix+view.HEAD', or 'prefix+view.BRIK'.
 You can also add a sub-brick selection list after the end of the
 dataset name.  This allows only a subset of the sub-bricks to be
 read in (by default, all of a dataset's sub-bricks are input).
 A sub-brick selection list looks like one of the following forms:
   fred+orig[5]                     ==> use only sub-brick #5
   fred+orig[5,9,17]                ==> use #5, #9, and #17
   fred+orig[5..8]     or [5-8]     ==> use #5, #6, #7, and #8
   fred+orig[5..13(2)] or [5-13(2)] ==> use #5, #7, #9, #11, and #13
 Sub-brick indexes start at 0.  You can use the character '$'
 to indicate the last sub-brick in a dataset; for example, you
 can select every third sub-brick by using the selection list
   fred+orig[0..$(3)]

 N.B.: The sub-bricks are read in the order specified, which may
 not be the order in the original dataset.  For example, using
   fred+orig[0..$(2),1..$(2)]
 will cause the sub-bricks in fred+orig to be input into memory
 in an interleaved fashion.  Using
   fred+orig[$..0]
 will reverse the order of the sub-bricks.

 N.B.: You may also use the syntax  after the name of an input 
 dataset to restrict the range of values read in to the numerical
 values in a..b, inclusive.  For example,
    fred+orig[5..7]<100..200>
 creates a 3 sub-brick dataset with values less than 100 or
 greater than 200 from the original set to zero.
 If you use the <> sub-range selection without the [] sub-brick
 selection, it is the same as if you had put [0..$] in front of
 the sub-range selection.

 N.B.: Datasets using sub-brick/sub-range selectors are treated as:
  - 3D+time if the dataset is 3D+time and more than 1 brick is chosen
  - otherwise, as bucket datasets (-abuc or -fbuc)
    (in particular, fico, fitt, etc datasets are converted to fbuc!)

 N.B.: The characters '$ ( ) [ ] < >'  are special to the shell,
 so you will have to escape them.  This is most easily done by
 putting the entire dataset plus selection list inside forward
 single quotes, as in 'fred+orig[5..7,9]', or double quotes "x".
                                                                        
** WARNING: you cannot combine sub-brick selection of the form          
               -b3 bambam+orig       (the old method)                   
            with sub-brick selection of the form                        
               -b  'bambam+orig[3]'  (the new method)                   
            If you try, the Doom of Mandos will fall upon you!          
                                                                        
------------------------------------------------------------------------
1D TIME SERIES:                                                         
--------------                                                          
                                                                        
 You can also input a '*.1D' time series file in place of a dataset.    
 In this case, the value at each spatial voxel at time index n will be  
 the same, and will be the n-th value from the time series file.        
 At least one true dataset must be input.  If all the input datasets    
 are 3D (single sub-brick) or are single sub-bricks from multi-brick    
 datasets, then the output will be a 'manufactured' 3D+time dataset.    
                                                                        
 For example, suppose that 'a3D+orig' is a 3D dataset:                  
                                                                        
   3dcalc -a a3D+orig -b b.1D -expr "a*b"                             
                                                                        
 The output dataset will 3D+time with the value at (x,y,z,t) being      
 computed by a3D(x,y,z)*b(t).  The TR for this dataset will be set      
 to 'tstep' seconds -- this could be altered later with program 3drefit.
 Another method to set up the correct timing would be to input an       
 unused 3D+time dataset -- 3dcalc will then copy that dataset's time    
 information, but simply do not use that dataset's letter in -expr.     
                                                                        
 If the *.1D file has multiple columns, only the first read will be     
 used in this program.  You can select a column to be the first by      
 using a sub-vector selection of the form 'b.1D[3]', which will         
 choose the 4th column (since counting starts at 0).                    
                                                                        
 '{...}' row selectors can also be used - see the output of '1dcat -help'
 for more details on these.  Note that if multiple timeseries or 3D+time
 or 3D bucket datasets are input, they must all have the same number of 
 points along the 'time' dimension.                                     
                                                                        
 N.B.: To perform calculations ONLY on .1D files, use program 1deval.   
       3dcalc takes .1D files for use in combination with 3D datasets!  
                                                                        
 N.B.: If you auto-transpose a .1D file on the command line, (by ending 
       the filename with \'), then 3dcalc will NOT treat it as the     
       special case described above, but instead will treat it as       
       a normal dataset, where each row in the transposed input is a    
       'voxel' time series.  This would allow you to do differential    
       subscripts on 1D time series, which program 1deval does not      
       implement.  For example:                                         
                                                                        
        3dcalc -a '1D: 3 4 5 6'\' -b a+l -expr 'sqrt(a+b)' -prefix -   
                                                                        
       This technique allows expression evaluation on multi-column      
       .1D files, which 1deval also does not implement.  For example:   
                                                                        
        3dcalc -a '1D: 3 4 5 | 1 2 3'\' -expr 'cbrt(a)' -prefix -      
                                                                        
------------------------------------------------------------------------
'1D:' INPUT:                                                            
-----------                                                             
                                                                        
 You can input a 1D time series 'dataset' directly on the command line, 
 without an external file.  The 'filename for such input takes the      
 general format                                                         
                                                                        
   '1D:n_1@val_1,n_2@val_2,n_3@val_3,...'                               
                                                                        
 where each 'n_i' is an integer and each 'val_i' is a float.  For       
 example                                                                
                                                                        
    -a '1D:5@0,10@1,5@0,10@1,5@0'                                       
                                                                        
 specifies that variable 'a' be assigned to a 1D time series of 35,     
 alternating in blocks between values 0 and value 1.                    
                                                                        
------------------------------------------------------------------------
'I:*.1D' and 'J:*.1D' and 'K:*.1D' INPUT:                               
----------------------------------------                                
                                                                        
 You can input a 1D time series 'dataset' to be defined as spatially    
 dependent instead of time dependent using a syntax like:               
                                                                        
   -c I:fred.1D                                                         
                                                                        
 This indicates that the n-th value from file fred.1D is to be associated
 with the spatial voxel index i=n (respectively j=n and k=n for 'J: and 
 K: input dataset names).  This technique can be useful if you want to  
 scale each slice by a fixed constant; for example:                     
                                                                        
   -a dset+orig -b K:slicefactor.1D -expr 'a*b'                         
                                                                        
 In this example, the '-b' value only varies in the k-index spatial     
 direction.                                                             
                                                                        
------------------------------------------------------------------------
COORDINATES and PREDEFINED VALUES:                                      
---------------------------------                                       
                                                                        
 If you don't use '-x', '-y', or '-z' for a dataset, then the voxel     
 spatial coordinates will be loaded into those variables.  For example, 
 the expression 'a*step(x*x+y*y+z*z-100)' will zero out all the voxels  
 inside a 10 mm radius of the origin x=y=z=0.                           
                                                                        
 Similarly, the '-t' value, if not otherwise used by a dataset or *.1D  
 input, will be loaded with the voxel time coordinate, as determined    
 from the header file created for the OUTPUT.  Please note that the units
 of this are variable; they might be in milliseconds, seconds, or Hertz.
 In addition, slices of the dataset might be offset in time from one    
 another, and this is allowed for in the computation of 't'.  Use program
 3dinfo to find out the structure of your datasets, if you are not sure.
 If no input datasets are 3D+time, then the effective value of TR is    
 tstep in the output dataset, with t=0 at the first sub-brick.          
                                                                        
 Similarly, the '-i', '-j', and '-k' values, if not otherwise used,     
 will be loaded with the voxel spatial index coordinates.  The '-l'     
 (letter 'ell') value will be loaded with the temporal index coordinate.
                                                                        
 Otherwise undefined letters will be set to zero.  In the future,       
 new default values for other letters may be added.                     
                                                                        
 NOTE WELL: By default, the coordinate order of (x,y,z) is the order in 
 *********  which the data array is stored on disk; this order is output
            by 3dinfo.  The options below control can change this order:
                                                                        
 -dicom }= Sets the coordinates to appear in DICOM standard (RAI) order,
 -RAI   }= (the AFNI standard), so that -x=Right, -y=Anterior , -z=Inferior,
                                        +x=Left , +y=Posterior, +z=Superior.
                                                                        
 -SPM   }= Sets the coordinates to appear in SPM (LPI) order,           
 -LPI   }=                      so that -x=Left , -y=Posterior, -z=Inferior,
                                        +x=Right, +y=Anterior , +z=Superior.
                                                                        
------------------------------------------------------------------------
DIFFERENTIAL SUBSCRIPTS [22 Nov 1999]:                                  
-----------------------                                                 
                                                                        
 Normal calculations with 3dcalc are strictly on a per-voxel basis:
 there is no 'cross-talk' between spatial or temporal locations.
 The differential subscript feature allows you to specify variables
 that refer to different locations, relative to the base voxel.
 For example,
   -a fred+orig -b 'a[1,0,0,0]' -c 'a[0,-1,0,0]' -d 'a[0,0,2,0]'
 means: symbol 'a' refers to a voxel in dataset fred+orig,
        symbol 'b' refers to the following voxel in the x-direction,
        symbol 'c' refers to the previous voxel in the y-direction
        symbol 'd' refers to the 2nd following voxel in the z-direction

 To use this feature, you must define the base dataset (e.g., 'a')
 first.  Then the differentially subscripted symbols are defined
 using the base dataset symbol followed by 4 integer subscripts,
 which are the shifts in the x-, y-, z-, and t- (or sub-brick index)
 directions. For example,

   -a fred+orig -b 'a[0,0,0,1]' -c 'a[0,0,0,-1]' -expr 'median(a,b,c)'

 will produce a temporal median smoothing of a 3D+time dataset (this
 can be done more efficiently with program 3dTsmooth).

 Note that the physical directions of the x-, y-, and z-axes depend
 on how the dataset was acquired or constructed.  See the output of
 program 3dinfo to determine what direction corresponds to what axis.

 For convenience, the following abbreviations may be used in place of
 some common subscript combinations:

   [1,0,0,0] == +i    [-1, 0, 0, 0] == -i
   [0,1,0,0] == +j    [ 0,-1, 0, 0] == -j
   [0,0,1,0] == +k    [ 0, 0,-1, 0] == -k
   [0,0,0,1] == +l    [ 0, 0, 0,-1] == -l

 The median smoothing example can thus be abbreviated as

   -a fred+orig -b a+l -c a-l -expr 'median(a,b,c)'

 When a shift calls for a voxel that is outside of the dataset range,
 one of three things can happen:

   STOP => shifting stops at the edge of the dataset
   WRAP => shifting wraps back to the opposite edge of the dataset
   ZERO => the voxel value is returned as zero

 Which one applies depends on the setting of the shifting mode at the
 time the symbol using differential subscripting is defined.  The mode
 is set by one of the switches '-dsSTOP', '-dsWRAP', or '-dsZERO'.  The
 default mode is STOP.  Suppose that a dataset has range 0..99 in the
 x-direction.  Then when voxel 101 is called for, the value returned is

   STOP => value from voxel 99 [didn't shift past edge of dataset]
   WRAP => value from voxel 1  [wrapped back through opposite edge]
   ZERO => the number 0.0 

 You can set the shifting mode more than once - the most recent setting
 on the command line applies when a differential subscript symbol is
 encountered.

N.B.: You can also use program 3dLocalstat to process data from a
      spatial neighborhood of each voxel; for example, to compute
      the maximum over a sphere of radius 9 mm placed around
      each voxel:
        3dLocalstat -nbhd 'SPHERE(9)' -stat max -prefix Amax9 A+orig

------------------------------------------------------------------------
ISSUES:
------ 

 * Complex-valued datasets cannot be processed, except via '-cx2r'.
 * This program is not very efficient (but is faster than it once was).
 * Differential subscripts slow the program down even more.

------------------------------------------------------------------------
------------------------------------------------------------------------
EXPRESSIONS:
----------- 

 As noted above, datasets are referred to by single letter variable names.
 Arithmetic expressions are allowed, using + - * / ** ^ and parentheses.
 C relational, boolean, and conditional expressions are NOT implemented!
 Built in functions include:

    sin  , cos  , tan  , asin  , acos  , atan  , atan2,       
    sinh , cosh , tanh , asinh , acosh , atanh , exp  ,       
    log  , log10, abs  , int   , sqrt  , max   , min  ,       
    J0   , J1   , Y0   , Y1    , erf   , erfc  , qginv, qg ,  
    rect , step , astep, bool  , and   , or    , mofn ,       
    sind , cosd , tand , median, lmode , hmode , mad  ,       
    gran , uran , iran , eran  , lran  , orstat, mod  ,       
    mean , stdev, sem  , Pleg  , cbrt  , rhddc2, hrfbk4,hrfbk5

 where some of the less obvious funcions are:
 * qg(x)    = reversed cdf of a standard normal distribution
 * qginv(x) = inverse function to qg
 * min, max, atan2 each take 2 arguments ONLY
 * J0, J1, Y0, Y1 are Bessel functions (see the holy book: Watson)
 * Pleg(m,x) is the m'th Legendre polynomial evaluated at x
 * erf, erfc are the error and complementary error functions
 * sind, cosd, tand take arguments in degrees (vs. radians)
 * median(a,b,c,...) computes the median of its arguments
 * mad(a,b,c,...) computes the MAD of its arguments
 * mean(a,b,c,...) computes the mean of its arguments
 * stdev(a,b,c,...) computes the standard deviation of its arguments
 * sem(a,b,c,...) computes standard error of the mean of its arguments,
                  where sem(n arguments) = stdev(same)/sqrt(n)
 * orstat(n,a,b,c,...) computes the n-th order statistic of
    {a,b,c,...} - that is, the n-th value in size, starting
    at the bottom (e.g., orstat(1,a,b,c) is the minimum)
 * lmode(a,b,c,...) and hmode(a,b,c,...) compute the mode
    of their arguments - lmode breaks ties by choosing the
    smallest value with the maximal count, hmode breaks ties by
    choosing the largest value with the maximal count
    [median,lmode,hmode take a variable number of arguments]
 * gran(m,s) returns a Gaussian deviate with mean=m, stdev=s
 * uran(r)   returns a uniform deviate in the range [0,r]
 * iran(t)   returns a random integer in the range [0..t]
 * eran(s)   returns an exponentially distributed deviate
               with parameter s; mean=s
 * lran(t)   returns a logistically distributed deviate
               with parameter t; mean=0, stdev=t*1.814
 * mod(a,b)  returns (a modulo b) = a - b*int(a/b)
 * hrfbk4(t,L) and hrfbk5(t,L) are the BLOCK4 and BLOCK5 hemodynamic
    response functions from 3dDeconvolve (L=stimulus duration in sec,
    and t is the time in sec since start of stimulus); for example:
 1deval -del 0.1 -num 400 -expr 'hrfbk5(t-2,20)' | 1dplot -stdin -del 0.1
    These HRF functions are scaled to return values in the range [0..1]

 You may use the symbol 'PI' to refer to the constant of that name.
 This is the only 2 letter symbol defined; all variables are
 referred to by 1 letter symbols.  The case of the expression is
 ignored (in fact, it is converted to uppercase as the first step
 in the parsing algorithm).

 The following functions are designed to help implement logical
 functions, such as masking of 3D volumes against some criterion:
       step(x)    = {1 if x>0        , 0 if x<=0},
       posval(x)  = {x if x>0        , 0 if x<=0},
       astep(x,y) = {1 if abs(x) > y , 0 otherwise} = step(abs(x)-y)
       rect(x)    = {1 if abs(x)<=0.5, 0 if abs(x)>0.5},
       bool(x)    = {1 if x != 0.0   , 0 if x == 0.0},
    notzero(x)    = bool(x),
     iszero(x)    = 1-bool(x) = { 0 if x != 0.0, 1 if x == 0.0 },
        not(x)    = same as iszero(x)
     equals(x,y)  = 1-bool(x-y) = { 1 if x == y , 0 if x != y },
   ispositive(x)  = { 1 if x > 0; 0 if x <= 0 },
   isnegative(x)  = { 1 if x < 0; 0 if x >= 0 },
   and(a,b,...,c) = {1 if all arguments are nonzero, 0 if any are zero}
    or(a,b,...,c) = {1 if any arguments are nonzero, 0 if all are zero}
        not(x)    = same as iszero(x) = Boolean negation
  mofn(m,a,...,c) = {1 if at least 'm' arguments are nonzero, else 0 }
  argmax(a,b,...) = index of largest argument; = 0 if all args are 0
  argnum(a,b,...) = number of nonzero arguments
  pairmax(a,b,...)= finds the 'paired' argument that corresponds to the
                    maximum of the first half of the input arguments;
                    for example, pairmax(a,b,c,p,q,r) determines which
                    of {a,b,c} is the max, then returns corresponding
                    value from {p,q,r}; requires even number of args.
  pairmin(a,b,...)= Similar to pairmax, but for minimum; for example,
                    pairmin(a,b,c,p,q,r} finds the minimum of {a,b,c}
                    and returns the corresponding value from {p,q,r};
                      pairmin(3,2,7,5,-1,-2,-3,-4) = -2
                    (The 'pair' functions are Lukas Pezawas specials!)
  amongst(a,b,...)= Return value is 1 if any of the b,c,... values
                    equals the a value; otherwise, return value is 0.

  [These last 8 functions take a variable number of arguments.]

 The following 27 functions are used for statistical conversions,
 as in the program 'cdf':
   fico_t2p(t,a,b,c), fico_p2t(p,a,b,c), fico_t2z(t,a,b,c),
   fitt_t2p(t,a)    , fitt_p2t(p,a)    , fitt_t2z(t,a)    ,
   fift_t2p(t,a,b)  , fift_p2t(p,a,b)  , fift_t2z(t,a,b)  ,
   fizt_t2p(t)      , fizt_p2t(p)      , fizt_t2z(t)      ,
   fict_t2p(t,a)    , fict_p2t(p,a)    , fict_t2z(t,a)    ,
   fibt_t2p(t,a,b)  , fibt_p2t(p,a,b)  , fibt_t2z(t,a,b)  ,
   fibn_t2p(t,a,b)  , fibn_p2t(p,a,b)  , fibn_t2z(t,a,b)  ,
   figt_t2p(t,a,b)  , figt_p2t(p,a,b)  , figt_t2z(t,a,b)  ,
   fipt_t2p(t,a)    , fipt_p2t(p,a)    , fipt_t2z(t,a)    .

 See the output of 'cdf -help' for documentation on the meanings of
 and arguments to these functions.  The two functions below use the
 NIfTI-1 statistical codes to map between statistical values and
 cumulative distribution values:
   cdf2stat(val,code,p1,p2,p3)
   stat2cdf(val,code,p1,p2,p3)
 where code is
   2 = correlation statistic     p1 = DOF
   3 = t statistic (central)     p1 = DOF
   4 = F statistic (central)     p1 = num DOF, p2 = den DOF
   5 = N(0,1) statistic          no parameters
   6 = Chi-squared (central)     p1 = DOF
   7 = Beta variable (central)   p1 = a , p2 = b
   8 = Binomial variable         p1 = #trials, p2 = prob per trial
   9 = Gamma distribution        p1 = shape, p2 = scale
  10 = Poisson distribution      p1 = mean
  11 = N(mu,variance) normal     p1 = mean, p2 = scale
  12 = noncentral F statistic    p1 = num DOF, p2 = den DOF, p3 = noncen
  13 = noncentral chi-squared    p1 = DOF, p2 = noncentrality parameter
  14 = Logistic distribution     p1 = mean, p2 = scale
  15 = Laplace distribution      p1 = mean, p2 = scale
  16 = Uniform distribution      p1 = min, p2 = max
  17 = noncentral t statistic    p1 = DOF, p2 = noncentrality parameter
  18 = Weibull distribution      p1 = location, p2 = scale, p3 = power
  19 = Chi statistic (central)   p1 = DOF
  20 = inverse Gaussian variable p1 = mu, p2 = lambda
  21 = Extreme value type I      p1 = location, p2 = scale
  22 = 'p-value'                 no parameters
  23 = -ln(p)                    no parameters
  24 = -log10(p)                 no parameters

Finally, note that the expression evaluator is designed not to crash, or
to return NaN or Infinity.  Illegal operations, such as division by 0,
logarithm of negative value, etc., are intercepted and something else
will be returned.  To find out what that 'something else' is in any
specific problematic case, you should play with the ccalc program.

** If you modify a statistical sub-brick, you may want to use program
  '3drefit' to modify the dataset statistical auxiliary parameters.

** Computations are carried out in double precision before being
   truncated to the final output 'datum'.

** Note that the quotes around the expression are needed so the shell
   doesn't try to expand * characters, or interpret parentheses.

** Try the 'ccalc' program to see how the expression evaluator works.
   The arithmetic parser and evaluator is written in Fortran-77 and
   is derived from a program written long ago by RW Cox to facilitate
   compiling on an array processor hooked up to a VAX. (It's a mess, but
   it works - somewhat slowly - but hey, computers are fast these days.)

++ Compile date = Nov  5 2009




AFNI program: 3dClipLevel
Usage: 3dClipLevel [options] dataset
Estimates the value at which to clip the anatomical dataset so
  that background regions are set to zero.

The program's output is a single number sent to stdout.  This
  value can be 'captured' to a shell variable using the backward
  single quote operator; a trivial csh/tcsh example is

    set ccc = `3dClipLevel -mfrac 0.333 Elvis+orig`
    3dcalc -a Elvis+orig -expr "step(a-$ccc)" -prefix Presley

Algorithm:
  (a) Set some initial clip value using wizardry (AKA 'variance').
  (b) Find the median of all positive values >= clip value.
  (c) Set the clip value to 0.50 of this median.
  (d) Loop back to (b) until the clip value doesn't change.
This method was made up out of nothing, based on histogram gazing.

Options:
--------
  -mfrac ff = Use the number ff instead of 0.50 in the algorithm.

  -grad ppp = In addition to using the 'one size fits all routine',
              also compute a 'gradual' clip level as a function
              of voxel position, and output that to a dataset with
              prefix 'ppp'.
             [This is the same 'gradual' clip level that is now the
              default in 3dAutomask - as of 24 Oct 2006.
              You can use this option to see how 3dAutomask clips
              the dataset as its first step.  The algorithm above is
              is used in each octant of the dataset, and then these
              8 values are interpolated to cover the whole volume.]
Notes:
------
* Use at your own risk!  You might want to use the AFNI Histogram
    plugin to see if the results are reasonable.  This program is
    likely to produce bad results on images gathered with local
    RF coils, or with pulse sequences with unusual contrasts.

* For brain images, most brain voxels seem to be in the range from
    the clip level (mfrac=0.5) to about 3-3.5 times the clip level.
    - In T1-weighted images, voxels above that level are usually
      blood vessels (e.g., inflow artifact brightens them).

* If the input dataset has more than 1 sub-brick, the data is
    analyzed on the median volume -- at each voxel, the median
    of all sub-bricks at that voxel is computed, and then this
    median volume is used in the histogram algorithm.

* If the input dataset is short- or byte-valued, the output will
    be an integer; otherwise, the output is a float value.
------
Author: Emperor Zhark -- Sadistic Galactic Domination since 1994!


++ Compile date = Nov  5 2009




AFNI program: 3dclust


Program: 3dclust 
Author:  RW Cox et al 
Date:    21 Jul 2005 

3dclust - performs simple-minded cluster detection in 3D datasets       
                                                                        
     This program can be used to find clusters of 'active' voxels and   
     print out a report about them.                                     
      * 'Active' refers to nonzero voxels that survive the threshold    
         that you (the user) have specified                             
      * Clusters are defined by a connectivity radius parameter 'rmm'   
                                                                        
      Note: by default, this program clusters on the absolute values    
            of the voxels                                               
----------------------------------------------------------------------- 
Usage: 3dclust [editing options] [other options] rmm vmul dset ...      
-----                                                                   
                                                                        
Examples:                                                               
--------                                                                
                                                                        
    3dclust         -1clip   0.3  5 2000 func+orig'[1]'                 
    3dclust -1noneg -1thresh 0.3  5 2000 func+orig'[1]'                 
    3dclust -1noneg -1thresh 0.3  5 2000 func+orig'[1]' func+orig'[3]   
                                                                        
    3dclust -noabs  -1clip 0.5   -dxyz=1  1  10 func+orig'[1]'          
    3dclust -noabs  -1clip 0.5            5 700 func+orig'[1]'          
                                                                        
    3dclust -noabs  -2clip 0 999 -dxyz=1 1  10 func+orig'[1]'           
                                                                        
    3dclust                   -1clip 0.3  5 3000 func+orig'[1]'         
    3dclust -quiet            -1clip 0.3  5 3000 func+orig'[1]'         
    3dclust -summarize -quiet -1clip 0.3  5 3000 func+orig'[1]'         
    3dclust -1Dformat         -1clip 0.3  5 3000 func+orig'[1]' > out.1D
----------------------------------------------------------------------- 
                                                                        
Arguments (must be included on command line):                           
---------                                                               
                                                                        
   rmm            : cluster connection radius (in millimeters).         
                    All nonzero voxels closer than rmm millimeters      
                    (center-to-center distance) to the given voxel are  
                    included in the cluster.                            
                     * If rmm = 0, then clusters are defined by nearest-
                       neighbor connectivity                            
                                                                        
   vmul           : minimum cluster volume (micro-liters)               
                    i.e., determines the size of the volume cluster.    
                     * If vmul = 0, then all clusters are kept.         
                     * If vmul < 0, then the absolute vmul is the minimum
                          number of voxels allowed in a cluster.        
                                                                        
   dset           : input dataset (more than one allowed, but only the  
                    first sub-brick of the dataset)                     
                                                                        
 The results are sent to standard output (i.e., the screen)             
                                                                        
----------------------------------------------------------------------- 
                                                                        
Options:                                                                
-------                                                                 
                                                                        
* Editing options are as in 3dmerge (see 3dmerge -help)                 
  (including -1thresh, -1dindex, -1tindex, -dxyz=1 options)             
                                                                        
* -noabs      => Use the signed voxel intensities (not the absolute     
                 value) for calculation of the mean and Standard        
                 Error of the Mean (SEM)                                
                                                                        
* -summarize  => Write out only the total nonzero voxel                 
                 count and volume for each dataset                      
                                                                        
* -nosum      => Suppress printout of the totals                        
                                                                        
* -verb       => Print out a progress report (to stderr)                
                 as the computations proceed                            
                                                                        
* -1Dformat   => Write output in 1D format (now default). You can       
                 redirect the output to a .1D file and use the file     
                 as input to whereami for obtaining Atlas-based         
                 information on cluster locations.                      
                 See whereami -help for more info.                      
* -no_1Dformat=> Do not write output in 1D format.                      
                                                                        
* -quiet      => Suppress all non-essential output                      
                                                                        
* -mni        => If the input dataset is in +tlrc coordinates, this     
                 option will stretch the output xyz-coordinates to the  
                 MNI template brain.                                    
                                                                        
           N.B.1: The MNI template brain is about 5 mm higher (in S),   
                  10 mm lower (in I), 5 mm longer (in PA), and tilted   
                  about 3 degrees backwards, relative to the Talairach- 
                  Tournoux Atlas brain.  For more details, see          
                    http://www.mrc-cbu.cam.ac.uk/Imaging/mnispace.html  
           N.B.2: If the input dataset is not in +tlrc coordinates,     
                  then the only effect is to flip the output coordinates
                  to the 'LPI' (neuroscience) orientation, as if you    
                  gave the '-orient LPI' option.)                       
                                                                        
* -isovalue   => Clusters will be formed only from contiguous (in the   
                 rmm sense) voxels that also have the same value.       
                                                                        
           N.B.:  The normal method is to cluster all contiguous        
                  nonzero voxels together.                              
                                                                        
* -isomerge   => Clusters will be formed from each distinct value       
                 in the dataset; spatial contiguity will not be         
                 used (but you still have to supply rmm and vmul        
                 on the command line).                                  
                                                                        
           N.B.:  'Clusters' formed this way may well have components   
                   that are widely separated!                           
                                                                        
* -prefix ppp => Write a new dataset that is a copy of the              
                 input, but with all voxels not in a cluster            
                 set to zero; the new dataset's prefix is 'ppp'         
                                                                        
           N.B.:  Use of the -prefix option only affects the            
                  first input dataset                                   
----------------------------------------------------------------------- 
                                                                        
E.g., 3dclust -1clip 0.3  5  3000 func+orig'[1]'                        
                                                                        
  The above command tells 3dclust to find potential cluster volumes for 
  dataset func+orig, sub-brick #1, where the threshold has been set     
  to 0.3 (i.e., ignore voxels with an activation threshold of >0.3 or   
  <-0.3.  Voxels must be no more than 5 mm apart, and the cluster volume
  must be at least 3000 micro-liters in size.                           
                                                                        
Explanation of 3dclust Output:                                          
-----------------------------                                           
                                                                        
   Volume       : Volume that makes us the cluster, in microliters (mm^3)
                  (or the number of voxels, if -dxyz=1 is given)        
                                                                        
   CM RL        : Center of mass (CM) for the cluster in the Right-Left 
                  direction (i.e., the coordinates for the CM)          
                                                                        
   CM AP        : Center of mass for the cluster in the                 
                  Anterior-Posterior direction                          
                                                                        
   CM IS        : Center of mass for the cluster in the                 
                  Inferior-Superior direction                           
                                                                        
   minRL, maxRL : Bounding box for the cluster, min and max             
                  coordinates in the Right-Left direction               
                                                                        
   minAP, maxAP : Min and max coordinates in the Anterior-Posterior     
                  direction of the volume cluster                       
                                                                        
   minIS, max IS: Min and max coordinates in the Inferior-Superior      
                  direction of the volume cluster                       
                                                                        
   Mean         : Mean value for the volume cluster                     
                                                                        
   SEM          : Standard Error of the Mean for the volume cluster     
                                                                        
   Max Int      : Maximum Intensity value for the volume cluster        
                                                                        
   MI RL        : Coordinate of the Maximum Intensity value in the      
                  Right-Left direction of the volume cluster            
                                                                        
   MI AP        : Coordinate of the Maximum Intensity value in the      
                  Anterior-Posterior direction of the volume cluster    
                                                                        
   MI IS        : Coordinate of the Maximum Intensity value in the      
                  Inferior-Superior direction of the volume cluster     
----------------------------------------------------------------------- 
                                                                        
Nota Bene:                                                              
                                                                        
   * The program does not work on complex- or rgb-valued datasets!      
                                                                        
   * Using the -1noneg option is strongly recommended!                  
                                                                        
   * 3D+time datasets are allowed, but only if you use the              
     -1tindex and -1dindex options.                                     
                                                                        
   * Bucket datasets are allowed, but you will almost certainly         
     want to use the -1tindex and -1dindex options with these.          
                                                                        
   * SEM values are not realistic for interpolated data sets!           
     A ROUGH correction is to multiply the SEM of the interpolated      
     data set by the square root of the number of interpolated          
     voxels per original voxel.                                         
                                                                        
   * If you use -dxyz=1, then rmm should be given in terms of           
     voxel edges (not mm) and vmul should be given in terms of          
     voxel counts (not microliters).  Thus, to connect to only          
     3D nearest neighbors and keep clusters of 10 voxels or more,       
     use something like '3dclust -dxyz=1 1.01 10 dset+orig'.            
     In the report, 'Volume' will be voxel count, but the rest of       
     the coordinate dependent information will be in actual xyz         
     millimeters.                                                       
                                                                        
  * The default coordinate output order is DICOM.  If you prefer        
    the SPM coordinate order, use the option '-orient LPI' or           
    set the environment variable AFNI_ORIENT to 'LPI'.  For more        
    information, see file README.environment.                           

++ Compile date = Nov  5 2009




AFNI program: 3dCM
Usage: 3dCM [options] dset
Output = center of mass of dataset, to stdout.
  -mask mset   Means to use the dataset 'mset' as a mask:
                 Only voxels with nonzero values in 'mset'
                 will be averaged from 'dataset'.  Note
                 that the mask dataset and the input dataset
                 must have the same number of voxels.
  -automask    Generate the mask automatically.
  -set x y z   After computing the CM of the dataset, set the
                 origin fields in the header so that the CM
                 will be at (x,y,z) in DICOM coords.

++ Compile date = Nov  5 2009




AFNI program: 3dConvolve
++ 3dConvolve: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward
Program to calculate the voxelwise convolution of given impulse response   
function (IRF) time series contained in a 3d+time dataset with a specified 
input stimulus function time series.  This program will also calculate     
convolutions involving multiple IRF's and multiple stimulus functions.     
Input options include addition of system noise to the estimated output.    
Output consists of an AFNI 3d+time dataset which contains the estimated    
system response.  Alternatively, if all inputs are .1D time series files,  
then the output will be a single .1D time series file.                     
                                                                       
Usage:                                                                 
3dConvolve                                                             
-input fname         fname = filename of 3d+time template dataset      
[-input1D]           flag to indicate all inputs are .1D time series   
[-mask mname]        mname = filename of 3d mask dataset               
[-censor cname]      cname = filename of censor .1D time series        
[-concat rname]      rname = filename for list of concatenated runs    
[-nfirst fnum]       fnum = number of first time point to calculate by 
                       convolution procedure.  (default = max maxlag)  
[-nlast  lnum]       lnum = number of last time point to calculate by  
                       convolution procedure.  (default = last point)  
[-polort pnum]       pnum = degree of polynomial corresponding to the  
                       baseline model  (default: pnum = 1)             
[-base_file bname]   bname = file containing baseline parameters       
                                                                       
-num_stimts num      num = number of input stimulus time series        
                       (default: num = 0)                              
-stim_file k sname   sname = filename of kth time series input stimulus
[-stim_minlag k m]   m = minimum time lag for kth input stimulus       
                       (default: m = 0)                                
[-stim_maxlag k n]   n = maximum time lag for kth input stimulus       
                       (default: n = 0)                                
[-stim_nptr k p]     p = number of stimulus function points per TR     
                       Note: This option requires 0 slice offset times 
                       (default: p = 1)                                
                                                                       
[-iresp k iprefix]   iprefix = prefix of 3d+time input dataset which   
                       contains the kth impulse response function      
                                                                       
[-errts eprefix]     eprefix = prefix of 3d+time input dataset which   
                       contains the residual error time series         
                       (i.e., noise which will be added to the output) 
                                                                       
[-sigma s]           s = std. dev. of additive Gaussian noise          
                       (default: s = 0)                                
[-seed d]            d = seed for random number generator              
                       (default: d = 1234567)                          
                                                                       
[-xout]              flag to write X matrix to screen                  
[-output tprefix]    tprefix = prefix of 3d+time output dataset which  
                       will contain the convolved time series data     
                       (or tprefix = prefix of .1D output time series  
                       if the -input1D option is used)                 
                                                                       

++ Compile date = Nov  5 2009




AFNI program: 3dcopy
Usage 1: 3dcopy [-verb] [-denote] old_prefix new_prefix
  Will copy all datasets using the old_prefix to use the new_prefix;
    3dcopy fred ethel
  will copy   fred+orig.HEAD    to ethel+orig.HEAD
              fred+orig.BRIK    to ethel+orig.BRIK
              fred+tlrc.HEAD    to ethel+tlrc.HEAD
              fred+tlrc.BRIK.gz to ethel+tlrc.BRIK.gz

Usage 2: 3dcopy old_prefix+view new_prefix
  Will copy only the dataset with the given view (orig, acpc, tlrc).

Usage 3: 3dcopy old_dataset new_prefix
  Will copy the non-AFNI formatted dataset (e.g., MINC, ANALYZE, CTF)
  to the AFNI formatted dataset with the given new prefix.

Notes:
* The new datasets have new ID codes.  If you are renaming
   multiple datasets (as in Usage 1), then if the old +orig
   dataset is the warp parent of the old +acpc and/or +tlrc
   datasets, then the new +orig dataset will be the warp
   parent of the new +acpc and +tlrc datasets.  If any other
   datasets point to the old datasets as anat or warp parents,
   they will still point to the old datasets, not these new ones.
* The BRIK files are copied if they exist, keeping the compression
   suffix unchanged (if any).
* The old_prefix may have a directory name attached in front,
   as in 'gerard/manley/hopkins'.
* If the new_prefix does not have a directory name attached
   (i.e., does NOT look like 'homer/simpson'), then the new
   datasets will be written in the current directory ('./').
* The new_prefix cannot JUST be a directory (unlike the Unix
   utility 'cp'); you must supply a filename prefix, even if
   is identical to the filename prefix in old_prefix.
* The '-verb' option will print progress reports; otherwise, the
   program operates silently (unless an error is detected).
* The '-denote' option will remove any Notes from the file.

++ Compile date = Nov  5 2009




AFNI program: 3dCRUISEtoAFNI

Usage: 3dCRUISEtoAFNI -input CRUISE_HEADER.dx
 Converts a CRUISE dataset defined by a heder in OpenDX format
 The conversion is based on sample data and information
 provided by Aaron Carass from JHU's IACL iacl.ece.jhu.edu
   [-novolreg|-noxform]: Ignore any Rotate, Volreg, Tagalign, 
                or WarpDrive transformations present in 
                the Surface Volume.
  Common Debugging Options:
   [-trace]: Turns on In/Out debug and Memory tracing.
             For speeding up the tracing log, I recommend 
             you redirect stdout to a file when using this option.
             For example, if you were running suma you would use:
             suma -spec lh.spec -sv ... > TraceFile
             This option replaces the old -iodbg and -memdbg.
   [-TRACE]: Turns on extreme tracing.
   [-nomall]: Turn off memory tracing.
   [-yesmall]: Turn on memory tracing (default).
  NOTE: For programs that output results to stdout
    (that is to your shell/screen), the debugging info
    might get mixed up with your results.
 

++ SUMA version 2006_7_3

CVS tag:
   SUMA_2005_04_29_1733

Compile Date:
   Nov  5 2009

       Ziad S. Saad SSCC/NIMH/NIH saadz@mail.nih.gov     



AFNI program: 3dDeconvolve
++ 3dDeconvolve: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward, et al.

------------------------------------------------------------------------
-----                 DESCRIPTION and PROLEGOMENON                 -----
------------------------------------------------------------------------
Program to calculate the deconvolution of a measurement 3D+time dataset 
with a specified input stimulus time series.  This program can also     
perform multiple linear regression using multiple input stimulus time   
series. Output consists of an AFNI 'bucket' type dataset containing     
(for each voxel)                                                        
 * the least squares estimates of the linear regression coefficients    
 * t-statistics for significance of the coefficients                    
 * partial F-statistics for significance of individual input stimuli    
 * the F-statistic for significance of the overall regression model     
The program can optionally output extra datasets containing             
 * the estimated impulse response function                              
 * the fitted model and error (residual) time series                    
------------------------------------------------------------------------
* Program 3dDeconvolve does Ordinary Least Squares (OLSQ) regression.   
* Program 3dREMLfit can be used to do Generalized Least Squares (GLSQ)  
  regression (AKA 'pre-whitened' least squares) combined with REML      
  estimation of an ARMA(1,1) temporal correlation structure:            
    http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dREMLfit.html   
* The input to 3dREMLfit is the .xmat.1D matrix file output by          
  3dDeconvolve, which also writes a 3dREMLfit command line to a file    
  to make it relatively easy to use the latter program.                 
* Nonlinear time series model fitting can be done with program 3dNLfim: 
    http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dNLfim.html     
* Preprocessing of the time series input can be done with various AFNI  
  programs, or with the 'uber-script' afni_proc.py:                     
    http://afni.nimh.nih.gov/pub/dist/doc/program_help/afni_proc.py.html
* The recommended way to use 3dDeconvolve is via afni_proc.py, especially
  if you are not familiar with its usage and its peculiarities.         
------------------------------------------------------------------------
Consider the time series model  Z(t) = K(t)*S(t) + baseline + noise,    
where Z(t) = data                                                       
      K(t) = kernel (e.g., hemodynamic response function or HRF)        
      S(t) = stimulus time series                                       
  baseline = constant, drift, etc. [regressors of no interest]          
     and * = convolution                                                
Then 3dDeconvolve solves for K(t) given S(t).  If you want to process   
the reverse problem and solve for S(t) given the kernel K(t), use the   
program 3dTfitter with the '-FALTUNG' option.  The difference between   
the two cases is that K(t) is presumed to be causal and have limited    
support, whereas S(t) is a full-length time series.  Note that program  
3dTfitter does not have all the capabilities of 3dDeconvolve for        
calculating output statistics; on the other hand, 3dTfitter can solve   
a deconvolution problem (in either direction) with L1 or L2 regression, 
and with sign constraints on the computed values (e.g., requiring that  
the output S(t) or K(t) be non-negative):                               
  http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dTfitter.html     
------------------------------------------------------------------------
The 'baseline model' in 3dDeconvolve (and 3dREMLfit) does not mean just 
a constant (mean) level of the signal, or even just the slow drifts that
happen in FMRI time series.  'Baseline' here also means the model that  
forms the null hypothesis.  The Full_Fstat result is the F-statistic    
of the full model (all regressors) vs. the baseline model.  Thus, it    
it common to include irregular time series, such as estimated motion    
parameters, in the baseline model via the -stim_file/-stim_base options.
------------------------------------------------------------------------
It is VERY important to realize that statistics (F, t, R^2) computed in 
3dDeconvolve are MARGINAL (or partial) statistics.  For example, the    
t-statistic for a single beta coefficient measures the significance of  
that beta value against the regression model where ONLY that one column 
of the matrix is removed; that is, the null hypothesis for that         
t-statistic is the full regression model minus just that single         
regressor.  Similarly, the F-statistic for a set of regressors measures 
the significance of that set of regressors (eg, a set of TENT functions)
against the full model with just that set of regressors removed.  If    
this explanation or its consequences are unclear, you need to consult   
with a statistician, or with the AFNI message board guru entities.      
------------------------------------------------------------------------

Usage Details:                                                         
3dDeconvolve command-line-arguments ...
                                                                       
**** Input data and control options:                                   
-input fname         fname = filename of 3D+time input dataset         
                       (more than  one filename  can be  given)        
                       (here,   and  these  datasets  will  be)        
                       (catenated  in time;   if you do this, )        
                       ('-concat' is not needed and is ignored)        
                  ** You can input a 1D time series file here,         
                     but the time axis should run along the            
                     ROW direction, not the COLUMN direction as        
                     in the -input1D option.  You can automatically    
                     transpose a 1D file on input using the \'        
                     operator at the end of the filename, as in        
                       -input fred.1D\'                               
                   * This is the only way to use 3dDeconvolve          
                     with a multi-column 1D time series file.          
                   * The output datasets by default will then          
                     be in 1D format themselves.  To have them         
                     formatted as AFNI datasets instead, use           
                       -DAFNI_WRITE_1D_AS_PREFIX=YES                   
                     on the command line.                              
                   * You should use '-force_TR' to set the TR of       
                     the 1D 'dataset' if you use '-input' rather       
                     than '-input1D' [the default is 1.0 sec].         
[-force_TR TR]       Use this value of TR instead of the one in        
                     the -input dataset.                               
                     (It's better to fix the input using 3drefit.)     
[-input1D dname]     dname = filename of single (fMRI) .1D time series 
                             where time run downs the column.          
[-TR_1D tr1d]        tr1d = TR for .1D time series [default 1.0 sec].  
                     This option has no effect without -input1D        
[-nodata [NT [TR]]   Evaluate experimental design only (no input data) 
[-mask mname]        mname = filename of 3d mask dataset               
[-automask]          build a mask automatically from input data        
                      (will be slow for long time series datasets)     
                  ** If you don't specify ANY mask, the program will   
                      build one automatically (from each voxel's RMS)  
                      and use this mask solely for the purpose of      
                      reporting truncation-to-short errors (unless     
                      '-float' is used) AND for computing the FDR curves
                      in the bucket dataset's header (unless '-noFDR'  
                      is used, of course).                             
                   * If you don't want the FDR curves to be computed   
                      inside this automatically generated mask, then   
                      use '-noFDR' and later run '3drefit -addFDR' on  
                      the bucket dataset.                              
                   * To be precise, the above default masking only     
                      happens when you use '-input' to run the program 
                      with a 3D+time dataset; not with '-input1D'.     
[-censor cname]      cname = filename of censor .1D time series        
[-CENSORTR clist]    clist = list of strings that specify time indexes 
                       to be removed from the analysis.  Each string is
                       of one of the following forms:                  
                           37 => remove global time index #37          
                         2:37 => remove time index #37 in run #2       
                       37..47 => remove global time indexes #37-47     
                       37-47  => same as above                         
                     2:37..47 => remove time indexes #37-47 in run #2  
                     *:0-2    => remove time indexes #0-2 in all runs  
                      +Time indexes within each run start at 0.        
                      +Run indexes start at 1 (just be to confusing).  
                      +Multiple -CENSORTR options may be used, or      
                        multiple -CENSORTR strings can be given at     
                        once, separated by spaces or commas.           
                      +N.B.: 2:37,47 means index #37 in run #2 and     
                        global time index 47; it does NOT mean         
                        index #37 in run #2 AND index #47 in run #2.   
[-concat rname]      rname = filename for list of concatenated runs    
                      * 'rname' can be in the format                   
                          '1D: 0 100 200 300'                          
                        which indicates 4 runs, the first of which     
                        starts at time index=0, second at index=100,   
                        and so on.                                     
[-nfirst fnum]       fnum = number of first dataset image to use in the
                       deconvolution procedure. [default = max maxlag] 
[-nlast  lnum]       lnum = number of last dataset image to use in the 
                       deconvolution procedure. [default = last point] 
[-polort pnum]       pnum = degree of polynomial corresponding to the  
                       null hypothesis  [default: pnum = 1]            
                    ** If you use 'A' for pnum, the program will       
                       automatically choose a value based on the       
                       time duration of the longest run.               
[-legendre]          use Legendre polynomials for null hypothesis      
                       (baseline model)                                
[-nolegendre]        use power polynomials for null hypotheses         
                       [default is -legendre]                          
[-nodmbase]          don't de-mean baseline time series                
                       (i.e., polort>0 and -stim_base inputs)          
[-dmbase]            de-mean baseline time series [default if polort>=0]
[-svd]               Use SVD instead of Gaussian elimination [default] 
[-nosvd]             Use Gaussian elimination instead of SVD           
                       (only use for testing + backwards compatibility)
[-rmsmin r]          r = minimum rms error to reject reduced model     
                       (default = 0; don't use this option normally!)  
[-nocond]            DON'T calculate matrix condition number           
                      ** This value is NOT the same as Matlab!         
[-singvals]          Print out the matrix singular values              
                      (useful for some testing/debugging purposes)     
[-GOFORIT [g]]       Use this to proceed even if the matrix has        
                     bad problems (e.g., duplicate columns, large      
                     condition number, etc.).                          
               *N.B.: Warnings that you should particularly heed have  
                      the string '!!' somewhere in their text.         
               *N.B.: Error and Warning messages go to stderr and      
                      also to file 3dDeconvolve.err.               
               *N.B.: The optional number 'g' that appears is the      
                      number of warnings that can be ignored.          
                      That is, if you use -GOFORIT 7 and 9 '!!'        
                      matrix warnings appear, then the program will    
                      not run.  If 'g' is not present, 1 is used.      
[-allzero_OK]        Don't consider all zero matrix columns to be      
                      the type of error that -GOFORIT is needed to     
                      ignore.                                          
                     * Please know what you are doing when you use     
                       this option!                                    
[-Dname=val]       = Set environment variable 'name' to 'val' for this 
                     run of the program only.                          
                                                                       
******* Input stimulus options *******                                 
                                                                       
-num_stimts num      num = number of input stimulus time series        
                       (0 <= num)   [default: num = 0]                 
               *N.B.: '-num_stimts' must come before any of the        
                      following 'stim' options!                        
               *N.B.: Most 'stim' options have as their first argument 
                      an integer 'k', ranging from 1..num, indicating  
                      which stimulus class the argument is defining.   
                                                                       
-stim_file k sname   sname = filename of kth time series input stimulus
               *N.B.: This option directly inserts a column into the   
                      regression matrix; unless you are using the 'old'
                      method of deconvolution (cf below), you would    
                      only use '-stim_file' to insert baseline model   
                      components such as motion parameters.            
                                                                       
[-stim_label k slabel] slabel = label for kth input stimulus           
               *N.B.: This option is highly recommended, so that       
                      output sub-bricks will be labeled for ease of    
                      recognition when you view them in the AFNI GUI.  
                                                                       
[-stim_base k]       kth input stimulus is part of the baseline model  
               *N.B.: 'Baseline model' == Null Hypothesis model        
               *N.B.: The most common baseline components to add are   
                      the 6 estimated motion parameters from 3dvolreg. 
                                                                       
**N.B.: The following 3 options are for the 'old' style of explicit    
        deconvolution.  For most purposes, their usage is no longer    
        recommended.  Instead, you should use the '-stim_times' options
        to directly input the stimulus times, rather than code the     
        stimuli as a sequence of 0s and 1s in this 'old' method!       
                                                                       
[-stim_minlag k m]   m = minimum time lag for kth input stimulus       
                       [default: m = 0]                                
[-stim_maxlag k n]   n = maximum time lag for kth input stimulus       
                       [default: n = 0]                                
[-stim_nptr k p]     p = number of stimulus function points per TR     
                       Note: This option requires 0 slice offset times 
                       [default: p = 1]                                
                                                                       
**N.B.: The '-stim_times' options below are the recommended way of     
        analyzing FMRI time series data now.  The options directly     
        above are only maintained for the sake of backwards            
        compatibility!  For most FMRI users, the 'BLOCK' and 'TENT'    
        response models will serve their needs.                        
                                                                       
[-stim_times k tname Rmodel]                                           
   Generate the k-th response model from a set of stimulus times       
   given in file 'tname'.  The response model is specified by the      
   'Rmodel' argument, which can be one of the following:               
         [In the descriptions, a '1 parameter' model is a model ]      
         [that has a fixed shape, and only the amplitude varies.]      
         [Models with more than 1 parameter have multiple basis ]      
         [functions, and the parameters are their amplitudes.   ]      
                                                                       
     'BLOCK(d,p)'  = 1 parameter block stimulus of duration 'd'        
                    ** There are 2 variants of BLOCK:                  
                         BLOCK4 [the default] and BLOCK5               
                       which have slightly different delays:           
                         HRF(t) = int( g(t-s) , s=0..min(t,d) )        
                       where g(t) = t^q * exp(-t) /(q^q*exp(-q))       
                       and q = 4 or 5.  The case q=5 is delayed by     
                       about 1 second from the case q=4.               
                    ** Despite the name, you can use 'BLOCK' for event-
                       related analyses just by setting the duration to
                       a small value; e.g., 'BLOCK5(1,1)'              
                    ** The 'p' parameter is the amplitude of the       
                       basis function, and should usually be set to 1. 
                       If 'p' is omitted, the amplitude will depend on 
                       the duration 'd', which is useful only in       
                       special circumstances!                          
     'TENT(b,c,n)' = n parameter tent function expansion from times    
                       b..c after stimulus time [piecewise linear]     
                       [n must be at least 2; time step is (c-b)/(n-1)]
    'CSPLIN(b,c,n)'= n parameter cubic spline function expansion       
                       from times b..c after stimulus time             
                     ** TENT and CSPLIN are 'cardinal' interpolation   
                        functions; CSPLIN is a drop-in upgrade of      
                        TENT to a differentiable set of functions.     
                       [n must be at least 4]                          
     'GAM(p,q)'    = 1 parameter gamma variate                         
                         (t/(p*q))^p * exp(p-t/q)                      
                       Defaults: p=8.6 q=0.547 if only 'GAM' is used   
     'SPMG1'       = 1 parameter SPM gamma variate basis function      
                         exp(-t)*(A1*t^P1-A2*t^P2) where               
                       A1 = 0.0083333333  P1 = 5  (main positive lobe) 
                       A2 = 1.274527e-13  P2 = 15 (undershoot part)    
                       This function is NOT normalized to have peak=1! 
     'SPMG2'       = 2 parameter SPM: gamma variate + d/dt derivative  
                       [For backward compatibility: 'SPMG' == 'SPMG2'] 
     'SPMG3'       = 3 parameter SPM basis function set                
                      * The SPMGx functions now can take an optional   
                        (duration) argument, specifying that the primal
                        SPM basis functions should be convolved with   
                        a square wave 'duration' seconds long and then 
                        be normalized to have peak absolute value = 1; 
                        e.g., 'SPMG3(20)' for a 20 second duration with
                        three basis function.  [28 Apr 2009]           
                      * Note that 'SPMG1(0)' will produce the usual    
                        'SPMG1' wavefunction shape, but normalized to  
                        have peak value = 1 (for example).             
     'POLY(b,c,n)' = n parameter Legendre polynomial expansion         
                       from times b..c after stimulus time             
                       [n can range from 1 (constant) to 20]           
     'SIN(b,c,n)'  = n parameter sine series expansion                 
                       from times b..c after stimulus time             
                       [n must be at least 1]                          
     'WAV(d)'      = 1 parameter block stimulus of duration 'd'.       
                      * This is the '-WAV' function from program waver!
                      * If you wish to set the shape parameters of the 
                        WAV function, you can do that by adding extra  
                        arguments, in the order                        
                         delay time , rise time , fall time ,          
                         undershoot fraction, undershoot restore time  
                      * The default values are 'WAV(d,2,4,6,0.2,2)'    
                      * Omitted parameters get the default values.     
                      * 'WAV(d,,,,0)' (setting undershoot=0) is        
                        very similar to 'BLOCK5(d,1)', for d > 0.      
                      * Setting duration d to 0 (or just using 'WAV')  
                        gives the pure '-WAV' impulse response function
                        from waver.                                    
                      * If d > 0, the WAV(0) function is convolved with
                        a square wave of duration d to make the HRF,   
                        and the amplitude is scaled back down to 1.    
     'EXPR(b,c) exp1 ... expn'                                         
                   = n parameter; arbitrary expressions from times     
                     b..c after stimulus time                          
                      * Expressions are separated by spaces, so        
                        each expression must be a contiguous block     
                        of non-whitespace characters                   
                      * Expressions use the same format as 3dcalc      
                      * Symbols that can be used in an expression:     
                         t = time in sec since stimulus time           
                         x = time scaled to be x= 0..1 for t=bot..top  
                         z = time scaled to be z=-1..1 for t=bot..top  
                      * Spatially dependent regressors are not allowed!
                      * Other symbols are set to 0 (silently).         
                                                                       
 * 3dDeconvolve does LINEAR regression, so the model parameters are    
   amplitudes of the basis functions; 1 parameter models are 'simple'  
   regression, where the shape of the impulse response function is     
   fixed and only the magnitude/amplitude varies.  Models with more    
   free parameters have 'variable' shape impulse response functions.   
                                                                       
 * If you want NONLINEAR regression, see program 3dNLfim.              
                                                                       
 * If you want LINEAR regression with allowance for non-white noise,   
   use program 3dREMLfit.                                              
                                                                       
 * For the format of the 'tname' file, see the last part of            
 http://afni.nimh.nih.gov/pub/dist/doc/misc/Decon/DeconSummer2004.html 
   and also see the other documents stored in the directory below:     
 http://afni.nimh.nih.gov/pub/dist/doc/misc/Decon/                     
   and also read the presentation below:                               
 http://afni.nimh.nih.gov/pub/dist/edu/latest/afni_handouts/afni05_regression.pdf
   ** Note Well:                                                       
    * The contents of the 'tname' file are NOT just 0s and 1s,         
      but are the actual times of the stimulus events IN SECONDS.      
    * You can give the times on the command line by using a string     
      of the form '1D: 3.2 7.9 | 8.2 16.2 23.7' in place of 'tname',   
      where the '|' character indicates the start of a new line        
      (so this example is for a case with 2 catenated runs).           
    * You cannot use the '1D:' form of input for any of the more       
      complicated '-stim_times_*' options below!!                      
    * It is a good idea to examine the shape of the response models    
      if you are unsure of what the different functions will look like.
      You can graph columns from the .xmat.1D matrix file with 1dplot; 
      for example, comparing 'WAV(10)', 'BLOCK4(10,1)', and 'SPMG1(10)':

       3dDeconvolve -nodata 200 1.0 -num_stimts 3 -polort -1         \
                    -local_times -x1D stdout:                        \
                    -stim_times 1 '1D: 10 60 110 160' 'WAV(10)'      \
                    -stim_times 2 '1D: 10 60 110 160' 'BLOCK4(10,1)' \
                    -stim_times 3 '1D: 10 60 110 160' 'SPMG1(10)'    \
             | 1dplot -one -stdin -xlabel Time -ynames WAV BLOCK4 SPMG1
                                                                       
[-stim_times_AM1 k tname Rmodel]                                       
   Similar, but generates an amplitude modulated response model.       
   The 'tname' file should consist of 'time*amplitude' pairs.          
   As in '-stim_times', the '*' character can be used as a placeholder 
   when an imaging run doesn't have any stimulus of a given class.     
   *N.B.: If no run has a stimulus of a given class, then you must     
          have at least 1 time that is not '*' for -stim_times_* to    
          work.  You can use a negative time for this purpose, which   
          will produce a warning message and then be ignored, as in:   
             -1*37                                                     
             *                                                         
          for a 2 run 'tname' file to be used with -stim_times_*.      
          In such a case, you will also need the -allzero_OK option,   
          and probably -GOFORIT as well.                               
[-stim_times_AM2 k tname Rmodel]                                       
   Similar, but generates 2 response models: one with the mean         
   amplitude and one with the differences from the mean.               
                                                                       
** NOTE [04 Dec 2008] **                                               
 -stim_times_AM1 and -stim_times_AM2 now take files with more          
   than 1 amplitude attached to each time; for example,                
     33.7*9,-2,3                                                       
   indicates a stimulus at time 33.7 seconds with 3 amplitudes         
   attached (9 and -2 and 3).  In this example, -stim_times_AM2 would  
   generate 4 response models: 1 for the constant response case        
   and 1 scaled by each of the amplitude sets.                         
 For more information on modulated regression, see                     
   http://afni.nimh.nih.gov/pub/dist/doc/misc/Decon/AMregression.pdf   
                                                                       
** NOTE [08 Dec 2008] **                                               
 -stim_times_AM1 and -stim_times_AM2 now have 1 extra response model   
 function available:                                                   
   dmBLOCK (or dmBLOCK4 or dmBLOCK5)                                   
 where 'dm' means 'duration modulated'.  If you use this response      
 model, then the LAST married parameter in the timing file will        
 be used to modulate the duration of the block stimulus.  Any          
 earlier parameters will be used to modulate the amplitude,            
 and should be separated from the duration parameter by a ':'          
 character, as in '30*5,3:12' which means (for dmBLOCK):               
   a block starting at 30 s,                                           
   with amplitude parameters 5 and 3,                                  
   and with duration 12 s.                                             
 The unmodulated peak response of dmBLOCK is normally set to 1.        
 If you want the peak response to be a different value, use            
   dmBLOCK(p)                                                          
 where p = the desired peak value.  As a special case, if you set      
 p = 0, then the peak response will vary with the duration, as         
 the simulated BOLD response accumulates.  Understand what you         
 are doing in this case!                                               
 *N.B.: The maximum allowed dmBLOCK duration is 999 s.                 
 *N.B.: You can also use dmBLOCK with -stim_times_IM, in which case    
        each time in the 'tname' file should have just ONE extra       
        parameter -- the duration -- married to it, as in '30:15',     
        meaning a block of duration 15 seconds starting at t=30 s.     
 For some graphs of what dmBLOCK regressors look like, see             
   http://afni.nimh.nih.gov/pub/dist/doc/misc/Decon/AMregression.pdf   
                                                                       
[-stim_times_IM k tname Rmodel]                                        
   Similar, but each separate time in 'tname' will get a separate      
   regressor; 'IM' means 'Individually Modulated' -- that is, each     
   event will get its own amplitude(s).  Presumably you will collect   
   these many amplitudes afterwards and do some sort of statistics     
   on them.                                                            
 *N.B.: Each time in the 'tname' file will get a separate regressor.   
        If some time is outside the duration of the imaging run(s),    
        or if the response model for that time happens to hit only     
        censored-out data values, then the corresponding regressor     
        will be all zeros.  Normally, 3dDeconvolve will not run        
        if the matrix has any all zero columns.  To carry out the      
        analysis, use the '-allzero_OK' option.  Amplitude estimates   
        for all zero columns will be zero, and should be excluded      
        from any subsequent analysis.  (Probably you should fix the    
        times in the 'tname' file instead of using '-allzero_OK'.)     
                                                                       
[-global_times]                                                        
[-local_times]                                                         
   By default, 3dDeconvolve guesses whether the times in the 'tname'   
   files for the various '-stim_times' options are global times        
   (relative to the start of run #1) or local times (relative to       
   the start of each run).  With one of these options, you can force   
   the times to be considered as global or local for '-stim_times'     
   options that are AFTER the '-local_times' or '-global_times'.       
 ** Using one of these options (most commonly, '-local_times') is      
    very highly recommended.                                           
                                                                       
[-stim_times_millisec]                                                 
 This option scales all the times in any '-stim_times_*' option by     
 0.001; the purpose is to allow you to input the times in ms instead   
 of in s.  This factor will be applied to ALL '-stim_times' inputs,    
 before or after this option on the command line.  This factor will    
 be applied before -stim_times_subtract, so the subtraction value      
 (if present) must be given in seconds, NOT milliseconds!              
                                                                       
[-stim_times_subtract SS]                                              
 This option means to subtract 'SS' seconds from each time encountered 
 in any '-stim_times*' option.  The purpose of this option is to make  
 it simple to adjust timing files for the removal of images from the   
 start of each imaging run.  Note that this option will be useful      
 only if both of the following are true:                               
  (a) each imaging run has exactly the same number of images removed   
  (b) the times in the 'tname' files were not already adjusted for     
      these image removal (i.e., the times refer to the image runs     
      as acquired, not as input to 3dDeconvolve).                      
 In other words, use this option with understanding and care!          
 ** Note that the subtraction of 'SS' applies to ALL '-stim_times'     
    inputs, before or after this option on the command line!           
 ** And it applies to global times and local times alike!              
 ** Any time (thus subtracted) below 0 will be ignored, as falling     
    before the start of the imaging run.                               
 ** This option, and the previous one, are simply for convenience, to  
    help you in setting up your '-stim_times*' timing files from       
    whatever source you get them.                                      
                                                                       
[-basis_normall a]                                                     
   Normalize all basis functions for '-stim_times' to have             
   amplitude 'a' (must have a > 0).  The peak absolute value           
   of each basis function will be scaled to be 'a'.                    
   NOTE: -basis_normall only affect -stim_times options that           
         appear LATER on the command line                              
                                                                       
******* General linear test (GLT) options *******                      
                                                                       
-num_glt num         num = number of general linear tests (GLTs)       
                       (0 <= num)   [default: num = 0]                 
                  **N.B.: You only need this option if you have        
                          more than 10 GLTs specified; the program     
                          has built-in space for 10 GLTs, and          
                          this option is used to expand that space.    
                          If you use this option, you should place     
                          it on the command line BEFORE any of the     
                          other GLT options.                           
[-glt s gltname]     Perform s simultaneous linear tests, as specified 
                       by the matrix contained in file 'gltname'       
[-glt_label k glabel]  glabel = label for kth general linear test      
[-gltsym gltname]    Read the GLT with symbolic names from the file    
                       'gltname'; see the document below for details:  
  http://afni.nimh.nih.gov/pub/dist/doc/misc/Decon/DeconSummer2004.html
                                                                       
******* Options to create 3D+time datasets *******                     
                                                                       
[-iresp k iprefix]   iprefix = prefix of 3D+time output dataset which  
                       will contain the kth estimated impulse response 
[-tshift]            Use cubic spline interpolation to time shift the  
                       estimated impulse response function, in order to
                       correct for differences in slice acquisition    
                       times. Note that this effects only the 3D+time  
                       output dataset generated by the -iresp option.  
             **N.B.: This option only applies to the 'old' style of    
                     deconvolution analysis.  Do not use this with     
                     -stim_times analyses!                             
[-sresp k sprefix]   sprefix = prefix of 3D+time output dataset which  
                       will contain the standard deviations of the     
                       kth impulse response function parameters        
[-fitts  fprefix]    fprefix = prefix of 3D+time output dataset which  
                       will contain the (full model) time series fit   
                       to the input data                               
[-errts  eprefix]    eprefix = prefix of 3D+time output dataset which  
                       will contain the residual error time series     
                       from the full model fit to the input data       
[-TR_times dt]                                                         
   Use 'dt' as the stepsize for output of -iresp and -sresp file       
   for response models generated by '-stim_times' options.             
   Default is same as time spacing in the '-input' 3D+time dataset.    
   The units here are in seconds!                                      
                                                                       
**** Options to control the contents of the output bucket dataset **** 
                                                                       
[-fout]            Flag to output the F-statistics for each stimulus   
                    ** F tests the null hypothesis that each and every 
                       beta coefficient in the stimulus set is zero    
                    ** If there is only 1 stimulus class, then its     
                       '-fout' value is redundant with the Full_Fstat  
                       computed for all stimulus coefficients together.
[-rout]            Flag to output the R^2 statistics                   
[-tout]            Flag to output the t-statistics                     
                    ** t tests a single beta coefficient against zero  
                    ** If a stimulus class has only one regressor, then
                       F = t^2 and the F statistic is redundant with t.
[-vout]            Flag to output the sample variance (MSE) map        
[-nobout]          Flag to suppress output of baseline coefficients    
                     (and associated statistics) [** DEFAULT **]       
[-bout]            Flag to turn on output of baseline coefs and stats. 
                    ** Will make the output dataset larger.            
[-nocout]          Flag to suppress output of regression coefficients  
                     (and associated statistics)                       
                    ** Useful if you just want GLT results.            
[-full_first]      Flag to specify that the full model statistics will 
                     be first in the bucket dataset [** DEFAULT **]    
[-nofull_first]    Flag to specify that full model statistics go last  
[-nofullf_atall]   Flag to turn off the full model F statistic         
                     ** DEFAULT: the full F is always computed, even if
                     sub-model partial F's are not ordered with -fout. 
[-bucket bprefix]  Create one AFNI 'bucket' dataset containing various 
                     parameters of interest, such as the estimated IRF 
                     coefficients, and full model fit statistics.      
                     Output 'bucket' dataset is written to bprefix.    
[-nobucket]        Don't output a bucket dataset.  By default, the     
                     program uses '-bucket Decon' if you don't give    
                     either -bucket or -nobucket on the command line.  
[-noFDR]           Don't compute the statistic-vs-FDR curves for the   
                     bucket dataset.                                   
                     [same as 'setenv AFNI_AUTOMATIC_FDR NO']          
                                                                       
[-xsave]           Flag to save X matrix into file bprefix.xsave       
                     (only works if -bucket option is also given)      
[-noxsave]         Don't save X matrix [this is the default]           
[-cbucket cprefix] Save the regression coefficients (no statistics)    
                     into a dataset named 'cprefix'.  This dataset     
                     will be used in a -xrestore run instead of the    
                     bucket dataset, if possible.                      
                ** Also, the -cbucket and -x1D output can be combined  
                     in 3dSynthesize to produce 3D+time datasets that  
                     are derived from subsets of the regression model  
                     [generalizing the -fitts option, which produces]  
                     [a 3D+time dataset derived from the full model].  
                                                                       
[-xrestore f.xsave] Restore the X matrix, etc. from a previous run     
                     that was saved into file 'f.xsave'.  You can      
                     then carry out new -glt tests.  When -xrestore    
                     is used, most other command line options are      
                     ignored.                                          
                                                                       
[-float]            Write output datasets in float format, instead of  
                    as scaled shorts [** recommended **]               
[-short]            Write output as scaled shorts [default, for now]   
                                                                       
***** The following options control miscellanous outputs *****         
                                                                       
[-quiet]             Flag to suppress most screen output               
[-xout]              Flag to write X and inv(X'X) matrices to screen   
[-xjpeg filename]    Write a JPEG file graphing the X matrix           
                     * If filename ends in '.png', a PNG file is output
[-x1D filename]      Save X matrix to a .xmat.1D (ASCII) file [default]
                     * If 'filename' is 'stdout:', the file is written 
                       to standard output, and could be piped into     
                       1dplot (an example is given earlier).           
                     * This can be used for quick checks to see if your
                       inputs are setting up a 'reasonable' matrix.    
[-nox1D]             Don't save X matrix [a bad idea]                  
[-x1D_uncensored ff  Save X matrix to a .xmat.1D file, but WITHOUT     
                     ANY CENSORING.  Might be useful in 3dSynthesize.  
[-x1D_stop]          Stop running after writing .xmat.1D files.        
                     * Useful for testing, or if you are going to      
                       run 3dREMLfit instead -- that is, you are just  
                       using 3dDeconvolve to set up the matrix file.   
[-progress n]        Write statistical results for every nth voxel     
                     * To let you know that something is happening!    
[-fdisp fval]        Write statistical results to the screen, for those
                       voxels whose full model F-statistic is > fval   

**** Multiple CPU option (local CPUs only, no networking) ****

 -jobs J   Run the program with 'J' jobs (sub-processes).
             On a multi-CPU machine, this can speed the
             program up considerably.  On a single CPU
             machine, using this option would be silly.
         * J should be a number from 1 up to the
             number of CPUs sharing memory on the system.
         * J=1 is normal (single process) operation.
         * The maximum allowed value of J is 32.
         * For more information on parallelizing, see
           http://afni.nimh.nih.gov/afni/doc/misc/afni_parallelize
         * Also use -mask or -automask to get more speed; cf. 3dAutomask.

** NOTE **
This version of the program has been compiled to use
double precision arithmetic for most internal calculations.

++ Compile date = Nov  5 2009




AFNI program: 3dDeconvolve_f
**
** 3dDeconvolve_f is now disabled by default.
** It is dangerous, due to roundoff problems.
** Please use 3dDeconvolve from now on!
**
** HOWEVER, if you insist on using 3dDeconvolve_f, then:
**        + Use '-OK' as the first command line option.
**        + Check the matrix condition number;
**            if it is greater than 100, BEWARE!
**
** RWCox - July 2004
**



AFNI program: 3ddelay
++ 3ddelay: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: Ziad Saad (with help from B Douglas Ward)
The program estimates the time delay between each voxel time series    
in a 3D+time dataset and a reference time series[1][2].                
The estimated delays are relative to the reference time series.
For example, a delay of 4 seconds means that the voxel time series 
is delayed by 4 seconds with respect to the reference time series.

                                                                       
Usage:                                                                 
3ddelay                                                                 
-input fname       fname = filename of input 3d+time dataset           
                   DO NOT USE CATENATED timeseries! Time axis is assumed
                   to be continuous and not evil.
-ideal_file rname  rname = input ideal time series file name           
   The length of the reference time series should be equal to           
     that of the 3d+time data set. 
     The reference time series vector is stored in an ascii file.        
     The programs assumes that there is one value per line and that all  
     values in the file are part of the reference vector.                
     PS: Unlike with 3dfim, and FIM in AFNI, values over 33333 are treated
     as part of the time series.                                          
-fs fs             Sampling frequency in Hz. of data time series (1/TR). 
-T  Tstim          Stimulus period in seconds. 
                   If the stimulus is not periodic, you can set Tstim to 0.
[-prefix bucket]   The prefix for the results Brick.
                   The first subbrick is for Delay.
                   The second subbrick is for Covariance, which is an 
                   estimate of the power in voxel time series at the
                   frequencies present in the reference time series.
                   The third subbrick is for the Cross Correlation 
                   Coefficients between FMRI time series and reference time
                   series. The fourth subbrick contains estimates of the
                   Variance of voxel time series. 
                   The default prefix is the prefix of the input dset 
                   with a '.DEL' extension appended to it.

[-polort order]    Detrend input time series with polynomial of order
                   'order'. If you use -1 for order then the program will
                   suggest an order for you (about 1 for each 150 seconds)
                   The minimum recommended is 1. The default is -1 for auto
                   selection. This is the same as option Nort in the plugin
                   version.
[-nodtrnd]         Equivalent to polort 0, whereby only the mean is removed.
           NOTE:   Regardless of these detrending options, No detrending is 
                   done to the reference time series.

[-uS/-uD/-uR]      Units for delay estimates. (Seconds/Degrees/Radians)
                   You can't use Degrees or Radians as units unless 
                   you specify a value for Tstim > 0.
[-phzwrp]          Delay (or phase) wrap.
                   This switch maps delays from: 
                   (Seconds) 0->T/2 to 0->T/2 and T/2->T to -T/2->0
                   (Degrees) 0->180 to 0->180 and 180->360 to -180->0
                   (Radians) 0->pi to 0->pi and pi->2pi to -pi->0
                   You can't use this option unless you specify a 
                   value for Tstim > 0.
[-nophzwrp]        Do not wrap phase (default).

[-bias]            Do not correct for the bias in the estimates [1][2]
[-nobias | -correct_bias] Do correct for the bias in the estimates
                          (default).

[-dsamp]           Correct for slice timing differences        (default).
[-nodsamp ]        Do not correct for slice timing differences .

[-mask mname]      mname = filename of 3d mask dataset                 
                   only voxels with non-zero values in the mask would be 
                   considered.                                           

[-nfirst fnum]     fnum = number of first dataset image to use in      
                     the delay estimate. (default = 0)                 
[-nlast  lnum]     lnum = number of last dataset image to use in       
                     the delay estimate. (default = last)              

[-co CCT]          Cross Correlation Coefficient threshold value.
                   This is only used to limit the ascii output (see below).

[-asc [out]]       Write the results to an ascii file for voxels with 
[-ascts [out]]     cross correlation coefficients larger than CCT.
                   If 'out' is not specified, a default name similar 
                   to the default output prefix is used.
                   -asc, only files 'out' and 'out.log' are written to disk
                   (see ahead)
                   -ascts, an additional file, 'out.ts', is written to disk
                   (see ahead)
                   There a 9 columns in 'out' which hold the following
                   values:
                    1- Voxel Index (VI) : Each voxel in an AFNI brick has a
                          unique index.
                          Indices map directly to XYZ coordinates.
                          See AFNI plugin documentations for more info.
                    2..4- Voxel coordinates (X Y Z): Those are the voxel 
                          slice coordinates. You can see these coordinates
                          in the upper left side of the AFNI window.
                          To do so, you must first switch the voxel 
                          coordinate units from mm to slice coordinates. 
                          Define Datamode -> Misc -> Voxel Coords ?
                          PS: The coords that show up in the graph window
                              may be different from those in the upper left
                              side of AFNI's main window.
                    5- Duff : A value of no interest to you. It is preserved
                              for backward compatibility.
                    6- Delay (Del) : The estimated voxel delay.
                    7- Covariance (Cov) : Covariance estimate.
                    8- Cross Correlation Coefficient (xCorCoef) : 
                          Cross Correlation Coefficient.
                    9- Variance (VTS) : Variance of voxel's time series.

                   The file 'out' can be used as an input to two plugins:
                     '4Ddump' and '3D+t Extract'

                   The log file 'out.log' contains all parameter settings 
                   used for generating the output brick. 
                   It also holds any warnings generated by the plugin.
                   Some warnings, such as 'null time series ...' , or 
                   'Could not find zero crossing ...' are harmless. '
                   I might remove them in future versions.

                   A line (L) in the file 'out.ts' contains the time series 
                   of the voxel whose results are written on line (L) in the
                   file 'out'.
                   The time series written to 'out.ts' do not contain the
                   ignored samples, they are detrended and have zero mean.

                                                                      
Random Comments/Advice:
   The longer you time series, the better. It is generally recomended that
   the largest delay be less than N/10, N being time series' length.
   The algorithm does go all the way to N/2.

   If you have/find questions/comments/bugs about the plugin, 
   send me an E-mail: saadz@mail.nih.gov

                          Ziad Saad Dec 8 00.

   [1] : Bendat, J. S. (1985). The Hilbert transform and applications 
         to correlation measurements, Bruel and Kjaer Instruments Inc.
          
   [2] : Bendat, J. S. and G. A. Piersol (1986). Random Data analysis and
         measurement procedures, John Wiley & Sons.
   Author's publications on delay estimation using the Hilbert Transform:
   [3] : Saad, Z.S., et al., Analysis and use of FMRI response delays. 
         Hum Brain Mapp, 2001. 13(2): p. 74-93.
   [4] : Saad, Z.S., E.A. DeYoe, and K.M. Ropella, Estimation of FMRI 
         Response Delays.  Neuroimage, 2003. 18(2): p. 494-504.


++ Compile date = Nov  5 2009




AFNI program: 3dDespike
Usage: 3dDespike [options] dataset
Removes 'spikes' from the 3D+time input dataset and writes
a new dataset with the spike values replaced by something
more pleasing to the eye.

Method:
 * L1 fit a smooth-ish curve to each voxel time series
    [see -corder option for description of the curve].
 * Compute the MAD of the difference between the curve and
    the data time series (the residuals).
 * Estimate the standard deviation 'sigma' of the residuals
    as sqrt(PI/2)*MAD.
 * For each voxel value, define s = (value-curve)/sigma.
 * Values with s > c1 are replaced with a value that yields
    a modified s' = c1+(c2-c1)*tanh((s-c1)/(c2-c1)).
 * c1 is the threshold value of s for a 'spike' [default c1=2.5].
 * c2 is the upper range of the allowed deviation from the curve:
    s=[c1..infinity) is mapped to s'=[c1..c2)   [default c2=4].

Options:
 -ignore I  = Ignore the first I points in the time series:
               these values will just be copied to the
               output dataset [default I=0].
 -corder L  = Set the curve fit order to L:
               the curve that is fit to voxel data v(t) is

                       k=L [        (2*PI*k*t)          (2*PI*k*t) ]
 f(t) = a+b*t+c*t*t + SUM  [ d * sin(--------) + e * cos(--------) ]
                       k=1 [  k     (    T   )    k     (    T   ) ]

               where T = duration of time series;
               the a,b,c,d,e parameters are chosen to minimize
               the sum over t of |v(t)-f(t)| (L1 regression);
               this type of fitting is is insensitive to large
               spikes in the data.  The default value of L is
               NT/30, where NT = number of time points.

 -cut c1 c2 = Alter default values for the spike cut values
               [default c1=2.5, c2=4.0].
 -prefix pp = Save de-spiked dataset with prefix 'pp'
               [default pp='despike']
 -ssave ttt = Save 'spikiness' measure s for each voxel into a
               3D+time dataset with prefix 'ttt' [default=no save]
 -nomask    = Process all voxels
               [default=use a mask of high-intensity voxels, ]
               [as created via '3dAutomask -dilate 4 dataset'].
 -q[uiet]   = Don't print '++' informational messages.

 -localedit = Change the editing process to the following:
                If a voxel |s| value is >= c2, then replace
                the voxel value with the average of the two
                nearest non-spike (|s| < c2) values; the first
                one previous and the first one after.
                Note that the c1 cut value is not used here.

Caveats:
* Despiking may interfere with image registration, since head
   movement may produce 'spikes' at the edge of the brain, and
   this information would be used in the registration process.
   This possibility has not been explored or calibrated.
* Check your data visually before and after despiking and
   registration!
   [Hint: open 2 AFNI controllers, and turn Time Lock on.]

 =========================================================================
* This binary version of 3dDespike is NOT compiled using OpenMP, a
   semi-automatic parallelizer software toolkit, which splits the work
   across multiple CPUs/cores on the same shared memory computer.
* However, the source code is modified for OpenMP, and can be compiled
   with an OpenMP-capable compiler, such as gcc 4.2, Intel's icc, and
   Sun Studio.
* If you wish to compile this program with OpenMP, see the man page for
   your C compiler, and (if needed) consult the AFNI message board, and
    http://afni.nimh.nih.gov/pub/dist/doc/misc/OpenMP.html

++ Compile date = Nov  5 2009




AFNI program: 3dDetrend
Usage: 3dDetrend [options] dataset
* This program removes components from voxel time series using
  linear least squares.  Each voxel is treated independently.
* Note that least squares detrending is equivalent to orthogonalizing
  the input dataset time series with respect to the basis time series
  provided by the '-vector', '-polort', et cetera options.
* The input dataset may have a sub-brick selector string; otherwise,
  all sub-bricks will be used.

General Options:
 -prefix pname = Use 'pname' for the output dataset prefix name.
                   [default='detrend']
 -session dir  = Use 'dir' for the output dataset session directory.
                   [default='./'=current working directory]
 -verb         = Print out some verbose output as the program runs.
 -replace      = Instead of subtracting the fit from each voxel,
                   replace the voxel data with the time series fit.
 -normalize    = Normalize each output voxel time series; that is,
                   make the sum-of-squares equal to 1.
           N.B.: This option is only valid if the input dataset is
                   stored as floats! (1D files are always floats.)
 -byslice      = Treat each input vector (infra) as describing a set of
                   time series interlaced across slices.  If NZ is the
                   number of slices and NT is the number of time points,
                   then each input vector should have NZ*NT values when
                   this option is used (usually, they only need NT values).
                   The values must be arranged in slice order, then time
                   order, in each vector column, as shown here:
                       f(z=0,t=0)       // first slice, first time
                       f(z=1,t=0)       // second slice, first time
                       ...
                       f(z=NZ-1,t=0)    // last slice, first time
                       f(z=0,t=1)       // first slice, second time
                       f(z=1,t=1)       // second slice, second time
                       ...
                       f(z=NZ-1,t=NT-1) // last slice, last time

Component Options:
These options determine the components that will be removed from
each dataset voxel time series.  They may be repeated to specify
multiple regression.  At least one component must be specified.

 -vector vvv   = Remove components proportional to the columns vectors
                   of the ASCII *.1D file 'vvv'.  You may use a
                   sub-vector selector string to specify which columns
                   to use; otherwise, all columns will be used.
                   For example:
                    -vector 'xyzzy.1D[3,5]'
                   will remove the 4th and 6th columns of file xyzzy.1D
                   from the dataset (sub-vector indexes start at 0).

 -expr eee     = Remove components proportional to the function
                   specified in the expression string 'eee'.
                   Any single letter from a-z may be used as the
                   independent variable in 'eee'.  For example:
                    -expr 'cos(2*PI*t/40)' -expr 'sin(2*PI*t/40)'
                   will remove sine and cosine waves of period 40
                   from the dataset.

 -polort ppp   = Add Legendre polynomials of order up to and
                   including 'ppp' in the list of vectors to remove.

 -del ddd      = Use the numerical value 'ddd' for the stepsize
                   in subsequent -expr options.  If no -del option
                   is ever given, then the TR given in the dataset
                   header is used for 'ddd'; if that isn't available,
                   then 'ddd'=1.0 is assumed.  The j-th time point
                   will have independent variable = j * ddd, starting
                   at j=0.  For example:
                     -expr 'sin(x)' -del 2.0 -expr 'z**3'
                   means that the stepsize in 'sin(x)' is delta-x=TR,
                   but the stepsize in 'z**3' is delta-z = 2.

 N.B.: expressions are NOT calculated on a per-slice basis when the
        -byslice option is used.  If you have to do this, you could
        compute vectors with the required time series using 1deval.

Detrending 1D files
-------------------
As far as '3d' programs are concerned, you can input a 1D file as
a 'dataset'.  Each row is a separate voxel, and each column is a
separate time point.  If you want to detrend a single column, then
you need to transpose it on input.  For example:

  3dDetrend -prefix - -vector G1.1D -polort 3 G5.1D\' | 1dplot -stdin

Note that the '-vector' file is NOT transposed with \', but that
the input dataset file IS transposed.  This is because in the first
case the program expects a 1D file, and so knows that the column
direction is time.  In the second case, the program expects a 3D
dataset, and when given a 1D file, knows that the row direction is
time -- so it must be transposed.  I'm sorry if this is confusing,
but that's the way it is.

NOTE: to have the output file appear so that time is in the column
      direction, you'll have to add the option '-DAFNI_1D_TRANOUT=YES'
      to the command line, as in

  3dDetrend -DAFNI_1D_TRANOUT=YES -prefix - -vector G1.1D -polort 3 G5.1D\' > Q.1D


++ Compile date = Nov  5 2009




AFNI program: 3dDFT
Usage: 3dDFT [-prefix ppp] [-abs] [-nfft N] [-detrend] dataset
   where dataset is complex or float valued.

 -abs     == output float dataset = abs(DFT)
 -nfft N  == use 'N' for DFT length (must be >= #time points)
 -detrend == least-squares remove linear drift before DFT
             [for more complex detrending, use 3dDetrend first]
 -taper f == taper 'f' fraction of data at ends (0 <= f <= 1).
             [Hamming 'raised cosine' taper of f/2 of the ]
             [data length at each end; default is no taper]

++ Compile date = Nov  5 2009




AFNI program: 3ddot
Usage: 3ddot [options] dset1 dset2
Output = correlation coefficient between 2 dataset bricks
         - you can use sub-brick selectors on the dsets
         - the result is a number printed to stdout
Options:
  -mask mset   Means to use the dataset 'mset' as a mask:
                 Only voxels with nonzero values in 'mset'
                 will be averaged from 'dataset'.  Note
                 that the mask dataset and the input dataset
                 must have the same number of voxels.
  -mrange a b  Means to further restrict the voxels from
                 'mset' so that only those mask values
                 between 'a' and 'b' (inclusive) will
                 be used.  If this option is not given,
                 all nonzero values from 'mset' are used.
                 Note that if a voxel is zero in 'mset', then
                 it won't be included, even if a < 0 < b.
  -demean      Means to remove the mean from each volume
                 prior to computing the correlation.
  -dodot       Return the dot product (unscaled).
  -docoef      Return the least square fit coefficients
                 {a,b} so that dset2 is approximately a + b*dset1
  -dosums      Return the 5 numbers xbar= ybar=
                 <(x-xbar)^2> <(y-ybar)^2> <(x-xbar)(y-ybar)>

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dDTeig
Usage: 3dDTeig [options] dataset
Computes eigenvalues and eigenvectors for an input dataset of
 6 sub-bricks Dxx,Dxy,Dyy,Dxz,Dyz,Dzz (lower diagonal order).
 The results are stored in a 14-subbrick bucket dataset.
 The resulting 14-subbricks are
  lambda_1,lambda_2,lambda_3,
  eigvec_1[1-3],eigvec_2[1-3],eigvec_3[1-3],
  FA,MD.

The output is a bucket dataset.  The input dataset
may use a sub-brick selection list, as in program 3dcalc.
 Options:
  -prefix pname = Use 'pname' for the output dataset prefix name.
    [default='eig']

  -datum type = Coerce the output data to be stored as the given type
    which may be byte, short or float. [default=float]

  -sep_dsets = save eigenvalues,vectors,FA,MD in separate datasets

  -uddata = tensor data is stored as upper diagonal instead of lower diagonal

 Mean diffusivity (MD) calculated as simple average of eigenvalues.
 Fractional Anisotropy (FA) calculated according to Pierpaoli C, Basser PJ.
 Microstructural and physiological features of tissues elucidated by
 quantitative-diffusion tensor MRI, J Magn Reson B 1996; 111:209-19

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3ddup
Usage: 3ddup [options] dataset
 'Duplicates' a 3D dataset by making a warp-on-demand copy.
 Applications:
   - allows AFNI to resample a dataset to a new grid without
       destroying an existing data .BRIK
   - change a functional dataset to anatomical, or vice-versa

OPTIONS:
  -'type'           = Convert to the given 'type', which must be
                       chosen from the same list as in to3d
  -session dirname  = Write output into given directory (default=./)
  -prefix  pname    = Use 'pname' for the output directory prefix
                       (default=dup)
N.B.: Even if the new dataset is anatomical, it will not contain
      any markers, duplicated from the original, or otherwise.

++ Compile date = Nov  5 2009




AFNI program: 3dDWItoDT
Usage: 3dDWItoDT [options] gradient-file dataset
Computes 6 principle direction tensors from multiple gradient vectors
 and corresponding DTI image volumes.
 The program takes two parameters as input :  
    a 1D file of the gradient vectors with lines of ASCII floats Gxi,Gyi,Gzi.
    Only the non-zero gradient vectors are included in this file (no G0 line).
    a 3D bucket dataset with Np+1 sub-briks where the first sub-brik is the
    volume acquired with no diffusion weighting.
 Options:
   -prefix pname = Use 'pname' for the output dataset prefix name.
    [default='DT']

   -automask =  mask dataset so that the tensors are computed only for
    high-intensity (presumably brain) voxels.  The intensity level is
    determined the same way that 3dClipLevel works.

   -mask dset = use dset as mask to include/exclude voxels

   -nonlinear = compute iterative solution to avoid negative eigenvalues.
    This is the default method.

   -linear = compute simple linear solution.

   -reweight = recompute weight factors at end of iterations and restart

   -max_iter n = maximum number of iterations for convergence (Default=10).
    Values can range from -1 to any positive integer less than 101.
    A value of -1 is equivalent to the linear solution.
    A value of 0 results in only the initial estimate of the diffusion tensor
    solution adjusted to avoid negative eigenvalues.

   -max_iter_rw n = max number of iterations after reweighting (Default=5)
    values can range from 1 to any positive integer less than 101.

   -eigs = compute eigenvalues, eigenvectors, fractional anisotropy and mean
    diffusivity in sub-briks 6-19. Computed as in 3dDTeig

   -debug_briks = add sub-briks with Ed (error functional), Ed0 (orig. error),
     number of steps to convergence and I0 (modeled B0 volume)

   -cumulative_wts = show overall weight factors for each gradient level
    May be useful as a quality control

   -verbose nnnnn = print convergence steps every nnnnn voxels that survive to
    convergence loops (can be quite lengthy).

   -drive_afni nnnnn = show convergence graphs every nnnnn voxels that survive
    to convergence loops. AFNI must have NIML communications on (afni -niml)

   -sep_dsets = save tensor, eigenvalues,vectors,FA,MD in separate datasets

   -opt mname =  if mname is 'powell', use Powell's 2004 method for optimization
    If mname is 'gradient' use gradient descent method. If mname is 'hybrid',
    use combination of methods.
    MJD Powell, "The NEWUOA software for unconstrained optimization without
    derivatives", Technical report DAMTP 2004/NA08, Cambridge University
    Numerical Analysis Group -- http://www.damtp.cam.ac.uk/user/na/reports.html

 Example:
  3dDWItoDT -prefix rw01 -automask -reweight -max_iter 10 \
            -max_iter_rw 10 tensor25.1D grad02+orig.

 The output is a 6 sub-brick bucket dataset containing Dxx,Dxy,Dyy,Dxz,Dyz,Dzz
 (the lower triangular, row-wise elements of the tensor in symmetric matrix form)
 Additional sub-briks may be appended with the -eigs and -debug_briks options.
 These results are appropriate as the input to the 3dDTeig program.


INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.



AFNI program: 3dedge3
Usage: 3dedge3 [options] dset dset ...
Does 3D Edge detection using the library 3DEdge by;
by Gregoire Malandain (gregoire.malandain@sophia.inria.fr)

Options :
  -input iii  = Input dataset
  -verbose    = Print out some information along the way.
  -prefix ppp = Sets the prefix of the output dataset.
  -datum ddd  = Sets the datum of the output dataset.
  -fscale     = Force scaling of the output to the maximum integer range.
  -gscale     = Same as '-fscale', but also forces each output sub-brick to
                  to get the same scaling factor.
  -nscale     = Don't do any scaling on output to byte or short datasets.


References for the algorithms:
 -  Optimal edge detection using recursive filtering
    R. Deriche, International Journal of Computer Vision,
    pp 167-187, 1987.
 -  Recursive filtering and edge tracking: two primary tools
    for 3-D edge detection, O. Monga, R. Deriche, G. Malandain
    and J.-P. Cocquerez, Image and Vision Computing 4:9, 
    pp 203-214, August 1991.


++ Compile date = Nov  5 2009




AFNI program: 3dEmpty
Usage: 3dEmpty [options]
Makes an 'empty' dataset .HEAD file.

Options:
=======
 -prefix p   = Prefix name for output file
 -nxyz x y z = Set number of voxels to be 'x', 'y', and 'z'
                 along the 3 axes [defaults=64]
 -nt         = Number of time points [default=1]

* Other dataset parameters can be changed with 3drefit.
* The purpose of this program (combined with 3drefit) is to
  allow you to make up an AFNI header for an existing file.


++ Compile date = Nov  5 2009




AFNI program: 3dEntropy
Usage: 3dEntropy dataset ...

++ Compile date = Nov  5 2009




AFNI program: 3dErrtsCormat
Usage: 3dErrtsCormat [options] dset

Computes the correlation (not covariance) matrix corresponding
to the residual (or error) time series in 'dset', which will
usually be the '-errts' output from 3dDeconvolve.  The output
is a 1D file of the Toeplitz entries (to stdout).

Options:
  -concat rname  = as in 3dDeconvolve
  -input  dset   = alternate way of telling what dataset to read
  -mask   mset   = mask dataset
  -maxlag mm     = set maximum lag
  -polort pp     = set polort level (default=0)

-- RWCox -- June 2008 -- for my own pleasant purposes
-- Also see program 3dLocalCormat to do this on each voxel,
   and optionally estimate the ARMA(1,1) model parameters.

++ Compile date = Nov  5 2009




AFNI program: 3dExtrema
++ 3dExtrema: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward
This program finds local extrema (minima or maxima) of the input       
dataset values for each sub-brick of the input dataset.  The extrema   
may be determined either for each volume, or for each individual slice.
Only those voxels whose corresponding intensity value is greater than  
the user specified data threshold will be considered.                  

Usage: 3dExtrema  options  datasets                                  
where the options are:                                                 
-prefix pname    = Use 'pname' for the output dataset prefix name.     
  OR                 [default = NONE; only screen output]              
-output pname                                                          
                                                                       
-session dir     = Use 'dir' for the output dataset session directory. 
                     [default='./'=current working directory]          
                                                                       
-quiet           = Flag to suppress screen output                      
                                                                       
-mask_file mname = Use mask statistic from file mname.                 
                   Note: If file mname contains more than 1 sub-brick, 
                   the mask sub-brick must be specified!               
-mask_thr m        Only voxels whose mask statistic is >= m            
                   in absolute value will be considered.               
                   A default value of 1 is assumed.                    
                                                                       
-data_thr d        Only voxels whose value (intensity) is greater      
                   than d in absolute value will be considered.        
                                                                       
-sep_dist d        Min. separation distance [mm] for distinct extrema  
                                                                       
Choose type of extrema (one and only one choice):                      
-minima            Find local minima.                                  
-maxima [default]  Find local maxima.                                  
                                                                       
Choose form of binary relation (one and only one choice):              
-strict [default]  >  for maxima,  <  for minima                       
-partial           >= for maxima,  <= for minima                       
                                                                       
Choose boundary criteria (one and only one choice):                    
-interior [default]Extrema must be interior points (not on boundary)   
-closure           Extrema may be boundary points                      
                                                                       
Choose domain for finding extrema (one and only one choice):           
-slice [default]   Each slice is considered separately                 
-volume            The volume is considered as a whole                 
                                                                       
Choose option for merging of extrema (one and only one choice):        
-remove [default]  Remove all but strongest of neighboring extrema     
-average           Replace neighboring extrema by average              
-weight            Replace neighboring extrema by weighted average     
                                                                       
Command line arguments after the above are taken to be input datasets. 

 Examples: 
  Compute maximum value in amygdala region of Talairach-transformed dataset
    3dExtrema -volume -closure -sep_dist 512 \ 
      -mask_file 'TT_Daemon::amygdala' func_slim+tlrc.'[0]'
  Show minimum voxel values not on edge of mask, where the mask >= 0.95
    3dExtrema -minima -volume -mask_file 'statmask+orig' \ 
      -mask_thr 0.95 func_slim+tlrc.'[0]'


INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dFDR
++ 3dFDR: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward
This program implements the False Discovery Rate (FDR) algorithm for       
thresholding of voxelwise statistics.                                      
                                                                           
Program input consists of a functional dataset containing one (or more)    
statistical sub-bricks.  Output consists of a bucket dataset with one      
sub-brick for each input sub-brick.  For non-statistical input sub-bricks, 
the output is a copy of the input.  However, statistical input sub-bricks  
are replaced by their corresponding FDR values, as follows:                
                                                                           
For each voxel, the minimum value of q is determined such that             
                               E(FDR) <= q                                 
leads to rejection of the null hypothesis in that voxel. Only voxels inside
the user specified mask will be considered.  These q-values are then mapped
to z-scores for compatibility with the AFNI statistical threshold display: 
                                                                           
               stat ==> p-value ==> FDR q-value ==> FDR z-score            
                                                                           
Usage:                                                                     
  3dFDR                                                                    
    -input fname       fname = filename of input 3d functional dataset     
      OR                                                                   
    -input1D dname     dname = .1D file containing column of p-values      
                                                                           
    -mask_file mname   Use mask values from file mname.                    
     *OR*              Note: If file mname contains more than 1 sub-brick, 
    -mask mname        the mask sub-brick must be specified!               
                       Default: No mask                                    
                     ** Generally speaking, you really should use a mask   
                        to avoid counting non-brain voxels.  However, with 
                        the changes described below, the program will      
                        automatically ignore voxels where the statistics   
                        are set to 0, so if the program that created the   
                        dataset used a mask, then you don't need one here. 
                                                                           
    -mask_thr m        Only voxels whose corresponding mask value is       
                       greater than or equal to m in absolute value will   
                       be considered.  Default: m=1                        
                                                                           
                       Constant c(N) depends on assumption about p-values: 
    -cind              c(N) = 1   p-values are independent across N voxels 
    -cdep              c(N) = sum(1/i), i=1,...,N   any joint distribution 
                       Default:  c(N) = 1                                  
                                                                           
    -quiet             Flag to suppress screen output                      
                                                                           
    -list              Write sorted list of voxel q-values to screen       
                                                                           
    -prefix pname      Use 'pname' for the output dataset prefix name.     
      OR                                                                   
    -output pname                                                          
                                                                           

===========================================================================

January 2008: Changes to 3dFDR
------------------------------
The default mode of operation of 3dFDR has altered somewhat:

 * Voxel p-values of exactly 1 (e.g., from t=0 or F=0 or correlation=0)
     are ignored by default; in the old mode of operation, they were
     included in the count which goes into the FDR algorithm.  The old
     process tends to increase the q-values and so decrease the z-scores.

 * The array of voxel p-values are now sorted via Quicksort, rather than
     by binning, as in the old mode.  This (by itself) probably has no
     discernible effect on the results, but should be faster.

New Options:
------------
    -old     = Use the old mode of operation (for compatibility/nostalgia)
    -new     = Use the new mode of operation [now the default]
                N.B.: '-list' does not work in the new mode!
    -pmask   = Instruct the program to ignore p=1 voxels
                [the default in the new mode, but not in the old mode]
               N.B.: voxels that were masked in 3dDeconvolve (etc.)
                     will have their statistics set to 0, which means p=1,
                     which means that such voxels are implicitly masked
                     with '-new', and so don't need to be explicitly
                     masked with the '-mask' option.
    -nopmask = Instruct the program to count p=1 voxels
                [the default in the old mode, but NOT in the new mode]
    -force   = Force the conversion of all sub-bricks, even if they
                are not marked as with a statistical code; such
                sub-bricks are treated as though they were p-values.
    -float   = Force the output of z-scores in floating point format.
    -qval    = Force the output of q-values rather than z-scores.
                N.B.: A smaller q-value is more significant!
                [-float is strongly recommended when -qval is used]

* To be clear, you can use '-new -nopmask' to have the new mode of computing
   carried out, but with p=1 voxels included (which should give results
   nearly identical to '-old').

* Or you can use '-old -pmask' to use the old mode of computing but where
   p=1 voxels are not counted (which should give results virtually
   identical to '-new').

* However, the combination of '-new', '-nopmask' and '-mask_file' does not
   work -- if you try it, '-pmask' will be turned back on and a warning
   message printed to aid your path towards elucidation and enlightenment.

Other Notes:
------------
* '3drefit -addFDR' can be used to add FDR curves of z(q) as a function
    of threshold for all statistic sub-bricks in a dataset; in turn, these
    curves let you see the (estimated) q-value as you move the threshold
    slider in AFNI.
   - Since 3drefit doesn't have a '-mask' option, you will have to mask
     statistical sub-bricks yourself via 3dcalc (if desired):
       3dcalc -a stat+orig -b mask+orig -expr 'a*step(b)' -prefix statmm
   - '-addFDR' runs as if '-new -pmask' were given to 3dFDR, so that
     stat values == 0 are ignored in the FDR calculations.
   - most AFNI statistical programs now automatically add FDR curves to
     the output dataset header, so you can see the q-value as you adjust
     the threshold slider.

* q-values are estimates of the False Discovery Rate at a given threshold;
   that is, about 5% of all voxels with q <= 0.05 (z >= 1.96) are
   (presumably) 'false positive' detections, and the other 95% are
   (presumably) 'true positives'.  Of course, there is no way to tell
   which above-threshold voxels are 'true' detections and which are 'false'.

* Note the use of the words 'estimate' and 'about' in the above statement!
   In particular, the accuracy of the q-value calculation depends on the
   assumption that the p-values calculated from the input statistics are
   correctly distributed (e.g., that the DOF parameters are correct).

* The z-score is the conversion of the q-value to a double-sided tail
   probability of the unit Gaussian N(0,1) distribution; that is, z(q)
   is the value such that if x is a N(0,1) random variable, then
   Prob[|x|>z] = q: for example, z(0.05) = 1.95996.
  The reason for using z-scores here is simply that their range is
   highly compressed relative to the range of q-values
   (e.g., z(1e-9) = 6.10941), so z-scores are easily stored as shorts,
   whereas q-values are much better stored as floats.

* Changes above by RWCox -- 18 Jan 2008 == Cary Grant's Birthday!

26 Mar 2009 -- Yet Another Change [RWCox]
-----------------------------------------
* FDR calculations in AFNI now 'adjust' the q-values downwards by
   estimating the number of true negatives [m0 in the statistics
   literature], and then reporting
     q_new = q_old * m0 / m, where m = number of voxels being tested.
   If you do NOT want this adjustment, then set environment variable
   AFNI_DONT_ADJUST_FDR to YES.  You can do this on the 3dFDR command
   line with the option '-DAFNI_DONT_ADJUST_FDR=YES'

For Further Reading and Amusement
---------------------------------
* cf. http://en.wikipedia.org/wiki/False_discovery_rate [Easy overview of FDR]
* cf. http://dx.doi.org/10.1093/bioinformatics/bti448   [False Negative Rate]
* cf. http://dx.doi.org/10.1093/biomet/93.3.491         [m0 adjustment idea]
* cf. C implementation in mri_fdrize.c                  [trust in the Source]
* cf. http://afni.nimh.nih.gov/pub/dist/doc/misc/FDR/FDR_Jan2008.pdf

++ Compile date = Nov  5 2009




AFNI program: 3dFFT
Usage: 3dFFT [options] dataset

* Does the FFT of the input dataset in 3 directions (x,y,z) and
   produces the output dataset.

* Why you'd want to do this is an interesting question.

* Program 3dcalc can operate on complex-valued datasets, but
   only on one component at a time (cf. the '-cx2r' option).

* Most other AFNI programs can only operate on real-valued
   datasets.

* You could use 3dcalc (twice) to split a complex-valued dataset
   into two real-valued datasets, do your will on those with other
   AFNI programs, then merge the results back into a complex-valued
   dataset with 3dTwotoComplex.

Options
=======
 -abs       = Outputs the magnitude of the FFT [default]
 -phase     = Outputs the phase of the FFT (-PI..PI == no unwrapping!)
 -complex   = Outputs the complex-valued FFT
 -inverse   = Does the inverse FFT instead of the forward FFT

 -Lx xx     = Use FFT of length 'xx' in the x-direction
 -Ly yy     = Use FFT of length 'yy' in the y-direction
 -Lz zz     = Use FFT of length 'zz' in the z-direction
              * Set a length to 0 to skip the FFT in that direction

 -altIN     = Alternate signs of input data before FFT, to bring
               zero frequency from edge of FFT-space to center of grid
               for cosmetic purposes.
 -altOUT    = Alternate signs of output data after FFT.  If you
               use '-altI' on the forward transform, then you should
               use '-altO' an the inverse transform, to get the
               signs of the recovered image correct.
      **N.B.: You cannot use '-altIN' and '-altOUT' in the same run!

 -input dd  = Read the input dataset from 'dd', instead of
               from the last argument on the command line.

 -prefix pp = Use 'pp' for the output dataset prefix.

Notes
=====
 * In the present avatar, only 1 sub-brick will be processed.

 * The program can only do FFT lengths that are factorable
    into a product of powers of 2, 3, and 5, and are even.
   + The largest power of 3 that is allowed is 3^3 = 27.
   + The largest power of 5 that is allowed is 5^3 = 125.
   + e.g., FFT of length 3*5*8=120 is possible.
   + e.g., FFT of length 4*31 =124 is not possible.

 * The 'x', 'y', and 'z' axes here refer to the order the
    data is stored, not DICOM coordinates; cf. 3dinfo.

 * If you force (via '-Lx' etc.) an FFT length that is not
    allowed, the program will stop with an error message.

 * If you force an FFT length that is shorter than an dataset
    axis dimension, the program will stop with an error message.

 * If you don't force an FFT length along a particular axis,
    the program will pick the smallest legal value that is
    greater than or equal to the corresponding dataset dimension.
   + e.g., 124 would be increased to 128.

 * If an FFT length is longer than an axis length, then the
    input data in that direction is zero-padded at the end.

 * For -abs and -phase, the output dataset is in float format.

 * If you do the forward and inverse FFT, then you should get back
    the original dataset, except for roundoff error and except that
    the new dataset axis dimensions may be longer than the original.

 * Forward FFT = sum_{k=0..N-1} [ exp(-2*PI*i*k/N) * data(k) ]

 * Inverse FFT = sum_{k=0..N-1} [ exp(+2*PI*i*k/N) * data(k) ] / N

 * Started a long time ago, but only finished in Aug 2009 at the
    request of John Butman, because he asked so nicely.  (Now pay up!)

++ Compile date = Nov  5 2009




AFNI program: 3dfim
++ 3dfim: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: R. W. Cox and B. D. Ward
 Program:   3dfim 

Purpose:   Calculate functional image from 3d+time data file. 
Usage:     3dfim  [-im1 num]  -input fname  -prefix name 
              -ideal fname  [-ideal fname] [-ort fname] 
 
 options are:
 -im1 num        num   = index of first image to be used in time series 
                         correlation; default is 1  
  
 -input fname    fname = filename of 3d + time data file for input
  
 -prefix name    name  = prefix of filename for saving functional data
  
 -ideal fname    fname = filename of a time series to which the image data
                         is to be correlated. 
  
 -percent p      Calculate percentage change due to the ideal time series 
                 p     = maximum allowed percentage change from baseline 
                         Note: values greater than p are set equal to p. 
  
 -ort fname      fname = filename of a time series to which the image data
                         is to be orthogonalized 
  
             N.B.: It is possible to specify more than
             one ideal time series file. Each one is separately correlated
             with the image time series and the one most highly correlated
             is selected for each pixel.  Multiple ideals are specified
             using more than one '-ideal fname' option, or by using the
             form '-ideal [ fname1 fname2 ... ]' -- this latter method
             allows the use of wildcarded ideal filenames.
             The '[' character that indicates the start of a group of
             ideals can actually be any ONE of these: [{/%
             and the ']' that ends the group can be:  ]}/%
  
             [Format of ideal time series files:
             ASCII; one number per line;
             Same number of lines as images in the time series;
             Value over 33333 --> don't use this image in the analysis]
  
             N.B.: It is also possible to specify more than
             one ort time series file.  The image time series is  
             orthogonalized to each ort time series.  Multiple orts are 
             specified by using more than one '-ort fname' option, 
             or by using the form '-ort [ fname1 fname2 ... ]'.  This 
             latter method allows the use of wildcarded ort filenames.
             The '[' character that indicates the start of a group of
             ideals can actually be any ONE of these: [{/%
             and the ']' that ends the group can be:  ]}/%
  
             [Format of ort time series files:
             ASCII; one number per line;
             At least same number of lines as images in the time series]
  
  

++ Compile date = Nov  5 2009




AFNI program: 3dfim+
++ 3dfim+: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward
Program to calculate the cross-correlation of an ideal reference waveform  
with the measured FMRI time series for each voxel.                         
                                                                       
Usage:                                                                 
3dfim+                                                                 
-input fname       fname = filename of input 3d+time dataset           
[-input1D dname]   dname = filename of single (fMRI) .1D time series   
[-mask mname]      mname = filename of 3d mask dataset                 
[-nfirst fnum]     fnum = number of first dataset image to use in      
                     the cross-correlation procedure. (default = 0)    
[-nlast  lnum]     lnum = number of last dataset image to use in       
                     the cross-correlation procedure. (default = last) 
[-polort pnum]     pnum = degree of polynomial corresponding to the    
                     baseline model  (pnum = 0, 1, etc.)               
                     (default: pnum = 1). Use -1 for no baseline model.
[-fim_thr p]       p = fim internal mask threshold value (0 <= p <= 1) 
                     (default: p = 0.0999)                             
[-cdisp cval]      Write (to screen) results for those voxels          
                     whose correlation stat. > cval  (0 <= cval <= 1)  
                     (default: disabled)                               
[-ort_file sname]  sname = input ort time series file name             
-ideal_file rname  rname = input ideal time series file name           
                                                                       
            Note:  The -ort_file and -ideal_file commands may be used  
                   more than once.                                     
            Note:  If files sname or rname contain multiple columns,   
                   then ALL columns will be used as ort or ideal       
                   time series.  However, individual columns or        
                   a subset of columns may be selected using a file    
                   name specification like 'fred.1D[0,3,5]', which     
                   indicates that only columns #0, #3, and #5 will     
                   be used for input.                                  

[-out param]       Flag to output the specified parameter, where       
                   the string 'param' may be any one of the following: 
                                                                       
    Fit Coef       L.S. fit coefficient for Best Ideal                
  Best Index       Index number for Best Ideal                        
    % Change       P-P amplitude of signal response / Baseline        
    Baseline       Average of baseline model response                 
 Correlation       Best Ideal product-moment correlation coefficient  
  % From Ave       P-P amplitude of signal response / Average         
     Average       Baseline + average of signal response              
  % From Top       P-P amplitude of signal response / Topline         
     Topline       Baseline + P-P amplitude of signal response        
 Sigma Resid       Std. Dev. of residuals from best fit               
         All       This specifies all of the above parameters       
 Spearman CC       Spearman correlation coefficient                   
 Quadrant CC       Quadrant correlation coefficient                   
                                                                       
            Note:  Multiple '-out' commands may be used.               
            Note:  If a parameter name contains imbedded spaces, the   
                   entire parameter name must be enclosed by quotes,   
                   e.g.,  -out 'Fit Coef'                                   
                                                                       
[-bucket bprefix]  Create one AFNI 'bucket' dataset containing the     
                   parameters of interest, as specified by the above   
                   '-out' commands.                                    
                   The output 'bucket' dataset is written to a file    
                   with the prefix name bprefix.                       

++ Compile date = Nov  5 2009




AFNI program: 3dFourier
3dFourier 
(c) 1999 Medical College of Wisconsin
by T. Ross and K. Heimerl
Version 0.8 last modified 8-17-99

Usage: 3dFourier [options] dataset

The paramters and options are:
	dataset		an afni compatible 3d+time dataset to be operated upon
	-prefix name	output name for new 3d+time dataset [default = fourier]
	-lowpass f 	low pass filter with a cutoff of f Hz
	-highpass f	high pass filter with a cutoff of f Hz
	-ignore n	ignore the first n images [default = 1]
	-retrend	Any mean and linear trend are removed before filtering.
			This will restore the trend after filtering.

Note that by combining the lowpass and highpass options, one can construct
bandpass and notch filters

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.



AFNI program: 3dfractionize
Usage: 3dfractionize [options]

* For each voxel in the output dataset, computes the fraction
    of it that is occupied by nonzero voxels from the input.
* The fraction is stored as a short in the range 0..10000,
    indicating fractions running from 0..1.
* The template dataset is used only to define the output grid;
    its brick(s) will not be read into memory.  (The same is
    true of the warp dataset, if it is used.)
* The actual values stored in the input dataset are irrelevant,
    except in that they are zero or nonzero (UNLESS the -preserve
    option is used).

The purpose of this program is to allow the resampling of a mask
dataset (the input) from a fine grid to a coarse grid (defined by
the template).  When you are using the output, you will probably
want to threshold the mask so that voxels with a tiny occupancy
fraction aren't used.  This can be done in 3dmaskave, by using
3calc, or with the '-clip' option below.

Options are [the first 2 are 'mandatory options']:
  -template tset  = Use dataset 'tset' as a template for the output.
                      The output dataset will be on the same grid as
                      this dataset.

  -input iset     = Use dataset 'iset' for the input.
                      Only the sub-brick #0 of the input is used.
                      You can use the sub-brick selection technique
                      described in '3dcalc -help' to choose the
                      desired sub-brick from a multi-brick dataset.

  -prefix ppp     = Use 'ppp' for the prefix of the output.
                      [default prefix = 'fractionize']

  -clip fff       = Clip off voxels that are less than 'fff' occupied.
                      'fff' can be a number between 0.0 and 1.0, meaning
                      the fraction occupied, can be a number between 1.0
                      and 100.0, meaning the percent occupied, or can be
                      a number between 100.0 and 10000.0, meaning the
                      direct output value to use as a clip level.
                   ** Some sort of clipping is desirable; otherwise,
                        an output voxel that is barely overlapped by a
                        single nonzero input voxel will enter the mask.
                      [default clip = 0.0]

  -warp wset      = If this option is used, 'wset' is a dataset that
                      provides a transformation (warp) from +orig
                      coordinates to the coordinates of 'iset'.
                      In this case, the output dataset will be in
                      +orig coordinates rather than the coordinates
                      of 'iset'.  With this option:
                   ** 'tset' must be in +orig coordinates
                   ** 'iset' must be in +acpc or +tlrc coordinates
                   ** 'wset' must be in the same coordinates as 'iset'

  -preserve       = When this option is used, the program will copy
     or               the nonzero values of input voxels to the output
  -vote               dataset, rather than create a fractional mask.
                      Since each output voxel might be overlapped
                      by more than one input voxel, the program 'votes'
                      for which input value to preserve.  For example,
                      if input voxels with value=1 occupy 10% of an
                      output voxel, and inputs with value=2 occupy 20%
                      of the same voxel, then the output value in that
                      voxel will be set to 2 (provided that 20% is >=
                      to the clip fraction).
                   ** Voting can only be done on short-valued datasets,
                        or on byte-valued datasets.
                   ** Voting is a relatively time-consuming option,
                        since a separate loop is made through the
                        input dataset for each distinct value found.
                   ** Combining this with the -warp option does NOT
                        make a general +tlrc to +orig transformer!
                        This is because for any value to survive the
                        vote, its fraction in the output voxel must be
                        >= clip fraction, regardless of other values
                        present in the output voxel.

Sample usage:

  1. Compute the fraction of each voxel occupied by the warped input.

          3dfractionize -template grid+orig -input data+tlrc  \
                        -warp anat+tlrc -clip 0.2

  2. Apply the (inverse) -warp tranformation to transform the -input
     from +tlrc space to +orig space, storing it according to the grid
     of the -template.
     A voxel in the output dataset gets the value that occupies most of
     its volume, providing that value occupies 20% of the voxel.

     Note that the essential difference from above is '-preserve'.

          3dfractionize -template grid+orig -input data+tlrc  \
                        -warp anat+tlrc -preserve -clip 0.2   \
                        -prefix new_data

This program will also work in going from a coarse grid to a fine grid,
but it isn't clear that this capability has any purpose.
-- RWCox - February 1999
         - October 1999: added -warp and -preserve options

++ Compile date = Nov  5 2009




AFNI program: 3dFriedman
++ 3dFriedman: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward
This program performs nonparametric Friedman test for               
randomized complete block design experiments.                     

Usage:                                                              
3dFriedman                                                          
-levels s                      s = number of treatments             
-dset 1 filename               data set for treatment #1            
 . . .                           . . .                              
-dset 1 filename               data set for treatment #1            
 . . .                           . . .                              
-dset s filename               data set for treatment #s            
 . . .                           . . .                              
-dset s filename               data set for treatment #s            
                                                                    
[-workmem mega]                number of megabytes of RAM to use    
                                 for statistical workspace          
[-voxel num]                   screen output for voxel # num        
-out prefixname                Friedman statistics are written      
                                 to file prefixname                 


N.B.: For this program, the user must specify 1 and only 1 sub-brick  
      with each -dset command. That is, if an input dataset contains  
      more than 1 sub-brick, a sub-brick selector must be used, e.g.: 
      -dset 2 'fred+orig[3]'                                          

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dFWHM
++ 3dFWHM: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward
*+ WARNING: This program is obsolete!  Use 3dFWHMx instead!
This program estimates the Filter Width Half Maximum (FWHM).  

Usage: 
3dFWHM 
-dset file     file  = name of input AFNI 3d dataset 
[-mask mname]  mname = filename of 3d mask dataset   
[-quiet]       suppress screen output                
[-out file]    file  = name of output file           

[-compat] = Be compatible with the older 3dFWHM, where if a
            voxel is in the mask, then its neighbors are used
            for differencing, even if they are not themselves in
            the mask.  This was an error; now, neighbors must also
            be in the mask to be used in the differencing.
            Use '-compat' to use the older method [for comparison].
         ** This change made 09 Nov 2006.

ALSO SEE:
 - 3dFWHMx, which can deal with multi-brick datasets
 - 3dLocalstat -stat FWHM, which can estimate the FWHM at each voxel
3dFWHM itself will no longer be upgraded.  Any future improvements
will be made to 3dFWHMx.  **** PLEASE SWITCH TO THAT PROGRAM ****

INPUT FILE RECOMMENDATIONS:
For FMRI statistical purposes, you DO NOT want the FWHM to reflect
the spatial structure of the underlying anatomy.  Rather, you want
the FWHM to reflect the spatial structure of the noise.  This means
that the input dataset should not have anatomical structure.  One
good form of input is the output of '3dDeconvolve -errts', which is
the residuals left over after the GLM fitted signal model is subtracted
out from each voxel's time series.  If you don't want to go to that
trouble, use the output of 3dDetrend for the same purpose.  But just
giving a raw EPI dataset to this program will produce un-useful values.


INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dFWHMx
Usage: 3dFWHMx [options] dataset

Unlike the older 3dFWHM, this program computes FWHMs for all sub-bricks
in the input dataset, each one separately.  The output for each one is
written to the file specified by '-out'.  The mean (arithmetic or geometric)
of all the FWHMs along each axis is written to stdout.  (A non-positive
output value indicates something happened; e.g., FWHM in z is meaningless
for a 2D dataset.)

METHODS:
 - Calculate ratio of variance of first differences to data variance.
 - Should be the same as 3dFWHM for a 1-brick dataset.
   (But the output format is simpler to use in a script.)

OPTIONS:
  -mask mmm   = Use only voxels that are nonzero in dataset 'mmm'.
  -automask   = Compute a mask from THIS dataset, a la 3dAutomask.
                [Default = use all voxels]

  -input ddd }=
    *OR*     }= Use dataset 'ddd' as the input.
  -dset  ddd }=

  -demed      = If the input dataset has more than one sub-brick
                (e.g., has a time axis), then subtract the median
                of each voxel's time series before processing FWHM.
                This will tend to remove intrinsic spatial structure
                and leave behind the noise.
                [Default = don't do this]
  -unif       = If the input dataset has more than one sub-brick,
                then normalize each voxel's time series to have
                the same MAD before processing FWHM.  Implies -demed.
                [Default = don't do this]
  -detrend [q]= Instead of demed (0th order detrending), detrend to
                order 'q'.  If q is not given, the program picks q=NT/30.
                -detrend disables -demed, and includes -unif.
        **N.B.: I recommend this option, and it is not the default
                only for historical compatibility reasons.  It may
                become the default someday. Depending on my mood.
                It is already the default in program 3dBlurToFWHM.
        **N.B.: This is the same detrending as done in 3dDespike;
                using 2*q+3 basis functions for q > 0.
  -detprefix d= Save the detrended file into a dataset with prefix 'd'.
                Used mostly to figure out what the hell is going on,
                when funky results transpire.

  -geom      }= If the input dataset has more than one sub-brick,
    *OR*     }= compute the final estimate as the geometric mean
  -arith     }= or the arithmetic mean of the individual sub-brick
                FWHM estimates. [Default = -geom, for no good reason]

  -out ttt    = Write output to file 'ttt' (3 columns of numbers).
                If not given, the sub-brick outputs are not written.
                Use '-out -' to write to stdout, if desired.

  -compat     = Be compatible with the older 3dFWHM, where if a
                voxel is in the mask, then its neighbors are used
                for differencing, even if they are not themselves in
                the mask.  This was an error; now, neighbors must also
                be in the mask to be used in the differencing.
                Use '-compat' to use the older method.
              **NOT RECOMMENDED except for comparison purposes!

SAMPLE USAGE: (tcsh)
  set zork = ( `3dFWHMx -automask -input junque+orig` )
Captures the FWHM-x, FWHM-y, FWHM-z values into shell variable 'zork'.

INPUT FILE RECOMMENDATIONS:
For FMRI statistical purposes, you DO NOT want the FWHM to reflect
the spatial structure of the underlying anatomy.  Rather, you want
the FWHM to reflect the spatial structure of the noise.  This means
that the input dataset should not have anatomical structure.  One
good form of input is the output of '3dDeconvolve -errts', which is
the residuals left over after the GLM fitted signal model is subtracted
out from each voxel's time series.  If you don't want to go to that
trouble, use '-unif' to at least partially subtract out the anatomical
spatial structure, or use the output of 3dDetrend for the same purpose.

ALSO SEE:
 - The older program 3dFWHM is superseded by 3dFWHMx.
 - 3dLocalstat -stat FWHM will estimate the FWHM values at each
   voxel, using the same algorithm as this program but applied only
   to a local neighborhood of each voxel in turn.
 - 3dBlurToFWHM will blur a dataset to have a given global FWHM.

-- Emperor Zhark - Halloween 2006 --- BOO!

++ Compile date = Nov  5 2009




AFNI program: 3dGetrow
Program to extract 1 row from a dataset and write it as a .1D file
Usage: 3dGetrow [options] dataset

OPTIONS:
-------
Exactly ONE of the following three options is required:
 -xrow j k  = extract row along the x-direction at fixed y-index of j
              and fixed z-index of k.
 -yrow i k  = similar for a row along the y-direction
 -zrow i j  = similar for a row along the z-direction
 -input ddd = read input from dataset 'ddd'
              (instead of putting dataset name at end of command line)
 -output ff = filename for output .1D ASCII file will be 'ff'
              (if 'ff' is '-', then output is to stdout, the default)

N.B.: if the input dataset has more than one sub-brick, each
      sub-brick will appear as a separate column in the output file.

++ Compile date = Nov  5 2009




AFNI program: 3dhistog
Compute histogram of 3D Dataset
Usage: 3dhistog [editing options] [histogram options] dataset

The editing options are the same as in 3dmerge
 (i.e., the options starting with '-1').

The histogram options are:
  -nbin #   Means to use '#' bins [default=100]
            Special Case: for short or byte dataset bricks,
                          set '#' to zero to have the number
                          of bins set by the brick range.
  -dind i   Means to take data from sub-brick #i, rather than #0
  -omit x   Means to omit the value 'x' from the count;
              -omit can be used more than once to skip multiple values.
  -mask m   Means to use dataset 'm' to determine which voxels to use
  -doall    Means to include all sub-bricks in the calculation;
              otherwise, only sub-brick #0 (or that from -dind) is used.
  -notit    Means to leave the title line off the output.
  -log10    Output log10() of the counts, instead of the count values.
  -min x    Means specify minimum of histogram.
  -max x    Means specify maximum of histogram.
  -unq U.1D Writes out the sorted unique values to file U.1D.
            This option is not allowed for float data
            If you have a problem with this, write
            Ziad S. Saad (saadz@mail.nih.gov)

The histogram is written to stdout.  Use redirection '>' if you
want to save it to a file.  The format is a title line, then
three numbers printed per line:
  bottom-of-interval  count-in-interval  cumulative-count

-- by RW Cox (V Roopchansingh added the -mask option)

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dinfo

Prints out sort-of-useful information from a 3D dataset's header
Usage: 3dinfo [-verb OR -short] dataset [dataset ...]
  -verb means to print out lots of stuff
  -VERB means even more stuff
  -short means to print out less stuff [now the default]

Alternative Usage (without either of the above options):
  3dinfo -label2index label dataset
  * Prints to stdout the index corresponding to the sub-brick with
    the name label, or a blank line if label not found.
  * If this option is used, then the ONLY output is this sub-brick index.
    This is intended to be used in a script, as in this tcsh fragment:
      set face = `3dinfo -label2index Face#0 AA_Decon+orig`
      set hous = `3dinfo -label2index House#0 AA_Decon+orig`
      3dcalc -a AA_Decon+orig"[$face]" -b AA_Decon+orig"[$hous]" ...
  * Added per the request and efforts of Colm Connolly.

++ Compile date = Nov  5 2009




AFNI program: 3dIntracranial
++ 3dIntracranial: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. D. Ward
3dIntracranial - performs automatic segmentation of intracranial region.
                                                                        
   This program will strip the scalp and other non-brain tissue from a  
   high-resolution T1 weighted anatomical dataset.                      
                                                                        
** Nota Bene: the newer program 3dSkullStrip should also be considered  
**            for this functionality -- it usually works better.        
                                                                        
----------------------------------------------------------------------- 
                                                                        
Usage:                                                                  
-----                                                                   
                                                                        
3dIntracranial                                                          
   -anat filename   => Filename of anat dataset to be segmented         
                                                                        
   [-min_val   a]   => Minimum voxel intensity limit                    
                         Default: Internal PDF estimate for lower bound 
                                                                        
   [-max_val   b]   => Maximum voxel intensity limit                    
                         Default: Internal PDF estimate for upper bound 
                                                                        
   [-min_conn  m]   => Minimum voxel connectivity to enter              
                         Default: m=4                                   
                                                                        
   [-max_conn  n]   => Maximum voxel connectivity to leave              
                         Default: n=2                                   
                                                                        
   [-nosmooth]      => Suppress spatial smoothing of segmentation mask  
                                                                        
   [-mask]          => Generate functional image mask (complement)      
                         Default: Generate anatomical image            
                                                                        
   [-quiet]         => Suppress output to screen                        
                                                                        
   -prefix pname    => Prefix name for file to contain segmented image  
                                                                        
   ** NOTE **: The newer program 3dSkullStrip will probably give        
               better segmentation results than 3dIntracranial!         
----------------------------------------------------------------------- 
                                                                        
Examples:                                                               
--------                                                                
                                                                        
   3dIntracranial -anat elvis+orig -prefix elvis_strip                 
                                                                        
   3dIntracranial -min_val 30 -max_val 350 -anat elvis+orig -prefix strip
                                                                        
   3dIntracranial -nosmooth -quiet -anat elvis+orig -prefix elvis_strip 
                                                                        
----------------------------------------------------------------------- 

++ Compile date = Nov  5 2009




AFNI program: 3dInvFMRI
Usage: 3dInvFMRI [options]
Program to compute stimulus time series, given a 3D+time dataset
and an activation map (the inverse of the usual FMRI analysis problem).
-------------------------------------------------------------------
OPTIONS:

 -data yyy  =
   *OR*     = Defines input 3D+time dataset [a non-optional option].
 -input yyy =

 -map  aaa  = Defines activation map; 'aaa' should be a bucket dataset,
                each sub-brick of which defines the beta weight map for
                an unknown stimulus time series [also non-optional].

 -mapwt www = Defines a weighting factor to use for each element of
                the map.  The dataset 'www' can have either 1 sub-brick,
                or the same number as in the -map dataset.  In the
                first case, in each voxel, each sub-brick of the map
                gets the same weight in the least squares equations.
                  [default: all weights are 1]

 -mask mmm  = Defines a mask dataset, to restrict input voxels from
                -data and -map.  [default: all voxels are used]

 -base fff  = Each column of the 1D file 'fff' defines a baseline time
                series; these columns should be the same length as
                number of time points in 'yyy'.  Multiple -base options
                can be given.
 -polort pp = Adds polynomials of order 'pp' to the baseline collection.
                The default baseline model is '-polort 0' (constant).
                To specify no baseline model at all, use '-polort -1'.

 -out vvv   = Name of 1D output file will be 'vvv'.
                [default = '-', which is stdout; probably not good]

 -method M  = Determines the method to use.  'M' is a single letter:
               -method C = least squares fit to data matrix Y [default]
               -method K = least squares fit to activation matrix A

 -alpha aa  = Set the 'alpha' factor to 'aa'; alpha is used to penalize
                large values of the output vectors.  Default is 0.
                A large-ish value for alpha would be 0.1.

 -fir5     = Smooth the results with a 5 point lowpass FIR filter.
 -median5  = Smooth the results with a 5 point median filter.
               [default: no smoothing; only 1 of these can be used]
-------------------------------------------------------------------
METHODS:
 Formulate the problem as
    Y = V A' + F C' + errors
 where Y = data matrix      (N x M) [from -data]
       V = stimulus         (N x p) [to -out]
       A = map matrix       (M x p) [from -map]
       F = baseline matrix  (N x q) [from -base and -polort]
       C = baseline weights (M x q) [not computed]
       N = time series length = length of -data file
       M = number of voxels in mask
       p = number of stimulus time series to estimate
         = number of paramters in -map file
       q = number of baseline parameters
   and ' = matrix transpose operator
 Next, define matrix Z (Y detrended relative to columns of F) by
                       -1
   Z = [I - F(F'F)  F']  Y
-------------------------------------------------------------------
 The method C solution is given by
                 -1
   V0 = Z A [A'A]

 This solution minimizes the sum of squares over the N*M elements
 of the matrix   Y - V A' + F C'   (N.B.: A' means A-transpose).
-------------------------------------------------------------------
 The method K solution is given by
             -1                            -1
   W = [Z Z']  Z A   and then   V = W [W'W]

 This solution minimizes the sum of squares of the difference between
 the A(V) predicted from V and the input A, where A(V) is given by
                    -1
   A(V) = Z' V [V'V]   = Z'W
-------------------------------------------------------------------
 Technically, the solution is unidentfiable up to an arbitrary
 multiple of the columns of F (i.e., V = V0 + F G, where G is
 an arbitrary q x p matrix); the solution above is the solution
 that is orthogonal to the columns of F.

-- RWCox - March 2006 - purely for experimental purposes!

===================== EXAMPLE USAGE =====================================
** Step 1: From a training dataset, generate activation map.
  The input dataset has 4 runs, each 108 time points long.  3dDeconvolve
  is used on the first 3 runs (time points 0..323) to generate the
  activation map.  There are two visual stimuli (Complex and Simple).

  3dDeconvolve -x1D xout_short_two.1D -input rall_vr+orig'[0..323]'   \
      -num_stimts 2                                                   \
      -stim_file 1 hrf_complex.1D               -stim_label 1 Complex \
      -stim_file 2 hrf_simple.1D                -stim_label 2 Simple  \
      -concat '1D:0,108,216'                                          \
      -full_first -fout -tout                                         \
      -bucket func_ht2_short_two -cbucket cbuc_ht2_short_two

  N.B.: You may want to de-spike, smooth, and register the 3D+time
        dataset prior to the analysis (as usual).  These steps are not
        shown here -- I'm presuming you know how to use AFNI already.

** Step 2: Create a mask of highly activated voxels.
  The F statistic threshold is set to 30, corresponding to a voxel-wise
  p = 1e-12 = very significant.  The mask is also lightly clustered, and
  restricted to brain voxels.

  3dAutomask -prefix Amask rall_vr+orig
  3dcalc -a 'func_ht2_short+orig[0]' -b Amask+orig -datum byte \
         -nscale -expr 'step(a-30)*b' -prefix STmask300
  3dmerge -dxyz=1 -1clust 1.1 5 -prefix STmask300c STmask300+orig

** Step 3: Run 3dInvFMRI to estimate the stimulus functions in run #4.
  Run #4 is time points 324..431 of the 3D+time dataset (the -data
  input below).  The -map input is the beta weights extracted from
  the -cbucket output of 3dDeconvolve.

  3dInvFMRI -mask STmask300c+orig                       \
            -data rall_vr+orig'[324..431]'              \
            -map cbuc_ht2_short_two+orig'[6..7]'        \
            -polort 1 -alpha 0.01 -median5 -method K    \
            -out ii300K_short_two.1D

  3dInvFMRI -mask STmask300c+orig                       \
            -data rall_vr+orig'[324..431]'              \
            -map cbuc_ht2_short_two+orig'[6..7]'        \
            -polort 1 -alpha 0.01 -median5 -method C    \
            -out ii300C_short_two.1D

** Step 4: Plot the results, and get confused.

  1dplot -ynames VV KK CC -xlabel Run#4 -ylabel ComplexStim \
         hrf_complex.1D'{324..432}'                         \
         ii300K_short_two.1D'[0]'                           \
         ii300C_short_two.1D'[0]'

  1dplot -ynames VV KK CC -xlabel Run#4 -ylabel SimpleStim \
         hrf_simple.1D'{324..432}'                         \
         ii300K_short_two.1D'[1]'                          \
         ii300C_short_two.1D'[1]'

  N.B.: I've found that method K works better if MORE voxels are
        included in the mask (lower threshold) and method C if
        FEWER voxels are included.  The above threshold gave 945
        voxels being used to determine the 2 output time series.
=========================================================================

++ Compile date = Nov  5 2009




AFNI program: 3dKruskalWallis
++ 3dKruskalWallis: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward
This program performs nonparametric Kruskal-Wallis test for         
comparison of multiple treatments.                                

Usage:                                                              
3dKruskalWallis                                                     
-levels s                      s = number of treatments             
-dset 1 filename               data set for treatment #1            
 . . .                           . . .                              
-dset 1 filename               data set for treatment #1            
 . . .                           . . .                              
-dset s filename               data set for treatment #s            
 . . .                           . . .                              
-dset s filename               data set for treatment #s            
                                                                    
[-workmem mega]                number of megabytes of RAM to use    
                                 for statistical workspace          
[-voxel num]                   screen output for voxel # num        
-out prefixnamename            Kruskal-Wallis statistics are written
                                 to file prefixname                 


N.B.: For this program, the user must specify 1 and only 1 sub-brick  
      with each -dset command. That is, if an input dataset contains  
      more than 1 sub-brick, a sub-brick selector must be used, e.g.: 
      -dset 2 'fred+orig[3]'                                          

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dLocalBistat
Usage: 3dLocalBistat [options] dataset1 dataset2

This program computes statistics between 2 datasets,
at each voxel, based on a local neighborhood of that voxel.
 - The neighborhood is defined by the '-nbhd' option.
 - Statistics to be calculated are defined by the '-stat' option(s).

OPTIONS
-------
 -nbhd 'nnn' = The string 'nnn' defines the region around each
               voxel that will be extracted for the statistics
               calculation.  The format of the 'nnn' string are:
               * 'SPHERE(r)' where 'r' is the radius in mm;
                 the neighborhood is all voxels whose center-to-
                 center distance is less than or equal to 'r'.
                 ** A negative value for 'r' means that the region
                    is calculated using voxel indexes rather than
                    voxel dimensions; that is, the neighborhood
                    region is a "sphere" in voxel indexes of
                    "radius" abs(r).
               * 'RECT(a,b,c)' is a rectangular block which
                 proceeds plus-or-minus 'a' mm in the x-direction,
                 'b' mm in the y-direction, and 'c' mm in the
                 z-direction.  The correspondence between the
                 dataset xyz axes and the actual spatial orientation
                 can be determined by using program 3dinfo.
                 ** A negative value for 'a' means that the region
                    extends plus-and-minus abs(a) voxels in the
                    x-direction, rather than plus-and-minus a mm.
                    Mutatis mutandum for negative 'b' and/or 'c'.
               * 'RHDD(r)' is a rhombic dodecahedron of 'radius' r.
               * 'TOHD(r)' is a truncated octahedron of 'radius' r.

 -stat sss   = Compute the statistic named 'sss' on the values
               extracted from the region around each voxel:
               * pearson  = Pearson correlation coefficient
               * spearman = Spearman correlation coefficient
               * quadrant = Quadrant correlation coefficient
               * mutinfo  = Mutual Information
               * normuti  = Normalized Mutual Information
               * jointent = Joint entropy
               * hellinger= Hellinger metric
               * crU      = Correlation ratio (Unsymmetric)
               * crM      = Correlation ratio (symmetrized by Multiplication)
               * crA      = Correlation ratio (symmetrized by Addition)
               * num    = number of the values in the region:
                          with the use of -mask or -automask,
                          the size of the region around any given
                          voxel will vary; this option lets you
                          map that size.
               * ncd    = Normalized Compression Distance (zlib; very slow)
               * ALL    = all of the above, in that order
               More than one '-stat' option can be used.

 -mask mset  = Read in dataset 'mset' and use the nonzero voxels
               therein as a mask.  Voxels NOT in the mask will
               not be used in the neighborhood of any voxel. Also,
               a voxel NOT in the mask will have its statistic(s)
               computed as zero (0).
 -automask   = Compute the mask as in program 3dAutomask.
               -mask and -automask are mutually exclusive: that is,
               you can only specify one mask.
 -weight ws  = Use dataset 'ws' as a weight.  Only applies to 'pearson'.

 -prefix ppp = Use string 'ppp' as the prefix for the output dataset.
               The output dataset is always stored as floats.

ADVANCED OPTIONS
----------------
 -histpow pp   = By default, the number of bins in the histogram used
                 for calculating the Hellinger, Mutual Information, NCD,
                 and Correlation Ratio statistics is n^(1/3), where n
                 is the number of data points in the -nbhd mask.  You
                 can change that exponent to 'pp' with this option.
 -histbin nn   = Or you can just set the number of bins directly to 'nn'.
 -hclip1 a b   = Clip dataset1 to lie between values 'a' and 'b'.  If 'a'
                 and 'b' end in '%', then these values are percentage
                 points on the cumulative histogram.
 -hclip2 a b   = Similar to '-hclip1' for dataset2.

-----------------------------
Author: RWCox - October 2006.

++ Compile date = Nov  5 2009




AFNI program: 3dLocalCormat
Usage: 3dLocalCORMAT [options] inputdataset

Compute the correlation matrix (in time) of the input dataset,
up to lag given by -maxlag.  The matrix is averaged over the
neighborhood specified by the -nbhd option, and then the entries
are output at each voxel in a new dataset.

Normally, the input to this program would be the -errts output
from 3dDeconvolve, or the equivalent residuals from some other
analysis.  If you input a non-residual time series file, you at
least should use an appropriate -polort level for detrending!

Options:
  -input inputdataset
  -prefix ppp
  -mask mset    {these 2 options are}
  -automask     {mutually exclusive.}
  -nbhd nnn     [e.g., 'SPHERE(9)' for 9 mm radius]
  -polort ppp   [default = 0, which is reasonable for -errts output]
  -concat ccc   [as in 3dDeconvolve]
  -maxlag mmm   [default = 10]
  -ARMA         [estimate ARMA(1,1) parameters into last 2 sub-bricks]

A quick hack for my own benignant purposes -- RWCox -- June 2008

++ Compile date = Jul  8 2009




AFNI program: 3dLocalstat
Usage: 3dLocalstat [options] dataset

This program computes statistics at each voxel, based on a
local neighborhood of that voxel.
 - The neighborhood is defined by the '-nbhd' option.
 - Statistics to be calculated are defined by the '-stat' option(s).

OPTIONS
-------
 -nbhd 'nnn' = The string 'nnn' defines the region around each
               voxel that will be extracted for the statistics
               calculation.  The format of the 'nnn' string are:
               * 'SPHERE(r)' where 'r' is the radius in mm;
                 the neighborhood is all voxels whose center-to-
                 center distance is less than or equal to 'r'.
                 ** A negative value for 'r' means that the region
                    is calculated using voxel indexes rather than
                    voxel dimensions; that is, the neighborhood
                    region is a "sphere" in voxel indexes of
                    "radius" abs(r).
               * 'RECT(a,b,c)' is a rectangular block which
                 proceeds plus-or-minus 'a' mm in the x-direction,
                 'b' mm in the y-direction, and 'c' mm in the
                 z-direction.  The correspondence between the
                 dataset xyz axes and the actual spatial orientation
                 can be determined by using program 3dinfo.
                 ** A negative value for 'a' means that the region
                    extends plus-and-minus abs(a) voxels in the
                    x-direction, rather than plus-and-minus a mm.
                    Mutatis mutandum for negative 'b' and/or 'c'.
               * 'RHDD(a)' where 'a' is the size parameter in mm;
                 this is Kepler's rhombic dodecahedron [volume=2*a^3].
               * 'TOHD(a)' where 'a' is the size parameter in mm;
                 this is a truncated octahedron. [volume=4*a^3]
                 ** This is the polyhedral shape that tiles space
                    and is the most 'sphere-like'.
               * If no '-nbhd' option is given, the region extracted
                 will just be the voxel and its 6 nearest neighbors.
               * Voxels not in the mask (if any) or outside the
                 dataset volume will not be used.  This means that
                 different output voxels will have different numbers
                 of input voxels that went into calculating their
                 statistics.  The 'num' statistic can be used to
                 get this count on a per-voxel basis, if you need it.

 -stat sss   = Compute the statistic named 'sss' on the values
               extracted from the region around each voxel:
               * mean   = average of the values
               * stdev  = standard deviation
               * var    = variance (stdev*stdev)
               * cvar   = coefficient of variation = stdev/fabs(mean)
               * median = median of the values
               * MAD    = median absolute deviation
               * min    = minimum
               * max    = maximum
               * absmax = maximum of the absolute values
               * num    = number of the values in the region:
                          with the use of -mask or -automask,
                          the size of the region around any given
                          voxel will vary; this option lets you
                          map that size.  It may be useful if you
                          plan to compute a t-statistic (say) from
                          the mean and stdev outputs.
               * sum    = sum of the values in the region:
               * FWHM   = compute (like 3dFWHM) image smoothness
                          inside each voxel's neighborhood.  Results
                          are in 3 sub-bricks: FWHMx, FHWMy, and FWHMz.
                          Places where an output is -1 are locations
                          where the FWHM value could not be computed
                          (e.g., outside the mask).
               * FWHMbar= Compute just the average of the 3 FWHM values
                          (normally would NOT do this with FWHM also).
               * perc:P0:P1:Pstep = 
                          Compute percentiles between P0 and P1 with a 
                          step of Pstep.
                          Default P1 is equal to P0 and default P2 = 1
               * ALL    = all of the above, in that order 
                         (except for FWHMbar and perc).
               More than one '-stat' option can be used.

 -mask mset  = Read in dataset 'mset' and use the nonzero voxels
               therein as a mask.  Voxels NOT in the mask will
               not be used in the neighborhood of any voxel. Also,
               a voxel NOT in the mask will have its statistic(s)
               computed as zero (0).
 -automask   = Compute the mask as in program 3dAutomask.
               -mask and -automask are mutually exclusive: that is,
               you can only specify one mask.

 -use_nonmask = Just above, I said that voxels NOT in the mask will
                not have their local statistics computed.  This option
                will make it so that voxels not in the mask WILL have
                their local statistics computed from all voxels in
                their neighborhood that ARE in the mask.
               * You could use '-use_nonmask' to compute the average
                 local white matter time series, for example, even at
                 non-WM voxels.

 -prefix ppp = Use string 'ppp' as the prefix for the output dataset.
               The output dataset is normally stored as floats.

 -datum type = Coerce the output data to be stored as the given type, 
               which may be byte, short, or float.
               Default is float

 -quiet      = Stop the highly informative progress reports.

Author: RWCox - August 2005.  Instigator: ZSSaad.

 =========================================================================
* This binary version of 3dLocalstat is NOT compiled using OpenMP, a
   semi-automatic parallelizer software toolkit, which splits the work
   across multiple CPUs/cores on the same shared memory computer.
* However, the source code is modified for OpenMP, and can be compiled
   with an OpenMP-capable compiler, such as gcc 4.2, Intel's icc, and
   Sun Studio.
* If you wish to compile this program with OpenMP, see the man page for
   your C compiler, and (if needed) consult the AFNI message board, and
    http://afni.nimh.nih.gov/pub/dist/doc/misc/OpenMP.html

++ Compile date = Nov  5 2009




AFNI program: 3dLocalSVD
Usage: 3dLocalSVD [options] inputdataset
* You may want to use 3dDetrend before running this program,
   or at least use the '-polort' option.
* This program is highly experimental.  And slowish.
* Computes the SVD of the time series from a neighborhood of each
   voxel.  An inricate way of 'smoothing' 3D+time datasets,
   in some sense, maybe.

Options:
 -mask mset           = restrict operations to this mask
 -automask            = create a mask from time series dataset
 -prefix ppp          = save SVD vector result into this new dataset
 -input inputdataset  = input time series dataset
 -nbhd nnn            = e.g., 'SPHERE(5)' 'TOHD(7)' etc.
 -polort p [+]        = detrending ['+' means to add trend back]
 -vnorm               = normalize data vectors
                         [strongly recommended]
 -vproj [ndim]        = project central data time series onto local SVD subspace
                         of dimension 'ndim'
                         [default: just output principal singular vector]
                         [for 'smoothing' purposes, '-vnorm -vproj 2' is a good idea]

++ Compile date = Nov  5 2009




AFNI program: 3dLRflip
Usage: 3dLRflip [-LR|-AP|-IS|-X|-Y|-Z] [-prefix ppp] dataset dataset dataset ...
Flips the rows of a dataset along one of the three
axis.
This is useful in the case where you, or some fast
program, constructed a dataset with one of the 
directions incorrectly labeled. 
 Optional options:
 -LR | -AP | -IS: Axis about which to flip the data
                  Default is -LR.
      or
 -X | -Y | -Z: Flip about 1st, 2nd or 3rd directions,
               respectively. 
 Note: Only one of these 6 options can be  used at a time.
        
 -prefix ppp: Prefix to use for output. If you have 
              multiple datasets as input, you are better
              off letting the program choose a prefix for
              each output.


++ Compile date = Nov  5 2009




AFNI program: 3dMannWhitney
++ 3dMannWhitney: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward
This program performs nonparametric Mann-Whitney two-sample test. 

Usage: 
3dMannWhitney 
-dset 1 filename               data set for X observations          
 . . .                           . . .                              
-dset 1 filename               data set for X observations          
-dset 2 filename               data set for Y observations          
 . . .                           . . .                              
-dset 2 filename               data set for Y observations          
                                                                    
[-workmem mega]                number of megabytes of RAM to use    
                                 for statistical workspace          
[-voxel num]                   screen output for voxel # num        
-out prefixname                estimated population delta and       
                                 Wilcoxon-Mann-Whitney statistics   
                                 written to file prefixname         


N.B.: For this program, the user must specify 1 and only 1 sub-brick  
      with each -dset command. That is, if an input dataset contains  
      more than 1 sub-brick, a sub-brick selector must be used, e.g.: 
      -dset 2 'fred+orig[3]'                                          

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dmaskave
Usage: 3dmaskave [options] dataset

Computes average of all voxels in the input dataset
which satisfy the criterion in the options list.
If no options are given, then all voxels are included.

------------------------------------------------------------
Examples:

1. compute the average timeseries in epi_r1+orig, over voxels
   that are set (any non-zero value) in the dataset, ROI+orig:

    3dmaskave -mask ROI+orig epi_r1+orig

2. restrict the ROI to values of 3 or 4, and save (redirect)
   the output to the text file run1_roi_34.txt:

    3dmaskave -mask ROI+orig -quiet -mrange 3 4   \
              epi_r1+orig > run1_roi_34.txt
------------------------------------------------------------

Options:
  -mask mset   Means to use the dataset 'mset' as a mask:
                 Only voxels with nonzero values in 'mset'
                 will be averaged from 'dataset'.  Note
                 that the mask dataset and the input dataset
                 must have the same number of voxels.
               SPECIAL CASE: If 'mset' is the string 'SELF',
                             then the input dataset will be
                             used to mask itself.  That is,
                             only nonzero voxels from the
                             #miv sub-brick will be used.
  -mindex miv  Means to use sub-brick #'miv' from the mask
                 dataset.  If not given, miv=0.
  -mrange a b  Means to further restrict the voxels from
                 'mset' so that only those mask values
                 between 'a' and 'b' (inclusive) will
                 be used.  If this option is not given,
                 all nonzero values from 'mset' are used.
                 Note that if a voxel is zero in 'mset', then
                 it won't be included, even if a < 0 < b.

  -xbox x y z     } These options are the same as in
  -dbox x y z     } program 3dmaskdump:
  -nbox x y z     } They create a mask by putting down boxes
  -ibox x y z     } or balls (filled spheres) at the specified
  -xball x y z r  } locations.  See the output of
  -dball x y z r  }   3dmaskdump -help
  -nball x y z r  } for the gruesome and tedious details.
   http://afni.nimh.nih.gov/pub/dist/doc/program_help/3dmaskdump.html

  -dindex div  Means to use sub-brick #'div' from the dataset.
                 If not given, all sub-bricks will be processed.
  -drange a b  Means to only include voxels from the dataset whose
                 values fall in the range 'a' to 'b' (inclusive).
                 Otherwise, all voxel values are included.

  -slices p q  Means to only included voxels from the dataset
                 whose slice numbers are in the range 'p' to 'q'
                 (inclusive).  Slice numbers range from 0 to
                 NZ-1, where NZ can be determined from the output
                 of program 3dinfo.  The default is to include
                 data from all slices.
                 [There is no provision for geometrical voxel]
                 [selection except in the slice (z) direction]

  -sigma       Means to compute the standard deviation as well
                 as the mean.
  -median      Means to compute the median instead of the mean.
  -max         Means to compute the max instead of the mean.
  -min         Means to compute the min instead of the mean.
                 (-sigma is ignored with -median, -max, or -min)
  -dump        Means to print out all the voxel values that
                 go into the average.
  -udump       Means to print out all the voxel values that
                 go into the average, UNSCALED by any internal
                 factors.
                 N.B.: the scale factors for a sub-brick
                       can be found using program 3dinfo.
  -indump      Means to print out the voxel indexes (i,j,k) for
                 each dumped voxel.  Has no effect if -dump
                 or -udump is not also used.
                 N.B.: if nx,ny,nz are the number of voxels in
                       each direction, then the array offset
                       in the brick corresponding to (i,j,k)
                       is i+j*nx+k*nx*ny.
 -q     or
 -quiet        Means to print only the minimal results.
               This is useful if you want to create a *.1D file.

The output is printed to stdout (the terminal), and can be
saved to a file using the usual redirection operation '>'.

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dmaskdump
Usage: 3dmaskdump [options] dataset dataset ...
Writes to an ASCII file values from the input datasets
which satisfy the mask criteria given in the options.
If no options are given, then all voxels are included.
This might result in a GIGANTIC output file.
Options:
  -mask mset   Means to use the dataset 'mset' as a mask:
                 Only voxels with nonzero values in 'mset'
                 will be printed from 'dataset'.  Note
                 that the mask dataset and the input dataset
                 must have the same number of voxels.
  -mrange a b  Means to further restrict the voxels from
                 'mset' so that only those mask values
                 between 'a' and 'b' (inclusive) will
                 be used.  If this option is not given,
                 all nonzero values from 'mset' are used.
                 Note that if a voxel is zero in 'mset', then
                 it won't be included, even if a < 0 < b.
  -index       Means to write out the dataset index values.
  -noijk       Means not to write out the i,j,k values.
  -xyz         Means to write the x,y,z coordinates from
                 the 1st input dataset at the start of each
                 output line.  These coordinates are in
                 the 'RAI' (DICOM) order.
  -o fname     Means to write output to file 'fname'.
                 [default = stdout, which you won't like]

  -cmask 'opts' Means to execute the options enclosed in single
                  quotes as a 3dcalc-like program, and produce
                  produce a mask from the resulting 3D brick.
       Examples:
        -cmask '-a fred+orig[7] -b zork+orig[3] -expr step(a-b)'
                  produces a mask that is nonzero only where
                  the 7th sub-brick of fred+orig is larger than
                  the 3rd sub-brick of zork+orig.
        -cmask '-a fred+orig -expr 1-bool(k-7)'
                  produces a mask that is nonzero only in the
                  7th slice (k=7); combined with -mask, you
                  could use this to extract just selected voxels
                  from particular slice(s).
       Notes: * You can use both -mask and -cmask in the same
                  run - in this case, only voxels present in
                  both masks will be dumped.
              * Only single sub-brick calculations can be
                  used in the 3dcalc-like calculations -
                  if you input a multi-brick dataset here,
                  without using a sub-brick index, then only
                  its 0th sub-brick will be used.
              * Do not use quotes inside the 'opts' string!

  -xbox x y z   Means to put a 'mask' down at the dataset (not DICOM)
                  coordinates of 'x y z' mm.  By default, this box is
                  1 voxel wide in each direction.  You can specify
                  instead a range of coordinates using a colon ':'
                  after the coordinates; for example:
                    -xbox 22:27 31:33 44
                  means a box from (x,y,z)=(22,31,44) to (27,33,44).
           NOTE: dataset coordinates are NOT the coordinates you
                 typically see in AFNI's main controller top left corner.
                 Those coordinates are typically in either RAI/DICOM order
                 or in LPI/SPM order and should be used with -dbox and
                 -nbox, respectively.

  -dbox x y z   Means the same as -xbox, but the coordinates are in
                  RAI/DICOM order (+x=Left, +y=Posterior, +z=Superior).
                  If your AFNI environment variable AFNI_ORIENT is set to
                  RAI, these coordinates correspond to those you'd enter
                  into the 'Jump to (xyz)' control in AFNI, and to
                  those output by 3dclust.
            NOTE: It is possible to make AFNI and/or 3dclust output 
                  coordinates in an order different from the one specified 
                  by AFNI_ORIENT, but you'd have to work hard on that. 
                  In any case, the order is almost always specified along 
                  with the coordinates. If you see RAI/DICOM, then use 
                  -dbox. If you see LPI/SPM then use -nbox. 

  -nbox x y z   Means the same as -xbox, but the coordinates are in
                  LPI/SPM or 'neuroscience' order where the signs of the
                  x and y coordinates are reversed relative to RAI/DICOM.
                  (+x=Right, +y=Anterior, +z=Superior)

  -ibox i j k   Means to put a 'mask' down at the voxel indexes
                  given by 'i j k'.  By default, this picks out
                  just 1 voxel.  Again, you can use a ':' to specify
                  a range (now in voxels) of locations.
       Notes: * Boxes are cumulative; that is, if you specify more
                  than 1 box, you'll get more than one region.
              * If a -mask and/or -cmask option is used, then
                  the INTERSECTION of the boxes with these masks
                  determines which voxels are output; that is,
                  a voxel must be inside some box AND inside the
                  mask in order to be selected for output.
              * If boxes select more than 1 voxel, the output lines
                  are NOT necessarily in the order of the options on
                  the command line.
              * Coordinates (for -xbox, -dbox, and -nbox) are relative
                  to the first dataset on the command line.

  -xball x y z r  Means to put a ball (sphere) mask down at dataset
                    coordinates (x,y,z) with radius r.
  -dball x y z r  Same, but (x,y,z) are in RAI/DICOM order.
  -nball x y z r  Same, but (x,y,z) are in LPI/SPM order.
       Notes: * The combined (set UNION) of all ball and/or box masks
                is created first.  Then, if a -mask and/or -cmask
                option was used, then the ball+box mask will be
                INTERSECTED with the existing mask.

  -nozero       Means to skip output of any voxel where all the
                  data values are zero.

  -n_rand N_RAND Means to keep only N_RAND randomly selected
                 voxels from what would have been the output.

  -n_randseed SEED  Seed the random number generator with SEED,
                    instead of the default seed of 1234

  -niml name    Means to output data in the XML/NIML format that
                  is compatible with input back to AFNI via
                  the READ_NIML_FILE command.
              * 'name' is the 'target_name' for the NIML header
                  field, which is the name that will be assigned
                  to the dataset when it is sent into AFNI.
              * Also implies '-noijk' and '-xyz' and '-nozero'.

  -quiet        Means not to print progress messages to stderr.

Inputs after the last option are datasets whose values you
want to be dumped out.  These datasets (and the mask) can
use the sub-brick selection mechanism (described in the
output of '3dcalc -help') to choose which values you get.

Each selected voxel gets one line of output:
  i j k val val val ....
where (i,j,k) = 3D index of voxel in the dataset arrays,
and val = the actual voxel value.  Note that if you want
the mask value to be output, you have to include that
dataset in the dataset input list again, after you use
it in the '-mask' option.

* To eliminate the 'i j k' columns, use the '-noijk' option.
* To add spatial coordinate columns, use the '-xyz' option.

N.B.: This program doesn't work with complex-valued datasets!

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dmaskSVD
Usage:  3dmaskSVD [options] inputdataset
Author: Zhark the Gloriously Singular

* Computes the principal singular vector of the time series
    vectors extracted from the input dataset over the input mask.
  ++ You can use the '-sval' option to change which singular
     vectors are output.
* The sign of the output vector is chosen so that the average
    of arctanh(correlation coefficient) over all input data
    vectors (from the mask) is positive.
* The output vector is normalized: the sum of its components
    squared is 1.
* You probably want to use 3dDetrend (or something similar) first,
    to get rid of annoying artifacts, such as motion, breathing,
    dark matter interactions with the brain, etc.
  ++ If you are lazy scum like Zhark, you might be able to get
     away with using the '-polort' option.
  ++ In particular, if your data time series has a nonzero mean,
     then you probably want at least '-polort 0' to remove the
     mean, otherwise you'll pretty much just get a constant
     time series as the principal singular vector!
* An alternative to this program would be 3dmaskdump followed
    by 1dsvd, which could give you all the singular vectors you
    could ever want, and much more -- enough to confuse you for days.
  ++ In particular, although you COULD input a 1D file into
     3dmaskSVD, the 1dsvd program would make much more sense.
* This program will be pretty slow if there are over about 2000
    voxels in the mask.  It could be made more efficient for
    such cases, but you'll have to give Zhark some 'incentive'.
* Result vector goes to stdout.  Redirect per your pleasures and needs.
* Also see program 3dLocalSVD if you want to compute the principal
    singular time series vector from a neighborhood of EACH voxel.
  ++ (Which is a pretty slow operation!)
http://en.wikipedia.org/wiki/Singular_value_decomposition

-------
Options:
-------
 -vnorm      = L2 normalize all time series before SVD [recommended!]
 -sval a     = output singular vectors 0 .. a [default a=0 = first one only]
 -mask mset  = define the mask [default is entire dataset == slow!]
 -automask   = you'll have to guess what this option does
 -polort p   = if you are lazy and didn't run 3dDetrend (like Zhark)
 -ort xx.1D  = time series to remove from the data before SVD-ization
               ++ You can give more than 1 '-ort' option
               ++ 'xx.1D' can contain more than 1 column
 -input ddd  = alternative way to give the input dataset name

-------
Example:
-------
 You have a mask dataset with discrete values 1, 2, ... 77 indicating
 some ROIs; you want to get the SVD from each ROI's time series separately,
 and then put these into 1 big 77 column .1D file.  You can do this using
 a csh shell script like the one below:

 # Compute the individual SVD vectors
 foreach mm ( `count 1 77` )
   3dmaskSVD -vnorm -mask mymask+orig"<${mm}..${mm}>" epi+orig > qvec${mm}.1D
 end
 # Glue them together into 1 big file, then delete the individual files
 1dcat qvec*.1D > allvec.1D
 /bin/rm -f qvec*.1D
 # Plot the results to a JPEG file, then compute their correlation matrix
 1dplot -one -nopush -jpg allvec.jpg allvec.1D
 1ddot -terse allvec.1D > allvec_COR.1D

 [[ If you use the bash shell,  you'll have to figure out the syntax ]]
 [[ yourself. Zhark has no sympathy for you bash shell infidels, and ]]
 [[ considers you only slightly better than those lowly Emacs users. ]]
 [[ And do NOT ever even mention 'nedit' in Zhark's august presence! ]]

++ Compile date = Nov  5 2009




AFNI program: 3dmatcalc
Usage: 3dmatcalc [options]
Apply a matrix to a dataset, voxel-by-voxel, to produce a new
dataset.

* If the input dataset has 'N' sub-bricks, and the input matrix
   is 'MxN', then the output dataset will have 'M' sub-bricks; the
   results in each voxel will be the result of extracting the N
   values from the input at that voxel, multiplying the resulting
   N-vector by the matrix, and output the resulting M-vector.

* If the input matrix has 'N+1' columns, then it will be applied
   to an (N+1)-vector whose first N elements are from the dataset
   and the last value is 1.  This convention allows the addition
   of a constant vector (the last row of the matrix) to each voxel.
* The output dataset is always stored in float format.
* Useful applications are left to your imagination.  The example
   below is pretty fracking hopeless.  Something more useful might
   be to project a 3D+time dataset onto some subspace, then run
   3dpc on the results.


OPTIONS:
-------
 -input ddd  = read in dataset 'ddd'  [required option]
 -matrix eee = specify matrix, which can be done as a .1D file
                or as an expression in the syntax of 1dmatcalc
                [required option]
 -prefix ppp = write to dataset with prefix 'ppp'
 -mask mmm   = only apply to voxels in the mask; other voxels
                will be set to all zeroes

EXAMPLE:
-------
Assume dataset 'v+orig' has 50 sub-bricks:
 3dmatcalc -input v+orig -matrix '&read(1D:50@1,\,50@0.02) &transp' -prefix w
The -matrix option computes a 2x50 matrix, whose first row is all 1's
and whose second row is all 0.02's.  Thus, the output dataset w+orig has
2 sub-bricks, the first of which is the voxel-wise sum of all 50 inputs,
and the second is the voxel-wise average (since 0.02=1/50).

-- Zhark, Emperor -- April 2006

++ Compile date = Nov  5 2009




AFNI program: 3dmatmult
-------------------------------------------------------------------------
Multiply AFNI datasets slice-by-slice as matrices.

If dataset A has Ra rows and Ca columns (per slice), and dataset B has
Rb rows and Cb columns (per slice), multiply each slice pair as matrices
to obtain a dataset with Ra rows and Cb columns.  Here Ca must equal Rb
and the number of slices must be equal.

In practice the first dataset will probably be a transformation matrix
(or a sequence of them) while the second dataset might just be an image.
For this reason, the output dataset will be based on inputB.

----------------------------------------
examples:

    3dmatmult -inputA matrix+orig -inputB image+orig -prefix transformed

    3dmatmult -inputA matrix+orig -inputB image+orig  \
              -prefix transformed -datum float -verb 2

----------------------------------------
informational command arguments (execute option and quit):

    -help                   : show this help
    -hist                   : show program history
    -ver                    : show program version

----------------------------------------
required command arguments:

    -inputA DSET_A          : specify first (matrix) dataset

        The slices of this dataset might be transformation matrices.

    -inputB DSET_B          : specify second (matrix) dataset

        This dataset might be any image.

    -prefix PREFIX          : specify output dataset prefix

        This will be the name of the product (output) dataset.

----------------------------------------
optional command arguments:

    -datum TYPE             : specify verbosity level

        Valid TYPEs are 'byte', 'short' and 'float'.  The default is
        that of the inputB dataset.

    -verb LEVEL             : specify verbosity level

        The default level is 1, while 0 is considered 'quiet'.

----------------------------------------
* If you need to re-orient a 3D dataset so that the rows, columns
  and slices are correct for 3dmatmult, you can use the one of the
  programs 3daxialize or 3dresample for this purpose.

* To multiply a constant matrix into a vector at each voxel, the
  program 3dmatcalc is the proper tool.

----------------------------------------------------------------------
R. Reynolds    (requested by W. Gaggl)

3dmatmult version 0.0, 29 September 2008
compiled: Nov  5 2009




AFNI program: 3dmaxima
3dmaxima - used to locate extrema in a functional dataset.

   This program reads a functional dataset and locates any relative extrema
   (maximums or minimums, depending on the user option).  A _relative_
   maximum is a point that is greater than all neighbors (not necessarily
   greater than all other values in the sub-brick).  The output from this
   process can be text based (sent to the terminal window) and it can be a
   mask (integral) dataset, where the locations of the extrema are set.

   When writing a dataset, it is often useful to set a sphere around each
   extrema, not to just set individual voxels.  This makes viewing those
   locations much more reasonable.  Also, if the 'Sphere Values' option is
   set to 'N to 1', the sphere around the most extreme voxel will get the
   value N, giving it the 'top' color in afni (and so on, down to 1).

   Notes : The only required option is the input dataset.
           Input datasets must be of type short.
           All distances are in voxel units.

----------------------------------------------------------------------
                        ***  Options  ***

-----  Input Dset:  -----

   -input DSET           : specify input dataset

         e.g. -input func+orig'[7]'

       Only one sub-brick may be specified.  So if a dataset has multiple
       sub-bricks, the [] selector must be used.

-----  Output Dset:  -----

   -prefix PREFIX        : prefix for an output mask dataset

         e.g. -prefix maskNto1

       This dataset may be viewed as a mask.  It will have a value set at
       the location of any selected extrema.  The -out_rad option can be
       used to change those points to 'spheres'.

   -spheres_1            : [flag] set all output values to 1

       This is the default, which sets all values in the output dataset
       to 1.  This is for the extreme points, and for the spheres centered
       around them.

   -spheres_1toN         : [flag] output values will range from 1 to N

       In this case, the most extreme voxel will be set with a value of 1.
       The next most extreme voxel will get 2, and so on.

   -spheres_Nto1         : [flag] output values will range from N to 1

       With this option, the highest extrema will be set to a value of N,
       where N equals the number of reported extrema.  The advantage of
       this is that the most extreme point will get the highest color in
       afni.

-----  Threshold:  -----

   -thresh CUTOFF        : provides a cutoff value for extrema

         e.g. -thresh 17.4

       Extrema not meeting this cutoff will not be considered.
       Note that if the '-neg_ext' option is applied, the user
       will generally want a negative threshold.

-----  Separation:  -----

   -min_dist VOXELS      : minimum acceptable distance between extrema

         e.g. -min_dist 4

       Less significant extrema which are close to more significant extrema
       will be discounted in some way, depending on the 'neighbor style'
       options.

       See '-n_style_sort' and '-n_style_weight_ave' for more information.

       Note that the distance is in voxels, not mm.

-----  Output Size:  -----

   -out_rad SIZE         : set the output radius around extrema voxels

         e.g. -out_rad 9

       If the user wants the output BRIK to consist of 'spheres' centered
       at extrema points, this option can be used to set the radius for
       those spheres.  Note again that this is in voxel units.

-----  Neighbor:  -----

   If extrema are not as far apart as is specified by the '-min_dist'
   option, the neighbor style options specify how to handle the points.

   -n_style_sort         : [flag] use 'Sort-n-Remove' style (default)

       The extrema are sorted by magnitude.  For each extrema (which has
       not previously removed), all less significant extrema neighbors
       within the separation radius (-min_dist) are removed.

       See '-min_dist' for more information.

   -n_style_weight_ave   : [flag] use 'Weighted-Average' style

       Again, traverse the sorted list of extrema.  Replace the current
       extrema with the center of mass of all extrema within the Separation
       radius of the current point, removing all others within this radius.

       This should not change the number of extrema, it should only shift
       the locations.

-----  Params:  -----

   -neg_ext              : [flag] search for negative extrema (minima)

       This will search for the minima of the dataset.
       Note that a negative threshold may be desired.

   -true_max             : [flag] extrema may not have equal neighbors

       By default, points may be considered extrema even if they have a
       neighbor with the same value.  This flag option requires extrema
       to be strictly greater than any of their neighbors.

       With this option, extrema locations that have neighbors at the same
       value are ignored.

-----  Output Text:  -----

   -debug LEVEL          : output extra information to the terminal

       e.g. -debug 2

   -no_text              : [flag] do not display the extrma points as text

   -coords_only          : [flag] only output coordinates (no text or vals)

-----  Output Coords:  -----

   -dset_coords          : [flag] display output in the dataset orientation

       By default, the xyz-coordinates are displayed in DICOM orientation
       (RAI), i.e. right, anterior and inferior coordinates are negative,
       and they are printed in that order (RL, then AP, then IS).

       If this flag is set, the dataset orientation is used, whichever of
       the 48 it happens to be.

       Note that in either case, the output orientation is printed above
       the results in the terminal window, to remind the user.

-----  Other :  -----

   -help                 : display this help

   -hist                 : display module history

   -ver                  : display version number

Author: R Reynolds




AFNI program: 3dMean
Usage: 3dMean [options] dset dset ...
Takes the voxel-by-voxel mean of all input datasets;
the main reason is to be faster than 3dcalc.

Options [see 3dcalc -help for more details on these]:
  -verbose    = Print out some information along the way.
  -prefix ppp = Sets the prefix of the output dataset.
  -datum ddd  = Sets the datum of the output dataset.
  -fscale     = Force scaling of the output to the maximum integer range.
  -gscale     = Same as '-fscale', but also forces each output sub-brick to
                  to get the same scaling factor.
  -nscale     = Don't do any scaling on output to byte or short datasets.

  -sd *OR*    = Calculate the standard deviation (variance/n-1) instead
  -stdev         of the mean (cannot be used with -sqr or -sum).

  -sqr        = Average the squares, instead of the values.
  -sum        = Just take the sum (don't divide by number of datasets).

N.B.: All input datasets must have the same number of voxels along
       each axis (x,y,z,t).
    * At least 2 input datasets are required.
    * Dataset sub-brick selectors [] are allowed.
    * The output dataset origin, time steps, etc., are taken from the
       first input dataset.

++ Compile date = Nov  5 2009




AFNI program: 3dMedianFilter
Usage: 3dMedianFilter [options] dataset
Computes the median in a spherical nbhd around each point in the
input to produce the output.

Options:
  -irad x    = Radius in voxels of spherical regions
  -iter n    = Iterate 'n' times [default=1]
  -verb      = Be verbose during run
  -prefix pp = Use 'pp' for prefix of output dataset
  -automask  = Create a mask (a la 3dAutomask)

Output dataset is always stored in float format.  If the input
dataset has more than 1 sub-brick, only sub-brick #0 is processed.

-- Feb 2005 - RWCox

++ Compile date = Nov  5 2009




AFNI program: 3dmerge
Program 3dmerge 
This program has 2 different functions:
 (1) To edit 3D datasets in various ways (threshold, blur, cluster, ...);
 (2) To merge multiple datasets in various ways (average, max, ...).
Either or both of these can be applied.

The 'editing' operations are controlled by options that start with '-1',
which indicates that they apply to individual datasets
(e.g., '-1blur_fwhm').

The 'merging' operations are controlled by options that start with '-g',
which indicate that they apply to the entire group of input datasets
(e.g., '-gmax').

----------------------------------------------------------------------
Usage: 3dmerge [options] datasets ...

Examples:

  1. Apply a 4.0mm FWHM Gaussian blur to EPI run 7.

       3dmerge -1blur_fwhm 4.0 -doall -prefix e1.run7_blur run7+orig

* These examples are based on a data grid of 3.75 x 3.75 x 3.5, in mm.
  So a single voxel has a volume of ~49.22 mm^3 (mvul), and a 40 voxel
  cluster has a volume of ~1969 mm^3 (as used in some examples).

  2. F-stat only:

     Cluster based on a threshold of F=10 (F-stats are in sub-brick #0),
     and require a volume of 40 voxels (1969 mm^3).  The output will be
     the same F-stats as in the input, but subject to the threshold and
     clustering.

       3dmerge -1clust 3.76 1969 -1thresh 10.0    \
               -prefix e2.f10 stats+orig'[0]'

  3. F-stat only:

     Perform the same clustering (as in #2), but apply the radius and
     cluster size in terms of cubic millimeter voxels (as if the voxels
     were 1x1x1).  So add '-dxyz=1', and adjust rmm and mvul.

       3dmerge -dxyz=1 -1clust 1 40 -1thresh 10.0    \
               -prefix e3.f10 stats+orig'[0]'

  4. t-stat and beta weight:

     For some condition, our beta weight is in sub-brick #4, with the
     corresponding t-stat in sub-brick #5.  Cluster based on 40 voxels
     and a t-stat threshold of 3.25.  Output the data from the beta
     weights, not the t-stats.

       3dmerge -dxyz=1 -1clust 1 40 -1thresh 3.25    \
               -1tindex 5 -1dindex 4                 \
               -prefix e4.t3.25 stats+orig

  5. t-stat mask:

     Apply the same threshold and cluster as in #4, but output a mask.
     Since there are 5 clusters found in this example, the values in
     the mask will be from 1 to 5, representing the largest cluster to
     the smallest.  Use -1clust_order on sub-brick 5.

       3dmerge -dxyz=1 -1clust_order 1 40 -1thresh 3.25    \
               -prefix e5.mask5 stats+orig'[5]'

     Note: this should match the 3dclust output from:

       3dclust -1thresh 3.25 -dxyz=1 1 40 stats+orig'[5]'

----------------------------------------------------------------------
EDITING OPTIONS APPLIED TO EACH INPUT DATASET:
  -1thtoin         = Copy threshold data over intensity data.
                       This is only valid for datasets with some
                       thresholding statistic attached.  All
                       subsequent operations apply to this
                       substituted data.
  -2thtoin         = The same as -1thtoin, but do NOT scale the
                       threshold values from shorts to floats when
                       processing.  This option is only provided
                       for compatibility with the earlier versions
                       of the AFNI package '3d*' programs.
  -1noneg          = Zero out voxels with negative intensities
  -1abs            = Take absolute values of intensities
  -1clip val       = Clip intensities in range (-val,val) to zero
  -2clip v1 v2     = Clip intensities in range (v1,v2) to zero
  -1uclip val      = These options are like the above, but do not apply
  -2uclip v1 v2        any automatic scaling factor that may be attached
                       to the data.  These are for use only in special
                       circumstances.  (The 'u' means 'unscaled'.  Program
                       '3dinfo' can be used to find the scaling factors.)
               N.B.: Only one of these 'clip' options can be used; you cannot
                       combine them to have multiple clipping executed.
  -1thresh thr     = Use the threshold data to censor the intensities
                       (only valid for 'fith', 'fico', or 'fitt' datasets)
                       (or if the threshold sub-brick is set via -1tindex)
               N.B.: The value 'thr' is floating point, in the range
                           0.0 < thr < 1.0  for 'fith' and 'fico' datasets,
                       and 0.0 < thr < 32.7 for 'fitt' datasets.
  -2thresh t1 t2   = Zero out voxels where the threshold sub-brick value
                       lies between 't1' and 't2' (exclusive).  If t1=-t2,
                       is the same as '-1thresh t2'.
  -1blur_sigma bmm = Gaussian blur with sigma = bmm (in mm)
  -1blur_rms bmm   = Gaussian blur with rms deviation = bmm
  -1blur_fwhm bmm  = Gaussian blur with FWHM = bmm
  -t1blur_sigma bmm= Gaussian blur of threshold with sigma = bmm(in mm)
  -t1blur_rms bmm  = Gaussian blur of threshold with rms deviation = bmm
  -t1blur_fwhm bmm = Gaussian blur of threshold with FWHM = bmm
  -1zvol x1 x2 y1 y2 z1 z2
                   = Zero out entries inside the 3D volume defined
                       by x1 <= x <= x2, y1 <= y <= y2, z1 <= z <= z2 ;
               N.B.: The ranges of x,y,z in a dataset can be found
                       using the '3dinfo' program. Dimensions are in mm.
               N.B.: This option may not work correctly at this time, but
                       I've not figured out why!

 CLUSTERING
  -dxyz=1  = In the cluster editing options, the spatial clusters
             are defined by connectivity in true 3D distance, using
             the voxel dimensions recorded in the dataset header.
             This option forces the cluster editing to behave as if
             all 3 voxel dimensions were set to 1 mm.  In this case,
             'rmm' is then the max number of grid cells apart voxels
             can be to be considered directly connected, and 'vmul'
             is the min number of voxels to keep in the cluster.
       N.B.: The '=1' is part of the option string, and can't be
             replaced by some other value.  If you MUST have some
             other value for voxel dimensions, use program 3drefit.
 
  The following cluster options are mutually exclusive: 
  -1clust rmm vmul = Form clusters with connection distance rmm
                       and clip off data not in clusters of
                       volume at least vmul microliters
  -1clust_mean rmm vmul = Same as -1clust, but all voxel intensities 
                            within a cluster are replaced by the average
                            intensity of the cluster. 
  -1clust_max rmm vmul  = Same as -1clust, but all voxel intensities 
                            within a cluster are replaced by the maximum
                            intensity of the cluster. 
  -1clust_amax rmm vmul = Same as -1clust, but all voxel intensities 
                            within a cluster are replaced by the maximum
                            absolute intensity of the cluster. 
  -1clust_smax rmm vmul = Same as -1clust, but all voxel intensities 
                            within a cluster are replaced by the maximum
                            signed intensity of the cluster. 
  -1clust_size rmm vmul = Same as -1clust, but all voxel intensities 
                            within a cluster are replaced by the size 
                            of the cluster (in multiples of vmul).   
  -1clust_order rmm vmul= Same as -1clust, but all voxel intensities 
                            within a cluster are replaced by the cluster
                            size index (largest cluster=1, next=2, ...).
 * If rmm is given as 0, this means to use the 6 nearest neighbors to
     form clusters of nonzero voxels.
 * If vmul is given as zero, then all cluster sizes will be accepted
     (probably not very useful!).
 * If vmul is given as negative, then abs(vmul) is the minimum number
     of voxels to keep.
 
  The following commands produce erosion and dilation of 3D clusters.  
  These commands assume that one of the -1clust commands has been used.
  The purpose is to avoid forming strange clusters with 2 (or more)    
  main bodies connected by thin 'necks'.  Erosion can cut off the neck.
  Dilation will minimize erosion of the main bodies.                   
  Note:  Manipulation of values inside a cluster (-1clust commands)    
         occurs AFTER the following two commands have been executed.   
  -1erode pv    For each voxel, set the intensity to zero unless pv %  
                of the voxels within radius rmm are nonzero.           
  -1dilate      Restore voxels that were removed by the previous       
                command if there remains a nonzero voxel within rmm.   
 
  The following filter options are mutually exclusive: 
  -1filter_mean rmm   = Set each voxel to the average intensity of the 
                          voxels within a radius of rmm. 
  -1filter_nzmean rmm = Set each voxel to the average intensity of the 
                          non-zero voxels within a radius of rmm. 
  -1filter_max rmm    = Set each voxel to the maximum intensity of the 
                          voxels within a radius of rmm. 
  -1filter_amax rmm   = Set each voxel to the maximum absolute intensity
                          of the voxels within a radius of rmm. 
  -1filter_smax rmm   = Set each voxel to the maximum signed intensity 
                          of the voxels within a radius of rmm. 
  -1filter_aver rmm   = Same idea as '_mean', but implemented using a
                          new code that should be faster.
 
  The following threshold filter options are mutually exclusive: 
  -t1filter_mean rmm   = Set each correlation or threshold voxel to the 
                          average of the voxels within a radius of rmm. 
  -t1filter_nzmean rmm = Set each correlation or threshold voxel to the 
                          average of the non-zero voxels within 
                          a radius of rmm. 
  -t1filter_max rmm    = Set each correlation or threshold voxel to the 
                          maximum of the voxels within a radius of rmm. 
  -t1filter_amax rmm   = Set each correlation or threshold voxel to the 
                          maximum absolute intensity of the voxels 
                          within a radius of rmm. 
  -t1filter_smax rmm   = Set each correlation or threshold voxel to the 
                          maximum signed intensity of the voxels 
                          within a radius of rmm. 
  -t1filter_aver rmm   = Same idea as '_mean', but implemented using a
                          new code that should be faster.
 
  -1mult factor    = Multiply intensities by the given factor
  -1zscore         = If the sub-brick is labeled as a statistic from
                     a known distribution, it will be converted to
                     an equivalent N(0,1) deviate (or 'z score').
                     If the sub-brick is not so labeled, nothing will
                     be done.

The above '-1' options are carried out in the order given above,
regardless of the order in which they are entered on the command line.

N.B.: The 3 '-1blur' options just provide different ways of
      specifying the radius used for the blurring function.
      The relationships among these specifications are
         sigma = 0.57735027 * rms = 0.42466090 * fwhm
      The requisite convolutions are done using FFTs; this is by
      far the slowest operation among the editing options.

OTHER OPTIONS:
  -datum type = Coerce the output data to be stored as the given type,
                  which may be byte, short, or float.
          N.B.: Byte data cannot be negative.  If this datum type is chosen,
                  any negative values in the edited and/or merged dataset
                  will be set to zero.
  -keepthr    = When using 3dmerge to edit exactly one dataset of a
                  functional type with a threshold statistic attached,
                  normally the resulting dataset is of the 'fim'
                  (intensity only) type.  This option tells 3dmerge to
                  copy the threshold data (unedited in any way) into
                  the output dataset.
          N.B.: This option is ignored if 3dmerge is being used to
                  combine 2 or more datasets.
          N.B.: The -datum option has no effect on the storage of the
                  threshold data.  Instead use '-thdatum type'.

  -doall      = Apply editing and merging options to ALL sub-bricks 
                  uniformly in a dataset.
          N.B.: All input datasets must have the same number of sub-bricks
                  when using the -doall option. 
          N.B.: The threshold specific options (such as -1thresh, 
                  -keepthr, -tgfisher, etc.) are not compatible with 
                  the -doall command.  Neither are the -1dindex or
                  the -1tindex options.
          N.B.: All labels and statistical parameters for individual 
                  sub-bricks are copied from the first dataset.  It is 
                  the responsibility of the user to verify that these 
                  are appropriate.  Note that sub-brick auxiliary data 
                  can be modified using program 3drefit. 

  -1dindex j  = Uses sub-brick #j as the data source , and uses sub-brick
  -1tindex k  = #k as the threshold source.  With these, you can operate
                  on any given sub-brick of the inputs dataset(s) to produce
                  as output a 1 brick dataset.  If desired, a collection
                  of 1 brick datasets can later be assembled into a
                  multi-brick bucket dataset using program '3dbucket'
                  or into a 3D+time dataset using program '3dTcat'.
          N.B.: If these options aren't used, j=0 and k=1 are the defaults

  The following option allows you to specify a mask dataset that
  limits the action of the 'filter' options to voxels that are
  nonzero in the mask:

  -1fmask mset = Read dataset 'mset' (which can include a
                  sub-brick specifier) and use the nonzero
                  voxels as a mask for the filter options.
                  Filtering calculations will not use voxels
                  that are outside the mask.  If an output
                  voxel does not have ANY masked voxels inside
                  the rmm radius, then that output voxel will
                  be set to 0.
         N.B.: * Only the -1filter_* and -t1filter_* options are
                 affected by -1fmask.
               * Voxels NOT in the fmask will be set to zero in the
                 output when the filtering occurs.  THIS IS NEW BEHAVIOR,
                 as of 11 Oct 2007.  Previously, voxels not in the fmask,
                 but within 'rmm' of a voxel in the mask, would get a
                 nonzero output value, as those nearby voxels would be
                 combined (via whatever '-1f...' option was given).
               * If you wish to restore this old behavior, where non-fmask
                 voxels can get nonzero output, then use the new option
                 '-1fm_noclip' in addition to '-1fmask'. The two comments
                 below apply to the case where '-1fm_noclip' is given!
                 * In the linear averaging filters (_mean, _nzmean,
                   and _expr), voxels not in the mask will not be used
                   or counted in either the numerator or denominator.
                   This can give unexpected results if you use '-1fm_noclip'.
                   For example, if the mask is designed to exclude the volume
                   outside the brain, then voxels exterior to the brain,
                   but within 'rmm', will have a few voxels inside the brain
                   included in the filtering.  Since the sum of weights (the
                   denominator) is only over those few intra-brain
                   voxels, the effect will be to extend the significant
                   part of the result outward by rmm from the surface
                   of the brain.  In contrast, without the mask, the
                   many small-valued voxels outside the brain would
                   be included in the numerator and denominator sums,
                   which would barely change the numerator (since the
                   voxel values are small outside the brain), but would
                   increase the denominator greatly (by including many
                   more weights).  The effect in this case (no -1fmask)
                   is to make the filtering taper off gradually in the
                   rmm-thickness shell around the brain.
                 * Thus, if the -1fmask is intended to clip off non-brain
                   data from the filtering, its use should be followed by
                   masking operation using 3dcalc:
   3dmerge -1filter_aver 12 -1fm_noclip -1fmask mask+orig -prefix x input+orig
   3dcalc  -a x -b mask+orig -prefix y -expr 'a*step(b)'
   rm -f x+orig.*
                 The desired result is y+orig - filtered using only
                 brain voxels (as defined by mask+orig), and with
                 the output confined to the brain voxels as well.

  The following option allows you to specify an almost arbitrary
  weighting function for 3D linear filtering:

  -1filter_expr rmm expr
     Defines a linear filter about each voxel of radius 'rmm' mm.
     The filter weights are proportional to the expression evaluated
     at each voxel offset in the rmm neighborhood.  You can use only
     these symbols in the expression:
         r = radius from center
         x = dataset x-axis offset from center
         y = dataset y-axis offset from center
         z = dataset z-axis offset from center
         i = x-axis index offset from center
         j = y-axis index offset from center
         k = z-axis index offset from center
     Example:
       -1filter_expr 12.0 'exp(-r*r/36.067)'
     This does a Gaussian filter over a radius of 12 mm.  In this
     example, the FWHM of the filter is 10 mm. [in general, the
     denominator in the exponent would be 0.36067 * FWHM * FWHM.
     This is one way to get a Gaussian blur combined with the
     -1fmask option.  The radius rmm=12 is chosen where the weights
     get smallish.]  Another example:
       -1filter_expr 20.0 'exp(-(x*x+16*y*y+z*z)/36.067)'
     which is a non-spherical Gaussian filter.

  ** For shorthand, you can also use the new option (11 Oct 2007)
  -1filter_blur fwhm
        which is equivalent to
  -1filter_expr 1.3*fwhm 'exp(-r*r/(.36067*fwhm*fwhm)'
        and will implement a Gaussian blur.  The only reason to do
        Gaussian blurring this way is if you also want to use -1fmask!

  The following option lets you apply a 'Winsor' filter to the data:

  -1filter_winsor rmm nw
     The data values within the radius rmm of each voxel are sorted.
     Suppose there are 'N' voxels in this group.  We index the
     sorted voxels as s[0] <= s[1] <= ... <= s[N-1], and we call the
     value of the central voxel 'v' (which is also in array s[]).
                 If v < s[nw]    , then v is replaced by s[nw]
       otherwise If v > s[N-1-nw], then v is replace by s[N-1-nw]
       otherwise v is unchanged
     The effect is to increase 'too small' values up to some
     middling range, and to decrease 'too large' values.
     If N is odd, and nw=(N-1)/2, this would be a median filter.
     In practice, I recommend that nw be about N/4; for example,
       -dxyz=1 -1filter_winsor 2.5 19
     is a filter with N=81 that gives nice results.
   N.B.: This option is NOT affected by -1fmask
   N.B.: This option is slow! and experimental.

  The following option returns a rank value at each voxel in 
  the input dataset.
  -1rank 
     If the input voxels were, say, 12  45  9  0  9  12  0
     the output would be             2   3  1  0  1   2  0
     This option is handy for turning FreeSurfer's segmentation
     volumes to ROI volumes that can be easily colorized with AFNI.
     For example:
     3dmerge -1rank -prefix aparc+aseg_rank aparc+aseg.nii 
     To view aparc+aseg_rank+orig, use the ROI_128 colormap
     and set the colorbar range to 128.
     The -1rank option also outputs a 1D file that contains 
     the mapping from the input dataset to the ranked output.

     See also program 3dRank

MERGING OPTIONS APPLIED TO FORM THE OUTPUT DATASET:
 [That is, different ways to combine results. The]
 [following '-g' options are mutually exclusive! ]
  -gmean     = Combine datasets by averaging intensities
                 (including zeros) -- this is the default
  -gnzmean   = Combine datasets by averaging intensities
                 (not counting zeros)
  -gmax      = Combine datasets by taking max intensity
                 (e.g., -7 and 2 combine to 2)
  -gamax     = Combine datasets by taking max absolute intensity
                 (e.g., -7 and 2 combine to 7)
  -gsmax     = Combine datasets by taking max signed intensity
                 (e.g., -7 and 2 combine to -7)
  -gcount    = Combine datasets by counting number of 'hits' in
                  each voxel (see below for defintion of 'hit')
  -gorder    = Combine datasets in order of input:
                * If a voxel is nonzero in dataset #1, then
                    that value goes into the voxel.
                * If a voxel is zero in dataset #1 but nonzero
                    in dataset #2, then the value from #2 is used.
                * And so forth: the first dataset with a nonzero
                    entry in a given voxel 'wins'
  -gfisher   = Takes the arctanh of each input, averages these,
                  and outputs the tanh of the average.  If the input
                  datum is 'short', then input values are scaled by
                  0.0001 and output values by 10000.  This option
                  is for merging bricks of correlation coefficients.

  -nscale    = If the output datum is shorts, don't do the scaling
                  to the max range [similar to 3dcalc's -nscale option]

MERGING OPERATIONS APPLIED TO THE THRESHOLD DATA:
 [That is, different ways to combine the thresholds.  If none of these ]
 [are given, the thresholds will not be merged and the output dataset  ]
 [will not have threshold data attached.  Note that the following '-tg']
 [command line options are mutually exclusive, but are independent of  ]
 [the '-g' options given above for merging the intensity data values.  ]
  -tgfisher  = This option is only applicable if each input dataset
                  is of the 'fico' or 'fith' types -- functional
                  intensity plus correlation or plus threshold.
                  (In the latter case, the threshold values are
                  interpreted as correlation coefficients.)
                  The correlation coefficients are averaged as
                  described by -gfisher above, and the output
                  dataset will be of the fico type if all inputs
                  are fico type; otherwise, the output datasets
                  will be of the fith type.
         N.B.: The difference between the -tgfisher and -gfisher
                  methods is that -tgfisher applies to the threshold
                  data stored with a dataset, while -gfisher
                  applies to the intensity data.  Thus, -gfisher
                  would normally be applied to a dataset created
                  from correlation coefficients directly, or from
                  the application of the -1thtoin option to a fico
                  or fith dataset.

OPTIONAL WAYS TO POSTPROCESS THE COMBINED RESULTS:
 [May be combined with the above methods.]
 [Any combination of these options may be used.]
  -ghits count     = Delete voxels that aren't !=0 in at least
                       count datasets (!=0 is a 'hit')
  -gclust rmm vmul = Form clusters with connection distance rmm
                       and clip off data not in clusters of
                       volume at least vmul microliters

The '-g' and '-tg' options apply to the entire group of input datasets.

OPTIONS THAT CONTROL THE NAMES OF THE OUTPUT DATASET:
  -session dirname  = write output into given directory (default=./)
  -prefix  pname    = use 'pname' for the output dataset prefix
                       (default=mrg)

NOTES:
 **  If only one dataset is read into this program, then the '-g'
       options do not apply, and the output dataset is simply the
       '-1' options applied to the input dataset (i.e., edited).
 **  A merged output dataset is ALWAYS of the intensity-only variety.
 **  You can combine the outputs of 3dmerge with other sub-bricks
       using the program 3dbucket.
 **  Complex-valued datasets cannot be merged.
 **  This program cannot handle time-dependent datasets without -doall.
 **  Note that the input datasets are specified by their .HEAD files,
       but that their .BRIK files must exist also!

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

 ** Input datasets using sub-brick selectors are treated as follows:
      - 3D+time if the dataset is 3D+time and more than 1 brick is chosen
      - otherwise, as bucket datasets (-abuc or -fbuc)
       (in particular, fico, fitt, etc. datasets are converted to fbuc)
 ** If you are NOT using -doall, and choose more than one sub-brick
     with the selector, then you may need to use -1dindex to further
     pick out the sub-brick on which to operate (why you would do this
     I cannot fathom).  If you are also using a thresholding operation
     (e.g., -1thresh), then you also MUST use -1tindex to choose which
     sub-brick counts as the 'threshold' value.  When used with sub-brick
     selection, 'index' refers the dataset AFTER it has been read in:
          -1dindex 1 -1tindex 3 'dset+orig[4..7]'
     means to use the #5 sub-brick of dset+orig as the data for merging
     and the #7 sub-brick of dset+orig as the threshold values.
 ** The above example would better be done with
          -1tindex 1 'dset+orig[5,7]'
     since the default data index is 0. (You would only use -1tindex if
     you are actually using a thresholding operation.)
 ** -1dindex and -1tindex apply to all input datasets.

++ Compile date = Nov  5 2009




AFNI program: 3dMINCtoAFNI
Usage: 3dMINCtoAFNI [-prefix ppp] dataset.mnc
Reads in a MINC formatted file and writes it out as an
AFNI dataset file pair with the given prefix.  If the
prefix option isn't used, the input filename will be
used, after the '.mnc' is chopped off.

NOTES:
* Setting environment variable AFNI_MINC_FLOATIZE to Yes
   will cause MINC datasets to be converted to floats on
   input.  Otherwise, they will be kept in their 'native'
   data type if possible, which may cause problems with
   scaling on occasion.
* The TR recorded in MINC files is often incorrect.  You may
   need to fix this (or other parameters) using 3drefit.

++ Compile date = Nov  5 2009




AFNI program: 3dnewid
Assigns a new ID code to a dataset; this is useful when making
a copy of a dataset, so that the internal ID codes remain unique.

Usage: 3dnewid dataset [dataset ...]
 or
       3dnewid -fun [n]
       to see what n randomly generated ID codes look like.
       (If the integer n is not present, 1 ID code is printed.)

How ID codes are created (here and in other AFNI programs):
----------------------------------------------------------
The AFNI ID code generator attempts to create a globally unique
string identifier, using the following steps.
1) A long string is created from the system identifier
   information ('uname -a'), the current epoch time in seconds
   and microseconds, the process ID, and the number of times
   the current process has called the ID code function.
2) This string is then hashed into a 128 bit code using the
   MD5 algorithm. (cf. file thd_md5.c)
3) This bit code is then converted to a 22 character string
   using Base64 encoding, replacing '/' with '-' and '+' with '_'.
   With these changes, the ID code can be used as a Unix filename
   or an XML name string. (cf. file thd_base64.c)
4) A 4 character prefix is attached at the beginning to produce
   the final ID code.  If you set the environment variable
   IDCODE_PREFIX to something, then its first 3 characters and an
   underscore will be used for the prefix of the new ID code,
   provided that the first character is alphabetic and the other
   2 alphanumeric; otherwise, the default prefix 'NIH_' will be
   used.
The source code is function UNIQ_idcode() in file niml.c.

++ Compile date = Nov  5 2009




AFNI program: 3dNLfim
++ 3dNLfim: AFNI version=AFNI_2008_07_18_1710 (Nov  5 2009) [32-bit]
++ Authored by: B. Douglas Ward
This program calculates a nonlinear regression for each voxel of the  
input AFNI 3d+time data set.  The nonlinear regression is calculated  
by means of a least squares fit to the signal plus noise models which 
are specified by the user.                                            
                                                                      
Usage:                                                                
3dNLfim                                                               
-input fname       fname = filename of 3d + time data file for input  
[-mask mset]       Use the 0 sub-brick of dataset 'mset' as a mask    
                     to indicate which voxels to analyze (a sub-brick 
                     selector is allowed)  [default = use all voxels] 
[-ignore num]      num   = skip this number of initial images in the  
                     time series for regresion analysis; default = 0  
               ****N.B.: default ignore value changed from 3 to 0,    
                         on 04 Nov 2008 (BHO day).                    
[-inTR]            set delt = TR of the input 3d+time dataset         
                     [The default is to compute with delt = 1.0 ]     
                     [The model functions are calculated using a      
                      time grid of: 0, delt, 2*delt, 3*delt, ... ]    
[-TR delt]         directly set the TR of the time series model;      
                     can be useful if the input file is a .1D file    
                     (transposed with the \' operator)               
[-time fname]      fname = ASCII file containing each time point      
                     in the time series. Defaults to even spacing     
                     given by TR (this option overrides -inTR).       
-signal slabel     slabel = name of (non-linear) signal model         
-noise  nlabel     nlabel = name of (linear) noise model              
-sconstr k c d     constraints for kth signal parameter:              
                      c <= gs[k] <= d                                 
                 **N.B.: It is important to set the parameter         
                         constraints with care!                       
                 **N.B.: -sconstr and -nconstr options must appear    
                         AFTER -signal and -noise on the command line 
-nconstr k c d     constraints for kth noise parameter:               
                      c+b[k] <= gn[k] <= d+b[k]                       
[-nabs]            use absolute constraints for noise parameters:     
                     c <= gn[k] <= d  [default=relative, as above]    
[-nrand n]         n = number of random test points [default=19999]      
[-nbest b]         b = use b best test points to start [default=9]   
[-rmsmin r]        r = minimum rms error to reject reduced model      
[-fdisp fval]      display (to screen) results for those voxels       
                     whose f-statistic is > fval [default=999.0]       
[-progress ival]   display (to screen) results for those voxels       
                     every ival number of voxels                      
[-voxel_count]     display (to screen) the current voxel index        
                                                                      
--- These options choose the least-square minimization algorithm ---  
                                                                      
[-SIMPLEX]         use Nelder-Mead simplex method [default]           
[-POWELL]          use Powell's NEWUOA method instead of the          
                     Nelder-Mead simplex method to find the           
                     nonlinear least-squares solution                 
                     [slower; usually more accurate, but not always!] 
[-BOTH]            use both Powell's and Nelder-Mead method           
                     [slowest, but should be most accurate]           
                                                                      
--- These options generate individual AFNI 2 sub-brick datasets ---   
--- [All these options must be AFTER options -signal and -noise]---   
                                                                      
[-freg fname]      perform f-test for significance of the regression; 
                     output 'fift' is written to prefix filename fname
[-frsqr fname]     calculate R^2 (coef. of multiple determination);   
                     store along with f-test for regression;          
                     output 'fift' is written to prefix filename fname
[-fsmax fname]     estimate signed maximum of signal; store along     
                     with f-test for regression; output 'fift' is     
                     written to prefix filename fname                 
[-ftmax fname]     estimate time of signed maximum; store along       
                     with f-test for regression; output 'fift' is     
                     written to prefix filename fname                 
[-fpsmax fname]    calculate (signed) maximum percentage change of    
                     signal from baseline; output 'fift' is           
                     written to prefix filename fname                 
[-farea fname]     calculate area between signal and baseline; store  
                     with f-test for regression; output 'fift' is     
                     written to prefix filename fname                 
[-fparea fname]    percentage area of signal relative to baseline;    
                     store with f-test for regression; output 'fift'  
                     is written to prefix filename fname              
[-fscoef k fname]  estimate kth signal parameter gs[k]; store along   
                     with f-test for regression; output 'fift' is     
                     written to prefix filename fname                 
[-fncoef k fname]  estimate kth noise parameter gn[k]; store along    
                     with f-test for regression; output 'fift' is     
                     written to prefix filename fname                 
[-tscoef k fname]  perform t-test for significance of the kth signal  
                     parameter gs[k]; output 'fitt' is written        
                     to prefix filename fname                         
[-tncoef k fname]  perform t-test for significance of the kth noise   
                     parameter gn[k]; output 'fitt' is written        
                     to prefix filename fname                         
                                                                      
--- These options generate one AFNI 'bucket' type dataset ---         
                                                                      
[-bucket n prefixname]   create one AFNI 'bucket' dataset containing  
                           n sub-bricks; n=0 creates default output;  
                           output 'bucket' is written to prefixname   
The mth sub-brick will contain:                                       
[-brick m scoef k label]   kth signal parameter regression coefficient
[-brick m ncoef k label]   kth noise parameter regression coefficient 
[-brick m tmax label]      time at max. abs. value of signal          
[-brick m smax label]      signed max. value of signal                
[-brick m psmax label]     signed max. value of signal as percent     
                             above baseline level                     
[-brick m area label]      area between signal and baseline           
[-brick m parea label]     signed area between signal and baseline    
                             as percent of baseline area              
[-brick m tscoef k label]  t-stat for kth signal parameter coefficient
[-brick m tncoef k label]  t-stat for kth noise parameter coefficient 
[-brick m resid label]     std. dev. of the full model fit residuals  
[-brick m rsqr  label]     R^2 (coefficient of multiple determination)
[-brick m fstat label]     F-stat for significance of the regression  

[-noFDR]                   Don't write the FDR (q vs. threshold)
                           curves into the output dataset.
                           (Same as 'setenv AFNI_AUTOMATIC_FDR NO')
                                                                      
     --- These options write time series fit for ---                  
     --- each voxel to an AFNI 3d+time dataset   ---                  
                                                                      
[-sfit fname]      fname = prefix for output 3d+time signal model fit 
[-snfit fname]     fname = prefix for output 3d+time signal+noise fit 
                                                                      

 -jobs J   Run the program with 'J' jobs (sub-processes).
             On a multi-CPU machine, this can speed the
             program up considerably.  On a single CPU
             machine, using this option is silly.
             J should be a number from 1 up to the
             number of CPU sharing memory on the system.
             J=1 is normal (single process) operation.
             The maximum allowed value of J is 32.
         * For more information on parallelizing, see
             http://afni.nimh.nih.gov/afni/doc/misc/parallize.html
         * Use -mask to get more speed; cf. 3dAutomask.

----------------------------------------------------------------------
Signal Models (see the appropriate model_*.c file for exact details) :

  Null                     : No Signal
                             (no parameters)
                             see model_null.c

  SineWave_AP              : Sinusoidal Response
                             (amplitude, phase)
                             see model_sinewave_ap.c

  SquareWave_AP            : Square Wave Response
                             (amplitude, phase)
                             see model_squarewave_ap.c

  TrnglWave_AP             : Triangular Wave Response
                             (amplitude, phase)
                             see model_trnglwave_ap.c

  SineWave_APF             : Sinusoidal Wave Response
                             (amplitude, phase, frequency)
                             see model_sinewave_apf.c

  SquareWave_APF           : Sinusoidal Wave Response
                             (amplitude, phase, frequency)
                             see model_squarewave_apf.c

  TrnglWave_APF            : Sinusoidal Wave Response
                             (amplitude, phase, frequency)
                             see model_trnglwave_apf.c

  Exp                      : Exponential Function
                             (a,b): a * exp(b * t)
                             see model_exp.c

  DiffExp                  : Differential-Exponential Drug Response
                             (t0, k, alpha1, alpha2)
                             see model_diffexp.c

  GammaVar                 : Gamma-Variate Function Drug Response
                             (t0, k, r, b)
                             see model_gammavar.c

  Beta                     : Beta Distribution Model
                             (t0, tf, k, alpha, beta)
                             see model_beta.c

  ConvGamma2a              : Gamma Convolution with 2 Input Time Series
                             (t0, r, b)
                             see model_convgamma2a.c

  ConvGamma                : Gamma Vairate Response Model
                             (t0, amp, r, b)
                             see model_convgamma.c

  demri_3                  : Dynamic (contrast) Enhanced MRI
                             (K_trans, Ve, k_ep)
                             see model_demri_3.c
                  for help : setenv AFNI_MODEL_HELP_DEMRI_3 YES

  ADC                      : Diffusion Signal Model
                             (So, D)
                             see model_diffusion.c

  michaelis_menton         : Michaelis/Menten Concentration Model
                             (v, vmax, k12, k21, mag)
                             see model_michaelis_menton.c

  Expr2                    : generic (3dcalc-like) expression with
                             exactly 2 'free' parameters and using
                             symbol 't' as the time variable;
                             see model_expr2.c for details.

----------------------------------------
Noise Models (see the appropriate model_*.c file for exact details) :

  Zero                     : Zero Noise Model
                             (no parameters)
                             see model_zero.c

  Constant                 : Constant Noise Model
                             (constant)
                             see model_constant.c

  Linear                   : Linear Noise Model
                             (constant, linear)
                             see model_linear.c

  Linear+Ort               : Linear+Ort Noise Model
                             (constant, linear, Ort)
                             see model_linplusort.c

  Quadratic                : Quadratic Noise Model
                             (constant, linear, quadratic)
                             see model_quadratic.c

++ Compile date = Nov  5 2009




AFNI program: 3dnoise
Usage: 3dnoise [-blast] [-snr fac] [-nl x ] datasets ...
Estimates noise level in 3D datasets, and optionally
set voxels below the noise threshold to zero.
This only works on datasets that are stored as shorts,
and whose elements are all nonnegative.
  -blast   = Set values at or below the cutoff to zero.
               In 3D+time datasets, a spatial location
               is set to zero only if a majority of time
               points fall below the cutoff; in that case
               all the values at that location are zeroed.
  -snr fac = Set cutoff to 'fac' times the estimated
               noise level.  Default fac = 2.5.  What to
               use for this depends strongly on your MRI
               system -- I often use 5, but our true SNR
               is about 100 for EPI.
  -nl x    = Set the noise level to 'x', skipping the
               estimation procedure.  Also sets fac=1.0.
               You can use program 3dClipLevel to get an
               estimate of a value for 'x'.
Author -- RW Cox

++ Compile date = Nov  5 2009




AFNI program: 3dNotes
Program: 3dNotes 
Author:  T. Ross 
(c)1999 Medical College of Wisconsin 
                                                                        
3dNotes - a program to add, delete and show notes for AFNI datasets.    
 
----------------------------------------------------------------------- 
                                                                        
Usage: 3dNotes [-a "string"] [-h "string"][-d num] [-help] dataset  
 
Examples: 
 
3dNotes -a      "Subject sneezed in scanner, Aug 13 2004" elvis+orig     
3dNotes -h      "Subject likes fried PB & banana sandwiches" elvis+orig  
3dNotes -HH     "Subject has left the building" elvis+orig              
3dNotes -d 2 -h "Subject sick of PB'n'banana sandwiches" elvis+orig  
 
----------------------------------------------------------------------- 
                                                                        
Explanation of Options:
---------------------- 
   dataset       : AFNI compatible dataset [required].
                                                                        
   -a   "str"  : Add the string "str" to the list of notes.
                                                                        
                   Note that you can use the standard C escape codes,
                   \n for newline \t for tab, etc.
                                                                        
   -h   "str"   : Append the string "str" to the dataset's history.  This
                    can only appear once on the command line.  As this is
                    added to the history, it cannot easily be deleted. But,
                    history is propagated to the children of this dataset.
                                                                        
   -HH  "str"   : Replace any existing history note with "str".  This 
                    line cannot be used with '-h'.
                                                                        
   -d   num       : deletes note number num.
                                                                        
   -ses           : Print to stdout the expanded notes.                 
                                                                        
   -help          : Displays this screen.
                                                                        
                                                                        
The default action, with no options, is to display the notes for the
dataset.  If there are options, all deletions occur first and essentially
simultaneously.  Then, notes are added in the order listed on the command
line.  If you do something like -d 10 -d 10, it will delete both notes 10
and 11.  Don't do that.


++ Compile date = Nov  5 2009




AFNI program: 3dnvals
Usage: 3dnvals [-all] [-verbose] dataset [dataset dataset ...]
Prints out the number of sub-bricks in a 3D dataset
If -all is specified, prints out all 4 dimensions
Nx, Ny, Nz, Nvals
If -verbose is used then the header name of the dataset is printed first.


++ Compile date = Nov  5 2009




AFNI program: 3dOverlap
Usage: 3dOverlap [options] dset1 dset2 ...
Output = count of number of voxels that are nonzero in ALL
         of the input dataset sub-bricks
The result is simply a number printed to stdout.  (If a single
brick was input, this is just the count of the number of nonzero
voxels in that brick.)
Options:
  -save ppp = Save the count of overlaps at each voxel into a
              dataset with prefix 'ppp' (properly thresholded,
              this could be used as a mask dataset).
Example:
  3dOverlap -save abcnum a+orig b+orig c+orig
  3dmaskave -mask 'abcnum+orig<3..3>' a+orig

++ Compile date = Nov  5 2009




AFNI program: 3dPAR2AFNI.pl
Unknown option: e
Unknown option: l
Unknown option: p
3dPAR2ANFI
Version: 2008/07/18 11:12

Command line Options:
-h     This help message.
-v     Be verbose in operation.
-s     Skip the outliers test when converting 4D files
       The default is to perform the outliers test.
-n     Output NIfTI files instead of HEAD/BRIK.
       The default is create HEAD/BRIK files.
-a     Output ANALYZE files instead of HEAD/BRIK.
-o     The name of the directory where the created files should be
       placed.  If this directory does not exist the program exits
       without performing any conversion.
       The default is to place created files in the same directory
       as the PAR files.
-g     Gzip the files created.
       The default is not to gzip the files.
-2     2-Byte-swap the files created.
       The default is not to 2 byte-swap.
-4     4-Byte-swap the files created.
       The default is not to 4 byte-swap.

Sample invocations:
3dPAR2AFNI subject1.PAR
	Converts the file subject1.PAR file to subject1+orig.{HEAD,BRIK}
3dPAR2AFNI -s subject1.PAR
       Same as above but skip the outlier test
3dPAR2AFNI -n subject1.PAR
       Converts the file subject1.PAR file to subject1.nii
3dPAR2AFNI -n -s subject1.PAR
       Same as above but skip the outlier test
3dPAR2AFNI -n -s -o ~/tmp subject1.PAR
       Same as above but skip the outlier test and place the
       created NIfTI files in ~/tmp
3dPAR2AFNI -n -s -o ~/tmp *.PAR
       Converts all the PAR/REC files in the current directory to
       NIfTI files, skip the outlier test and place the created
       NIfTI files in ~/tmp



AFNI program: 3dpc
Principal Component Analysis of 3D Datasets
Usage: 3dpc [options] dataset dataset ...

Each input dataset may have a sub-brick selector list.
Otherwise, all sub-bricks from a dataset will be used.

OPTIONS:
  -dmean        = remove the mean from each input brick (across space)
  -vmean        = remove the mean from each input voxel (across bricks)
                    [N.B.: -dmean and -vmean are mutually exclusive]
                    [default: don't remove either mean]
  -vnorm        = L2 normalize each input voxel time series
                    [occurs after the de-mean operations above,]
                    [and before the brick normalization below. ]
  -normalize    = L2 normalize each input brick (after mean subtraction)
                    [default: don't normalize]
  -pcsave sss   = 'sss' is the number of components to save in the output;
                    it can't be more than the number of input bricks
                    [default = none of them]
                  * To get all components, set 'sss' to a very large
                    number (more than the time series length), like 99999
  -reduce r pp  = Compute a 'dimensionally reduced' dataset with the top
                    'r' eigenvalues and write to disk in dataset 'pp'
                    [default = don't compute this at all]
                  * If '-vmean' is given, then each voxel's mean will
                    be added back into the reduced time series.  If you
                    don't want this behaviour, you could remove the mean
                    with 3dDetrend before running 3dpc.
                  * On the other hand, the effects of '-vnorm' and '-dmean'
                    and '-normalize' are not reversed in this output
                    (at least at present -- send some cookies and we'll talk).
  -prefix pname = Name for output dataset (will be a bucket type);
                  * Also, the eigen-timeseries will be in 'pname'.1D
                    (all of them) and in 'pnameNN.1D' for eigenvalue
                    #NN individually (NN=00 .. 'sss'-1, corresponding
                    to the brick index in the output dataset)
                  * The eigenvalues will be printed to file 'pname'_eig.1D
                    All eigenvalues are printed, regardless of '-pcsave'.
                    [default value of pname = 'pc']
  -1ddum ddd    = Add 'ddd' dummy lines to the top of each *.1D file.
                    These lines will have the value 999999, and can
                    be used to align the files appropriately.
                    [default value of ddd = 0]
  -verbose      = Print progress reports during the computations
  -quiet        = Don't print progress reports [the default]
  -eigonly      = Only compute eigenvalues, then
                    write them to 'pname'_eig.1D, and stop.
  -float        = Save eigen-bricks as floats
                    [default = shorts, scaled so that |max|=10000]
  -mask mset    = Use the 0 sub-brick of dataset 'mset' as a mask
                    to indicate which voxels to analyze (a sub-brick
                    selector is allowed) [default = use all voxels]

++ Compile date = Nov  5 2009




AFNI program: 3dPeriodogram
Usage: 3dPeriodogram [options] dataset
Computes the periodogram of each voxel time series.
(Squared FFT = a crude estimate of the power spectrum)

Options:
 -prefix p = use string 'p' for the prefix of the
               output dataset [DEFAULT = 'pgram']
 -taper    = fraction of data to taper [DEFAULT = 0.1]
 -nfft L   = set FFT length to 'L' points
               (longer than the data ==> zero padding)
               (shorter than the data ==> data pruning)

Notes:
* Output is in float format; number of sub-bricks will be
   half the FFT length; sub-brick #0 = FFT bin #1, etc.
* Grid spacing in the frequency (sub-brick) dimension will
   be 1/(nfft*TR) where nfft=FFT length, TR=dataset timestep.
* There is no '-mask' option.  The hyper-clever user could
   use something like
     '3dcalc( -a dset+orig -b mask+orig -expr a*b )'
   to apply a binary mask on the command line.
* Data is not scaled exactly as in the AFNI Power plugin.
* Each time series is linearly detrended prior to FFT-ization.
* FFT length defaults to be the next legal length >= input dataset.
* The program can only do FFT lengths that are factorable
   into a product of powers of 2, 3, and 5, and are even.
  + The largest power of 3 that is allowed is 3^3 = 27.
  + The largest power of 5 that is allowed is 5^3 = 125.
  + e.g., FFT of length 3*5*8=120 is possible.
  + e.g., FFT of length 4*31 =124 is not possible.
  + '-nfft' with an illegal value will cause the program to fail.
* If you want to do smaller FFTs, then average the periodograms
   (to reduce random fluctuations), you can use 3dPeriodogram in
   a script with "[...]" sub-brick selectors, then average
   the results with 3dMean.
* Or you could use the full-length FFT, then smooth that FFT
   in the frequency direction (e.g., with 3dTsmooth).
* This is a really quick hack for DH and PB and SfN.
* Author = RWCox -- who doesn't want any bribe at all for this!
                 -- http://ethics.od.nih.gov/topics/gifts.htm

++ Compile date = Nov  5 2009




AFNI program: 3dproject
Projection along cardinal axes from a 3D dataset
Usage: 3dproject [editing options]
        [-sum|-max|-amax|-smax] [-output root] [-nsize] [-mirror]
        [-RL {all | x1 x2}] [-AP {all | y1 y2}] [-IS {all | z1 z2}]
        [-ALL] dataset

Program to produce orthogonal projections from a 3D dataset.
  -sum     ==> Add the dataset voxels along the projection direction
  -max     ==> Take the maximum of the voxels [the default is -sum]
  -amax    ==> Take the absolute maximum of the voxels
  -smax    ==> Take the signed maximum of the voxels; for example,
                -max  ==> -7 and 2 go to  2 as the projected value
                -amax ==> -7 and 2 go to  7 as the projected value
                -smax ==> -7 and 2 go to -7 as the projected value
  -first x ==> Take the first value greater than x
  -nsize   ==> Scale the output images up to 'normal' sizes
               (e.g., 64x64, 128x128, or 256x256)
               This option only applies to byte or short datasets.
  -mirror  ==> The radiologists' and AFNI convention is to display
               axial and coronal images with the subject's left on
               the right of the image; the use of this option will
               mirror the axial and coronal projections so that
               left is left and right is right.

  -output root ==> Output projections will named
                   root.sag, root.cor, and root.axi
                   [the default root is 'proj']

  -RL all      ==> Project in the Right-to-Left direction along
                   all the data (produces root.sag)
  -RL x1 x2    ==> Project in the Right-to-Left direction from
                   x-coordinate x1 to x2 (mm)
                   [negative x is Right, positive x is Left]
                   [OR, you may use something like -RL 10R 20L
                        to project from x=-10 mm to x=+20 mm  ]

  -AP all      ==> Project in the Anterior-to-Posterior direction along
                   all the data (produces root.cor)
  -AP y1 y2    ==> Project in the Anterior-to-Posterior direction from
                   y-coordinate y1 to y2 (mm)
                   [negative y is Anterior, positive y is Posterior]
                   [OR, you may use something like -AP 10A 20P
                        to project from y=-10 mm to y=+20 mm  ]

  -IS all      ==> Project in the Inferior-to-Superior direction along
                   all the data (produces root.axi)
  -IS y1 y2    ==> Project in the Inferior-to-Superior direction from
                   z-coordinate z1 to z2 (mm)
                   [negative z is Inferior, positive z is Superior]
                   [OR, you may use something like -IS 10I 20S
                        to project from z=-10 mm to z=+20 mm  ]

  -ALL         ==> Equivalent to '-RL all -AP all -IS all'

* NOTE that a projection direction will not be used if the bounds aren't
   given for that direction; thus, at least one of -RL, -AP, or -IS must
   be used, or nothing will be computed!
* NOTE that in the directions transverse to the projection direction,
   all the data is used; that is, '-RL -5 5' will produce a full sagittal
   image summed over a 10 mm slice, irrespective of the -IS or -AP extents.
* NOTE that the [editing options] are the same as in 3dmerge.
   In particular, the '-1thtoin' option can be used to project the
   threshold data (if available).

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3dRank
Usage: 3dRank [-prefix PREFIX] <-input DATASET1 [DATASET2 ...]>

Replaces voxel values by their rank in the set of
values collected over all voxels in all input datasets
If you input one dataset, the output should be identical
to the -1rank option in 3dmerge

  -input DATASET1 [DATASET2 ...]: Input datasets.
                                  Acceptable data types are:
                                  byte, short, and floats.
  -prefix PREFIX: Ouput prefix.
                  If you have multiple datasets on input
                  the prefix is preceded by r00., r01., etc.
                  If no prefix is given, the default is 
                  rank.DATASET1, rank.DATASET2, etc.

                  In addition to the ranked volume, a rank map
                  1D file is created. It shows the mapping from 
                  the rank to the input dataset value 
                  The second column of this file contains the unique
                  values found in the input datasets.

  -ver = print author and version info
  -help = print this help screen

INPUT DATASET NAMES
-------------------
This program accepts datasets that are modified on input according to the
following schemes:
  'r1+orig[3..5]'                                    {sub-brick selector}
  'r1+orig<100..200>'                                {sub-range selector}
  'r1+orig[3..5]<100..200>'                          {both selectors}
  '3dcalc( -a r1+orig -b r2+orig -expr 0.5*(a+b) )'  {calculation}
For the gruesome details, see the output of 'afni -help'.

++ Compile date = Nov  5 2009




AFNI program: 3drefit
Changes some of the information inside a 3D dataset's header.
Note that this program does NOT change the .BRIK file at all;
the main purpose of 3drefit is to fix up errors made when
using to3d.
To see the current values stored in a .HEAD file, use the command
'3dinfo dataset'.  Using 3dinfo both before and after 3drefit is
a good idea to make sure the changes have been made correctly!

20 Jun 2006: 3drefit will now work on NIfTI datasets (but it will write
             out the entire dataset, into the current working directory)

Usage: 3drefit [options] dataset ...
where the options are
  -orient code    Sets the orientation of the 3D volume(s) in the .BRIK.
                  The code must be 3 letters, one each from the
                  pairs {R,L} {A,P} {I,S}.  The first letter gives
                  the orientation of the x-axis, the second the
                  orientation of the y-axis, the third the z-axis:
                     R = right-to-left         L = left-to-right
                     A = anterior-to-posterior P = posterior-to-anterior
                     I = inferior-to-superior  S = superior-to-inferior
               ** WARNING: when changing the orientation, you must be sure
                  to check the origins as well, to make sure that the volume
                  is positioned correctly in space.

  -xorigin distx  Puts the center of the edge voxel off at the given
  -yorigin disty  distance, for the given axis (x,y,z); distances in mm.
  -zorigin distz  (x=first axis, y=second axis, z=third axis).
                  Usually, only -zorigin makes sense.  Note that this
                  distance is in the direction given by the corresponding
                  letter in the -orient code.  For example, '-orient RAI'
                  would mean that '-zorigin 30' sets the center of the
                  first slice at 30 mm Inferior.  See the to3d manual
                  for more explanations of axes origins.
               ** SPECIAL CASE: you can use the string 'cen' in place of
                  a distance to force that axis to be re-centered.

  -xorigin_raw xx Puts the center of the edge voxel at the given COORDINATE
  -yorigin_raw yy rather than the given DISTANCE.  That is, these values
  -zorigin_raw zz directly replace the offsets in the dataset header,
                  without any possible sign changes.

  -duporigin cset Copies the xorigin, yorigin, and zorigin values from
                  the header of dataset 'cset'.

  -dxorigin dx    Adds distance 'dx' (or 'dy', or 'dz') to the center
  -dyorigin dy    coordinate of the edge voxel.  Can be used with the
  -dzorigin dz    values input to the 'Nudge xyz' plugin.
               ** WARNING: you can't use these options at the same
                  time you use -orient.
               ** WARNING: consider -shift_tags if dataset has tags

  -xdel dimx      Makes the size of the voxel the given dimension,
  -ydel dimy      for the given axis (x,y,z); dimensions in mm.
  -zdel dimz   ** WARNING: if you change a voxel dimension, you will
                  probably have to change the origin as well.
  -keepcen        When changing a voxel dimension with -xdel (etc.),
                  also change the corresponding origin to keep the
                  center of the dataset at the same coordinate location.
  -xyzscale fac   Scale the size of the dataset voxels by the factor 'fac'.
                  This is equivalent to using -xdel, -ydel, -zdel together.
                  -keepcen is used on the first input dataset, and then
                  any others will be shifted the same amount, to maintain
                  their alignment with the first one.
               ** WARNING: -xyzscale can't be used with any of the other
                  options that change the dataset grid coordinates!
               ** N.B.: 'fac' must be positive, and using fac=1.0 is stupid.

  -TR time        Changes the TR time to a new value (see 'to3d -help').
  -notoff         Removes the slice-dependent time-offsets.
  -Torg ttt       Set the time origin of the dataset to value 'ttt'.
                  (Time origins are set to 0 in to3d.)
               ** WARNING: These 3 options apply only to 3D+time datasets.
                   **N.B.: Using '-TR' on a dataset without a time axis
                           will add a time axis to the dataset.

  -newid          Changes the ID code of this dataset as well.

  -nowarp         Removes all warping information from dataset.

  -apar aset      Set the dataset's anatomy parent dataset to 'aset'
               ** N.B.: The anatomy parent is the dataset from which the
                  transformation from +orig to +acpc and +tlrc coordinates
                  is taken.  It is appropriate to use -apar when there is
                  more than 1 anatomical dataset in a directory that has
                  been transformed.  In this way, you can be sure that
                  AFNI will choose the correct transformation.  You would
                  use this option on all the +orig dataset that are
                  aligned with 'aset' (i.e., that were acquired in the
                  same scanning session).
               ** N.B.: Special cases of 'aset'
                   aset = NULL --> remove the anat parent info from the dataset
                   aset = SELF --> set the anat parent to be the dataset itself

  -wpar wset      Set the warp parent (the +orig version of a +tlrc dset).
                  This option is used by @auto_tlrc. Do not use it unless
                  you know what you're doing. 

  -clear_bstat    Clears the statistics (min and max) stored for each sub-brick
                  in the dataset.  This is useful if you have done something to
                  modify the contents of the .BRIK file associated with this
                  dataset.
  -redo_bstat     Re-computes the statistics for each sub-brick.  Requires
                  reading the .BRIK file, of course.  Also does -clear_bstat
                  before recomputing statistics, so that if the .BRIK read
                  fails for some reason, then you'll be left without stats.

  -statpar v ...  Changes the statistical parameters stored in this
                  dataset.  See 'to3d -help' for more details.

  -markers        Adds an empty set of AC-PC markers to the dataset,
                  if it can handle them (is anatomical, is in the +orig
                  view, and isn't 3D+time).
               ** WARNING: this will erase any markers that already exist!

  -shift_tags     Apply -dxorigin (and y and z) changes to tags.

  -dxtag dx       Add dx to the coordinates of all tags.
  -dytag dy       Add dy to the coordinates of all tags.
  -dztag dz       Add dz to the coordinates of all tags.

  -view code      Changes the 'view' to be 'code', where the string 'code'
                  is one of 'orig', 'acpc', or 'tlrc'.
               ** WARNING: The program will also change the .HEAD and .BRIK
                  filenames to match.  If the dataset filenames already
                  exist in the '+code' view, then this option will fail.
                  You will have to rename the dataset files before trying
                  to use '-view'.  If you COPY the files and then use
                  '-view', don't forget to use '-newid' as well!

  -label2 llll    Set the 'label2' field in a dataset .HEAD file to the
                  string 'llll'.  (Can be used as in AFNI window titlebars.)

  -denote         Means to remove all possibly-identifying notes from
                  the header.  This includes the History Note, other text
                  Notes, keywords, and labels.

  -deoblique      Replace transformation matrix in header with cardinal matrix.
                  This option DOES NOT deoblique the volume. To do so
                  you should use 3dWarp -deoblique. This option is not 
                  to be used unless you really know what you're doing.

  -oblique_origin
                  assume origin and orientation from oblique transformation
                  matrix rather than traditional cardinal information

  -byteorder bbb  Sets the byte order string in the header.
                  Allowable values for 'bbb' are:
                     LSB_FIRST   MSB_FIRST   NATIVE_ORDER
                  Note that this does not change the .BRIK file!
                  This is done by programs 2swap and 4swap.

  -appkey ll      Appends the string 'll' to the keyword list for the
                  whole dataset.
  -repkey ll      Replaces the keyword list for the dataset with the
                  string 'll'.
  -empkey         Destroys the keyword list for the dataset.

  -atrcopy dd nn  Copy AFNI header attribute named 'nn' from dataset 'dd'
                  into the header of the dataset(s) being modified.
                  For more information on AFNI header attributes, see
                  documentation file README.attributes. More than one
                  '-atrcopy' option can be used.
          **N.B.: This option is for those who know what they are doing!
                  Without the -saveatr option, this option is
                  meant to be used to alter attributes that are NOT
                  directly mapped into dataset internal structures, since
                  those structures are mapped back into attribute values
                  as the dataset is being written to disk.  If you want
                  to change such an attribute, you have to use the
                  corresponding 3drefit option directly or use the 
                  -saveatr option.

                  If you are confused, try to understand this: 
                  Option -atrcopy was never intended to modify AFNI-
                  specific attributes. Rather, it was meant to copy
                  user-specific attributes that had been added to some
                  dataset using -atrstring option. A cursed day came when
                  it was convenient to use -atrcopy to copy an AFNI-specific
                  attribute (BRICK_LABS to be exact) and for that to
                  take effect in the output, the option -saveatr was added.
                  Contact Daniel Glen and/or Rick Reynolds for further 
                  clarification and any other needs you may have.

                  Do NOT use -atrcopy or -atrstring with other modification
                  options.

  -atrstring n 'x' Copy the string 'x' into the dataset(s) being
                   modified, giving it the attribute name 'n'.
                   To be safe, the 'x' string should be in quotes.
          **N.B.: You can store attributes with almost any name in
                  the .HEAD file.  AFNI will ignore those it doesn't
                  know anything about.  This technique can be a way of
                  communicating information between programs.  However,
                  when most AFNI programs write a new dataset, they will
                  not preserve any such non-standard attributes.
  -atrfloat name 'values'
  -atrint name 'values'
                  Create or modify floating point or integer attributes.
                  The input values may be specified as a single string
                  in quotes or as a 1D filename or string. For example,
     3drefit -atrfloat IJK_TO_DICOM_REAL '1 0 0 0 0 1 0 0 0 0 0 1' dset+orig
     3drefit -atrfloat IJK_TO_DICOM_REAL flipZ.1D dset+orig
     3drefit -atrfloat IJK_TO_DICOM_REAL '1D:1,3@0,0,1,2@0,2@0,1,0' dset+orig
                  Almost all afni attributes can be modified in this way
  -saveatr        (default) Copy the attributes that are known to AFNI into 
                  the dset->dblk structure thereby forcing changes to known
                  attributes to be present in the output.
                  This option only makes sense with -atrcopy
          **N.B.: Don't do something like copy labels of a dataset with 
                  30 sub-bricks to one that has only 10, or vice versa.
                  This option is for those who would deservedly earn a
                  hunting license.
  -nosaveatr      Opposite of -saveatr
     Example: 
     3drefit -saveatr -atrcopy WithLabels+tlrc BRICK_LABS NeedsLabels+tlrc

  -'type'         Changes the type of data that is declared for this
                  dataset, where 'type' is chosen from the following:
       ANATOMICAL TYPES
         spgr == Spoiled GRASS             fse == Fast Spin Echo  
         epan == Echo Planar              anat == MRI Anatomy     
           ct == CT Scan                  spct == SPECT Anatomy   
          pet == PET Anatomy               mra == MR Angiography  
         bmap == B-field Map              diff == Diffusion Map   
         omri == Other MRI                abuc == Anat Bucket     
       FUNCTIONAL TYPES
          fim == Intensity                fith == Inten+Thr       
         fico == Inten+Cor                fitt == Inten+Ttest     
         fift == Inten+Ftest              fizt == Inten+Ztest     
         fict == Inten+ChiSq              fibt == Inten+Beta      
         fibn == Inten+Binom              figt == Inten+Gamma     
         fipt == Inten+Poisson            fbuc == Func-Bucket     
  -copyaux auxset Copies the 'auxiliary' data from dataset 'auxset'
                  over the auxiliary data for the dataset being
                  modified.  Auxiliary data comprises sub-brick labels,
                  keywords, and statistics codes.
                  '-copyaux' occurs BEFORE the '-sub' operations below,
                  so you can use those to alter the auxiliary data
                  that is copied from auxset.

The options below allow you to attach auxiliary data to sub-bricks
in the dataset.  Each option may be used more than once so that
multiple sub-bricks can be modified in a single run of 3drefit.

  -sublabel  n ll  Attach to sub-brick #n the label string 'll'.
  -subappkey n ll  Add to sub-brick #n the keyword string 'll'.
  -subrepkey n ll  Replace sub-brick #n's keyword string with 'll'.
  -subempkey n     Empty out sub-brick #n' keyword string

  -substatpar n type v ...
                  Attach to sub-brick #n the statistical type and
                  the auxiliary parameters given by values 'v ...',
                  where 'type' is one of the following:
         type  Description  PARAMETERS
         ----  -----------  ----------------------------------------
         fico  Cor          SAMPLES  FIT-PARAMETERS  ORT-PARAMETERS
         fitt  Ttest        DEGREES-of-FREEDOM
         fift  Ftest        NUMERATOR and DENOMINATOR DEGREES-of-FREEDOM
         fizt  Ztest        N/A
         fict  Chi