Learn R Programming

⚠️There's a newer version (1.0) of this package.Take me there.

ANTsR Instagram

ANTsR

A package providing ANTs features in R as well as imaging-specific data representations, spatially regularized dimensionality reduction and segmentation tools. See also the Neuroconductor site.

Description

Version: 0.3.3

License: GPL (>=2)

Depends: R (≥ 3.0), methods

Imports: Rcpp, tools, magrittr

LinkingTo: Rcpp, ITKR, ANTsRCore

Author: Brian B. Avants, Benjamin M. Kandel, Jeff T. Duda, Philip A. Cook, Nicholas J. Tustison, Dorian Pustina

Maintainer: Brian B. Avants

URL: homepage

BugReports: github issues

NeedsCompilation: yes

Travis checks: ANTsR results

Downloads

Reference manual: ANTsR.pdf

Vignettes:

Wiki: Notes and work in progress examples

Package source: from github

OS X Mavericks, Yosemite binaries: OSX

Linux binaries: Ubuntu

Windows installation option here

Install the binary, after downloading, via command line:

R CMD INSTALL ANTsR_*.tgz

Research using ANTsR

Installation from source

Please read this entire section before choosing which method you prefer.

In general, these assume you have git installed / accessible in your environment, as well as a compiler, preferably clang. you may also need cmake if you do/can not install cmaker.

Windows users should see Rtools and maybe, also, installr for assistance in setting up their environment for building (must have a compiler too). To my knowledge, there are no recorded instances of ANTsR being installed on Windows. If someone does so, we would like to know.

You will need to install R packages that ANTsR requires. Minimally: Install ITKR and ANTsRCore here and here then do:

mydeps <- c( "Rcpp", "tools", "methods", "magrittr" )
install.packages( pkgs = mydeps, dependencies = TRUE )

You can gain additional functionality by installing packages that are listed in the DESCRIPTION file under Suggests. A complete list of recommended ancillary packages here.

Method 1: drat See full instructions here but briefly:

install.packages("drat")
drat::addRepo("ANTs-R")
install.packages("ANTsR")

Thanks to zarquon42b.

Method 2: with devtools in R

library( devtools )
# install_github("stnava/cmaker") # if you do not have cmake
install_github("stnava/ITKR")
install_github("stnava/ANTsRCore")
install_github("stnava/ANTsR")

Method 3: from command line (most traditional method)

Assumes git, cmake and compilers are available in your environment (as above).

First, clone the repository:

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

Install the package as follows:

$ R CMD INSTALL ITKR
$ R CMD INSTALL ANTsRCore
$ R CMD INSTALL ANTsR

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( 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<-getNeighborhoodInMask(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)

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]" )

Tagging a beta release

git tag -d beta
git push origin :refs/tags/beta
git tag beta
git push  --tags origin

Release notes

More like development highlights, as opposed to release notes. See git log for the complete history. We try to follow these versioning recommendations for R packages. Under these guidelines, only major.minor is an official release.

0.4.0

  • ENH: better compilation and release style.
  • ENH: return boolean same size as image
  • ENH: improved decomposition methods
  • ENH: easier to use antsrSurf and antsrVol

0.3.3

  • ENH: spare distance matrix, multi scale svd

0.3.2

  • ENH: added domainImg option to plot.antsImage which can standardize plot.

  • COMP: test for DVCL define requirement to improve clang and gcc compilations

  • WIP: transform objects can be created on the fly and manipulated thanks to jeff duda

  • ENH: automation for eigenanatomy

  • ENH: reworked SCCAN and eanat

  • ENH: mrvnrfs

  • ENH: resting state Vignette

  • DOC: clarify/extend antsApplyTransforms

  • ENH: multidimensional images

  • STYLE: iMath not ImageMath in ANTsR

0.3.1

  • WIP: iMath improvements

  • WIP: ASL pipeline fuctionality

  • BUG: Fixed image indexing bug

  • BUG: plot.antsImage improvements

  • ENH: more antsRegistration options

  • ENH: geoSeg

  • ENH: JointLabelFusion and JointIntensityFusion

  • ENH: Enable negating images

  • ENH: weingarten curvature

  • ENH: antsApplyTransformsToPoints with example

  • ENH: renormalizeProbabilityImages

  • ENH: Suppress output from imageWrite.

0.3.0

First official release.

Copy Link

Version

Version

0.4.0

License

GPL (>=2)

Maintainer

