# Presentation: 570356

## AFNI Jewel BoxAKA Tool Box, Treasure Chest or Miscellaneous Tools

- There are more than 300 AFNI programs, plugins, and scripts
- Most come with help output or menus that provide a reminder about their usage; for most programs, the output of **-help** is the most up-to-date documentation. Some actually have more extensive documentation including white papers, publications and presentations available through website.

## Dataset Creation and Conversion

**to3d**			Read image files, write AFNI format datasets
**3dcopy**			Convert standard file format to AFNI or copy
- 	**3dAFNIto3D**		Convert AFNI dataset to .3D format (ASCII lists)
- 	**3dAFNItoANALYZE**	Convert AFNI dataset to ANALYZE format
- 	**3dAFNItoMINC**		Convert AFNI dataset to MINC format
**	****3dAFNItoRaw****	****	**Convert AFNI dataset to binary n-tuples from n sub-bricks
** ****	****3dAFNItoNIFTI****	****  ****	**Convert AFNI dataset to NIFTI standard
**	****3dANALYZEtoAFNI**	Convert ANALYZE format dataset to AFNI format
- 	**3dMINCtoAFNI**		Convert MINC format dataset to AFNI format
- 	**3dBRAIN_VOYAGERtoAFNI  ****	**Convert Brain Voyager vmr format dataset to AFNI format
- 	**3dCRUISEtoAFNI**		Convert JHU Cruise format dataset to AFNI format
**3dThreetoRGB**		Convert 3 scalar datasets to 1 RGB AFNI format dataset
-  	3dcalc -prefix DTIevec -a 'DTI+orig.[9..11]' -c 'DTI00+orig.[18]‘ \
- 		-expr 'c*STEP(c-  0.25)*255*ABS(a)'3dThreetoRGB -prefix DTIRGB -anat 'DTIevec+orig.[0]‘ \
-  		'DTIevec+orig.[1]' 'DTIevec+orig.[2]'
**from3d**			Write dataset slices into separate 2D slice image files
- 	from3d -prefix xxx -raw -input anat+orig
- For a single brick dataset with 256x256x41 slices outputs 41 256x256 image files that are each 131,072 bytes in length with the names xxx.001 through xxx.041

-  Discussed in other lectures
-  Discussed here

## Auxiliary Programs for Dataset Creation from Images
	Ifile			Read GE realtime EPI files and runs to3d
	Imon			Read GE realtime EPI files as they are created
Dimon			Read DICOM files as they are created, organize 				DICOM files, send to AFNI GUI in realtime.
Dimon -infile_prefix run1/image -dicom_org –GERT_reco -quit 

	rtfeedme		Send AFNI datasets to AFNI realtime plugin (afni –rt) 			and send DRIVE_AFNI commands
	plugin: RT Options	Control options for AFNI-side realtime image input 
	abut			Create zero-filled slices to put into dataset gaps

- 	**Ifile**			Read GE realtime EPI files and runs to3d
- 	**Imon**			Read GE realtime EPI files as they are created
**Dimon**			Read DICOM files as they are created, organize 				DICOM files, send to AFNI GUI in realtime.
- Dimon -infile_prefix run1/image -dicom_org –GERT_reco -quit
- 	**rtfeedme**		Send AFNI datasets to AFNI realtime plugin (afni –rt) 			and send DRIVE_AFNI commands
- 	**plugin:** **RT Options**	Control options for AFNI-side realtime image input
- 	**abut**			Create zero-filled slices to put into dataset gaps

## ccalc		Command line calculator
ccalc '3 * 4'
12.000000

ccalc -form '********\n%6.4f%%\n********' -eval '100*328/457'
********
0.7177%
********
1deval	1D calculator (like 3dcalc for 1D files)
	  Example: Calculate simple first derivative numerically for a column of numbers
1deval -a data.1D'[1]{0..98}' -b data.1D'[1]{1..99}' -expr '(b-a)/2’

- ccalc '3 * 4'
- 12.000000
- ccalc -form '********\n%6.4f%%\n********' -eval '100*328/457'
- ********
- 0.7177%
- ********
**1deval**	1D calculator (like 3dcalc for 1D files)
- 	  Example: Calculate simple first derivative numerically for a column of numbers
- 1deval -a data.1D'[1]{0..98}' -b data.1D'[1]{1..99}' -expr '(b-a)/2’

- Calculators

## 3dcalc	Voxel-by-voxel general purpose calculator for 3D datasets
Useful for combining ROI masks in various ways
Useful for forming ‘conjunction tests’, and many other voxel-wise operations
	3dcalc -prefix mask_17.2 -a stats+orig'[2]' -expr 'ispositive(a-17.2)'
	3dcalc -prefix stat_mask -a stats+orig'[2]' -b mask+orig -expr 'a*ispositive(b)'
Example: convert dataset from short (16-bit signed integer) to floating point
  3dcalc -prefix floatdata -a shortdata+orig  -datum float -expr 'a'
Example: calculate ROI statistics only on a specific slice (slice 17)
  3dROIstats -mask '3dcalc(-a func_slim+orig[0] -expr equals(k,17))'   func_slim+orig

