Learn R Programming

ANTsR

and check the new vignette and manual

An R package providing ANTs features in R.

Current Authors and Contributors: Brian B. Avants, Benjamin M. Kandel, Jeff T. Duda, Philip A. Cook, Nicholas J. Tustison

Original Authors: Shrinidhi KL, Brian B. Avants

Easiest installation approach (from within R)

library( devtools )
install_github("stnava/cmaker")
install_github("stnava/ITKR")
install_github("stnava/ANTsR")

this assumes you have git installed / accessible in your environment, as well as a compiler, preferably clang.

windows users should see Rtools and maybe, also, installr for assistance in setting up their environment for building (must have a compiler too)

ANTsR manual and releases

Releases are new so let us know of any issues ...

Installation from source

First, clone the repository:

$ git clone https://github.com/stnava/ITKR.git
$ git clone https://github.com/stnava/ANTsR.git

Install the package as follows:

$ R CMD INSTALL ITKR
$ R CMD INSTALL ANTsR

R dependencies

You may need to install R packages that ANTsR requires. For example:

install.packages(pkgs = c("Rcpp", "tools", "methods"), dependencies = TRUE);

These dependencies are subject to change until development is stable. You can gain additional functionality by installing packages that are listed in the DESCRIPTION file under Suggests.

The travis.yml file also shows a way to install from Linux command line.

Usage

Load the package:

library(ANTsR)

List the available functions in the namespace ANTsR:

ANTsR::<double-tab>

Call help on a function via ?functionName or see function arguments via args(functionName)

Overview of ANTsR functionality and useful tools

If nothing else, ANTsR makes it easy to read and write medical images and to map them into a format compatible with R.

Read, write, access an image

mnifilename<-getANTsRData("mni")
img<-antsImageRead(mnifilename)
antsImageWrite(img,mnifilename)
antsGetSpacing(img)
antsGetDirection(img)
antsGetOrigin(img)
print(antsGetPixels(img,50,60,44))
print(max(img))

Index an image with a label

gaussimg<-array( data=rnorm(125), dim=c(5,5,5))
arrayimg<-array( data=(1:125), dim=c(5,5,5))
img<-as.antsImage( arrayimg )
print( max(img) )
print( mean(img[ img > 50  ]))
print( max(img[ img >= 50 & img <= 99  ]))
print( mean( gaussimg[ img >= 50 & img <= 99  ]) )

Convert a 4D image to a matrix

gaussimg<-array( data=rnorm(125*10), dim=c(5,5,5,10))
gaussimg<-as.antsImage(gaussimg)
print(dim(gaussimg))
mask<-getAverageOfTimeSeries( gaussimg )
voxelselect <- mask < 0
mask[ voxelselect  ]<-0
mask[ !voxelselect  ]<-1
gmat<-timeseries2matrix( gaussimg, mask )
print(dim(gmat))

Convert a list of images to a matrix

nimages<-100
ilist<-list()
for ( i in 1:nimages )
{
  simimg<-makeImage( c(50,50) , rnorm(2500) )
  simimg<-smoothImage(simimg,1.5)
  ilist[i]<-simimg
}
# get a mask from the first image
mask<-getMask( ilist[[1]],
  lowThresh=mean(ilist[[1]]), cleanup=TRUE )
mat<-imageListToMatrix( ilist, mask )
print(dim(mat))

Do fast statistics on a big matrix

Once we have a matrix representation of our population, we might run a quick voxel-wise regression within the mask.
Then we look at some summary statistics.

mat<-imageListToMatrix( ilist, mask )
age<-rnorm( nrow(mat) ) # simulated age
gender<-rep( c("F","M"), nrow(mat)/2 ) # simulated gender
# this creates "real" but noisy effects to detect
mat<-mat*(age^2+rnorm(nrow(mat)))
mdl<-lm( mat ~ age + gender )
mdli<-bigLMStats( mdl, 1.e-4 )
print(names(mdli))
print(rownames(mdli$beta.t))
print(paste("age",min(p.adjust(mdli$beta.pval[1,]))))
print(paste("gen",min(p.adjust(mdli$beta.pval[2,]))))

Write out a statistical map

We might also write out the images so that we can save them for later or look at them with other software.

agebetas<-makeImage( mask , mdli$beta.t[1,] )
antsImageWrite( agebetas, tempfile(fileext ='.nii.gz') )

Neighborhood operations

Images neighborhoods contain rich shape and texture information.
We can extract neighborhoods for further analysis at a given scale.