Brian Avants

Last Published

August 23rd, 2020

Functions in ANTsR (0.4.0)

antsApplyTransforms

Apply transforms to images.
antsAverageImages

Computes average of image list
DesikanKillianyTourville

DesikanKillianyTourville
affineInitializer

a multi-start optimizer for affine registration
alffmap

alffmap
antsApplyTransformsToPoints

Apply transforms to points.
abpN4

MR image bias correction based on the N4 algorithm.
antsBOLDNetworkAnalysis

a basic framework for network analysis that produces graph metrics
abpBrainExtraction

An ants-based brain extraction script.
aal

aal
antsImageIterator

antsImageIterator
antsImageIterator-class

An S4 class for an antsImageIterator
antsImageGetSet

antsImageGetSet
antsImageHeaderInfo

Read file info from image header
mean,antsImage-method

arith.antsImage
antsImage-class

An S4 class for an antsImage
antsCopyImageInfo

Copy header info
antsImageClone

Clone an antsImage.
antsImageIteratorGet

antsImageIteratorGet
antsImageIteratorGetIndex

antsImageIteratorGetIndex
antsImageIteratorSetIndex

antsImageIteratorSetIndex
antsImageIteratorIsAtEnd

antsImageIteratorIsAtEnd
antsImageMutualInformation

mutual information between two images
antsImageIteratorIsAtReverseEnd

antsImageIteratorIsAtReverseEnd
antsRegion-class

An S4 class to hold a region of an antsImage
antsImageIteratorGoToBegin

antsImageIteratorGoToBegin
antsImageIteratorGoToReverseBegin

antsImageIteratorGoToReverseBegin
antsRegistration

Perform registration between two images.
antsImageIteratorSet

antsImageIteratorSet
antsImageIteratorRemaining

antsImageIteratorRemaining
antsImagePhysicalSpaceConsistency

Check for physical space consistency
antsImageRead

Image Read
antsTransformIndexToPhysicalPoint

Get Spatial Point from Index
aslCensoring

Censor bad volumes from ASL data.
antsTransformPhysicalPointToIndex

Get Index from Spatial Point
aslAveraging

Average ASL tag-control pairs to estimate perfusion
antsSetPixels

Set a pixel value at an index
antsrSurf

Render a function onto a surface.
antsSpatialICAfMRI

Perform spatial ICA on fMRI bold data.
antsrTransform-class

An S4 class for an antsrTransform
applyAntsrTransform

applyAntsrTransform
antsrGetPointerName

Return the antsImage pointer string
applyAntsrTransformToImage

applyAntsrTransformToImage
antsrMotionCalculation

antsrMotionCalculation
applyAntsrTransformToPoint

applyAntsrTransformToPoint
applyAntsrTransformToVector

applyAntsrTransformToVector
bayesianCBF

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

Simple bayesian regression function.
antsrTransformFromDisplacementField

getAntsrTransformParameters
antsrVol

Render an image volume with or without overlay.
aslDenoiseR

WIP: data-driven denoising for ASL MRI
bloodPerfusionSVD

Calculate blood perfusion using deconvolution.
aslPerfusion

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

bold_correlation_matrix
computeDVARS

computeDVARS
composeTransformsToField

Compose arbitrary transform list into a deformation field.
deconvolutionSVD

Regularize SVD (deconvolution) solution of cerebral blood flow.
decropImage

decrop a sub-image back into the full image
fastMarchingExtension

Fast Marching Extension filter will extend an intensity or label image from a known region into the unknown region along a geodesic path
filterfMRIforNetworkAnalysis

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

Efficiently compute basic statistical inference from regressions with multiple outcomes
corw

produces a correlation matrix via weighted correlation.
blockStimulus

Block stimulus model for FMRI Data
createAntsrTransform

createAntsrTransform
crossvalidatedR2

Cross-Validated R^2 value
cvEigenanatomy

Cross-validation method for eigenanatomy decompositions.
frequencyFilterfMRI

Band pass filtering for BOLD image.
fsl2antsrTransform

fsl2antsrTransform
getAntsrTransformParameters

getAntsrTransformParameters
antsImageIteratorNext

antsImageIteratorNext
antsImageIteratorPrevious

antsImageIteratorPrevious
antsMotionCorr

Motion Correction
antsMotionCalculation

antsMotionCalculation
atropos

FMM Segmentation
basicInPaint

Inpaints missing imaging data from boundary data
compcor