1dmatcalc	Matrix calculator using 1D files
Useful for operations on vectors or matrices. Uses reverse polish notation stack oriented interface. Operations include matrix multiplication, addition, subtraction, pseudo-inverse, transpose, read and write.
  1dmatcalc "&read(V.1D) &read(U.1D) &transp * &write(VUT.1D)"
  1dmatcalc '&read(3cols.1D) 2 * &write(-)'

3dmatcalc	"Applies" matrix to datasets
Multiplies matrix (m x n) by a vector of n voxels through time of 3D+time dataset creating a new dataset m sub-bricks long

- Useful for combining ROI masks in various ways
- Useful for forming ‘conjunction tests’, and many other voxel-wise operations
- 	3dcalc -prefix mask_17.2 -a stats+orig'[2]' -expr 'ispositive(a-17.2)'
- 	3dcalc -prefix stat_mask -a stats+orig'[2]' -b mask+orig -expr 'a*ispositive(b)'
- Example: convert dataset from short (16-bit signed integer) to floating point
-   3dcalc -prefix floatdata -a shortdata+orig  -datum float -expr 'a'
- Example: calculate ROI statistics only on a specific slice (slice 17)
-   3dROIstats -mask '3dcalc(-a func_slim+orig[0] -expr equals(k,17))'   func_slim+orig
**1dmatcalc**	Matrix calculator using 1D files
- Useful for operations on vectors or matrices. Uses reverse polish notation stack oriented interface. Operations include matrix multiplication, addition, subtraction, pseudo-inverse, transpose, read and write.
-   1dmatcalc "&read(V.1D) &read(U.1D) &transp * &write(VUT.1D)"
-   1dmatcalc '&read(3cols.1D) 2 * &write(-)'
**3dmatcalc**	"Applies" matrix to datasets
- Multiplies matrix (m x n) by a vector of n voxels through time of 3D+time dataset creating a new dataset m sub-bricks long

## 3dcalc (continued)

Example: make right and left hemisphere masks from with aligned volumes
  3dautomask -prefix M epi+orig
  3dcalc -a M+orig -dicom -expr 'ispositive(x-3.5)' -prefix Mright
  3dcalc -a M+orig -dicom -expr 'isnegative(x-3.5)' -prefix Mleft
Example: temporal median smoothing
	3dcalc  -a fred+orig -b 'a[0,0,0,1]' -c 'a[0,0,0,-1]' -expr 'median(a,b,c)'
Example: create dataset following a 2D cosine periodic function centered around the center of each slice
	3dcalc -prefix cos0.4 -a 256blank+orig. -expr 'cos(PI * 0.4 * sqrt( (x * x)+ (y * y)) )'

- Example: make right and left hemisphere masks from with aligned volumes
-   3dautomask -prefix M epi+orig
-   3dcalc -a M+orig -dicom -expr 'ispositive(x-3.5)' -prefix Mright
-   3dcalc -a M+orig -dicom -expr 'isnegative(x-3.5)' -prefix Mleft
- Example: temporal median smoothing
- 	3dcalc  -a fred+orig -b 'a[0,0,0,1]' -c 'a[0,0,0,-1]' -expr 'median(a,b,c)'
- Example: create dataset following a 2D cosine periodic function centered around the center of each slice
- 	3dcalc -prefix cos0.4 -a 256blank+orig. -expr 'cos(PI * 0.4 * sqrt( (x * x)+ (y * y)) )'

## Simple statistics on datasets
3dTstat	Various statistics of multi-brick datasets, voxel-by-voxel, across 			sub-bricks
3dMean	Average datasets together, voxel-by-voxel, across datasets
3dLocalstat	Find simple statistical values for “neighborhoods” around 	
			each voxel
3dLocalstat -nbhd 'rect(0,0,1)' -stat min -prefix 3dgrass_minip 3dgrass_uni+orig
3dBrickStat		Return simple statistical values of voxel values (max, min, count) 			over a whole dataset (results only, useful for scripting)
3dBrickStat -slow -min -max "DT+orig[18]"
3dcalc -prefix RGB3EVA255scaled -a 'DT+orig.[9..11]' -c 'DT+orig.[18]' -expr 'c*255*ABS(a)/'`3dMax "DT+orig.[18]"`
	3dExtrema, 3dMaxima, Maxima plug-in	Find coordinates of all local maxima (or minima) across sub-bricks and return list or mask dataset for those voxels

**3dTstat**	Various statistics of multi-brick datasets, voxel-by-voxel, across 			sub-bricks
**3dMean**	Average datasets together, voxel-by-voxel, across datasets
**3dLocalstat**	Find simple statistical values for “neighborhoods” around
- 			each voxel
- 3dLocalstat -nbhd 'rect(0,0,1)' -stat min -prefix 3dgrass_minip 3dgrass_uni+orig
**3dBrickStat**		Return simple statistical values of voxel values (max, min, count) 			over a whole dataset (results only, useful for scripting)
- 3dBrickStat -slow -min -max "DT+orig[18]"
- 3dcalc -prefix RGB3EVA255scaled -a 'DT+orig.[9..11]' -c 'DT+orig.[18]' -expr 'c*255*ABS(a)/'`3dMax "DT+orig.[18]"`
**	****3dExtrema, 3dMaxima, Maxima plug-in**	Find coordinates of all local maxima (or minima) across sub-bricks and return list or mask dataset for those voxels