mnit<-getANTsRData("mni")
mnit<-antsImageRead(mnit)
mnit <- resampleImage( mnit , rep(4, mnit@dimension) )
mask2<-getMask(mnit,lowThresh=mean(mnit),cleanup=TRUE)
radius <- rep(2,mnit@dimension)
mat2<-getNeighborhoodMatrix(mnit, mask2, radius,
  physical.coordinates = FALSE,
  boundary.condition = "mean" )

The boundary.condition says how to treat data that is outside of the mask or the image boundaries. Here, we replace this data with the mean in-mask value of the local neighborhood.

Eigenanatomy & SCCAN

Images often have many voxels ($p$-voxels) and, in medical applications, this means that $p>n$ or even $p>>n$, where $n$ is the number of subjects. Therefore, we often want to "intelligently" reduce the dimensionality of the data. However, we want to retain spatial locality. This is the point of "eigenanatomy" which is a variation of sparse PCA that uses (optionally) biologically-motivated smoothness, locality or sparsity constraints.

# assume you ran the population example above
eanat<-sparseDecom( mat, mask, 0.2, 5, cthresh=2, its=2 )
eseg<-eigSeg(mask,eanat$eig,F)
jeanat<-joinEigenanatomy(mat,mask,eanat$eig, c(0.1))
eseg2<-eigSeg(mask,jeanat$fusedlist,F)

The parameters for the example above are set for fast processing. You can see our paper for some theory on these methods[@Kandel2014a].

More information is available within the examples that can be seen within the help for sparseDecom, sparseDecom2 and the helper function initializeEigenanatomy. You might also see the sccan tutorial.

Other useful tools

?iMath
?ThresholdImage
?quantifyCBF
?antsPreprocessfMRI
?aslPerfusion
?computeDVARS
?getROIValues
?hemodynamicRF
?inspectImageData3D
?makeGraph
?matrixToImages
?antsRegistration
?plotPrettyGraph
?plotBasicNetwork
?getTemplateCoordinates
?antsSet*

Parts of ImageMath from ANTs are accessible via

?iMath

for more fMRI focused tools, see RKRNS and its github site github RKRNS.

A good visualization alternative is antsSurf.

Direct access to ANTs tools

Alternatively, one can use any function in the namespace by providing arguments exactly same as one provides to the corresponding command-line version.

For example, to call the antsRegistration routine:

ANTsR::antsRegistration( "-d", "2", "-m", "mi[r16slice.nii.gz,r64slice.nii.gz,1,20,Regular,0.05]", "-t", "affine[1.0]", "-c", "2100x1200x1200x0", "-s", "3x2x1x0", "-f", "4x3x2x1","-u", "1", "-o", "[xtest,xtest.nii.gz,xtest_inv.nii.gz]" )

ANTsR::antsRegistration( "-d", "2", "-m", "mi[r16slice.nii.gz,r64slice.nii.gz,1,20,Regular,0.05]", "-t", "affine[1.0]", "-c", "2100x1200x1200x0", "-s", "3x2x1x0", "-f", "4x3x2x1", "-m", "cc[r16slice.nii.gz,r64slice.nii.gz,1,4]", "-t", "syn[5.0,3,0.0]", "-i", "100x100x0", "-s", "2x1x0", "-f", "3x2x1", "-u", "1", "-o", "[xtest,xtest.nii.gz,xtest_inv.nii.gz]" )

Research using ANTsR

Inter-modality inference yet to be added RIPMMARC

Eigenanatomy for multiple modality population studies function sparseDecom

Tumor segmentation function mrvnrfs (not exactly the same but close)

Multiple modality pediatric template and population study employs several aspects of ANTsR

Structural networks from subject-level data function makeGraph plus yet to be added RIPMMARC

SCCAN relating neuroimaging and cognitive batteries function sparseDecom2

Sparse regression with manifold smoothness constraints function sparseRegression

Prior-based eigenanatomy function sparseDecom

Copy Link

Version

Version

1.0

License

GPL (>=2)

Maintainer

Brian Avants

Last Published

August 23rd, 2020

Functions in ANTsR (1.0)

abpN4

MR image bias correction based on the N4 algorithm.
affineInitializer

a multi-start optimizer for affine registration
mean,antsImage-method

arith.antsImage
antsImageClone

Image Clone
antsMotionCalculation

Correct 4D time-series data for motion.
antsRegistration

A simplified (or full) interface to antsRegistration.
antsImagePhysicalSpaceConsistency

Check for physical space consistency
antsImageRead

Image Read
antsrimpute

Impute NA's on data frame.
antsImageHeaderInfo

Read file info from image header
antsMotionCorr

Motion Correction
antsImageGetSet

antsImageGetSet
antsImageMutualInformation

mutual information between two images
antsImageWrite

Image Write
antsSetPixels

Set a pixel value at an index
aslDenoiseR