Compcors the input matrix using SVD and returns the result.
composeAntsrTransforms

composeAntsrTransforms
cropImage

crop a sub-image via a mask
cropIndices

crop a sub-image by image indices
fMRINormalization

Multi-run normalization, filtering and nuisance estimation for fMRI.
extractSlice

extract a slice from an image
getCentroids

Convert an image to the geometric centroids of its signal
getCenterOfMass

center of mass
getfMRInuisanceVariables

Extract generic fMRI nuisance variables for ASL or BOLD
getTemplateCoordinates

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

Read Images into a Matrix
imageFileNames2ImageList

Simple imageFileNames2ImageListing function.
labelGeometryMeasures

labelGeometryMeasures
labels2matrix

Convert label image to a matrix
labelImageCentroids

labelImageCentroids
labelStats

labelStats
morphology

Morphological image operations
mni2tal

Brett's mni2tal
pairwiseImageDistanceMatrix

Simple pairwiseImageDistanceMatrix function for images
partialVolumeCorrection

Perform partial volume correction for ASL images.
priorBasedSegmentation

spatial prior-based image segmentation.
quantifyCBF

quantifyCBF
reflectImage

reflectImage
eigSeg

Segmentation for eigenanatomy.
estSmooth

Estimate image smoothness
getMask

Get Mask
getMultiResFeatureMatrix

build multiple resolution predictor matrix from feature images
iMathOps

iMathOps
icawhiten

Simple icawhitening function.
invertAntsrTransform

invertAntsrTransform
joinEigenanatomy

Simple joinEigenanatomy function.
is.antsImage

is.antsImage
jointIntensityFusion

joint intensity fusion
renderSurfaceFunction

3D surface-based rendering of volume images.
regressProjections

Regression on image set projection
renderImageLabels

3D surface-based rendering of image segmentation labels
setAntsrTransformParameters

setAntsrTransformParameters
smoothImage

Smooth image
splitMask

split a mask into n labeled sub-masks
splitNDImageToList

splitNDImageToList
vectortomultichannel

Convert vector to multichannel antsImage.
vwnrfs

voxelwise neighborhood random forest segmentation and prediction
image2ClusterImages

Converts an image to several independent images.
writeAntsrTransform

writeAntsrTransform
getNeighborhoodAtVoxel

Get a hypercube neighborhood at a voxel
getMultivariateTemplateCoordinates

Label multivariate components by an anatomical coordinate system.
whiten

Simple whitening function.
imageDomainToSpatialMatrix

Image domain to spatial position
kmeansSegmentation

k means image segmentation.
labelClusters

Simple labelClustering function.
make3ViewPNG

Rotate an existing 3d window into different views.
makeGraph

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

mergeListToNDImage
mergeChannels

merge images into a multiChannel antsImage
getAverageOfTimeSeries

getAverageOfTimeSeries
hemodynamicRF

Linear Model for FMRI Data
%>%

Pipe an object forward
interleaveMatrixWithItself

Simple interleaveMatrixWithItself function.
invariantImageSimilarity

similarity metrics between two images as a function of geometry
jointLabelFusion3D

jointLabelFusion3D
kellyKapowski

Compute cortical thickness using the DiReCT algorithm.
makePointsImage

Create label image from physical space points
multiLabelMorphology

Morphology on multi label images.
antsImageWrite

Image Write
makeImage

Simple makeImage function.
antsrimpute

antsrimpute
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'
apply.antsImage

Extension of apply to allow input of antsImage
as.antsImage

as.antsImage
as.antsMatrix

as.antsMatrix
clusterTimeSeries

Split time series image into k distinct images
createWarpedGrid

Create a warped grid for visualization.
quantifySNPs

Simple quantifySNPs function.
combineNuisancePredictors

Combine and reduce dimensionality of nuisance predictors.
createJacobianDeterminantImage

createJacobianDeterminantImage
randcca

randomized cca function.
reho

REHO
regressionNetworkViz

Visualize a regression result by a d3 network visualization.
rfSegmentationPredict

A rfSegmentationPredict function.
rftPval

RFT p-values
ripmmarcBasisImage

Generate an antsImage from ripmmarc basis data
sparseDecom2boot

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

Convenience wrapper for eigenanatomy decomposition.
computeDVARSspatialMap

computeDVARSspatialMap
robustMatrixTransform

Simple robustMatrixTransform function.
convolveImage