## 
Smoothing and filtering datasets
3dmerge	 Various spatial filters, thresholds, clustering and averaging
3dmerge -1filter_aver 8 -prefix funcFaver8 funcslim+orig
	3danisosmooth	 Anisotropical smoothing (preserves edges)
	 3danisosmooth -iters 4 -matchorig -3D -prefix anat_as -viewer anat+orig
	3dWinsor	 Nonlinear order statistics filter for spatial smoothing
    3dUniformize	 Correct for image intensity non-uniformity in anatomical datasets

- _Smoothing and filtering datasets_
**3dmerge**	 Various spatial filters, thresholds, clustering and averaging
- 3dmerge -1filter_aver 8 -prefix funcFaver8 funcslim+orig
**	****3danisosmooth**	 Anisotropical smoothing (preserves edges)
- 	 3danisosmooth -iters 4 -matchorig -3D -prefix anat_as -viewer anat+orig
- 	**3dWinsor**	 Nonlinear order statistics filter for spatial smoothing
-     **3dUniformize**	 Correct for image intensity non-uniformity in anatomical datasets

- Original

- 3dmerge -1filter_aver 8

- 3dmerge -1blur_fwhm 8

- Image Filters

## Spatial sharpening filter options

- Original Image

- 3danisosmooth

- Winsor-9 filter

- Display options

- Sharpen-4 filter

## 3danisosmooth - DWI/DT data

- Fractional Anisotropy (FA) maps (original, with added noise from DWI data, 3danisosmooth)

## 3D+time Pre-Processing Programs
3dTshift		Shift slices to a common time origin (temporal interpolation)
	3dDespike		Remove spikes from voxel time series
	3dDetrend		Remove trends from voxel time series
	3dFourier		FFT-based lowpass and highpass filtering
	3dTsmooth		Smooth time series in the time domain

**3dTshift**		Shift slices to a common time origin (temporal interpolation)
- 	**3dDespike**		Remove spikes from voxel time series
- 	**3dDetrend**		Remove trends from voxel time series
- 	**3dFourier**		FFT-based lowpass and highpass filtering
- 	**3dTsmooth**		Smooth time series in the time domain

- black - original
- red - 3dTsmooth –med
- blue - 3dFourier –highpass 0.01

## 3D+time Analysis Programs
Regression of individual datasets
3dDeconvolve	Multiple linear regression and deconvolution
			Supercedes 3dfim, 3dfim+
	plugin: DeconvolutionInteractive deconvolution
3dNLfim		Nonlinear regression
	plugins: Nlfit & Nlerr	
     square wave fit

	3dTcorrelate		Correlate two input datasets, voxel-by-voxel
	3dAutoTcorrelate	Correlate each voxel with every other voxel
	3dpc			Principal component analysis
	3ddelay 		estimate delay response between a time series and a 				reference time series

Model 1D Time Series Generators
	sqwave	Generate a square wave (on / off cycles)
waver		Generate hemodynamic responses to stimulus time series

**Regression of individual datasets**
**3dDeconvolve**	Multiple linear regression and deconvolution
- 			Supercedes 3dfim, 3dfim+
- 	**plugin:** **Deconvolution**Interactive deconvolution
**3dNLfim**		Nonlinear regression
- 	**plugins:** **Nlfit** **&** **Nlerr**
-      square wave fit
**	****3dTcorrelate**		Correlate two input datasets, voxel-by-voxel
- 	**3dAutoTcorrelate**	Correlate each voxel with every other voxel
- 	**3dpc**			Principal component analysis
- 	**3ddelay** 		estimate delay response between a time series and a 				reference time series
- _Model 1D Time Series Generators_
- 	**sqwave**	Generate a square wave (on / off cycles)
**waver**		Generate hemodynamic responses to stimulus time series

## Dataset Histogram Programs
3dAnhist	Create and plot “Anatomy” histogram of dataset, print 			peaks
	3dAnhist -h 3dgrass+orig

**3dAnhist**	Create and plot “Anatomy” histogram of dataset, print 			peaks
- 	3dAnhist -h 3dgrass+orig

## Dataset Histogram Programs
3dhistog	Create histogram of dataset to a file
   % 3dhistog -nbin 0 zork+orig#Magnitude Freq Cum_Freq0.000000 77821 778211.000000 1 778222.000000 1 778233.000000 0 778234.000000 1 77824----- 
plugin: Histogram	Interactively graphs histogram of a dataset (or ROI)

**3dhistog**	Create histogram of dataset to a file
-    % 3dhistog -nbin 0 zork+orig#Magnitude Freq Cum_Freq0.000000 77821 778211.000000 1 778222.000000 1 778233.000000 0 778234.000000 1 77824-----
**plugin:** **Histogram**	Interactively graphs histogram of a dataset (or ROI)

## ROI Generation and Usage Programs

**   ****plugin:** **Draw Dataset **Manually draw ROI mask datasets
** ****3dAutomask**	  Generate a brain-only mask from an EPI dataset
** ****3dmaskave**	  Calculate dataset values averaged over an ROI
** ****3dROIstats**	  Calculate dataset values from multiple ROIs
** ****3dmaskdump**	  Output voxel values in an ROI or a dataset
- 3dmaskdump -ibox 32 18 10 -noijk > voxelvstime.1D
- 1dtranspose voxelvstime.1D
- 1dplot voxelvstime.1D &
**  ****3dUndump**	  Input text values into a dataset (inverse of 3dmaskdump)
**  ****3dGetrow**	  Output voxel values for a row/column in x,y,z space
**  **