WIP: data-driven denoising for ASL MRI
aslPerfusion

ASL-based Perfusion from PASL, CASL or pCASL.
antsTransformIndexToPhysicalPoint

Get Spatial Point from Index
[,antsImage,NULL,ANY-method

as.antsImage
antsTransformPhysicalPointToIndex

Get Index from Spatial Point
antsSpatialICAfMRI

Perform spatial ICA on fMRI bold data.
aslOutlierRejection

Pair-wise subtraction based outlier rejection.
atropos

FMM Segmentation
as.antsMatrix

as.antsMatrix
combineNuisancePredictors

Combine and reduce dimensionality of nuisance predictors.
clusterTimeSeries

Split time series image into k distinct images
bigLMStats

Efficiently compute basic statistical inference from regressions with multiple outcomes
bayesianlm

Simple bayesian regression function.
computeDVARS

computeDVARS
compcor

Simple compcor function.
basicInPaint

Inpaints missing imaging data from boundary data
bayesianCBF

Uses probabilistic segmentation to constrain pcasl-based cbf computation.
blockStimulus

Block stimulus model for FMRI Data
bold_correlation_matrix

bold_correlation_matrix
crossvalidatedR2

Cross-Validated R^2 value
createJacobianDeterminantImage

createJacobianDeterminantImage
DesikanKillianyTourville

DesikanKillianyTourville
eigSeg

Segmentation for eigenanatomy.
cropImage

crop a sub-image via a mask
cropIndices

crop a sub-image by image indices
convolveImage

convolve one image with another
corw

produces a correlation matrix via weighted correlation.
cvEigenanatomy

Cross-validation method for eigenanatomy decompositions.
decropImage

decrop a sub-image back into the full image
getMask

Get Mask
getfMRInuisanceVariables

Extract generic fMRI nuisance variables for ASL or BOLD
getNeighborhoodInMask

Get neighborhoods for voxels within mask
getPixels

Get Pixels
icawhiten

Simple icawhitening function.
image2ClusterImages

Converts an image to several independent images.
imageFileNames2ImageList

Simple imageFileNames2ImageListing function.
imageListToMatrix

Read Images into a Matrix
iMath

iMath
iMathOps

iMathOps
maskImage

Mask input image by mask image.
matrix2timeseries

Simple matrix2timeseries function.
getAverageOfTimeSeries

getAverageOfTimeSeries
getCentroids

Convert an image to the geometric centroids of its signal
hemodynamicRF

Linear Model for FMRI Data
iBind

iBind
initializeEigenanatomy

Convert a matrix to a form that can be used to initialize sparse cca and pca.
interleaveMatrixWithItself

Simple interleaveMatrixWithItself function.
labelStats

labelStats
lappend

Simple list append tool
makeGraph

Simple function to create and measure a graph from a square input matrix.
makeImage

Simple makeImage function.
partialVolumeCorrection

Perform partial volume correction for ASL images.
projectImageAlongAxis

Simple projectImageAlongAxis function.
perfusionregression

Perfusion Regression
quantifyCBF

Simple quantifyCBF function.
sparseDecom

Convenience wrapper for eigenanatomy decomposition.
sparseDecom2

Convenience wrapper for 2-view eigenanatomy decomposition.
usePkg

Use any package. If package is not installed, this will install from CRAN.
vwnrfs

voxelwise neighborhood random forest segmentation and prediction
antsApplyTransforms

Apply transforms to images.
n4BiasFieldCorrection

Bias Field Correction
reorientImage

reorient image by its principal axis
renderSurfaceFunction

3D surface-based rendering of volume images.
rfSegmentationPredict

A rfSegmentationPredict function.
subjectDataToGroupDataFrame

Simple subjectDataToGroupDataFrameing function.
timeseries2matrix

Time-series image to matrix
rsfDenoise

WIP: data-driven denoising for resting state fMRI
taskFMRI

Simple taskFMRI function.
timeseriesN3

Run N3 on slices of timeseries.
filterfMRIforNetworkAnalysis

Basic pre-processing for BOLD or ASL-based network analysis.
getNeighborhoodAtVoxel

Get a hypercube neighborhood at a voxel
imagesToMatrix

Read Images into a Matrix
getMultivariateTemplateCoordinates

Label multivariate components by an anatomical coordinate system.
lowrankRowMatrix

Produces a low rank version of the input matrix
imageMath

R access to the ANTs program ImageMath
labelGeometryMeasures

labelGeometryMeasures
labelImageCentroids

labelImageCentroids
frequencyFilterfMRI

Band pass filtering for BOLD image.
antsBOLDNetworkAnalysis

a basic framework for network analysis that produces graph metrics
antsCopyImageInfo

Copy header info
getANTsRData

getANTsRData
plotBasicNetwork

Simple plotBasicNetwork function.
getASLNoisePredictors

Get nuisance predictors from ASL images
is.antsImage

is.antsImage
joinEigenanatomy

Simple joinEigenanatomy function.
invariantImageSimilarity

similarity metrics between two images as a function of geometry
jointIntensityFusion

joint intensity fusion
aal

aal
plot.antsImage

Plotting an image slice or multi-slice with optional color overlay.
abpBrainExtraction

An ants-based brain extraction script.
getTemplateCoordinates

Define an anatomical coordinate system in a new image based on a template
extractSlice

extract a slice from an image
%>%

Pipe an object forward
exemplarInpainting

Uses example images to inpaint or approximate an existing image.
quantifySNPs

Simple quantifySNPs function.
rapidlyInspectImageData

Simple rapidlyInspectImageData function.
whiten

Simple whitening function.
temporalwhiten

Simple autocorrelation-based temporal whitening function.
thresholdImage

Threshold Image
jointIntensityFusion3D

jointIntensityFusion3D
antsAverageImages

Computes average of image list
kellyKapowski

Compute cortical thickness using the DiReCT algorithm.
mrvnrfs

multi-res voxelwise neighborhood random forest segmentation learning
mrvnrfs.predict

multi-res voxelwise neighborhood random forest segmentation
n3BiasFieldCorrection

Bias Field Correction
plotPrettyGraph

Simple plotPrettyGraph function saves to png.
preprocessfMRI

Preprocess BOLD fMRI image data.
reflectImage

reflectImage
sparseDecom2boot

Convenience wrapper for 2-view eigenanatomy decomposition w/bootstrap initialization.
sparseDecomboot

Convenience wrapper for eigenanatomy decomposition.
regressionNetworkViz

Visualize a regression result by a d3 network visualization.
timeserieswindow2matrix

Time-series image to matrix of time windows around user-specified events
tracts

tracts
save.ANTsR

save.ANTsR
segmentShapeFromImage

convolution-based shape identification
kmeansSegmentation

k means image segmentation.
labelClusters

Simple labelClustering function.
matrixToImages

Convert rows of a matrix to images
networkEiganat

Convenience wrapper for eigenanatomy decomposition.
mni2tal

Brett's mni2tal
pairwiseImageDistanceMatrix

Simple pairwiseImageDistanceMatrix function for images
regressProjections

Regression on image set projection
renderImageLabels

3D surface-based rendering of image segmentation labels
sliceTimingCorrection

slice timing correction for fMRI.
sparseRegression

Sparse regression on input images.
smoothImage

Smooth image
spatialbayesianlm

spatially constrained bayesian regression function.
make3ViewPNG

Rotate an existing 3d window into different views.
resampleImage

resampleImage
rfSegmentation

A rfSegmentation function.
splitData

Split data for testing and training
subgradientL1Regression

Simple subgradientL1Regressioning function.
antsPreprocessfMRI

Preprocess BOLD fMRI image data.
as.matrix

antsImage to numeric matrix
as.numeric

antsImage to numeric vector
perfusion-predictors

Get perfusion predictors
getROIValues

Compute mean value in each ROI label.
phantom_population_study

ANTsR population study using R linear regression.
fastwhiten

Simple fastwhitening function.
Motion-Correction

Motion Correction
sccan

Sparse Statistical Analysis
as.antsImage

numeric matrix/array to antsImage
as.array

antsImage to numeric array
MeasureMinMaxMean

Measure Min Max Mean
plotANTsImage

Plotting an image slice or multi-slice with optional color overlay.
renderNetwork

3D surface-based rendering of image ROI-based networks
visualizeBlob

Visualize cortical blob
inspectImageData3D

Simple inspectImageData3D function.
antsImage-class

Class "antsImage"
CBF

CBF Computation
simple_roi_analysis

Perform ROI population analysis between two groups.
simple_voxel_based_analysis

Perform voxel-based population analysis between two groups.
KellyKapowski

Compute cortical thickness using the DiReCT algorithm.
Atropos

FMM Segmentation
Extract

Extract/Replace regions an antsImage
SmoothImage

Smooth an image
N3BiasFieldCorrection

Bias Field Correction
ImageMath

Image Math
Comparison

Relational operators for antsImage
ThresholdImage

Theshold Image
antsMatrix-class

An S4 class to hold an antsMatrix imported from ITK types C++ type used to represent an element of the matrix pointer to the actual image C++ type 'itk::image< pixeltype , dimension >::Pointer'
antsRegion-class

An S4 class to hold a region of an antsImage
%>%

Pipe an object forward