convolve one image with another
eanatDef

Eigenanatomy with deflation
eanatSelect

Selection of n eigenvectors and sparsity for eigenanatomy
euler

Euler Character
exemplarInpainting

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

Get nuisance predictors from ASL images
getNeighborhoodInMask

Get neighborhoods for voxels within mask
n4BiasFieldCorrection

Bias Field Correction
getAntsrTransformFixedParameters

getAntsrTransformParameters
getPixels

Get Pixels
multiResRandomForestRegression

multiple resolution neighborhood random forest regression
powers_areal_mni_itk

powers_areal_mni_itk
networkEiganat

Convenience wrapper for eigenanatomy decomposition.
plotPrettyGraph

Simple plotPrettyGraph function saves to png.
rftResults

RFT Statistical Results
ripmmarc

Rotation Invariant Patch-based Multi-Modality Analysis aRChitecture
sparseDecom

Convenience wrapper for eigenanatomy decomposition.
sparseDecom2

Convenience wrapper for 2-view eigenanatomy decomposition.
taskFMRI

Simple taskFMRI function.
temporalwhiten

Simple autocorrelation-based temporal whitening function.
testEanat

Test eigenanatomy in order
matrix2timeseries

Simple matrix2timeseries function.
thresholdImage

Threshold Image
matrixToImages

Convert rows of a matrix to images
multiscaleSVD

Multi-scale svd
n3BiasFieldCorrection

Bias Field Correction
preprocessRestingBOLD

Preprocess resting BOLD fMRI image data.
preprocessfMRI

Preprocess BOLD fMRI image data.
randwhiten

randomized whitening function.
resampleImage

resampleImage
rapidlyInspectImageData

Simple rapidlyInspectImageData function.
resampleImageToTarget

resampleImageToTarget
makePowersPointsImage

Label image from Powers points
maskImage

Mask input image by mask image.
perfusionregression

Perfusion Regression
randomMask

Get a random mask
petSUVR

Compute SUVR from PET time series images
randsvd

randomized svd function.
renormalizeProbabilityImages

Normalize (modified) probability images
segmentationRefinement.train

Segmentation refinement using corrective learning (training)
reorientImage

reorient image by its principal axis
setAntsrTransformFixedParameters

setAntsrTransformParameters
statFieldThresh

Produces a threshold value based on cluster or voxel level statistics
[,antsImage,NULL,ANY-method

ants image substitutions
timeserieswindow2matrix

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

tracts
writeNormalizedPopulationData

Save normalized population data to a h5 file
rsfDenoise

WIP: data-driven denoising for resting state fMRI
save.ANTsR

save.ANTsR
sparseDistanceMatrix

Create sparse distance, covariance or correlation matrix
sparseDistanceMatrixXY

Create sparse distance, covariance or correlation matrix from x, y
trapz

Calculate the area under a sampled curve (or set of curves).
subgradientL1Regression

Simple subgradientL1Regression function.
subjectDataToGroupDataFrame

convert subject matrix data to a row in a dataframe.
usePkg

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

voxelwise neighborhood random forest prediction
weingartenImageCurvature

image curvature for 2D or 3D
geoSeg

brain segmentation based on geometric priors
getANTsRData

getANTsRData
iBind

iBind
initializeEigenanatomy

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

iMath
imagesToMatrix

Read Images into a Matrix
jointIntensityFusion3D

jointIntensityFusion3D
jointLabelFusion

joint label and intensity fusion
lappend

Simple list append tool
lowrankRowMatrix

Produces a low rank version of the input matrix
mrvnrfs

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

multi-res voxelwise neighborhood random forest segmentation
multichannelPCA

Shape analysis of multichannel images based on PCA
plot.antsImage

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

Convert multichannel antsImage to a vector.
plotBasicNetwork

Simple plotBasicNetwork function.
resels

Estimates image resels
readAntsrTransform

readAntsrTransform
readNormalizedPopulationData

Read normalized population from h5 file
rfSegmentation

A rfSegmentation function.
segmentShapeFromImage

convolution-based shape identification
segmentationRefinement.predict

Segmentation refinement using corrective learning (prediction)
sparseRegression

Sparse regression on input images.
timeseriesN3

Run N3 on slices of timeseries.
spatialbayesianlm

spatially constrained bayesian regression function.
splitChannels

split a multichannel antsImage
splitData

Split data for testing and training
timeseries2matrix

Time-series image to matrix