## ROI Generation and Usage Programs (Continued)

**  ****3dOverlap**	  Create mask that is overlap of nonzero voxels from 			   multiple datasets
**  ****3dfractionize**  Resample a mask dataset to a different resolution
** ****whereami**	  get atlas region name for coordinates (now vice-versa 		   too)
- whereami -13 68 -11 anat+tlrc
- +++++++ nearby Atlas structures +++++++
- Focus point (LPI)=
-      13 mm [R], -68 mm [P], -11 mm [I] {T-T Atlas}
-      13 mm [R], -69 mm [P], -17 mm [I] {MNI Brain}
-      14 mm [R], -77 mm [P],  -7 mm [I] {MNI Anat.}
- Atlas TT_Daemon: Talairach-Tournoux Atlas
-    Focus point: Left  Declive
-    Within 1 mm: Left  Culmen
-    Within 5 mm: Left  Lingual Gyrus
-           -AND- Left  Brodmann area 18
-    Within 6 mm: Left  Brodmann area 19
-    Within 7 mm: Left  Fusiform Gyrus

## 3dinfo		Print out information from the header
Example from command line: 3dinfo astrip+orig
Example from afni GUI: Define Datamode  Misc  Anat Info
	Dataset File:    astrip+orig
	Identifier Code: XYZ_8qmBAapL9YwE3I Creation Date: Wed Jun 9 11:54:12 2004
	Dataset Type:    Spoiled GRASS (-spgr)
	Byte Order: 	   MSB_FIRST [this CPU native = LSB_FIRST]
	Data Axes Orientation:
		first  (x) = Anterior-to-Posterior
		second (y) = Superior-to-Inferior
		third  (z) = Left-to-Right   [-orient ASL]
	R-to-L extent:   -74.000 [R] -to-   73.600 [L] -step-   1.200 mm[124 voxels]
	A-to-P extent:  -119.531 [A] -to-  119.531 [P] -step-   0.938 mm[256 voxels]
	I-to-S extent:  -119.531 [I] -to-  119.531 [S] -step-   0.938 mm[256 voxels]
	R-to-L center:    -0.200 [R]
	A-to-P center:     0.000 [P]
	I-to-S center:    -0.000 [I]
	Number of values stored at each pixel = 1
		-- At sub-brick #0 ‘#0’ datum type is short:	    0 to		733

	---HISTORY---
	[cox@elrond: Mon Jun 14 16:04:31 2004] 3dIntracranial -min_val 30 
  		-anat fred+orig -prefix astrip

- Example from command line: **3dinfo astrip+orig**
- Example from afni GUI: **Define Datamode ******** Misc ******** Anat Info**
- 	**Dataset File:    astrip+orig**
**	****Identifier Code: XYZ_8qmBAapL9YwE3I Creation Date: Wed Jun 9 11:54:12 2004**
**	****Dataset Type:    Spoiled GRASS (-spgr)**
**	****Byte Order: ****	****   MSB_FIRST [this CPU native = LSB_FIRST]**
**	****Data Axes Orientation:**
**	****	****first  (x) = Anterior-to-Posterior**
**	****	****second (y) = Superior-to-Inferior**
**	****	****third  (z) = Left-to-Right   [-orient ASL]**
**	****R-to-L extent:   -74.000 [R] -to-   73.600 [L] -step-   1.200 mm[124 voxels]**
**	****A-to-P extent:  -119.531 [A] -to-  119.531 [P] -step-   0.938 mm[256 voxels]**
**	****I-to-S extent:  -119.531 [I] -to-  119.531 [S] -step-   0.938 mm[256 voxels]**
**	****R-to-L center:    -0.200 [R]**
**	****A-to-P center:     0.000 [P]**
**	****I-to-S center:    -0.000 [I]**
**	****Number of values stored at each pixel = 1**
**	****	****-- At sub-brick #0 ‘#0’ datum type is short:****	****    0 to****	****	****733**
**	****---HISTORY---**
**	****[cox@elrond: Mon Jun 14 16:04:31 2004] 3dIntracranial -min_val 30 **
**  ****	****	****-anat fred+orig -prefix astrip**

- Dataset File Utilities

## Dataset File Utilities (continued)

**3dAttribute**		Print out a single or all header attributes
- 3dAttribute -name ORIGIN epi_r1+orig
-  ORIGIN = 118.125 118.125 -69
- 3dAttribute -name BRICK_STATS 3dgrass_uni+orig.
-  BRICK_STATS = 0 4480
- 	**3dnewid**		Assign a new ID code to a dataset
**3drefit**		Lets you change attributes in a dataset header
-   	   Example: change orientation code and location of origin
**	****  ****3drefit -orient LPI -zorigin 30 fred+orig**
- 	   Example: anonymize dataset
**	****  ****3drefit -denote fred+orig**
- 	**3dNotes**		Lets you put text notes into a dataset header
- 	**plugin**: **Dataset NOTES  **Interactive header notes editor
- 	**nifti_tool**		Displays, modifies, copies nifti structures in datasets

## Programs for Changing Dataset Spatial Structure
	3daxialize	Rewrite dataset with slices in different direction
	3dresample	Rewrite dataset in new orientation, with new voxel size
	3dLRflip	Flip dataset Left to Right
Programs for Assembling Sub-bricks into 4D Datasets
3dTcat	Assemble a 3D+time dataset from multiple input sub-bricks
	3dbucket	Assemble a bucket dataset from multiple input sub-bricks
Programs for Changing Slice Structure
	3dZcat	Glue multiple sub-bricks together along the z-axis
	3dZcutup	Cut slices out of a dataset to make a ‘thinner’ dataset
	3dZeropad	Add zero slices around the edges of a dataset
Can also cut planes off edges of dataset to deal with a smaller dataset
3dZeropad -R 4 -L 6 -I 2 -S 3 -prefix fred_pad  fred+orig
	3dZregrid	Interpolate a dataset to a different slice thickness

- 	**3daxialize**	Rewrite dataset with slices in different direction
- 	**3dresample**	Rewrite dataset in new orientation, with new voxel size
- 	**3dLRflip**	Flip dataset Left to Right
- _Programs for Assembling Sub-bricks into 4D Datasets_
**3dTcat**	Assemble a 3D+time dataset from multiple input sub-bricks
- 	**3dbucket**	Assemble a bucket dataset from multiple input sub-bricks
- _Programs for Changing Slice Structure_
**	****3dZcat**	Glue multiple sub-bricks together along the z-axis
- 	**3dZcutup**	Cut slices out of a dataset to make a ‘thinner’ dataset
- 	**3dZeropad**	Add zero slices around the edges of a dataset
- Can also cut planes off edges of dataset to deal with a smaller dataset
**3dZeropad -R 4 -L 6 -I 2 -S 3 -prefix fred_pad  fred+orig**
- 	**3dZregrid**	Interpolate a dataset to a different slice thickness

## Spatial Transformations of Dataset Geometry
	3drotate		Rigid body rotation of dataset in 3D
	3dWarp		Non-rigid transformation of 3D coordinates
	3dAnatNudge		Try to align EPI and structural volumes automatically
	plugin: Nudge Dataset Align EPI and structural volumes manually
	3dTagalign		Align datasets by matching manually placed ‘tags’
	plugin: Edit Tagset	Place ‘tags’ in a dataset interactively
adwarp		Transform dataset using warp from dataset header
	Vecwarp		Transform 3-vectors using warp from dataset header
Dataset File Manipulation
	3dcopy		Copy a dataset to make new files
	3drename		Rename dataset files
	3ddup		Make an ‘empty’ duplicate (warp-on-demand) of 
				a dataset

- 	**3drotate**		Rigid body rotation of dataset in 3D
- 	**3dWarp**		Non-rigid transformation of 3D coordinates
- 	**3dAnatNudge**		Try to align EPI and structural volumes automatically
- 	**plugin****:** **Nudge Dataset **Align EPI and structural volumes manually
- 	**3dTagalign**		Align datasets by matching manually placed ‘tags’
- 	**plugin****:** **Edit Tagset**	Place ‘tags’ in a dataset interactively
**adwarp**		Transform dataset using warp from dataset header
- 	**Vecwarp**		Transform 3-vectors using warp from dataset header
- _Dataset File Manipulation_
- 	**3dcopy**		Copy a dataset to make new files
- 	**3drename**		Rename dataset files
- 	**3ddup**		Make an ‘empty’ duplicate (warp-on-demand) of
- 				a dataset

## Volume Segmentation Tools

**3dIntracranial** -- Strip the scalp and other non-brain tissue from a high-resolution T1-weighted dataset
**3dIntracranial -anat fred+orig -prefix fred_strip**
**3dSkullStrip** -- Improves upon 3dIntracranial, creates a brain-only mask
**3dSkullStrip -input fred_anat+orig -prefix fred_strip \**
**-no_avoid_eyes -niter 750 -ld 50**
- Also GyrusFinder plug-in, 3dAnhist, 3dClipLevel, 3dAutomask, 3dclust, 3dmerge, 3dUniformize

##  Computation of Various Numbers from Datasets

** ****3ddot**		Dot product (correlation coefficient) of 2 sub-bricks
** ****3dclust**	Find connected clusters of nonzero voxels
**3dFWHM**	Estimate Full Width Half Max of dataset spatial 			correlation
- _ __Simulated Dataset Generators_
** ****3dTSgen**	Generate 3D+time dataset from 1D model and noise
** ****AlphaSim**	Simulate datasets and estimate statistical power
-   		(Monte Carlo multiple comparison correction)
** ****3dConvolve**	Simulate datasets via convolution
** ****3dInvFMRI**	Compute stimulus time series given activation map
- 		and 3D+time dataset
- _ __Programs for Dealing with 1D Time Series_
** ****1dcat**		Concatenate columns from multiple 1D files row by row
-   **1dplot**	Graph the columns as the y-values in a graph
** ****1dtranspose**	Transpose (interchange) rows and columns

## Spatial Utilities

_**3dclust**_ -- Find clusters of “active” voxels and print out a report about them
- “Active” means nonzero (survives thresholding operation)
- Clusters are defined by a connectivity radius parameter **rmm**:

- Clustering starts by finding some nonzero voxel
- All nonzero voxels closer than **rmm** millimeters (center-to-center distance) to the given voxel are included in the cluster
- Cluster then grows outwards from all newly included voxels, using rmm again

- rmm = 1.01 mm
- clusters nearest neighbors

- rmm = 1.415 mm (1.734 -3D)
- clusters next nearest neighbors

- rmm = 2.01 mm
- clusters 2nd next nearest neighbors

- 1 mm voxels

- Clustering actually takes place in 3D

## Clustering actually takes place in 3D:
Assume cubical voxels with grid size L mm
       L  <  rmm  <        L    connect voxels that share a common face
       L  <  rmm  <        L    connect voxels that share a common edge
       L  <  rmm  <      2L    connect voxels that share a corner
Larger values of rmm will jump over zero voxels
You can override actual voxel size (which may not be cubical) by using the  -dxyz=1 command line switch, which then pretends that voxel size L=1
Sample report: 3dclust -1thresh 0.47 7 600 fred_epi+orig

Cluster report for file fred_epi+orig
[Connectivity radius 	= 7.00 mm Volume threshold = 600.00 ]
[Single voxel volume 	= 98.4 (microliters) ]
[Voxel datum type	= short ]
[Voxel dimensions 	= 3.750 mm x 3.750 mm x 7.000 mm ]
Mean and SEM based on Absolute Value of voxel intensities:

-1thresh 0.47=threshold to apply to dataset; 7 = rmm; 600 = volume of smallest cluster to report (in mm3 = microliters)

- Assume cubical voxels with grid size L mm
-        L  <  **rmm**  <        L    connect voxels that share a common face
-        L  <  **rmm**  <        L    connect voxels that share a common edge
-        L  <  **rmm**  <      2L    connect voxels that share a corner
- Larger values of **rmm** will jump over zero voxels
- You can override actual voxel size (which may not be cubical) by using the  **-dxyz=1** command line switch, which then pretends that voxel size L=1
- Sample report: **3dclust -1thresh 0.47 7 600 fred_epi+orig**
**Cluster report for file fred_epi+orig**
**[Connectivity radius ****	****= 7.00 mm Volume threshold = 600.00 ]**
**[Single voxel volume ****	****= 98.4 (microliters) ]**
**[Voxel datum type****	****= short ]**
**[Voxel dimensions ****	****= 3.750 mm x 3.750 mm x 7.000 mm ]**
**Mean and SEM based on Absolute Value of voxel intensities:**
**-1thresh 0.47**=threshold to apply to dataset; **7** = **rmm**; **600** = volume of smallest cluster to report (in mm3 = microliters)

## Image Registration Programs
3dvolreg		Volumetric registration (rigid body in 3D)
	3dWarpDrive		Extension of 3dvolreg to include warping
	3dImReg		Slice-by-slice registration (rigid body in 2D)

Miscellaneous File Manipulations
	2swap			Byte pair swap: ab    ba
	4swap			Byte quad swap: abcd    dcba
	24swap		Mixed 2 and 4 byte swaps in same file
	strblast		Find a string in a file and replace it with junk (anonymize)
	byteorder		Report the byteorder of the current CPU

Miscellaneous Utilities
	byteorder		Report the byteorder of the current CPU
	cdf			Compute probabilities, thresholds for standard distributions
	count			Generate numbered strings for command line scripts
Image File Header Printouts
	dicom_hdr		Print information from a DICOM file
	ge_header		Print information from a GE I. file
	mayo_analyze		Print information from an ANALYZE .hdr file
	siemens_vision	Print information from a Siemens Vision .ima file

**3dvolreg**		Volumetric registration (rigid body in 3D)
- 	**3dWarpDrive**		Extension of 3dvolreg to include warping
- 	**3dImReg**		Slice-by-slice registration (rigid body in 2D)
- _Miscellaneous File Manipulations_
- 	**2swap**			Byte pair swap: ab    ba
- 	**4swap****	**		Byte quad swap: abcd    dcba
- 	**24swap**		Mixed 2 and 4 byte swaps in same file
**	****strblast**		Find a string in a file and replace it with junk (anonymize)
**	****byteorder**		Report the byteorder of the current CPU
- _Miscellaneous Utilities_
**	****byteorder**		Report the byteorder of the current CPU
**	****cdf****	**		Compute probabilities, thresholds for standard distributions
- 	**count****	**		Generate numbered strings for command line scripts
- _Image File Header Printouts_
- 	**dicom_hdr**		Print information from a DICOM file
- 	**ge_header**		Print information from a GE I. file
- 	**mayo_analyze**		Print information from an ANALYZE .hdr file
- 	**siemens_vision**	Print information from a Siemens Vision .ima file

## Miscellaneous Visualization Tools
aiv			AFNI Image Viewer program
aiv ~/abin/splash_earth.jpg &

plugin: Render[new]	Interactive volume rendering
plugin: Dataset#N	Graph extra dataset time series in AFNI graph viewer

**aiv****	**		AFNI Image Viewer program
- aiv ~/abin/splash_earth.jpg &
- plugin: **Render[new]**	Interactive volume rendering
- plugin: **Dataset#N**	Graph extra dataset time series in AFNI graph viewer

## Group Dataset Statistical Analysis Programs

- 	**3dttest**		Paired and unpaired t-tests
- 	**3dANOVA**		1-way ANOVA (fixed effects)
- 	**3dANOVA2**		2-way ANOVA (fixed, random, mixed effects)
- 	**3dANOVA3**		3-way ANOVA (fixed, random, mixed effects)
- 	**GroupAna**		n-way ANOVA - 1 to 5 ways (Matlab script)
- 	**3dFriedman**		Nonparametric Friedman test for randomized complete 				block design experiments
- 	**3dKruskalWallis**	Nonparametric Kruskal-Wallis test for comparison of multiple 			treatments
- 	**3dWilcoxon**		Nonparametric Wilcoxon test signed-rank test for paired 				comparisons of two samples
- 	**3dMannWhitney****	****	**Nonparametric 3dMannWhitney two-sample test
- 	**3dRegAna**		Voxel-wise multiple linear regression group analysis
- 	**3dFDR**			False Discovery Rate analysis for thresholding of voxelwise 				statistics
- 	**AlphaSim**		Alpha probability simulations for Monte Carlo analysis
- 				of clusters

## Diffusion Tensor Imaging (DTI) Programs

_**3dDWItoDT**_ -- For diffusion weighted image (DWI) data, calculate the diffusion tensor image (DTI) data.
- Uses traditional linear or an iterative non-linear method to compute diffusion tensor.  Computes eigenvalues, eigenvectors, fractional anisotropy, mean diffusivity
_**3dTeig**_ -- From DTI data compute eigenvalues, eigenvectors and fractional anisotropy.
_**3dDTtoDWI**_ -- Compute diffusion weighted volumes based on the diffusion tensor and an ideal B0 volume with no gradient.
- Useful for testing purposes only.
_**DTIStudioFibertoSegments**_ -- Takes output of fiber tracking from DTIStudio.
- Popular DTI program from Johns Hopkins.  Output can be displayed in SUMA.

- FA - non-linear

- DWI

- DWI q1

- Dxx

- 1

- fibers

## Scripts

- @SUMA_Make_Spec_FS – convert Freesurfer surfaces to SUMA spec files
- @SUMA_Make_Spec_SF – convert SureFit surfaces to SUMA spec files
- @auto_tlrc – automatic transformation of dataset to match Talairach template
- @CommandGlobb – execute AFNI commands for multiple datasets
- @make_stim_file – make stim file for 3dDeconvolve from user input or file
- @2dwarper – sample script to align slices of a time series dataset
- @GetAfniOrient – return orientation code for a dataset (e.g. RAI)
- @UpdateAfni – sample script for updates (also AFNI_UPDATER)

## Scripts (continued)

- @4Daverage – sample script for calculating means of multiple datasets
- @GetAfniPrefix  - pull the prefix part of the name out of dataset
- @VolCenter –return the center coordinate of a dataset
- @AfniOrient2RAImap –return index map of the RAI directions
- @GetAfniView – return view part of name of dataset
- @align_partial_oblique – align a partial T1 dataset with a full dataset
- @AfniOrientSign – code for orientation relative to RAI (1 1 1);
- 			 LPS (-1 -1 -1)
- @NoExt – remove specified file extensions from end of filename
- @Align_Centers - align centers of dataset(s) to a base dataset
- @Purify_1D – extract columns from 1D files

## Scripts (continued)

- @Center_Distance – return distance between two centers
- @RenamePanga – create AFNI datasets from GE realtime data
- @clip_volume – crop or zero out parts of a volume
- @CheckForAfniDset – check for existence of AFNI datasets
- @SUMA_AlignToExperiment – align anatomical volume to experimental volume
- @fix_FSsphere – fix Freesurfer spherical surface
- @DTI_studio_reposition – match DTIStudio analyze file format to parent AFNI dataset
- @parse_afni_name – return the path, prefix, view and sub-brick selection from dataset name
- @parse_name – return path, prefix and extension from any file name
- @FromRAI  - return equivalent other coordinates (e.g. LPS) given RAI coordinates
- @ToRAI – return equivalent RAI coordinates

## Plug-ins

## GyrusFinder

- Semi-automatic white/gray segmentation plug-in

- Use blank copy (Dataset copy). Also set See OverLay.
- Start Gyrus finder plug-in, and choose copy dataset
- Set fill point in white matter (middle button)
- Suggest range in white/gray finder window
- Select Fill
- Unfill and adjust search range, neighbor and connection constraints
- Do gray matter Fill
- Save data

## ScatterPlot plug-in

## Environment Variables and .afnirc

- Operation of AFNI is affected by many Unix environment variables
- Full documentation is in file _README.environment_ (in AFNI distributions)
- Environment variables can be set in your shell startup file (e.g., .cshrc) or in AFNI’s startup file (.afnirc), in your home directory
- Some environment variables can be set from the pseudo-plugin
- 	_**Define Datamode **__****__** Misc **__****__** Edit Environment**_
*Some* useful environment variables (there are many more)
**AFNI_PLUGINPATH** gives the directory where AFNI will look for plugins when it starts up
**AFNI_SESSTRAIL** gives the number of directory levels to show in the         Switch Session chooser
**AFNI_HINTS** can be used to turn off the popup hints (tooltips)
**AFNI_COMPRESSOR** can be used to tell AFNI programs to compress .BRIK files when they are written out
**AFNI_AUTOGZIP** can be used to tell AFNI programs to gzip compress .BRIK files if they appear like “good” candidates for compression (e.g., ROI datasets)

## AFNI_LEFT_IS_LEFT can be used to have axial and coronal images displayed with the subject’s left on the display left (default is subject’s left on the display right: radiological order) 
AFNI_ALWAYS_LOCK can be used to turn on inter-controller Lock at startup
AFNI_NOSPLASH can be used to hide the AFNI splash window (but why?!)
AFNI_ENFORCE_ASPECT can be used to make defective window managers (KDE, Gnome) keep the image window aspect ratios when resizing (I then also recommend setting the window manager so that it doesn’t redraw the windows during resizing operations)
Sample .afnirc file:

See README.environment and README.setup for details on all environment variables and other setup issues

**AFNI_ALWAYS_LOCK** can be used to turn on inter-controller Lock at startup
**AFNI_NOSPLASH** can be used to hide the AFNI splash window (but why?!)
**AFNI_ENFORCE_ASPECT** can be used to make defective window managers (KDE, Gnome) keep the image window aspect ratios when resizing (I then also recommend setting the window manager so that it doesn’t redraw the windows during resizing operations)
- Sample .afnirc file:
- See _README.environment_ and _README.setup_ for details on all environment variables and other setup issues

## AFNI GUI Plugouts and command line options

**AFNI GUI Plugouts and command line options**

- #!/bin/tcsh
- # '.afni.startup_script' in current directory.
- # AFNI will automatically read such a file at
- # startup and carry out its orders.
- # ---------------------------------------
- # Sample script to generate image file
- # sss.jpg from the anat+tlrc and func+tlrc
- # datasets. See file README.driver for a list
- # of all the functions you can invoke to drive
- # AFNI from the outside. See file
- # README.environment for other settings that
- # can influence the way AFNI operates.
- # Set environment variables to force square
- # pixels in saved image, and linear
- # interpolation in the functional overlay
- # volumes
- setenv AFNI_IMAGE_SAVESQUARE YES
- setenv AFNI_resam_func Li
- setenv AFNI_resam_thr Li

- Or ...
- afni -com 'OPEN_WINDOW A.axialimage' \
- -com 'SWITCH_UNDERLAY A.fred' \
- -com 'SET_VIEW A.tlrc' \
- somedirectory

- # Start AFNI with plugouts enabled
- afni -yesplugouts &
- # Give AFNI 4 seconds to get started
- sleep 4
- # Drive AFNI to set up the desired
- # image, save it, then quit
- plugout_drive -verb -host localhost \
- -com "SWITCH_UNDERLAY A.anat" \
- -com "SWITCH_OVERLAY A.func" \
- -com "SET_VIEW A.tlrc" \
- -com "OPEN_WINDOW A.axialimage \
-     mont=5x5:5:2:green" \
- -com "SET_DICOM_XYZ A.0 0 0" \
- -com "SET_XHAIRS A.OFF" \
- -com "SET_FUNC_RANGE A.777" \
- -com "SET_THRESHNEW A.0.666 *" \
- -com "SET_PBAR_NUMBER A.9" \
- -com "SET_FUNC_VISIBLE A.+" \
- -com "SAVE_JPEG A.axialimage sss.jpg" \
- -com "QUIT"

## Matlab Library

- _Opening and Saving AFNI datasets_
- BrikInfo
- BrikLoad
- WriteBrik
- _Functions that deal with voxel coordinates_
- AFNI_XYZcontinuous2Index
- AFNI_Index2XYZcontinuous
- AFNI_CoordChange
- _Functions that deal with extracting and selecting slices a la AFNI_
- GetAfniSlice
- GetAfniSliceTriplet

## ACE Exam

-    1. Explain the difference between 'Min-to-Max' and '2%-to-98%' in the AFNI image viewer. Why is 2%-to-98% the default?
-    2. What does the 'R' key do when typed into an AFNI image viewer window? What about in a graph viewer window?
-    3. On some systems, it is possible to drag an image viewer window so that its aspect ratio (height/width) is not preserved; in this situation, the image becomes distorted. Describe at least 2 ways to bring the image viewer quickly back into the correct aspect ratio.
-    4. What does the 'Project' menu button do in the AFNI image viewer Disp control panel?
-    5. When you have 2 (or more) AFNI controllers open, can you lock their threshold sliders so that they move together? If so, how?
-    6. In an AFNI graph viewer window, how can you get a display of the time series that is the average of all the sub-graphs currently being shown?
-    7. Suppose you are showing a time series graph of a very long 3D+time dataset, and want to only see the points between time indexes 200..400 displayed in the graphs. How can you do this?
-    8. Explain the 3 different baseline modes available in an AFNI graph viewer.
-    9. On most systems, the AFNI interface shows the cursor as an arrow pointing to the upper left, but this arrow changes shape and color slightly when you move it over certain controls. What does this cursor shape change mean?
-   10. Given a list of coordinates, describe one way to create an AFNI dataset that equals 1 at each point inside a sphere of radius 5 about each coordinate in the list, and equals zero at all other points.
-   11. Explain why it is better to use the 3dcopy program to make a copy of an AFNI dataset (.HEAD and .BRIK files) rather than use the Unix 'cp' command twice.
-   12. How do you get AFNI '3d' programs to treat a .1D file with a single column of numbers as a 1-voxel 3D+time dataset?
-   13. How do you get AFNI to automatically compress output .BRIK files with gzip?