| Title: | ANTs in R: Quantification Tools for Biomedical Images |
|---|---|
| Description: | Quantification tools for biomedical images that interface state of the art image processing with R statistical methods. The project grew out of the need, at University of Pennsylvania, to develop large-scale analytics pipelines that track provenance from scanner to scientific study. ANTsR wraps an ANTs and ITK C++ core via Rcpp to access these frameworks from within R and support reproducible analyses. Specialized functionality in ANTsR includes image segmentation and registration along imaging specific variations of principal component and canonical correlation analysis. |
| Authors: | Brian B. Avants [aut, cre], Benjamin M. Kandel [ctb], Jeff T. Duda [ctb], Philip A. Cook [ctb], Nicholas J. Tustison [ctb], Dorian Pustina [ctb] |
| Maintainer: | Brian B. Avants <[email protected]> |
| License: | Apache License (== 2.0) | file LICENSE |
| Version: | 0.6.7 |
| Built: | 2026-10-29 22:55:18 UTC |
| Source: | https://github.com/ANTsX/ANTsR |
Processing arguments for command line parsing
.int_antsProcessArguments(args).int_antsProcessArguments(args)
args |
arguments to parse into those for |
A character vector args = "hey" .int_antsProcessArguments(args) args = list(h = "hey") .int_antsProcessArguments(args) args = list(h = list("hey")) .int_antsProcessArguments(args)
motion corrects 4D time series imaging data
.motion_correction( img, fixed = NULL, moreaccurate = 1, txtype = "Affine", verbose = FALSE ).motion_correction( img, fixed = NULL, moreaccurate = 1, txtype = "Affine", verbose = FALSE )
img |
4D antsImage |
fixed |
target fixed image |
moreaccurate |
0, 1 or 2 with higher values being more accurate (use 2 for real applications, 0 for testing) |
txtype |
Transformation type |
verbose |
verbosity boolean |
list of outputs
This function may give different results on multiple runs.
Avants BB
testimg <- makeImage(c(10, 10, 10, 5), rnorm(5000)) testimg <- iMath(testimg, "PadImage", 5) mocorr <- .motion_correction(testimg) aimg_to_array <- function(x) { if (is.antsImage(x)) { x <- as.array(x) } x } amocorr <- lapply(mocorr, aimg_to_array) mocorr2 <- .motion_correction(testimg) amocorr2 <- lapply(mocorr2, aimg_to_array) # This function may give different results on multiple runs # without setting the seedtestimg <- makeImage(c(10, 10, 10, 5), rnorm(5000)) testimg <- iMath(testimg, "PadImage", 5) mocorr <- .motion_correction(testimg) aimg_to_array <- function(x) { if (is.antsImage(x)) { x <- as.array(x) } x } amocorr <- lapply(mocorr, aimg_to_array) mocorr2 <- .motion_correction(testimg) amocorr2 <- lapply(mocorr2, aimg_to_array) # This function may give different results on multiple runs # without setting the seed
Operators acting on antsImage objects to extract or replace parts.
## S4 replacement method for signature 'antsImage,NULL,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,logical,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,array,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,matrix,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,list,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,antsImage,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,NULL,antsRegion,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,logical,antsRegion,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,array,antsRegion,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,matrix,antsRegion,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,NULL,NULL,numeric' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,numeric,numeric,numeric' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,numeric,NULL,numeric' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,NULL,numeric,numeric' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,numeric,missing,array' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,missing,numeric,array' x[i, j, ...] <- value ## S4 method for signature 'antsImage,NULL,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,antsImage,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'ANY,antsImage,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,logical,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,logical,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,ANY,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,ANY,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,NULL,NULL,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,NULL,NULL,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,numeric,numeric,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,numeric,numeric,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,numeric,NULL,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,numeric,NULL,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,NULL,numeric,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,NULL,numeric,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,missing,numeric,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,numeric,missing,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,missing,missing,ANY' x[i, j, k = NA, l = NA, ..., drop]## S4 replacement method for signature 'antsImage,NULL,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,logical,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,array,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,matrix,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,list,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,antsImage,ANY,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,NULL,antsRegion,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,logical,antsRegion,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,array,antsRegion,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,matrix,antsRegion,ANY' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,NULL,NULL,numeric' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,numeric,numeric,numeric' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,numeric,NULL,numeric' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,NULL,numeric,numeric' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,numeric,missing,array' x[i, j, ...] <- value ## S4 replacement method for signature 'antsImage,missing,numeric,array' x[i, j, ...] <- value ## S4 method for signature 'antsImage,NULL,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,antsImage,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'ANY,antsImage,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,logical,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,logical,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,ANY,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,ANY,ANY,ANY' x[i, j, ..., drop = TRUE] ## S4 method for signature 'antsImage,NULL,NULL,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,NULL,NULL,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,numeric,numeric,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,numeric,numeric,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,numeric,NULL,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,numeric,NULL,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,NULL,numeric,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,NULL,numeric,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,missing,numeric,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,numeric,missing,ANY' x[i, j, k = NA, l = NA, ..., drop] ## S4 method for signature 'antsImage,missing,missing,ANY' x[i, j, k = NA, l = NA, ..., drop]
x |
antsImage |
i |
logical or i-th dimension |
j |
not used or j-th dimension |
... |
not used |
value |
value to assign to the subset in assignment operator |
drop |
method for missing data |
k |
not used or k-th dimension |
l |
not used or l-th dimension |
fi <- antsImageRead(getANTsRData("r16")) l <- prod(dim(fi)) sub <- sample(c(TRUE, FALSE), size = l, replace = TRUE) fi[sub] <- rnorm(sum(sub)) fi[, 1] <- array(10, dim = dim(fi[, 1])) fi <- antsImageRead(getANTsRData("ch2")) fi[2, 1, 2] fi[2, 1, 2] <- 4 fi[, 1, 2] fi[, 1, 2] <- array(10, dim = dim(fi[, 1, 2])) fi[2, , 2] fi[2, , 2] <- array(10, dim = dim(fi[2, , 2])) fi[2, 1, ] # fi[2, 1, ] = array(10, dim = dim(fi[2, 1, ])) fi[2, , ] fi[, 1, ] fi[, , 2] # fi[, , 2] = array(10, dim = dim(fi[, , 2])) l <- prod(dim(fi)) sub <- sample(c(TRUE, FALSE), size = l, replace = TRUE) sub <- array(sub, dim = dim(fi)) fi[sub] <- rnorm(sum(sub)) fi <- antsImageRead(getANTsRData("r16")) l <- prod(dim(fi)) sub <- sample(c(TRUE, FALSE), size = l, replace = TRUE) sub <- array(sub, dim = dim(fi)) fi[sub] <- rnorm(sum(sub)) fi <- antsImageRead(getANTsRData("r16")) fi[fi > 200] <- 200 fi <- antsImageRead(getANTsRData("r16")) i <- sample(seq(nrow(fi)), 5) i <- as.numeric(i) j <- i fi[i, j] <- 26.2 fi <- antsImageRead(getANTsRData("r16")) fi[1, ] <- array(10, dim = dim(fi[1, ])) fi <- antsImageRead(getANTsRData("r16")) fi[, 1] <- array(10, dim = dim(fi[, 1])) fi <- antsImageRead(getANTsRData("r16")) fi[, 1] fi[, 2:5] fi <- antsImageRead(getANTsRData("r16")) fi[fi > 45] fi <- antsImageRead(getANTsRData("r16")) arr <- c(as.array(fi) > 45) fi[arr] fi[1:10, 2:14] fi[1:10 * 1.0, 2:14 * 1.0] fi <- antsImageRead(getANTsRData("ch2")) fi[, , 2]fi <- antsImageRead(getANTsRData("r16")) l <- prod(dim(fi)) sub <- sample(c(TRUE, FALSE), size = l, replace = TRUE) fi[sub] <- rnorm(sum(sub)) fi[, 1] <- array(10, dim = dim(fi[, 1])) fi <- antsImageRead(getANTsRData("ch2")) fi[2, 1, 2] fi[2, 1, 2] <- 4 fi[, 1, 2] fi[, 1, 2] <- array(10, dim = dim(fi[, 1, 2])) fi[2, , 2] fi[2, , 2] <- array(10, dim = dim(fi[2, , 2])) fi[2, 1, ] # fi[2, 1, ] = array(10, dim = dim(fi[2, 1, ])) fi[2, , ] fi[, 1, ] fi[, , 2] # fi[, , 2] = array(10, dim = dim(fi[, , 2])) l <- prod(dim(fi)) sub <- sample(c(TRUE, FALSE), size = l, replace = TRUE) sub <- array(sub, dim = dim(fi)) fi[sub] <- rnorm(sum(sub)) fi <- antsImageRead(getANTsRData("r16")) l <- prod(dim(fi)) sub <- sample(c(TRUE, FALSE), size = l, replace = TRUE) sub <- array(sub, dim = dim(fi)) fi[sub] <- rnorm(sum(sub)) fi <- antsImageRead(getANTsRData("r16")) fi[fi > 200] <- 200 fi <- antsImageRead(getANTsRData("r16")) i <- sample(seq(nrow(fi)), 5) i <- as.numeric(i) j <- i fi[i, j] <- 26.2 fi <- antsImageRead(getANTsRData("r16")) fi[1, ] <- array(10, dim = dim(fi[1, ])) fi <- antsImageRead(getANTsRData("r16")) fi[, 1] <- array(10, dim = dim(fi[, 1])) fi <- antsImageRead(getANTsRData("r16")) fi[, 1] fi[, 2:5] fi <- antsImageRead(getANTsRData("r16")) fi[fi > 45] fi <- antsImageRead(getANTsRData("r16")) arr <- c(as.array(fi) > 45) fi[arr] fi[1:10, 2:14] fi[1:10 * 1.0, 2:14 * 1.0] fi <- antsImageRead(getANTsRData("ch2")) fi[, , 2]
Chain operators together
lhs %>% rhslhs %>% rhs
lhs |
input from left side |
rhs |
additional params |
The %>>% operator pipes the object on the left-hand side to the
right-hand side according to the syntax.
A data frame label numbers and names for the neuroanatomical AAL labels.
aalaal
A data frame listing the following variables.
label_numNumerical label value.
label_nameShorthand anatomical value.
cerebellumbinary value
cortexbinary value
deepgreybinary value
frontalbinary value
isdmnbinary value
issaliencebinary value
leftbinary value
limbicbinary value
occipitalbinary value
parietalbinary value
rightbinary value
temporalbinary value
unknownbinary value
https://en.wikipedia.org/wiki/Automated_Anatomical_Labeling
data(aal)data(aal)
Brain extraction based on mapping a template image and its mask to the input image. Should be preceded by abpN4.
abpBrainExtraction( img, tem, temmask, temregmask = NULL, regtype = "SyN", tdir = NA, pad = 0, verbose = FALSE )abpBrainExtraction( img, tem, temmask, temregmask = NULL, regtype = "SyN", tdir = NA, pad = 0, verbose = FALSE )
img |
whole head image to which we map a brain mask |
tem |
Template image (the whole head) which has an associated label mask. |
temmask |
Template's antsImage brain mask. |
temregmask |
Template's registration mask including skull but not the face |
regtype |
registration type: 'SyN' (fast, default), 'SyNabp' (better, slower) |
tdir |
temporary directory (optional) |
pad |
argument passed to |
verbose |
print diagnostic messages |
outputs a brain image and brain mask.
Tustison N, Avants BB
n <- 64 fn <- getANTsRData("r16") img <- antsImageRead(fn) img <- resampleImage(img, c(n, n), 1, 0) tf <- getANTsRData("r27") tem <- antsImageRead(tf) tem <- resampleImage(tem, c(n, n), 1, 0) temmask <- antsImageClone(tem) temmask[tem > 20] <- 1 temmask[tem <= 20] <- 0 ## Not run: bm <- abpBrainExtraction(img = img, tem = tem, temmask = temmask) ## End(Not run)n <- 64 fn <- getANTsRData("r16") img <- antsImageRead(fn) img <- resampleImage(img, c(n, n), 1, 0) tf <- getANTsRData("r27") tem <- antsImageRead(tf) tem <- resampleImage(tem, c(n, n), 1, 0) temmask <- antsImageClone(tem) temmask[tem > 20] <- 1 temmask[tem <= 20] <- 0 ## Not run: bm <- abpBrainExtraction(img = img, tem = tem, temmask = temmask) ## End(Not run)
Truncate outlier intensities and bias correct with the N4 algorithm.
abpN4( img, intensityTruncation = c(0.025, 0.975, 256), mask, usen3 = FALSE, ... )abpN4( img, intensityTruncation = c(0.025, 0.975, 256), mask, usen3 = FALSE, ... )
img |
image to be bias corrected |
intensityTruncation |
quantiles for image truncation. |
mask |
optional antsImage mask |
usen3 |
Use N3 algorithm instead of N4 |
... |
additional arguments to pass to
|
outputs a bias corrected image. 1 indicates failure.
Tustison N, Avants BB
img <- antsImageRead(getANTsRData("r16")) img2 <- abpN4(img) img3 <- abpN4(img) testthat::expect_equal(mean(img2), 82.6, tolerance = 1e-2) testthat::expect_equal(img2, img3)img <- antsImageRead(getANTsRData("r16")) img2 <- abpN4(img) img3 <- abpN4(img) testthat::expect_equal(mean(img2), 82.6, tolerance = 1e-2) testthat::expect_equal(img2, img3)
Add noise to image using additive Guassian, salt-and-pepper, shot, or speckle noise.
addNoiseToImage( image, noiseModel = c("additivegaussian", "saltandpepper", "shot", "speckle"), noiseParameters )addNoiseToImage( image, noiseModel = c("additivegaussian", "saltandpepper", "shot", "speckle"), noiseParameters )
image |
input image |
noiseModel |
either "additivegaussian", "saltandpepper", "shot", or "speckle". |
noiseParameters |
vector defining the noise models.
|
noise corrupted image.
NJ Tustison
image <- antsImageRead(getANTsRData("r16")) noiseImage <- addNoiseToImage(image, "additivegaussian", c(0, 1)) noiseImage <- addNoiseToImage(image, "saltandpepper", c(0.1, 0, 100)) noiseImage <- addNoiseToImage(image, "shot", c(1.0)) noiseImage <- addNoiseToImage(image, "speckle", c(1.0))image <- antsImageRead(getANTsRData("r16")) noiseImage <- addNoiseToImage(image, "additivegaussian", c(0, 1)) noiseImage <- addNoiseToImage(image, "saltandpepper", c(0.1, 0, 100)) noiseImage <- addNoiseToImage(image, "shot", c(1.0)) noiseImage <- addNoiseToImage(image, "speckle", c(1.0))
This function avoids all redundant computations by getting all necessary components from a single call to an internal dispatcher.
adjusted_rvcoef(X, Y)adjusted_rvcoef(X, Y)
X |
A numeric matrix (n observations, p variables). |
Y |
A numeric matrix (n observations, q variables). |
A single scalar value for the adjusted RV-coefficient.
Searches over the sphere to find a good initialization for further registration refinement, if needed. This is a wrapper for the ANTs function antsAffineInitializer.
affineInitializer( fixedImage, movingImage, searchFactor = 20, radianFraction = 0.1, usePrincipalAxis = FALSE, localSearchIterations = 10, mask, txfn )affineInitializer( fixedImage, movingImage, searchFactor = 20, radianFraction = 0.1, usePrincipalAxis = FALSE, localSearchIterations = 10, mask, txfn )
fixedImage |
the fixed reference image |
movingImage |
the moving image to be mapped to the fixed space |
searchFactor |
degree of increments on the sphere to search |
radianFraction |
between zero and one, defines the arc to search over |
usePrincipalAxis |
boolean to initialize by principal axis |
localSearchIterations |
gradient descent iterations |
mask |
optional mask to restrict registration |
txfn |
filename for the transformation |
transformationMatrix
See https://github.com/ANTsX/ANTs/issues/444 for reproducibility discussion
Avants BB
fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r27")) tx <- affineInitializer(fi, mi) mi2 <- resampleImage(mi, c(1.25, 1.25)) tx <- affineInitializer(fi, mi2) tx2 <- affineInitializer(fi, mi2)fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r27")) tx <- affineInitializer(fi, mi) mi2 <- resampleImage(mi, c(1.25, 1.25)) tx <- affineInitializer(fi, mi2) tx2 <- affineInitializer(fi, mi2)
Amplitude of Low Frequency Fluctuations (ALFF; Zang et al., 2007) and fractional Amplitude of Low Frequency Fluctuations (f/ALFF; Zou et al., 2008) are related measures that quantify the amplitude of low frequency oscillations (LFOs). This function outputs ALFF and fALFF for the input.
alffmap( x, flo = 0.01, fhi = 0.1, tr = 1, detrend = TRUE, takesqrt = FALSE, kernel )alffmap( x, flo = 0.01, fhi = 0.1, tr = 1, detrend = TRUE, takesqrt = FALSE, kernel )
x |
input vector for the time series of interest |
flo |
low frequency, typically 0.01 |
fhi |
high frequency, typically 0.1 |
tr |
the period associated with the vector x (inverse of frequency) |
detrend |
detrend the input time series |
takesqrt |
take the sqrt of the computed values |
kernel |
smoothing kernel in estimate, see |
vector is output showing ALFF and fALFF values
Avants BB
set.seed(1) mat <- matrix(rnorm(3000), ncol = 50) fallf <- apply(mat, FUN = alffmap, MARGIN = 2) k <- kernel("daniell", rep(2, 3)) fallf2 <- apply(mat, FUN = alffmap, MARGIN = 2, kernel = k) testthat::expect_equal(mean(fallf2), 3.00367017972746)set.seed(1) mat <- matrix(rnorm(3000), ncol = 50) fallf <- apply(mat, FUN = alffmap, MARGIN = 2) k <- kernel("daniell", rep(2, 3)) fallf2 <- apply(mat, FUN = alffmap, MARGIN = 2, kernel = k) testthat::expect_equal(mean(fallf2), 3.00367017972746)
Apply a transform list to map an image from one domain to another. In image registration, one computes mappings between (usually) pairs of images. These transforms are often a sequence of increasingly complex maps, e.g. from translation, to rigid, to affine to deformation. The list of such transforms is passed to this function to interpolate one image domain into the next image domain, as below. The order matters strongly and the user is advised to familiarize with the standards established in examples.
antsApplyTransforms( fixed, moving, transformlist = "", interpolator = c("linear", "nearestNeighbor", "multiLabel", "gaussian", "bSpline", "cosineWindowedSinc", "welchWindowedSinc", "hammingWindowedSinc", "lanczosWindowedSinc", "genericLabel"), imagetype = 0, whichtoinvert = NA, compose = NA, verbose = FALSE, ... )antsApplyTransforms( fixed, moving, transformlist = "", interpolator = c("linear", "nearestNeighbor", "multiLabel", "gaussian", "bSpline", "cosineWindowedSinc", "welchWindowedSinc", "hammingWindowedSinc", "lanczosWindowedSinc", "genericLabel"), imagetype = 0, whichtoinvert = NA, compose = NA, verbose = FALSE, ... )
fixed |
fixed image defining domain into which the moving image is transformed. |
moving |
moving image to be mapped to fixed space. |
transformlist |
character vector of transforms generated by antsRegistration where each transform is a filename. |
interpolator |
Choice of interpolator. Supports partial matching.
|
imagetype |
choose 0/1/2/3 mapping to scalar/vector/tensor/time-series |
whichtoinvert |
optional list of booleans, same length as transforms. whichtoinvert[i] is TRUE if transformlist[i] is a matrix, and the matrix should be inverted. If transformlist[i] is a warp field, whichtoinvert[i] must be FALSE. If the transform list is a matrix followed by a warp field, whichtoinvert defaults to c(TRUE,FALSE). Otherwise it defaults to rep(FALSE, length(transformlist)). |
compose |
if it is a character string pointing to a valid file location, this will force the function to return a composite transformation filename. |
verbose |
print command and run verbose application of transform. |
... |
extra parameters |
an antsImage or transformation filename is output. 1 – Failure
Shrinidhi KL, Avants BB
# will give the full form of help antsApplyTransforms("-h") # see antsRegistration # example 1 - simplified fixed <- ri(1) moving <- ri(2) fixed <- resampleImage(fixed, c(64, 64), 1, 0) moving <- resampleImage(moving, c(68, 68), 1, 0) mytx <- antsRegistration( fixed = fixed, moving = moving, typeofTransform = "SyN", verbose = TRUE, printArgs = TRUE ) mywarpedimage <- antsApplyTransforms( fixed = fixed, moving = moving, transformlist = mytx$fwdtransforms ) testthat::expect_true(antsImagePhysicalSpaceConsistency(mywarpedimage, fixed)) invwarped_image <- antsApplyTransforms( fixed = moving, moving = fixed, transformlist = mytx$invtransforms ) testthat::expect_true(antsImagePhysicalSpaceConsistency(invwarped_image, moving)) # full access via listing the inputs in standard ANTs format res1 <- antsApplyTransforms( fixed = fixed, moving = moving, transformlist = mytx$fwdtransforms[2], whichtoinvert = 1, verbose = TRUE ) cfile <- antsApplyTransforms( fixed = fixed, moving = moving, transformlist = mytx$fwdtransforms, compose = tempfile() ) cimg <- antsImageRead(cfile) cout <- antsApplyTransforms( fixed = fixed, moving = moving, transformlist = cimg ) testthat::expect_error( antsApplyTransforms( fixed = fixed, moving = moving, transformlist = cimg, whichtoinvert = 1 ), "nnot invert transform" ) testthat::expect_error( antsApplyTransforms( fixed = fixed, moving = moving, transformlist = cimg, whichtoinvert = c(1, 2) ), "same length" ) testthat::expect_error(antsApplyTransforms( fixed = fixed, moving = moving, transformlist = "" ))# will give the full form of help antsApplyTransforms("-h") # see antsRegistration # example 1 - simplified fixed <- ri(1) moving <- ri(2) fixed <- resampleImage(fixed, c(64, 64), 1, 0) moving <- resampleImage(moving, c(68, 68), 1, 0) mytx <- antsRegistration( fixed = fixed, moving = moving, typeofTransform = "SyN", verbose = TRUE, printArgs = TRUE ) mywarpedimage <- antsApplyTransforms( fixed = fixed, moving = moving, transformlist = mytx$fwdtransforms ) testthat::expect_true(antsImagePhysicalSpaceConsistency(mywarpedimage, fixed)) invwarped_image <- antsApplyTransforms( fixed = moving, moving = fixed, transformlist = mytx$invtransforms ) testthat::expect_true(antsImagePhysicalSpaceConsistency(invwarped_image, moving)) # full access via listing the inputs in standard ANTs format res1 <- antsApplyTransforms( fixed = fixed, moving = moving, transformlist = mytx$fwdtransforms[2], whichtoinvert = 1, verbose = TRUE ) cfile <- antsApplyTransforms( fixed = fixed, moving = moving, transformlist = mytx$fwdtransforms, compose = tempfile() ) cimg <- antsImageRead(cfile) cout <- antsApplyTransforms( fixed = fixed, moving = moving, transformlist = cimg ) testthat::expect_error( antsApplyTransforms( fixed = fixed, moving = moving, transformlist = cimg, whichtoinvert = 1 ), "nnot invert transform" ) testthat::expect_error( antsApplyTransforms( fixed = fixed, moving = moving, transformlist = cimg, whichtoinvert = c(1, 2) ), "same length" ) testthat::expect_error(antsApplyTransforms( fixed = fixed, moving = moving, transformlist = "" ))
Apply a transform list to map a pointset from one domain to another. In registration, one computes mappings between pairs of domains. These transforms are often a sequence of increasingly complex maps, e.g. from translation, to rigid, to affine to deformation. The list of such transforms is passed to this function to interpolate one image domain into the next image domain, as below. The order matters strongly and the user is advised to familiarize with the standards established in examples. Importantly, point mapping goes the opposite direction of image mapping, for both reasons of convention and engineering.
antsApplyTransformsToPoints( dim, points, transformlist = "", whichtoinvert = NA )antsApplyTransformsToPoints( dim, points, transformlist = "", whichtoinvert = NA )
dim |
dimensionality of the transformation. |
points |
moving point set with n-points in rows of at least dim columns - we maintain extra information in additional columns. this may be either a dataframe or a 2D antsImage - the latter may be better for large pointsets. |
transformlist |
character vector of transforms generated by antsRegistration where each transform is a filename. |
whichtoinvert |
vector of booleans, same length as transforms |
same type as input. 1 – Failure
Avants BB
fixed <- antsImageRead(getANTsRData("r16"), 2) moving <- antsImageRead(getANTsRData("r64"), 2) fixed <- resampleImage(fixed, c(64, 64), 1, 0) moving <- resampleImage(moving, c(64, 64), 1, 0) mytx <- antsRegistration( fixed = fixed, moving = moving, typeofTransform = c("SyN"), verbose = FALSE ) pts <- data.frame( x = c(110.5, 120, 130), y = c(108.1, 121.0, 130), label = c(1, 2, 3) ) wpts <- antsApplyTransformsToPoints( dim = 2, points = pts, transformlist = mytx$fwdtransforms ) wptsi <- antsApplyTransformsToPoints( dim = 2, points = wpts, transformlist = mytx$invtransforms ) # close to pts ## Not run: fixed <- antsImageRead(getANTsRData("r16"), 2) moving <- antsImageRead(getANTsRData("r64"), 2) fpts <- kmeansSegmentation(fixed, 3)$segmentation %>% thresholdImage(1, 1) %>% labelClusters(5) %>% getCentroids(5) wpts <- antsApplyTransformsToPoints( dim = 2, points = fpts, transformlist = mytx$fwdtransforms ) labimgf <- fixed * 0 labimgm <- moving * 0 for (p in 1:nrow(wpts)) { pt <- as.numeric(wpts[p, 1:2]) idx <- round(antsTransformPhysicalPointToIndex(moving, pt)) labimgm[idx[1], idx[2]] <- p pt <- as.numeric(fpts[p, 1:2]) idx <- round(antsTransformPhysicalPointToIndex(fixed, pt)) labimgf[idx[1], idx[2]] <- p } plot(fixed, labimgf %>% iMath("GD", 2)) plot(moving, labimgm %>% iMath("GD", 2)) ## End(Not run)fixed <- antsImageRead(getANTsRData("r16"), 2) moving <- antsImageRead(getANTsRData("r64"), 2) fixed <- resampleImage(fixed, c(64, 64), 1, 0) moving <- resampleImage(moving, c(64, 64), 1, 0) mytx <- antsRegistration( fixed = fixed, moving = moving, typeofTransform = c("SyN"), verbose = FALSE ) pts <- data.frame( x = c(110.5, 120, 130), y = c(108.1, 121.0, 130), label = c(1, 2, 3) ) wpts <- antsApplyTransformsToPoints( dim = 2, points = pts, transformlist = mytx$fwdtransforms ) wptsi <- antsApplyTransformsToPoints( dim = 2, points = wpts, transformlist = mytx$invtransforms ) # close to pts ## Not run: fixed <- antsImageRead(getANTsRData("r16"), 2) moving <- antsImageRead(getANTsRData("r64"), 2) fpts <- kmeansSegmentation(fixed, 3)$segmentation %>% thresholdImage(1, 1) %>% labelClusters(5) %>% getCentroids(5) wpts <- antsApplyTransformsToPoints( dim = 2, points = fpts, transformlist = mytx$fwdtransforms ) labimgf <- fixed * 0 labimgm <- moving * 0 for (p in 1:nrow(wpts)) { pt <- as.numeric(wpts[p, 1:2]) idx <- round(antsTransformPhysicalPointToIndex(moving, pt)) labimgm[idx[1], idx[2]] <- p pt <- as.numeric(fpts[p, 1:2]) idx <- round(antsTransformPhysicalPointToIndex(fixed, pt)) labimgf[idx[1], idx[2]] <- p } plot(fixed, labimgf %>% iMath("GD", 2)) plot(moving, labimgm %>% iMath("GD", 2)) ## End(Not run)
Calculate the mean of a list of antsImages
antsAverageImages(imageList, normalize = FALSE, weights, verbose = TRUE)antsAverageImages(imageList, normalize = FALSE, weights, verbose = TRUE)
imageList |
list of antsImages or a character vector of filenames |
normalize |
boolean determines if image is divided by mean before averaging |
weights |
a vector of weights of length equal to imageList |
verbose |
print a progress bar |
Avants BB, Pustina D
f1 <- getANTsRData("r16") f2 <- getANTsRData("r64") r16 <- antsImageRead(f1) r64 <- antsImageRead(f2) mylist <- list(r16, r64) antsAverageImages(mylist) bad <- resampleImage(r16, c(2, 2), useVoxels = FALSE) antsAverageImages(mylist, normalize = TRUE) antsAverageImages(c(f1, f2)) testthat::expect_error(antsAverageImages(list(f1, ""))) testthat::expect_error(antsAverageImages(list(r64, bad))) diff_size <- as.antsImage(r64[1:10, 1:10], ref = r64) testthat::expect_error(antsAverageImages(list(r64, diff_size)))f1 <- getANTsRData("r16") f2 <- getANTsRData("r64") r16 <- antsImageRead(f1) r64 <- antsImageRead(f2) mylist <- list(r16, r64) antsAverageImages(mylist) bad <- resampleImage(r16, c(2, 2), useVoxels = FALSE) antsAverageImages(mylist, normalize = TRUE) antsAverageImages(c(f1, f2)) testthat::expect_error(antsAverageImages(list(f1, ""))) testthat::expect_error(antsAverageImages(list(r64, bad))) diff_size <- as.antsImage(r64[1:10, 1:10], ref = r64) testthat::expect_error(antsAverageImages(list(r64, diff_size)))
An implementation of a network analysis framework for BOLD data. We expect that you mapped a label image ( e.g. aal ) to the 3D BOLD space. We build a network and graph metrics from this image and these labels based on the user-defined graph density level.
antsBOLDNetworkAnalysis( bold = NULL, mask = NULL, labels = NULL, motion, gdens = 0.2, threshLo = 1, threshHi = 90, freqLo = 0.01, freqHi = 0.1, winsortrim = 0.02, throwaway )antsBOLDNetworkAnalysis( bold = NULL, mask = NULL, labels = NULL, motion, gdens = 0.2, threshLo = 1, threshHi = 90, freqLo = 0.01, freqHi = 0.1, winsortrim = 0.02, throwaway )
bold |
input 4D image |
mask |
antsImage defines areas of interest |
labels |
antsImage defines regions of interest ie a parcellation |
motion |
motion parameters - if missing, will estimate from data |
gdens |
graph density applied to network covariance matrix |
threshLo |
lower threshold for the label image |
threshHi |
upper threshold for the label image |
freqLo |
lower frequency cutoff |
freqHi |
upper frequency cutoff |
winsortrim |
winsorize the bold signal by these values eg 0.02 |
throwaway |
this number of initial bold volumes |
list of outputs
BB Avants
# none yet - this is not very well tested with recent ANTsR ## Not run: myimg <- antsImageRead(getANTsRData("ch2"), 3) mylab <- antsImageRead(getANTsRData("ch2a"), 3) boldfn <- getANTsRData("pcasl") bold <- antsImageRead(boldfn, 4) avgbold <- getAverageOfTimeSeries(bold) breg <- antsRegistration(avgbold, myimg, typeofTransform = c("AffineFast")) warpedParcellation <- antsApplyTransforms(avgbold, mylab, transformlist = breg$fwdtransforms, interpolator = "NearestNeighbor" ) mask <- getMask(avgbold) warpedParcellation <- maskImage(warpedParcellation, img.mask = mask) old <- NA labels <- warpedParcellation gdens <- 0.2 threshLo <- 1 threshHi <- 90 freqLo <- 0.01 freqHi <- 0.1 winsortrim <- 0.02 result <- antsBOLDNetworkAnalysis(bold = bold, mask = mask, warpedParcellation) ## End(Not run)# none yet - this is not very well tested with recent ANTsR ## Not run: myimg <- antsImageRead(getANTsRData("ch2"), 3) mylab <- antsImageRead(getANTsRData("ch2a"), 3) boldfn <- getANTsRData("pcasl") bold <- antsImageRead(boldfn, 4) avgbold <- getAverageOfTimeSeries(bold) breg <- antsRegistration(avgbold, myimg, typeofTransform = c("AffineFast")) warpedParcellation <- antsApplyTransforms(avgbold, mylab, transformlist = breg$fwdtransforms, interpolator = "NearestNeighbor" ) mask <- getMask(avgbold) warpedParcellation <- maskImage(warpedParcellation, img.mask = mask) old <- NA labels <- warpedParcellation gdens <- 0.2 threshLo <- 1 threshHi <- 90 freqLo <- 0.01 freqHi <- 0.1 winsortrim <- 0.02 result <- antsBOLDNetworkAnalysis(bold = bold, mask = mask, warpedParcellation) ## End(Not run)
call this to get the compilation flags used for ants and dependent software
antsCompileFlags()antsCompileFlags()
Avants BB
antsCompileFlags()antsCompileFlags()
Copy origin, direction, and spacing from one antsImage to another
antsCopyImageInfo(reference, target)antsCopyImageInfo(reference, target)
reference |
image object of S4 class |
target |
image object of S4 class |
Target image with reference header information.
img <- makeImage(c(10, 10), rnorm(100)) img2 <- makeImage(c(10, 10), rnorm(100)) img2 <- antsCopyImageInfo(img, img2) testthat::expect_error(antsCopyImageInfo(img, 1))img <- makeImage(c(10, 10), rnorm(100)) img2 <- makeImage(c(10, 10), rnorm(100)) img2 <- antsCopyImageInfo(img, img2) testthat::expect_error(antsCopyImageInfo(img, 1))
Copy origin, direction, and spacing from one antsImage to another.
Opposite order of input relative to antsCopyImageInfo
antsCopyImageInfo2(target, reference)antsCopyImageInfo2(target, reference)
target |
image object of S4 class |
reference |
image object of S4 class |
Target image with reference header information.
img <- makeImage(c(10, 10), rnorm(100)) img2 <- makeImage(c(10, 10), rnorm(100)) img2 <- antsCopyImageInfo(img2, img) testthat::expect_error(antsCopyImageInfo(img, 1))img <- makeImage(c(10, 10), rnorm(100)) img2 <- makeImage(c(10, 10), rnorm(100)) img2 <- antsCopyImageInfo(img2, img) testthat::expect_error(antsCopyImageInfo(img, 1))
call this to get the binary paths to ANTs executables.
antsDir()antsDir()
Avants BB
antsDir()antsDir()
C++ type used to represent an ITK image pointed to by 'pointer'. the actual image is of C++ type 'itk::image< pixeltype , dimension >::Pointer'
## S4 method for signature 'antsImage' show(object) ## S4 method for signature 'antsImage' initialize( .Object, pixeltype = "float", dimension = 3, components = 1, isVector = FALSE, filename = "" )## S4 method for signature 'antsImage' show(object) ## S4 method for signature 'antsImage' initialize( .Object, pixeltype = "float", dimension = 3, components = 1, isVector = FALSE, filename = "" )
object |
input object to convert |
.Object |
input object to convert |
pixeltype |
usually float, can be other types unsigned char, int, double etc noting that short is not supported |
dimension |
usually 2 or 3 but can be 4 |
components |
number of pixel components |
isVector |
logical indicator of the image is a vector |
filename |
character filename if the data was read in, otherwise "" |
pixeltypeusually float, can be other types unsigned char, int, double etc noting that short is not supported
dimensionusually 2 or 3 but can be 4
componentsnumber of pixel components
pointerthe memory location
isVectorlogical indicator of the image is a vector
filenamecharacter filename if the data was read in, otherwise ""
pixeltypeusually float, can be other types unsigned char, int, double etc noting that short is not supported
dimensionusually 2 or 3 but can be 4
componentsnumber of pixel components
isVectorboolean
filenamecharacter filename if the data was read in, otherwise ""
Overloaded math for antsImage objects
## S4 method for signature 'antsImage' Math(x) ## S4 method for signature 'antsImage' abs(x) ## S4 method for signature 'antsImage' sign(x) ## S4 method for signature 'antsImage' sqrt(x) ## S4 method for signature 'antsImage' ceiling(x) ## S4 method for signature 'antsImage' round(x) ## S4 method for signature 'antsImage' floor(x) ## S4 method for signature 'antsImage' trunc(x) ## S4 method for signature 'antsImage' log(x, base = exp(1)) ## S4 method for signature 'antsImage' log10(x) ## S4 method for signature 'antsImage' log2(x) ## S4 method for signature 'antsImage' acos(x) ## S4 method for signature 'antsImage' asin(x) ## S4 method for signature 'antsImage' atan(x) ## S4 method for signature 'antsImage' acosh(x) ## S4 method for signature 'antsImage' asinh(x) ## S4 method for signature 'antsImage' atanh(x) ## S4 method for signature 'antsImage' cos(x) ## S4 method for signature 'antsImage' sin(x) ## S4 method for signature 'antsImage' tan(x) ## S4 method for signature 'antsImage' cosh(x) ## S4 method for signature 'antsImage' sinh(x) ## S4 method for signature 'antsImage' tanh(x) ## S4 method for signature 'antsImage' cospi(x) ## S4 method for signature 'antsImage' sinpi(x) ## S4 method for signature 'antsImage' tanpi(x) ## S4 method for signature 'antsImage' exp(x) ## S4 method for signature 'antsImage' gamma(x) ## S4 method for signature 'antsImage' lgamma(x) ## S4 method for signature 'antsImage' !x## S4 method for signature 'antsImage' Math(x) ## S4 method for signature 'antsImage' abs(x) ## S4 method for signature 'antsImage' sign(x) ## S4 method for signature 'antsImage' sqrt(x) ## S4 method for signature 'antsImage' ceiling(x) ## S4 method for signature 'antsImage' round(x) ## S4 method for signature 'antsImage' floor(x) ## S4 method for signature 'antsImage' trunc(x) ## S4 method for signature 'antsImage' log(x, base = exp(1)) ## S4 method for signature 'antsImage' log10(x) ## S4 method for signature 'antsImage' log2(x) ## S4 method for signature 'antsImage' acos(x) ## S4 method for signature 'antsImage' asin(x) ## S4 method for signature 'antsImage' atan(x) ## S4 method for signature 'antsImage' acosh(x) ## S4 method for signature 'antsImage' asinh(x) ## S4 method for signature 'antsImage' atanh(x) ## S4 method for signature 'antsImage' cos(x) ## S4 method for signature 'antsImage' sin(x) ## S4 method for signature 'antsImage' tan(x) ## S4 method for signature 'antsImage' cosh(x) ## S4 method for signature 'antsImage' sinh(x) ## S4 method for signature 'antsImage' tanh(x) ## S4 method for signature 'antsImage' cospi(x) ## S4 method for signature 'antsImage' sinpi(x) ## S4 method for signature 'antsImage' tanpi(x) ## S4 method for signature 'antsImage' exp(x) ## S4 method for signature 'antsImage' gamma(x) ## S4 method for signature 'antsImage' lgamma(x) ## S4 method for signature 'antsImage' !x
x |
is an object of class |
base |
a positive or complex number: the base with respect to which logarithms are computed. Defaults to e=exp(1). |
img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_true(is.antsImage(abs(img01))) testthat::expect_true(is.antsImage(sign(img01))) testthat::expect_true(is.antsImage(sqrt(img01))) testthat::expect_true(is.antsImage(ceiling(img01))) testthat::expect_true(is.antsImage(floor(img01))) testthat::expect_true(is.antsImage(trunc(img01))) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_true(is.antsImage(log(img01))) testthat::expect_true(is.antsImage(exp(img01))) testthat::expect_true(is.antsImage(log(img01, base = exp(1)))) testthat::expect_true(is.antsImage(log(img01, base = 2))) testthat::expect_true(is.antsImage(log(img01, base = 10))) testthat::expect_true(is.antsImage(log10(img01))) testthat::expect_true(is.antsImage(log2(img01))) testthat::expect_true(is.antsImage(gamma(img01))) testthat::expect_true(is.antsImage(lgamma(img01))) testthat::expect_true(is.antsImage(cos(img01))) testthat::expect_true(is.antsImage(cospi(img01))) testthat::expect_true(is.antsImage(acos(img01))) testthat::expect_true(is.antsImage(acosh(img01))) testthat::expect_true(is.antsImage(sin(img01))) testthat::expect_true(is.antsImage(sinpi(img01))) testthat::expect_true(is.antsImage(asin(img01))) testthat::expect_true(is.antsImage(asinh(img01))) testthat::expect_true(is.antsImage(tan(img01))) testthat::expect_true(is.antsImage(tanpi(img01))) testthat::expect_true(is.antsImage(atan(img01))) testthat::expect_true(is.antsImage(atanh(img01)))img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_true(is.antsImage(abs(img01))) testthat::expect_true(is.antsImage(sign(img01))) testthat::expect_true(is.antsImage(sqrt(img01))) testthat::expect_true(is.antsImage(ceiling(img01))) testthat::expect_true(is.antsImage(floor(img01))) testthat::expect_true(is.antsImage(trunc(img01))) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_true(is.antsImage(log(img01))) testthat::expect_true(is.antsImage(exp(img01))) testthat::expect_true(is.antsImage(log(img01, base = exp(1)))) testthat::expect_true(is.antsImage(log(img01, base = 2))) testthat::expect_true(is.antsImage(log(img01, base = 10))) testthat::expect_true(is.antsImage(log10(img01))) testthat::expect_true(is.antsImage(log2(img01))) testthat::expect_true(is.antsImage(gamma(img01))) testthat::expect_true(is.antsImage(lgamma(img01))) testthat::expect_true(is.antsImage(cos(img01))) testthat::expect_true(is.antsImage(cospi(img01))) testthat::expect_true(is.antsImage(acos(img01))) testthat::expect_true(is.antsImage(acosh(img01))) testthat::expect_true(is.antsImage(sin(img01))) testthat::expect_true(is.antsImage(sinpi(img01))) testthat::expect_true(is.antsImage(asin(img01))) testthat::expect_true(is.antsImage(asinh(img01))) testthat::expect_true(is.antsImage(tan(img01))) testthat::expect_true(is.antsImage(tanpi(img01))) testthat::expect_true(is.antsImage(atan(img01))) testthat::expect_true(is.antsImage(atanh(img01)))
Overloaded operators for antsImage objects
## S4 method for signature 'antsImage,antsImage' Arith(e1, e2) ## S4 method for signature 'antsImage,antsImage' e1 + e2 ## S4 method for signature 'antsImage,antsImage' e1 - e2 ## S4 method for signature 'antsImage,antsImage' e1 * e2 ## S4 method for signature 'antsImage,antsImage' e1 / e2 ## S4 method for signature 'antsImage,antsImage' e1 ^ e2 ## S4 method for signature 'antsImage,antsImage' e1 %% e2 ## S4 method for signature 'antsImage,antsImage' e1 %/% e2 ## S4 method for signature 'antsImage,numeric' Arith(e1, e2) ## S4 method for signature 'antsImage,numeric' e1 + e2 ## S4 method for signature 'antsImage,numeric' e1 - e2 ## S4 method for signature 'antsImage,numeric' e1 * e2 ## S4 method for signature 'antsImage,numeric' e1 / e2 ## S4 method for signature 'antsImage,numeric' e1 ^ e2 ## S4 method for signature 'antsImage,numeric' e1 %% e2 ## S4 method for signature 'antsImage,numeric' e1 %/% e2 ## S4 method for signature 'numeric,antsImage' e1 + e2 ## S4 method for signature 'numeric,antsImage' e1 - e2 ## S4 method for signature 'numeric,antsImage' e1 * e2 ## S4 method for signature 'numeric,antsImage' e1 / e2 ## S4 method for signature 'numeric,antsImage' e1 ^ e2 ## S4 method for signature 'numeric,antsImage' e1 %% e2 ## S4 method for signature 'numeric,antsImage' e1 %/% e2 ## S4 method for signature 'antsImage,missing' Arith(e1, e2) ## S4 method for signature 'numeric,antsImage' Arith(e1, e2) ## S4 method for signature 'antsImage,logical' Arith(e1, e2) ## S4 method for signature 'logical,antsImage' Arith(e1, e2) ## S4 method for signature 'antsImage,array' Arith(e1, e2) ## S4 method for signature 'array,antsImage' Arith(e1, e2) ## S4 method for signature 'list,antsImage' Arith(e1, e2) ## S4 method for signature 'antsImage,list' Arith(e1, e2) ## S4 method for signature 'antsImage,antsImage' e1 == e2 ## S4 method for signature 'antsImage,list' e1 == e2 ## S4 method for signature 'antsImage,array' e1 == e2 ## S4 method for signature 'array,antsImage' e1 == e2 ## S4 method for signature 'antsImage,ANY' e1 == e2 ## S4 method for signature 'ANY,antsImage' e1 == e2 ## S4 method for signature 'antsImage,antsImage' e1 > e2 ## S4 method for signature 'antsImage,list' e1 > e2 ## S4 method for signature 'antsImage,array' e1 > e2 ## S4 method for signature 'array,antsImage' e1 > e2 ## S4 method for signature 'antsImage,ANY' e1 > e2 ## S4 method for signature 'ANY,antsImage' e1 > e2 ## S4 method for signature 'antsImage,antsImage' e1 < e2 ## S4 method for signature 'antsImage,list' e1 < e2 ## S4 method for signature 'antsImage,array' e1 < e2 ## S4 method for signature 'array,antsImage' e1 < e2 ## S4 method for signature 'antsImage,ANY' e1 < e2 ## S4 method for signature 'ANY,antsImage' e1 < e2 ## S4 method for signature 'antsImage,antsImage' e1 != e2 ## S4 method for signature 'antsImage,list' e1 != e2 ## S4 method for signature 'antsImage,array' e1 != e2 ## S4 method for signature 'array,antsImage' e1 != e2 ## S4 method for signature 'antsImage,ANY' e1 != e2 ## S4 method for signature 'ANY,antsImage' e1 != e2 ## S4 method for signature 'antsImage,antsImage' e1 <= e2 ## S4 method for signature 'antsImage,list' e1 <= e2 ## S4 method for signature 'antsImage,array' e1 <= e2 ## S4 method for signature 'array,antsImage' e1 <= e2 ## S4 method for signature 'antsImage,ANY' e1 <= e2 ## S4 method for signature 'ANY,antsImage' e1 <= e2 ## S4 method for signature 'antsImage,antsImage' e1 >= e2 ## S4 method for signature 'antsImage,list' e1 >= e2 ## S4 method for signature 'antsImage,array' e1 >= e2 ## S4 method for signature 'array,antsImage' e1 >= e2 ## S4 method for signature 'antsImage,ANY' e1 >= e2 ## S4 method for signature 'ANY,antsImage' e1 >= e2 ## S4 method for signature 'antsImage,antsImage' e1 & e2 ## S4 method for signature 'antsImage,antsImage' e1 | e2 ## S4 method for signature 'antsImage,array' Logic(e1, e2) ## S4 method for signature 'array,antsImage' Logic(e1, e2) ## S4 method for signature 'antsImage,logical' e1 & e2 ## S4 method for signature 'antsImage,logical' e1 | e2 ## S4 method for signature 'logical,antsImage' Logic(e1, e2) ## S4 method for signature 'antsImage,numeric' Logic(e1, e2) ## S4 method for signature 'numeric,antsImage' Logic(e1, e2) ## S4 method for signature 'antsImage,ANY' Logic(e1, e2) ## S4 method for signature 'ANY,antsImage' Logic(e1, e2) ## S4 method for signature 'list,antsImage' Logic(e1, e2) ## S4 method for signature 'antsImage,list' Logic(e1, e2) ## S4 method for signature 'antsImage' is.na(x) ## S4 method for signature 'antsImage' anyNA(x, recursive = FALSE) ## S4 method for signature 'antsImage' is.nan(x) ## S4 method for signature 'antsImage' is.infinite(x) ## S4 method for signature 'antsImage' is.finite(x) ## S4 method for signature 'antsImage' which(x, arr.ind = FALSE, useNames = TRUE)## S4 method for signature 'antsImage,antsImage' Arith(e1, e2) ## S4 method for signature 'antsImage,antsImage' e1 + e2 ## S4 method for signature 'antsImage,antsImage' e1 - e2 ## S4 method for signature 'antsImage,antsImage' e1 * e2 ## S4 method for signature 'antsImage,antsImage' e1 / e2 ## S4 method for signature 'antsImage,antsImage' e1 ^ e2 ## S4 method for signature 'antsImage,antsImage' e1 %% e2 ## S4 method for signature 'antsImage,antsImage' e1 %/% e2 ## S4 method for signature 'antsImage,numeric' Arith(e1, e2) ## S4 method for signature 'antsImage,numeric' e1 + e2 ## S4 method for signature 'antsImage,numeric' e1 - e2 ## S4 method for signature 'antsImage,numeric' e1 * e2 ## S4 method for signature 'antsImage,numeric' e1 / e2 ## S4 method for signature 'antsImage,numeric' e1 ^ e2 ## S4 method for signature 'antsImage,numeric' e1 %% e2 ## S4 method for signature 'antsImage,numeric' e1 %/% e2 ## S4 method for signature 'numeric,antsImage' e1 + e2 ## S4 method for signature 'numeric,antsImage' e1 - e2 ## S4 method for signature 'numeric,antsImage' e1 * e2 ## S4 method for signature 'numeric,antsImage' e1 / e2 ## S4 method for signature 'numeric,antsImage' e1 ^ e2 ## S4 method for signature 'numeric,antsImage' e1 %% e2 ## S4 method for signature 'numeric,antsImage' e1 %/% e2 ## S4 method for signature 'antsImage,missing' Arith(e1, e2) ## S4 method for signature 'numeric,antsImage' Arith(e1, e2) ## S4 method for signature 'antsImage,logical' Arith(e1, e2) ## S4 method for signature 'logical,antsImage' Arith(e1, e2) ## S4 method for signature 'antsImage,array' Arith(e1, e2) ## S4 method for signature 'array,antsImage' Arith(e1, e2) ## S4 method for signature 'list,antsImage' Arith(e1, e2) ## S4 method for signature 'antsImage,list' Arith(e1, e2) ## S4 method for signature 'antsImage,antsImage' e1 == e2 ## S4 method for signature 'antsImage,list' e1 == e2 ## S4 method for signature 'antsImage,array' e1 == e2 ## S4 method for signature 'array,antsImage' e1 == e2 ## S4 method for signature 'antsImage,ANY' e1 == e2 ## S4 method for signature 'ANY,antsImage' e1 == e2 ## S4 method for signature 'antsImage,antsImage' e1 > e2 ## S4 method for signature 'antsImage,list' e1 > e2 ## S4 method for signature 'antsImage,array' e1 > e2 ## S4 method for signature 'array,antsImage' e1 > e2 ## S4 method for signature 'antsImage,ANY' e1 > e2 ## S4 method for signature 'ANY,antsImage' e1 > e2 ## S4 method for signature 'antsImage,antsImage' e1 < e2 ## S4 method for signature 'antsImage,list' e1 < e2 ## S4 method for signature 'antsImage,array' e1 < e2 ## S4 method for signature 'array,antsImage' e1 < e2 ## S4 method for signature 'antsImage,ANY' e1 < e2 ## S4 method for signature 'ANY,antsImage' e1 < e2 ## S4 method for signature 'antsImage,antsImage' e1 != e2 ## S4 method for signature 'antsImage,list' e1 != e2 ## S4 method for signature 'antsImage,array' e1 != e2 ## S4 method for signature 'array,antsImage' e1 != e2 ## S4 method for signature 'antsImage,ANY' e1 != e2 ## S4 method for signature 'ANY,antsImage' e1 != e2 ## S4 method for signature 'antsImage,antsImage' e1 <= e2 ## S4 method for signature 'antsImage,list' e1 <= e2 ## S4 method for signature 'antsImage,array' e1 <= e2 ## S4 method for signature 'array,antsImage' e1 <= e2 ## S4 method for signature 'antsImage,ANY' e1 <= e2 ## S4 method for signature 'ANY,antsImage' e1 <= e2 ## S4 method for signature 'antsImage,antsImage' e1 >= e2 ## S4 method for signature 'antsImage,list' e1 >= e2 ## S4 method for signature 'antsImage,array' e1 >= e2 ## S4 method for signature 'array,antsImage' e1 >= e2 ## S4 method for signature 'antsImage,ANY' e1 >= e2 ## S4 method for signature 'ANY,antsImage' e1 >= e2 ## S4 method for signature 'antsImage,antsImage' e1 & e2 ## S4 method for signature 'antsImage,antsImage' e1 | e2 ## S4 method for signature 'antsImage,array' Logic(e1, e2) ## S4 method for signature 'array,antsImage' Logic(e1, e2) ## S4 method for signature 'antsImage,logical' e1 & e2 ## S4 method for signature 'antsImage,logical' e1 | e2 ## S4 method for signature 'logical,antsImage' Logic(e1, e2) ## S4 method for signature 'antsImage,numeric' Logic(e1, e2) ## S4 method for signature 'numeric,antsImage' Logic(e1, e2) ## S4 method for signature 'antsImage,ANY' Logic(e1, e2) ## S4 method for signature 'ANY,antsImage' Logic(e1, e2) ## S4 method for signature 'list,antsImage' Logic(e1, e2) ## S4 method for signature 'antsImage,list' Logic(e1, e2) ## S4 method for signature 'antsImage' is.na(x) ## S4 method for signature 'antsImage' anyNA(x, recursive = FALSE) ## S4 method for signature 'antsImage' is.nan(x) ## S4 method for signature 'antsImage' is.infinite(x) ## S4 method for signature 'antsImage' is.finite(x) ## S4 method for signature 'antsImage' which(x, arr.ind = FALSE, useNames = TRUE)
e1 |
is an object of class |
e2 |
is an object of class |
x |
a logical vector or array. |
recursive |
not used |
arr.ind |
logical; should array indices be returned when x is an array? |
useNames |
logical indicating if the value of arrayInd() should have (non-null) dimnames at all. |
Overloading binary operators for antsImage Objects
John Muschellli [email protected]
img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) img02 <- as.antsImage(array(64:1, c(4, 4, 4, 1))) is.antsImage(img01 + img02) is.antsImage(sqrt(2) * img01) is.antsImage(img02 / pi) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) et <- function(x) { testthat::expect_true(x) } x <- is.antsImage(img01 == img01) et(x) x <- is.antsImage(img01 == as.array(img01)) et(x) x <- is.antsImage(img01 == 1) et(x) x <- is.antsImage(1 == img01) et(x) x <- is.antsImage(as.array(img01) == img01) et(x) x <- is.antsImage(img01 >= img01) et(x) x <- is.antsImage(img01 >= as.array(img01)) et(x) x <- is.antsImage(img01 >= 1) et(x) x <- is.antsImage(1 >= img01) et(x) x <- is.antsImage(as.array(img01) >= img01) et(x) x <- is.antsImage(img01 > img01) et(x) x <- is.antsImage(img01 > as.array(img01)) et(x) x <- is.antsImage(img01 > 1) et(x) x <- is.antsImage(1 > img01) et(x) x <- is.antsImage(as.array(img01) > img01) et(x) x <- is.antsImage(img01 < img01) et(x) x <- is.antsImage(img01 < as.array(img01)) et(x) x <- is.antsImage(img01 < 1) et(x) x <- is.antsImage(1 < img01) et(x) x <- is.antsImage(as.array(img01) < img01) et(x) x <- is.antsImage(img01 <= img01) et(x) x <- is.antsImage(img01 <= as.array(img01)) et(x) x <- is.antsImage(1 <= img01) et(x) x <- is.antsImage(img01 <= 1) et(x) x <- is.antsImage(as.array(img01) <= img01) et(x) x <- is.antsImage(img01 != img01) et(x) x <- is.antsImage(img01 != as.array(img01)) et(x) x <- is.antsImage(1 != img01) et(x) x <- is.antsImage(img01 != 1) et(x) x <- is.antsImage(as.array(img01) != img01) et(x) ########################### # Multi image operations ######################## fname <- system.file("extdata", "multi_component_image.nii.gz", package = "ANTsRCore" ) img <- antsImageRead(fname) testthat::expect_is(img > 0, "antsImage") testthat::expect_is(0 < img, "antsImage") testthat::expect_is(img > c(0, 0), "antsImage") testthat::expect_is(img >= 0, "antsImage") testthat::expect_is(0 <= img, "antsImage") testthat::expect_is(img >= c(0, 0), "antsImage") testthat::expect_is(img < 0, "antsImage") testthat::expect_is(0 > img, "antsImage") testthat::expect_is(img < c(0, 0), "antsImage") testthat::expect_is(img <= 0, "antsImage") testthat::expect_is(0 >= img, "antsImage") testthat::expect_is(img <= c(0, 0), "antsImage") testthat::expect_is(img == 0, "antsImage") testthat::expect_is(0 == img, "antsImage") testthat::expect_is(img == c(0, 0), "antsImage") testthat::expect_is(img != 0, "antsImage") testthat::expect_is(0 != img, "antsImage") testthat::expect_is(img != c(0, 0), "antsImage") img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 == list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 > list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 < list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 != list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 <= list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 >= list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) mask1 <- img01 == 1 mask2 <- img01 == 2 testthat::expect_true(is.antsImage(mask1)) testthat::expect_true(is.antsImage(mask2)) testthat::expect_true(is.antsImage(mask1 & mask2)) testthat::expect_true(is.antsImage(mask1 | mask2)) testthat::expect_true(is.antsImage(as.array(mask2) | mask1)) testthat::expect_true(is.antsImage(as.array(mask2) & mask1)) testthat::expect_true(is.antsImage(mask2 | as.array(mask1))) testthat::expect_true(is.antsImage(mask2 & as.array(mask1))) testthat::expect_true(is.antsImage(mask2 | 1)) testthat::expect_true(is.antsImage(mask2 | TRUE)) testthat::expect_true(is.antsImage(mask2 & 1)) testthat::expect_true(is.antsImage(mask2 & TRUE)) img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 which(mask) which(mask, arr.ind = TRUE)img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) img02 <- as.antsImage(array(64:1, c(4, 4, 4, 1))) is.antsImage(img01 + img02) is.antsImage(sqrt(2) * img01) is.antsImage(img02 / pi) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) et <- function(x) { testthat::expect_true(x) } x <- is.antsImage(img01 == img01) et(x) x <- is.antsImage(img01 == as.array(img01)) et(x) x <- is.antsImage(img01 == 1) et(x) x <- is.antsImage(1 == img01) et(x) x <- is.antsImage(as.array(img01) == img01) et(x) x <- is.antsImage(img01 >= img01) et(x) x <- is.antsImage(img01 >= as.array(img01)) et(x) x <- is.antsImage(img01 >= 1) et(x) x <- is.antsImage(1 >= img01) et(x) x <- is.antsImage(as.array(img01) >= img01) et(x) x <- is.antsImage(img01 > img01) et(x) x <- is.antsImage(img01 > as.array(img01)) et(x) x <- is.antsImage(img01 > 1) et(x) x <- is.antsImage(1 > img01) et(x) x <- is.antsImage(as.array(img01) > img01) et(x) x <- is.antsImage(img01 < img01) et(x) x <- is.antsImage(img01 < as.array(img01)) et(x) x <- is.antsImage(img01 < 1) et(x) x <- is.antsImage(1 < img01) et(x) x <- is.antsImage(as.array(img01) < img01) et(x) x <- is.antsImage(img01 <= img01) et(x) x <- is.antsImage(img01 <= as.array(img01)) et(x) x <- is.antsImage(1 <= img01) et(x) x <- is.antsImage(img01 <= 1) et(x) x <- is.antsImage(as.array(img01) <= img01) et(x) x <- is.antsImage(img01 != img01) et(x) x <- is.antsImage(img01 != as.array(img01)) et(x) x <- is.antsImage(1 != img01) et(x) x <- is.antsImage(img01 != 1) et(x) x <- is.antsImage(as.array(img01) != img01) et(x) ########################### # Multi image operations ######################## fname <- system.file("extdata", "multi_component_image.nii.gz", package = "ANTsRCore" ) img <- antsImageRead(fname) testthat::expect_is(img > 0, "antsImage") testthat::expect_is(0 < img, "antsImage") testthat::expect_is(img > c(0, 0), "antsImage") testthat::expect_is(img >= 0, "antsImage") testthat::expect_is(0 <= img, "antsImage") testthat::expect_is(img >= c(0, 0), "antsImage") testthat::expect_is(img < 0, "antsImage") testthat::expect_is(0 > img, "antsImage") testthat::expect_is(img < c(0, 0), "antsImage") testthat::expect_is(img <= 0, "antsImage") testthat::expect_is(0 >= img, "antsImage") testthat::expect_is(img <= c(0, 0), "antsImage") testthat::expect_is(img == 0, "antsImage") testthat::expect_is(0 == img, "antsImage") testthat::expect_is(img == c(0, 0), "antsImage") testthat::expect_is(img != 0, "antsImage") testthat::expect_is(0 != img, "antsImage") testthat::expect_is(img != c(0, 0), "antsImage") img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 == list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 > list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 < list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 != list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 <= list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) testthat::expect_error(img01 >= list()) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) mask1 <- img01 == 1 mask2 <- img01 == 2 testthat::expect_true(is.antsImage(mask1)) testthat::expect_true(is.antsImage(mask2)) testthat::expect_true(is.antsImage(mask1 & mask2)) testthat::expect_true(is.antsImage(mask1 | mask2)) testthat::expect_true(is.antsImage(as.array(mask2) | mask1)) testthat::expect_true(is.antsImage(as.array(mask2) & mask1)) testthat::expect_true(is.antsImage(mask2 | as.array(mask1))) testthat::expect_true(is.antsImage(mask2 & as.array(mask1))) testthat::expect_true(is.antsImage(mask2 | 1)) testthat::expect_true(is.antsImage(mask2 | TRUE)) testthat::expect_true(is.antsImage(mask2 & 1)) testthat::expect_true(is.antsImage(mask2 & TRUE)) img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 which(mask) which(mask, arr.ind = TRUE)
Overloaded Summary for antsImage objects
## S4 method for signature 'antsImage' Summary(x, ..., mask = NULL, na.rm = FALSE) max(x, ..., na.rm = FALSE) min(x, ..., na.rm = FALSE) ## S4 method for signature 'antsImage' min(x, ..., mask = NULL, na.rm = FALSE) ## S4 method for signature 'antsImage' max(x, ..., mask = NULL, na.rm = FALSE) range(x, ..., na.rm = FALSE) prod(x, ..., na.rm = FALSE) sum(x, ..., na.rm = FALSE) any(x, ..., na.rm = FALSE) all(x, ..., na.rm = FALSE)## S4 method for signature 'antsImage' Summary(x, ..., mask = NULL, na.rm = FALSE) max(x, ..., na.rm = FALSE) min(x, ..., na.rm = FALSE) ## S4 method for signature 'antsImage' min(x, ..., mask = NULL, na.rm = FALSE) ## S4 method for signature 'antsImage' max(x, ..., mask = NULL, na.rm = FALSE) range(x, ..., na.rm = FALSE) prod(x, ..., na.rm = FALSE) sum(x, ..., na.rm = FALSE) any(x, ..., na.rm = FALSE) all(x, ..., na.rm = FALSE)
x |
is an object of class |
... |
further arguments passed to summary methods |
mask |
binary mask of values to subset |
na.rm |
logical: should missing values be removed? |
vec <- 1:64 img01 <- as.antsImage(array(vec, c(4, 4, 4, 1))) testthat::expect_equal(max(img01), max(vec)) max(img01) testthat::expect_equal(min(img01), min(vec)) min(img01) testthat::expect_equal(sum(img01), sum(vec)) range(img01) testthat::expect_equal(range(img01), range(vec)) prod(img01 / 25) testthat::expect_equal(prod(img01 / 25), prod(vec / 25), tolerance = 1e-5)vec <- 1:64 img01 <- as.antsImage(array(vec, c(4, 4, 4, 1))) testthat::expect_equal(max(img01), max(vec)) max(img01) testthat::expect_equal(min(img01), min(vec)) min(img01) testthat::expect_equal(sum(img01), sum(vec)) range(img01) testthat::expect_equal(range(img01), range(vec)) prod(img01 / 25) testthat::expect_equal(prod(img01 / 25), prod(vec / 25), tolerance = 1e-5)
antsImage.Clone an image object of S4 class antsImage. N.B.: You cannot use
a <- img because the R assignment operator does not deal with the underlying
C++ pointers.
antsImageClone(in_image, out_pixeltype = in_image@pixeltype)antsImageClone(in_image, out_pixeltype = in_image@pixeltype)
in_image |
image object of S4 class |
out_pixeltype |
C++ datatype to be used to represent the pixels in the
output image. Allowed values: |
object of class antsImage
Shrinidhi KL
img <- antsImageRead(getANTsRData("r16"), 2) img2 <- antsImageClone(img) img.int <- antsImageClone(img, "unsigned int") multi <- antsImageRead(getANTsRData("multi_component_image")) img <- antsImageRead(getANTsRData("r16"), 2) m2 <- antsImageClone(multi)img <- antsImageRead(getANTsRData("r16"), 2) img2 <- antsImageClone(img) img.int <- antsImageClone(img, "unsigned int") multi <- antsImageRead(getANTsRData("multi_component_image")) img <- antsImageRead(getANTsRData("r16"), 2) m2 <- antsImageClone(multi)
Get and set methods for image header information
antsGetSpacing(x) antsSetSpacing(x, spacing) antsGetOrigin(x) antsSetOrigin(x, origin) antsGetDirection(x) antsSetDirection(x, direction)antsGetSpacing(x) antsSetSpacing(x, spacing) antsGetOrigin(x) antsSetOrigin(x, origin) antsGetDirection(x) antsSetDirection(x, direction)
x |
antsImage to access, of dimensionality |
spacing |
numeric vector of length |
origin |
numeric vector of length |
direction |
matrix of size |
For get methods, vector of length d (origin, spacing) or matrix of size d * d (direction).
For set methods, 0 to indicate success.
img <- makeImage(c(5, 5), rnorm(25)) antsGetSpacing(img) antsSetSpacing(img, c(2.0, 2.0)) antsGetOrigin(img) antsSetOrigin(img, c(0.5, 0.5)) img <- makeImage(c(5, 5), rnorm(25)) antsGetDirection(img) testthat::expect_error(antsGetDirection(as.array(img))) outimg <- makeImage(c(5, 5), rnorm(25)) antsGetDirection(outimg) direct <- antsGetDirection(outimg) antsSetDirection(outimg, direct) testthat::expect_error(antsSetDirection(as.array(outimg), direct)) testthat::expect_error(antsSetDirection(outimg, as.numeric(direct))) testthat::expect_error(antsSetDirection(outimg, diag(length(dim(outimg)) + 1)))img <- makeImage(c(5, 5), rnorm(25)) antsGetSpacing(img) antsSetSpacing(img, c(2.0, 2.0)) antsGetOrigin(img) antsSetOrigin(img, c(0.5, 0.5)) img <- makeImage(c(5, 5), rnorm(25)) antsGetDirection(img) testthat::expect_error(antsGetDirection(as.array(img))) outimg <- makeImage(c(5, 5), rnorm(25)) antsGetDirection(outimg) direct <- antsGetDirection(outimg) antsSetDirection(outimg, direct) testthat::expect_error(antsSetDirection(as.array(outimg), direct)) testthat::expect_error(antsSetDirection(outimg, as.numeric(direct))) testthat::expect_error(antsSetDirection(outimg, diag(length(dim(outimg)) + 1)))
Read file info from image header
antsImageHeaderInfo(filename)antsImageHeaderInfo(filename)
filename |
name of image file to scan for info |
outputs a list containing:
Type of pixel (scalar, vector, etc).
Type of pixel values (int, float, etc).
Number of image dimensions.
Number of pixel dimensions.
Size of image dimensions.
Pixel resolution.
Spatial origin of image
Spatial directions of image axes.
Duda JT
antsImageHeaderInfo(getANTsRData("r16")) img <- antsImageRead(getANTsRData("r16")) antsImageHeaderInfo(img) antsImageHeaderInfo(getANTsRData("r16")) testthat::expect_error(antsImageHeaderInfo(""))antsImageHeaderInfo(getANTsRData("r16")) img <- antsImageRead(getANTsRData("r16")) antsImageHeaderInfo(img) antsImageHeaderInfo(getANTsRData("r16")) testthat::expect_error(antsImageHeaderInfo(""))
Get image iterator
antsImageIterator(x)antsImageIterator(x)
x |
antsImage |
antsImageIterator
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img)img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img)
C++ type used to represent an ITK image iterator. the actual iterator is of C++ type 'itk::ImageRegionIteratorWithIndex< itk::image< pixeltype, dimension > >'
## S4 method for signature 'antsImageIterator' show(object) ## S4 method for signature 'antsImageIterator' initialize(.Object, pixeltype = "float", dimension = 3, components = 1)## S4 method for signature 'antsImageIterator' show(object) ## S4 method for signature 'antsImageIterator' initialize(.Object, pixeltype = "float", dimension = 3, components = 1)
object |
input object to convert |
.Object |
input object to convert |
pixeltype |
string e.g. "float" "unsigned char" "int" |
dimension |
dimensionality of the image |
components |
number of components per pixel |
pixeltypeusually float, can be other types unsigned char, int, double etc noting that short is not supported
dimensionusually 2 or 3 but can be 4
componentsnumber of pixel components, currently only 1 is suppored
pointerto the memory location of the itk object
Get value at current position
antsImageIteratorGet(x)antsImageIteratorGet(x)
x |
antsImageIterator |
pixel value
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) value <- antsImageIteratorGet(it)img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) value <- antsImageIteratorGet(it)
Get index at current position
antsImageIteratorGetIndex(x)antsImageIteratorGetIndex(x)
x |
antsImageIterator |
image index
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) index <- antsImageIteratorGetIndex(it)img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) index <- antsImageIteratorGetIndex(it)
move iterator to begining
antsImageIteratorGoToBegin(x)antsImageIteratorGoToBegin(x)
x |
antsImageIterator |
antsImageIterator
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorNext(it) it <- antsImageIteratorGoToBegin(it)img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorNext(it) it <- antsImageIteratorGoToBegin(it)
move iterator to begining of reverse data
antsImageIteratorGoToReverseBegin(x)antsImageIteratorGoToReverseBegin(x)
x |
antsImageIterator |
antsImageIterator
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorGoToReverseBegin(it)img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorGoToReverseBegin(it)
test if iterator is at end of data
antsImageIteratorIsAtEnd(x)antsImageIteratorIsAtEnd(x)
x |
antsImageIterator |
boolean indicating position
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorNext(it) flag <- antsImageIteratorIsAtEnd(it)img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorNext(it) flag <- antsImageIteratorIsAtEnd(it)
test if iterator is at end of reverse data
antsImageIteratorIsAtReverseEnd(x)antsImageIteratorIsAtReverseEnd(x)
x |
antsImageIterator |
boolean indicating position
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorGoToReverseBegin(it) it <- antsImageIteratorPrevious(it) flag <- antsImageIteratorIsAtReverseEnd(it)img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorGoToReverseBegin(it) it <- antsImageIteratorPrevious(it) flag <- antsImageIteratorIsAtReverseEnd(it)
advance iterator forward
antsImageIteratorNext(x)antsImageIteratorNext(x)
x |
antsImageIterator |
antsImageIterator
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorNext(it)img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorNext(it)
advance iterator backward
antsImageIteratorPrevious(x)antsImageIteratorPrevious(x)
x |
antsImageIterator |
antsImageIterator
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorPrevious(it)img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorPrevious(it)
test if iterator is at end of data
antsImageIteratorRemaining(x)antsImageIteratorRemaining(x)
x |
antsImageIterator |
boolean indicating if data remains
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorNext(it) flag <- antsImageIteratorRemaining(it)img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) it <- antsImageIteratorNext(it) flag <- antsImageIteratorRemaining(it)
Set value at current position
antsImageIteratorSet(x, value)antsImageIteratorSet(x, value)
x |
antsImageIterator |
value |
pixel value to set |
TRUE'
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) flag <- antsImageIteratorSet(it, 2.0)img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) flag <- antsImageIteratorSet(it, 2.0)
move interator to a given index
antsImageIteratorSetIndex(x, index)antsImageIteratorSetIndex(x, index)
x |
antsImageIterator |
index |
index to move to |
TRUE'
img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) flag <- antsImageIteratorSetIndex(it, c(2, 3))img <- makeImage(c(5, 5), rnorm(25)) it <- antsImageIterator(img) flag <- antsImageIteratorSetIndex(it, c(2, 3))
compute mutual information between two images
antsImageMutualInformation(in_image1, in_image2, sampling.percentage, nBins)antsImageMutualInformation(in_image1, in_image2, sampling.percentage, nBins)
in_image1 |
antsImage |
in_image2 |
antsImage |
sampling.percentage |
value between zero and one determining ratio of points in image to use for metric estimation |
nBins |
number of bins to use in joint histogram estimate, often set between 8 and 32 |
mutual information value
Brian B. Avants
fi <- antsImageRead(getANTsRData("r16"), 2) mi <- antsImageRead(getANTsRData("r64"), 2) testthat::expect_error(antsImageMutualInformation(fi, "hey")) testthat::expect_error(antsImageMutualInformation("hey", fi)) fi3 <- resampleImage(fi, c(2, 2)) fi2 <- antsImageClone(fi) pixeltype(fi2) <- "unsigned int" testthat::expect_error(antsImageMutualInformation(fi2, mi)) testthat::expect_error(antsImageMutualInformation(fi3, mi))fi <- antsImageRead(getANTsRData("r16"), 2) mi <- antsImageRead(getANTsRData("r64"), 2) testthat::expect_error(antsImageMutualInformation(fi, "hey")) testthat::expect_error(antsImageMutualInformation("hey", fi)) fi3 <- resampleImage(fi, c(2, 2)) fi2 <- antsImageClone(fi) pixeltype(fi2) <- "unsigned int" testthat::expect_error(antsImageMutualInformation(fi2, mi)) testthat::expect_error(antsImageMutualInformation(fi3, mi))
Check if two antsImage objects occupy the same physical space
antsImagePhysicalSpaceConsistency( img1, img2, coordinate.tolerance = 0.01, direction.tolerance = 0.01, data.type = FALSE )antsImagePhysicalSpaceConsistency( img1, img2, coordinate.tolerance = 0.01, direction.tolerance = 0.01, data.type = FALSE )
img1 |
Image object of S4 class |
img2 |
Image object of S4 class |
coordinate.tolerance |
floating point error tolerance in origin |
direction.tolerance |
floating point error tolerance in direction matrix |
data.type |
boolean, if TRUE check pixeltype and components, default is FALSE |
Boolean indicating consistency of physical space
img1 <- makeImage(c(10, 10), rnorm(100)) img2 <- makeImage(c(10, 10), rnorm(100)) check <- antsImagePhysicalSpaceConsistency(img1, img2) check <- antsImagePhysicalSpaceConsistency(img1, img2, data.type = TRUE) testthat::expect_error( antsImagePhysicalSpaceConsistency(img1, as.array(img2)) ) i2 <- img2 pixeltype(i2) <- "unsigned int" testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2, data.type = TRUE) ) i2 <- mergeChannels(list(img2, img2)) testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2, data.type = TRUE) ) i2 <- as.antsImage(img2[1:5, 1:5], reference = img2) testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2) ) i2 <- img2 antsSetSpacing(i2, c(0.5, 0.5)) testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2) ) i2 <- img2 antsSetOrigin(i2, c(1, 2)) testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2) ) i2 <- img2 antsSetDirection(i2, -1 * antsGetDirection(i2)) testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2) )img1 <- makeImage(c(10, 10), rnorm(100)) img2 <- makeImage(c(10, 10), rnorm(100)) check <- antsImagePhysicalSpaceConsistency(img1, img2) check <- antsImagePhysicalSpaceConsistency(img1, img2, data.type = TRUE) testthat::expect_error( antsImagePhysicalSpaceConsistency(img1, as.array(img2)) ) i2 <- img2 pixeltype(i2) <- "unsigned int" testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2, data.type = TRUE) ) i2 <- mergeChannels(list(img2, img2)) testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2, data.type = TRUE) ) i2 <- as.antsImage(img2[1:5, 1:5], reference = img2) testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2) ) i2 <- img2 antsSetSpacing(i2, c(0.5, 0.5)) testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2) ) i2 <- img2 antsSetOrigin(i2, c(1, 2)) testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2) ) i2 <- img2 antsSetDirection(i2, -1 * antsGetDirection(i2)) testthat::expect_false( antsImagePhysicalSpaceConsistency(img1, i2) )
Read an image file into an S4 object of class 'antsImage'.
antsImageRead(filename, dimension = NULL, pixeltype = "float")antsImageRead(filename, dimension = NULL, pixeltype = "float")
filename |
Name of the file to read the image from. |
dimension |
Number of dimensions of the image read. This need not be the same as the dimensions of the image in the file. Allowed values: 2, 3, 4. If not provided, the dimension is obtained from the image file |
pixeltype |
C++ datatype to be used to represent the pixels read. This datatype need not be the same as the datatype used in the file. Allowed values: 'double', 'float' , 'unsigned int' , 'unsigned char'. |
S4 object of Class 'antsImage' – Success
1 – Failure
Shrinidhi KL
fn <- getANTsRData("r16") fi <- antsImageRead(fn) img <- antsImageRead(fn, dimension = 2) img <- antsImageRead(fn, dimension = 2, "double")fn <- getANTsRData("r16") fi <- antsImageRead(fn) img <- antsImageRead(fn, dimension = 2) img <- antsImageRead(fn, dimension = 2, "double")
Cast images to either a passed pixeltype or the most precise of the inputs
antsImageTypeCast(imageList, pixeltype = NA)antsImageTypeCast(imageList, pixeltype = NA)
imageList |
list of images |
pixeltype |
to cast to |
list of antsImages
J Duda
img <- antsImageRead(getANTsRData("rand")) %>% resampleImage(c(32, 32)) img2 <- antsImageRead(getANTsRData("rand"), pixeltype = "double") %>% resampleImage(c(32, 32)) allDoubles <- antsImageTypeCast(list(img, img2)) floats <- antsImageTypeCast(list(img)) pixeltype(img) <- "unsigned int" ints <- antsImageTypeCast(list(img))img <- antsImageRead(getANTsRData("rand")) %>% resampleImage(c(32, 32)) img2 <- antsImageRead(getANTsRData("rand"), pixeltype = "double") %>% resampleImage(c(32, 32)) allDoubles <- antsImageTypeCast(list(img, img2)) floats <- antsImageTypeCast(list(img)) pixeltype(img) <- "unsigned int" ints <- antsImageTypeCast(list(img))
Write an image object of S4 class antsImage to a file.
antsImageWrite(image, filename, as.tensor = FALSE)antsImageWrite(image, filename, as.tensor = FALSE)
image |
Image object of S4 class |
filename |
Name of the file to write the image to. |
as.tensor |
flag indicating to write as symmetric tensor if image has 6 components |
0 – Success
1 – Failure
Shrinidhi KL
fn <- getANTsRData("r16") fi <- antsImageRead(fn) antsImageWrite(fi, tempfile(fileext = ".nii.gz")) antsImageWrite(fi, tempfile(fileext = ".mha")) antsImageWrite(fi, tempfile(fileext = ".nrrd")) antsImageWrite( antsImageClone(fi, "unsigned char"), tempfile(fileext = ".jpg") ) antsImageWrite( antsImageClone(fi, "float"), tempfile(fileext = ".tif") ) antsImageWrite(fi, tempfile(fileext = ".mrc")) antsImageWrite(fi, tempfile(fileext = ".hd5")) components(fi) <- 0L antsImageWrite(fi, tempfile(fileext = ".nii.gz"))fn <- getANTsRData("r16") fi <- antsImageRead(fn) antsImageWrite(fi, tempfile(fileext = ".nii.gz")) antsImageWrite(fi, tempfile(fileext = ".mha")) antsImageWrite(fi, tempfile(fileext = ".nrrd")) antsImageWrite( antsImageClone(fi, "unsigned char"), tempfile(fileext = ".jpg") ) antsImageWrite( antsImageClone(fi, "float"), tempfile(fileext = ".tif") ) antsImageWrite(fi, tempfile(fileext = ".mrc")) antsImageWrite(fi, tempfile(fileext = ".hd5")) components(fi) <- 0L antsImageWrite(fi, tempfile(fileext = ".nii.gz"))
call this to get the include path for ANTs headers and libraries
antsIncludes()antsIncludes()
Avants BB
antsIncludes()antsIncludes()
call this to get the path to ants static libaries to which you will link
antsLibs()antsLibs()
Avants BB
antsLibs()antsLibs()
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'
## S4 method for signature 'antsMatrix' initialize(.Object, elementtype)## S4 method for signature 'antsMatrix' initialize(.Object, elementtype)
.Object |
input object to convert |
elementtype |
string e.g. "float" |
elementtypestring of the type of storage of the matrix e.g. "float"
pointerthe memory location
mat <- as.antsMatrix(matrix(rnorm(10), nrow = 2)) as.data.frame(mat) as.matrix(mat)mat <- as.antsMatrix(matrix(rnorm(10), nrow = 2)) as.data.frame(mat) as.matrix(mat)
Correct 4D time-series data for motion.
antsMotionCalculation( img, mask = NULL, fixed = NULL, moreaccurate = 1, txtype = "Affine", framewise = 1, verbose = FALSE, ... )antsMotionCalculation( img, mask = NULL, fixed = NULL, moreaccurate = 1, txtype = "Affine", framewise = 1, verbose = FALSE, ... )
img |
antsImage, usually 4D. |
mask |
mask for image (3D). If not provided, estimated from data. |
fixed |
Fixed image to register all timepoints to. If not provided, mean image is used. |
moreaccurate |
strategy desired for motion correction. One of 0 (test) 1 (high-res only), 2 (multi-level inter-subject), 3 (FIXME), or a special method for intraSubjectBOLD. |
txtype |
Type of transform. One of |
framewise |
Calculate framewise displacement? |
verbose |
enables verbose output. |
... |
additional argument to |
List containing:
Motion corrected time-series image.
Data frame of translation parameters.
Average motion-corrected image.
Mask used to calculate framewise displacement.
Time-series displacement image.
Time-series mean and max displacements.
DVARS, derivative of frame-wise intensity changes.
Benjamin M. Kandel
This program is a user-level registration application meant to utilize ITKv4-only classes. The user can specify any number of stages where a stage consists of – a transform, an image metric, number of iterations, shrink factors, and smoothing sigmas for each level. Specialized for 4D time series data: fixed image is 3D, moving image should be the 4D time series. Fixed image is a reference space or time slice.
antsMotionCorr(paramList)antsMotionCorr(paramList)
paramList |
antsMotionCorr parameters, as in ANTs. this is a direct call to
the low level |
0 – Success
1 – Failure
This function may give different results on multiple runs.
Shrinidhi KL
# boldfn <- getANTsRData( "pcasl" ) # bold <- antsImageRead( boldfn , 4 ) set.seed(123) bold <- makeImage(c(10, 10, 10, 20), rnorm(10 * 10 * 10 * 20) + 1) bold <- iMath(bold, "PadImage", 5) aimg <- new("antsImage", "float", 3) aimg <- new("antsImage", "float", 3) mocoImg <- new("antsImage", "float", 4) mocoParams <- new("antsMatrix", "double") antsMotionCorr(list(d = 3, a = bold, o = aimg)) aimg2 <- new("antsImage", "float", 3) antsMotionCorr(list(d = 3, a = bold, o = aimg2)) antsMotionCorr(list( d = 3, o = list(mocoParams, mocoImg, aimg), m = list(name = "MI", aimg, bold, 1, 32, "Regular", 0.1), t = "Rigid[0.01]", i = 25, u = 1, e = 1, s = 0, f = 1, n = 25 )) motiondf <- as.data.frame(mocoParams)# boldfn <- getANTsRData( "pcasl" ) # bold <- antsImageRead( boldfn , 4 ) set.seed(123) bold <- makeImage(c(10, 10, 10, 20), rnorm(10 * 10 * 10 * 20) + 1) bold <- iMath(bold, "PadImage", 5) aimg <- new("antsImage", "float", 3) aimg <- new("antsImage", "float", 3) mocoImg <- new("antsImage", "float", 4) mocoParams <- new("antsMatrix", "double") antsMotionCorr(list(d = 3, a = bold, o = aimg)) aimg2 <- new("antsImage", "float", 3) antsMotionCorr(list(d = 3, a = bold, o = aimg2)) antsMotionCorr(list( d = 3, o = list(mocoParams, mocoImg, aimg), m = list(name = "MI", aimg, bold, 1, 32, "Regular", 0.1), t = "Rigid[0.01]", i = 25, u = 1, e = 1, s = 0, f = 1, n = 25 )) motiondf <- as.data.frame(mocoParams)
these strings can be used with getNamesFromDataFrame or multigrep to either include or exclude nuisance variables.
antspymm_nuisance_names()antspymm_nuisance_names()
This function generates a list of variable names to be used as predictors in a model, based antspymm tabular version of imaging data. It filters and processes the data to create meaningful predictors. LRAVG
antspymm_predictors(demog, doasym = FALSE, return_colnames = FALSE)antspymm_predictors(demog, doasym = FALSE, return_colnames = FALSE)
demog |
A dataframe containing demographic and imaging data. |
doasym |
boolean |
return_colnames |
boolean |
A dataframe with processed demographic and imaging data.
# predictors <- antspymm_predictors(demographic_data)# predictors <- antspymm_predictors(demographic_data)
This function returns a vector of quality control (QC) metric names used in the antspymm package.
These metrics include volume measures, reflection errors, PSNR (Peak Signal-to-Noise Ratio), CNR (Contrast-to-Noise Ratio),
and various metrics related to motion correction in rsfMRI and DTI.
antspymm_qc_names()antspymm_qc_names()
A character vector containing the names of QC metrics.
qc_names <- antspymm_qc_names() print(qc_names)qc_names <- antspymm_qc_names() print(qc_names)
This function inspects the input character vector for specific patterns indicating the type of variable (e.g., "T1", "rsfMRI", "DTI", "NM2") and returns a corresponding string identifier for the first matched type. If no known pattern is found, it returns 'NA'.
antspymm_vartype(x)antspymm_vartype(x)
x |
A character vector containing names or identifiers to be checked against known patterns for variable types. It must be a character vector. |
A character string indicating the type of variable matched based on the predefined patterns ("T1", "rsfMRI", "DTI", "NM2DMT"). Returns 'NA' if no pattern matches.
This function only checks for the first occurrence of a pattern and does not account for multiple different patterns within the same input. The order of pattern checking is fixed and may affect the result if multiple patterns are present.
antspymm_vartype("This is a T1 weighted image") # Returns "T1" antspymm_vartype("Subject underwent rsfMRI") # Returns "rsfMRI" antspymm_vartype("DTI sequence") # Returns "DTI" antspymm_vartype("Analysis of NM2") # Returns "NM2DMT" antspymm_vartype("Unknown type") # Returns NAantspymm_vartype("This is a T1 weighted image") # Returns "T1" antspymm_vartype("Subject underwent rsfMRI") # Returns "rsfMRI" antspymm_vartype("DTI sequence") # Returns "DTI" antspymm_vartype("Analysis of NM2") # Returns "NM2DMT" antspymm_vartype("Unknown type") # Returns NA
Applies multi-view Canonical Correlation Analysis (MCCA) to a list of subject-by-feature matrices. Each view (modality) is projected into a shared latent space that maximizes inter-view correlation.
antsr_mcca_features( data_matrices, k = 10, regularization = 0.001, center = TRUE, scale = FALSE )antsr_mcca_features( data_matrices, k = 10, regularization = 0.001, center = TRUE, scale = FALSE )
data_matrices |
A named list of numeric matrices, each subjects x features. All matrices must have the same number of subjects (rows). |
k |
Integer. Number of canonical components to extract. |
regularization |
Scalar ridge penalty to improve numerical stability (default = 1e-3). |
center |
Logical. Whether to center each matrix before analysis (default = TRUE). |
scale |
Logical. Whether to scale each matrix to unit variance (default = FALSE). |
This provides a classical linear baseline for benchmarking against SiMLR or multimodal deep models.
A list containing:
loadings |
List of projection matrices (features x k) for each view. |
scores |
List of canonical variates (subjects x k) for each view. |
shared_embedding |
Average canonical embedding across views (subjects x k). |
correlations |
Vector of canonical correlations. |
## Not run: set.seed(1500) nsub <- 25 npix <- c(100, 200, 133) nk <- 5 outcome <- matrix(rnorm(nsub * nk), ncol = nk) outcome1 <- matrix(rnorm(nsub * nk), ncol = nk) outcome2 <- matrix(rnorm(nsub * nk), ncol = nk) outcome3 <- matrix(rnorm(nsub * nk), ncol = nk) view1tx <- matrix(rnorm(npix[1] * nk), nrow = nk) view2tx <- matrix(rnorm(npix[2] * nk), nrow = nk) view3tx <- matrix(rnorm(npix[3] * nk), nrow = nk) mat1 <- (outcome %*% t(outcome1) %*% (outcome1)) %*% view1tx mat2 <- (outcome %*% t(outcome2) %*% (outcome2)) %*% view2tx mat3 <- (outcome %*% t(outcome3) %*% (outcome3)) %*% view3tx matlist <- list(vox = mat1, vox2 = mat2, vox3 = mat3) mcca <- antsr_mcca_features(matlist, k = 5) str(mcca) ## End(Not run)## Not run: set.seed(1500) nsub <- 25 npix <- c(100, 200, 133) nk <- 5 outcome <- matrix(rnorm(nsub * nk), ncol = nk) outcome1 <- matrix(rnorm(nsub * nk), ncol = nk) outcome2 <- matrix(rnorm(nsub * nk), ncol = nk) outcome3 <- matrix(rnorm(nsub * nk), ncol = nk) view1tx <- matrix(rnorm(npix[1] * nk), nrow = nk) view2tx <- matrix(rnorm(npix[2] * nk), nrow = nk) view3tx <- matrix(rnorm(npix[3] * nk), nrow = nk) mat1 <- (outcome %*% t(outcome1) %*% (outcome1)) %*% view1tx mat2 <- (outcome %*% t(outcome2) %*% (outcome2)) %*% view2tx mat3 <- (outcome %*% t(outcome3) %*% (outcome3)) %*% view3tx matlist <- list(vox = mat1, vox2 = mat2, vox3 = mat3) mcca <- antsr_mcca_features(matlist, k = 5) str(mcca) ## End(Not run)
This function applies principal component analysis (PCA) to each matrix in a list of voxel matrices and returns a list of projection matrices (principal axes).
antsr_pca_features(data_matrices, k)antsr_pca_features(data_matrices, k)
data_matrices |
A list of numeric matrices. Each matrix should have dimensions (subjects by voxels). |
k |
Integer. Number of principal components to retain. |
A named list of projection matrices (voxels by k), one per input matrix.
This function applies random projection to each matrix in a list of voxel matrices. It uses a fixed seed to ensure reproducibility across runs.
antsr_random_features(data_matrices, k, seed = 42)antsr_random_features(data_matrices, k, seed = 42)
data_matrices |
A list of numeric matrices. Each matrix should have dimensions (subjects by voxels). |
k |
Integer. Number of projection dimensions (features) to generate. |
seed |
Integer. Random seed for reproducibility. Default is 42. |
A list of projection matrices, each with dimensions (voxels by k).
Multi-view Regularized CCA baseline using RGCCA
antsr_rgcca_baseline(data_matrices, tau = 0.5, scheme = "factorial", ncomp = 3)antsr_rgcca_baseline(data_matrices, tau = 0.5, scheme = "factorial", ncomp = 3)
data_matrices |
A named list of subject x feature matrices |
tau |
Regularization parameter (0 = no regularization, 1 = PCA limit) |
scheme |
RGCCA scheme ('horst', 'factorial', 'centroid') |
ncomp |
Number of components |
Implements a sparse multi-view canonical correlation analysis using RGCCA, enforcing sparsity on each modality to obtain interpretable feature loadings. Compatible with RGCCA >= 3.0 (using 'blocks' and 'connection' arguments).
antsr_rgcca_sparse( data_matrices, ncomp = 3, tau = 0.5, sparsity = 0.3, scheme = "factorial", scale = TRUE, verbose = FALSE )antsr_rgcca_sparse( data_matrices, ncomp = 3, tau = 0.5, sparsity = 0.3, scheme = "factorial", scale = TRUE, verbose = FALSE )
data_matrices |
Named list of subject x feature matrices. Each must have the same number of rows. |
ncomp |
Number of canonical components per view (default = 3) |
tau |
Numeric in [0,1] or vector. Regularization per view (0 = pure CCA, 1 = PCA limit) |
sparsity |
Numeric in (0,1]. L1 sparsity per view; lower = sparser (default = 0.3) |
scheme |
RGCCA optimization scheme: 'factorial', 'centroid', or 'horst' (default = 'factorial') |
scale |
Logical. Whether to z-score features (default = TRUE) |
verbose |
Logical. Print progress messages (default = FALSE) |
A list with:
loadings |
List of sparse feature loadings (features x components) |
scores |
List of subject x component canonical variates |
shared_embedding |
Average canonical embedding across modalities |
correlations |
Canonical correlations across shared space |
Applies sparse principal component analysis using the selected backend ("elasticnet", "PMA", or "sparsepca") to each matrix in a list of subject by voxel data.
antsr_spca_features( data_matrices, k, method = c("default", "elasticnet", "PMA", "sparsepca"), para = NULL )antsr_spca_features( data_matrices, k, method = c("default", "elasticnet", "PMA", "sparsepca"), para = NULL )
data_matrices |
A list of numeric matrices. Each matrix should be subjects by voxels. |
k |
Integer. Number of components to retain. |
method |
Character. Sparse PCA backend to use. One of "default", "elasticnet", "PMA", or "sparsepca". |
para |
Sparsity control parameter(s). Interpretation depends on backend: - For "elasticnet": number of nonzero loadings per component (length-k vector). - For "PMA": L1 bound on loading vector (scalar or length-k). - For "sparsepca": ignored (uses built-in defaults). - For "default": length-k vector of sparsity parameters. |
A named list of sparse projection matrices (voxels by k).
An S4 class to hold a region of an antsImage
indexindices of the region
sizesize of the region
Register a pair of images either through the full or simplified interface to the ANTs registration method.
antsRegistration( fixed = NULL, moving = NULL, typeofTransform = "SyN", initialTransform = NA, outprefix = NULL, mask = NULL, movingMask = NULL, maskAllStages = FALSE, gradStep = 0.2, flowSigma = 3, totalSigma = 0, affMetric = "mattes", affSampling = 32, synMetric = "mattes", synSampling = 32, affIterations, regIterations = c(40, 20, 0), multivariateExtras, restrictTransformation, writeCompositeTransform = FALSE, samplingPercentage = 0.2, verbose = FALSE, printArgs = FALSE, ... )antsRegistration( fixed = NULL, moving = NULL, typeofTransform = "SyN", initialTransform = NA, outprefix = NULL, mask = NULL, movingMask = NULL, maskAllStages = FALSE, gradStep = 0.2, flowSigma = 3, totalSigma = 0, affMetric = "mattes", affSampling = 32, synMetric = "mattes", synSampling = 32, affIterations, regIterations = c(40, 20, 0), multivariateExtras, restrictTransformation, writeCompositeTransform = FALSE, samplingPercentage = 0.2, verbose = FALSE, printArgs = FALSE, ... )
fixed |
fixed image to which we register the moving image. |
moving |
moving image to be mapped to fixed space. |
typeofTransform |
A linear or non-linear registration type. Mutual
information metric by default. See |
initialTransform |
either a single transform file name, a vector of transform file names, or a single antsTransform object. If NA, an initial translation aligns the center of mass of the moving image to that of the fixed image, unless the transform is "deformable only", in which case the intial transform is 'Identity'. |
outprefix |
output will be named with this prefix. |
mask |
Registration metric mask in the fixed image space. |
movingMask |
Registration metric mask in the moving image space. |
maskAllStages |
If true, apply metric mask(s) to all registration stages, instead of just the final stage. |
gradStep |
gradient step size (not for all tx) |
flowSigma |
smoothing for update field |
totalSigma |
smoothing for total field |
affMetric |
the metric for the affine part (GC, mattes, meansquares) |
affSampling |
the sampling parameter for the affine metric |
synMetric |
the metric for the syn part (CC, mattes, meansquares, demons) |
synSampling |
the nbins or radius parameter for the syn metric |
affIterations |
vector of iterations for low-dimensional registration. we will set the smoothing and multi-resolution parameters based on the length of this vector. |
regIterations |
vector of iterations for syn. we will set the smoothing and multi-resolution parameters based on the length of this vector. |
multivariateExtras |
list of additional images and metrics which will
trigger the use of multiple metrics in the registration process
in the deformable stage. Multivariate metrics needs 5 entries:
name of metric, fixed, moving, weight, samplingParam.
the list should be of the form
|
restrictTransformation |
This option allows the user to restrict the
optimization of the displacement field, translation, rigid or affine
transform on a per-component basis. For example, if one wants to limit
the deformation or rotation of 3-D volume to the first two dimensions,
this is possible by specifying a weight vector of |
writeCompositeTransform |
if |
samplingPercentage |
value between zero and one that allows the percentage of points sampled to be controlled in low-dimensional metric estimation. |
verbose |
request verbose output (useful for debugging) |
printArgs |
print raw command line (useful for debugging) |
... |
additional options see antsRegistration in ANTs |
typeofTransform can be one of:
Translation transformation.
Rigid transformation: Only rotation and translation.
Similarity transformation: scaling, rotation and translation.
Rigid transformation: Only rotation and translation. May be useful for quick visualization fixes.'
Rigid transformation: Only rotation and translation. Employs dense sampling during metric estimation.'
Rigid transformation: Parameters typical for BOLD to BOLD intrasubject registration'.'
Affine transformation: Rigid + scaling.
Fast version of Affine.
Affine transformation: Parameters typical for BOLD to BOLD intrasubject registration'.'
translation, rigid, similarity, affine (twice). please set
regIterations if using this option. this would be used in cases
where you want a really high quality affine mapping (perhaps with mask).
Symmetric normalization: Affine + deformable transformation.
Uses synMetric as optimization metric and elastic regularization.
Symmetric normalization: Affine + deformable transformation.
Uses synMetric as optimization metric.
Symmetric normalization: Rigid + Affine + deformable transformation.
Uses synMetric as optimization metric.
Symmetric normalization: no initial transformation.
Uses synMetric as optimization metric. Assumes images are
aligned by an inital transformation. Can be useful if you want to run
an unmasked affine followed by masked deformable registration.
Elastic normalization: no initial transformation.
SyN, but with cross-correlation as the metric.
Note, the default or chosen parameters will be replaced with
synMetric="CC", synSampling=4, synits="2100x1200x1200x20",
smoothingsigmas="3x2x1x0", shrinkfactors="4x3x2x1".
SyN optimized for abpBrainExtraction, forces mutual information as optimization metric.
SyN, but optimized for registrations between BOLD and T1 images.
SyN, but optimized for registrations between BOLD and T1 images, with additional affine step.
SyN, but with more aggressive registration
(fine-scale matching and more deformation). Takes more time than SyN.
time-varying diffeomorphism with where 'n' indicates number of time points in velocity field discretization. The initial transform should be computed, if needed, in a separate call to ants.registration.
time-varying diffeomorphism with mean square metric
time-varying diffeomorphism with mean square metric for very large deformation
simple elastic deformation. one might want to run an
affine transformation before this. may not produce diffeomorphic transformations.
user may need to explore gradient and sigma parameters. this will not produce a valid inverse deformation. totalSigma should be greater than zero.
recreation of the antsRegistrationSyN.sh script in ANTs where 'x' is one of the transforms available (e.g., 't', 'b', 's')
recreation of the antsRegistrationSyNQuick.sh script in ANTs where 'x' is one of the transforms available (e.g., 't', 'b', 's')
reproducible registration. x options as above.
quick reproducible registration. x options as above.
outputs a list containing:
Moving image warped to space of fixed image.
Fixed image warped to space of moving image.
Transforms to move from moving to fixed image.
Transforms to move from fixed to moving image.
Ouptut of 1 indicates failure
Shrinidhi KL, Tustison NJ, Avants BB
# print help antsRegistration() fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r64")) mytx2 <- antsRegistration(fixed = fi, typeofTransform = "") rig <- antsRegistration( fixed = fi, moving = mi, typeofTransform = "Rigid", verbose = TRUE ) trans <- readAntsrTransform(rig$fwdtransforms, 2) postrig <- antsRegistration( fixed = fi, moving = mi, typeofTransform = "Affine", initialTransform = trans ) for (itype in c("AffineFast", "BOLDAffine")) { print(itype) mytx2 <- antsRegistration( fixed = fi, moving = mi, typeofTransform = itype ) } mytx2 <- antsRegistration( fixed = fi, moving = mi, typeofTransform = "SyNOnly", multivariateExtras = list(list("MeanSquares", fi, mi, 0.5, 0)) ) testthat::expect_error( antsRegistration(fixed = fi, moving = mi, typeofTransform = "sdf") ) bad <- antsRegistration(fixed = fi, moving = mi, regIterations = 40) affIterations <- c(3, 2, 1, 0) mytx2 <- antsRegistration( fixed = fi, moving = mi, affIterations = affIterations ) fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r64")) fi <- resampleImage(fi, c(60, 60), 1, 0) mi <- resampleImage(mi, c(50, 50), 1, 0) # speed up mytx <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) mywarpedimage <- antsApplyTransforms( fixed = fi, moving = mi, transformlist = mytx$fwdtransforms ) mytx2 <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) mywarpedimage2 <- antsApplyTransforms( fixed = fi, moving = mi, transformlist = mytx2$fwdtransforms ) # testthat::expect_equal(as.array(mywarpedimage), as.array(mywarpedimage2)) ## Not run: # quick visualization fix for images with odd orientation mni <- antsImageRead(getANTsRData("mni")) strokt1 <- antsImageRead("strokt1.nii.gz") strokt1reg <- antsRegistration( fixed = mni, moving = strokt1, typeofTransform = "QuickRigid", verbose = TRUE ) plot(strokt1reg$warpedmovout, axis = 3, nslices = 20) # now - how to use a mask fi <- antsImageRead(getANTsRData("r16")) fiseg <- kmeansSegmentation(fi, 3) mi <- antsImageRead(getANTsRData("r64")) msk <- thresholdImage(fiseg$segmentation, 0, 0) mytx <- antsRegistration( fixed = fi, moving = mi, typeofTransform = c("SyNCC"), mask = msk, verbose = F ) jac <- createJacobianDeterminantImage(fi, mytx$fwdtransforms[1]) ## End(Not run)# print help antsRegistration() fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r64")) mytx2 <- antsRegistration(fixed = fi, typeofTransform = "") rig <- antsRegistration( fixed = fi, moving = mi, typeofTransform = "Rigid", verbose = TRUE ) trans <- readAntsrTransform(rig$fwdtransforms, 2) postrig <- antsRegistration( fixed = fi, moving = mi, typeofTransform = "Affine", initialTransform = trans ) for (itype in c("AffineFast", "BOLDAffine")) { print(itype) mytx2 <- antsRegistration( fixed = fi, moving = mi, typeofTransform = itype ) } mytx2 <- antsRegistration( fixed = fi, moving = mi, typeofTransform = "SyNOnly", multivariateExtras = list(list("MeanSquares", fi, mi, 0.5, 0)) ) testthat::expect_error( antsRegistration(fixed = fi, moving = mi, typeofTransform = "sdf") ) bad <- antsRegistration(fixed = fi, moving = mi, regIterations = 40) affIterations <- c(3, 2, 1, 0) mytx2 <- antsRegistration( fixed = fi, moving = mi, affIterations = affIterations ) fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r64")) fi <- resampleImage(fi, c(60, 60), 1, 0) mi <- resampleImage(mi, c(50, 50), 1, 0) # speed up mytx <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) mywarpedimage <- antsApplyTransforms( fixed = fi, moving = mi, transformlist = mytx$fwdtransforms ) mytx2 <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) mywarpedimage2 <- antsApplyTransforms( fixed = fi, moving = mi, transformlist = mytx2$fwdtransforms ) # testthat::expect_equal(as.array(mywarpedimage), as.array(mywarpedimage2)) ## Not run: # quick visualization fix for images with odd orientation mni <- antsImageRead(getANTsRData("mni")) strokt1 <- antsImageRead("strokt1.nii.gz") strokt1reg <- antsRegistration( fixed = mni, moving = strokt1, typeofTransform = "QuickRigid", verbose = TRUE ) plot(strokt1reg$warpedmovout, axis = 3, nslices = 20) # now - how to use a mask fi <- antsImageRead(getANTsRData("r16")) fiseg <- kmeansSegmentation(fi, 3) mi <- antsImageRead(getANTsRData("r64")) msk <- thresholdImage(fiseg$segmentation, 0, 0) mytx <- antsRegistration( fixed = fi, moving = mi, typeofTransform = c("SyNCC"), mask = msk, verbose = F ) jac <- createJacobianDeterminantImage(fi, mytx$fwdtransforms[1]) ## End(Not run)
This is a low-level function that may be useful for debugging. It will return the pointer name itself from an antsImage object.
antsrGetPointerName(img)antsrGetPointerName(img)
img |
image whose pointer we want |
string
Avants BB
img <- antsImageRead(getANTsRData("r16")) antsrGetPointerName(img) antsrGetPointerName(antsImageClone(img))img <- antsImageRead(getANTsRData("r16")) antsrGetPointerName(img) antsrGetPointerName(antsImageClone(img))
Impute NA's on data frame.
antsrimpute(mydat, FUN = mean, ...)antsrimpute(mydat, FUN = mean, ...)
mydat |
Data frame to be imputed. |
FUN |
Method to be used for imputation (defaults to mean). |
... |
Additional parameters to pass to FUN. |
Imputes NA's on data frame (column-wise), using a user-specified function (mean is default). also works on a vector.
Returns mydat with NA's replaced by imputed numbers.
Kandel BM, Avants BB
mydat <- data.frame(A = c(1, 2, 4, 5), B = c(1, NA, 4, 5)) mean.impute <- antsrimpute(mydat) mean.impute <- antsrimpute(mydat$B) median.impute <- antsrimpute(mydat, median)mydat <- data.frame(A = c(1, 2, 4, 5), B = c(1, NA, 4, 5)) mean.impute <- antsrimpute(mydat) mean.impute <- antsrimpute(mydat$B) median.impute <- antsrimpute(mydat, median)
C++ type used to represent an ITK image metric
## S4 method for signature 'antsrMetric' show(object) ## S4 method for signature 'antsrMetric' initialize(.Object, dimension = 3, type = "MeanSquares")## S4 method for signature 'antsrMetric' show(object) ## S4 method for signature 'antsrMetric' initialize(.Object, dimension = 3, type = "MeanSquares")
object |
input object to convert |
.Object |
input object to convert |
dimension |
dimensionality of the transform (2,3,or 4) |
type |
type of transform' etc noting that short is not supported |
dimensionusually 2 or 3 but can be 4
precisionmath precision is float or double'
typeThe type of transform: usually one of AffineTransform, CenteredAffineTransform, CenteredEuler3DTransform, CenteredRigid2DTransform, CenteredSimilarity2DTransform, Euler2DTransform, Euler3DTransform, QuaternionRigidTransform, Rigid2DTransform, Similarity2DTransform, Similarity3DTransform
pointerto the memory location of the itk object
create object that measures similarity between two images
antsrMetricCreate( fixed, moving, type = c("MeanSquares", "MattesMutualInformation", "ANTSNeighborhoodCorrelation", "Correlation", "Demons", "JointHistogramMutualInformation"), fixed.mask = NULL, moving.mask = NULL, sampling.strategy = "none", sampling.percentage = 1, nBins = 32, radius = 3 )antsrMetricCreate( fixed, moving, type = c("MeanSquares", "MattesMutualInformation", "ANTSNeighborhoodCorrelation", "Correlation", "Demons", "JointHistogramMutualInformation"), fixed.mask = NULL, moving.mask = NULL, sampling.strategy = "none", sampling.percentage = 1, nBins = 32, radius = 3 )
fixed |
the fixed antsImage |
moving |
the moving antsImage |
type |
image metric to calculate
|
fixed.mask |
mask for the fixed image |
moving.mask |
mask for the moving image |
sampling.strategy |
sampling strategy, default if full sampling
|
sampling.percentage |
percentage of data to sample when calculating metric |
nBins |
number of bins for histogram metrics (default = 32) |
radius |
radius for neighborhoo metrics (default = 3) |
value of image to image metric
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares")x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares")
get derivative of image metric
antsrMetricGetDerivative(metric)antsrMetricGetDerivative(metric)
metric |
an 'antsrMetric' |
image similarity value
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") tx <- createAntsrTransform(precision = "double", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0, -1, 1, 0, 0, 0)) setAntsrTransformFixedParameters(tx, c(128, 128)) antsrMetricSetMovingTransform(metric, tx) metricValue <- antsrMetricGetDerivative(metric)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") tx <- createAntsrTransform(precision = "double", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0, -1, 1, 0, 0, 0)) setAntsrTransformFixedParameters(tx, c(128, 128)) antsrMetricSetMovingTransform(metric, tx) metricValue <- antsrMetricGetDerivative(metric)
get current value of metric
antsrMetricGetValue(metric)antsrMetricGetValue(metric)
metric |
an 'antsrMetric' |
image similarity value
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") metricValue <- antsrMetricGetValue(metric)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") metricValue <- antsrMetricGetValue(metric)
prepare to return values
antsrMetricInitialize(metric)antsrMetricInitialize(metric)
metric |
an 'antsrMetric' |
must call this after setting up object, before getting values back
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) z <- getMask(y) metric <- antsrMetricCreate(x, y, type = "MeanSquares") antsrMetricSetMovingImageMask(metric, z) antsrMetricInitialize(metric)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) z <- getMask(y) metric <- antsrMetricCreate(x, y, type = "MeanSquares") antsrMetricSetMovingImageMask(metric, z) antsrMetricInitialize(metric)
set fixed image for image to image metric
antsrMetricSetFixedImage(metric, image)antsrMetricSetFixedImage(metric, image)
metric |
an 'antsrMetric' |
image |
the fixed 'antsImage' |
After calling this, must call antsrMetricInitialize(metric)
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") z <- x * 2 antsrMetricSetFixedImage(metric, z)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") z <- x * 2 antsrMetricSetFixedImage(metric, z)
set fixed image for image to image metric
antsrMetricSetFixedImageMask(metric, image)antsrMetricSetFixedImageMask(metric, image)
metric |
an 'antsrMetric' |
image |
the fixed 'antsImage' |
After calling this, must call antsrMetricInitialize(metric)
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") z <- getMask(x) antsrMetricSetFixedImageMask(metric, z)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") z <- getMask(x) antsrMetricSetFixedImageMask(metric, z)
set transform for fixed image
antsrMetricSetFixedTransform(metric, transform)antsrMetricSetFixedTransform(metric, transform)
metric |
an 'antsrMetric' |
transform |
an 'antsrTransform' |
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "ANTSNeighborhoodCorrelation") tx <- createAntsrTransform(precision = "double", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0, -1, 1, 0, 0, 0)) setAntsrTransformFixedParameters(tx, c(128, 128)) antsrMetricSetFixedTransform(metric, tx) antsrMetricGetValue(metric)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "ANTSNeighborhoodCorrelation") tx <- createAntsrTransform(precision = "double", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0, -1, 1, 0, 0, 0)) setAntsrTransformFixedParameters(tx, c(128, 128)) antsrMetricSetFixedTransform(metric, tx) antsrMetricGetValue(metric)
set moving image for image to image metric
antsrMetricSetMovingImage(metric, image)antsrMetricSetMovingImage(metric, image)
metric |
an 'antsrMetric' |
image |
the moving 'antsImage' |
After calling this, must call antsrMetricInitialize(metric)
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") z <- y * 2 antsrMetricSetMovingImage(metric, z)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") z <- y * 2 antsrMetricSetMovingImage(metric, z)
set moving image for image to image metric
antsrMetricSetMovingImageMask(metric, image)antsrMetricSetMovingImageMask(metric, image)
metric |
an 'antsrMetric' |
image |
the moving 'antsImage' |
After calling this, must call antsrMetricInitialize(metric)
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") z <- getMask(y) antsrMetricSetMovingImageMask(metric, z)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") z <- getMask(y) antsrMetricSetMovingImageMask(metric, z)
set transform for moving image
antsrMetricSetMovingTransform(metric, transform)antsrMetricSetMovingTransform(metric, transform)
metric |
an 'antsrMetric' |
transform |
an 'antsrTransform' |
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "ANTSNeighborhoodCorrelation") tx <- createAntsrTransform(precision = "double", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0, -1, 1, 0, 0, 0)) setAntsrTransformFixedParameters(tx, c(128, 128)) antsrMetricSetMovingTransform(metric, tx) antsrMetricGetValue(metric)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "ANTSNeighborhoodCorrelation") tx <- createAntsrTransform(precision = "double", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0, -1, 1, 0, 0, 0)) setAntsrTransformFixedParameters(tx, c(128, 128)) antsrMetricSetMovingTransform(metric, tx) antsrMetricGetValue(metric)
set histogram bins image to image metric
antsrMetricSetNumberOfHistogramBins(metric, nBins)antsrMetricSetNumberOfHistogramBins(metric, nBins)
metric |
an 'antsrMetric' of type 'MattesMutualInformation' or 'JointHistogramMutualInformation' |
nBins |
number of bins (minimum is 5 even for binary data) |
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MattesMutualInformation") antsrMetricSetNumberOfHistogramBins(metric, 12)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MattesMutualInformation") antsrMetricSetNumberOfHistogramBins(metric, 12)
set neighborhood radius
antsrMetricSetRadius(metric, radius)antsrMetricSetRadius(metric, radius)
metric |
an 'antsrMetric' of type 'ANTSNeighborhoodCorrelation' |
radius |
radius of neighborhood |
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "ANTSNeighborhoodCorrelation") antsrMetricSetRadius(metric, 5)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "ANTSNeighborhoodCorrelation") antsrMetricSetRadius(metric, 5)
set image sampling strategy and rate
antsrMetricSetSampling(metric, sampling.strategy, sampling.percentage)antsrMetricSetSampling(metric, sampling.strategy, sampling.percentage)
metric |
an 'antsrMetric' |
sampling.strategy |
sampling strategy, default if full sampling
|
sampling.percentage |
percentage of data to sample when calculating metric |
After calling this, must call antsrMetricInitialize(metric)
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") antsrMetricSetSampling(metric, "random", 0.4)x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- antsrMetricCreate(x, y, type = "MeanSquares") antsrMetricSetSampling(metric, "random", 0.4)
Correct time-series data for motion.
antsrMotionCalculation( img, fixed, mask, typeofTransform = c("Rigid", "QuickRigid", "BOLDRigid", "Affine", "AffineFast", "BOLDAffine", "SyN", "SyNOnly"), getMotionDescriptors = TRUE, verbose = FALSE, ... )antsrMotionCalculation( img, fixed, mask, typeofTransform = c("Rigid", "QuickRigid", "BOLDRigid", "Affine", "AffineFast", "BOLDAffine", "SyN", "SyNOnly"), getMotionDescriptors = TRUE, verbose = FALSE, ... )
img |
antsImage, usually ND where D=4. |
fixed |
Fixed image to register all timepoints to. If not provided, mean image is used. |
mask |
mask for image (ND-1). If not provided, estimated from data. |
typeofTransform |
One of |
getMotionDescriptors |
computes dvars and framewise displacement. May take additional memory. |
verbose |
enables verbose output. |
... |
extra parameters passed to antsRegistration |
List containing:
Motion corrected time-series image.
Data frame of translation parameters.
Average motion-corrected image.
Mask used to calculate framewise displacement.
Time-series mean and max displacements.
DVARS, derivative of frame-wise intensity changes.
BB Avants, Benjamin M. Kandel, JT Duda, Jeffrey S. Phillips
Use a system call to antsSurf in order to render a function onto
a surface. This requires antsSurf to be in the environment as well
as ConvertScalarImageToRGB, both available in Advanced Normalization
Tools software on github.
antsrSurf( x, y, z, quantlimits = c(0.1, 0.9), colormap = "jet", alpha = NA, inflationFactor = 25, smoothingSigma = 0, rotationParams = c(270, 0, 270), overlayLimits = NA, backgroundColor, filename = NA, antspath = NA, verbose = FALSE )antsrSurf( x, y, z, quantlimits = c(0.1, 0.9), colormap = "jet", alpha = NA, inflationFactor = 25, smoothingSigma = 0, rotationParams = c(270, 0, 270), overlayLimits = NA, backgroundColor, filename = NA, antspath = NA, verbose = FALSE )
x |
input antsImage defining the surface on which to render |
y |
input antsImage list defining the function to render
on the surface. these image(s) should be in the same space as |
z |
input antsImage list mask for each |
quantlimits |
lower and upper quantile limits for overlay |
colormap |
character, one of: grey, red, green, blue, copper, jet, hsv, spring, summer, autumn, winter, hot, cool, overunder, custom |
alpha |
transparency vector for underlay and each overlay, default zero |
inflationFactor |
number of inflation iterations to run |
smoothingSigma |
gaussian smooth the overlay by this sigma |
rotationParams |
3 Rotation angles expressed in degrees or a matrix of rotation parameters that will be applied in sequence. |
overlayLimits |
absolute lower and upper limits for functional overlay.
this parameter will override |
backgroundColor |
a three entry vector where each entry is in the range of 0 to 255 and corresponds to red green and blue color channels. Alternatively, pass a string white or black. |
filename |
prefix filename for output pngs |
antspath |
pass the ANTSPATH here otherwise we try to detect it from environment |
verbose |
prints the command used to call |
no output
Avants BB, Tustison NJ
## Not run: myantspath <- Sys.getenv("ANTSPATH") surf_ex <- file.path(myantspath, "antsSurf") if (file.exists(surf_ex)) { ch2i <- antsImageRead(getANTsRData("ch2")) ch2seg <- thresholdImage(ch2i, "Otsu", 3) wm <- thresholdImage(ch2seg, 3, 3) wm2 <- smoothImage(wm, 1) %>% thresholdImage(0.5, Inf) kimg <- weingartenImageCurvature(ch2i, 1.5) %>% smoothImage(1) rp1 <- matrix(c(90, 180, 90), ncol = 3) rp2 <- matrix(c(90, 180, 270), ncol = 3) rp3 <- matrix(c(90, 180, 180), ncol = 3) rp <- rbind(rp1, rp3, rp2) antsrSurf( x = wm2, y = list(kimg), z = list(wm2 %>% iMath("MD", 3)), inflationFactor = 255, overlayLimits = c(-0.3, 0.3), verbose = TRUE, rotationParams = rp, filename = tempfile() ) fn <- getANTsRData("surf") img <- antsImageRead(fn) # see antsSurf on github for data wm <- thresholdImage(img, 3, 4) wm <- thresholdImage(img, 3, 4) %>% iMath("FillHoles") wm <- wm %>% thresholdImage(1, 2) wms <- smoothImage(wm, 1.0) wmk <- weingartenImageCurvature(wms, 1.5, 0) # will display to screen antsrSurf( x = wm, y = list(wmk %>% smoothImage(1)), z = list(wm %>% iMath("MD", 1)), rotationParams = c(270, 0, 90), overlayLimits = c(-0.4, 0.4) ) # surface and two overlays blob <- antsImageRead(getANTsRData("blob")) blob[1:266, 1:266, 1:100] <- 0 z <- list(wm %>% iMath("MD", 1), blob %>% smoothImage(1)) antsrSurf( x = wm, y = list(wmk %>% smoothImage(1), blob), z = z, colormap = c("jet", "blue"), alpha = c(1, 0.5, 1), rotationParams = c(270, 0, 90), overlayLimits = list(c(-0.4, 0.4), c(0.9, 1.001)) ) # separate pos and neg curvature y <- list( thresholdImage(wmk, 0.00, Inf), thresholdImage(wmk, -100, -0.00) ) z <- list( y[[1]] %>% iMath("MD", 1), y[[2]] %>% iMath("MD", 1) ) antsrSurf( x = wm, y = y, z = z, smoothingSigma = 0.5, alpha = c(1, 1, 1), colormap = c("red", "blue"), inflationFactor = 155, overlayLimits = list(c(0.5, 1.0001), c(0.5, 1.0001)), verbose = TRUE, rotationParams = rp[1, ] ) } ## End(Not run)## Not run: myantspath <- Sys.getenv("ANTSPATH") surf_ex <- file.path(myantspath, "antsSurf") if (file.exists(surf_ex)) { ch2i <- antsImageRead(getANTsRData("ch2")) ch2seg <- thresholdImage(ch2i, "Otsu", 3) wm <- thresholdImage(ch2seg, 3, 3) wm2 <- smoothImage(wm, 1) %>% thresholdImage(0.5, Inf) kimg <- weingartenImageCurvature(ch2i, 1.5) %>% smoothImage(1) rp1 <- matrix(c(90, 180, 90), ncol = 3) rp2 <- matrix(c(90, 180, 270), ncol = 3) rp3 <- matrix(c(90, 180, 180), ncol = 3) rp <- rbind(rp1, rp3, rp2) antsrSurf( x = wm2, y = list(kimg), z = list(wm2 %>% iMath("MD", 3)), inflationFactor = 255, overlayLimits = c(-0.3, 0.3), verbose = TRUE, rotationParams = rp, filename = tempfile() ) fn <- getANTsRData("surf") img <- antsImageRead(fn) # see antsSurf on github for data wm <- thresholdImage(img, 3, 4) wm <- thresholdImage(img, 3, 4) %>% iMath("FillHoles") wm <- wm %>% thresholdImage(1, 2) wms <- smoothImage(wm, 1.0) wmk <- weingartenImageCurvature(wms, 1.5, 0) # will display to screen antsrSurf( x = wm, y = list(wmk %>% smoothImage(1)), z = list(wm %>% iMath("MD", 1)), rotationParams = c(270, 0, 90), overlayLimits = c(-0.4, 0.4) ) # surface and two overlays blob <- antsImageRead(getANTsRData("blob")) blob[1:266, 1:266, 1:100] <- 0 z <- list(wm %>% iMath("MD", 1), blob %>% smoothImage(1)) antsrSurf( x = wm, y = list(wmk %>% smoothImage(1), blob), z = z, colormap = c("jet", "blue"), alpha = c(1, 0.5, 1), rotationParams = c(270, 0, 90), overlayLimits = list(c(-0.4, 0.4), c(0.9, 1.001)) ) # separate pos and neg curvature y <- list( thresholdImage(wmk, 0.00, Inf), thresholdImage(wmk, -100, -0.00) ) z <- list( y[[1]] %>% iMath("MD", 1), y[[2]] %>% iMath("MD", 1) ) antsrSurf( x = wm, y = y, z = z, smoothingSigma = 0.5, alpha = c(1, 1, 1), colormap = c("red", "blue"), inflationFactor = 155, overlayLimits = list(c(0.5, 1.0001), c(0.5, 1.0001)), verbose = TRUE, rotationParams = rp[1, ] ) } ## End(Not run)
C++ type used to represent an ITK image transform.
## S4 method for signature 'antsrTransform' show(object) ## S4 method for signature 'antsrTransform' initialize( .Object, precision = "float", dimension = 3, type = "AffineTransform", parameters = NA )## S4 method for signature 'antsrTransform' show(object) ## S4 method for signature 'antsrTransform' initialize( .Object, precision = "float", dimension = 3, type = "AffineTransform", parameters = NA )
object |
input object to convert |
.Object |
input object to convert |
precision |
string e.g. "float" or "double" |
dimension |
dimensionality of the transform (2,3,or 4) |
type |
type of transform' etc noting that short is not supported |
parameters |
transformation parameters to send to
|
dimensionusually 2 or 3 but can be 4
precisionmath precision is float or double'
typeThe type of transform: usually one of AffineTransform, CenteredAffineTransform, CenteredEuler3DTransform, CenteredRigid2DTransform, CenteredSimilarity2DTransform, Euler2DTransform, Euler3DTransform, QuaternionRigidTransform, Rigid2DTransform, Similarity2DTransform, Similarity3DTransform
pointerto the memory location of the itk object
Convert deformation field (multiChannel image) to antsrTransform
antsrTransformFromDisplacementField(field)antsrTransformFromDisplacementField(field)
field |
deformation field (multiChannel image) |
antsrTransform'
A data frame defining the git tag for the current ANTsR version. One can also see antsrVersions from ANTsRCore to get the git tag for those dependencies.
A data frame listing the following variables.
DependencyName of software dependency.
GitTagThe git tag. This can also be used to trace other dependencies, e.g. the ITK version used by the current ANTs version.
data(antsrVersions)data(antsrVersions)
Use a system call to antsVol in order to render an image. This
requires antsVol to be in the environment as well as
ConvertScalarImageToRGB, both available in Advanced Normalization
Tools software on github.
antsrVol( x, y, quantlimits = c(0.1, 0.9), colormap = "jet", rotationParams = c(270, 0, 270), overlayLimits = NA, magnificationFactor = 1, intensityTruncation = c(0, 1), filename = NA, antspath = NA, verbose = FALSE )antsrVol( x, y, quantlimits = c(0.1, 0.9), colormap = "jet", rotationParams = c(270, 0, 270), overlayLimits = NA, magnificationFactor = 1, intensityTruncation = c(0, 1), filename = NA, antspath = NA, verbose = FALSE )
x |
input antsImage defining the image to render |
y |
input antsImage list defining the function to render on the image. these image(s) should be in the same space. |
quantlimits |
lower and upper quantile limits for overlay |
colormap |
character, one of: grey, red, green, blue, copper, jet, hsv, spring, summer, autumn, winter, hot, cool, overunder, custom |
rotationParams |
3 Rotation angles expressed in degrees or a matrix of rotation parameters that will be applied in sequence. |
overlayLimits |
absolute lower and upper limits for functional overlay.
this parameter will override |
magnificationFactor |
zooms in on image during rendering |
intensityTruncation |
lower and upper quantiles at which to truncate intensity |
filename |
prefix filename for output pngs |
antspath |
pass the ANTSPATH here otherwise we try to detect it from environment |
verbose |
prints the command used to call |
no output
Avants BB, Tustison NJ
## Not run: ch2i <- antsImageRead(getANTsRData("mni")) ch2seg <- thresholdImage(ch2i, "Otsu", 3) wm <- thresholdImage(ch2seg, 3, 3) kimg <- weingartenImageCurvature(ch2i, 1.5) %>% smoothImage(1) ap <- path.expand("~/code/ants-src/bin/") rp0 <- matrix(c(90, 180, 90), ncol = 3) rp2 <- matrix(c(0, 0, 0), ncol = 3) rp3 <- matrix(c(270, 90, 90), ncol = 3) rp <- rbind(rp0, rp2, rp3) # pass these as rotationParams antsrVol(wm, list(kimg), quantlimits = c(0.01, 0.99)) ## End(Not run)## Not run: ch2i <- antsImageRead(getANTsRData("mni")) ch2seg <- thresholdImage(ch2i, "Otsu", 3) wm <- thresholdImage(ch2seg, 3, 3) kimg <- weingartenImageCurvature(ch2i, 1.5) %>% smoothImage(1) ap <- path.expand("~/code/ants-src/bin/") rp0 <- matrix(c(90, 180, 90), ncol = 3) rp2 <- matrix(c(0, 0, 0), ncol = 3) rp3 <- matrix(c(270, 90, 90), ncol = 3) rp <- rbind(rp0, rp2, rp3) # pass these as rotationParams antsrVol(wm, list(kimg), quantlimits = c(0.01, 0.99)) ## End(Not run)
Set a pixel value at an index in an 'antsImage'.
antsSetPixels(x, i = NA, j = NA, k = NA, l = NA, value)antsSetPixels(x, i = NA, j = NA, k = NA, l = NA, value)
x |
Image object of S4 class 'antsImage'. |
i |
the slowest moving index to the image |
j |
the next slowest moving index to the image, similar for k ( 2d ) |
k |
the next slowest moving index to the image ( 3d ) |
l |
the next slowest moving index to the image ( 4d ) |
value |
the value to place at this location |
array of pixel values
img <- makeImage(c(10, 10), rnorm(100)) antsSetPixels(img, 2, 3, value = Inf)img <- makeImage(c(10, 10), rnorm(100)) antsSetPixels(img, 2, 3, value = Inf)
Perform spatial ICA on group or individual fMRI data. Preprocessing should be performed prior to calling this function (cf preprocessfMRI.R).
antsSpatialICAfMRI( boldImages, maskImage = NULL, numberOfICAComponents = 20, normalizeComponentImages = TRUE, verbose = FALSE )antsSpatialICAfMRI( boldImages, maskImage = NULL, numberOfICAComponents = 20, normalizeComponentImages = TRUE, verbose = FALSE )
boldImages |
a list of 4-D ANTs image fMRI data. |
maskImage |
A 3-D ANTs image defining the region of interest. This must be specified. |
numberOfICAComponents |
Number of estimated observers (components). |
normalizeComponentImages |
Boolean to specify whether each component vector element is normalized to its z-score. |
verbose |
boolean setting verbosity level. |
Output list includes standard ICA matrices from the fastICA algorithm:
X = pre-processed data matrix
K = pre-whitening matrix that projects data onto the first n.comp principal components
W = estimated un-mixing matrix (see definition in details)
A = estimated mixing matrix
S = estimated source matrix
and the component images.
Tustison NJ, Avants BB
set.seed(2017) boldImages <- list() n <- 16 nvox <- n * n * n * 12 dims <- c(n, n, n, 12) boldImages[[1]] <- makeImage(dims, rnorm(nvox) + 500) boldImages[[2]] <- makeImage(dims, rnorm(nvox) + 500) boldImages[[3]] <- makeImage(dims, rnorm(nvox) + 500) maskImage <- getAverageOfTimeSeries(boldImages[[1]]) * 0 + 1 icaResults <- antsSpatialICAfMRI(boldImages, maskImage, numberOfICAComponents = 2 )set.seed(2017) boldImages <- list() n <- 16 nvox <- n * n * n * 12 dims <- c(n, n, n, 12) boldImages[[1]] <- makeImage(dims, rnorm(nvox) + 500) boldImages[[2]] <- makeImage(dims, rnorm(nvox) + 500) boldImages[[3]] <- makeImage(dims, rnorm(nvox) + 500) maskImage <- getAverageOfTimeSeries(boldImages[[1]]) * 0 + 1 icaResults <- antsSpatialICAfMRI(boldImages, maskImage, numberOfICAComponents = 2 )
Get spatial point from index of an antsImage.
antsTransformIndexToPhysicalPoint(x, index)antsTransformIndexToPhysicalPoint(x, index)
x |
image object of S4 class |
index |
image index |
array of pixel values
img <- makeImage(c(10, 10), rnorm(100)) pt <- antsTransformIndexToPhysicalPoint(img, c(2, 2))img <- makeImage(c(10, 10), rnorm(100)) pt <- antsTransformIndexToPhysicalPoint(img, c(2, 2))
Get index from spatial point of an 'antsImage'.
antsTransformPhysicalPointToIndex(x, point)antsTransformPhysicalPointToIndex(x, point)
x |
Image object of S4 class 'antsImage' to get values from. |
point |
image physical point |
array of pixel values
img <- makeImage(c(10, 10), rnorm(100)) pt <- antsTransformPhysicalPointToIndex(img, c(2, 2)) arr <- as.array(img) testthat::expect_error( antsTransformPhysicalPointToIndex(arr, c(2, 2)), "antsImage" ) testthat::expect_error( antsTransformPhysicalPointToIndex(img, c("2", 2)), "point must be" ) testthat::expect_error( antsTransformPhysicalPointToIndex(img, c(2, 2, 2)), "matrix must be of" )img <- makeImage(c(10, 10), rnorm(100)) pt <- antsTransformPhysicalPointToIndex(img, c(2, 2)) arr <- as.array(img) testthat::expect_error( antsTransformPhysicalPointToIndex(arr, c(2, 2)), "antsImage" ) testthat::expect_error( antsTransformPhysicalPointToIndex(img, c("2", 2)), "point must be" ) testthat::expect_error( antsTransformPhysicalPointToIndex(img, c(2, 2, 2)), "matrix must be of" )
A data frame defining the git tag for the current ANTsRCore version of ANTs.
A data frame listing the following variables.
DependencyName of software dependency.
GitTagThe git tag. This can also be used to trace other dependencies, e.g. the ITK version used by the current ANTs version.
Returns an antsImage after applying function.
apply(X, MARGIN, FUN, ...) ## Default S3 method: apply(X, MARGIN, FUN, ...) ## S3 method for class 'antsImage' apply(X, MARGIN, FUN, ...)apply(X, MARGIN, FUN, ...) ## Default S3 method: apply(X, MARGIN, FUN, ...) ## S3 method for class 'antsImage' apply(X, MARGIN, FUN, ...)
X |
an antsImage |
MARGIN |
a vector giving the subscripts which the function will be applied over. |
FUN |
the function to be applied. |
... |
optional arguments to FUN |
output is antsImage of lower dimnesion than input
Duda JT
img <- makeImage(c(4, 4, 4), rnorm(4 * 4 * 4)) img2 <- apply(img, c(1, 2), mean) is.antsImage(img2)img <- makeImage(c(4, 4, 4), rnorm(4 * 4 * 4)) img2 <- apply(img, c(1, 2), mean) is.antsImage(img2)
Automatically handles name collisions by appending versioned suffixes:
No collision -> petPC1, petPC2, ...
Collision -> petPCr01.1, petPCr01.2, ...
Next round -> petPCr02.1, petPCr02.2, ...
apply_simlr_matrices( existing_df, simlr_v, n_limit = NULL, version_prefix = "r", verbose = FALSE )apply_simlr_matrices( existing_df, simlr_v, n_limit = NULL, version_prefix = "r", verbose = FALSE )
existing_df |
Data frame (samples in rows, features in columns) |
simlr_v |
Named list of weight matrices (rownames = original features) |
n_limit |
Optional: keep only first n_limit components per block |
version_prefix |
Prefix before version number (default: "r") |
verbose |
Print messages when versioning occurs |
List with extended_df and new_colnames
set.seed(123) df <- data.frame(petPC1 = rnorm(5), petPC2 = rnorm(5), age = 1:5) W <- matrix(rnorm(6), 2, 3, dimnames = list(c("petPC1", "petPC2"), c("PC1", "PC2", "PC3"))) weights <- list(pet = W) # First application res1 <- apply_simlr_matrices(df, weights, verbose = TRUE) res1$new_colnames # [1] "petPCr01.1" "petPCr01.2" "petPCr01.3" # Second application res2 <- apply_simlr_matrices(res1$extended_df, weights) res2$new_colnames # [1] "petPCr02.1" "petPCr02.2" "petPCr02.3" # No collision example clean <- df[, "age", drop = FALSE] apply_simlr_matrices(clean, weights)$new_colnames # [1] "petPC1" "petPC2" "petPC3"set.seed(123) df <- data.frame(petPC1 = rnorm(5), petPC2 = rnorm(5), age = 1:5) W <- matrix(rnorm(6), 2, 3, dimnames = list(c("petPC1", "petPC2"), c("PC1", "PC2", "PC3"))) weights <- list(pet = W) # First application res1 <- apply_simlr_matrices(df, weights, verbose = TRUE) res1$new_colnames # [1] "petPCr01.1" "petPCr01.2" "petPCr01.3" # Second application res2 <- apply_simlr_matrices(res1$extended_df, weights) res2$new_colnames # [1] "petPCr02.1" "petPCr02.2" "petPCr02.3" # No collision example clean <- df[, "age", drop = FALSE] apply_simlr_matrices(clean, weights)$new_colnames # [1] "petPC1" "petPC2" "petPC3"
This function takes a list of matrices, applies each matrix via matrix multiplication to an existing data frame, and combines the resulting projections with the original data frame. Handles an as yet uncharacterized issue with column names in prior versions of data processing.
apply_simlr_matrices_dtfix( existing_df, matrices_list, n_limit = NULL, robust = FALSE, center = FALSE, scale = FALSE, verbose = FALSE )apply_simlr_matrices_dtfix( existing_df, matrices_list, n_limit = NULL, robust = FALSE, center = FALSE, scale = FALSE, verbose = FALSE )
existing_df |
An existing data frame to which the matrices will be applied. |
matrices_list |
A list of matrices read from CSV files. |
n_limit |
NULL or integer that can limit the number of projections |
robust |
boolean |
center |
boolean center the data before applying |
scale |
boolean scale the data before applying |
verbose |
boolean |
A list including (entry one) data frame with the original data frame combined with the projections (entry two) the new column names
Applies the same centering, scaling, and normalization learned from a training matrix.
apply_transform_matrix(Xnew, params)apply_transform_matrix(Xnew, params)
Xnew |
New data matrix to transform. |
params |
Parameters returned by |
Transformed matrix using the learned parameters.
Apply transform to point, vector or antsImage data
applyAntsrTransform(transform, data, dataType = "point", reference = NULL, ...)applyAntsrTransform(transform, data, dataType = "point", reference = NULL, ...)
transform |
antsrTransform |
data |
data to transform |
dataType |
data type for non-antsImage data. Either "point" or "vector" |
reference |
target space for transforming an antsImage |
... |
options passed to 'applyAntsrTransformToImage' |
transformed data
tx <- createAntsrTransform(dimension = 2, precision = "float", type = "AffineTransform") params <- getAntsrTransformParameters(tx) setAntsrTransformParameters(tx, params * 2) pt2 <- applyAntsrTransform(tx, c(1, 2, 3))tx <- createAntsrTransform(dimension = 2, precision = "float", type = "AffineTransform") params <- getAntsrTransformParameters(tx) setAntsrTransformParameters(tx, params * 2) pt2 <- applyAntsrTransform(tx, c(1, 2, 3))
Apply transform to spatial point
applyAntsrTransformToImage( transform, image, reference, interpolation = "linear" )applyAntsrTransformToImage( transform, image, reference, interpolation = "linear" )
transform |
antsrTransform |
image |
antsImage to transform |
reference |
antImage giving the reference output space |
interpolation |
type of interpolator to use |
antsImage
img <- antsImageRead(getANTsRData("r16")) tx <- new("antsrTransform", precision = "float", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0.9, 0, 0, 1.1, 10, 11)) img2 <- applyAntsrTransformToImage(tx, img, img) # plot(img,img2)img <- antsImageRead(getANTsRData("r16")) tx <- new("antsrTransform", precision = "float", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0.9, 0, 0, 1.1, 10, 11)) img2 <- applyAntsrTransformToImage(tx, img, img) # plot(img,img2)
Apply transform to spatial point
applyAntsrTransformToPoint(transform, points)applyAntsrTransformToPoint(transform, points)
transform |
antsrTransform |
points |
a matrix which each row is a spatial point |
array of coordinates
tx <- new("antsrTransform") params <- getAntsrTransformParameters(tx) setAntsrTransformParameters(tx, params * 2) pt2 <- applyAntsrTransformToPoint(tx, c(1, 2, 3))tx <- new("antsrTransform") params <- getAntsrTransformParameters(tx) setAntsrTransformParameters(tx, params * 2) pt2 <- applyAntsrTransformToPoint(tx, c(1, 2, 3))
Apply transform to spatial vector
applyAntsrTransformToVector(transform, vectors)applyAntsrTransformToVector(transform, vectors)
transform |
antsrTransform |
vectors |
a matrix where each row is a vector to transform |
array of coordinates
transform <- new("antsrTransform", precision = "float", type = "AffineTransform", dimension = 2 ) vec2 <- applyAntsrTransformToVector(transform, c(1, 2, 3))transform <- new("antsrTransform", precision = "float", type = "AffineTransform", dimension = 2 ) vec2 <- applyAntsrTransformToVector(transform, c(1, 2, 3))
Convert types to antsImage
as.antsImage( object, pixeltype = "float", spacing = as.numeric(seq.int(from = 1, by = 0, length.out = length(dim(object)))), origin = as.numeric(seq.int(from = 0, by = 0, length.out = length(dim(object)))), direction = diag(length(dim(object))), components = FALSE, reference = NULL, ... ) ## S4 method for signature 'matrix' as.antsImage( object, pixeltype = "float", spacing = as.numeric(seq.int(from = 1, by = 0, length.out = length(dim(object)))), origin = as.numeric(seq.int(from = 0, by = 0, length.out = length(dim(object)))), direction = diag(length(dim(object))), components = FALSE, reference = NULL ) ## S4 method for signature 'array' as.antsImage( object, pixeltype = "float", spacing = as.numeric(seq.int(from = 1, by = 0, length.out = length(dim(object)))), origin = as.numeric(seq.int(from = 0, by = 0, length.out = length(dim(object)))), direction = diag(length(dim(object))), components = FALSE, reference = NULL )as.antsImage( object, pixeltype = "float", spacing = as.numeric(seq.int(from = 1, by = 0, length.out = length(dim(object)))), origin = as.numeric(seq.int(from = 0, by = 0, length.out = length(dim(object)))), direction = diag(length(dim(object))), components = FALSE, reference = NULL, ... ) ## S4 method for signature 'matrix' as.antsImage( object, pixeltype = "float", spacing = as.numeric(seq.int(from = 1, by = 0, length.out = length(dim(object)))), origin = as.numeric(seq.int(from = 0, by = 0, length.out = length(dim(object)))), direction = diag(length(dim(object))), components = FALSE, reference = NULL ) ## S4 method for signature 'array' as.antsImage( object, pixeltype = "float", spacing = as.numeric(seq.int(from = 1, by = 0, length.out = length(dim(object)))), origin = as.numeric(seq.int(from = 0, by = 0, length.out = length(dim(object)))), direction = diag(length(dim(object))), components = FALSE, reference = NULL )
object |
An object |
pixeltype |
a character string e.g. "float" |
spacing |
numeric vector matching image dimensionality e.g. c(1.2,1.2) |
origin |
numeric vector matching image dimensionality e.g. c(0,0) |
direction |
numeric matrix matching image dimensionality eg diag(2) |
components |
number of components per voxel, e.g. 1 |
reference |
optional reference antsImage providing all header info |
... |
Extra named arguments passed to FUN |
arr <- array(rnorm(10^3), dim = rep(10, 3)) img <- as.antsImage(arr) i2 <- as.antsImage(arr, reference = img)arr <- array(rnorm(10^3), dim = rep(10, 3)) img <- as.antsImage(arr) i2 <- as.antsImage(arr, reference = img)
convert types to an antsMatrix
as.antsMatrix(object, elementtype = "float", ...) ## S4 method for signature 'list' as.antsMatrix(object, elementtype = "float") ## S4 method for signature 'data.frame' as.antsMatrix(object, elementtype = "float") ## S4 method for signature 'matrix' as.antsMatrix(object, elementtype = "float")as.antsMatrix(object, elementtype = "float", ...) ## S4 method for signature 'list' as.antsMatrix(object, elementtype = "float") ## S4 method for signature 'data.frame' as.antsMatrix(object, elementtype = "float") ## S4 method for signature 'matrix' as.antsMatrix(object, elementtype = "float")
object |
An object |
elementtype |
e.g. "float" or "double" |
... |
other parameters |
as.antsMatrix(matrix(rnorm(10), nrow = 2)) mat <- matrix(rnorm(10), nrow = 2) df <- as.data.frame(mat) as.antsMatrix(df) as.antsMatrix(as.list(df))as.antsMatrix(matrix(rnorm(10), nrow = 2)) mat <- matrix(rnorm(10), nrow = 2) df <- as.data.frame(mat) as.antsMatrix(df) as.antsMatrix(as.list(df))
Converts antsImage, antsImage object to different data types
## S4 method for signature 'antsImage' dim(x) ## S4 method for signature 'antsImage' as.numeric( x, mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S4 method for signature 'antsImage' as.matrix( x, mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S3 method for class 'antsImage' as.matrix( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S4 method for signature 'antsImage' as.array( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S3 method for class 'antsImage' as.array( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S3 method for class 'antsImage' as.character( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S3 method for class 'antsImage' as.factor( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S3 method for class 'antsImage' factor( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S4 method for signature 'antsMatrix' as.data.frame(x) ## S3 method for class 'antsMatrix' as.data.frame(x, row.names = NULL, optional = FALSE, ...) ## S4 method for signature 'antsMatrix' as.matrix(x, ...) ## S4 method for signature 'antsMatrix' as.list(x, ...)## S4 method for signature 'antsImage' dim(x) ## S4 method for signature 'antsImage' as.numeric( x, mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S4 method for signature 'antsImage' as.matrix( x, mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S3 method for class 'antsImage' as.matrix( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S4 method for signature 'antsImage' as.array( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S3 method for class 'antsImage' as.array( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S3 method for class 'antsImage' as.character( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S3 method for class 'antsImage' as.factor( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S3 method for class 'antsImage' factor( x, ..., mask = logical(), region = new("antsRegion", index = integer(), size = integer()) ) ## S4 method for signature 'antsMatrix' as.data.frame(x) ## S3 method for class 'antsMatrix' as.data.frame(x, row.names = NULL, optional = FALSE, ...) ## S4 method for signature 'antsMatrix' as.matrix(x, ...) ## S4 method for signature 'antsMatrix' as.list(x, ...)
x |
object of class |
mask |
a logical vector/array or binary antsImage object |
region |
a |
... |
additional arguments passed to functions |
row.names |
NULL or a character vector giving the row names for the data frame. |
optional |
passsed to |
outimg <- makeImage(c(2, 10), rnorm(20)) as.numeric(outimg) as.numeric(outimg, mask = outimg > 1) testthat::expect_error(as.numeric(outimg, mask = outimg)) outimg <- makeImage(c(2, 10), rnorm(20)) as.matrix(outimg) as.matrix(outimg, mask = outimg > 1) testthat::expect_error(as.matrix(outimg, mask = outimg)) outimg <- makeImage(c(2, 10, 2), rnorm(40)) testthat::expect_error(as.matrix(outimg)) outimg <- makeImage(c(2, 10), rnorm(20)) as.matrix(outimg) as.matrix(outimg, mask = outimg > 1) outimg <- makeImage(c(2, 10, 2), rnorm(40)) testthat::expect_error(as.matrix(outimg)) img <- antsImageRead(getANTsRData("r16")) img[img > 5] <- 0 sort(unique(as.character(img))) factor(img) table(img, img)outimg <- makeImage(c(2, 10), rnorm(20)) as.numeric(outimg) as.numeric(outimg, mask = outimg > 1) testthat::expect_error(as.numeric(outimg, mask = outimg)) outimg <- makeImage(c(2, 10), rnorm(20)) as.matrix(outimg) as.matrix(outimg, mask = outimg > 1) testthat::expect_error(as.matrix(outimg, mask = outimg)) outimg <- makeImage(c(2, 10, 2), rnorm(40)) testthat::expect_error(as.matrix(outimg)) outimg <- makeImage(c(2, 10), rnorm(20)) as.matrix(outimg) as.matrix(outimg, mask = outimg > 1) outimg <- makeImage(c(2, 10, 2), rnorm(40)) testthat::expect_error(as.matrix(outimg)) img <- antsImageRead(getANTsRData("r16")) img[img > 5] <- 0 sort(unique(as.character(img))) factor(img) table(img, img)
This function averages arterial spin labeling (ASL) functional MRI tag-control image pairs to estimate perfusion.
aslAveraging( asl, mask = NULL, tc = NA, nuisance = NA, method = "regression", ... )aslAveraging( asl, mask = NULL, tc = NA, nuisance = NA, method = "regression", ... )
asl |
input asl image |
mask |
in which to calculate perfusion |
tc |
vector indicating which images are tagged and which are controls.
Strongly recommended if using |
nuisance |
nuisance covariates to include in regression |
method |
method to use for computing average. One of |
... |
additional parameters to pass to ASL averaging functions.
See |
Two major types of methods are available for ASL signal averaging:
: All the subtraction methods are based on subtracting
the tag from control images and averaging the result. simple
subtracts adjacent tag and control images. The other methods use
interpolation to obtain a subtracted time-series. Sinc subtraction may
be marginally more accurate than cubic interpolation, but takes much
longer. Surround subtraction uses linear interpolation and is fast.
: Regression regresses the time-series on a vector of alternating tag-control dummy variables. Regression can incorporate nuisance covariates. Bayesian regression incorporates regularization in the regression to encourage all voxels of the same tissue type to have similar perfusion values.
For bayesian, two more arguments are required:
: a segmentation image
: a list of tissue probability images
These would be as output from atropos; see Examples for a
sample usage.
Kandel BM, Avants BB
set.seed(1) nvox <- 8 * 8 * 8 * 10 dims <- c(8, 8, 8, 10) voxvals <- array(rnorm(nvox) + 500, dim = dims) asl <- makeImage(dims, voxvals) tc <- rep(c(-0.5, 0.5), dims[4] / 2) avg <- aslAveraging(asl, tc = tc) testthat::expect_equal(mean(avg), 0.00739, tolerance = .1) slice <- extractSlice(asl, 4, 4) mask <- getMask(slice) seg <- atropos(d = 3, a = slice, x = mask, i = "kmeans[6]", m = "[0.0,1x1x1]") perfSurr <- aslAveraging(asl, mask = NULL, method = "surroundSubtract") bayesAvg <- aslAveraging(asl, tc = tc, method = "bayesian", segmentation = seg$segmentation, tissuelist = seg$probabilityimages )set.seed(1) nvox <- 8 * 8 * 8 * 10 dims <- c(8, 8, 8, 10) voxvals <- array(rnorm(nvox) + 500, dim = dims) asl <- makeImage(dims, voxvals) tc <- rep(c(-0.5, 0.5), dims[4] / 2) avg <- aslAveraging(asl, tc = tc) testthat::expect_equal(mean(avg), 0.00739, tolerance = .1) slice <- extractSlice(asl, 4, 4) mask <- getMask(slice) seg <- atropos(d = 3, a = slice, x = mask, i = "kmeans[6]", m = "[0.0,1x1x1]") perfSurr <- aslAveraging(asl, mask = NULL, method = "surroundSubtract") bayesAvg <- aslAveraging(asl, tc = tc, method = "bayesian", segmentation = seg$segmentation, tissuelist = seg$probabilityimages )
Censor bad volumes from ASL data.
aslCensoring( asl, mask = NULL, nuis = NA, method = "outlier", reject.pairs = FALSE, ... )aslCensoring( asl, mask = NULL, nuis = NA, method = "outlier", reject.pairs = FALSE, ... )
asl |
input asl image |
mask |
mask for calculating perfusion |
nuis |
fixed nuisance parameters |
method |
one of 'outlier', 'robust', or 'scor'. See |
reject.pairs |
whether to reject only tag-control pairs of images, as opposed to single images. Rejecting pairs of images is necessary for non-regression-based ASL averaging methods. |
... |
Additional arguments to pass to censoring method. See |
aslCensoring is an interface to ASL timepoint censoring algorithms.
Three options are currently provided, with different additional arguments:
outlierOutlier rejection from Tan et al. This method rejects volumes that are either far from the mean of the time-series or whose standard deviation is far from the standard deviations of the individual volumes. Accepts two additional arguments:
sigma.mean: how many standard deviations the mean of the volume can be from the mean of all the volumes before being thrown out.
sigma.sd: how many standard deviations from the mean of standard deviations can the standard deviation of the volume be before being thrown out.
robustUses a robust regression approach to estimate volumes with high leverage. Accepts three arguments:
nuis:Nuisance regressors to use as covariates.
robthresh:Threshold for weights on leverage estimates. Points with weights under this value will be thrown out; defaults to 0.95.
skip:Proportion of points to skip when estimating leverage. Defaults to 20 (1/20 of the image is used).
scorSCOR method of Dolui et al. No parameters.
vector of the same length as number of timepoints in asl, with
1 indicating the corresponding timepoint is included and 0 indicating exclusion.
Kandel BM
Tan H. et al., “A Fast, Effective Filtering Method for Improving Clinical Pulsed Arterial Spin Labeling MRI,” JMRI 2009.
set.seed(1) nvox <- 5 * 5 * 5 * 30 dims <- c(5, 5, 5, 30) voxvals <- array(rnorm(nvox) + 500, dim = dims) voxvals[, , , 5] <- voxvals[, , , 5] + 600 asl <- makeImage(dims, voxvals) censored <- aslCensoring(asl)set.seed(1) nvox <- 5 * 5 * 5 * 30 dims <- c(5, 5, 5, 30) voxvals <- array(rnorm(nvox) + 500, dim = dims) voxvals[, , , 5] <- voxvals[, , , 5] + 600 asl <- makeImage(dims, voxvals) censored <- aslCensoring(asl)
Denoises regression based reconstruction of CBF from arterial spin labeling
aslDenoiseR( boldmatrix, targety, covariates = NA, selectionthresh = 0.1, maxnoisepreds = 2:12, polydegree = "loess", crossvalidationgroups = 4, scalemat = F, noisepoolfun = max, usecompcor = F, verbose = F )aslDenoiseR( boldmatrix, targety, covariates = NA, selectionthresh = 0.1, maxnoisepreds = 2:12, polydegree = "loess", crossvalidationgroups = 4, scalemat = F, noisepoolfun = max, usecompcor = F, verbose = F )
boldmatrix |
input bold matrix |
targety |
target to predict |
covariates |
motion or other parameters / nuisance variables |
selectionthresh |
e.g. 0.1 take 10 percent worst variables for noise estimation |
maxnoisepreds |
integer search range e.g 1:10 |
polydegree |
eg 4 for polynomial nuisance variables or 'loess' |
crossvalidationgroups |
prior defined or integer valued |
scalemat |
boolean |
noisepoolfun |
function to help select noise pool e.g. max |
usecompcor |
boolean |
verbose |
boolean |
matrix is output
Avants BB
# asl<-antsImageRead( getANTsRData("pcasl") ) set.seed(1) nvox <- 10 * 10 * 10 * 20 dims <- c(10, 10, 10, 20) asl <- makeImage(dims, rnorm(nvox) + 500) aslmean <- getAverageOfTimeSeries(asl) aslmask <- getMask(aslmean) aslmat <- timeseries2matrix(asl, aslmask) for (i in 1:10) aslmat[, i * 2] <- aslmat[, i * 2] * 2 asl <- matrix2timeseries(asl, aslmask, aslmat) tc <- as.factor(rep(c("C", "T"), nrow(aslmat) / 2)) dv <- computeDVARS(aslmat) dnz <- aslDenoiseR(aslmat, tc, covariates = dv, selectionthresh = 0.1, maxnoisepreds = c(1:2), polydegree = 2, crossvalidationgroups = 2 ) testthat::expect_equal(dnz$R2atBestN, 7, tolerance = 0.5) ## Not run: # a classic regression approach to estimating perfusion # not recommended, but shows the basic idea. # see ?quantifyCBF for a better approach perfmodel <- lm(aslmat ~ tc + dnz$noiseu) perfimg <- antsImageClone(aslmask) perfimg[aslmask == 1] <- bigLMStats(perfmodel)$beta[1, ] m0 <- getAverageOfTimeSeries(asl) ctl <- c(1:(nrow(aslmat) / 2)) * 2 m0[aslmask == 1] <- colMeans(aslmat[ctl, ]) pcasl.parameters <- list(sequence = "pcasl", m0 = m0) cbf <- quantifyCBF(perfimg, aslmask, pcasl.parameters) # default mode network example if (!exists("bold")) { bold <- antsImageRead(getANTsRData("rsbold")) meanbold <- getAverageOfTimeSeries(bold) boldmask <- getMask(meanbold) # map to mni mni <- antsImageRead(getANTsRData("mni")) mniaal <- antsImageRead(getANTsRData("mnia")) mymap <- antsRegistration(meanbold * boldmask, mni, typeofTransform = "SyNBold", verbose = 1 ) aalimg <- antsApplyTransforms(meanbold, mniaal, mymap$fwdtransforms, interpolator = "NearestNeighbor" ) data("aal", package = "ANTsR") timeselect <- 10:dim(bold)[4] if (!exists("moco")) { moco <- antsMotionCalculation(bold, boldmask) } sbold <- smoothImage(moco$moco_img, 3.0) antsImageWrite(boldmask, "boldmask.nii.gz") antsImageWrite(meanbold, "boldmean.nii.gz") antsImageWrite(aalimg, "boldaal.nii.gz") boldmask <- boldmask * thresholdImage(aalimg, 1, Inf) } postcing <- aal$label_num[grep("Cingulum_Post", aal$label_name)] postCingMask <- maskImage(boldmask, aalimg, level = as.numeric(postcing), binarize = T ) mpostCingMask <- antsImageClone(postCingMask) * 0 mpostCingMask[postCingMask == 0] <- 1 boldmat <- timeseries2matrix(sbold, boldmask * mpostCingMask) boldmat <- boldmat[timeselect, ] boldmat <- frequencyFilterfMRI(boldmat, tr = antsGetSpacing(bold)[4], opt = "trig") dmnvec <- (timeseries2matrix(sbold, postCingMask)[timeselect, ]) dmnvec <- rowMeans( frequencyFilterfMRI(dmnvec, tr = antsGetSpacing(bold)[4], opt = "trig") ) dmnmat <- matrix(dmnvec, ncol = 1) mocpar <- moco$moco_params[timeselect, 3:14] dnz <- aslDenoiseR(boldmat, dmnvec, covariates = mocpar, selectionthresh = 0.2, maxnoisepreds = c(2:10), polydegree = "loess", crossvalidationgroups = 8 ) boldmat <- timeseries2matrix(sbold, boldmask) boldmat <- boldmat[timeselect, ] boldmat <- frequencyFilterfMRI(boldmat, tr = antsGetSpacing(bold)[4], opt = "trig") mdl <- bigLMStats(lm(boldmat ~ dmnvec + dnz$covariates + dnz$noiseu), 0.001) betas <- mdl$beta.t[1, ] betaImg <- makeImage(boldmask, betas) antsImageWrite(betaImg, "dmnBetas.nii.gz") # this should give default mode network around beta = 12 ## End(Not run)# asl<-antsImageRead( getANTsRData("pcasl") ) set.seed(1) nvox <- 10 * 10 * 10 * 20 dims <- c(10, 10, 10, 20) asl <- makeImage(dims, rnorm(nvox) + 500) aslmean <- getAverageOfTimeSeries(asl) aslmask <- getMask(aslmean) aslmat <- timeseries2matrix(asl, aslmask) for (i in 1:10) aslmat[, i * 2] <- aslmat[, i * 2] * 2 asl <- matrix2timeseries(asl, aslmask, aslmat) tc <- as.factor(rep(c("C", "T"), nrow(aslmat) / 2)) dv <- computeDVARS(aslmat) dnz <- aslDenoiseR(aslmat, tc, covariates = dv, selectionthresh = 0.1, maxnoisepreds = c(1:2), polydegree = 2, crossvalidationgroups = 2 ) testthat::expect_equal(dnz$R2atBestN, 7, tolerance = 0.5) ## Not run: # a classic regression approach to estimating perfusion # not recommended, but shows the basic idea. # see ?quantifyCBF for a better approach perfmodel <- lm(aslmat ~ tc + dnz$noiseu) perfimg <- antsImageClone(aslmask) perfimg[aslmask == 1] <- bigLMStats(perfmodel)$beta[1, ] m0 <- getAverageOfTimeSeries(asl) ctl <- c(1:(nrow(aslmat) / 2)) * 2 m0[aslmask == 1] <- colMeans(aslmat[ctl, ]) pcasl.parameters <- list(sequence = "pcasl", m0 = m0) cbf <- quantifyCBF(perfimg, aslmask, pcasl.parameters) # default mode network example if (!exists("bold")) { bold <- antsImageRead(getANTsRData("rsbold")) meanbold <- getAverageOfTimeSeries(bold) boldmask <- getMask(meanbold) # map to mni mni <- antsImageRead(getANTsRData("mni")) mniaal <- antsImageRead(getANTsRData("mnia")) mymap <- antsRegistration(meanbold * boldmask, mni, typeofTransform = "SyNBold", verbose = 1 ) aalimg <- antsApplyTransforms(meanbold, mniaal, mymap$fwdtransforms, interpolator = "NearestNeighbor" ) data("aal", package = "ANTsR") timeselect <- 10:dim(bold)[4] if (!exists("moco")) { moco <- antsMotionCalculation(bold, boldmask) } sbold <- smoothImage(moco$moco_img, 3.0) antsImageWrite(boldmask, "boldmask.nii.gz") antsImageWrite(meanbold, "boldmean.nii.gz") antsImageWrite(aalimg, "boldaal.nii.gz") boldmask <- boldmask * thresholdImage(aalimg, 1, Inf) } postcing <- aal$label_num[grep("Cingulum_Post", aal$label_name)] postCingMask <- maskImage(boldmask, aalimg, level = as.numeric(postcing), binarize = T ) mpostCingMask <- antsImageClone(postCingMask) * 0 mpostCingMask[postCingMask == 0] <- 1 boldmat <- timeseries2matrix(sbold, boldmask * mpostCingMask) boldmat <- boldmat[timeselect, ] boldmat <- frequencyFilterfMRI(boldmat, tr = antsGetSpacing(bold)[4], opt = "trig") dmnvec <- (timeseries2matrix(sbold, postCingMask)[timeselect, ]) dmnvec <- rowMeans( frequencyFilterfMRI(dmnvec, tr = antsGetSpacing(bold)[4], opt = "trig") ) dmnmat <- matrix(dmnvec, ncol = 1) mocpar <- moco$moco_params[timeselect, 3:14] dnz <- aslDenoiseR(boldmat, dmnvec, covariates = mocpar, selectionthresh = 0.2, maxnoisepreds = c(2:10), polydegree = "loess", crossvalidationgroups = 8 ) boldmat <- timeseries2matrix(sbold, boldmask) boldmat <- boldmat[timeselect, ] boldmat <- frequencyFilterfMRI(boldmat, tr = antsGetSpacing(bold)[4], opt = "trig") mdl <- bigLMStats(lm(boldmat ~ dmnvec + dnz$covariates + dnz$noiseu), 0.001) betas <- mdl$beta.t[1, ] betaImg <- makeImage(boldmask, betas) antsImageWrite(betaImg, "dmnBetas.nii.gz") # this should give default mode network around beta = 12 ## End(Not run)
This function will estimate perfusion from an ASL time series using a (robust) regression approach. It will do motion correction, compcorr, factor out nuisance variables and use regression to estimate the perfusion itself. It will mask the image too based on a simple procedure ( should fix this in the future by allowing the user to optionally pass a mask in from the outside ). WARNING: the function will estimate the m0 image from the mean of the control tags assuming that the data is acquired T C T C as is most of JJ's data. Quantitative CBF can be obtained by mutiplying the output of this function by a scalar.
aslPerfusion( asl, maskThresh = 0.75, moreaccurate = 1, dorobust = 0.92, m0 = NA, skip = 20, mask = NULL, checkmeansignal = 100, moco_results = NULL, regweights = NULL, useDenoiser = NULL, useBayesian = 0, verbose = FALSE, ncompcor = 0, N3 = FALSE )aslPerfusion( asl, maskThresh = 0.75, moreaccurate = 1, dorobust = 0.92, m0 = NA, skip = 20, mask = NULL, checkmeansignal = 100, moco_results = NULL, regweights = NULL, useDenoiser = NULL, useBayesian = 0, verbose = FALSE, ncompcor = 0, N3 = FALSE )
asl |
input asl image |
maskThresh |
for estimating a brain mask |
moreaccurate |
zero, one or two with the last being the most accurate |
dorobust |
robustness parameter, lower value keeps more data |
m0 |
known M0 if any |
skip |
stride to speed up robust regression weight estimates |
mask |
known brain mask |
checkmeansignal |
throw out volumes with mean lower than this thresh |
moco_results |
passes prior motion results so moco does not get repeated |
regweights |
known temporal weights on regression solution, if any |
useDenoiser |
use the aslDenoiser if this value is a range gt than zero |
useBayesian |
strength of bayesian prior |
verbose |
bool |
ncompcor |
number of compcor parameters |
N3 |
bool correct target image before motion corr |
output a list of relevant objects
Avants BB
# image available at http://files.figshare.com/1701182/PEDS012_20131101.zip # fn<-'PEDS012_20131101_pcasl_1.nii.gz' # asl<-antsImageRead(fn,4) set.seed(1) nvox <- 5 * 5 * 5 * 10 dims <- c(5, 5, 5, 10) asl <- makeImage(dims, rnorm(nvox) + 500) %>% iMath("PadImage", 2) aslmean <- getAverageOfTimeSeries(asl) aslmask <- getMask(aslmean, 0.001, Inf) aslmat <- timeseries2matrix(asl, aslmask) for (i in 1:10) aslmat[, i * 2] <- aslmat[, i * 2] * 2 asl <- matrix2timeseries(asl, aslmask, aslmat) # NOT WORKING ## Not run: pcasl.processing <- aslPerfusion(asl, moreaccurate = 1, dorobust = 0) testthat::expect_equal(mean(pcasl.processing$m1), 62.2115522470984) pcasl.processing <- aslPerfusion(asl, moreaccurate = 1, ncompcor = 2) # allow some rejection pcasl.processing <- aslPerfusion(asl, moreaccurate = 1, dorobust = 0.925) ## End(Not run)# image available at http://files.figshare.com/1701182/PEDS012_20131101.zip # fn<-'PEDS012_20131101_pcasl_1.nii.gz' # asl<-antsImageRead(fn,4) set.seed(1) nvox <- 5 * 5 * 5 * 10 dims <- c(5, 5, 5, 10) asl <- makeImage(dims, rnorm(nvox) + 500) %>% iMath("PadImage", 2) aslmean <- getAverageOfTimeSeries(asl) aslmask <- getMask(aslmean, 0.001, Inf) aslmat <- timeseries2matrix(asl, aslmask) for (i in 1:10) aslmat[, i * 2] <- aslmat[, i * 2] * 2 asl <- matrix2timeseries(asl, aslmask, aslmat) # NOT WORKING ## Not run: pcasl.processing <- aslPerfusion(asl, moreaccurate = 1, dorobust = 0) testthat::expect_equal(mean(pcasl.processing$m1), 62.2115522470984) pcasl.processing <- aslPerfusion(asl, moreaccurate = 1, ncompcor = 2) # allow some rejection pcasl.processing <- aslPerfusion(asl, moreaccurate = 1, dorobust = 0.925) ## End(Not run)
A finite mixture modeling (FMM) segmentation approach with possibilities for
specifying prior constraints. These prior constraints include the
specification of a prior label image, prior probability images (one for each
class), and/or an MRF prior to enforce spatial smoothing of the labels.
Similar algorithms include FAST and SPM. atropos can also perform
multivariate segmentation if you pass a list of images in: e.g.
a=c(img1,img2).
atropos( a, x, i = "KMeans[3]", m = "[0.2,1x1]", c = "[5,0]", priorweight = 0.25, verbose = FALSE, use_random_seed = FALSE, ... )atropos( a, x, i = "KMeans[3]", m = "[0.2,1x1]", c = "[5,0]", priorweight = 0.25, verbose = FALSE, use_random_seed = FALSE, ... )
a |
One or more scalar images to segment. If priors are not used, the intensities of the first image are used to order the classes in the segmentation output, from lowest to highest intensity. Otherwise the order of the classes is dictated by the order of the prior images. |
x |
mask image. |
i |
initialization usually |
m |
mrf parameters as a string, usually |
c |
convergence parameters, |
priorweight |
usually 0 (priors used for initialization only), 0.25 or 0.5. |
verbose |
boolean |
use_random_seed |
Initialize internal random number generator with a random seed.
Otherwise, initialize with a constant seed number. If this is |
... |
more parameters, see Atropos help in ANTs |
0 – Success
1 – Failure
Shrinidhi KL, B Avants
img <- antsImageRead(getANTsRData("r16"), 2) img <- resampleImage(img, c(64, 64), 1, 0) mask <- getMask(img) segs1 <- atropos( a = img, m = "[0.2,1x1]", c = "[2,0]", i = "kmeans[3]", x = mask ) # Use probabilities from k-means seg as priors segs2 <- atropos( a = img, m = "[0.2,1x1]", c = "[2,0]", i = segs1$probabilityimages, x = mask ) feats <- list(img, iMath(img, "Laplacian"), iMath(img, "Grad")) segs3 <- atropos( a = feats, m = "[0.2,1x1]", c = "[2,0]", i = segs1$probabilityimages, x = mask )img <- antsImageRead(getANTsRData("r16"), 2) img <- resampleImage(img, c(64, 64), 1, 0) mask <- getMask(img) segs1 <- atropos( a = img, m = "[0.2,1x1]", c = "[2,0]", i = "kmeans[3]", x = mask ) # Use probabilities from k-means seg as priors segs2 <- atropos( a = img, m = "[0.2,1x1]", c = "[2,0]", i = segs1$probabilityimages, x = mask ) feats <- list(img, iMath(img, "Laplacian"), iMath(img, "Grad")) segs3 <- atropos( a = feats, m = "[0.2,1x1]", c = "[2,0]", i = segs1$probabilityimages, x = mask )
This function attempts a standard SVD using base R's svd().
If that fails (typically due to ill-conditioning or non-convergence),
it automatically falls back to a randomized SVD via the rsvd package.
ba_svd( x, nu = min(nrow(x), ncol(x)), nv = min(nrow(x), ncol(x)), dividebymax = FALSE, NA2Noise = TRUE )ba_svd( x, nu = min(nrow(x), ncol(x)), nv = min(nrow(x), ncol(x)), dividebymax = FALSE, NA2Noise = TRUE )
x |
A numeric matrix. |
nu |
Number of left singular vectors to compute.
Default: |
nv |
Number of right singular vectors to compute.
Default: |
dividebymax |
Logical. If TRUE, scale |
NA2Noise |
boolean replaces NA values with small noise values |
Optionally, the matrix can be scaled by its maximum absolute value to improve numerical stability before decomposition.
A list with components u, d, and v, matching
the structure of base R's svd() output.
mat <- matrix(rnorm(100 * 50), 100, 50) sv <- ba_svd(mat, nu = 10, nv = 0)mat <- matrix(rnorm(100 * 50), 100, 50) sv <- ba_svd(mat, nu = 10, nv = 0)
backup simlr implementation
backup_simlr( data_matrices, smoothingMatrices, iterations = 500, sparsenessQuantiles = NULL, positivities = NULL, initialUMatrix = NULL, mixAlg = c("svd", "ica", "avg", "rrpca-l", "rrpca-s", "pca", "stochastic", "newton-schulz", "ica-newton"), repeatedMeasures = NA, lineSearchRange = c(-500, 500), lineSearchTolerance = 1e-12, randomSeed = 0, constraint = c("nsaflowx0.5x10", "orthox0x1", "Grassmannx0", "Stiefelx0", "none"), energyType = c("cca", "regression", "normalized", "ucca", "lowRank", "lowRankRegression", "normalized_correlation", "acc", "nc", "dat", "lrr", "reconorm", "logcosh", "exp", "kurtosis", "gauss"), vmats = NULL, connectors = NULL, optimizationStyle = c("bidirectional_lookahead", "armijo_gradient", "lookahead", "bidirectional_armijo_gradient"), scale = c("center", "eigenvalue"), expBeta = 0.9, jointInitialization = TRUE, sparsenessAlg = "soft", orthogonalizeU = FALSE, domainMatrices = NULL, domainLambdas = NULL, sparse_gradient = TRUE, verbose = FALSE )backup_simlr( data_matrices, smoothingMatrices, iterations = 500, sparsenessQuantiles = NULL, positivities = NULL, initialUMatrix = NULL, mixAlg = c("svd", "ica", "avg", "rrpca-l", "rrpca-s", "pca", "stochastic", "newton-schulz", "ica-newton"), repeatedMeasures = NA, lineSearchRange = c(-500, 500), lineSearchTolerance = 1e-12, randomSeed = 0, constraint = c("nsaflowx0.5x10", "orthox0x1", "Grassmannx0", "Stiefelx0", "none"), energyType = c("cca", "regression", "normalized", "ucca", "lowRank", "lowRankRegression", "normalized_correlation", "acc", "nc", "dat", "lrr", "reconorm", "logcosh", "exp", "kurtosis", "gauss"), vmats = NULL, connectors = NULL, optimizationStyle = c("bidirectional_lookahead", "armijo_gradient", "lookahead", "bidirectional_armijo_gradient"), scale = c("center", "eigenvalue"), expBeta = 0.9, jointInitialization = TRUE, sparsenessAlg = "soft", orthogonalizeU = FALSE, domainMatrices = NULL, domainLambdas = NULL, sparse_gradient = TRUE, verbose = FALSE )
data_matrices |
A list that contains the named matrices. Note: the optimization will likely perform much more smoothly if the input matrices are each scaled to zero mean unit variance e.g. by the |
smoothingMatrices |
list of (sparse) matrices that allow parameter smoothing/regularization. These should be square and same order and size of input matrices. |
iterations |
number of gradient descent iterations |
sparsenessQuantiles |
vector of quantiles to control sparseness - higher is sparser |
positivities |
vector that sets for each matrix if we restrict to positive or negative solution (beta) weights. choices are positive, negative or either as expressed as a string. |
initialUMatrix |
list of initialization matrix size |
mixAlg |
'svd', 'ica', 'rrpca-l', 'rrpca-s', 'stochastic', 'pca', 'newton-schulz', 'ica-newton' or 'avg' denotes the algorithm employed when estimating the mixed modality bases |
repeatedMeasures |
list of repeated measurement identifiers. this will allow estimates of per identifier intercept. |
lineSearchRange |
lower and upper limit used in |
lineSearchTolerance |
tolerance used in |
randomSeed |
controls repeatability of ica-based decomposition |
constraint |
one of none, Grassmann, GrassmannInv or Stiefel |
energyType |
one of regression, normalized, lowRank, cca or ucca |
vmats |
optional initial |
connectors |
a list ( length of projections or number of modalities ) that indicates which modalities should be paired with current modality |
optimizationStyle |
the simlr optimizer |
scale |
options to standardize each matrix. e.g. divide by the square root of its number of variables (Westerhuis, Kourti, and MacGregor 1998), divide by the number of variables or center or center and scale or ... (see code). can be a vector which will apply each strategy in order. |
expBeta |
if greater than zero, use exponential moving average on gradient and mixing (default 0.9). |
jointInitialization |
boolean for initialization options, default TRUE |
sparsenessAlg |
NA is default otherwise basic, spmp or orthorank |
orthogonalizeU |
boolean controlling whether we orthogonalize the U matrices |
domainMatrices |
matrices containing domain knowledge length of |
domainLambdas |
weights for domain knowledge term length of |
sparse_gradient |
boolean default TRUE |
verbose |
boolean to control verbosity of output - set to level |
A data frame label numbers and names for basal forebrain regions.
basal_forebrainbasal_forebrain
A data frame with columns: Label, Description, Side.
Smooths data along the boundary into the missing region.
basicInPaint(img, paintMask, speedimage = NULL, its = 0, gparam = 0.05)basicInPaint(img, paintMask, speedimage = NULL, its = 0, gparam = 0.05)
img |
antsImage to be approximated / painted |
paintMask |
painting mask with values 1 or values 1 and 2 - if there is a 2 then it will learn from label 1 to paint label 2. should cover the brain. |
speedimage |
- larger means faster/better |
its |
- iterations of graddescent |
gparam |
- graddescent param e.g. 0.05 |
inpainted image
Brian B. Avants
set.seed(123) fi <- abs(replicate(100, rnorm(100))) fi[1:10, ] <- fi[, 1:10] <- fi[91:100, ] <- fi[, 91:100] <- 0 mask <- fi mask[mask > 0] <- 1 mask2 <- mask mask2[11:20, 11:20] <- 2 mask <- as.antsImage(mask2) fi <- as.antsImage(fi) fi <- smoothImage(fi, 3) ## Not run: painted <- basicInPaint(fi, mask) ## End(Not run)set.seed(123) fi <- abs(replicate(100, rnorm(100))) fi[1:10, ] <- fi[, 1:10] <- fi[91:100, ] <- fi[, 91:100] <- 0 mask <- fi mask[mask > 0] <- 1 mask2 <- mask mask2[11:20, 11:20] <- 2 mask <- as.antsImage(mask2) fi <- as.antsImage(fi) fi <- smoothImage(fi, 3) ## Not run: painted <- basicInPaint(fi, mask) ## End(Not run)
Employs a robust regression approach to learn the relationship between a sample image and a list of images that are mapped to the same space as the sample image.
bayesianCBF( pcasl, segmentation, tissuelist, myPriorStrength = 30, useDataDrivenMask = 3, denoisingComponents = 1:8, robustnessvalue = 0.95, localweights = FALSE, priorBetas = NA )bayesianCBF( pcasl, segmentation, tissuelist, myPriorStrength = 30, useDataDrivenMask = 3, denoisingComponents = 1:8, robustnessvalue = 0.95, localweights = FALSE, priorBetas = NA )
pcasl |
img antsImage for cbf |
segmentation |
image, should cover the brain. |
tissuelist |
a list containing antsImages eg list(prob1,...,probN) |
myPriorStrength |
- e.g 30 |
useDataDrivenMask |
- morphology parameters e.g. 3 |
denoisingComponents |
- data-driven denoising parameters |
robustnessvalue |
- value (e.g. 0.95) that throws away time points |
localweights |
Use estimate of voxel-wise reliability to inform prior weight? |
priorBetas |
prior betas for each tissue and predictor |
estimated cbf image
Brian Beaumont Avants and Benjamin M. Kandel
## Not run: set.seed(123) # see fMRIANTs github repository for data and I/O suggestions ## End(Not run)## Not run: set.seed(123) # see fMRIANTs github repository for data and I/O suggestions ## End(Not run)
Take a prior mean and precision matrix for the regression solution and uses them to solve for the regression parameters. The Bayesian model, here, is on the multivariate distribution of the parameters.
bayesianlm( X, y, priorMean, priorPrecision, priorIntercept = 0, regweights, includeIntercept = F )bayesianlm( X, y, priorMean, priorPrecision, priorIntercept = 0, regweights, includeIntercept = F )
X |
data matrix |
y |
outcome |
priorMean |
expected parameters |
priorPrecision |
inverse covariance matrix of the parameters - |
priorIntercept |
inverse covariance matrix of the parameters - |
regweights |
weights on each y, a vector as in lm |
includeIntercept |
include the intercept in the model |
bayesian regression solution is output
Avants BB
# make some simple data set.seed(1) n <- 20 rawvars <- sample(1:n) nois <- rnorm(n) # for some reason we dont know age is correlated w/noise age <- as.numeric(rawvars) + (abs(nois)) * sign(nois) wt <- (sqrt(rawvars) + rnorm(n)) mdl <- lm(wt ~ age + nois) summary(mdl) X <- model.matrix(mdl) priorcoeffs <- coefficients(mdl) covMat <- diag(length(priorcoeffs)) + 0.1 # make some new data rawvars2 <- sample(1:n) nois2 <- rnorm(n) # now age is correlated doubly w/noise age2 <- as.numeric(rawvars2) + (abs(nois2)) * sign(nois2) * 2.0 wt2 <- (sqrt(rawvars2) + rnorm(n)) mdl2 <- lm(wt2 ~ age2 + nois2) X2 <- model.matrix(mdl2) precisionMat <- solve(covMat) precisionMat[2, 2] <- precisionMat[2, 2] * 1.e3 # heavy prior on age precisionMat[3, 3] <- precisionMat[3, 3] * 1.e2 # some prior on noise bmdl <- bayesianlm(X2, wt2, priorMean = priorcoeffs, precisionMat) # testthat::expect_equal(bmdl$beta, c(0.157536274628774, -0.224079937323326)) bmdlNoPrior <- bayesianlm(X2, wt2) print(priorcoeffs) print(bmdl$beta) print(bmdlNoPrior$beta) ## Not run: fn <- "PEDS012_20131101_pcasl_1.nii.gz" fn <- getANTsRData("pcasl") # image available at http://files.figshare.com/1701182/PEDS012_20131101.zip asl <- antsImageRead(fn, 4) tr <- antsGetSpacing(asl)[4] aslmean <- getAverageOfTimeSeries(asl) aslmask <- getMask(aslmean, lowThresh = mean(aslmean), cleanup = TRUE) aslmat <- timeseries2matrix(asl, aslmask) tc <- as.factor(rep(c("C", "T"), nrow(aslmat) / 2)) dv <- computeDVARS(aslmat) # do some comparison with a single y, no priors y <- rowMeans(aslmat) perfmodel <- lm(y ~ tc + dv) # standard model tlm <- bigLMStats(perfmodel) X <- model.matrix(perfmodel) blm <- bayesianlm(X, y) print(tlm$beta.p) print(blm$beta.p) # do some bayesian learning based on the data perfmodel <- lm(aslmat ~ tc + dv) # standard model X <- model.matrix(perfmodel) perfmodel <- lm(aslmat ~ tc + dv) bayesianperfusionloc <- rep(0, ncol(aslmat)) smoothcoeffmat <- perfmodel$coefficients nmatimgs <- list() for (i in 1:nrow(smoothcoeffmat)) { temp <- antsImageClone(aslmask) temp[aslmask == 1] <- smoothcoeffmat[i, ] # temp<-iMath(temp,'PeronaMalik',150,10) temp <- smoothImage(temp, 1.5) nmatimgs[[i]] <- getNeighborhoodInMask(temp, aslmask, rep(2, 3), boundary.condition = "mean" ) smoothcoeffmat[i, ] <- temp[aslmask == 1] } prior <- rowMeans(smoothcoeffmat) invcov <- solve(cov(t(smoothcoeffmat))) blm2 <- bayesianlm(X, y, prior, invcov * 1.e4) print(blm2$beta.p) for (i in 1:ncol(aslmat)) { parammat <- nmatimgs[[1]][, i] for (k in 2:length(nmatimgs)) { parammat <- cbind(parammat, nmatimgs[[k]][, i]) } locinvcov <- solve(cov(parammat)) localprior <- (smoothcoeffmat[, i]) blm <- bayesianlm(X, aslmat[, i], localprior, locinvcov * 1.e4) bayesianperfusionloc[i] <- blm$beta[1] } perfimg <- antsImageClone(aslmask) basicperf <- bigLMStats(perfmodel)$beta[1, ] perfimg[aslmask == 1] <- basicperf antsImageWrite(perfimg, "perf.nii.gz") perfimg[aslmask == 1] <- bayesianperfusionloc antsImageWrite(perfimg, "perf_bayes.nii.gz") print(cor.test(basicperf, perfimg[aslmask == 1])) ## End(Not run)# make some simple data set.seed(1) n <- 20 rawvars <- sample(1:n) nois <- rnorm(n) # for some reason we dont know age is correlated w/noise age <- as.numeric(rawvars) + (abs(nois)) * sign(nois) wt <- (sqrt(rawvars) + rnorm(n)) mdl <- lm(wt ~ age + nois) summary(mdl) X <- model.matrix(mdl) priorcoeffs <- coefficients(mdl) covMat <- diag(length(priorcoeffs)) + 0.1 # make some new data rawvars2 <- sample(1:n) nois2 <- rnorm(n) # now age is correlated doubly w/noise age2 <- as.numeric(rawvars2) + (abs(nois2)) * sign(nois2) * 2.0 wt2 <- (sqrt(rawvars2) + rnorm(n)) mdl2 <- lm(wt2 ~ age2 + nois2) X2 <- model.matrix(mdl2) precisionMat <- solve(covMat) precisionMat[2, 2] <- precisionMat[2, 2] * 1.e3 # heavy prior on age precisionMat[3, 3] <- precisionMat[3, 3] * 1.e2 # some prior on noise bmdl <- bayesianlm(X2, wt2, priorMean = priorcoeffs, precisionMat) # testthat::expect_equal(bmdl$beta, c(0.157536274628774, -0.224079937323326)) bmdlNoPrior <- bayesianlm(X2, wt2) print(priorcoeffs) print(bmdl$beta) print(bmdlNoPrior$beta) ## Not run: fn <- "PEDS012_20131101_pcasl_1.nii.gz" fn <- getANTsRData("pcasl") # image available at http://files.figshare.com/1701182/PEDS012_20131101.zip asl <- antsImageRead(fn, 4) tr <- antsGetSpacing(asl)[4] aslmean <- getAverageOfTimeSeries(asl) aslmask <- getMask(aslmean, lowThresh = mean(aslmean), cleanup = TRUE) aslmat <- timeseries2matrix(asl, aslmask) tc <- as.factor(rep(c("C", "T"), nrow(aslmat) / 2)) dv <- computeDVARS(aslmat) # do some comparison with a single y, no priors y <- rowMeans(aslmat) perfmodel <- lm(y ~ tc + dv) # standard model tlm <- bigLMStats(perfmodel) X <- model.matrix(perfmodel) blm <- bayesianlm(X, y) print(tlm$beta.p) print(blm$beta.p) # do some bayesian learning based on the data perfmodel <- lm(aslmat ~ tc + dv) # standard model X <- model.matrix(perfmodel) perfmodel <- lm(aslmat ~ tc + dv) bayesianperfusionloc <- rep(0, ncol(aslmat)) smoothcoeffmat <- perfmodel$coefficients nmatimgs <- list() for (i in 1:nrow(smoothcoeffmat)) { temp <- antsImageClone(aslmask) temp[aslmask == 1] <- smoothcoeffmat[i, ] # temp<-iMath(temp,'PeronaMalik',150,10) temp <- smoothImage(temp, 1.5) nmatimgs[[i]] <- getNeighborhoodInMask(temp, aslmask, rep(2, 3), boundary.condition = "mean" ) smoothcoeffmat[i, ] <- temp[aslmask == 1] } prior <- rowMeans(smoothcoeffmat) invcov <- solve(cov(t(smoothcoeffmat))) blm2 <- bayesianlm(X, y, prior, invcov * 1.e4) print(blm2$beta.p) for (i in 1:ncol(aslmat)) { parammat <- nmatimgs[[1]][, i] for (k in 2:length(nmatimgs)) { parammat <- cbind(parammat, nmatimgs[[k]][, i]) } locinvcov <- solve(cov(parammat)) localprior <- (smoothcoeffmat[, i]) blm <- bayesianlm(X, aslmat[, i], localprior, locinvcov * 1.e4) bayesianperfusionloc[i] <- blm$beta[1] } perfimg <- antsImageClone(aslmask) basicperf <- bigLMStats(perfmodel)$beta[1, ] perfimg[aslmask == 1] <- basicperf antsImageWrite(perfimg, "perf.nii.gz") perfimg[aslmask == 1] <- bayesianperfusionloc antsImageWrite(perfimg, "perf_bayes.nii.gz") print(cor.test(basicperf, perfimg[aslmask == 1])) ## End(Not run)
This function simplifies calculating p-values from linear models in which
there are many outcome variables, such as in voxel-wise regressions. To
perform such an analysis in R, you can concatenate the outcome variables
column-wise into an n by p matrix y, where there are n subjects and p
outcomes (see Examples). Calling lm(y~x) calculates the
coefficients, but statistical inference is not provided. This function
provides basic statistical inference efficiently.
bigLMStats(mylm, lambda = 0, includeIntercept = FALSE)bigLMStats(mylm, lambda = 0, includeIntercept = FALSE)
mylm |
Object of class |
lambda |
Value of ridge penalty for inverting ill-conditioned matrices. |
includeIntercept |
Whether or not to include p-values for intercept term in result. |
A list containing objects:
fstat |
F-statistic of whole model (one value per outcome). |
pval.model |
p-value of model (one value per outcome). |
beta |
Values of coefficients (one value per predictor per outcome). |
beta.std |
Standard error of coefficients. |
beta.t |
T-statistic of coefficients. |
beta.pval |
p-value of coefficients. |
Kandel BM.
nsub <- 100 set.seed(1500) x <- 1:nsub y <- matrix(c(x + rnorm(nsub), sin(x)), nrow = nsub) x <- cbind(x, x^2) y1 <- y[, 1] y2 <- y[, 2] lm1 <- lm(y1 ~ x) lm2 <- lm(y2 ~ x) mylm <- lm(y ~ x) myest <- bigLMStats(mylm) print(paste( "R beta estimates for first outcome is", summary(lm1)$coefficients[-1, 1], "and for second outcome is", summary(lm2)$coefficients[-1, 1] )) print(paste("and our estimate is", as.numeric(myest$beta[, 1]), as.numeric(myest$beta[, 2]))) print(paste( "R std error estimate for first outcome is", summary(lm1)$coefficients[-1, 2], "and for second outcome is", summary(lm2)$coefficients[-1, 2], "and our estimate is", myest$beta.std[, 1], myest$beta.std[, 2] )) print(paste( "R t value estimate for first outcome is", summary(lm1)$coefficients[-1, 3], "and for second outcome is", summary(lm2)$coefficients[-1, 3], "and our estimate is", myest$beta.t[, 1], myest$beta.t[, 2] )) print(paste( "R pval for first outcome is", summary(lm1)$coefficients[-1, 4], "and for second outcome is", summary(lm2)$coefficients[-1, 4], "and our estimate is", myest$beta.pval[, 1], myest$beta.pval[, 2] ))nsub <- 100 set.seed(1500) x <- 1:nsub y <- matrix(c(x + rnorm(nsub), sin(x)), nrow = nsub) x <- cbind(x, x^2) y1 <- y[, 1] y2 <- y[, 2] lm1 <- lm(y1 ~ x) lm2 <- lm(y2 ~ x) mylm <- lm(y ~ x) myest <- bigLMStats(mylm) print(paste( "R beta estimates for first outcome is", summary(lm1)$coefficients[-1, 1], "and for second outcome is", summary(lm2)$coefficients[-1, 1] )) print(paste("and our estimate is", as.numeric(myest$beta[, 1]), as.numeric(myest$beta[, 2]))) print(paste( "R std error estimate for first outcome is", summary(lm1)$coefficients[-1, 2], "and for second outcome is", summary(lm2)$coefficients[-1, 2], "and our estimate is", myest$beta.std[, 1], myest$beta.std[, 2] )) print(paste( "R t value estimate for first outcome is", summary(lm1)$coefficients[-1, 3], "and for second outcome is", summary(lm2)$coefficients[-1, 3], "and our estimate is", myest$beta.t[, 1], myest$beta.t[, 2] )) print(paste( "R pval for first outcome is", summary(lm1)$coefficients[-1, 4], "and for second outcome is", summary(lm2)$coefficients[-1, 4], "and our estimate is", myest$beta.pval[, 1], myest$beta.pval[, 2] ))
Create the block BOLD stimulus for a given task indicator function. Current units in terms of volumes. Sort of a bug, should be in TR.
blockStimulus(scans = 1, onsets = c(1), durations = c(1), rt = 3)blockStimulus(scans = 1, onsets = c(1), durations = c(1), rt = 3)
scans |
number of scans |
onsets |
vector of onset times (in scans) |
durations |
vector of duration of ON stimulus in scans or seconds (if
|
rt |
time between scans in seconds (TR) |
None
Vector with dimension c(scans, 1).
b avants [email protected]
Worsley, K.J., Liao, C., Aston, J., Petre, V., Duncan, G.H., Morales, F., Evans, A.C. (2002). A general statistical analysis for fMRI data. NeuroImage, 15:1-15.
# Example 1 hrf <- blockStimulus(107, c(18, 48, 78), 15, 2)# Example 1 hrf <- blockStimulus(107, c(18, 48, 78), 15, 2)
Implementation of the deconvolution technique of Ostergaard et al. (https://pubmed.ncbi.nlm.nih.gov/8916023) for calculating cerebral (or pulmonary) blood flow. Other relevant references include https://pubmed.ncbi.nlm.nih.gov/16261573, https://pubmed.ncbi.nlm.nih.gov/8916023, and https://pubmed.ncbi.nlm.nih.gov/15332240.
bloodPerfusionSVD( perfusionImage, voiMaskImage, aifMaskImage, thresholdSVD = 0.2, deltaTime = 1 )bloodPerfusionSVD( perfusionImage, voiMaskImage, aifMaskImage, thresholdSVD = 0.2, deltaTime = 1 )
perfusionImage |
time series (n-D + time) perfusion acquisition. |
voiMaskImage |
n-D mask image indicating where the cerebral blood flow parameter images are calculated. |
aifMaskImage |
n-D mask image indicating where the arterial input function is calculated. |
thresholdSVD |
is used to threshold the smaller elements of the diagonal matrix during the SVD regularization. 0.2 is a common choice (cf. page 571, end of column 2 in https://pubmed.ncbi.nlm.nih.gov/16971140). |
deltaTime |
time between volumetric acquisitions. We assume a uniform time sampling. |
list with the cerebral blood flow image (cbfImage), cerebral blood volume image (cbvImage), mean transit time (mttImage), and arterial input function signal from the image (aifSignal) and the calculated arterial input function concentration (aifConcentration).
Tustison NJ
## Not run: perfusionFileName <- "" if (file.exists(perfusionFileName)) { perfusionImage <- antsImageRead( filename = perfusionFileName, dimension = 4, pixeltype = "float" ) voiMaskImage <- antsImageRead( filename = voiMaskFileName, dimension = 3, pixeltype = "unsigned int" ) aifMaskImage <- antsImageRead( filename = aifMaskFileName, dimension = 3, pixeltype = "unsigned int" ) deltaTime <- 3.4 results <- bloodPerfusionSVD(perfusionImage, voiMaskImage, aifMaskImage, thresholdSVD = 0.2, deltaTime = deltaTime ) antsImageWrite(results$cbfImage, paste0("cbf.nii.gz")) antsImageWrite(results$cbvImage, paste0("cpbv.nii.gz")) antsImageWrite(results$mttImage, paste0("mtt.nii.gz")) } ## End(Not run)## Not run: perfusionFileName <- "" if (file.exists(perfusionFileName)) { perfusionImage <- antsImageRead( filename = perfusionFileName, dimension = 4, pixeltype = "float" ) voiMaskImage <- antsImageRead( filename = voiMaskFileName, dimension = 3, pixeltype = "unsigned int" ) aifMaskImage <- antsImageRead( filename = aifMaskFileName, dimension = 3, pixeltype = "unsigned int" ) deltaTime <- 3.4 results <- bloodPerfusionSVD(perfusionImage, voiMaskImage, aifMaskImage, thresholdSVD = 0.2, deltaTime = deltaTime ) antsImageWrite(results$cbfImage, paste0("cbf.nii.gz")) antsImageWrite(results$cbvImage, paste0("cpbv.nii.gz")) antsImageWrite(results$mttImage, paste0("mtt.nii.gz")) } ## End(Not run)
A data frame with an example square BOLD correlation matrix.
bold_correlation_matrixbold_correlation_matrix
A data frame square correlation matrix listed by AAL anatomical column names.
https://en.wikipedia.org/wiki/Automated_Anatomical_Labeling
data(bold_correlation_matrix)data(bold_correlation_matrix)
Computes the boxplot of values of an image with the option for a mask.
## S3 method for class 'antsImage' boxplot(x, ..., mask)## S3 method for class 'antsImage' boxplot(x, ..., mask)
x |
Object of class |
... |
Arguments passed to |
mask |
object to subset the image. If missing, then all values of the image are plotted. |
Output of boxplot
img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 boxplot(img, mask = mask)img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 boxplot(img, mask = mask)
Iteratively estimate a population shape and intensity average image. This
can be computationally intensive and currently is not parallelized. Perhaps
better to use official antsMultivariateTemplateConstruction* in ANTs.
However, this code can be useful for smaller problems/populations.
buildTemplate( initialTemplate, imgList, typeofTransform, iterations = 3, gradientStep = 0.25, blendingWeight = 0.5, segList, weights, verbose = TRUE, ... )buildTemplate( initialTemplate, imgList, typeofTransform, iterations = 3, gradientStep = 0.25, blendingWeight = 0.5, segList, weights, verbose = TRUE, ... )
initialTemplate |
fixed image to which we register the population. |
imgList |
moving image list from which template will be built. |
typeofTransform |
A linear or non-linear registration type. Mutual
information metric by default. See |
iterations |
should be greater than 1 less than 10. |
gradientStep |
speed of template shape update step, less than 1. |
blendingWeight |
parameter between zero and one, default 0.5; higher values lead to sharper intensity but may also cause artifacts. |
segList |
segmentations for each target image, this will trigger a joint label fusion call for each iteration and use masks during registration. |
weights |
numeric vector, length of number of images providing weights |
verbose |
print diagnostic messages,
passed to |
... |
Additional options to pass to |
template antsImage
Avants BB
pop <- getANTsRData("population") avg <- antsAverageImages(pop) # this is in ANTsR template <- buildTemplate(avg, pop, "SyN", iterations = 1)pop <- getANTsRData("population") avg <- antsAverageImages(pop) # this is in ANTsR template <- buildTemplate(avg, pop, "SyN", iterations = 1)
Computes the energy for SiMLR based on the specified energy type, with partial matching for energy_type. Returns negative values for maximization objectives to align with minimization goals.
calculate_simlr_energy( V, X, U, energy_type, lambda = 1, prior_matrix = NULL, verbose = 0 )calculate_simlr_energy( V, X, U, energy_type, lambda = 1, prior_matrix = NULL, verbose = 0 )
V |
Matrix V in the SiMLR decomposition. |
X |
Data matrix for the modality. |
U |
Matrix U in the SiMLR decomposition. |
energy_type |
Character string specifying the energy type. Supports partial matching (e.g., "reg" for "regression", "cca" for "cca" or "acc"). Valid options: regression, reconorm, lowRankRegression, lrr, cca, acc, logcosh, kurtosis, exp, gauss, normalized_correlation, dat. |
lambda |
Numeric, weight for domain energy (default = 1.0). |
prior_matrix |
Optional prior matrix for domain energy (used with "dat"). |
verbose |
Integer, verbosity level: 0 (none), 1 (log matched energy_type) (default = 0). |
Numeric energy value (negative for maximization objectives).
This dispatcher computes the gradient for the similarity part of the SiMLR objective, ensuring it is a descent direction for the energy function. Supports partial matching for energy_type.
calculate_simlr_gradient( V, X, U, energy_type, clipping_threshold = NULL, lambda = 1, prior_matrix = NULL, verbose = 0 )calculate_simlr_gradient( V, X, U, energy_type, clipping_threshold = NULL, lambda = 1, prior_matrix = NULL, verbose = 0 )
V |
The current loading matrix [p x k]. |
X |
The data matrix for the modality [n x p]. |
U |
The shared basis matrix [n x k]. |
energy_type |
Character string specifying the similarity objective. Supports partial matching (e.g., "reg" for "regression", "cca" for "cca" or "acc"). Valid options: regression, reconorm, lowRankRegression, lrr, cca, acc, normalized_correlation, nc, logcosh, kurtosis, exp, gauss, dat. |
clipping_threshold |
Optional numeric value for gradient clipping. |
lambda |
Numeric, weight for domain energy (default = 1.0). |
prior_matrix |
Optional matrix of prior weights, same shape as V (used with "dat"). |
verbose |
Integer, verbosity level: 0 (none), 1 (log matched energy_type) (default = 0). |
A matrix [p x k] representing the descent direction.
A data frame label numbers and names for cerebellum regions.
cerebellum_labelscerebellum_labels
A data frame with columns: Label, Description.
Simple check to see if input is character, list, nifti,
or class antsImage
check_ants(x, ...) ## S4 method for signature 'antsImage' check_ants(x, ...) ## S4 method for signature 'ANY' check_ants(x, ...) ## S4 method for signature 'character' check_ants(x, ...) ## S4 method for signature 'list' check_ants(x, ...)check_ants(x, ...) ## S4 method for signature 'antsImage' check_ants(x, ...) ## S4 method for signature 'ANY' check_ants(x, ...) ## S4 method for signature 'character' check_ants(x, ...) ## S4 method for signature 'list' check_ants(x, ...)
x |
character path of image or an object of class antsImage |
... |
arguments passed to other methods,
namely |
antsImage object
John Muschelli [email protected]
This function checks a numeric matrix for rows or columns with zero variance. It reports how many and which ones are affected, using either their names (if present) or indices.
check_zero_variance(mat)check_zero_variance(mat)
mat |
A numeric matrix. |
Zero variance means all values in a row or column are identical
(after removing NAs).
Boolean checking if any zero-variance rows or columns found.
m <- matrix(c(1, 1, 1, 2, 3, 4, 5, 6, 7), nrow = 3, byrow = TRUE) rownames(m) <- c("rowA", "rowB", "rowC") colnames(m) <- c("colX", "colY", "colZ") check_zero_variance(m)m <- matrix(c(1, 1, 1, 2, 3, 4, 5, 6, 7), nrow = 3, byrow = TRUE) rownames(m) <- c("rowA", "rowB", "rowC") colnames(m) <- c("colX", "colY", "colZ") check_zero_variance(m)
A data frame label numbers and names for the CIT168 brainstem atlas.
cit168_brainstemcit168_brainstem
A data frame with columns: Label, Description, Side.
A data frame label numbers and names for the CIT168 reinforcement learning atlas.
cit168_reinf_learncit168_reinf_learn
A data frame with columns: Label, Description.
CIT168 reinforcement learning atlas label descriptions
This function provides an adaptive method for controlling gradient magnitudes. It calculates a threshold based on a specified quantile of the absolute values within the gradient matrix itself. Any value exceeding this dynamic threshold is "clipped" or shrunk back to the threshold, preserving its original sign.
clip_gradient_by_quantile(gradient, quantile = 0.8)clip_gradient_by_quantile(gradient, quantile = 0.8)
gradient |
The gradient matrix to be clipped. |
quantile |
The quantile to use for determining the clipping threshold. For example, a value of '0.98' means that any gradient value larger in magnitude than the 98th percentile of all absolute gradient values will be clipped. Must be between 0 and 1. |
This is more robust than a fixed threshold as it automatically adapts to the scale of the gradients at each optimization step.
A new gradient matrix with extreme values clipped.
# Create a gradient with some large outlier values set.seed(123) grad_matrix <- matrix(rnorm(100, mean = 0, sd = 1), 10, 10) grad_matrix[1, 1] <- 10 # Large positive outlier grad_matrix[5, 5] <- -12 # Large negative outlier # Clip at the 80th percentile. This will tame the outliers. clipped_grad <- clip_gradient_by_quantile(grad_matrix, quantile = 0.80) cat("Original Gradient Range:\n") print(range(grad_matrix)) cat("\n80th Percentile Threshold:\n") # The threshold will be the 80th percentile of the absolute values print(quantile(abs(grad_matrix), probs = 0.80)) cat("\nClipped Gradient Range:\n") # The new range will be capped at the threshold print(range(clipped_grad))# Create a gradient with some large outlier values set.seed(123) grad_matrix <- matrix(rnorm(100, mean = 0, sd = 1), 10, 10) grad_matrix[1, 1] <- 10 # Large positive outlier grad_matrix[5, 5] <- -12 # Large negative outlier # Clip at the 80th percentile. This will tame the outliers. clipped_grad <- clip_gradient_by_quantile(grad_matrix, quantile = 0.80) cat("Original Gradient Range:\n") print(range(grad_matrix)) cat("\n80th Percentile Threshold:\n") # The threshold will be the 80th percentile of the absolute values print(quantile(abs(grad_matrix), probs = 0.80)) cat("\nClipped Gradient Range:\n") # The new range will be capped at the threshold print(range(clipped_grad))
This function prevents exploding gradients by rescaling any gradient whose Frobenius norm exceeds a specified threshold. The direction of the gradient is preserved.
This function prevents exploding gradients by rescaling any gradient whose Frobenius norm exceeds a specified threshold. The direction of the gradient is preserved.
clip_gradient_norm(gradient, threshold = 1) clip_gradient_norm(gradient, threshold = 1)clip_gradient_norm(gradient, threshold = 1) clip_gradient_norm(gradient, threshold = 1)
gradient |
The gradient matrix to be clipped. |
threshold |
The maximum allowed Frobenius norm for the gradient. |
A gradient matrix whose Frobenius norm is guaranteed to be less than or equal to the threshold.
A gradient matrix whose Frobenius norm is guaranteed to be less than or equal to the threshold.
Uses clustering methods to split a time series into similar subsets.
clusterTimeSeries(mat, krange = 2:10, nsvddims = NA, criterion = "asw")clusterTimeSeries(mat, krange = 2:10, nsvddims = NA, criterion = "asw")
mat |
input time series matrix |
krange |
k cluster range to explore |
nsvddims |
eg 2 |
criterion |
for clustering see pamk |
matrix is output
Avants BB
## Not run: if (!exists("fn")) fn <- getANTsRData("pcasl") # high motion subject asl <- antsImageRead(fn, 4) tr <- antsGetSpacing(asl)[4] aslmean <- getAverageOfTimeSeries(asl) aslmask <- getMask(aslmean, lowThresh = mean(aslmean), cleanup = TRUE) omat <- timeseries2matrix(asl, aslmask) clustasl <- clusterTimeSeries(omat, krange = 4:10) for (ct in 1:max(clustasl$clusters)) { sel <- clustasl$clusters != ct img <- matrix2timeseries(asl, aslmask, omat[sel, ]) perf <- aslPerfusion(img, dorobust = 0.9, useDenoiser = 4, skip = 10, useBayesian = 0, moreaccurate = 0, verbose = F, mask = aslmask ) perfp <- list(sequence = "pcasl", m0 = perf$m0) cbf <- quantifyCBF(perf$perfusion, perf$mask, perfp) } ## End(Not run)## Not run: if (!exists("fn")) fn <- getANTsRData("pcasl") # high motion subject asl <- antsImageRead(fn, 4) tr <- antsGetSpacing(asl)[4] aslmean <- getAverageOfTimeSeries(asl) aslmask <- getMask(aslmean, lowThresh = mean(aslmean), cleanup = TRUE) omat <- timeseries2matrix(asl, aslmask) clustasl <- clusterTimeSeries(omat, krange = 4:10) for (ct in 1:max(clustasl$clusters)) { sel <- clustasl$clusters != ct img <- matrix2timeseries(asl, aslmask, omat[sel, ]) perf <- aslPerfusion(img, dorobust = 0.9, useDenoiser = 4, skip = 10, useBayesian = 0, moreaccurate = 0, verbose = F, mask = aslmask ) perfp <- list(sequence = "pcasl", m0 = perf$m0) cbf <- quantifyCBF(perf$perfusion, perf$mask, perfp) } ## End(Not run)
Creates a logical array from an antsImage object
coerce_mask(x, error = TRUE)coerce_mask(x, error = TRUE)
x |
antsImage object |
error |
should the function error if the mask as not binary? |
Array, logical if all values within 0, 1, NA, and NaN
img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 coerce_mask(mask, error = TRUE) coerce_mask(mask + 1, error = FALSE) testthat::expect_error(coerce_mask(mask + 1, error = TRUE)) coerce_mask(as.array(mask) > 0, error = FALSE)img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 coerce_mask(mask, error = TRUE) coerce_mask(mask + 1, error = FALSE) testthat::expect_error(coerce_mask(mask + 1, error = TRUE)) coerce_mask(as.array(mask) > 0, error = FALSE)
Combine and select nuisance predictors to maximize
correlation between inmat and target.
combineNuisancePredictors( inmat, target, globalpredictors = NA, maxpreds = 4, localpredictors = NA, method = "cv", k = 5, covariates = NA, ordered = FALSE )combineNuisancePredictors( inmat, target, globalpredictors = NA, maxpreds = 4, localpredictors = NA, method = "cv", k = 5, covariates = NA, ordered = FALSE )
inmat |
Input predictor matrix. |
target |
Target outcome matrix. |
globalpredictors |
Global predictors of size |
maxpreds |
Maximum number of predictors to output. |
localpredictors |
Local predictor array of size |
method |
Method of selecting noisy voxels. One of 'svd' or 'cv'.
See |
k |
Number of cross-validation folds. |
covariates |
Covariates to be considered when assessing prediction
of |
ordered |
Can the predictors be assumed to be ordered from most important to least important, as in output from PCA? Computation is much faster if so. |
Array of size nrow(aslmat) by npreds,
containing a timeseries of all the nuisance predictors.
If localpredictors is not NA, array is of size nrow(aslmat)
by ncol(aslmat) by npreds.
Benjamin M. Kandel, Brian B. Avants
Compcors the input matrix using SVD and returns the result.
compcor( fmri, ncompcor = 4, variance_extreme = 0.975, mask = NULL, randomSamples = 1, returnv = FALSE, returnhighvarmat = FALSE, returnhighvarmatinds = FALSE, highvarmatinds = NA, scale = TRUE )compcor( fmri, ncompcor = 4, variance_extreme = 0.975, mask = NULL, randomSamples = 1, returnv = FALSE, returnhighvarmat = FALSE, returnhighvarmatinds = FALSE, highvarmatinds = NA, scale = TRUE )
fmri |
input fmri image or matrix |
ncompcor |
n compcor vectors |
variance_extreme |
high variance threshold e.g 0.95 for 95 percent |
mask |
optional mask for image |
randomSamples |
take this many random samples to speed things up |
returnv |
return the spatial vectors |
returnhighvarmat |
bool to return the high variance matrix |
returnhighvarmatinds |
bool to return the high variance matrix indices |
highvarmatinds |
index list |
scale |
scale the matrix of high variance voxels, default FALSE. note that you may get slightly different results by scaling the input matrix before passing into this function. |
dataframe of nuisance predictors is output
Avants BB
mat <- matrix(rnorm(50000), ncol = 500) compcorrdf <- compcor(mat)mat <- matrix(rnorm(50000), ncol = 500) compcorrdf <- compcor(mat)
compose multiple transforms
composeAntsrTransforms(transformList)composeAntsrTransforms(transformList)
transformList |
a list of antsrTransforms in the reverse order they should be applied |
antsrTransform of type "CompositeTransform"
tx <- new("antsrTransform", precision = "float", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0, -1, 1, 0, 0, 0)) tx2 <- new("antsrTransform", precision = "float", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx2, c(0, -1, 1, 0, 0, 0)) tx3 <- composeAntsrTransforms(list(tx, tx2))tx <- new("antsrTransform", precision = "float", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0, -1, 1, 0, 0, 0)) tx2 <- new("antsrTransform", precision = "float", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx2, c(0, -1, 1, 0, 0, 0)) tx3 <- composeAntsrTransforms(list(tx, tx2))
Compose displacement fields.
composeDisplacementFields(displacementField, warpingField)composeDisplacementFields(displacementField, warpingField)
displacementField |
displacement field. |
warpingField |
warping field. |
composite displacement field
NJ Tustison
A deformation field can capture any domain to domain correspondence that we can represent in ANTsR. This function will map a list of transforms into a single deformation field object.
composeTransformsToField(image, transforms)composeTransformsToField(image, transforms)
image |
input image defines the transformation domain |
transforms |
list of transform filenames or antrTransforms |
field deformation object is output
Avants BB, Duda JT
fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r64")) fi <- resampleImage(fi, c(60, 60), 1, 0) mi <- resampleImage(mi, c(60, 60), 1, 0) # speed up mytx <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) compfield <- composeTransformsToField(fi, mytx$fwd) atx <- antsrTransformFromDisplacementField(compfield) wrped <- applyAntsrTransformToImage(atx, mi, fi)fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r64")) fi <- resampleImage(fi, c(60, 60), 1, 0) mi <- resampleImage(mi, c(60, 60), 1, 0) # speed up mytx <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) compfield <- composeTransformsToField(fi, mytx$fwd) atx <- antsrTransformFromDisplacementField(compfield) wrped <- applyAntsrTransformToImage(atx, mi, fi)
This function calculates the communality for each variable in the dataset, defined as the proportion of variance explained by the factor scores (R^2 from multiple linear regression of each variable on the scores). It provides an empirical estimate of how much each variable's variance is accounted for by the common factors. The function assumes the data is centered or standardized as appropriate for factor analysis.
compute_communalities(data, scores)compute_communalities(data, scores)
data |
Numeric matrix or data.frame with n rows (observations) and p columns (variables). |
scores |
Numeric matrix of factor scores with n rows and k columns (factors). |
For each variable, a linear model is fit: lm(data[, i] ~ scores), and
the R^2 is extracted. This aligns with model-based communalities in factor
analysis for large samples but may slightly overestimate due to in-sample
fitting. For efficiency with large p, consider matrix-based alternatives, but
this loop-based approach is simple and leverages base R.
A named numeric vector of length p containing the communalities for
each variable, named by the column names of data (if available).
## Not run: # Synthetic data example set.seed(42) n <- 100; p <- 5; k <- 2 scores <- matrix(rnorm(n * k), n, k) loadings <- matrix(runif(p * k, 0.5, 0.8), p, k) data <- scores %*% t(loadings) + matrix(rnorm(n * p, sd = 0.5), n, p) colnames(data) <- paste0("Var", 1:p) comm <- compute_communalities(data, scores) print(comm) ## End(Not run)## Not run: # Synthetic data example set.seed(42) n <- 100; p <- 5; k <- 2 scores <- matrix(rnorm(n * k), n, k) loadings <- matrix(runif(p * k, 0.5, 0.8), p, k) data <- scores %*% t(loadings) + matrix(rnorm(n * p, sd = 0.5), n, p) colnames(data) <- paste0("Var", 1:p) comm <- compute_communalities(data, scores) print(comm) ## End(Not run)
This function calculates the variance explained by each factor in a factor analysis model.
compute_variance_explained_per_factor(data, scores, method = "PAF")compute_variance_explained_per_factor(data, scores, method = "PAF")
data |
A numeric matrix or data frame of observed variables (n x p). |
scores |
A numeric matrix of factor scores (n x k). |
method |
A string indicating the factor analysis method (e.g., "PAF"). |
A data frame with the variance explained by each factor.
# data(mtcars) # fa_result <- factanal(mtcars, factors = 2) # scores <- fa_result$scores # compute_variance_explained_per_factor(mtcars, scores)# data(mtcars) # fa_result <- factanal(mtcars, factors = 2) # scores <- fa_result$scores # compute_variance_explained_per_factor(mtcars, scores)
compute the DVARS quality control metric
computeDVARS(boldMatrix)computeDVARS(boldMatrix)
boldMatrix |
matrix of bold signal |
DVARS vector.
Tustison NJ, Avants BB
mat <- matrix(c(0, 1, 2, 0, 0, 1, 2, 2, 2), ncol = 3) dv <- computeDVARS(mat)mat <- matrix(c(0, 1, 2, 0, 0, 1, 2, 2, 2), ncol = 3) dv <- computeDVARS(mat)
compute the DVARS quality control metric at every voxel
computeDVARSspatialMap(boldMatrix)computeDVARSspatialMap(boldMatrix)
boldMatrix |
matrix of bold signal |
DVARS spatial vector.
Tustison NJ, Avants BB
mat <- matrix(c(0, 1, 2, 0, 0, 1, 2, 2, 2), ncol = 3) dv <- computeDVARSspatialMap(mat)mat <- matrix(c(0, 1, 2, 0, 0, 1, 2, 2, 2), ncol = 3) dv <- computeDVARSspatialMap(mat)
A helper function to generate a character vector of SiMLR feature names based on a set of modality prefixes and numeric indices.
construct_sim_names(base_names, indices)construct_sim_names(base_names, indices)
base_names |
A character vector of modality prefixes (e.g., c("t1", "dt", "rsf")). |
indices |
An integer vector of component indices (e.g., 1:10). |
A character vector of combined names (e.g., "t1PC1", "dtPC1", ... "rsfPC10").
modalities <- c("t1", "dt", "rsf") components <- 1:3 construct_sim_names(modalities, components)modalities <- c("t1", "dt", "rsf") components <- 1:3 construct_sim_names(modalities, components)
convolves images together
convolveImage(image, kernelImage, crop = TRUE)convolveImage(image, kernelImage, crop = TRUE)
image |
antsImage to convolve |
kernelImage |
antsImage acting as kernel |
crop |
boolean automatically crops kernelImage |
convimage
Brian B. Avants
fi <- antsImageRead(getANTsRData("r16"), 2) convimg <- makeImage(c(3, 3), c(1, 0, 1, 0, -4, 0, 1, 0, 1)) convout <- convolveImage(fi, convimg) convimg2 <- makeImage(c(3, 3), c(0, 1, 0, 1, 0, -1, 0, -1, 0)) convout2 <- convolveImage(fi, convimg2)fi <- antsImageRead(getANTsRData("r16"), 2) convimg <- makeImage(c(3, 3), c(1, 0, 1, 0, -4, 0, 1, 0, 1)) convout <- convolveImage(fi, convimg) convimg2 <- makeImage(c(3, 3), c(0, 1, 0, 1, 0, -1, 0, -1, 0)) convout2 <- convolveImage(fi, convimg2)
Uses weighted regression to compute pairwise correlation matrix on input matrix - by columns.
corw(mat, weights)corw(mat, weights)
mat |
input matrix |
weights |
input weights, size of nrow of matrix |
matrix is output
Avants BB
mat <- matrix(rnorm(100), nrow = 10) wcmat <- corw(mat, weights = abs(nrorm(nrow(mat))))mat <- matrix(rnorm(100), nrow = 10) wcmat <- corw(mat, weights = abs(nrorm(nrow(mat))))
This factory function creates an optimizer object that holds the state and update logic for a chosen optimization strategy.
create_optimizer(optimizer_type = "hybrid_adam", vmats, ...)create_optimizer(optimizer_type = "hybrid_adam", vmats, ...)
optimizer_type |
A string identifying the optimizer. One of: "hybrid_adam" (Adam direction with Armijo line search - robust), "adam" (Adam with a learning rate schedule - fast), "nadam" (Nesterov-accelerated Adam - fast and robust), "sgd_momentum" (SGD with momentum and learning rate schedule - classic), "armijo_gradient" (steepest descent with robust Armijo backtracking line search - maximally robust). |
vmats |
The list of initial V matrices, used to set up the dimensions of the optimizer's internal state variables. |
... |
Additional hyperparameters for the optimizer (e.g., 'beta1', 'beta2'). |
An optimizer object (a list with a class attribute).
Create and initialize an antsrTransform
createAntsrTransform( type = "AffineTransform", precision = "float", dimension = 3, matrix = NA, offset = NA, center = NA, translation = NA, parameters = NA, fixed.parameters = NA, displacement.field = NULL, supported.types = FALSE )createAntsrTransform( type = "AffineTransform", precision = "float", dimension = 3, matrix = NA, offset = NA, center = NA, translation = NA, parameters = NA, fixed.parameters = NA, displacement.field = NULL, supported.types = FALSE )
type |
type of transform
|
precision |
numerical precision |
dimension |
spatial dimension of transform |
matrix |
matrix for linear transforms |
offset |
offset for linear transforms |
center |
center for linear transforms |
translation |
translation for linear transforms |
parameters |
array of parameters |
fixed.parameters |
array of fixed parameters |
displacement.field |
multichannel antsImage for non-linear transform |
supported.types |
flag that returns array of possible transforms types |
antsrTransform or list of transform types
trans <- c(3, 4, 5) tx <- createAntsrTransform(type = "Euler3DTransform", translation = trans)trans <- c(3, 4, 5) tx <- createAntsrTransform(type = "Euler3DTransform", translation = trans)
Compute the jacobian determinant from a transformation file
createJacobianDeterminantImage(domainImg, tx, doLog = FALSE, geom = FALSE)createJacobianDeterminantImage(domainImg, tx, doLog = FALSE, geom = FALSE)
domainImg |
image that defines transformation domain |
tx |
deformation transformation file name |
doLog |
return the log jacobian |
geom |
use the geometric jacobian calculation (boolean) |
jacobianImage
BB Avants
fi <- antsImageRead(getANTsRData("r16"), 2) mi <- antsImageRead(getANTsRData("r64"), 2) fi <- resampleImage(fi, c(128, 128), 1, 0) mi <- resampleImage(mi, c(128, 128), 1, 0) mytx <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) jac <- createJacobianDeterminantImage(fi, mytx$fwdtransforms[[1]], 1) # plot(jac)fi <- antsImageRead(getANTsRData("r16"), 2) mi <- antsImageRead(getANTsRData("r64"), 2) fi <- resampleImage(fi, c(128, 128), 1, 0) mi <- resampleImage(mi, c(128, 128), 1, 0) mytx <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) jac <- createJacobianDeterminantImage(fi, mytx$fwdtransforms[[1]], 1) # plot(jac)
Deforming a grid is a helpful way to visualize a deformation field. This function enables a user to define the grid parameters and apply a deformable map to that grid.
createWarpedGrid( img, gridStep = 10, gridWidth = 2, gridDirections = c(TRUE, TRUE), fixedReferenceImage = NULL, transform = NA, foreground = 1, background = 0 )createWarpedGrid( img, gridStep = 10, gridWidth = 2, gridDirections = c(TRUE, TRUE), fixedReferenceImage = NULL, transform = NA, foreground = 1, background = 0 )
img |
input image |
gridStep |
width of grid blocks |
gridWidth |
width of grid lines |
gridDirections |
directions in which to draw grid lines, boolean vector |
fixedReferenceImage |
reference image space |
transform |
vector of transforms |
foreground |
intensity value for grid blocks |
background |
intensity value for grid lines |
image is output
Avants BB
fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r64")) mygr <- createWarpedGrid(mi) ## Not run: mytx <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) mywarpedgrid <- createWarpedGrid(mi, gridDirections = c(F, T), transform = mytx$fwdtransforms, fixedReferenceImage = fi ) plot(fi, mywarpedgrid, alpha = 0.75, color.overlay = "blue") ## End(Not run)fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r64")) mygr <- createWarpedGrid(mi) ## Not run: mytx <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) mywarpedgrid <- createWarpedGrid(mi, gridDirections = c(F, T), transform = mytx$fwdtransforms, fixedReferenceImage = fi ) plot(fi, mywarpedgrid, alpha = 0.75, color.overlay = "blue") ## End(Not run)
uses a label image to crop a smaller image from within a larger image
cropImage(image, labelImage, label = 1)cropImage(image, labelImage, label = 1)
image |
antsImage to crop |
labelImage |
antsImage with label values. If not supplied, estimated from data. |
label |
the label value to use |
subimage
Brian B. Avants, Nicholas J. Tustison
fi <- antsImageRead(getANTsRData("r16")) cropped <- cropImage(fi) cropped <- cropImage(fi, fi, 100)fi <- antsImageRead(getANTsRData("r16")) cropped <- cropImage(fi) cropped <- cropImage(fi, fi, 100)
Crop the center of an image.
cropImageCenter(image, cropSize)cropImageCenter(image, cropSize)
image |
Input ANTs image |
cropSize |
width, height, depth (if 3-D), and time (if 4-D) of the cropped image. |
a cropped image
Tustison NJ
library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) croppedImage <- cropImageCenter( image, c( 64, 64 ) )library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) croppedImage <- cropImageCenter( image, c( 64, 64 ) )
Crop a patch from an image around a center point
cropImageFromCenterPoint(image, centerPoint, patchSize)cropImageFromCenterPoint(image, centerPoint, patchSize)
image |
Input ANTs image |
centerPoint |
Physical space coordinates of center point (vector). |
patchSize |
Vector defining patch size. |
A cropped resampled patch image
Tustison NJ
library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) center <- c( 128, 128 ) patch <- cropImageFromCenterPoint( image, center, c( 64, 64 ) )library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) center <- c( 128, 128 ) patch <- cropImageFromCenterPoint( image, center, c( 64, 64 ) )
create a proper antsImage sub-image by indexing the image with indices. this is similar to but different from array sub-setting in that the resulting sub-image can be decropped back into its place without having to store its original index locations explicitly.
cropIndices(image, lowerind, upperind)cropIndices(image, lowerind, upperind)
image |
antsImage to crop |
lowerind |
vector of lower index, should be length image dimensionality |
upperind |
vector of upper index, should be length image dimensionality |
subimage
Brian B. Avants, Nicholas J. Tustison
fi <- antsImageRead(getANTsRData("r16")) cropped <- cropIndices(fi, c(10, 10), c(100, 100)) cropped <- smoothImage(cropped, 5) decropped <- decropImage(cropped, fi)fi <- antsImageRead(getANTsRData("r16")) cropped <- cropIndices(fi, c(10, 10), c(100, 100)) cropped <- smoothImage(cropped, 5) decropped <- decropImage(cropped, fi)
Computes an R^2 value for predicting an outcome measure using a k-fold cross-validation scheme.
crossvalidatedR2(x, y, ngroups=5, covariates=NA, fast=F)crossvalidatedR2(x, y, ngroups=5, covariates=NA, fast=F)
x |
Input predictor matrix. |
y |
Target dependent variable. |
ngroups |
Number of cross-validation folds to use or the fold labels themselves, equal to the length of y. e.g. c(1,1,1,2,2,2...) |
covariates |
Covariate predictors. |
fast |
Use low-level |
Matrix of size ngroups by ncol(x), which each row corresponding to one fold and the columns corresponding to the R2 values for each predictor.
Brian B Avants, Benjamin M. Kandel
set.seed(300) ncol <- 30 nrow <- 20 covariate <- sin((1:nrow) * 2 * pi / nrow) x <- matrix(rep(NA, nrow * ncol), nrow = nrow) xsig <- seq(0, 1, length.out = nrow) y <- xsig + covariate + rnorm(nrow, sd = 0.5) for (i in 1:ncol) { x[, i] <- xsig + rnorm(nrow, sd = i / ncol) } r2 <- crossvalidatedR2(x, y, covariates = covariate)set.seed(300) ncol <- 30 nrow <- 20 covariate <- sin((1:nrow) * 2 * pi / nrow) x <- matrix(rep(NA, nrow * ncol), nrow = nrow) xsig <- seq(0, 1, length.out = nrow) y <- xsig + covariate + rnorm(nrow, sd = 0.5) for (i in 1:ncol) { x[, i] <- xsig + rnorm(nrow, sd = i / ncol) } r2 <- crossvalidatedR2(x, y, covariates = covariate)
Cuts a numeric image into an integer factor, with the option of a mask.
## S3 method for class 'antsImage' cut(x, breaks, ..., mask)## S3 method for class 'antsImage' cut(x, breaks, ..., mask)
x |
Object of class |
breaks |
either a numeric vector of two or more unique cut points
or a single number (greater than or equal to 2)
giving the number of intervals into which x is to be cut.
Passed to |
... |
Arguments passed to |
mask |
object to subset the image. If missing, then all values of the image are used |
Object of class antsImage with an attribute of levels
img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 cut(img, mask = mask, breaks = 4) cut(img, breaks = 4)img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 cut(img, mask = mask, breaks = 4) cut(img, breaks = 4)
Perform cross-validation on an image set using eigencomponents to predict an outcome variable.
cvEigenanatomy( demog, images, outcome, ratio = 10, mask = NULL, sparseness = 0.01, nvecs = 50, its = 5, cthresh = 250, ... )cvEigenanatomy( demog, images, outcome, ratio = 10, mask = NULL, sparseness = 0.01, nvecs = 50, its = 5, cthresh = 250, ... )
demog |
Demographics information that includes outcome and (optional) covariates. |
images |
n by p input image matrix, where n is the number of subjects and p is the number of voxels. |
outcome |
Name of outcome variable. Must be present in |
ratio |
If greater than 1, number of folds for cross-validation. If
less than 1, one testing-training step will be performed, using |
mask |
Mask image of type |
sparseness |
Desired level of sparsity in decomposition. |
nvecs |
Number of eigenvectors to use in decomposition. |
its |
Number of iterations for decomposition. |
cthresh |
Cluster threshold for decomposition. |
... |
Additional options passed to |
A result, or (if ratio > 1) list of results, from
regressProjection.
Kandel BM and Avants B
## Not run: # generate simulated outcome nsubjects <- 100 x1 <- seq(1, 10, length.out = nsubjects) + rnorm(nsubjects, sd = 2) x2 <- seq(25, 15, length.out = nsubjects) + rnorm(nsubjects, sd = 2) outcome <- 3 * x1 + 4 * x2 + rnorm(nsubjects, sd = 1) # generate simulated images with outcome predicted # by sparse subset of voxels voxel.1 <- 3 * x1 + rnorm(nsubjects, sd = 2) voxel.2 <- rnorm(nsubjects, sd = 2) voxel.3 <- 2 * x2 + rnorm(nsubjects, sd = 2) voxel.4 <- rnorm(nsubjects, sd = 3) input <- cbind(voxel.1, voxel.2, voxel.3, voxel.4) mask <- as.antsImage(matrix(c(1, 1, 1, 1), nrow = 2)) # generate sample demographics that do not explain outcome age <- runif(nsubjects, 50, 75) demog <- data.frame(outcome = outcome, age = age) result <- cvEigenanatomy(demog, input, "outcome", ratio = 5, mask, sparseness = 0.25, nvecs = 4 ) ## End(Not run)## Not run: # generate simulated outcome nsubjects <- 100 x1 <- seq(1, 10, length.out = nsubjects) + rnorm(nsubjects, sd = 2) x2 <- seq(25, 15, length.out = nsubjects) + rnorm(nsubjects, sd = 2) outcome <- 3 * x1 + 4 * x2 + rnorm(nsubjects, sd = 1) # generate simulated images with outcome predicted # by sparse subset of voxels voxel.1 <- 3 * x1 + rnorm(nsubjects, sd = 2) voxel.2 <- rnorm(nsubjects, sd = 2) voxel.3 <- 2 * x2 + rnorm(nsubjects, sd = 2) voxel.4 <- rnorm(nsubjects, sd = 3) input <- cbind(voxel.1, voxel.2, voxel.3, voxel.4) mask <- as.antsImage(matrix(c(1, 1, 1, 1), nrow = 2)) # generate sample demographics that do not explain outcome age <- runif(nsubjects, 50, 75) demog <- data.frame(outcome = outcome, age = age) result <- cvEigenanatomy(demog, input, "outcome", ratio = 5, mask, sparseness = 0.25, nvecs = 4 ) ## End(Not run)
Given an input image list (possibly multi-modal) and an optional corresponding segmentation image list, this function will perform data augmentation with the following augmentation possibilities: spatial transformations, added image noise, simulated bias field, and histogram warping.
dataAugmentation( inputImageList, segmentationImageList = NULL, pointsetList = NULL, numberOfSimulations = 10, referenceImage = NULL, transformType = "affineAndDeformation", noiseModel = "additivegaussian", noiseParameters = c(0, 0.05), sdSimulatedBiasField = 1, sdHistogramWarping = 0.05, sdAffine = 0.05, sdDeformation = 0.2, outputNumpyFilePrefix = NULL, verbose = FALSE )dataAugmentation( inputImageList, segmentationImageList = NULL, pointsetList = NULL, numberOfSimulations = 10, referenceImage = NULL, transformType = "affineAndDeformation", noiseModel = "additivegaussian", noiseParameters = c(0, 0.05), sdSimulatedBiasField = 1, sdHistogramWarping = 0.05, sdAffine = 0.05, sdDeformation = 0.2, outputNumpyFilePrefix = NULL, verbose = FALSE )
inputImageList |
list of lists of input images to warp. The internal list sets contains one or more images (per subject) which are assumed to be mutually aligned. The outer list contains multiple subject lists which are randomly sampled to produce output image list. |
segmentationImageList |
list of segmentation images corresponding to the input image list (optional). |
pointsetList |
list of pointsets (matrices) corresponding to the input image list (optional). If using this option, the transformType must be invertible. |
numberOfSimulations |
number of output images. Default = 10. |
referenceImage |
defines the spatial domain for all output images. If
the input images do not match the spatial domain of the reference image, we
internally resample the target to the reference image. This could have
unexpected consequences. Resampling to the reference domain is performed by
testing using |
transformType |
one of the following options
|
noiseModel |
one of the following options
|
noiseParameters |
parameters for the specified noise model. |
sdSimulatedBiasField |
Characterize the standard deviation of the amplitude. |
sdHistogramWarping |
Determines the strength of the histogram transformation. |
sdAffine |
Determines the amount of affine transformation. |
sdDeformation |
Determines the amount of deformable transformation. |
outputNumpyFilePrefix |
Filename of output numpy array containing all the simulated images and segmentations. |
verbose |
print progress to the screen. |
list of lists of transformed images and/or outputs to a numpy array.
Tustison NJ
## Not run: library( ANTsR ) image1 <- antsImageRead( getANTsRData( "r16" ) ) image2 <- antsImageRead( getANTsRData( "r64" ) ) segmentation1 <- thresholdImage( image1, "Otsu", 3 ) segmentation2 <- thresholdImage( image2, "Otsu", 3 ) points1 = getCentroids( segmentation1 )[,1:2] points2 = getCentroids( segmentation2 )[,1:2] data <- dataAugmentation( list( list( image1 ), list( image2 ) ), list( segmentation1, segmentation2 ), list( points1, points2 ), transformType = 'scaleShear' ) rm(segmentation1); gc() rm(segmentation2); gc() rm(image1); gc() rm(image2); gc() ## End(Not run)## Not run: library( ANTsR ) image1 <- antsImageRead( getANTsRData( "r16" ) ) image2 <- antsImageRead( getANTsRData( "r64" ) ) segmentation1 <- thresholdImage( image1, "Otsu", 3 ) segmentation2 <- thresholdImage( image2, "Otsu", 3 ) points1 = getCentroids( segmentation1 )[,1:2] points2 = getCentroids( segmentation2 )[,1:2] data <- dataAugmentation( list( list( image1 ), list( image2 ) ), list( segmentation1, segmentation2 ), list( points1, points2 ), transformType = 'scaleShear' ) rm(segmentation1); gc() rm(segmentation2); gc() rm(image1); gc() rm(image2); gc() ## End(Not run)
This function uses consolidated atlas data (AAL, DKT, CIT168, JHU, etc.) to translate technical shorthand strings into their original, legible anatomical descriptions. It performs normalization to handle variations in dots, underscores, and case.
decode_pymm_names(x)decode_pymm_names(x)
x |
A character vector of shorthand names to decode. |
A character vector of legible anatomical names.
decode_pymm_names("cit168.bn.str.pu.left") decode_pymm_names("dti.fa.thalamus.left.jhu.icbm.labels.1mm")decode_pymm_names("cit168.bn.str.pu.left") decode_pymm_names("dti.fa.thalamus.left.jhu.icbm.labels.1mm")
Ostergaard's regularization approach for a model independent solution of cerebral blood flow using a blood pool contrast agent (https://pubmed.ncbi.nlm.nih.gov/8916023).
deconvolutionSVD(arterialInputFunction, thresholdSVD = 0.2)deconvolutionSVD(arterialInputFunction, thresholdSVD = 0.2)
arterialInputFunction |
vector specifying the arterial input function over time. |
thresholdSVD |
is used to threshold the smaller elements of the diagonal matrix during the SVD regularization. 0.2 is a common choice (cf. page 571, end of column 2 in https://pubmed.ncbi.nlm.nih.gov/16971140). |
regularized residue function, i.e. the right-hand side of CBF * dT * R = ( V * L^-1 * U^T ) * Cvoi.
Tustison NJ
S0aif <- 17.62 Saif <- c( 16.25, 16.37, 20.22, 78.96, 230.5, 249.79, 198.58, 147.76, 110.39, 111.64, 129.43 ) Caif <- -log(Saif / S0aif) dSVD <- deconvolutionSVD(Caif, 0.2)S0aif <- 17.62 Saif <- c( 16.25, 16.37, 20.22, 78.96, 230.5, 249.79, 198.58, 147.76, 110.39, 111.64, 129.43 ) Caif <- -log(Saif / S0aif) dSVD <- deconvolutionSVD(Caif, 0.2)
the inverse function for cropImage
decropImage(croppedImage, fullImage)decropImage(croppedImage, fullImage)
croppedImage |
cropped antsImage |
fullImage |
antsImage to put back into |
decroppedImage
Brian B. Avants, Nicholas J. Tustison
fi <- antsImageRead(getANTsRData("r16")) mask <- getMask(fi) cropped <- cropImage(fi, mask, 1) cropped <- smoothImage(cropped, 1) decropped <- decropImage(cropped, fi)fi <- antsImageRead(getANTsRData("r16")) mask <- getMask(fi) cropped <- cropImage(fi, mask, 1) cropped <- smoothImage(cropped, 1) decropped <- decropImage(cropped, fi)
Denoise an image using a spatially adaptive filter originally described in J. V. Manjon, P. Coupe, Luis Marti-Bonmati, D. L. Collins, and M. Robles. Adaptive Non-Local Means Denoising of MR Images With Spatially Varying Noise Levels, Journal of Magnetic Resonance Imaging, 31:192-203, June 2010.
denoiseImage( img, mask, shrinkFactor = 1, p = 1, r = 3, noiseModel = c("Rician", "Gaussian"), verbose = FALSE )denoiseImage( img, mask, shrinkFactor = 1, p = 1, r = 3, noiseModel = c("Rician", "Gaussian"), verbose = FALSE )
img |
scalar image to denoise. |
mask |
optional to limit the denoise region. |
shrinkFactor |
downsampling level performed within the algorithm. |
p |
patch radius for local sample. can be a vector. |
r |
search radius from which to choose extra local samples. can be a vector. |
noiseModel |
either Rician or Gaussian. |
verbose |
boolean |
antsImage denoised version of image
N Tustison, B Avants
img <- antsImageRead(getANTsRData("rand")) %>% resampleImage(c(32, 32)) dimg <- denoiseImage(img, img * 0 + 1) dimg2 <- denoiseImage(img)img <- antsImageRead(getANTsRData("rand")) %>% resampleImage(c(32, 32)) dimg <- denoiseImage(img, img * 0 + 1) dimg2 <- denoiseImage(img)
Computes the density of values of an image with the option for a mask.
## S3 method for class 'antsImage' density(x, ..., mask)## S3 method for class 'antsImage' density(x, ..., mask)
x |
Object of class |
... |
Arguments passed to |
mask |
object to subset the image. If missing, then all values of the image are plotted. |
Output of density
img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 density(img, mask = mask)img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 density(img, mask = mask)
A data frame label numbers and names for the neuroanatomical DesikanKillianyTourville labels.
DesikanKillianyTourvilleDesikanKillianyTourville
A data frame listing the following variables.
label_numNumerical label value.
label_nameShorthand anatomical value.
tissueShorthand tissue value.
contralateralcontralateral anatomical value.
lobewhich lobe: temporal, parietal, occipital, frontal.
hemisphereleft or right hemisphere.
https://pubmed.ncbi.nlm.nih.gov/23227001
data(DesikanKillianyTourville)data(DesikanKillianyTourville)
Calculates Dice similarity coefficients between corresponding rows or columns of two matrices, treating all non-zero values as 1 (soft binary overlap).
dice_overlap_soft_matrix(A, B, margin = 1)dice_overlap_soft_matrix(A, B, margin = 1)
A |
Numeric matrix. |
B |
Numeric matrix of the same dimensions as 'A'. |
margin |
Integer: 1 for row-wise comparison, 2 for column-wise comparison. |
A numeric vector of Dice coefficients (length = nrow(A) or ncol(A)).
mat1 <- matrix(c(0,1,0,2, 1,0,0,0), nrow=2, byrow=TRUE) mat2 <- matrix(c(1,1,0,0, 0,0,1,0), nrow=2, byrow=TRUE) dice_overlap_soft_matrix(mat1, mat2, margin = 1) dice_overlap_soft_matrix(t(mat1), t(mat2), margin = 2)mat1 <- matrix(c(0,1,0,2, 1,0,0,0), nrow=2, byrow=TRUE) mat2 <- matrix(c(1,1,0,0, 0,0,1,0), nrow=2, byrow=TRUE) dice_overlap_soft_matrix(mat1, mat2, margin = 1) dice_overlap_soft_matrix(t(mat1), t(mat2), margin = 2)
This function computes the Dice similarity coefficient for two vectors, either using a soft binary threshold (non-zero = 1), or by thresholding values by quantile.
dice_overlap_soft_vector(x, y, quantile = 0.5)dice_overlap_soft_vector(x, y, quantile = 0.5)
x |
Numeric vector. |
y |
Numeric vector of the same length as 'x'. |
quantile |
Numeric between 0 and 1. If > 0, values below the given quantile (based on absolute value) are set to 0 before computing Dice. |
Dice similarity coefficient (between 0 and 1).
dice_overlap_soft_vector(c(0,1,0,2), c(3,1,0,0)) # returns 0.5 dice_overlap_soft_vector(c(0,0,0,0), c(0,0,0,0)) # returns 1 dice_overlap_soft_vector(c(1,2,3,4), c(1,0,0,4), quantile=0.5) # uses thresholddice_overlap_soft_vector(c(0,1,0,2), c(3,1,0,0)) # returns 0.5 dice_overlap_soft_vector(c(0,0,0,0), c(0,0,0,0)) # returns 1 dice_overlap_soft_vector(c(1,2,3,4), c(1,0,0,4), quantile=0.5) # uses threshold
Conver antsrTransform to displacement field
displacementFieldFromAntsrTransform(tx, reference = NA)displacementFieldFromAntsrTransform(tx, reference = NA)
tx |
antsrTransform |
reference |
reference antsImage if converting linear transform |
antsImage
Divide each column by the sum of column absolute values
divide_by_column_sum(m)divide_by_column_sum(m)
m |
A numeric matrix |
A matrix with each column divided by its sum
A data frame label numbers and names for consolidated DKT and CIT labels.
dkt_cit_labelsdkt_cit_labels
A data frame with columns: Label, Description.
A data frame label numbers and names for DKT cortical labels.
dkt_labelsdkt_labels
A data frame with columns: Label, Description, type.
Simplified, low-parameter eigenanatomy implemented with deflation. The
algorithm is able to automatically select hidden sparseness
parameters, given the key parameter nvecs. The user should select the
cthresh and smoother regularization parameters for a given
application and also based on observing algorithm behavior when
verbose=TRUE.
eanatDef( inmat, nvecs = 0, mask = NULL, smoother = 0, cthresh = 0, its = 5, eps = 0.1, positivity = FALSE, priors = NA, priorWeight = 0, sparEpsilon = 1e-04, whiten = FALSE, verbose = FALSE )eanatDef( inmat, nvecs = 0, mask = NULL, smoother = 0, cthresh = 0, its = 5, eps = 0.1, positivity = FALSE, priors = NA, priorWeight = 0, sparEpsilon = 1e-04, whiten = FALSE, verbose = FALSE )
inmat |
input matrix |
nvecs |
number of eigenanatomy vectors to compute. see
|
mask |
input mask, must match matrix |
smoother |
regularization parameter, typically 0 or 0.5, in voxels |
cthresh |
remove isolated voxel islands of size below this value |
its |
number of iterations |
eps |
gradient descent parameter |
positivity |
return unsigned eigenanatomy vectors |
priors |
external initialization matrix. |
priorWeight |
weight on priors in range 0 to 1. |
sparEpsilon |
threshold that controls initial sparseness estimate |
whiten |
use ICA style whitening. |
verbose |
controls whether computation is silent or not. |
matrix is output, analogous to svd(mat,nu=0,nv=nvecs)
Avants BB, Tustison NJ
Kandel, B. M.; Wang, D. J. J.; Gee, J. C. & Avants, B. B. Eigenanatomy: sparse dimensionality reduction for multi-modal medical image analysis. Methods, 2015, 73, 43-53. PS Dhillon, DA Wolk, SR Das, LH Ungar, JC Gee, BB Avants Subject-specific functional parcellation via Prior Based Eigenanatomy NeuroImage, 2014, 99, 14-27.
eanatSelect https://github.com/stnava/blindSourceSeparationInANTsR
## Not run: mat <- matrix(rnorm(2000), ncol = 50) nv <- eanatSelect(mat, selectorScale = 1.2) esol <- eanatDef(mat, nvecs = nv) es2 <- sparseDecom(mat, nvecs = nv) print(paste("selected", nrow(esol), "pseudo-eigenvectors")) print(mean(abs(cor(mat %*% t(esol))))) # what we use to select nvecs networkPriors <- getANTsRData("fmrinetworks") ilist <- networkPriors$images mni <- antsImageRead(getANTsRData("mni")) mnireg <- antsRegistration(meanbold * mask, mni, typeofTransform = "Affine") for (i in 1:length(ilist)) { ilist[[i]] <- antsApplyTransforms(meanbold, ilist[[i]], mnireg$fwdtransform) } pr <- imageListToMatrix(ilist, cortMask) esol <- eanatDef(boldMat, nvecs = length(ilist), cortMask, verbose = FALSE, cthresh = 25, smoother = 0, positivity = TRUE, its = 10, priors = pr, priorWeight = 0.15, eps = 0.1 ) ## End(Not run)## Not run: mat <- matrix(rnorm(2000), ncol = 50) nv <- eanatSelect(mat, selectorScale = 1.2) esol <- eanatDef(mat, nvecs = nv) es2 <- sparseDecom(mat, nvecs = nv) print(paste("selected", nrow(esol), "pseudo-eigenvectors")) print(mean(abs(cor(mat %*% t(esol))))) # what we use to select nvecs networkPriors <- getANTsRData("fmrinetworks") ilist <- networkPriors$images mni <- antsImageRead(getANTsRData("mni")) mnireg <- antsRegistration(meanbold * mask, mni, typeofTransform = "Affine") for (i in 1:length(ilist)) { ilist[[i]] <- antsApplyTransforms(meanbold, ilist[[i]], mnireg$fwdtransform) } pr <- imageListToMatrix(ilist, cortMask) esol <- eanatDef(boldMat, nvecs = length(ilist), cortMask, verbose = FALSE, cthresh = 25, smoother = 0, positivity = TRUE, its = 10, priors = pr, priorWeight = 0.15, eps = 0.1 ) ## End(Not run)
The algorithm automatically selects the key nvecs and hidden
sparseness parameters. The user should select the cthresh
regularization parameters for his or her application. The principle used
here is that we want few but sparse pseudo-eigenvectors that are minimally
correlated in row-space. true left and right eigenvectors are uncorrelated
in both row and column (left and right eigenvector) spaces, but this is not
the case when we impose sparsity.
eanatSelect( inmat, mask = NULL, cthresh = 0, smooth = 0, maxNEvec = 0, selectorScale = 1.1, whiten = FALSE, verbose = FALSE )eanatSelect( inmat, mask = NULL, cthresh = 0, smooth = 0, maxNEvec = 0, selectorScale = 1.1, whiten = FALSE, verbose = FALSE )
inmat |
input matrix |
mask |
input mask, must match matrix |
cthresh |
remove isolated voxel islands of size below this value |
smooth |
smooth the input data first by this value |
maxNEvec |
integer that, if set greater than zero, indicates that we use
a low-rank approximation to the input matrix before proceeding to eanat.
this value should be greater than |
selectorScale |
influences automatic selection of |
whiten |
use ICA style whitening. |
verbose |
controls whether computation is silent or not. |
nvecs is output, analogous to nvecs in
svd(mat,nu=0,nv=nvecs)
Avants BB, Tustison NJ
## Not run: mat <- matrix(rnorm(2000), ncol = 50) nvecsSel <- eanatSelect(mat, selectorScale = 1.2, maxNEvec = 4) esol <- sparseDecom(mat, nvecs = nvecsSel) print(paste("selected", nvecsSel, "pseudo-eigenvectors")) ## End(Not run)## Not run: mat <- matrix(rnorm(2000), ncol = 50) nvecsSel <- eanatSelect(mat, selectorScale = 1.2, maxNEvec = 4) esol <- sparseDecom(mat, nvecs = nvecsSel) print(paste("selected", nvecsSel, "pseudo-eigenvectors")) ## End(Not run)
Segment a mask into regions based on the max value in an image list. At a given voxel the segmentation label will contain the index to the image that has the largest value. If the 3rd image has the greatest value, the segmentation label will be 3 at that voxel.
eigSeg( mask = NULL, imgList = NA, applySegmentationToImages = FALSE, cthresh = 0, smooth = 1 )eigSeg( mask = NULL, imgList = NA, applySegmentationToImages = FALSE, cthresh = 0, smooth = 1 )
mask |
D-dimensional mask > 0 defining segmentation region. |
imgList |
list containing antsImages or a matrix matching the mask. |
applySegmentationToImages |
boolean determines if original image list is modified by the segmentation. |
cthresh |
throw away isolated clusters smaller than this value |
smooth |
smooth the input data first by this value |
segmentation image.
Avants BB
mylist <- list( antsImageRead(getANTsRData("r16")), antsImageRead(getANTsRData("r27")), antsImageRead(getANTsRData("r85")) ) mat <- imageListToMatrix(mylist, getMask(mylist[[1]])) myseg <- eigSeg(getMask(mylist[[1]]), mat)mylist <- list( antsImageRead(getANTsRData("r16")), antsImageRead(getANTsRData("r27")), antsImageRead(getANTsRData("r85")) ) mat <- imageListToMatrix(mylist, getMask(mylist[[1]])) myseg <- eigSeg(getMask(mylist[[1]]), mat)
This function removes the bias of treating a single column as "special" by running the 'sparsify_by_column_winner' function multiple times. In each run, the columns of the input matrix are permuted so that a different column is in the "first" position. The results are un-permuted and then averaged to produce a stable, unbiased sparse representation.
ensembled_sparsity(X, default_constraint = "positive")ensembled_sparsity(X, default_constraint = "positive")
X |
A numeric matrix [p_features x k_components]. |
default_constraint |
The constraint to apply to all other columns. |
A single, averaged sparse matrix with the same dimensions as X.
set.seed(42) mat <- matrix(rnorm(15), nrow=5, ncol=3) mat[2,1] <- 10; mat[4,2] <- -12; mat[1,3] <- 14 print("Original Matrix:") print(round(mat, 2)) # Keep one column dense, sparsify others by magnitude ('either') # sparse_ensembled <- ensembled_sparsity(mat, # default_constraint = "either" # )set.seed(42) mat <- matrix(rnorm(15), nrow=5, ncol=3) mat[2,1] <- 10; mat[4,2] <- -12; mat[1,3] <- 14 print("Original Matrix:") print(round(mat, 2)) # Keep one column dense, sparsify others by magnitude ('either') # sparse_ensembled <- ensembled_sparsity(mat, # default_constraint = "either" # )
Stop if not an antsImage object
error_not_antsImage(x, argname = "")error_not_antsImage(x, argname = "")
x |
object to test |
argname |
Name of argument to say was not an |
Invisible NULL
img <- antsImageRead(getANTsRData("r16"), 2) error_not_antsImage(img) testthat::expect_error(error_not_antsImage(as.array(img)))img <- antsImageRead(getANTsRData("r16"), 2) error_not_antsImage(img) testthat::expect_error(error_not_antsImage(as.array(img)))
This function provides a robust estimate of the number of significant, shared components in a list of data matrices. It uses a streamlined Parallel Analysis approach, comparing the singular value spectrum of the real data against the spectrum of permuted (noise) data.
estimate_joint_rank( mat_list, n_permutations = 20, pre_scaling = c("frobenius", "none"), plot_scree = TRUE )estimate_joint_rank( mat_list, n_permutations = 20, pre_scaling = c("frobenius", "none"), plot_scree = TRUE )
mat_list |
A list of numeric matrices [subjects x features]. |
n_permutations |
The number of permutations to perform to create a stable null distribution. A higher number is more stable but slower. Defaults to 20. |
pre_scaling |
Method to scale matrices before combining them. '"frobenius"' (default) scales each matrix to have a total variance of 1, ensuring fair contribution. '"none"' performs no scaling. |
plot_scree |
Logical. If TRUE, generates a scree plot comparing the real and permuted singular values, which is essential for visual diagnosis. |
The function first combines all modalities into a single matrix. It then computes the SVD and its eigenvalues (squared singular values) for this real data. It repeats this process 'n_permutations' times on shuffled versions of the data to generate a stable "null" or "chance" eigenvalue distribution. The optimal k is determined as the last component where the real eigenvalue exceeds the mean of the permuted eigenvalues.
A list containing:
optimal_k |
The estimated number of significant components. |
results |
A tibble showing the real vs. permuted eigenvalues for each component. |
plot |
A ggplot object of the scree plot. |
General-purpose estimator for an initial learning rate in nsa_flow(),
supporting multiple automatic strategies including the original Brent line search.
estimate_learning_rate_nsa( Y0, X0, w = 0.5, retraction = "soft_polar", nsa_energy = NULL, apply_nonneg = TRUE, method = c("brent", "grid", "armijo", "golden", "adaptive", "default"), search_range = c(-8, 2), verbose = TRUE, plot = TRUE )estimate_learning_rate_nsa( Y0, X0, w = 0.5, retraction = "soft_polar", nsa_energy = NULL, apply_nonneg = TRUE, method = c("brent", "grid", "armijo", "golden", "adaptive", "default"), search_range = c(-8, 2), verbose = TRUE, plot = TRUE )
Y0 |
Numeric matrix, initial point. |
X0 |
Numeric matrix, target matrix. |
w |
Weighting parameter between fidelity and orthogonality. |
retraction |
Retraction method used by nsa_flow. |
nsa_energy |
Optional function(Y) to compute NSA energy; if NULL, uses default. |
apply_nonneg |
Logical; if TRUE, applies nonnegativity. |
method |
Character; learning rate estimation method: one of c("brent", "grid", "armijo", "golden", "adaptive"). "default" returns fixed values (0.001 if nonneg, else 1.0). |
search_range |
Numeric vector of length 2; log10(alpha) search range |
verbose |
Logical; if TRUE, prints diagnostics. |
plot |
Logical; if TRUE, plots energy vs learning rate (if applicable). |
A list with:
estimated_learning_rate: numeric, chosen value.
search_df: data frame with log10(alpha), alpha, and energy (if available).
plot: ggplot object (if plot=TRUE), otherwise NULL.
Estimate Joint Rank via Cross-View RV Analysis
estimate_rank_by_permutation_rv( mat_list, n_permutations = 20, var_explained_threshold = 0.9, handle_missing = TRUE, return_max = FALSE )estimate_rank_by_permutation_rv( mat_list, n_permutations = 20, var_explained_threshold = 0.9, handle_missing = TRUE, return_max = FALSE )
mat_list |
A list of numeric matrices [subjects x features]. |
n_permutations |
Number of permutations (0 = Elbow method). |
var_explained_threshold |
Variance threshold to determine individual k_max. |
handle_missing |
Boolean; if TRUE, replaces NA/Constant columns with row means. |
return_max |
Boolean; if TRUE, returns only the k_max and skips curves. |
A list containing optimal_k, results tibble, and a diagnostic plot.
Estimates smoothness of a single image or image matrix
estSmooth(x, mask, rdf, scaleResid = TRUE, sample = NULL, verbose = TRUE)estSmooth(x, mask, rdf, scaleResid = TRUE, sample = NULL, verbose = TRUE)
x |
may be an image of class "antsImage" or an image matrix |
mask |
input mask, must match matrix |
rdf |
residual degrees of freedom |
scaleResid |
logical. if TRUE residuals are scaled |
sample |
number of images to use for estimating smoothing (default uses all images) |
verbose |
enables verbose output |
The partial derivatives of an image in x, y, and z directions are used to create a covariance matrix which in turn is used to calculate the full-widths at half maxima (FWHM). The FWHM is equivalent to the estimated image smoothness.
The resels per voxel image (RPVImg) represents the estimated resel at
each individual voxel throughout the search region. This may be used in
place of volumetric measurements (or sum voxel measurements) when estimating
the p-value of a cluster using rftPval. The intent behind using the
RPV image to estimate cluster level statistics is to offset the natural
probability of obtaining significant clusters solely by chance in very
smooth regions at low thresholds.
It is possible to use a single statistical field image to estimate the FWHM.
However, it's recommended that FWHM estimates are obtained from the scaled
residuals of statistical models (Stefan J.K et al., 1999). Therefore, this
function is optimized to estimate the pooled smoothness of the residual
images from a fitted model. By default residuals are scaled
(scaleResid = TRUE).
A scaling factor is used to correct for differences when using the
sample option. Scaling isn't effective when the number of images is
very low and typically results in an overestimation of the the FWHM. If only
one image or numeric vector is entered then the scaling factor is not used.
If a numeric vector is entered the imageMake function is used to
prepare it for smoothness estimation (see Worsley et al., 1999).
Any NA values in object will be set to zero.
Outputs the estimated FWHM and RPV image
Zachary P. Christensen
Hayasaka (2004) Nonstationary cluster-size inference with random field and permutation methods.
Worsley K.J. (1992) A Three-Dimensional Statistical Analysis for CBF Activation Studies in Human Brain.
Worsley K.J. (1996) A Unified Statistical Approach for Determining Significant Signals in Images of Cerebral Activation.
Worsley K.J. (1999) Detecting Changes in Nonisotropic Images
Stefan J.K. (1999) Robust Smoothness Estimation in Statistical Parametric Maps Using Standardized Residual from the General Linear Model
resels
# estimate individual image mnit1 <- antsImageRead(getANTsRData("r16")) mask <- getMask(mnit1) fwhm1 <- estSmooth(mnit1, mask)# estimate individual image mnit1 <- antsImageRead(getANTsRData("r16")) mask <- getMask(mnit1) fwhm1 <- estSmooth(mnit1, mask)
Mostly an for internal use in conjunction with resels. Calculates the
euler characteristic at a threshold level.
euler(u, df, fieldType)euler(u, df, fieldType)
u |
statistical value (typically the maxima of a cluster or statistical field) |
df |
degrees of freedom expressed as df = c(degrees of interest, degrees of error) |
fieldType |
|
A vector of estimated euler characteristics for dimensions 0:D
Zachary P. Christensen
Worlsey K.J., (1996) A Unified Statistical Approach for Determining Significant Signals in Images of Cerebral Activation.
rftPval, resels
mask <- getMask(antsImageRead(getANTsRData("r16"))) myresels <- resels(mask, c(1, 1)) # pretend these results are from a t-statistical field fitted with 10 df to # find a peak value. df <- c(1, 10) # made up degrees of freedom ec <- euler(4, df, fieldType = "T") # peak value is 4 ez <- euler(3, df, fieldType = "T") # we thresholded at 3 # uncorrected peak-level p-value pvox <- sum(ec * myresels) / sum(ez * myresels)mask <- getMask(antsImageRead(getANTsRData("r16"))) myresels <- resels(mask, c(1, 1)) # pretend these results are from a t-statistical field fitted with 10 df to # find a peak value. df <- c(1, 10) # made up degrees of freedom ec <- euler(4, df, fieldType = "T") # peak value is 4 ez <- euler(3, df, fieldType = "T") # we thresholded at 3 # uncorrected peak-level p-value pvox <- sum(ec * myresels) / sum(ez * myresels)
Employs a robust regression approach to learn the relationship between a sample image and a list of images that are mapped to the same space as the sample image. The regression uses data from an image neighborhood.
exemplarInpainting( img, paintMask, imageList, featureRadius = 2, scaleInpaintIntensity = 0, sharpen = FALSE, feather = 1, predalgorithm = "lm", debug = FALSE )exemplarInpainting( img, paintMask, imageList, featureRadius = 2, scaleInpaintIntensity = 0, sharpen = FALSE, feather = 1, predalgorithm = "lm", debug = FALSE )
img |
antsImage to be approximated / painted |
paintMask |
painting mask with values 1 or values 1 and 2 - if there is a 2 then it will learn from label 1 to paint label 2. should cover the brain. |
imageList |
a list containing antsImages |
featureRadius |
- radius of image neighborhood e.g. 2 |
scaleInpaintIntensity |
- brighter or darker painted voxels, default of 0 sets this parameter automatically |
sharpen |
- sharpen the approximated image |
feather |
- value (e.g. 1) that helps feather the mask for smooth blending |
predalgorithm |
- string svm or lm |
debug |
- TRUE or FALSE |
inpainted image
Brian B. Avants
set.seed(123) fi <- abs(replicate(100, rnorm(100))) fi[1:10, ] <- fi[, 1:10] <- fi[91:100, ] <- fi[, 91:100] <- 0 mask <- fi mask[mask > 0] <- 1 mask2 <- mask mask2[11:20, 11:20] <- 2 mask <- as.antsImage(mask, "float") fi <- as.antsImage(fi, "float") fi <- smoothImage(fi, 3) mo <- as.antsImage(replicate(100, rnorm(100)), "float") mo2 <- as.antsImage(replicate(100, rnorm(100)), "float") ilist <- list(mo, mo2) painted <- exemplarInpainting(fi, mask, ilist) mask2 <- as.antsImage(mask2, "float") painted2 <- exemplarInpainting(fi, mask2, ilist) # just use 1 image, so no regression is performed painted3 <- exemplarInpainting(fi, mask2, list(ilist[[1]]))set.seed(123) fi <- abs(replicate(100, rnorm(100))) fi[1:10, ] <- fi[, 1:10] <- fi[91:100, ] <- fi[, 91:100] <- 0 mask <- fi mask[mask > 0] <- 1 mask2 <- mask mask2[11:20, 11:20] <- 2 mask <- as.antsImage(mask, "float") fi <- as.antsImage(fi, "float") fi <- smoothImage(fi, 3) mo <- as.antsImage(replicate(100, rnorm(100)), "float") mo2 <- as.antsImage(replicate(100, rnorm(100)), "float") ilist <- list(mo, mo2) painted <- exemplarInpainting(fi, mask, ilist) mask2 <- as.antsImage(mask2, "float") painted2 <- exemplarInpainting(fi, mask2, ilist) # just use 1 image, so no regression is performed painted3 <- exemplarInpainting(fi, mask2, list(ilist[[1]]))
This function performs automated clustering using PAM and silhouette method, and visualizes the results using ggplot2 and ggdendro.
exploratory_visualization(data, dotsne = FALSE, verbose = FALSE)exploratory_visualization(data, dotsne = FALSE, verbose = FALSE)
data |
A data frame with numeric columns. |
dotsne |
boolean |
verbose |
boolean |
A list containing the combined plot and the optimal k value.
Rebuilds the projected SIMLR feature space from an existing SIMLR result,
adds one or more new modality blocks from the projected data, constructs
block-specific adjacency structures, chooses a joint initialization rank,
and runs simlr.perm() on the combined blocks.
extend_simlr_embedding_with_new_modalities( pymm, simlr_result, new_modalities, mode = c("concatenate", "split", "auto"), split_prefixes = c("t1", "dt", "rsf"), adjacency_type = c("feature_correlation"), cor_threshold = 0.8, use_abs_correlation = TRUE, k_new = NULL, k_method = c("cumulative", "elbow"), cumvar_threshold = 0.9, min_k = 2L, joint_k_policy = c("max", "median", "min"), preprocess = c("drop", "zero"), verbose = FALSE, ... )extend_simlr_embedding_with_new_modalities( pymm, simlr_result, new_modalities, mode = c("concatenate", "split", "auto"), split_prefixes = c("t1", "dt", "rsf"), adjacency_type = c("feature_correlation"), cor_threshold = 0.8, use_abs_correlation = TRUE, k_new = NULL, k_method = c("cumulative", "elbow"), cumvar_threshold = 0.9, min_k = 2L, joint_k_policy = c("max", "median", "min"), preprocess = c("drop", "zero"), verbose = FALSE, ... )
pymm |
Input multimodal object passed through to
|
simlr_result |
Existing SIMLR result object with a |
new_modalities |
Named list mapping modality names to projected-data
column names, e.g. |
mode |
How to construct existing blocks from the current SIMLR
projection. One of |
split_prefixes |
Character vector of prefixes used when
|
adjacency_type |
Type of within-block adjacency to build. Currently
|
cor_threshold |
Nonnegative threshold applied to absolute correlations when building adjacency matrices. |
use_abs_correlation |
Logical; if |
k_new |
Optional rank specification for new modalities. May be
|
k_method |
Method for automatic rank selection when |
cumvar_threshold |
Cumulative variance threshold used when
|
min_k |
Minimum admissible latent dimension. |
joint_k_policy |
Policy used to combine per-modality recommended ranks
into a single initialization rank. One of |
preprocess |
Policy for invalid columns. One of |
verbose |
Logical; emit progress messages. |
... |
Additional arguments forwarded to |
This implementation is intentionally strict:
- input validation is explicit
- preprocessing is deterministic
- constant / all-NA columns are dropped by default rather than jittered
- the input simlr_result is not mutated
- diagnostics are returned for auditability
A list with:
Copy of simlr_result with any returned
modality-specific $v entries merged in, without mutating input.
Result from simlr.perm().
Named list of processed block matrices used for fitting.
Named list of adjacency matrices.
Projected data returned by
apply_simlr_matrices_dtfix().
Named integer vector of per-new-modality ranks used.
Joint initialization rank passed to
initializeSimlr().
List of validation and preprocessing diagnostics.
Extract 2-D or 3-D image patch coordinates.
extractImagePatchCoordinates( image, patchSize, maxNumberOfPatches = "all", strideLength = 1, maskImage = NULL, physicalCoordinates = TRUE, cornerCoordinates = TRUE, randomSeed, randomize = TRUE )extractImagePatchCoordinates( image, patchSize, maxNumberOfPatches = "all", strideLength = 1, maskImage = NULL, physicalCoordinates = TRUE, cornerCoordinates = TRUE, randomSeed, randomize = TRUE )
image |
Input ANTs image with one or more components. |
patchSize |
Width, height, and depth (if 3-D) of patches. |
maxNumberOfPatches |
Maximum number of patches returned. If
"all" is specified, then all patches in sequence (defined by the
|
strideLength |
Defines the sequential patch overlap for
|
maskImage |
optional image specifying the sampling region for
the patches when |
physicalCoordinates |
boolean to determine whether indices or spatial coordinates are returned. |
cornerCoordinates |
boolean to determine whether indices or spatial coordinates of the corner or the center are returned. |
randomSeed |
integer seed that allows reproducible patch extraction across runs. |
randomize |
boolean controlling whether we randomize indices when masking. |
a matrix of image patch spatial or index coordinates.
Tustison NJ, Avants B
## Not run: library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) maskImage <- getMask( image, 1, 1000 ) patchCoordsP <- extractImagePatchCoordinates( image, c( 32, 32 ), 10, c( 32, 32 ), maskImage, randomSeed = 0, physicalCoordinates = TRUE ) patchCoordsI <- extractImagePatchCoordinates( image, c( 32, 32 ), 10, c( 32, 32 ), maskImage, randomSeed = 0, physicalCoordinates = FALSE ) ## End(Not run)## Not run: library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) maskImage <- getMask( image, 1, 1000 ) patchCoordsP <- extractImagePatchCoordinates( image, c( 32, 32 ), 10, c( 32, 32 ), maskImage, randomSeed = 0, physicalCoordinates = TRUE ) patchCoordsI <- extractImagePatchCoordinates( image, c( 32, 32 ), 10, c( 32, 32 ), maskImage, randomSeed = 0, physicalCoordinates = FALSE ) ## End(Not run)
Extract 2-D or 3-D image patches.
extractImagePatches( image, patchSize, maxNumberOfPatches = "all", strideLength = 1, maskImage = NULL, randomSeed, returnAsArray = FALSE, randomize = TRUE )extractImagePatches( image, patchSize, maxNumberOfPatches = "all", strideLength = 1, maskImage = NULL, randomSeed, returnAsArray = FALSE, randomize = TRUE )
image |
Input ANTs image with one or more components. |
patchSize |
Width, height, and depth (if 3-D) of patches. |
maxNumberOfPatches |
Maximum number of patches returned. If
"all" is specified, then all patches in sequence (defined by the
|
strideLength |
Defines the sequential patch overlap for
|
maskImage |
optional image specifying the sampling region for
the patches when |
randomSeed |
integer seed that allows reproducible patch extraction across runs. |
returnAsArray |
specifies the return type of the function. If
|
randomize |
boolean controlling whether we randomize indices when masking. |
a list (or array) of image patches.
Tustison NJ
library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) maskImage <- getMask( image, 1, 1000 ) patchSet1 <- extractImagePatches( image, c( 32, 32 ), 10, c( 32, 32 ), randomSeed = 0 ) patchSet2 <- extractImagePatches( image, c( 32, 32 ), 10, c( 32, 32 ), randomSeed = 1 ) patchSet3 <- extractImagePatches( image, c( 32, 32 ), 10, c( 32, 32 ), maskImage, randomSeed = 0 )library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) maskImage <- getMask( image, 1, 1000 ) patchSet1 <- extractImagePatches( image, c( 32, 32 ), 10, c( 32, 32 ), randomSeed = 0 ) patchSet2 <- extractImagePatches( image, c( 32, 32 ), 10, c( 32, 32 ), randomSeed = 1 ) patchSet3 <- extractImagePatches( image, c( 32, 32 ), 10, c( 32, 32 ), maskImage, randomSeed = 0 )
extract a slice from an image and return an image of dimensionality, d-1
extractSlice(image, slice, direction, collapseStrategy = 0)extractSlice(image, slice, direction, collapseStrategy = 0)
image |
antsImage to crop |
slice |
which slice, integer |
direction |
which axis, integer |
collapseStrategy |
collapse sub-matrix. 0: Collapse sub-matrix if positive definite. Otherwise, thrown exception. Default. 1: Set sub-matrix to identity. 2: Collapse if positive definite. Otherwise, set to identity. |
antsImage of dimension - 1
Brian B. Avants, Nicholas J. Tustison
fi <- makeImage(c(10, 10, 10), rnorm(1000)) slice <- extractSlice(fi, 1, 1)fi <- makeImage(c(10, 10, 10), rnorm(1000)) slice <- extractSlice(fi, 1, 1)
Perform whitening (sphering) of a data matrix such that the
covariance matrix of the output is approximately the identity.
The implementation automatically chooses the most efficient algorithm
depending on whether the number of features is much larger than
the number of samples () or vice versa ().
fast_whiten(X, epsilon = 1e-08)fast_whiten(X, epsilon = 1e-08)
X |
A numeric matrix of size |
epsilon |
A small non-negative numeric value used to stabilize the inversion of singular values (default = 1e-8). |
Whitening is performed via an SVD-based approach with Tikhonov-style regularization to handle small singular values.
- If , whitening is computed in the sample space
(avoids forming a covariance).
- If , whitening is computed in the feature space
(avoids forming an covariance).
Computational complexity:
when
when
A numeric matrix of the same dimensions as X, with whitened
columns. The covariance of the whitened data is approximately the identity
in the relevant space.
set.seed(42) # Case 1: p >> n X1 <- matrix(rnorm(50 * 2000), 50, 2000) Xw1 <- fast_whiten(X1) round(cov(t(Xw1))[1:5, 1:5], 3) # Case 2: n >> p X2 <- matrix(rnorm(2000 * 50), 2000, 50) Xw2 <- fast_whiten(X2) round(cov(Xw2)[1:5, 1:5], 3)set.seed(42) # Case 1: p >> n X1 <- matrix(rnorm(50 * 2000), 50, 2000) Xw1 <- fast_whiten(X1) round(cov(t(Xw1))[1:5, 1:5], 3) # Case 2: n >> p X2 <- matrix(rnorm(2000 * 50), 2000, 50) Xw2 <- fast_whiten(X2) round(cov(Xw2)[1:5, 1:5], 3)
This in an implementation of ITK's FastMarchingExtensionImageFilter - From http://www.itk.org/Doxygen/html/classitk_1_1FastMarchingExtensionImageFilter.html - Fast marching can be used to extend auxiliary variables smoothly from the zero level set. Starting from an initial position on the front, this class simultaneously calculate the signed distance and extend a set of auxiliary values. Implemenation of this class is based on Chapter 11 of "Level Set Methods and Fast Marching Methods", J.A. Sethian, Cambridge Press, Second edition, 1999.
fastMarchingExtension(speedImage, labelImage, valueImage)fastMarchingExtension(speedImage, labelImage, valueImage)
speedImage |
defines the cost or distance function |
labelImage |
defines the known (value 1) and unknown (value 2) regions |
valueImage |
these values are extended into the unknown regions |
antsImage
Duda, JT
img <- makeImage(c(7, 7), 0) img[3:5, 3:5] <- 1:9 mask <- getMask(img) mask[mask == 0] <- 2 speed <- smoothImage(mask, 1) extendedImg <- fastMarchingExtension(speed, mask, img)img <- makeImage(c(7, 7), 0) img[3:5, 3:5] <- 1:9 mask <- getMask(img) mask[mask == 0] <- 2 speed <- smoothImage(mask, 1) extendedImg <- fastMarchingExtension(speed, mask, img)
This function works for either raw BOLD time-series data, ASL-based BOLD time-series data or ASL-based CBF time series data. In all 3 cases, this function performs motion-correction, factoring out motion and compcor nuisance paramters, frequency filtering and masking. The output contains the filtered time series (matrix form), the mask and a vector of temporal signal variance. Some ASL MR sequences allow network analysis of either BOLD or ASL signal. See "Implementation of Quantitative Perfusion Imaging Techniques for Functional Brain Mapping using Pulsed Arterial Spin Labeling" by Wong et al, 1997 for an overview. This function employs "surround" techniques for deriving either CBF or BOLD signal from the input ASL. This is a WIP.
filterfMRIforNetworkAnalysis( aslmat, tr, freqLo = 0.01, freqHi = 0.1, cbfnetwork = "ASLCBF", mask = NULL, labels = NULL, graphdensity = 0.5, seg = NULL, useglasso = NA, nuisancein = NA, usesvd = FALSE, robustcorr = FALSE )filterfMRIforNetworkAnalysis( aslmat, tr, freqLo = 0.01, freqHi = 0.1, cbfnetwork = "ASLCBF", mask = NULL, labels = NULL, graphdensity = 0.5, seg = NULL, useglasso = NA, nuisancein = NA, usesvd = FALSE, robustcorr = FALSE )
aslmat |
The filename to an antsr image or pointer to an antsr image |
tr |
The sequence's TR value , typically 3 or 4. |
freqLo |
The lower frequency limit, e.g. 0.01 in band-pass filter |
freqHi |
The higher frequency limit, e.g. 0.1 in band-pass filter |
cbfnetwork |
"ASLCBF" A string dictating whether to do nothing special (standard BOLD) or get CBF (ASLCBF) or BOLD (ASLBOLD) signal from ASL |
mask |
the mask image |
labels |
the label image |
graphdensity |
desired density |
seg |
a segmentation image |
useglasso |
use sparse inverse covariance for network estimation |
nuisancein |
nuisance variable data frame |
usesvd |
bool, to reduce nuisance variables |
robustcorr |
bool |
output is a list containing "filteredTimeSeries" "mask" "temporalvar"
or
1 – Failure
Avants BB
## Not run: if (!exists("fn")) fn <- getANTsRData("pcasl") img <- antsImageRead(fn) mask <- getMask(getAverageOfTimeSeries(img)) fmat <- timeseries2matrix(img, mask) myres <- filterfMRIforNetworkAnalysis(fmat, tr = 4, 0.01, 0.1, cbfnetwork = "BOLD", mask = mask) ## End(Not run)## Not run: if (!exists("fn")) fn <- getANTsRData("pcasl") img <- antsImageRead(fn) mask <- getMask(getAverageOfTimeSeries(img)) fmat <- timeseries2matrix(img, mask) myres <- filterfMRIforNetworkAnalysis(fmat, tr = 4, 0.01, 0.1, cbfnetwork = "BOLD", mask = mask) ## End(Not run)
Fit a b-spline object to a dense displacement field image and/or a set of points
with associated displacements and smooths them using B-splines. The inverse
can also be estimated.. This is basically a wrapper
for the ITK filter http://docs.itk.org/projects/doxygen/en/stable/classitk_1_1DisplacementFieldToBSplineImageFilter.html
which, in turn is a wrapper for the ITK filter used for the function
ANTsR::fitBsplineObjectToScatteredData
fitBsplineDisplacementField( displacementField = NULL, displacementWeightImage = NULL, displacementOrigins = NULL, displacements = NULL, displacementWeights = NULL, origin = NULL, spacing = NULL, size = NULL, direction = NULL, numberOfFittingLevels = 4, meshSize = 1, splineOrder = 3, enforceStationaryBoundary = TRUE, estimateInverse = FALSE, rasterizePoints = FALSE )fitBsplineDisplacementField( displacementField = NULL, displacementWeightImage = NULL, displacementOrigins = NULL, displacements = NULL, displacementWeights = NULL, origin = NULL, spacing = NULL, size = NULL, direction = NULL, numberOfFittingLevels = 4, meshSize = 1, splineOrder = 3, enforceStationaryBoundary = TRUE, estimateInverse = FALSE, rasterizePoints = FALSE )
displacementField |
input displacement field. Either this and/or the points must be specified. |
displacementWeightImage |
input image defining weighting of the voxelwise displacements
in the |
displacementOrigins |
matrix ( |
displacements |
matrix ( |
displacementWeights |
vector defining the individual weighting of the corresponding scattered data value. Default = NULL meaning all values are weighted the same. |
origin |
vector defining the physical origin of the B-spline
displacement field. Must be specified if |
spacing |
vector defining the physical spacing of the B-spline
object. Defines the sampling rate in the parametric domain. Must be specified if
|
size |
vector defining the size (length) of the
B-spline object. Note that the length of the B-spline object in dimension |
direction |
matrix defining the orientation of the sampled
B-spline object. Must be specified if |
numberOfFittingLevels |
integer specifying the number of fitting levels. |
meshSize |
vector defining the mesh size at the initial fitting level. |
splineOrder |
spline order of the B-spline object. Default = 3. |
enforceStationaryBoundary |
ensure no displacements on the image boundary. Default = TRUE. |
estimateInverse |
estimate the inverse displacement field. Default = FALSE. |
rasterizePoints |
Use nearest neighbor rasterization of points for estimating the field (potential speed-up). |
ANTsR image.
NJ Tustison
# Perform 2-D fitting points <- matrix(data = c(-50, -50), nrow = 1, byrow = TRUE) deltas <- matrix(data = c(10, 10), nrow = 1, byrow = TRUE) bsplineField <- fitBsplineDisplacementField( displacementOrigins = points, displacements = deltas, origin = c(0.0, 0.0), spacing = c(1.0, 1.0), size = c(100, 100), direction = matrix(data = c(-1, 0, 0, -1), nrow = 2, byrow = TRUE), numberOfFittingLevels = 4, meshSize = c(1, 1) )# Perform 2-D fitting points <- matrix(data = c(-50, -50), nrow = 1, byrow = TRUE) deltas <- matrix(data = c(10, 10), nrow = 1, byrow = TRUE) bsplineField <- fitBsplineDisplacementField( displacementOrigins = points, displacements = deltas, origin = c(0.0, 0.0), spacing = c(1.0, 1.0), size = c(100, 100), direction = matrix(data = c(-1, 0, 0, -1), nrow = 2, byrow = TRUE), numberOfFittingLevels = 4, meshSize = c(1, 1) )
Fit a b-spline object to scattered data. This is basically a wrapper for the ITK filter http://docs.itk.org/projects/doxygen/en/stable/classitk_1_1BSplineScatteredDataPointSetToImageFilter.html. This filter is flexible in the possible objects that can be approximated. Possibilities include:
1/2/3/4-D
2-D surface in 3-D space (not available/templated)
2/3/4-D scalar field
2/3-D displacement field
2/3-D time-varying velocity field
In order to understand the input parameters, it is important to understand the difference between the parametric and data dimensions. A curve as one parametric dimension but the data dimension can be 1-D, 2-D, 3-D, or 4-D. In contrast, a 3-D displacement field has a parametric and data dimension of 3. The scattered data is what's approximated by the B-spline object and the parametric point is the location of scattered data within the domain of the B-spline object.
fitBsplineObjectToScatteredData( scatteredData, parametricData, parametricDomainOrigin, parametricDomainSpacing, parametricDomainSize, isParametricDimensionClosed = NULL, dataWeights = NULL, numberOfFittingLevels = 4, meshSize = 1, splineOrder = 3 )fitBsplineObjectToScatteredData( scatteredData, parametricData, parametricDomainOrigin, parametricDomainSpacing, parametricDomainSize, isParametricDimensionClosed = NULL, dataWeights = NULL, numberOfFittingLevels = 4, meshSize = 1, splineOrder = 3 )
scatteredData |
matrix defining the scattered data input to be approximated. Data is organized by row –> data v, column —> data dimension. |
parametricData |
matrix defining the parametric location of the scattered
data. Data is organized by row –> parametric point, column –> parametric
dimension. Note that each row corresponds to the same row in the
|
parametricDomainOrigin |
vector defining the parametric origin of the B-spline object. |
parametricDomainSpacing |
vector defining the parametric spacing of the B-spline object. Defines the sampling rate in the parametric domain. |
parametricDomainSize |
vector defining the size (length) of the
B-spline object. Note that the length of the B-spline object in dimension |
isParametricDimensionClosed |
vector of bools defining whether or not the corresponding parametric dimension is closed (e.g., closed loop). Default = FALSE. |
dataWeights |
vector defining the individual weighting of the corresponding scattered data value. Default = NULL meaning all values are weighted the same. |
numberOfFittingLevels |
integer specifying the number of fitting levels. |
meshSize |
vector defining the mesh size at the initial fitting level. |
splineOrder |
spline order of the B-spline object. Default = 3. |
Matrix for B-spline curve. Otherwise, returns ANTsR image.
NJ Tustison
# Perform 2-D curve example x <- seq(from = -4, to = 4, by = 0.1) y <- exp(-(x * x)) + runif(length(x), min = -0.1, max = 0.1) u <- seq(from = 0.0, to = 1.0, length.out = length(x)) scatteredData <- cbind(x, y) parametricData <- as.matrix(u, ncol = 1) numberOfSamplePoints <- 100 spacing <- 1 / (numberOfSamplePoints - 1) * 1.0 bsplineCurve <- fitBsplineObjectToScatteredData(scatteredData, parametricData, parametricDomainOrigin = c(0.0), parametricDomainSpacing = c(spacing), parametricDomainSize = c(numberOfSamplePoints), isParametricDimensionClosed = c(FALSE), numberOfFittingLevels = 5, meshSize = 1 ) plot(x, y, "p", col = "red") points(scatteredData[, 1], scatteredData[, 2], col = "green") lines(bsplineCurve[, 1], bsplineCurve[, 2], col = "blue") # Perform 2-D scalar field (i.e., image) example numberOfRandomPoints <- 10000 img <- antsImageRead(getANTsRData("r16")) imgArray <- as.array(img) rowIndices <- sample(2:(dim(imgArray)[1] - 1), numberOfRandomPoints, replace = TRUE) colIndices <- sample(2:(dim(imgArray)[2] - 1), numberOfRandomPoints, replace = TRUE) scatteredData <- as.matrix(array(data = 0, dim = c(numberOfRandomPoints, 1))) parametricData <- as.matrix(array(data = 0, dim = c(numberOfRandomPoints, 2))) for (i in seq_len(numberOfRandomPoints)) { scatteredData[i, 1] <- imgArray[rowIndices[i], colIndices[i]] parametricData[i, 1] <- rowIndices[i] parametricData[i, 2] <- colIndices[i] } bsplineImage <- fitBsplineObjectToScatteredData(scatteredData, parametricData, parametricDomainOrigin = c(0.0, 0.0), parametricDomainSpacing = c(1.0, 1.0), parametricDomainSize = dim(img), numberOfFittingLevels = 7, meshSize = c(1, 1) ) plot(bsplineImage)# Perform 2-D curve example x <- seq(from = -4, to = 4, by = 0.1) y <- exp(-(x * x)) + runif(length(x), min = -0.1, max = 0.1) u <- seq(from = 0.0, to = 1.0, length.out = length(x)) scatteredData <- cbind(x, y) parametricData <- as.matrix(u, ncol = 1) numberOfSamplePoints <- 100 spacing <- 1 / (numberOfSamplePoints - 1) * 1.0 bsplineCurve <- fitBsplineObjectToScatteredData(scatteredData, parametricData, parametricDomainOrigin = c(0.0), parametricDomainSpacing = c(spacing), parametricDomainSize = c(numberOfSamplePoints), isParametricDimensionClosed = c(FALSE), numberOfFittingLevels = 5, meshSize = 1 ) plot(x, y, "p", col = "red") points(scatteredData[, 1], scatteredData[, 2], col = "green") lines(bsplineCurve[, 1], bsplineCurve[, 2], col = "blue") # Perform 2-D scalar field (i.e., image) example numberOfRandomPoints <- 10000 img <- antsImageRead(getANTsRData("r16")) imgArray <- as.array(img) rowIndices <- sample(2:(dim(imgArray)[1] - 1), numberOfRandomPoints, replace = TRUE) colIndices <- sample(2:(dim(imgArray)[2] - 1), numberOfRandomPoints, replace = TRUE) scatteredData <- as.matrix(array(data = 0, dim = c(numberOfRandomPoints, 1))) parametricData <- as.matrix(array(data = 0, dim = c(numberOfRandomPoints, 2))) for (i in seq_len(numberOfRandomPoints)) { scatteredData[i, 1] <- imgArray[rowIndices[i], colIndices[i]] parametricData[i, 1] <- rowIndices[i] parametricData[i, 2] <- colIndices[i] } bsplineImage <- fitBsplineObjectToScatteredData(scatteredData, parametricData, parametricDomainOrigin = c(0.0, 0.0), parametricDomainSpacing = c(1.0, 1.0), parametricDomainSize = dim(img), numberOfFittingLevels = 7, meshSize = c(1, 1) ) plot(bsplineImage)
Fit a thin-plate spline object to a set of source points with associated displacements. This is basically a wrapper for the ITK class http://docs.itk.org/projects/doxygen/en/stable/itkThinPlateSplineKernelTransform_8h.html. Returns a displacement field.
fitThinPlateSplineDisplacementField( displacementOrigins = NULL, displacements = NULL, origin = NULL, spacing = NULL, size = NULL, direction = NULL )fitThinPlateSplineDisplacementField( displacementOrigins = NULL, displacements = NULL, origin = NULL, spacing = NULL, size = NULL, direction = NULL )
displacementOrigins |
matrix ( |
displacements |
matrix ( |
origin |
vector defining the physical origin of the B-spline
displacement field. Must be specified if |
spacing |
vector defining the physical spacing of the B-spline
object. Defines the sampling rate in the parametric domain. Must be specified if
|
size |
vector defining the size (length) of the
B-spline object. Note that the length of the B-spline object in dimension |
direction |
matrix defining the orientation of the sampled
B-spline object. Must be specified if |
ANTsR image.
NJ Tustison
# Perform 2-D fitting points <- matrix(data = c(-50, -50), nrow = 1, byrow = TRUE) deltas <- matrix(data = c(10, 10), nrow = 1, byrow = TRUE) tpsField <- fitThinPlateSplineDisplacementField( displacementOrigins = points, displacements = deltas, origin = c(0.0, 0.0), spacing = c(1.0, 1.0), size = c(100, 100), direction = matrix(data = c(-1, 0, 0, -1), nrow = 2, byrow = TRUE) )# Perform 2-D fitting points <- matrix(data = c(-50, -50), nrow = 1, byrow = TRUE) deltas <- matrix(data = c(10, 10), nrow = 1, byrow = TRUE) tpsField <- fitThinPlateSplineDisplacementField( displacementOrigins = points, displacements = deltas, origin = c(0.0, 0.0), spacing = c(1.0, 1.0), size = c(100, 100), direction = matrix(data = c(-1, 0, 0, -1), nrow = 2, byrow = TRUE) )
Estimate a time-varying transform from corresponding point sets (> 2).
fitTimeVaryingTransformToPointSets( pointSets, timePoints = NULL, initialVelocityField = NULL, numberOfTimeSteps = NULL, domainImage = NULL, numberOfFittingLevels = 4, meshSize = 1, splineOrder = 3, displacementWeights = NULL, numberOfCompositions = 10, compositionStepSize = 0.5, numberOfIntegrationSteps = 100, sigma = 0, convergenceThreshold = 1e-06, rasterizePoints = FALSE, verbose = FALSE )fitTimeVaryingTransformToPointSets( pointSets, timePoints = NULL, initialVelocityField = NULL, numberOfTimeSteps = NULL, domainImage = NULL, numberOfFittingLevels = 4, meshSize = 1, splineOrder = 3, displacementWeights = NULL, numberOfCompositions = 10, compositionStepSize = 0.5, numberOfIntegrationSteps = 100, sigma = 0, convergenceThreshold = 1e-06, rasterizePoints = FALSE, verbose = FALSE )
pointSets |
Corresponding points across sets specified in physical space as a
|
timePoints |
Set of scalar values, one for each point-set designating its time position in the velocity flow. If not set, it defaults to equal spacing between 0 and 1. |
initialVelocityField |
Optional velocity field for initializing optimization. Overrides the number of integration points. |
numberOfTimeSteps |
Time-varying velocity field parameter. Needs to be equal to or greater than the number of point sets. If not specified, it defaults to the number of point sets. |
domainImage |
Defines physical domain of the B-spline transform. Must be defined for nonlinear transforms. |
numberOfFittingLevels |
Integer specifying the number of fitting levels for the B-spline interpolation of the displacement field. |
meshSize |
Defines the mesh size at the initial fitting level for the B-spline interpolation of the displacement field. |
splineOrder |
Spline order of the B-spline displacement field. |
displacementWeights |
vector defining the individual weighting of the corresponding scattered data value. Default = NULL meaning all displacements are weighted the same. |
numberOfCompositions |
Total number of compositions for the diffeomorphic transform. |
compositionStepSize |
Scalar multiplication factor of the weighting of the update field for the diffeomorphic transforms. |
numberOfIntegrationSteps |
Number of steps used for integrating the velocity field. |
sigma |
Gaussian smoothing standard deviation of the update field (in mm). |
convergenceThreshold |
Composition-based convergence parameter for the diffeomorphic transforms using a window size of 10 values. |
rasterizePoints |
Use nearest neighbor rasterization of points for estimating update field (potential speed-up). |
verbose |
Print progress to the screen. |
object containing ANTsR transform, error, and scale (or displacement field)
B Avants, N Tustison
Estimate a transform using paired point sets. An ANTsR transform is returned.
fitTransformToPairedPoints( movingPoints, fixedPoints, transformType = "affine", regularization = 1e-06, domainImage = NULL, numberOfFittingLevels = 4, meshSize = 1, splineOrder = 3, enforceStationaryBoundary = TRUE, displacementWeights = NULL, numberOfCompositions = 10, compositionStepSize = 0.5, sigma = 0, convergenceThreshold = 1e-06, numberOfTimeSteps = 2, numberOfIntegrationSteps = 100, rasterizePoints = FALSE, verbose = FALSE )fitTransformToPairedPoints( movingPoints, fixedPoints, transformType = "affine", regularization = 1e-06, domainImage = NULL, numberOfFittingLevels = 4, meshSize = 1, splineOrder = 3, enforceStationaryBoundary = TRUE, displacementWeights = NULL, numberOfCompositions = 10, compositionStepSize = 0.5, sigma = 0, convergenceThreshold = 1e-06, numberOfTimeSteps = 2, numberOfIntegrationSteps = 100, rasterizePoints = FALSE, verbose = FALSE )
movingPoints |
Moving points specified in physical space as a |
fixedPoints |
Fixed points specified in physical space as a |
transformType |
'rigid', 'similarity', 'affine', 'bspline', 'tps', 'diffeo', 'syn', 'tv', or 'time-varying'. |
regularization |
Ridge penalty in [0,1] for linear transforms. |
domainImage |
Defines physical domain of the B-spline transform. Must be defined for nonlinear transforms. |
numberOfFittingLevels |
Integer specifying the number of fitting levels for the B-spline interpolation of the displacement field. |
meshSize |
Defines the mesh size at the initial fitting level for the B-spline interpolation of the displacement field. |
splineOrder |
Spline order of the B-spline displacement field. |
enforceStationaryBoundary |
Ensure no displacements on the image boundary (B-spline only). |
displacementWeights |
Defines the individual weighting of the corresponding scattered data value. Default = None meaning all displacements are weighted the same. |
numberOfCompositions |
Total number of compositions for the diffeomorphic transform. |
compositionStepSize |
Scalar multiplication factor of the weighting of the update field for the diffeomorphic transforms. |
sigma |
Gaussian smoothing standard deviation of the update field (in mm). |
convergenceThreshold |
Composition-based convergence parameter for the diffeomorphic transforms using a window size of 10 values. |
numberOfTimeSteps |
Time-varying velocity field parameter. |
numberOfIntegrationSteps |
Number of steps used for integrating the velocity field. |
rasterizePoints |
Use nearest neighbor rasterization of points for estimating update field (potential speed-up). |
verbose |
Print progress to the screen. |
object containing ANTsR transform, error, and scale (or displacement field)
B Avants, N Tustison
fixed <- matrix(c(50, 50, 200, 50, 50, 200), ncol = 2, byrow = TRUE) moving <- matrix(c(50, 50, 50, 200, 200, 200), ncol = 2, byrow = TRUE) # Affine transform xfrm <- fitTransformToPairedPoints(moving, fixed, transformType = "Affine", regularization = 0) params <- getAntsrTransformParameters(xfrm) # Rigid transform xfrm <- fitTransformToPairedPoints(moving, fixed, transformType = "Rigid", regularization = 0) params <- getAntsrTransformParameters(xfrm) # Similarity transform xfrm <- fitTransformToPairedPoints(moving, fixed, transformType = "Similarity", regularization = 0) params <- getAntsrTransformParameters(xfrm) # B-spline transform domainImage <- antsImageRead(getANTsRData("r16")) xfrm <- fitTransformToPairedPoints(moving, fixed, transformType = "Bspline", domainImage = domainImage, numberOfFittingLevels = 5)fixed <- matrix(c(50, 50, 200, 50, 50, 200), ncol = 2, byrow = TRUE) moving <- matrix(c(50, 50, 50, 200, 200, 200), ncol = 2, byrow = TRUE) # Affine transform xfrm <- fitTransformToPairedPoints(moving, fixed, transformType = "Affine", regularization = 0) params <- getAntsrTransformParameters(xfrm) # Rigid transform xfrm <- fitTransformToPairedPoints(moving, fixed, transformType = "Rigid", regularization = 0) params <- getAntsrTransformParameters(xfrm) # Similarity transform xfrm <- fitTransformToPairedPoints(moving, fixed, transformType = "Similarity", regularization = 0) params <- getAntsrTransformParameters(xfrm) # B-spline transform domainImage <- antsImageRead(getANTsRData("r16")) xfrm <- fitTransformToPairedPoints(moving, fixed, transformType = "Bspline", domainImage = domainImage, numberOfFittingLevels = 5)
This function leverages structural image processing based on ANTs cortical thickness to implement standard functional image processing recommendations. The function will crop out the first k time frames, do motion correction and produce a variety of nuisance regressors. It will also do spatial and temporal filtering as well as interpolation between time frames that exceed a given framewise displacement. Finally, we return maps to the common coordinate system. Output may be trimmed in the future but currently provides access at different stages: merging versus filtering and normalized, fused BOLD images in both subject and template space.
fMRINormalization( img, steadyT = 20, fdthresh = Inf, repeatMotionEst = 2, freqLimits = c(0.01, 0.1), nCompCor = 0, polydegree = NA, structuralImage = NULL, structuralSeg = NULL, structuralNodes = NULL, templateMap = NULL, templateImage = NULL, smoothingSigmas = NA, extraRuns = list(), verbose = FALSE )fMRINormalization( img, steadyT = 20, fdthresh = Inf, repeatMotionEst = 2, freqLimits = c(0.01, 0.1), nCompCor = 0, polydegree = NA, structuralImage = NULL, structuralSeg = NULL, structuralNodes = NULL, templateMap = NULL, templateImage = NULL, smoothingSigmas = NA, extraRuns = list(), verbose = FALSE )
img |
input time series antsImage. |
steadyT |
number of seconds for steady state (used to remove initial volumes) |
fdthresh |
threshold for framewise displacement. determines what time frames should be interpolated. Set typically between 0.1 and 0.5 or Inf. |
repeatMotionEst |
number of times to repeat motion estimation. We recommend the value 2, in general. The first run improves the template estimate such that the 2nd run gives a more accurate correction. |
freqLimits |
pair defining bandwidth of interest from low to high. |
nCompCor |
number of compcor components to use in CSF plus WM mask. |
polydegree |
eg 4 for polynomial nuisance variables. |
structuralImage |
the structural antsImage of the brain. |
structuralSeg |
a 3 or greater class tissue segmentation of the structural image. |
structuralNodes |
regions of interest for network analysis, in the structural image space. |
templateMap |
antsRegistration output mapping template space (as moving) to struturalImage (fixed). |
templateImage |
template reference space to which we map the BOLD image. |
smoothingSigmas |
4-vector defining amount of smoothing in FWHM units. |
extraRuns |
a list containing additional BOLD images (runs) to be merged with the first image. |
verbose |
enables visualization as well as commentary. |
outputs a list containing:
runs fused into one image and corrected if polydegree set
runs fused into one image and filtered
strutural segmentation in BOLD space.
strutural nodes in BOLD space.
BOLD fusedImg mapped to template space.
invertible maps from BOLD to template space.
Identifies which run over time series.
Matrix of filtered BOLD data.
BOLD mask.
Motion corrected data.
Polynomial nuisance variables.
Temporal variables.
Nuisance variables.
mean framewise displacement.
time frames that are above FD threshold.
Default mode network at BOLD resolution in MNI space.
Segmentation in BOLD resolution MNI space.
WIP: standard network priors in BOLD space.
Powers nodes in BOLD space i.e. fusedImg.
Powers points in BOLD space i.e. fusedImg.
User provided nodal system connectivity matrix.
TUser provided nodal system partial correlation matrix.
Avants BB, Duda JT
# this example is long-running ( perhaps 10 minutes on an OSX laptop 2016 ) ## Not run: exrun <- fMRINormalization(verbose = TRUE) # will download ex data myid <- "BBAvants" # some MRI data pre <- paste("~/rsfTest/", sep = "") fn <- list.files(pre, full.names = TRUE, recursive = TRUE, pattern = glob2rx(paste(myid, "*rsfMRI0.nii.gz", sep = "")) ) img <- antsImageRead(fn) sfn <- list.files(pre, full.names = TRUE, recursive = TRUE, pattern = glob2rx(paste(myid, "*BrainSegmentation.nii.gz", sep = "")) ) seg <- antsImageRead(sfn) t1fn <- list.files(pre, full.names = TRUE, recursive = TRUE, pattern = glob2rx(paste(myid, "*BrainSegmentation0N4.nii.gz", sep = "")) ) t1 <- antsImageRead(t1fn) tt <- fMRINormalization(img, repeatMotionEst = 1, structuralImage = t1, structuralSeg = seg, verbose = TRUE ) # bold to template antsApplyTransforms(mni, getAverageOfTimeSeries(img), transformlist = tt$mapsToTemplate$toTemplate, whichtoinvert = tt$mapsToTemplate$toTemplateInversion ) # template to bold antsApplyTransforms(getAverageOfTimeSeries(img), mni, transformlist = tt$mapsToTemplate$toBold, whichtoinvert = tt$mapsToTemplate$toBoldInversion ) ## End(Not run)# this example is long-running ( perhaps 10 minutes on an OSX laptop 2016 ) ## Not run: exrun <- fMRINormalization(verbose = TRUE) # will download ex data myid <- "BBAvants" # some MRI data pre <- paste("~/rsfTest/", sep = "") fn <- list.files(pre, full.names = TRUE, recursive = TRUE, pattern = glob2rx(paste(myid, "*rsfMRI0.nii.gz", sep = "")) ) img <- antsImageRead(fn) sfn <- list.files(pre, full.names = TRUE, recursive = TRUE, pattern = glob2rx(paste(myid, "*BrainSegmentation.nii.gz", sep = "")) ) seg <- antsImageRead(sfn) t1fn <- list.files(pre, full.names = TRUE, recursive = TRUE, pattern = glob2rx(paste(myid, "*BrainSegmentation0N4.nii.gz", sep = "")) ) t1 <- antsImageRead(t1fn) tt <- fMRINormalization(img, repeatMotionEst = 1, structuralImage = t1, structuralSeg = seg, verbose = TRUE ) # bold to template antsApplyTransforms(mni, getAverageOfTimeSeries(img), transformlist = tt$mapsToTemplate$toTemplate, whichtoinvert = tt$mapsToTemplate$toTemplateInversion ) # template to bold antsApplyTransforms(getAverageOfTimeSeries(img), mni, transformlist = tt$mapsToTemplate$toBold, whichtoinvert = tt$mapsToTemplate$toBoldInversion ) ## End(Not run)
This function works for a BOLD time-series data
frequencyFilterfMRI(boldmat, tr, freqLo = 0.01, freqHi = 0.1, opt = "butt")frequencyFilterfMRI(boldmat, tr, freqLo = 0.01, freqHi = 0.1, opt = "butt")
boldmat |
Time series matrix for bold image |
tr |
The sequence's TR value , typically 3 or 4. |
freqLo |
The lower frequency limit, e.g. 0.01 in band-pass filter |
freqHi |
The higher frequency limit, e.g. 0.1 in band-pass filter |
opt |
one of 'trig','butt','stl' Type of filter to use: butterworth, trigonometric, stl. |
output is the filtered time series.
Avants BB
fmat <- replicate(1000, rnorm(200)) k <- 1 tr <- 4 for (ftype in c("butt", "stl", "trig")) { myres <- frequencyFilterfMRI(fmat, tr = tr, freqLo = 0.01, freqHi = 0.05, opt = ftype) comparemat <- cbind(fmat[, k], myres[, k]) plot(ts(comparemat), main = ftype) Sys.sleep(0.3) # uncomment below to visualize effect of frequency filtering # temp = spectrum( ts(fmat[,k], frequency=1/tr ) ) # plot( temp$freq, temp$spec, type='l' ) # temp = spectrum( ts(myres[,k], frequency=1/tr ) ) # plot( temp$freq, temp$spec, type='l' ) }fmat <- replicate(1000, rnorm(200)) k <- 1 tr <- 4 for (ftype in c("butt", "stl", "trig")) { myres <- frequencyFilterfMRI(fmat, tr = tr, freqLo = 0.01, freqHi = 0.05, opt = ftype) comparemat <- cbind(fmat[, k], myres[, k]) plot(ts(comparemat), main = ftype) Sys.sleep(0.3) # uncomment below to visualize effect of frequency filtering # temp = spectrum( ts(fmat[,k], frequency=1/tr ) ) # plot( temp$freq, temp$spec, type='l' ) # temp = spectrum( ts(myres[,k], frequency=1/tr ) ) # plot( temp$freq, temp$spec, type='l' ) }
Computes the Frobenius norm of a matrix, defined as the square root of the sum of squared elements.
frob(A)frob(A)
A |
Numeric matrix. |
The Frobenius norm is , equivalent to the Euclidean norm of the vectorized matrix.
Used for scaling and computing residuals in NSA-Flow.
Numeric scalar, the Frobenius norm ||A||_F.
A <- matrix(1:4, 2, 2) frob(A)A <- matrix(1:4, 2, 2) frob(A)
Convert an FSL linear transform to an antsrTransform
fsl2antsrTransform(matrix, reference, moving)fsl2antsrTransform(matrix, reference, moving)
matrix |
4x4 matrix of parameters |
reference |
target image read in as antsImage |
moving |
image, read in as antsImage |
JT Duda
fslMat <- matrix(0, 4, 4) diag(fslMat) <- rep(1, 4) fslMat[1:3, 4] <- c(2, 3, 4) img <- antsImageRead(getANTsRData("ch2")) tx <- fsl2antsrTransform(fslMat, img, img)fslMat <- matrix(0, 4, 4) diag(fslMat) <- rep(1, 4) fslMat[1:3, 4] <- c(2, 3, 4) img <- antsImageRead(getANTsRData("ch2")) tx <- fsl2antsrTransform(fslMat, img, img)
Lung segmentation into classes based on ventilation as described in this paper:
functionalLungSegmentation( image, mask, numberOfIterations = 2, numberOfAtroposIterations = 5, mrfParameters = "[0.7,2x2x2]", numberOfClusters = 6, clusterCenters = NA, biasCorrection = "n4", verbose = TRUE )functionalLungSegmentation( image, mask, numberOfIterations = 2, numberOfAtroposIterations = 5, mrfParameters = "[0.7,2x2x2]", numberOfClusters = 6, clusterCenters = NA, biasCorrection = "n4", verbose = TRUE )
image |
input proton-weighted MRI. |
mask |
mask image designating the region to segment. 0/1 = background/foreground. |
numberOfIterations |
number of Atropos <–> bias correction iterations (outer loop). |
numberOfAtroposIterations |
number of Atropos iterations (inner loop).
If |
mrfParameters |
parameters for MRF in Atropos. |
numberOfClusters |
number of tissue classes (default = 4) |
clusterCenters |
initialization centers for k-means |
biasCorrection |
apply n3, n4, or no bias correction (default = "n4"). |
verbose |
print progress to the screen. |
https://pubmed.ncbi.nlm.nih.gov/21837781/
segmentation image, probability images, and processed input image.
Tustison NJ
## Not run: library(ANTsR) image <- antsImageRead("lung.nii.gz") mask <- antsImageRead("mask.nii.gz") output <- functionalLungSegmentation(image, mask) antsImageWrite(output$segmentationImage, "outputSegmentation.nii.gz") ## End(Not run)## Not run: library(ANTsR) image <- antsImageRead("lung.nii.gz") mask <- antsImageRead("mask.nii.gz") output <- functionalLungSegmentation(image, mask) antsImageWrite(output$segmentationImage, "outputSegmentation.nii.gz") ## End(Not run)
Fits a joint Fused Ridge regression model across multiple binarized thresholds, smoothing the coefficient trajectories using a 1D Graph Laplacian.
fusedRidge( X_pcs, y_raw, thresholds, covariates = NULL, lambda1 = 0.5, lambda2 = 0.5, family = "binomial", standardize = TRUE, foldid = NULL, topK = NULL, thresh = 1e-04, nlambda = 100, nfolds = 10, cv = TRUE, lambda = NULL, ... )fusedRidge( X_pcs, y_raw, thresholds, covariates = NULL, lambda1 = 0.5, lambda2 = 0.5, family = "binomial", standardize = TRUE, foldid = NULL, topK = NULL, thresh = 1e-04, nlambda = 100, nfolds = 10, cv = TRUE, lambda = NULL, ... )
X_pcs |
Matrix of predictor variables. For high-dimensional data (e.g., voxels), it is recommended to use dimensionality reduction (e.g., PCA) first, as the internal Kronecker product can be memory-intensive. |
y_raw |
Vector of continuous exposure or response variable. |
thresholds |
Vector of thresholds at which to binarize y_raw. |
covariates |
Optional matrix or data frame of covariates to adjust for. Covariates are unpenalized. An intercept is automatically added if not present. |
lambda1 |
Ridge penalty weight (defaults to 0.5). |
lambda2 |
Fusion penalty weight (defaults to 0.5). |
family |
Model family, passed to glmnet. Defaults to "binomial". |
standardize |
Boolean indicating whether to scale the predictor matrix. Defaults to TRUE. |
foldid |
Optional fold IDs for group-structured cross-validation. |
topK |
Optional integer. If provided, fits a first pass model, selects the union of the |
thresh |
Convergence threshold for |
nlambda |
Number of lambda values to use in |
nfolds |
Number of folds for cross-validation (defaults to 10). |
cv |
Boolean indicating whether to select the Ridge lambda by |
lambda |
Optional numeric value. If provided, CV is skipped and the model is fit directly using the specified lambda value. |
... |
Additional arguments passed to |
Fits a joint Fused Ridge regression model across multiple binarized thresholds of a continuous response variable, smoothing the coefficient trajectories using a 1D Graph Laplacian.
The model is formulated by transforming the predictor matrix using a transformation matrix
, where is a 1D Graph Laplacian matrix.
The design matrix is stacked block-diagonally for unpenalized covariates and using Kronecker products for penalized features:
.
This transformation maps the fused ridge problem back into standard ridge regression, allowing the use of highly optimized solvers like glmnet.
A list containing the fitted glmnet model, cross-validation results, optimal lambda, reconstructed full coefficient matrix, and other helper parameters.
Lettink, A., Chinapaw, M. J. M., & van Wieringen, W. N. (2023). Two-dimensional fused targeted ridge regression for health indicator prediction from accelerometer data. Journal of the Royal Statistical Society Series C: Applied Statistics, 72(4), 1064-1078. doi:10.1093/jrsssc/qlad038
Li, H., & Li, Y. (2008). Network-constrained regularization and variable selection for analysis of genomic data. Bioinformatics, 24(9), 1175-1182. doi:10.1093/bioinformatics/btn081
Fits a joint Fused Ridge regression model across multiple binarized thresholds of a
continuous response variable using direct optimization (L-BFGS). This avoids the memory-intensive
Kronecker product design matrix expansion used in fusedRidge, making it highly scalable
for high-dimensional predictors.
fusedRidgeDirect( X_pcs, y_raw, thresholds, covariates = NULL, lambda1 = 0.5, lambda2 = 0.5, family = "binomial", standardize = TRUE, foldid = NULL, topK = NULL, thresh = 1e-04, nlambda = 20, nfolds = 10, cv = TRUE, ncores = 1, optim_control = list(maxit = 200), lambda = NULL, ... )fusedRidgeDirect( X_pcs, y_raw, thresholds, covariates = NULL, lambda1 = 0.5, lambda2 = 0.5, family = "binomial", standardize = TRUE, foldid = NULL, topK = NULL, thresh = 1e-04, nlambda = 20, nfolds = 10, cv = TRUE, ncores = 1, optim_control = list(maxit = 200), lambda = NULL, ... )
X_pcs |
Matrix of predictor variables. |
y_raw |
Vector of continuous exposure or response variable. |
thresholds |
Vector of thresholds at which to binarize y_raw. |
covariates |
Optional matrix or data frame of covariates to adjust for. Covariates are unpenalized. An intercept is automatically added if not present. |
lambda1 |
Ridge penalty weight (defaults to 0.5). |
lambda2 |
Fusion penalty weight (defaults to 0.5). |
family |
Model family. Supported values are |
standardize |
Boolean indicating whether to scale the predictor matrix. Defaults to TRUE. |
foldid |
Optional fold IDs. If |
topK |
Optional integer. If provided, fits a first pass model, selects the union of the |
thresh |
Convergence threshold. Ignored (provided for compatibility with |
nlambda |
Number of lambda values to use in the cross-validation grid. Defaults to 20. |
nfolds |
Number of folds for cross-validation (defaults to 10). |
cv |
Boolean indicating whether to perform pathwise group-structured cross-validation to select the optimal overall regularization scale. Defaults to TRUE. |
ncores |
Number of CPU cores to use for cross-validation. Defaults to |
optim_control |
Optional list of control parameters passed to |
lambda |
Optional numeric value. If provided, CV is skipped and the model is fit directly using the specified lambda value. |
... |
Additional arguments passed to |
Fits a joint Fused Ridge regression model across multiple binarized thresholds of a continuous response variable,
smoothing the coefficient trajectories using a 1D Graph Laplacian. Unlike fusedRidge, which transforms the
design matrix using a Kronecker product expansion, fusedRidgeDirect optimizes the loss function directly
using R's built-in optim function with the "L-BFGS-B" method and analytical gradients.
If cv = TRUE, it performs pathwise group-structured cross-validation (with warm starts) to select the optimal
overall scale multiplier for the penalties, matching the cross-validation behavior of fusedRidge.
A list of class c("fusedRidgeDirect", "fusedRidge") containing:
fit |
The final fitted optim object (or list of options). |
cv |
Cross-validation details including grid values, mean validation errors, and standard deviations. |
optimal_lambda |
Optimal lambda multiplier selected by cross-validation (or NA if cv = FALSE). |
a0 |
0 (intercepts are included in |
coefs_covs |
Reconstructed covariate coefficients matrix. |
coefs_full |
Reconstructed full coefficient matrix. |
theta_matrix |
Coefficients in the original space. |
H |
Identity matrix placeholder. |
thresholds |
Input thresholds vector. |
family |
Model family. |
y_matrix |
Binarized target matrix. |
mean_X |
Scaling center parameters. |
sd_X |
Scaling scale parameters. |
covs_names |
Names of covariates. |
Fits a joint Fused Ridge regression model across multiple binarized thresholds of a continuous response variable using PyTorch L-BFGS and automatic differentiation. This avoids the memory-intensive Kronecker product design matrix expansion, and leverages PyTorch's highly optimized solvers and potential hardware acceleration (MPS/CUDA).
fusedRidgeTorch( X_pcs, y_raw, thresholds, covariates = NULL, lambda1 = 0.5, lambda2 = 0.5, family = "binomial", standardize = TRUE, foldid = NULL, topK = NULL, thresh = 1e-04, nlambda = 20, nfolds = 10, cv = TRUE, device = "cpu", optim_control = list(maxit = 200), alpha = 0, sparsity_thresh = 1e-04, lambda = NULL, ... )fusedRidgeTorch( X_pcs, y_raw, thresholds, covariates = NULL, lambda1 = 0.5, lambda2 = 0.5, family = "binomial", standardize = TRUE, foldid = NULL, topK = NULL, thresh = 1e-04, nlambda = 20, nfolds = 10, cv = TRUE, device = "cpu", optim_control = list(maxit = 200), alpha = 0, sparsity_thresh = 1e-04, lambda = NULL, ... )
X_pcs |
Matrix of predictor variables. |
y_raw |
Vector of continuous exposure or response variable. |
thresholds |
Vector of thresholds at which to binarize y_raw. |
covariates |
Optional matrix or data frame of covariates to adjust for. Covariates are unpenalized. An intercept is automatically added if not present. |
lambda1 |
Ridge penalty weight (defaults to 0.5). |
lambda2 |
Fusion penalty weight (defaults to 0.5). |
family |
Model family. Supported values are |
standardize |
Boolean indicating whether to scale the predictor matrix. Defaults to TRUE. |
foldid |
Optional fold IDs. If |
topK |
Optional integer. If provided, fits a first pass model, selects the union of the |
thresh |
Convergence threshold. |
nlambda |
Number of lambda values to use in the cross-validation grid. Defaults to 20. |
nfolds |
Number of folds for cross-validation (defaults to 10). |
cv |
Boolean indicating whether to perform pathwise group-structured cross-validation to select the optimal overall regularization scale. Defaults to TRUE. |
device |
PyTorch device. Can be |
optim_control |
Optional list of control parameters passed to the PyTorch optimizer. Defaults to |
alpha |
Elastic net mixing parameter between 0 and 1. |
sparsity_thresh |
Hard threshold for sparsity post-optimization. Any coefficient smaller in absolute value is zeroed out. Defaults to 1e-4. |
lambda |
Optional numeric value. If provided, CV is skipped and the model is fit directly using the specified lambda value. |
... |
Additional arguments (currently ignored). |
A list of class c("fusedRidgeTorch", "fusedRidgeDirect", "fusedRidge") containing:
fit |
Details from the final PyTorch fit. |
cv |
Cross-validation details including grid values, mean validation errors, and standard deviations. |
optimal_lambda |
Optimal lambda multiplier selected by cross-validation (or NA if cv = FALSE). |
a0 |
0 (intercepts are included in |
coefs_covs |
Reconstructed covariate coefficients matrix. |
coefs_full |
Reconstructed full coefficient matrix. |
theta_matrix |
Coefficients in the original space. |
H |
Identity matrix placeholder. |
thresholds |
Input thresholds vector. |
family |
Model family. |
y_matrix |
Binarized target matrix. |
mean_X |
Scaling center parameters. |
sd_X |
Scaling scale parameters. |
covs_names |
Names of covariates. |
Fuzzy spatial c-means for image segmentation.
fuzzySpatialCMeansSegmentation( image, mask = NULL, numberOfClusters = 4, m = 2, p = 1, q = 1, radius = 2, maxNumberOfIterations = 20, convergenceThreshold = 0.02, verbose = FALSE )fuzzySpatialCMeansSegmentation( image, mask = NULL, numberOfClusters = 4, m = 2, p = 1, q = 1, radius = 2, maxNumberOfIterations = 20, convergenceThreshold = 0.02, verbose = FALSE )
image |
image to be segmented. |
mask |
optional mask image. Otherwise, the entire image is used. |
numberOfClusters |
number of segmentation clusters |
m |
fuzziness parameter (default = 2). |
p |
membership importance parameter (default = 1). |
q |
spatial constraint importance parameter (default = 1).
|
radius |
neighborhood radius (scalar or array) for spatial constraint. |
maxNumberOfIterations |
iteration limit (default = 20). |
convergenceThreshold |
Convergence between iterations is measured using the Dice coefficient (default = 0.02). |
verbose |
print progress. |
Image segmentation using fuzzy spatial c-means as described in
Chuang et al., Fuzzy c-means clustering with spatial information for image segmentation. CMIG: 30:9-15, 2006.
list containing segmentation and probability images
NJ Tustison
image <- antsImageRead(getANTsRData("r16")) mask <- getMask(image) fuzzy <- fuzzySpatialCMeansSegmentation(image, mask)image <- antsImageRead(getANTsRData("r16")) mask <- getMask(image) fuzzy <- fuzzySpatialCMeansSegmentation(image, mask)
This function creates simulated multi-view data with a complex and realistic ground truth, containing both shared and modality-specific latent signals.
generate_structured_multiview_data( n_subjects, n_features, k_shared, k_specific, noise_sd = 0.1, sparsity_level = 0.5, seed = NULL )generate_structured_multiview_data( n_subjects, n_features, k_shared, k_specific, noise_sd = 0.1, sparsity_level = 0.5, seed = NULL )
n_subjects |
The number of subjects (rows). |
n_features |
A vector of integers specifying the number of features for each view. |
k_shared |
The number of latent components common to ALL views. |
k_specific |
A vector of integers specifying the number of unique latent components for EACH view. If a single number is given, it's recycled. |
noise_sd |
The standard deviation of the Gaussian noise added to the data. |
sparsity_level |
The proportion of elements in the shared loading matrix (V_f) to set to zero. A value between 0 and 1. Defaults to 0.5. |
seed |
An optional random seed for reproducibility. |
A list containing:
data_list |
A named list of the final [n x p] data matrices. |
ground_truth |
A list containing the true latent structures:
|
Automated approach for generating a mask to be used for modeling the arterial input function using the method described in https://pubmed.ncbi.nlm.nih.gov/15956519.
generateAifMaskImage(perfusionImage, voiMaskImage, index = NA)generateAifMaskImage(perfusionImage, voiMaskImage, index = NA)
perfusionImage |
time series (n-D + time) perfusion acquisition. |
voiMaskImage |
n-D mask image indicating where the cerebral blood flow parameter images are calculated. |
index |
If the user prefers a specific voxel if looking at the plots, they can simply specify the index (gleaned from the file names) and the corresponding AIF mask image is created. |
list( mask image, fitting results )
Tustison NJ
uses topological constraints to enhance accuracy of brain segmentation
geoSeg( img, brainmask, priors, seginit, vesselopt = "none", vesselk = 2, gradStep = 1.25, mrfval = 0.1, atroposits = 10, jacw = NULL, beta = 0.9 )geoSeg( img, brainmask, priors, seginit, vesselopt = "none", vesselk = 2, gradStep = 1.25, mrfval = 0.1, atroposits = 10, jacw = NULL, beta = 0.9 )
img |
input image or list of images (multiple features) where 1st image would typically be the primary constrast |
brainmask |
binary image |
priors |
spatial priors, assume first is csf, second is gm, third is wm |
seginit |
a previously computed segmentation which should have the structure of |
vesselopt |
one of bright, dark or none |
vesselk |
integer for kmeans vessel-based processing |
gradStep |
scalar for registration |
mrfval |
e.g. 0.05 or 0.1 |
atroposits |
e.g. 5 iterations |
jacw |
precomputed diffeo jacobian |
beta |
for sigma transformation ( thksig output variable ) |
list of segmentation result images
Brian B. Avants
## Not run: img <- antsImageRead(getANTsRData("simple"), 2) img <- n3BiasFieldCorrection(img, 4) img <- n3BiasFieldCorrection(img, 2) bmk <- getMask(img) segs <- kmeansSegmentation(img, 3, bmk) priors <- segs$probabilityimages seg <- geoSeg(img, bmk, priors) ## End(Not run)## Not run: img <- antsImageRead(getANTsRData("simple"), 2) img <- n3BiasFieldCorrection(img, 4) img <- n3BiasFieldCorrection(img, 2) bmk <- getMask(img) segs <- kmeansSegmentation(img, 3, bmk) priors <- segs$probabilityimages seg <- geoSeg(img, bmk, priors) ## End(Not run)
Downloads antsr test data
getANTsRData( fileid, usefixedlocation = FALSE, verbose = FALSE, method = ifelse(Sys.info()["sysname"] == "Linux", "wget", "auto"), quiet = FALSE )getANTsRData( fileid, usefixedlocation = FALSE, verbose = FALSE, method = ifelse(Sys.info()["sysname"] == "Linux", "wget", "auto"), quiet = FALSE )
fileid |
one of the permitted file ids or pass "show" to list all valid possibilities. Note that most require internet access to download. |
usefixedlocation |
directory to which you download files |
verbose |
optional boolean |
method |
Method to be used for downloading files,
passed to |
quiet |
If |
filename string
Avants BB
fi <- getANTsRData("r16")fi <- getANTsRData("r16")
Get fixed parameters of transform
getAntsrTransformFixedParameters(transform)getAntsrTransformFixedParameters(transform)
transform |
antsrTransform |
array of fixed parameters
tx <- new("antsrTransform") params <- getAntsrTransformFixedParameters(tx)tx <- new("antsrTransform") params <- getAntsrTransformFixedParameters(tx)
Get parameters of transform
getAntsrTransformParameters(transform)getAntsrTransformParameters(transform)
transform |
antsrTransform |
array of parameters'
tx <- new("antsrTransform") params <- getAntsrTransformParameters(tx)tx <- new("antsrTransform") params <- getAntsrTransformParameters(tx)
Get nuisance predictors from ASL images
getASLNoisePredictors( aslmat, tc, noisefrac = 0.1, polydegree = "loess", k = 5, npreds = 12, method = "noisepool", covariates = NA, noisepoolfun = max )getASLNoisePredictors( aslmat, tc, noisefrac = 0.1, polydegree = "loess", k = 5, npreds = 12, method = "noisepool", covariates = NA, noisepoolfun = max )
aslmat |
ASL input matrix. |
tc |
Tag-control sawtooth pattern vector. |
noisefrac |
Fraction of data to include in noise pool. |
polydegree |
Degree of polynomial for detrending, with a value of 0
indicating no detrending, or |
k |
Number of cross-validation folds. |
npreds |
Number of predictors to output. |
method |
Method of selecting noisy voxels. One of 'compcor' or
'noisepool'. See |
covariates |
Covariates to be considered when assessing prediction of tc pattern. |
noisepoolfun |
Function used for aggregating R^2 values. |
Matrix of size nrow(aslmat) by npreds, containing a
timeseries of all the nuisance predictors.
Brian B. Avants, Benjamin M. Kandel
# for real data do img<-antsImageRead(getANTsRData("pcasl"),4) set.seed(120) img <- makeImage(c(10, 10, 10, 20), rnorm(1000 * 20) + 1) mask <- getMask(getAverageOfTimeSeries(img)) aslmat <- timeseries2matrix(img, mask) tc <- rep(c(0.5, -0.5), length.out = nrow(aslmat)) noise <- getASLNoisePredictors(aslmat, tc, k = 2, npreds = 2, noisefrac = 0.5) cm <- colMeans(noise) rounding_type <- RNGkind()[3] if (getRversion() < "3.6.0" || rounding_type == "Rounding") { testthat::expect_equal(cm, c(-0.223292128499263, 0.00434481670243642), tolerance = .01) } else { testthat::expect_equal(cm, c(-0.223377249912075, 0.0012754214030999), tolerance = .01) }# for real data do img<-antsImageRead(getANTsRData("pcasl"),4) set.seed(120) img <- makeImage(c(10, 10, 10, 20), rnorm(1000 * 20) + 1) mask <- getMask(getAverageOfTimeSeries(img)) aslmat <- timeseries2matrix(img, mask) tc <- rep(c(0.5, -0.5), length.out = nrow(aslmat)) noise <- getASLNoisePredictors(aslmat, tc, k = 2, npreds = 2, noisefrac = 0.5) cm <- colMeans(noise) rounding_type <- RNGkind()[3] if (getRversion() < "3.6.0" || rounding_type == "Rounding") { testthat::expect_equal(cm, c(-0.223292128499263, 0.00434481670243642), tolerance = .01) } else { testthat::expect_equal(cm, c(-0.223377249912075, 0.0012754214030999), tolerance = .01) }
Returns a 3D average of a 4D time series.
getAverageOfTimeSeries(img)getAverageOfTimeSeries(img)
img |
input 4D image |
3D ants image is output
Avants BB
img <- as.antsImage(array(data = rep(0, 10^4), dim = c(10, 10, 10, 10))) avg <- getAverageOfTimeSeries(img)img <- as.antsImage(array(data = rep(0, 10^4), dim = c(10, 10, 10, 10))) avg <- getAverageOfTimeSeries(img)
compute an image center of mass in physical space which is defined as the mean of the intensity weighted voxel coordinate system.
getCenterOfMass(img)getCenterOfMass(img)
img |
antsImage |
vector center of mass
Brian B. Avants
fi <- antsImageRead(getANTsRData("r16")) com1 <- getCenterOfMass(fi) fi <- antsImageRead(getANTsRData("r64")) com2 <- getCenterOfMass(fi)fi <- antsImageRead(getANTsRData("r16")) com1 <- getCenterOfMass(fi) fi <- antsImageRead(getANTsRData("r64")) com2 <- getCenterOfMass(fi)
Reduces a variate/statistical/network image to a set of centroids describing the center of each stand-alone non-zero component in the image.
getCentroids(img, clustparam = 0)getCentroids(img, clustparam = 0)
img |
the image to reduce to centroids - presumably some kind of statistical or network map |
clustparam |
look at regions greater than or equal to this size |
the centroids are output in matrix of size npoints by 3
Avants BB
img <- antsImageRead(getANTsRData("r16")) img <- thresholdImage(img, 90, 120) img <- labelClusters(img, 10) cents <- getCentroids(img)img <- antsImageRead(getANTsRData("r16")) img <- thresholdImage(img, 90, 120) img <- labelClusters(img, 10) cents <- getCentroids(img)
Will motion correct, run compcorr and estimate global signal. Outputs a list with the time series data matrix (time by voxels), motion and other nuisance variables, global signal (for BOLD or ASL), the mask and the average time series image. Meant to be used before filterfMRIforNetworkAnalysis or any other results-oriented processing.
getfMRInuisanceVariables(fmri, maskThresh = 500, moreaccurate = 1, mask = NULL)getfMRInuisanceVariables(fmri, maskThresh = 500, moreaccurate = 1, mask = NULL)
fmri |
input antsImage or filename |
maskThresh |
will use this intensity threshold to estimate a mask otherwise will use the mask passed in |
moreaccurate |
zero, one or two with increasing accuracy/computation |
mask |
binary image masking the intput image, precedent over mask thresh |
outputs list described above.
Avants BB
## Not run: if (!exists("fn")) fn <- getANTsRData("pcasl") pcasl <- antsImageRead(fn) aslmean <- getAverageOfTimeSeries(pcasl) aslmask <- getMask(aslmean) ee <- getfMRInuisanceVariables(pcasl, mask = aslmask, moreaccurate = F ) ## End(Not run)## Not run: if (!exists("fn")) fn <- getANTsRData("pcasl") pcasl <- antsImageRead(fn) aslmean <- getAverageOfTimeSeries(pcasl) aslmask <- getMask(aslmean) ee <- getfMRInuisanceVariables(pcasl, mask = aslmask, moreaccurate = F ) ## End(Not run)
Get a binary mask image from the given image after thresholding.
getMask(img, lowThresh, highThresh, cleanup = 2)getMask(img, lowThresh, highThresh, cleanup = 2)
img |
Input image. Can be an |
lowThresh |
An inclusive lower threshold for voxels to be included in the mask. |
highThresh |
An inclusive upper threshold for voxels to be included in the mask. |
cleanup |
If |
If cleanup is >0, the following steps are applied
Erosion with radius 2 voxels
Retain largest component
Dilation with radius 1 voxel
Morphological closing
These functions are available in iMath, see the operations “ME”, “GetLargestComponent”, “MD”, “FillHoles”.
Object of type antsImage containing the mask image. The
voxel intensities will be binarized, 1 for voxels in the mask and 0 outside.
Shrinidhi KL, Cook PA, Avants BB
img <- ri(1) mask <- getMask(img) testthat::expect_error(getMask(img, lowThresh = "hey")) pixeltype(img) <- "unsigned int" mask2 <- getMask(img)img <- ri(1) mask <- getMask(img) testthat::expect_error(getMask(img, lowThresh = "hey")) pixeltype(img) <- "unsigned int" mask2 <- getMask(img)
Represents feature images as a neighborhood across scales. each subject gets a label image and feature list. these labels/features should be the same type for all subjects. e.g each subject has a k-label image where the labels cover the same anatomy and the feature images are the same. for each label in a mask, produce a multi-resolution neighborhood sampling from the data within the label, for a given feature. do this for each feature. so, 2 labels will double the width of the predictor matrix. an additional scale parameter or feature will increase the width. more samples will increase the number of rows in the predictor matrix. the labels allow one to collect predictors side-by-side from different parts of an image-based feature set. future work will allow other covariates.
getMultiResFeatureMatrix( x, labelmask, rad = NA, multiResSchedule = c(0), nsamples = 10 )getMultiResFeatureMatrix( x, labelmask, rad = NA, multiResSchedule = c(0), nsamples = 10 )
x |
a list of feature images |
labelmask |
the mask defines the image space for the associated feature and increases the number of predictors. more labels means more predictors. a different mask may be used for each feature, if desired, in which case this should be a list of masks where the length of the list is equal to the number of features. |
rad |
vector of dimensionality d define nhood radius |
multiResSchedule |
a vector of smoothing values |
nsamples |
defines the number of samples to take for each label. |
mat a matrix of predictors with n samples rows
Avants BB, Tustison NJ
img <- antsImageRead(getANTsRData("r16")) seg <- kmeansSegmentation(img, 3)$segmentation flist <- list(img, img %>% iMath("Grad")) featMat <- getMultiResFeatureMatrix(flist, seg, rad = c(1, 1), multiResSchedule = c(2, 1), nsamples = 10 )img <- antsImageRead(getANTsRData("r16")) seg <- kmeansSegmentation(img, 3)$segmentation flist <- list(img, img %>% iMath("Grad")) featMat <- getMultiResFeatureMatrix(flist, seg, rad = c(1, 1), multiResSchedule = c(2, 1), nsamples = 10 )
This function will provide a mapping that labels the list of input images and each of their blobs.
getMultivariateTemplateCoordinates( imageSetToBeLabeledIn, templateWithLabels, labelnames = NULL, outprefix = NA, convertToTal = FALSE, pvals = NA, threshparam = 1, clustparam = 250, identifier )getMultivariateTemplateCoordinates( imageSetToBeLabeledIn, templateWithLabels, labelnames = NULL, outprefix = NA, convertToTal = FALSE, pvals = NA, threshparam = 1, clustparam = 250, identifier )
imageSetToBeLabeledIn |
a template paired with (most likely) the output of a multivariate sparse decomposition or (alternatively) could be just a statistical map with zeroes in non-interesting areas |
templateWithLabels |
e..g the mni image and brodmann label set |
labelnames |
a list of names for the labels |
outprefix |
if output to a file, provide file prefix |
convertToTal |
bool, return talairach coordinates |
pvals |
the already computed pvalue for each component |
threshparam |
for pvals |
clustparam |
for clusters |
identifier |
unique ID for this study |
Uses getTemplateCoordinates as a sub-routine.
TBN
The output point coordinates are in approximate Talairach / MNI (or whatever) template space.
Avants, BB
## Not run: tem <- antsImageRead(getANTsRData("ch2")) temlab <- antsImageRead(getANTsRData("ch2b")) temlab2 <- antsImageRead(getANTsRData("ch2a")) # try getANTsRData if you have www access mymni <- list( antsImageRead(getANTsRData("mni"), 3), antsImageRead(getANTsRData("mnib"), 3), antsImageRead(getANTsRData("mnia"), 3) ) mytem <- list(smoothImage(tem, 3), temlab, temlab2) # mynetworkdescriptor<-getMultivariateTemplateCoordinates( # mytem, mymni , convertToTal = TRUE , pvals=c(0.01,0.05) ) ## End(Not run)## Not run: tem <- antsImageRead(getANTsRData("ch2")) temlab <- antsImageRead(getANTsRData("ch2b")) temlab2 <- antsImageRead(getANTsRData("ch2a")) # try getANTsRData if you have www access mymni <- list( antsImageRead(getANTsRData("mni"), 3), antsImageRead(getANTsRData("mnib"), 3), antsImageRead(getANTsRData("mnia"), 3) ) mytem <- list(smoothImage(tem, 3), temlab, temlab2) # mynetworkdescriptor<-getMultivariateTemplateCoordinates( # mytem, mymni , convertToTal = TRUE , pvals=c(0.01,0.05) ) ## End(Not run)
Extract column names with concatenated search parameters
getNamesFromDataframe(x, demogIn, exclusions)getNamesFromDataframe(x, demogIn, exclusions)
x |
vector of strings |
demogIn |
the dataframe with column names to search. |
exclusions |
the strings to exclude |
vector of string column names
Avants BB
# nms = getNamesFromDataframe( c("sp","ed"), cars )# nms = getNamesFromDataframe( c("sp","ed"), cars )
Get the values in a local neighborhood of an antsImage.
getNeighborhoodAtVoxel(image, center, kernel, physical.coordinates = FALSE)getNeighborhoodAtVoxel(image, center, kernel, physical.coordinates = FALSE)
image |
Image object of S4 class |
center |
array of indices for neighborhood center |
kernel |
either an array of values for neighborhood radius (in voxels) or a binary array of the same dimension as the image, specifying the shape of the neighborhood to extract |
physical.coordinates |
a logical indicating if voxel indices and offsets should be in voxel or physical coordinates |
a list
numeric vector of values
matrix providing the coordinates for each value
Duda JT
img <- makeImage(c(10, 10), rnorm(100)) center <- dim(img) / 2 radius <- rep(3, 2) nhlist <- getNeighborhoodAtVoxel(img, center, radius) kernel <- 1 * (rnorm(49) > 0) dim(kernel) <- c(7, 7) randlist <- getNeighborhoodAtVoxel(img, center, kernel) randlist <- getNeighborhoodAtVoxel(img, center, kernel, physical.coordinates = TRUE ) arr <- as.array(img) testthat::expect_error(getNeighborhoodAtVoxel(arr, center, kernel), "class") testthat::expect_error( getNeighborhoodAtVoxel(img, as.character(center), kernel), "center must be" ) testthat::expect_error( getNeighborhoodAtVoxel(img, center, c(radius, 3)), "kernel must have same" )img <- makeImage(c(10, 10), rnorm(100)) center <- dim(img) / 2 radius <- rep(3, 2) nhlist <- getNeighborhoodAtVoxel(img, center, radius) kernel <- 1 * (rnorm(49) > 0) dim(kernel) <- c(7, 7) randlist <- getNeighborhoodAtVoxel(img, center, kernel) randlist <- getNeighborhoodAtVoxel(img, center, kernel, physical.coordinates = TRUE ) arr <- as.array(img) testthat::expect_error(getNeighborhoodAtVoxel(arr, center, kernel), "class") testthat::expect_error( getNeighborhoodAtVoxel(img, as.character(center), kernel), "center must be" ) testthat::expect_error( getNeighborhoodAtVoxel(img, center, c(radius, 3)), "kernel must have same" )
this converts a scalar image to a matrix with rows that contain neighbors around a center voxel
getNeighborhoodInMask( image, mask, radius, physical.coordinates = FALSE, boundary.condition = "NA", spatial.info = FALSE, get.gradient = FALSE )getNeighborhoodInMask( image, mask, radius, physical.coordinates = FALSE, boundary.condition = "NA", spatial.info = FALSE, get.gradient = FALSE )
image |
image object of S4 class |
mask |
image object of S4 class |
radius |
array of values for neighborhood radius (in voxels) |
physical.coordinates |
logical indicating if voxel indices and offsets should be in voxel or physical coordinates |
boundary.condition |
string indicating how to handle voxels in a
neighborhood, but not in the mask. See |
spatial.info |
a boolean indicating of voxel locations and neighborhood offsets should be returned along with pixel values. |
get.gradient |
a boolean indicating if a matrix of gradients (at the center voxel) should be returned in addition to the value matrix (WIP) |
boundary.condition should be one of:
NA: Fill values with NA.
image: Use image value, even if not in mask.
mean: Use man of all non-NA values for that neighborhood.
if spatial.info is false: a matrix of pixel values where the number of rows
is the size of the neighborhood and there is a column for each voxel
if spatial.info is true, a list containing three matrices:
matrix of pixel values where the number of rows is the size of the neighborhood and there is a column for each voxel.
matrix providing the center coordinates for each neighborhood
matrix providing the offsets from center for each voxel in a neighborhood
Duda JT
r16 <- getANTsRData("r16") r16 <- antsImageRead(r16, 2) mask <- getMask(r16, lowThresh = mean(r16), cleanup = 1) radius <- rep(2, 2) mat <- getNeighborhoodInMask(r16, mask, radius) mat <- getNeighborhoodInMask(r16, mask, radius, boundary.condition = "image" ) mat <- getNeighborhoodInMask(r16, mask, radius, boundary.condition = "mean" ) randlist <- getNeighborhoodInMask(r16, mask, radius, physical.coordinates = TRUE ) arr <- as.array(r16) testthat::expect_error(getNeighborhoodInMask(arr, mask, radius), "antsImage") testthat::expect_error( getNeighborhoodInMask(r16, as.numeric(mask), radius), "mask must be" ) testthat::expect_error( getNeighborhoodInMask(r16, mask, as.character(radius)), "radius must be" ) # testthat::expect_error(getNeighborhoodInMask(r16,mask,c(radius, 3)), # "Radius must")r16 <- getANTsRData("r16") r16 <- antsImageRead(r16, 2) mask <- getMask(r16, lowThresh = mean(r16), cleanup = 1) radius <- rep(2, 2) mat <- getNeighborhoodInMask(r16, mask, radius) mat <- getNeighborhoodInMask(r16, mask, radius, boundary.condition = "image" ) mat <- getNeighborhoodInMask(r16, mask, radius, boundary.condition = "mean" ) randlist <- getNeighborhoodInMask(r16, mask, radius, physical.coordinates = TRUE ) arr <- as.array(r16) testthat::expect_error(getNeighborhoodInMask(arr, mask, radius), "antsImage") testthat::expect_error( getNeighborhoodInMask(r16, as.numeric(mask), radius), "mask must be" ) testthat::expect_error( getNeighborhoodInMask(r16, mask, as.character(radius)), "radius must be" ) # testthat::expect_error(getNeighborhoodInMask(r16,mask,c(radius, 3)), # "Radius must")
Get pixel values from an 'antsImage'.
getPixels(x, i = NA, j = NA, k = NA, l = NA)getPixels(x, i = NA, j = NA, k = NA, l = NA)
x |
Image object of S4 class 'antsImage' to get values from. |
i |
indices in first dimension |
j |
indices in second dimension |
k |
indices in third dimension |
l |
indices in forth dimension |
array of pixel values
img <- makeImage(c(10, 10), rnorm(100)) pixel <- getPixels(img, i = c(1, 2), j = 1)img <- makeImage(c(10, 10), rnorm(100)) pixel <- getPixels(img, i = c(1, 2), j = 1)
This function will provide a mapping that labels an input image and its blobs.
getTemplateCoordinates( imagePairToBeLabeled, templatePairWithLabels, labelnames = NULL, outprefix = NA, convertToTal = FALSE )getTemplateCoordinates( imagePairToBeLabeled, templatePairWithLabels, labelnames = NULL, outprefix = NA, convertToTal = FALSE )
imagePairToBeLabeled |
e.g. the template image and the activation map |
templatePairWithLabels |
e..g the mni image and brodmann label set |
labelnames |
a list of names for the labels |
outprefix |
if output to a file, provide file prefix |
convertToTal |
bool, return talairach coordinates |
Uses Matthew Brett's mni2tal to get the final Talairach coordinates from MNI space.
This is a standard approach but it's not very accurate.
The output point is in approximate template space.
Avants, BB
## Not run: # # ch2bet is available in chris rorden's mricron # but you can do something with any other image # e.g. a statistical image # tem <- antsImageRead(getANTsRData("ch2"), 3) clust <- antsImageClone(tem) atem <- as.array(tem) clust[atem < 80] <- 0 clust[atem > 90] <- 0 clust[atem > 80 & atem < 90] <- 1 clust <- iMath(clust, "ME", 1) # erosion clust <- labelClusters(clust, minClusterSize = 30, minThresh = 1, maxThresh = 1) if (!exists("mymni")) { # try getANTsRData if you have www access mymni <- list( antsImageRead(getANTsRData("mni"), 3), antsImageRead(getANTsRData("mnib"), 3), antsImageRead(getANTsRData("mnia"), 3) ) } template_cluster_pair <- list(tem, clust) gcoords <- getTemplateCoordinates(template_cluster_pair, mymni, convertToTal = TRUE ) # output will be like # > gcoords$templatepoints # x y z t label Brodmann AAL # 1 -12 13 -3 0 1 0 Caudate_R # 2 13 16 5 0 2 0 Caudate_L # # can also use a white matter label set ... # ## End(Not run)## Not run: # # ch2bet is available in chris rorden's mricron # but you can do something with any other image # e.g. a statistical image # tem <- antsImageRead(getANTsRData("ch2"), 3) clust <- antsImageClone(tem) atem <- as.array(tem) clust[atem < 80] <- 0 clust[atem > 90] <- 0 clust[atem > 80 & atem < 90] <- 1 clust <- iMath(clust, "ME", 1) # erosion clust <- labelClusters(clust, minClusterSize = 30, minThresh = 1, maxThresh = 1) if (!exists("mymni")) { # try getANTsRData if you have www access mymni <- list( antsImageRead(getANTsRData("mni"), 3), antsImageRead(getANTsRData("mnib"), 3), antsImageRead(getANTsRData("mnia"), 3) ) } template_cluster_pair <- list(tem, clust) gcoords <- getTemplateCoordinates(template_cluster_pair, mymni, convertToTal = TRUE ) # output will be like # > gcoords$templatepoints # x y z t label Brodmann AAL # 1 -12 13 -3 0 1 0 Caudate_R # 2 13 16 5 0 2 0 Caudate_L # # can also use a white matter label set ... # ## End(Not run)
Impute missing data using GLM models
glm_impute( dataframe, columns_to_impute, predictor_columns, family = "gaussian" )glm_impute( dataframe, columns_to_impute, predictor_columns, family = "gaussian" )
dataframe |
A data frame containing the data to impute. |
columns_to_impute |
A vector of column names to impute. |
predictor_columns |
A vector of column names to use as predictors. |
family |
A string specifying the GLM family (default is 'gaussian'). |
A data frame with imputed values.
set.seed(123) df <- data.frame( age = c(25, 30, 35, NA, 45, 50, NA, 40, 35, NA), income = c(50000, 60000, 70000, 80000, 90000, 100000, 110000, NA, 120000, 130000), education = c(12, 16, 14, 12, NA, 18, 20, 16, 14, 12) ) columns_to_impute <- c("age") predictor_columns <- c( "income", "education") imputed_data <- glm_impute(df, columns_to_impute, predictor_columns, family = 'gaussian') print(imputed_data)set.seed(123) df <- data.frame( age = c(25, 30, 35, NA, 45, 50, NA, 40, 35, NA), income = c(50000, 60000, 70000, 80000, 90000, 100000, 110000, NA, 120000, 130000), education = c(12, 16, 14, 12, NA, 18, 20, 16, 14, 12) ) columns_to_impute <- c("age") predictor_columns <- c( "income", "education") imputed_data <- glm_impute(df, columns_to_impute, predictor_columns, family = 'gaussian') print(imputed_data)
This function computes the gradient of the orthogonality defect for a matrix A,
The orthogonality defect is defined as the sum of the squared off-diagonal elements
of t(A) %*% A.
gradient_invariant_orthogonality_defect(A) gradient_invariant_orthogonality_defect(A)gradient_invariant_orthogonality_defect(A) gradient_invariant_orthogonality_defect(A)
A |
A numeric matrix. |
A matrix representing the gradient of the orthogonality defect with respect to Ap.
This function computes the gradient of the orthogonality defect measure with respect to the input matrix 'A'. The gradient is useful for optimization techniques that require gradient information. The gradient will be zero for matrices where 'AtA' equals the diagonal matrix 'D'.
gradient_invariant_orthogonality_salad(A)gradient_invariant_orthogonality_salad(A)
A |
A numeric matrix. |
A numeric matrix representing the gradient of the orthogonality defect measure.
# library(salad) # A <- matrix(runif(20), nrow = 10, ncol = 2) # gradient_invariant_orthogonality_salad(A)# library(salad) # A <- matrix(runif(20), nrow = 10, ncol = 2) # gradient_invariant_orthogonality_salad(A)
Wrapper for the ITK class HausdorffDistanceImageFilter. More documentaiton available here:
hausdorffDistance(inputImage1, inputImage2)hausdorffDistance(inputImage1, inputImage2)
inputImage1 |
image 1. |
inputImage2 |
image 2. |
http://docs.itk.org/projects/doxygen/en/stable/classitk_1_1HausdorffDistanceImageFilter.html
data frame with overlap measures
Tustison NJ
sourceImage <- antsImageRead(getANTsRData("r16"), 2) sourceSegmentation <- kmeansSegmentation(sourceImage, 3)$segmentation referenceImage <- antsImageRead(getANTsRData("r16"), 2) referenceSegmentation <- kmeansSegmentation(referenceImage, 3)$segmentation hausdorff <- hausdorffDistance(sourceImage, referenceImage)sourceImage <- antsImageRead(getANTsRData("r16"), 2) sourceSegmentation <- kmeansSegmentation(sourceImage, 3)$segmentation referenceImage <- antsImageRead(getANTsRData("r16"), 2) referenceSegmentation <- kmeansSegmentation(referenceImage, 3)$segmentation hausdorff <- hausdorffDistance(sourceImage, referenceImage)
Create the expected BOLD response for a given task indicator function. Borrowed from the fmri package.
hemodynamicRF( scans = 1, onsets = c(1), durations = c(1), rt = 3, times = NULL, mean = TRUE, a1 = 6, a2 = 12, b1 = 0.9, b2 = 0.9, cc = 0.35 )hemodynamicRF( scans = 1, onsets = c(1), durations = c(1), rt = 3, times = NULL, mean = TRUE, a1 = 6, a2 = 12, b1 = 0.9, b2 = 0.9, cc = 0.35 )
scans |
number of scans |
onsets |
vector of onset times (in scans) |
durations |
vector of duration of ON stimulus in scans or seconds (if
|
rt |
time between scans in seconds (TR) |
times |
onset times in seconds. If present |
mean |
logical. if TRUE the mean is substracted from the resulting vector |
a1 |
parameter of the hemodynamic response function (see details) |
a2 |
parameter of the hemodynamic response function (see details) |
b1 |
parameter of the hemodynamic response function (see details) |
b2 |
parameter of the hemodynamic response function (see details) |
cc |
parameter of the hemodynamic response function (see details) |
The functions calculates the expected BOLD response for the task indicator function given by the argument as a convolution with the hemodynamic response function. The latter is modelled by the difference between two gamma functions as given in the reference (with the defaults for a1, a2, b1, b2, cc given therein):
The parameters of this function can be changed through the arguments
a1, a2, b1, b2, cc.
The dimension of the function value is set to c(scans,1).
If !is.null(times) durations are specified in seconds.
If mean is TRUE (default) the resulting vector is corrected to have
zero mean.
Vector with dimension c(scans, 1).
Karsten Tabelow [email protected]
Worsley, K.J., Liao, C., Aston, J., Petre, V., Duncan, G.H., Morales, F., Evans, A.C. (2002). A general statistical analysis for fMRI data. NeuroImage, 15:1-15.
Polzehl, J. and Tabelow, K. (2007) fmri: A Package for Analyzing fmri Data, R News, 7:13-17 .
# Example 1 hrf <- hemodynamicRF(107, c(18, 48, 78), 15, 2) # Example 2: effect of varying parameter cc cc <- round(seq(0, 1, length.out = 10), 2) nlev <- length(cc) cscale <- rgb(seq(0, 1, length.out = nlev), seq(1, 0, length.out = nlev), 0, 1) mat <- matrix(NA, nrow = nlev, ncol = 20) for (i in 1:nlev) { hrf <- ts(hemodynamicRF(scans = 20, onsets = 1, durations = 2, rt = 1, cc = cc[i], a1 = 4, a2 = 3)) mat[i, ] <- hrf } matplot(seq(1, 20), t(mat), "l", lwd = 1, col = cscale, xlab = "Time", ylab = "Response", main = "Parameter cc") legend(x = "topleft", legend = cc, text.col = cscale) # Example 3: effect of varying parameter a1 a1 <- seq(1, 10) nlev <- length(a1) cscale <- rgb(seq(0, 1, length.out = nlev), seq(1, 0, length.out = nlev), 0, 1) mat <- matrix(NA, nrow = nlev, ncol = 20) for (i in 1:nlev) { hrf <- ts(hemodynamicRF(scans = 20, onsets = 1, durations = 2, rt = 1, a1 = a1[i], a2 = 3)) mat[i, ] <- hrf } matplot(seq(1, 20), t(mat), "l", lwd = 1, col = cscale, xlab = "Time", ylab = "Response", main = "Parameter a1") legend(x = "topleft", legend = a1, text.col = cscale) # Example 4: effect of varying parameter a2 a2 <- seq(1, 10) nlev <- length(a2) cscale <- rgb(seq(0, 1, length.out = nlev), seq(1, 0, length.out = nlev), 0, 1) mat <- matrix(NA, nrow = nlev, ncol = 20) for (i in 1:nlev) { hrf <- ts(hemodynamicRF(scans = 20, onsets = 1, durations = 2, rt = 1, a1 = 4, a2 = a2[i])) mat[i, ] <- hrf } matplot(seq(1, 20), t(mat), "l", lwd = 1, col = cscale, xlab = "Time", ylab = "Response", main = "Parameter a2") legend(x = "topleft", legend = a2, text.col = cscale) # Example 5: effect of varying parameter b1 b1 <- seq(0.4, 1.3, by = 0.1) nlev <- length(b1) cscale <- rgb(seq(0, 1, length.out = nlev), seq(1, 0, length.out = nlev), 0, 1) mat <- matrix(NA, nrow = nlev, ncol = 20) for (i in 1:nlev) { hrf <- ts(hemodynamicRF(scans = 20, onsets = 1, durations = 2, rt = 1, a1 = 4, a2 = 3, b1 = b1[i])) mat[i, ] <- hrf } matplot(seq(1, 20), t(mat), "l", lwd = 1, col = cscale, xlab = "Time", ylab = "Response", main = "Parameter b1") legend(x = "topleft", legend = b1, text.col = cscale) # Example 6: effect of varying parameter b2 b2 <- seq(0.4, 1.3, by = 0.1) nlev <- length(b2) cscale <- rgb(seq(0, 1, length.out = nlev), seq(1, 0, length.out = nlev), 0, 1) mat <- matrix(NA, nrow = nlev, ncol = 20) for (i in 1:nlev) { hrf <- ts(hemodynamicRF(scans = 20, onsets = 1, durations = 2, rt = 1, a1 = 4, a2 = 3, b2 = b2[i])) mat[i, ] <- hrf } matplot(seq(1, 20), t(mat), "l", lwd = 1, col = cscale, xlab = "Time", ylab = "Response", main = "Parameter b2") legend(x = "topleft", legend = b2, text.col = cscale)# Example 1 hrf <- hemodynamicRF(107, c(18, 48, 78), 15, 2) # Example 2: effect of varying parameter cc cc <- round(seq(0, 1, length.out = 10), 2) nlev <- length(cc) cscale <- rgb(seq(0, 1, length.out = nlev), seq(1, 0, length.out = nlev), 0, 1) mat <- matrix(NA, nrow = nlev, ncol = 20) for (i in 1:nlev) { hrf <- ts(hemodynamicRF(scans = 20, onsets = 1, durations = 2, rt = 1, cc = cc[i], a1 = 4, a2 = 3)) mat[i, ] <- hrf } matplot(seq(1, 20), t(mat), "l", lwd = 1, col = cscale, xlab = "Time", ylab = "Response", main = "Parameter cc") legend(x = "topleft", legend = cc, text.col = cscale) # Example 3: effect of varying parameter a1 a1 <- seq(1, 10) nlev <- length(a1) cscale <- rgb(seq(0, 1, length.out = nlev), seq(1, 0, length.out = nlev), 0, 1) mat <- matrix(NA, nrow = nlev, ncol = 20) for (i in 1:nlev) { hrf <- ts(hemodynamicRF(scans = 20, onsets = 1, durations = 2, rt = 1, a1 = a1[i], a2 = 3)) mat[i, ] <- hrf } matplot(seq(1, 20), t(mat), "l", lwd = 1, col = cscale, xlab = "Time", ylab = "Response", main = "Parameter a1") legend(x = "topleft", legend = a1, text.col = cscale) # Example 4: effect of varying parameter a2 a2 <- seq(1, 10) nlev <- length(a2) cscale <- rgb(seq(0, 1, length.out = nlev), seq(1, 0, length.out = nlev), 0, 1) mat <- matrix(NA, nrow = nlev, ncol = 20) for (i in 1:nlev) { hrf <- ts(hemodynamicRF(scans = 20, onsets = 1, durations = 2, rt = 1, a1 = 4, a2 = a2[i])) mat[i, ] <- hrf } matplot(seq(1, 20), t(mat), "l", lwd = 1, col = cscale, xlab = "Time", ylab = "Response", main = "Parameter a2") legend(x = "topleft", legend = a2, text.col = cscale) # Example 5: effect of varying parameter b1 b1 <- seq(0.4, 1.3, by = 0.1) nlev <- length(b1) cscale <- rgb(seq(0, 1, length.out = nlev), seq(1, 0, length.out = nlev), 0, 1) mat <- matrix(NA, nrow = nlev, ncol = 20) for (i in 1:nlev) { hrf <- ts(hemodynamicRF(scans = 20, onsets = 1, durations = 2, rt = 1, a1 = 4, a2 = 3, b1 = b1[i])) mat[i, ] <- hrf } matplot(seq(1, 20), t(mat), "l", lwd = 1, col = cscale, xlab = "Time", ylab = "Response", main = "Parameter b1") legend(x = "topleft", legend = b1, text.col = cscale) # Example 6: effect of varying parameter b2 b2 <- seq(0.4, 1.3, by = 0.1) nlev <- length(b2) cscale <- rgb(seq(0, 1, length.out = nlev), seq(1, 0, length.out = nlev), 0, 1) mat <- matrix(NA, nrow = nlev, ncol = 20) for (i in 1:nlev) { hrf <- ts(hemodynamicRF(scans = 20, onsets = 1, durations = 2, rt = 1, a1 = 4, a2 = 3, b2 = b2[i])) mat[i, ] <- hrf } matplot(seq(1, 20), t(mat), "l", lwd = 1, col = cscale, xlab = "Time", ylab = "Response", main = "Parameter b2") legend(x = "topleft", legend = b2, text.col = cscale)
Interface to ITK filter. Based on the paper by Westin et al., "Geometrical Diffusion Measures for MRI from Tensor Basis Analysis" and Luca Antiga's Insight Journal paper http://hdl.handle.net/1926/576.
hessianObjectness( image, objectDimension = 1, isBrightObject = TRUE, sigmaMin = 0.1, sigmaMax = 10, numberOfSigmaSteps = 10, useSigmaLogarithmicSpacing = TRUE, alpha = 0.5, beta = 0.5, gamma = 5, setScaleObjectnessMeasure = TRUE )hessianObjectness( image, objectDimension = 1, isBrightObject = TRUE, sigmaMin = 0.1, sigmaMax = 10, numberOfSigmaSteps = 10, useSigmaLogarithmicSpacing = TRUE, alpha = 0.5, beta = 0.5, gamma = 5, setScaleObjectnessMeasure = TRUE )
image |
input image |
objectDimension |
0: 'sphere', 1: 'line', or 2: 'plane'. |
isBrightObject |
Set 'true' for enhancing bright objects and 'false' for dark objects. |
sigmaMin |
Define scale domain for feature extraction. |
sigmaMax |
Define scale domain for feature extraction. |
numberOfSigmaSteps |
Define number of samples for scale space. |
useSigmaLogarithmicSpacing |
Define sample spacing the for scale space. |
alpha |
Hessian filter parameter. |
beta |
Hessian filter parameter. |
gamma |
Hessian filter parameter. |
setScaleObjectnessMeasure |
... |
hessian objectness image.
NJ Tustison
image <- antsImageRead(getANTsRData("r16")) hessianObjectnessImage <- hessianObjectness(image)image <- antsImageRead(getANTsRData("r16")) hessianObjectnessImage <- hessianObjectness(image)
Computes and displays a histogram of the values of an image with the option for a mask.
## S3 method for class 'antsImage' hist(x, ..., mask)## S3 method for class 'antsImage' hist(x, ..., mask)
x |
Object of class |
... |
Arguments passed to |
mask |
object to subset the image. If missing, then all values of the image are plotted. |
Output of hist
img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 hist(img) hist(img, mask = mask)img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 hist(img) hist(img, mask = mask)
Histogram equalize image
histogramEqualizeImage(image, numberOfHistogramBins = 256)histogramEqualizeImage(image, numberOfHistogramBins = 256)
image |
image to undergo intensity transformation. |
numberOfHistogramBins |
number of histogram levels. |
equalized image.
NJ Tustison
image <- antsImageRead(getANTsRData("r16"), 2) eqImage <- histogramEqualizeImage(image)image <- antsImageRead(getANTsRData("r16"), 2) eqImage <- histogramEqualizeImage(image)
Match intensity profile with a reference image.
histogramMatchImage( sourceImage, referenceImage, numberOfHistogramBins = 255, numberOfMatchPoints = 64, useThresholdAtMeanIntensity = FALSE )histogramMatchImage( sourceImage, referenceImage, numberOfHistogramBins = 255, numberOfMatchPoints = 64, useThresholdAtMeanIntensity = FALSE )
sourceImage |
image to undergo intensity transformation. |
referenceImage |
image providing reference intensity profile. |
numberOfHistogramBins |
number of histogram levels. |
numberOfMatchPoints |
number of histogram match points. |
useThresholdAtMeanIntensity |
use a simple background exclusion criterion. |
source image intensity matched to reference image.
NJ Tustison
sourceImage <- antsImageRead(getANTsRData("r16"), 2) referenceImage <- antsImageRead(getANTsRData("r64"), 2) matchedImage <- histogramMatchImage(sourceImage, referenceImage)sourceImage <- antsImageRead(getANTsRData("r16"), 2) referenceImage <- antsImageRead(getANTsRData("r64"), 2) matchedImage <- histogramMatchImage(sourceImage, referenceImage)
Apply B-spline 1-D maps to an input image for intensity warping.
histogramMatchImage2( sourceImage, referenceImage, sourceMask = NULL, referenceMask = NULL, matchPoints = 64, transformDomainSize = 255 )histogramMatchImage2( sourceImage, referenceImage, sourceMask = NULL, referenceMask = NULL, matchPoints = 64, transformDomainSize = 255 )
sourceImage |
source image. |
referenceImage |
reference image. |
sourceMask |
source mask. |
referenceMask |
reference mask. |
matchPoints |
parametric points at which the intensity transform displacements are specified between [0, 1]. Alternatively, a single number can be given and the sequence is linearly spaced in [0, 1]. |
transformDomainSize |
Defines the sampling resolution of the B-spline warping. |
warped intensity image
Tustison NJ
library( ANTsR ) sourceImage <- antsImageRead(getANTsRData("r16"), 2) referenceImage <- antsImageRead(getANTsRData("r64"), 2) matchedImage <- histogramMatchImage2(sourceImage, referenceImage)library( ANTsR ) sourceImage <- antsImageRead(getANTsRData("r16"), 2) referenceImage <- antsImageRead(getANTsRData("r64"), 2) matchedImage <- histogramMatchImage2(sourceImage, referenceImage)
Apply B-spline 1-D maps to an input image for intensity warping.
histogramWarpImageIntensities( image, breakPoints = c(0.25, 0.5, 0.75), displacements = NULL, clampEndPoints = c(FALSE, FALSE), sdDisplacements = 0.05, transformDomainSize = 20 )histogramWarpImageIntensities( image, breakPoints = c(0.25, 0.5, 0.75), displacements = NULL, clampEndPoints = c(FALSE, FALSE), sdDisplacements = 0.05, transformDomainSize = 20 )
image |
input image. |
breakPoints |
parametric points at which the intensity transform displacements are specified between [0, 1]. Alternatively, a single number can be given and the sequence is linearly spaced in [0, 1]. |
displacements |
displacements to define intensity warping. Length
must be equal to the |
clampEndPoints |
specify non-zero intensity change at the ends of the histogram. |
sdDisplacements |
characterize the randomness of the intensity displacement. |
transformDomainSize |
Defines the sampling resolution of the B-spline warping. |
warped intensity image
Tustison NJ
library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) transformedImage <- histogramWarpImageIntensities( image, transformDomainSize = 10 ) rm(image); gc() rm(transformedImage); gc()library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) transformedImage <- histogramWarpImageIntensities( image, transformDomainSize = 10 ) rm(image); gc() rm(transformedImage); gc()
Humanize anatomical names by expanding abbreviations and reordering
humanize_anatomical_name(x)humanize_anatomical_name(x)
x |
character string |
humanized character string
bind two images along their edge
iBind(img1, img2, along = NA)iBind(img1, img2, along = NA)
img1 |
input object, an antsImage |
img2 |
second antsImage, same size as first |
along |
dimension to bind along |
BB Avants
fi <- antsImageRead(getANTsRData("r16"), 2) mi <- antsImageRead(getANTsRData("r62"), 2) bi <- iBind(fi, mi, 1) multismoo <- fi %>% iBind(smoothImage(fi, 2)) multismoo <- multismoo %>% iBind(smoothImage(fi, 4))fi <- antsImageRead(getANTsRData("r16"), 2) mi <- antsImageRead(getANTsRData("r62"), 2) bi <- iBind(fi, mi, 1) multismoo <- fi %>% iBind(smoothImage(fi, 2)) multismoo <- multismoo %>% iBind(smoothImage(fi, 4))
Icawhitens the input matrix using SVD and returns the result.
icawhiten(Xin, n.comp, verbose = FALSE)icawhiten(Xin, n.comp, verbose = FALSE)
Xin |
input matrix |
n.comp |
number of components on which to project |
verbose |
bool |
matrix is output
Avants BB, fastICA package (see CRAN)
mat <- matrix(c(rep(1, 100), rep(0, 200)), ncol = 50) wmat <- icawhiten(mat, 2)mat <- matrix(c(rep(1, 100), rep(0, 200)), ncol = 50) wmat <- icawhiten(mat, 2)
This function simplifies calculating p-values from linear models in which there is a similar formula that is applied many times with a change in image-based predictors. Image-based variables are stored in the input matrix list. They should be named consistently in the input formula and in the image list. If they are not, an error will be thrown. All input matrices should have the same number of rows and columns.
ilr(dataFrame, voxmats, myFormula)ilr(dataFrame, voxmats, myFormula)
dataFrame |
This data frame contains all relevant predictors except for the matrices associated with the image variables. |
voxmats |
The named list of matrices that contains the changing predictors. |
myFormula |
This is a character string that defines a valid regression formula. |
A list of different matrices that contain names derived from the formula and the coefficients of the regression model.
BB Avants.
set.seed(1500) nsub <- 100 outcome <- rnorm(nsub) covar <- rnorm(nsub) mat <- replicate(nsub, rnorm(nsub)) mat2 <- replicate(nsub, rnorm(nsub)) myform <- " outcome ~ covar + vox " df <- data.frame(outcome = outcome, covar = covar) result <- ilr(df, list(vox = mat), myform) print(names(result)) print(rownames(result$pValue)) myform <- " vox2 ~ covar + vox " df <- data.frame(outcome = outcome, covar = covar) result <- ilr(df, list(vox = mat, vox2 = mat2), myform) print(names(result)) print(rownames(result$pValue))set.seed(1500) nsub <- 100 outcome <- rnorm(nsub) covar <- rnorm(nsub) mat <- replicate(nsub, rnorm(nsub)) mat2 <- replicate(nsub, rnorm(nsub)) myform <- " outcome ~ covar + vox " df <- data.frame(outcome = outcome, covar = covar) result <- ilr(df, list(vox = mat), myform) print(names(result)) print(rownames(result$pValue)) myform <- " vox2 ~ covar + vox " df <- data.frame(outcome = outcome, covar = covar) result <- ilr(df, list(vox = mat, vox2 = mat2), myform) print(names(result)) print(rownames(result$pValue))
This function computes a prediction given ilr output.
ilr.predict(ilrResult, dataFrame, voxmats, myFormula)ilr.predict(ilrResult, dataFrame, voxmats, myFormula)
ilrResult |
This output form ilr |
dataFrame |
This data frame contains all relevant predictors except for the matrices associated with the image variables. |
voxmats |
The named list of matrices that contains the changing predictors. |
myFormula |
This is a character string that defines a valid regression formula. |
the predicted matrix.
BB Avants.
set.seed(1500) nsub <- 100 trte <- sample(1:nsub)[1:70] covarIn <- rnorm(nsub) mat <- replicate(nsub, rnorm(nsub)) mat2 <- replicate(nsub, rnorm(nsub)) outcomeAtVox <- mat[, 2] # also try myform = " vox ~ covar + vox2 " myform <- "outcome ~ covar + vox + vox2" df <- data.frame(outcome = outcomeAtVox, covar = covarIn) result <- ilr(df[trte, ], list(vox = mat[trte, ], vox2 = mat2[trte, ]), myform) df2 <- data.frame(covar = covarIn[-trte]) pred <- ilr.predict(result, df2, list(vox = mat[-trte, ], vox2 = mat2[-trte, ]), myform) max(cor(pred, outcomeAtVox[-trte]))set.seed(1500) nsub <- 100 trte <- sample(1:nsub)[1:70] covarIn <- rnorm(nsub) mat <- replicate(nsub, rnorm(nsub)) mat2 <- replicate(nsub, rnorm(nsub)) outcomeAtVox <- mat[, 2] # also try myform = " vox ~ covar + vox2 " myform <- "outcome ~ covar + vox + vox2" df <- data.frame(outcome = outcomeAtVox, covar = covarIn) result <- ilr(df[trte, ], list(vox = mat[trte, ], vox2 = mat2[trte, ]), myform) df2 <- data.frame(covar = covarIn[-trte]) pred <- ilr.predict(result, df2, list(vox = mat[-trte, ], vox2 = mat2[-trte, ]), myform) max(cor(pred, outcomeAtVox[-trte]))
Produces a unique image for each connected component 1 through N of size > minClusterSize
image2ClusterImages(x, minClusterSize = 50, minThresh = 1e-06, maxThresh = 1)image2ClusterImages(x, minClusterSize = 50, minThresh = 1e-06, maxThresh = 1)
x |
input antsImage e.g. a statistical map |
minClusterSize |
throw away clusters smaller than this value |
minThresh |
threshold to a statistical map |
maxThresh |
threshold to a statistical map |
the original image broken into a list of cluster images is the output
Avants BB
## Not run: img <- antsImageRead(getANTsRData("r16")) img <- thresholdImage(img, 1, Inf) imageclusterlist <- image2ClusterImages(img) ## End(Not run)## Not run: img <- antsImageRead(getANTsRData("r16")) img <- thresholdImage(img, 1, Inf) imageclusterlist <- image2ClusterImages(img) ## End(Not run)
Transform a d-dimensional image into a d by p matrix that encodes the spatial coordinates of the image domain.
imageDomainToSpatialMatrix(image, mask)imageDomainToSpatialMatrix(image, mask)
image |
input image |
mask |
optional input mask |
matrix is output
Avants BB
img <- antsImageRead(getANTsRData("r16")) spmat <- imageDomainToSpatialMatrix(img)img <- antsImageRead(getANTsRData("r16")) spmat <- imageDomainToSpatialMatrix(img)
ImageFileNames2ImageLists converts the input list of file names to a list containing antsImages.
imageFileNames2ImageList(x)imageFileNames2ImageList(x)
x |
input file name list |
a list containing the images this : mylist<-list( img1, img2 , etcetera ) is the
Avants BB, Kandel BM
dir <- paste(tempdir(), .Platform$file.sep, sep = "") img <- makeImage(c(4, 4)) for (ii in 1:6) { antsImageWrite(img, paste(dir, "image", ii, ".nii.gz", sep = "")) } imagenames <- list.files(dir, glob2rx("*.nii.gz"), full.names = TRUE) images <- imageFileNames2ImageList(imagenames)dir <- paste(tempdir(), .Platform$file.sep, sep = "") img <- makeImage(c(4, 4)) for (ii in 1:6) { antsImageWrite(img, paste(dir, "image", ii, ".nii.gz", sep = "")) } imagenames <- list.files(dir, glob2rx("*.nii.gz"), full.names = TRUE) images <- imageFileNames2ImageList(imagenames)
Read images into rows of a matrix.
imageListToMatrix( imageList, mask, sigma = NA, epsilon = 0, asymmetryTx = NULL, asymmetryMask = NULL )imageListToMatrix( imageList, mask, sigma = NA, epsilon = 0, asymmetryTx = NULL, asymmetryMask = NULL )
imageList |
A character vector containing a list of image files to read, in order - these are image objects, not file names. these are assumed to be in a normalized space i.e. they are all in registration. |
mask |
An |
sigma |
smoothing operation in physical space. See |
epsilon |
threshold value determining what is included in the mask |
asymmetryTx |
a reflection transform |
asymmetryMask |
a mask defining left and right side of the image. this should be defined in the space of the images within the imageList. |
A matrix containing the masked data, the result of calling
as.numeric(image, mask) on each input image.
Cook PA, Avants B, Kandel BM
img <- ri(1) %>% resampleImage(c(32, 32)) imglist <- list() nsubj <- 3 for (ii in 1:nsubj) { imglist[[ii]] <- img } mask <- getMask(img) imgmat <- imageListToMatrix(imglist, mask)img <- ri(1) %>% resampleImage(c(32, 32)) imglist <- list() nsubj <- 3 for (ii in 1:nsubj) { imglist[[ii]] <- img } mask <- getMask(img) imgmat <- imageListToMatrix(imglist, mask)
measure similarity between two images
imageSimilarity( fixed, moving, type = c("MeanSquares", "MattesMutualInformation", "ANTSNeighborhoodCorrelation", "Correlation", "Demons", "JointHistogramMutualInformation"), fixed.mask = NULL, moving.mask = NULL, sampling.strategy = "none", sampling.percentage = 1, nBins = 32, radius = 3 )imageSimilarity( fixed, moving, type = c("MeanSquares", "MattesMutualInformation", "ANTSNeighborhoodCorrelation", "Correlation", "Demons", "JointHistogramMutualInformation"), fixed.mask = NULL, moving.mask = NULL, sampling.strategy = "none", sampling.percentage = 1, nBins = 32, radius = 3 )
fixed |
the fixed antsImage |
moving |
the moving antsImage |
type |
image metric to calculate
|
fixed.mask |
mask for the fixed image |
moving.mask |
mask for the moving image |
sampling.strategy |
sampling strategy, default if full sampling
|
sampling.percentage |
percentage of data to sample when calculating metric |
nBins |
the number of bins for histogram metrics |
radius |
neighborhood radius of ANTSNeighborhoodCorrelation |
value of image to image metric
x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- imageSimilarity(x, y, type = "MeanSquares")x <- antsImageRead(getANTsRData("r16")) y <- antsImageRead(getANTsRData("r30")) metric <- imageSimilarity(x, y, type = "MeanSquares")
Read images into rows of a matrix, given a mask - much faster for large datasets as it is based on C++ implementations.
imagesToMatrix(imageList, mask)imagesToMatrix(imageList, mask)
imageList |
A character vector containing a list of image files to read, in order. |
mask |
An |
A matrix containing the masked data, the result of calling
as.numeric(image, mask) on each input image.
Cook PA, Avants BB (C++ version)
# make some simulated images and convert them to a matrix n <- 2 tdir <- tempdir() for (i in 1:n) { simimg <- as.antsImage(replicate(64, rnorm(64))) antsImageWrite(simimg, tempfile(fileext = ".mha")) } imageList <- list.files(tdir, pattern = ".mha", full.names = TRUE) mask <- getMask(antsImageRead(imageList[1])) mat <- imagesToMatrix(imageList, mask) print(dim(mat))# make some simulated images and convert them to a matrix n <- 2 tdir <- tempdir() for (i in 1:n) { simimg <- as.antsImage(replicate(64, rnorm(64))) antsImageWrite(simimg, tempfile(fileext = ".mha")) } imageList <- list.files(tdir, pattern = ".mha", full.names = TRUE) mask <- getMask(antsImageRead(imageList[1])) mat <- imagesToMatrix(imageList, mask) print(dim(mat))
Perform various (often mathematical) operations on the input image/s. Additional parameters should be specific for each operation. See the the full iMath in ANTs, on which this function is based.
iMath(img, operation, param = NULL, ...)iMath(img, operation, param = NULL, ...)
img |
input object, usually antsImage |
operation |
a character string e.g. "GetLargestComponent" ... the special case of "GetOperations" or "GetOperationsFull" will return a list of operations and brief description. Some operations may not be valid (WIP), but most are. |
param |
... additional parameters |
... |
further parameter options |
JT Duda
fi <- antsImageRead(getANTsRData("r16"), 2) mask <- getMask(fi) op1 <- iMath(fi, "GD", 1) # gray matter dilation by 1 voxel op2 <- iMath(mask, "D") # distance transform op3 <- iMath(0, "GetOperations") # list all ops if (usePkg("magrittr")) { # string ops together lapgd <- fi %>% iMath("Laplacian", 1) %>% iMath("GD", 3) } # Canny is useful e.g. # canny = ( iMath(myreg$warpedmovout,"Normalize")*255 ) %>% iMath("Canny",1,5,12) tf <- getANTsRData("r27") tem <- antsImageRead(tf) mask <- tem > 20 fh <- iMath(mask, "FillHoles") # list all ops stopifnot(range(fh) == c(0, 1)) filled <- fh > 0fi <- antsImageRead(getANTsRData("r16"), 2) mask <- getMask(fi) op1 <- iMath(fi, "GD", 1) # gray matter dilation by 1 voxel op2 <- iMath(mask, "D") # distance transform op3 <- iMath(0, "GetOperations") # list all ops if (usePkg("magrittr")) { # string ops together lapgd <- fi %>% iMath("Laplacian", 1) %>% iMath("GD", 3) } # Canny is useful e.g. # canny = ( iMath(myreg$warpedmovout,"Normalize")*255 ) %>% iMath("Canny",1,5,12) tf <- getANTsRData("r27") tem <- antsImageRead(tf) mask <- tem > 20 fh <- iMath(mask, "FillHoles") # list all ops stopifnot(range(fh) == c(0, 1)) filled <- fh > 0
Examples, description and categorization of iMath operations.
A data frame listing the following variables.
OperationName of operation
OperationTypeEnumerated type of the operation (filter, etc)
Parametersdescriptive parameters
Exampleworking example code
Descriptionfree text description
OutputDimensionalityChangeNA if not image, otherwise increment to output image dimensionality relative to input image
data(iMathOps) i <- antsImageRead(getANTsRData("r16"), 2) roiImg <- getMask(i) roiImg2 <- iMath(roiImg, "ME", 25) if (sum(roiImg == 1) == sum(roiImg2 == 1)) stop("erosion failure") roiImg2 <- iMath(roiImg, "MD", 25) if (sum(roiImg == 1) == sum(roiImg2 == 1)) stop("dilation failure") for (j in c(1:nrow(iMathOps))) { op <- as.character(iMathOps$Operation[j]) }data(iMathOps) i <- antsImageRead(getANTsRData("r16"), 2) roiImg <- getMask(i) roiImg2 <- iMath(roiImg, "ME", 25) if (sum(roiImg == 1) == sum(roiImg2 == 1)) stop("erosion failure") roiImg2 <- iMath(roiImg, "MD", 25) if (sum(roiImg == 1) == sum(roiImg2 == 1)) stop("dilation failure") for (j in c(1:nrow(iMathOps))) { op <- as.character(iMathOps$Operation[j]) }
This function runs the optimization on both the input matrix 'm' and its negative counterpart 'm * (-1)', returning the result that maximizes the sum 'sum(m * I)'.
indicator_opt_both_ways(m, verbose = FALSE)indicator_opt_both_ways(m, verbose = FALSE)
m |
A numeric matrix for which the optimization will be performed. |
verbose |
Logical. If TRUE, reports the objective value and convergence progress at each iteration. |
m*I
set.seed(123) m <- matrix(rnorm(500), nrow = 5) indicator_opt_both_ways(m)set.seed(123) m <- matrix(rnorm(500), nrow = 5) indicator_opt_both_ways(m)
InitializeEigenanatomy is a helper function to initialize sparseDecom and sparseDecom2. Can be used to estimate sparseness parameters per eigenvector. The user then only chooses nvecs and optional regularization parameters.
initializeEigenanatomy(initmat, mask = NULL, nreps = 1, smoothing = 0)initializeEigenanatomy(initmat, mask = NULL, nreps = 1, smoothing = 0)
initmat |
input matrix where rows provide initial vector values. alternatively, this can be an antsImage which contains labeled regions. |
mask |
mask if available |
nreps |
nrepetitions to use |
smoothing |
if using an initial label image, optionally smooth each roi |
list is output
Avants BB
mat <- t(replicate(3, rnorm(100))) initdf <- initializeEigenanatomy(mat) # produces a mask dmat <- replicate(100, rnorm(20)) # data matrix svdv <- t(svd(mat, nu = 0, nv = 10)$v) ilist <- matrixToImages(svdv, initdf$mask) eseg <- eigSeg(initdf$mask, ilist, TRUE) eanat <- sparseDecom(dmat, inmask = initdf$mask, sparseness = 0, smooth = 0, initializationList = ilist, cthresh = 0, nvecs = length(ilist) ) initdf2 <- initializeEigenanatomy(mat, nreps = 2) eanat <- sparseDecom(dmat, inmask = initdf$mask, sparseness = 0, smooth = 0, z = -0.5, initializationList = initdf2$initlist, cthresh = 0, nvecs = length(initdf2$initlist) ) # now a regression eanatMatrix <- eanat$eigenanatomyimages # 'averages' loosely speaking anyway myEigenanatomyRegionAverages <- dmat %*% t(eanatMatrix) dependentvariable <- rnorm(nrow(dmat)) res <- summary(lm(dependentvariable ~ myEigenanatomyRegionAverages)) nvox <- 1000 dmat <- replicate(nvox, rnorm(20)) dmat2 <- replicate(30, rnorm(20)) mat <- t(replicate(3, rnorm(nvox))) initdf <- initializeEigenanatomy(mat) eanat <- sparseDecom2( inmatrix = list(dmat, dmat2), inmask = list(initdf$mask, NA), sparseness = c(-0.1, -0.2), smooth = 0, initializationList = initdf$initlist, cthresh = c(0, 0), nvecs = length(initdf$initlist), priorWeight = 0.1 )mat <- t(replicate(3, rnorm(100))) initdf <- initializeEigenanatomy(mat) # produces a mask dmat <- replicate(100, rnorm(20)) # data matrix svdv <- t(svd(mat, nu = 0, nv = 10)$v) ilist <- matrixToImages(svdv, initdf$mask) eseg <- eigSeg(initdf$mask, ilist, TRUE) eanat <- sparseDecom(dmat, inmask = initdf$mask, sparseness = 0, smooth = 0, initializationList = ilist, cthresh = 0, nvecs = length(ilist) ) initdf2 <- initializeEigenanatomy(mat, nreps = 2) eanat <- sparseDecom(dmat, inmask = initdf$mask, sparseness = 0, smooth = 0, z = -0.5, initializationList = initdf2$initlist, cthresh = 0, nvecs = length(initdf2$initlist) ) # now a regression eanatMatrix <- eanat$eigenanatomyimages # 'averages' loosely speaking anyway myEigenanatomyRegionAverages <- dmat %*% t(eanatMatrix) dependentvariable <- rnorm(nrow(dmat)) res <- summary(lm(dependentvariable ~ myEigenanatomyRegionAverages)) nvox <- 1000 dmat <- replicate(nvox, rnorm(20)) dmat2 <- replicate(30, rnorm(20)) mat <- t(replicate(3, rnorm(nvox))) initdf <- initializeEigenanatomy(mat) eanat <- sparseDecom2( inmatrix = list(dmat, dmat2), inmask = list(initdf$mask, NA), sparseness = c(-0.1, -0.2), smooth = 0, initializationList = initdf$initlist, cthresh = c(0, 0), nvecs = length(initdf$initlist), priorWeight = 0.1 )
Four initialization approaches for simlr. Returns either a single matrix
derived from dimensionality reduction on all matrices bound together
(jointReduction=TRUE) or a list of reduced
dimensionality matrices, one for each input. Primarily, a helper function
for SiMLR.
initializeSimlr( voxmats, k, jointReduction = FALSE, zeroUpper = FALSE, uAlgorithm = "ba_svd", addNoise = 0 )initializeSimlr( voxmats, k, jointReduction = FALSE, zeroUpper = FALSE, uAlgorithm = "ba_svd", addNoise = 0 )
voxmats |
list that contains the named matrices. |
k |
rank of U matrix |
jointReduction |
boolean determining whether one or length of list bases are returned. |
zeroUpper |
boolean determining whether upper triangular part of initialization is zeroed out |
uAlgorithm |
either |
addNoise |
scalar value that adds zero mean unit variance noise, multiplied
by the value of |
A single matrix or list of matrices
BB Avants.
set.seed(1500) nsub <- 3 npix <- c(10, 6, 13) nk <- 2 outcome <- initializeSimlr( list( matrix(rnorm(nsub * npix[1]), ncol = npix[1]), matrix(rnorm(nsub * npix[2]), ncol = npix[2]), matrix(rnorm(nsub * npix[3]), ncol = npix[3]) ), k = 2, uAlgorithm = "pca" )set.seed(1500) nsub <- 3 npix <- c(10, 6, 13) nk <- 2 outcome <- initializeSimlr( list( matrix(rnorm(nsub * npix[1]), ncol = npix[1]), matrix(rnorm(nsub * npix[2]), ncol = npix[2]), matrix(rnorm(nsub * npix[3]), ncol = npix[3]) ), k = 2, uAlgorithm = "pca" )
Utility function to integrate a vector field and create a deformation field.
integrateVectorField( referenceImage, vectorFieldFileName, deformationFieldFileName, lowerTime = 0, upperTime = 1, deltaTime = 0.01 )integrateVectorField( referenceImage, vectorFieldFileName, deformationFieldFileName, lowerTime = 0, upperTime = 1, deltaTime = 0.01 )
referenceImage |
defines the image domain |
vectorFieldFileName |
the vector field exists on disk. |
deformationFieldFileName |
the deformation field output file name. |
lowerTime |
the starting time, usually zero for forward transformation and one for the inverse transformation. |
upperTime |
the ending time, usually one for forward transformation and zero for the inverse transformation. |
deltaTime |
the integration time step |
Avants BB
## Not run: set.seed(1234) fi <- (ri(1)) mi <- (ri(2)) mytx2 <- antsRegistration(fixed = fi, mi, typeofTransform = "SyN") integrateVectorField(fi, mytx2$velocityfield, "/tmp/def.nii.gz") ## End(Not run)## Not run: set.seed(1234) fi <- (ri(1)) mi <- (ri(2)) mytx2 <- antsRegistration(fixed = fi, mi, typeofTransform = "SyN") integrateVectorField(fi, mytx2$velocityfield, "/tmp/def.nii.gz") ## End(Not run)
Integrate velocity field
integrateVelocityField( velocityField, lowerIntegrationBound = 0, upperIntegrationBound = 1, numberOfIntegrationSteps = 10 )integrateVelocityField( velocityField, lowerIntegrationBound = 0, upperIntegrationBound = 1, numberOfIntegrationSteps = 10 )
velocityField |
time-varying displacement field |
lowerIntegrationBound |
Lower time bound for integration in [0, 1] |
upperIntegrationBound |
Upper time bound for integration in [0, 1] |
numberOfIntegrationSteps |
Number of integration steps used in the Runge-Kutta solution |
integrated field
NJ Tustison
fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r27")) reg <- antsRegistration(fi, mi, "TV[2]") velocityField <- antsImageRead(reg$velocityfield) field <- integrateVelocityField(velocityField, 0.0, 1.0, 10)fi <- antsImageRead(getANTsRData("r16")) mi <- antsImageRead(getANTsRData("r27")) reg <- antsRegistration(fi, mi, "TV[2]") velocityField <- antsImageRead(reg$velocityfield) field <- integrateVelocityField(velocityField, 0.0, 1.0, 10)
Replicate columns of input matrix n times as neighbors of columns in original matrix.
interleaveMatrixWithItself(x, n = 1)interleaveMatrixWithItself(x, n = 1)
x |
input matrix |
n |
number of interleaves |
matrix is output
Avants BB
mat <- replicate(100, rnorm(20)) wmat <- interleaveMatrixWithItself(mat, 5)mat <- replicate(100, rnorm(20)) wmat <- interleaveMatrixWithItself(mat, 5)
This function interprets a vector from SiMLR (similarity-driven multivariate linear reconstruction) specifically focusing on a given variable (e.g., a specific principal component or cluster). It extracts and normalizes the vector associated with the specified SiMLR variable, sorts it to identify the top elements, and optionally filters out non-significant values. This function is useful for understanding the contribution of different features in the context of the SiMLR analysis.
interpret_simlr_vector( simlrResult, simlrMats, simlrVariable, n2show = 5, shortnames = TRUE, return_dataframe = FALSE )interpret_simlr_vector( simlrResult, simlrMats, simlrVariable, n2show = 5, shortnames = TRUE, return_dataframe = FALSE )
simlrResult |
A list containing SiMLR analysis results, which should include a matrix 'v' representing vectors of interest (e.g., principal components). |
simlrMats |
A list of matrices associated with SiMLR analysis, where each matrix corresponds to a different modality or data type analyzed by SiMLR. |
simlrVariable |
A string specifying the variable within 'simlrResult' to interpret. The variable name should include both an identifier (e.g., "PC" for principal component) and a numeric index. |
n2show |
An integer specifying the number of top elements to show from the sorted, normalized vector. Defaults to 5. If 'NULL' or greater than the length of the vector, all elements are shown. |
shortnames |
boolean |
return_dataframe |
boolean |
A named vector of the top 'n2show' elements (or all if 'n2show' is 'NULL' or too large), sorted in decreasing order of their absolute values. Elements are named according to their identifiers in 'simlrMats' and filtered to exclude non-significant values (absolute value > 0).
# This example assumes you have SiMLR result `simlrResult`, matrices `simlrMats`, and you want to # interpret the first principal component "PC1". # simlrResult <- list(v = list(PC = matrix(runif(20), ncol = 2))) # simlrMats <- list(PC = matrix(runif(100), ncol = 10)) # simlrVariable <- "PC1" # interpretedVector <- interpret_simlr_vector(simlrResult, simlrMats, simlrVariable) # print(interpretedVector)# This example assumes you have SiMLR result `simlrResult`, matrices `simlrMats`, and you want to # interpret the first principal component "PC1". # simlrResult <- list(v = list(PC = matrix(runif(20), ncol = 2))) # simlrMats <- list(PC = matrix(runif(100), ncol = 10)) # simlrVariable <- "PC1" # interpretedVector <- interpret_simlr_vector(simlrResult, simlrMats, simlrVariable) # print(interpretedVector)
This function interprets a vector from SiMLR (similarity-driven multivariate linear reconstruction) specifically focusing on a given variable (e.g., a specific principal component or cluster). It extracts and normalizes the vector associated with the specified SiMLR variable, sorts it to identify the top elements, and optionally filters out non-significant values. This function is useful for understanding the contribution of different features in the context of the SiMLR analysis. Assumes this input is generated by NNHEmbed.
interpret_simlr_vector2( simlrResult, simlrVariable, n2show = 5, shortnames = TRUE, return_dataframe = FALSE )interpret_simlr_vector2( simlrResult, simlrVariable, n2show = 5, shortnames = TRUE, return_dataframe = FALSE )
simlrResult |
a specific v matrix out of SiMLR |
simlrVariable |
A string specifying the variable within 'simlrResult' to interpret. The variable name should include both an identifier (e.g., "PC" for principal component) and a numeric index. |
n2show |
An integer specifying the number of top elements to show from the sorted, normalized vector. Defaults to 5. If 'NULL' or greater than the length of the vector, all elements are shown. |
shortnames |
boolean |
return_dataframe |
boolean |
A named vector of the top 'n2show' elements (or all if 'n2show' is 'NULL' or too large), sorted in decreasing order of their absolute values. Elements are named according to their identifiers in 'simlrMats' and filtered to exclude non-significant values (absolute value > 0).
# This example assumes you have SiMLR result `simlrResult`, matrices `simlrMats`, and you want to # interpret the first principal component "PC1". # simlrResult <- list(v = list(PC = matrix(runif(20), ncol = 2))) # simlrMats <- list(PC = matrix(runif(100), ncol = 10)) # simlrVariable <- "PC1" # interpretedVector <- interpret_simlr_vector2(simlrResult$v[[1]] ) # print(interpretedVector)# This example assumes you have SiMLR result `simlrResult`, matrices `simlrMats`, and you want to # interpret the first principal component "PC1". # simlrResult <- list(v = list(PC = matrix(runif(20), ncol = 2))) # simlrMats <- list(PC = matrix(runif(100), ncol = 10)) # simlrVariable <- "PC1" # interpretedVector <- interpret_simlr_vector2(simlrResult$v[[1]] ) # print(interpretedVector)
Computes the inverse square root of a symmetric positive semi-definite matrix using eigen-decomposition.
inv_sqrt_sym(M, epsilon = 1e-10)inv_sqrt_sym(M, epsilon = 1e-10)
M |
Numeric symmetric matrix (k x k). |
epsilon |
Small numeric value for numerical stability (default 1e-10). |
For a symmetric matrix M, computes via eigen-decomposition, clipping eigenvalues
below 1e-12 to ensure numerical stability. Used in polar and soft retractions for NSA-Flow.
Numeric matrix, the inverse square root of M.
M <- matrix(c(4, 1, 1, 2), 2, 2) inv_sqrt_sym(M)M <- matrix(c(4, 1, 1, 2), 2, 2) inv_sqrt_sym(M)
Inverse square root of a symmetric matrix via Newton-Schulz
inv_sqrt_sym_newton( A, epsilon = 1e-10, max_iter = 10L, tol = 1e-06, verbose = FALSE )inv_sqrt_sym_newton( A, epsilon = 1e-10, max_iter = 10L, tol = 1e-06, verbose = FALSE )
A |
symmetric matrix |
epsilon |
small value for stability |
max_iter |
maximum number of iterations |
tol |
tolerance for convergence |
verbose |
boolean for verbosity |
Calculate the invariant orthogonality defect
invariant_orthogonality_defect(A)invariant_orthogonality_defect(A)
A |
input matrix |
invert a linear antsrTransform
invertAntsrTransform(transform)invertAntsrTransform(transform)
transform |
trasform to invert |
antsrTransform
img <- antsImageRead(getANTsRData("r16")) tx <- new("antsrTransform", precision = "float", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0, -1, 1, 0, dim(img)[1], 0)) txinv <- invertAntsrTransform(tx)img <- antsImageRead(getANTsRData("r16")) tx <- new("antsrTransform", precision = "float", type = "AffineTransform", dimension = 2) setAntsrTransformParameters(tx, c(0, -1, 1, 0, dim(img)[1], 0)) txinv <- invertAntsrTransform(tx)
Invert displacement field.
invertDisplacementField( displacementField, inverseFieldInitialEstimate, maximumNumberOfIterations = 20, meanErrorToleranceThreshold = 0.001, maxErrorToleranceThreshold = 0.1, enforceBoundaryCondition = TRUE )invertDisplacementField( displacementField, inverseFieldInitialEstimate, maximumNumberOfIterations = 20, meanErrorToleranceThreshold = 0.001, maxErrorToleranceThreshold = 0.1, enforceBoundaryCondition = TRUE )
displacementField |
displacement field. |
inverseFieldInitialEstimate |
initial guess. |
maximumNumberOfIterations |
number of iterations. |
meanErrorToleranceThreshold |
mean error tolerance threshold. |
maxErrorToleranceThreshold |
max error tolerance threshold. |
enforceBoundaryCondition |
enforce stationary boundary condition. |
inverse displacement field
NJ Tustison
Tests if object is antsImage
is.antsImage(x)is.antsImage(x)
x |
An object |
TRUE if object is antsImage; FALSE otherwise.
is.antsImage(antsImageRead(getANTsRData("r16"), 2))is.antsImage(antsImageRead(getANTsRData("r16"), 2))
A data frame label numbers and names for the JHU FA white matter labels.
jhu_fa_labelsjhu_fa_labels
A data frame with columns: Label, Description.
A data frame label numbers and names for the JHU MD white matter labels.
jhu_md_labelsjhu_md_labels
A data frame with columns: Label, Description.
The JLF initialization is reused throughout a time series with an additional lag argument.
jlfProp( targetI, targetIMask, atlasList, rad = 2, labelList = NULL, rSearch = 3, lagValue = 3, verbose = FALSE, ... )jlfProp( targetI, targetIMask, atlasList, rad = 2, labelList = NULL, rSearch = 3, lagValue = 3, verbose = FALSE, ... )
targetI |
antsImage list to be approximated |
targetIMask |
mask with value 1 |
atlasList |
list containing antsImages with intensity images |
rad |
neighborhood radius, default to 2 |
labelList |
optional list containing antsImages with segmentation labels |
rSearch |
radius of search, default is 3 |
lagValue |
number of prior images to use to fwd propagate JLF solution |
verbose |
boolean |
... |
arguments to pass to |
segmentation of time series
Brian B. Avants
## Not run: set.seed(123) ref <- ri(1) %>% resampleImage(4) %>% iMath("Normalize") mi1 <- ri(2) mi2 <- ri(3) mi3 <- ri(4) mi4 <- ri(5) mi5 <- ri(6) refmask <- getMask(ref) refmask <- iMath(refmask, "MD", 10) # just to speed things up ilist <- list(mi1, mi2, mi3, mi4, mi5) seglist <- list() for (i in 1:length(ilist)) { ilist[[i]] <- iMath(ilist[[i]], "Normalize") mytx <- antsRegistration( fixed = ref, moving = ilist[[i]], typeofTransform = c("Affine"), verbose = TRUE ) mywarpedimage <- antsApplyTransforms( fixed = ref, moving = ilist[[i]], transformlist = mytx$fwdtransforms ) ilist[[i]] <- mywarpedimage seg <- thresholdImage(ilist[[i]], "Otsu", 3) seglist[[i]] <- seg + 1 } tarlist <- list( iMath(ref, "GD", 3), iMath(ref, "GD", 2), iMath(ref, "GD", 1), iMath(ref, "GD", 0), iMath(ref, "GE", 1), iMath(ref, "GE", 2), iMath(ref, "GE", 3) ) pp <- jlfProp(tarlist, refmask, ilist, rSearch = 2, labelList = seglist, rad = rep(2, length(dim(ref))) ) ## End(Not run)## Not run: set.seed(123) ref <- ri(1) %>% resampleImage(4) %>% iMath("Normalize") mi1 <- ri(2) mi2 <- ri(3) mi3 <- ri(4) mi4 <- ri(5) mi5 <- ri(6) refmask <- getMask(ref) refmask <- iMath(refmask, "MD", 10) # just to speed things up ilist <- list(mi1, mi2, mi3, mi4, mi5) seglist <- list() for (i in 1:length(ilist)) { ilist[[i]] <- iMath(ilist[[i]], "Normalize") mytx <- antsRegistration( fixed = ref, moving = ilist[[i]], typeofTransform = c("Affine"), verbose = TRUE ) mywarpedimage <- antsApplyTransforms( fixed = ref, moving = ilist[[i]], transformlist = mytx$fwdtransforms ) ilist[[i]] <- mywarpedimage seg <- thresholdImage(ilist[[i]], "Otsu", 3) seglist[[i]] <- seg + 1 } tarlist <- list( iMath(ref, "GD", 3), iMath(ref, "GD", 2), iMath(ref, "GD", 1), iMath(ref, "GD", 0), iMath(ref, "GE", 1), iMath(ref, "GE", 2), iMath(ref, "GE", 3) ) pp <- jlfProp(tarlist, refmask, ilist, rSearch = 2, labelList = seglist, rad = rep(2, length(dim(ref))) ) ## End(Not run)
joinEigenanatomy joins the input matrix using a community membership approach.
joinEigenanatomy( datamatrix, mask = NULL, listEanatImages, graphdensity = 0.65, joinMethod = "walktrap", verbose = F )joinEigenanatomy( datamatrix, mask = NULL, listEanatImages, graphdensity = 0.65, joinMethod = "walktrap", verbose = F )
datamatrix |
input matrix before decomposition |
mask |
mask used to create datamatrix |
listEanatImages |
list containing pointers to eanat images |
graphdensity |
target graph density or densities to search over |
joinMethod |
see igraph's community detection |
verbose |
bool |
return(list(fusedlist = newelist, fusedproj = myproj, memberships = communitymembership , graph=gg, bestdensity=graphdensity ))
Avants BB
## Not run: # if you dont have images mat <- replicate(100, rnorm(20)) mydecom <- sparseDecom(mat) kk <- joinEigenanatomy(mat, mask = NULL, mydecom$eigenanatomyimages, 0.1) # or select optimal parameter from a list kk <- joinEigenanatomy(mat, mask = NULL, mydecom$eigenanatomyimages, c(1:10) / 50) # something similar may be done with images mask <- as.antsImage(t(as.matrix(array(rep(1, ncol(mat)), ncol(mat))))) mydecom <- sparseDecom(mat, inmask = mask) eanatimages <- matrixToImages(mydecom$eigenanatomyimages, mask) kki <- joinEigenanatomy(mat, mask = mask, eanatimages, 0.1) if (usePkg("igraph")) { mydecomf <- sparseDecom(mat, inmask = mask, initializationList = kki$fusedlist, sparseness = 0, nvecs = length(kki$fusedlist) ) } ## End(Not run)## Not run: # if you dont have images mat <- replicate(100, rnorm(20)) mydecom <- sparseDecom(mat) kk <- joinEigenanatomy(mat, mask = NULL, mydecom$eigenanatomyimages, 0.1) # or select optimal parameter from a list kk <- joinEigenanatomy(mat, mask = NULL, mydecom$eigenanatomyimages, c(1:10) / 50) # something similar may be done with images mask <- as.antsImage(t(as.matrix(array(rep(1, ncol(mat)), ncol(mat))))) mydecom <- sparseDecom(mat, inmask = mask) eanatimages <- matrixToImages(mydecom$eigenanatomyimages, mask) kki <- joinEigenanatomy(mat, mask = mask, eanatimages, 0.1) if (usePkg("igraph")) { mydecomf <- sparseDecom(mat, inmask = mask, initializationList = kki$fusedlist, sparseness = 0, nvecs = length(kki$fusedlist) ) } ## End(Not run)
A multiple atlas voting scheme to customize labels for a new subject. This
function will also perform intensity fusion. It almost directly calls the
C++ in the ANTs executable so is much faster than other variants in ANTsR.
One may want to normalize image intensities for each input image before
passing to this function. If no labels are passed, we do intensity fusion.
Note on computation time: the underlying C++
is multithreaded. You can control the number of threads by setting the
environment variable ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS e.g. to use all or
some of your CPUs. This will improve performance substantially. For instance,
on a macbook pro from 2015, 8 cores improves speed by about 4x.
jointLabelFusion( targetI, targetIMask, atlasList, beta = 4, rad = 2, labelList = NULL, rho = 0.01, usecor = FALSE, rSearch = 3, nonnegative = FALSE, maxLabelPlusOne = FALSE, noZeroes = FALSE, verbose = FALSE )jointLabelFusion( targetI, targetIMask, atlasList, beta = 4, rad = 2, labelList = NULL, rho = 0.01, usecor = FALSE, rSearch = 3, nonnegative = FALSE, maxLabelPlusOne = FALSE, noZeroes = FALSE, verbose = FALSE )
targetI |
antsImage to be approximated |
targetIMask |
mask with value 1 |
atlasList |
list containing antsImages with intensity images |
beta |
weight sharpness, default to 2 |
rad |
neighborhood radius, default to 2 |
labelList |
optional list containing antsImages with segmentation labels |
rho |
ridge penalty increases robustness to outliers but also makes image converge to average |
usecor |
employ correlation as local similarity |
rSearch |
radius of search, default is 3 |
nonnegative |
constrain weights to be non-negative |
maxLabelPlusOne |
boolean this will add max label plus one to the non-zero parts of each label where the target mask is greater than one. NOTE: this will have a side effect of adding to the original label images that are passed to the program. It also guarantees that every position in the labels have some label, rather than none. Ie it guarantees to explicitly parcellate the input data. |
noZeroes |
boolean will zero out target mask regions that have any zero label. this prevents JLF from computing a solution in regions not covered by the initial library. |
verbose |
boolean |
approximated image, segmentation and probabilities
Brian B. Avants, Hongzhi Wang, Paul Yushkevich, Nicholas J. Tustison
set.seed(123) ref <- ri(1) ref <- resampleImage(ref, c(50, 50), 1, 0) ref <- iMath(ref, "Normalize") mi <- ri(2) mi2 <- ri(3) mi3 <- ri(4) mi4 <- ri(5) mi5 <- ri(6) refmask <- getMask(ref) refmask <- iMath(refmask, "ME", 2) # just to speed things up ilist <- list(mi, mi2, mi3, mi4, mi5) seglist <- list() for (i in 1:length(ilist)) { ilist[[i]] <- iMath(ilist[[i]], "Normalize") mytx <- antsRegistration( fixed = ref, moving = ilist[[i]], typeofTransform = c("Affine"), verbose = TRUE ) mywarpedimage <- antsApplyTransforms( fixed = ref, moving = ilist[[i]], transformlist = mytx$fwdtransforms ) ilist[[i]] <- mywarpedimage seg <- thresholdImage(ilist[[i]], "Otsu", 3) seglist[[i]] <- seg } r <- 2 pp <- jointLabelFusion(ref, refmask, ilist, rSearch = 2, labelList = seglist, rad = rep(r, length(dim(ref))) ) pp2 <- jointLabelFusion(ref, refmask, ilist, rSearch = 2, labelList = seglist, rad = rep(r, length(dim(ref))) ) testthat::expect_equal(pp2$segmentation, pp$segmentation) pp <- jointLabelFusion(ref, refmask, ilist, rSearch = 2, rad = rep(r, length(dim(ref))) ) ## Not run: ref <- antsImageRead(getANTsRData("ch2")) n <- 50 ref <- resampleImage(ref, c(n, n, n), 1, 0) ref <- iMath(ref, "Normalize") refmask <- getMask(ref) ilist <- list() seglist <- list() for (k in 1:5) { mi <- antsImageClone(ref) + rnorm(n^3, 0, 0.1) mykseg <- kmeansSegmentation(mi, 3, refmask)$segmentation ilist[[k]] <- mi seglist[[k]] <- mykseg } pp <- jointLabelFusion(ref, refmask, ilist, rSearch = 2, labelList = seglist, rad = rep(2, length(dim(ref))), verbose = TRUE ) plot(ref, pp$segmentation) plot(pp$intensity) ## End(Not run)set.seed(123) ref <- ri(1) ref <- resampleImage(ref, c(50, 50), 1, 0) ref <- iMath(ref, "Normalize") mi <- ri(2) mi2 <- ri(3) mi3 <- ri(4) mi4 <- ri(5) mi5 <- ri(6) refmask <- getMask(ref) refmask <- iMath(refmask, "ME", 2) # just to speed things up ilist <- list(mi, mi2, mi3, mi4, mi5) seglist <- list() for (i in 1:length(ilist)) { ilist[[i]] <- iMath(ilist[[i]], "Normalize") mytx <- antsRegistration( fixed = ref, moving = ilist[[i]], typeofTransform = c("Affine"), verbose = TRUE ) mywarpedimage <- antsApplyTransforms( fixed = ref, moving = ilist[[i]], transformlist = mytx$fwdtransforms ) ilist[[i]] <- mywarpedimage seg <- thresholdImage(ilist[[i]], "Otsu", 3) seglist[[i]] <- seg } r <- 2 pp <- jointLabelFusion(ref, refmask, ilist, rSearch = 2, labelList = seglist, rad = rep(r, length(dim(ref))) ) pp2 <- jointLabelFusion(ref, refmask, ilist, rSearch = 2, labelList = seglist, rad = rep(r, length(dim(ref))) ) testthat::expect_equal(pp2$segmentation, pp$segmentation) pp <- jointLabelFusion(ref, refmask, ilist, rSearch = 2, rad = rep(r, length(dim(ref))) ) ## Not run: ref <- antsImageRead(getANTsRData("ch2")) n <- 50 ref <- resampleImage(ref, c(n, n, n), 1, 0) ref <- iMath(ref, "Normalize") refmask <- getMask(ref) ilist <- list() seglist <- list() for (k in 1:5) { mi <- antsImageClone(ref) + rnorm(n^3, 0, 0.1) mykseg <- kmeansSegmentation(mi, 3, refmask)$segmentation ilist[[k]] <- mi seglist[[k]] <- mykseg } pp <- jointLabelFusion(ref, refmask, ilist, rSearch = 2, labelList = seglist, rad = rep(2, length(dim(ref))), verbose = TRUE ) plot(ref, pp$segmentation) plot(pp$intensity) ## End(Not run)
Joints reconstruct a n by p, q, etc matrices or predictors. The reconstruction can be regularized. # norm( x - u_x v_x^t ) + norm( y - u_y v_y^t) + .... etc
jointSmoothMatrixReconstruction( x, nvecs, parameters, iterations = 10, subIterations = 5, gamma = 1e-06, sparsenessQuantile = 0.5, positivity = FALSE, smoothingMatrix = NA, rowWeights = NA, repeatedMeasures = NA, doOrth = FALSE, verbose = FALSE )jointSmoothMatrixReconstruction( x, nvecs, parameters, iterations = 10, subIterations = 5, gamma = 1e-06, sparsenessQuantile = 0.5, positivity = FALSE, smoothingMatrix = NA, rowWeights = NA, repeatedMeasures = NA, doOrth = FALSE, verbose = FALSE )
x |
input list of matrices to be jointly predicted. |
nvecs |
number of basis vectors to compute |
parameters |
should be a ncomparisons by 3 matrix where the first two columns define the pair to be matched and the last column defines the weight in the objective function. |
iterations |
number of gradient descent iterations |
subIterations |
number of gradient descent iterations in sub-algorithm |
gamma |
step size for gradient descent |
sparsenessQuantile |
quantile to control sparseness - higher is sparser |
positivity |
restrict to positive or negative solution (beta) weights. choices are positive, negative or either as expressed as a string. |
smoothingMatrix |
a list containing smoothing matrices of the same length as x. |
rowWeights |
vectors of weights with size n (assumes diagonal covariance) |
repeatedMeasures |
list of repeated measurement identifiers. this will allow estimates of per identifier intercept. |
doOrth |
boolean enforce gram-schmidt orthonormality |
verbose |
boolean option |
matrix list each of size p by k is output
Avants BB
## Not run: mat <- replicate(100, rnorm(20)) mat2 <- replicate(100, rnorm(20)) mat <- scale(mat) mat2 <- scale(mat2) wt <- 0.666 mat3 <- mat * wt + mat2 * (1 - wt) params <- matrix(nrow = 2, ncol = 3) params[1, ] <- c(1, 2, 1) params[2, ] <- c(2, 1, 1) x <- list((mat), (mat3)) jj <- jointSmoothMatrixReconstruction(x, 2, params, gamma = 1e-4, sparsenessQuantile = 0.5, iterations = 10, smoothingMatrix = list(NA, NA), verbose = TRUE ) # latent feature mask <- getMask(antsImageRead(getANTsRData("r16"))) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 27, sigma = 120.0) lfeats <- t(replicate(100, rnorm(3))) # map these - via matrix - to observed features n <- sum(mask) ofeats1 <- (lfeats + rnorm(length(lfeats), 0.0, 1.0)) %*% rbind(rnorm(n), rnorm(n), rnorm(n)) ofeats2 <- (lfeats + rnorm(length(lfeats), 0.0, 1.0)) %*% rbind(rnorm(n), rnorm(n), rnorm(n)) # only half of the matrix contains relevant data ofeats1[, 1:round(n / 2)] <- matrix(rnorm(round(n / 2) * 100), nrow = 100) ofeats2[, 1:round(n / 2)] <- matrix(rnorm(round(n / 2) * 100), nrow = 100) x <- list((ofeats1), (ofeats2)) jj <- jointSmoothMatrixReconstruction(x, 2, params, gamma = 0.0001, sparsenessQuantile = 0.75, iterations = 19, subIterations = 11, smoothingMatrix = list(smoomat, smoomat), verbose = TRUE ) p1 <- ofeats2 %*% jj$v[[2]] p2 <- ofeats1 %*% jj$v[[1]] cor(p1, lfeats) cor(p2, lfeats) print(cor(rowMeans(ofeats1), lfeats)) print(cor(rowMeans(ofeats2), lfeats)) # a 2nd example with 3 modalities imageIDs <- c("r16", "r27", "r30", "r62", "r64", "r85") images <- list() feature1Images <- list() feature2Images <- list() feature3Images <- list() ref <- antsImageRead(getANTsRData("r16")) for (i in 1:length(imageIDs)) { cat("Processing image", imageIDs[i], "\n") tar <- antsRegistration(ref, antsImageRead(getANTsRData(imageIDs[i])), typeofTransform = "Affine" )$warpedmov images[[i]] <- tar feature1Images[[i]] <- iMath(images[[i]], "Grad", 1.0) feature2Images[[i]] <- iMath(images[[i]], "Laplacian", 1.0) feature3Images[[i]] <- reflectImage(tar, axis = 0, tx = "Affine")$warpedmovout } i <- 1 mask <- getMask(antsImageRead(getANTsRData(imageIDs[i]))) mask2 <- iMath(mask, "ME", 2) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 125, sigma = 100.0) spatmat2 <- t(imageDomainToSpatialMatrix(mask2, mask2)) smoomat2 <- knnSmoothingMatrix(spatmat2, k = 125, sigma = 100.0) params <- matrix(nrow = 6, ncol = 3) params[1, ] <- c(1, 2, 1) params[2, ] <- c(2, 1, 1) params[3, ] <- c(1, 3, 1) params[4, ] <- c(3, 1, 1) params[5, ] <- c(2, 3, 1) params[6, ] <- c(3, 2, 1) mat <- imageListToMatrix(feature1Images, mask) mat2 <- imageListToMatrix(feature2Images, mask2) mat3 <- imageListToMatrix(feature3Images, mask) scl <- F x <- list(scale(mat, scale = scl), scale(mat2, scale = scl), scale(mat3, scale = scl)) slist <- list(smoomat2, smoomat, smoomat, smoomat, smoomat, smoomat2) jj <- jointSmoothMatrixReconstruction(x, 4, params, positivity = T, gamma = 1e-6, sparsenessQuantile = 0.9, iterations = 10, smoothingMatrix = slist, verbose = TRUE ) mm <- makeImage(mask, abs(jj$v[[2]][, 1])) %>% iMath("Normalize") plot(ref, mm, doCropping = FALSE, window.overlay = c(0.1, 1)) p1 <- mat2 %*% jj$v[[1]] p2 <- mat %*% jj$v[[2]] diag(cor(p1, p2)) p1 <- mat3 %*% jj$v[[5]] p2 <- mat2 %*% jj$v[[6]] diag(cor(p1, p2)) ## End(Not run)## Not run: mat <- replicate(100, rnorm(20)) mat2 <- replicate(100, rnorm(20)) mat <- scale(mat) mat2 <- scale(mat2) wt <- 0.666 mat3 <- mat * wt + mat2 * (1 - wt) params <- matrix(nrow = 2, ncol = 3) params[1, ] <- c(1, 2, 1) params[2, ] <- c(2, 1, 1) x <- list((mat), (mat3)) jj <- jointSmoothMatrixReconstruction(x, 2, params, gamma = 1e-4, sparsenessQuantile = 0.5, iterations = 10, smoothingMatrix = list(NA, NA), verbose = TRUE ) # latent feature mask <- getMask(antsImageRead(getANTsRData("r16"))) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 27, sigma = 120.0) lfeats <- t(replicate(100, rnorm(3))) # map these - via matrix - to observed features n <- sum(mask) ofeats1 <- (lfeats + rnorm(length(lfeats), 0.0, 1.0)) %*% rbind(rnorm(n), rnorm(n), rnorm(n)) ofeats2 <- (lfeats + rnorm(length(lfeats), 0.0, 1.0)) %*% rbind(rnorm(n), rnorm(n), rnorm(n)) # only half of the matrix contains relevant data ofeats1[, 1:round(n / 2)] <- matrix(rnorm(round(n / 2) * 100), nrow = 100) ofeats2[, 1:round(n / 2)] <- matrix(rnorm(round(n / 2) * 100), nrow = 100) x <- list((ofeats1), (ofeats2)) jj <- jointSmoothMatrixReconstruction(x, 2, params, gamma = 0.0001, sparsenessQuantile = 0.75, iterations = 19, subIterations = 11, smoothingMatrix = list(smoomat, smoomat), verbose = TRUE ) p1 <- ofeats2 %*% jj$v[[2]] p2 <- ofeats1 %*% jj$v[[1]] cor(p1, lfeats) cor(p2, lfeats) print(cor(rowMeans(ofeats1), lfeats)) print(cor(rowMeans(ofeats2), lfeats)) # a 2nd example with 3 modalities imageIDs <- c("r16", "r27", "r30", "r62", "r64", "r85") images <- list() feature1Images <- list() feature2Images <- list() feature3Images <- list() ref <- antsImageRead(getANTsRData("r16")) for (i in 1:length(imageIDs)) { cat("Processing image", imageIDs[i], "\n") tar <- antsRegistration(ref, antsImageRead(getANTsRData(imageIDs[i])), typeofTransform = "Affine" )$warpedmov images[[i]] <- tar feature1Images[[i]] <- iMath(images[[i]], "Grad", 1.0) feature2Images[[i]] <- iMath(images[[i]], "Laplacian", 1.0) feature3Images[[i]] <- reflectImage(tar, axis = 0, tx = "Affine")$warpedmovout } i <- 1 mask <- getMask(antsImageRead(getANTsRData(imageIDs[i]))) mask2 <- iMath(mask, "ME", 2) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 125, sigma = 100.0) spatmat2 <- t(imageDomainToSpatialMatrix(mask2, mask2)) smoomat2 <- knnSmoothingMatrix(spatmat2, k = 125, sigma = 100.0) params <- matrix(nrow = 6, ncol = 3) params[1, ] <- c(1, 2, 1) params[2, ] <- c(2, 1, 1) params[3, ] <- c(1, 3, 1) params[4, ] <- c(3, 1, 1) params[5, ] <- c(2, 3, 1) params[6, ] <- c(3, 2, 1) mat <- imageListToMatrix(feature1Images, mask) mat2 <- imageListToMatrix(feature2Images, mask2) mat3 <- imageListToMatrix(feature3Images, mask) scl <- F x <- list(scale(mat, scale = scl), scale(mat2, scale = scl), scale(mat3, scale = scl)) slist <- list(smoomat2, smoomat, smoomat, smoomat, smoomat, smoomat2) jj <- jointSmoothMatrixReconstruction(x, 4, params, positivity = T, gamma = 1e-6, sparsenessQuantile = 0.9, iterations = 10, smoothingMatrix = slist, verbose = TRUE ) mm <- makeImage(mask, abs(jj$v[[2]][, 1])) %>% iMath("Normalize") plot(ref, mm, doCropping = FALSE, window.overlay = c(0.1, 1)) p1 <- mat2 %*% jj$v[[1]] p2 <- mat %*% jj$v[[2]] diag(cor(p1, p2)) p1 <- mat3 %*% jj$v[[5]] p2 <- mat2 %*% jj$v[[6]] diag(cor(p1, p2)) ## End(Not run)
Diffeomorphic registration-based cortical thickness based on probabilistic segmentation of an image. This is an optimization algorithm.
kellyKapowski( s, g, w, its = 45, r = 0.025, m = 1.5, x = FALSE, e = FALSE, q = NULL, timeSigma = 1, verbose = FALSE, ... )kellyKapowski( s, g, w, its = 45, r = 0.025, m = 1.5, x = FALSE, e = FALSE, q = NULL, timeSigma = 1, verbose = FALSE, ... )
s |
segmentation image |
g |
gray matter probability image |
w |
white matter probability image |
its |
convergence params - controls iterations |
r |
gradient descent update parameter |
m |
gradient field smoothing parameter |
x |
matrix-based smoothing |
e |
restrict deformation boolean |
q |
time spacing, a vector equal to the number of time dimensions |
timeSigma |
a scalar sigma value for distances between time points |
verbose |
boolean |
... |
anything else, see KK help in ANTs |
thickness antsImage
Shrinidhi KL, Avants BB
img <- antsImageRead(getANTsRData("r16"), 2) img <- resampleImage(img, c(64, 64), 1, 0) mask <- getMask(img) segs <- kmeansSegmentation(img, k = 3, kmask = mask) thk <- kellyKapowski( s = segs$segmentation, g = segs$probabilityimages[[2]], w = segs$probabilityimages[[3]], its = 45, r = 0.5, m = 1 )img <- antsImageRead(getANTsRData("r16"), 2) img <- resampleImage(img, c(64, 64), 1, 0) mask <- getMask(img) segs <- kmeansSegmentation(img, k = 3, kmask = mask) thk <- kellyKapowski( s = segs$segmentation, g = segs$probabilityimages[[2]], w = segs$probabilityimages[[3]], its = 45, r = 0.5, m = 1 )
k means image segmentation that is a wrapper around atropos
kmeansSegmentation(img, k, kmask = NULL, mrf = 0.1, verbose = FALSE, ...)kmeansSegmentation(img, k, kmask = NULL, mrf = 0.1, verbose = FALSE, ...)
img |
input image |
k |
integer number of classes |
kmask |
segment inside this mask |
mrf |
smoothness, higher is smoother |
verbose |
boolean |
... |
additional arguments to pass to |
segmentation and probability images
This function will likely give different results on multiple runs.
Brian B. Avants
fi <- antsImageRead(getANTsRData("r16"), 2) orig <- antsImageClone(fi) fi <- n3BiasFieldCorrection(fi, 4) seg <- kmeansSegmentation(fi, 3) seg2 <- kmeansSegmentation(fi, 3) arr1 <- as.array(seg$segmentation) arr2 <- as.array(seg2$segmentation) testthat::expect_equal(arr1, arr2) set.seed(2) # set below for slower but numerically repeatable results # these should be set in .Renviron not by sys calls # Sys.setenv(ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS = 1 ) orig <- antsImageRead(getANTsRData("r16"), 2) seg <- kmeansSegmentation(orig, 3, use_random_seed = TRUE) seg2 <- kmeansSegmentation(orig, 3, use_random_seed = TRUE) arr1 <- as.array(seg$segmentation) arr2 <- as.array(seg2$segmentation) tab <- table(arr1, arr2) tab identical(arr1, arr2) seg <- kmeansSegmentation(orig, 3, use_random_seed = FALSE) seg2 <- kmeansSegmentation(orig, 3, use_random_seed = FALSE) arr1 <- as.array(seg$segmentation) arr2 <- as.array(seg2$segmentation) tab <- table(arr1, arr2) tabfi <- antsImageRead(getANTsRData("r16"), 2) orig <- antsImageClone(fi) fi <- n3BiasFieldCorrection(fi, 4) seg <- kmeansSegmentation(fi, 3) seg2 <- kmeansSegmentation(fi, 3) arr1 <- as.array(seg$segmentation) arr2 <- as.array(seg2$segmentation) testthat::expect_equal(arr1, arr2) set.seed(2) # set below for slower but numerically repeatable results # these should be set in .Renviron not by sys calls # Sys.setenv(ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS = 1 ) orig <- antsImageRead(getANTsRData("r16"), 2) seg <- kmeansSegmentation(orig, 3, use_random_seed = TRUE) seg2 <- kmeansSegmentation(orig, 3, use_random_seed = TRUE) arr1 <- as.array(seg$segmentation) arr2 <- as.array(seg2$segmentation) tab <- table(arr1, arr2) tab identical(arr1, arr2) seg <- kmeansSegmentation(orig, 3, use_random_seed = FALSE) seg2 <- kmeansSegmentation(orig, 3, use_random_seed = FALSE) arr1 <- as.array(seg$segmentation) arr2 <- as.array(seg2$segmentation) tab <- table(arr1, arr2) tab
Compute a smoothing matrix based on an input matrix of point coordinates as well as neighborhood intensity patterns. this performs a form of edge preserving smoothing.
knnSmoothImage( img, mask, radius, intensityWeight = 0.1, spatialSigma = 20, iterations = 1, returnMatrix = FALSE )knnSmoothImage( img, mask, radius, intensityWeight = 0.1, spatialSigma = 20, iterations = 1, returnMatrix = FALSE )
img |
input image to smooth |
mask |
input image mask |
radius |
number of neighbors, higher causes more smoothing |
intensityWeight |
weight for intensity component, value 1 will weight local voxel intensity roughly equally to spatial component |
spatialSigma |
for gaussian defining spatial distances |
iterations |
number of iterations over which to apply smoothing kernel |
returnMatrix |
boolean, will return smoothing matrix instead of image. |
antsImage is output
Avants BB
## Not run: img <- antsImageRead(getANTsRData("r16")) mask <- getMask(img) simg <- knnSmoothImage( img = img, mask = mask, radius = 2, intensityWeight = 1, spatialSigma = 1.5, iterations = 1 ) ## End(Not run)## Not run: img <- antsImageRead(getANTsRData("r16")) mask <- getMask(img) simg <- knnSmoothImage( img = img, mask = mask, radius = 2, intensityWeight = 1, spatialSigma = 1.5, iterations = 1 ) ## End(Not run)
Compute a smoothing matrix based on an input matrix of point coordinates
knnSmoothingMatrix(x, k, sigma, segmentation, ...)knnSmoothingMatrix(x, k, sigma, segmentation, ...)
x |
input matrix of point coordinates of dimensions n-spatial spatial dimensions by p points |
k |
number of neighbors, higher causes more smoothing |
sigma |
sigma for the gaussian function |
segmentation |
optional boolean to restrict specific rows to have minimal respons |
... |
arguments passed to |
sparse matrix is output
Avants BB
## Not run: mask <- getMask(antsImageRead(getANTsRData("r16"))) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoothingMatrix <- knnSmoothingMatrix(spatmat, k = 25, sigma = 3.0) rvec <- rnorm(nrow(smoothingMatrix)) srvec <- smoothingMatrix %*% rvec rvi <- makeImage(mask, rvec) srv <- makeImage(mask, as.numeric(srvec)) ## End(Not run)## Not run: mask <- getMask(antsImageRead(getANTsRData("r16"))) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoothingMatrix <- knnSmoothingMatrix(spatmat, k = 25, sigma = 3.0) rvec <- rnorm(nrow(smoothingMatrix)) srvec <- smoothingMatrix %*% rvec rvi <- makeImage(mask, rvec) srv <- makeImage(mask, as.numeric(srvec)) ## End(Not run)
This function scales the columns of a numeric matrix such that the sum of the absolute values of each column (the L1 norm) is equal to 1. This is a common preprocessing step for feature matrices.
l1_normalize_features(features)l1_normalize_features(features)
features |
A numeric matrix or a data frame that can be coerced into one. The normalization is applied column-wise. |
The function is designed to be highly efficient by using vectorized operations. It also robustly handles columns that sum to zero to prevent division-by-zero errors.
A matrix with the same dimensions as the input, where each column has been L1-normalized.
# Create a sample feature matrix set.seed(123) my_features <- matrix(rnorm(12, mean = 5), nrow = 4, ncol = 3) print(my_features) #> [,1] [,2] [,3] #> [1,] 4.4395244 5.487429 5.704929 #> [2,] 5.2325834 6.738325 5.558708 #> [3,] 3.4291247 5.575781 4.129288 #> [4,] 5.5060559 4.694612 4.261173 # Check the column sums of absolute values before normalization print(colSums(abs(my_features))) #> [1] 18.60729 22.49615 19.65410 # Apply L1 normalization normalized_features <- l1_normalize_features(my_features) print(normalized_features) #> [,1] [,2] [,3] #> [1,] 0.23859089 0.2439247 0.2800889 #> [2,] 0.28121151 0.2995321 0.2891398 #> [3,] 0.18429107 0.2478546 0.2151676 #> [4,] 0.29590653 0.2086886 0.2221037 # Confirm that the new column sums of absolute values are all 1 print(colSums(abs(normalized_features))) #> [1] 1 1 1# Create a sample feature matrix set.seed(123) my_features <- matrix(rnorm(12, mean = 5), nrow = 4, ncol = 3) print(my_features) #> [,1] [,2] [,3] #> [1,] 4.4395244 5.487429 5.704929 #> [2,] 5.2325834 6.738325 5.558708 #> [3,] 3.4291247 5.575781 4.129288 #> [4,] 5.5060559 4.694612 4.261173 # Check the column sums of absolute values before normalization print(colSums(abs(my_features))) #> [1] 18.60729 22.49615 19.65410 # Apply L1 normalization normalized_features <- l1_normalize_features(my_features) print(normalized_features) #> [,1] [,2] [,3] #> [1,] 0.23859089 0.2439247 0.2800889 #> [2,] 0.28121151 0.2995321 0.2891398 #> [3,] 0.18429107 0.2478546 0.2151676 #> [4,] 0.29590653 0.2086886 0.2221037 # Confirm that the new column sums of absolute values are all 1 print(colSums(abs(normalized_features))) #> [1] 1 1 1
This will give a unique ID to each connected component 1 through N of size > minClusterSize
labelClusters( imagein, minClusterSize = 50, minThresh = 1e-06, maxThresh = 1, fullyConnected = FALSE )labelClusters( imagein, minClusterSize = 50, minThresh = 1e-06, maxThresh = 1, fullyConnected = FALSE )
imagein |
input antsImage e.g. a statistical map |
minClusterSize |
throw away clusters smaller than this value |
minThresh |
threshold to a statistical map |
maxThresh |
threshold to a statistical map |
fullyConnected |
boolean sets neighborhood connectivity pattern |
labeled cluster image is output
Avants BB
img <- antsImageRead(getANTsRData("r16")) timgFully <- labelClusters(img, 10, 128, 150, TRUE) timgFace <- labelClusters(img, 10, 128, 150, FALSE) ## Not run: plot(img, timgFace) plot(img, timgFully) ## End(Not run)img <- antsImageRead(getANTsRData("r16")) timgFully <- labelClusters(img, 10, 128, 150, TRUE) timgFace <- labelClusters(img, 10, 128, 150, FALSE) ## Not run: plot(img, timgFace) plot(img, timgFully) ## End(Not run)
Wrapper for the ANTs funtion labelGeometryMeasures
labelGeometryMeasures(labelImage, intensityImage = NULL)labelGeometryMeasures(labelImage, intensityImage = NULL)
labelImage |
on which to compute geometry |
intensityImage |
optional |
none
Avants BB, Tustison NJ
fi <- antsImageRead(getANTsRData("r16"), 2) seg <- kmeansSegmentation(fi, 3)$segmentation geom <- labelGeometryMeasures(seg, fi)fi <- antsImageRead(getANTsRData("r16"), 2) seg <- kmeansSegmentation(fi, 3)$segmentation geom <- labelGeometryMeasures(seg, fi)
Converts a label image to coordinates summarizing their positions
labelImageCentroids(img, physical = FALSE, convex = TRUE)labelImageCentroids(img, physical = FALSE, convex = TRUE)
img |
ants image of labels (ints) |
physical |
boolean if you want physical space coordinates or not |
convex |
- if TRUE, return centroid, if FALSE return point with min average distance to other points with same label |
list with labels , array of label values, and centroids <- coordinates of label centroids
Avants BB, Duda JT
labelImage <- makeImage(c(2, 2, 2), 0:7) labelImageCentroids(labelImage)labelImage <- makeImage(c(2, 2, 2), 0:7) labelImageCentroids(labelImage)
Perform pairwise registration using fixed and moving sets of label images (and, optionally, sets of corresponding intensity images).
labelImageRegistration( fixedLabelImages, movingLabelImages, fixedIntensityImages = NULL, movingIntensityImages = NULL, fixedMask = NULL, movingMask = NULL, initialTransforms = "affine", typeOfDeformableTransform = "antsRegistrationSyNQuick[so]", labelImageWeighting = 1, outputPrefix = "", randomSeed = NULL, verbose = FALSE )labelImageRegistration( fixedLabelImages, movingLabelImages, fixedIntensityImages = NULL, movingIntensityImages = NULL, fixedMask = NULL, movingMask = NULL, initialTransforms = "affine", typeOfDeformableTransform = "antsRegistrationSyNQuick[so]", labelImageWeighting = 1, outputPrefix = "", randomSeed = NULL, verbose = FALSE )
fixedLabelImages |
A single (or set of) fixed label image(s). |
movingLabelImages |
A single (or set of) moving label image(s). |
fixedIntensityImages |
Optional—a single (or set of) fixed intensity image(s). |
movingIntensityImages |
Optional—a single (or set of) moving intensity image(s). |
fixedMask |
Defines region for similarity metric calculation in the space of the fixed image. |
movingMask |
Defines region for similarity metric calculation in the space of the moving image. |
initialTransforms |
If specified, there are two options:
1) Use label images with the centers of mass to a calculate linear
transform of type |
typeOfDeformableTransform |
Only works with deformable-only transforms,
specifically the family of |
labelImageWeighting |
Float or vector of floats giving the relative weighting for the label images. |
outputPrefix |
String definining the output prefix for the filenames of the output transform files. |
randomSeed |
Definition for deformable registration. |
verbose |
Print progress to the screen. |
outputs a list containing:
Transforms to move from moving to fixed image.
Transforms to move from fixed to moving image.
Output of 1 indicates failure.
Tustison NJ
## Not run: r16 <- antsImageRead( getANTsRData( "r16" ) ) r16Seg1 <- thresholdImage( r16, "Kmeans", 3 ) - 1 r16Seg2 <- thresholdImage( r16, "Kmeans", 5 ) - 1 r64 <- antsImageRead( getANTsRData( "r64" ) ) r64Seg1 <- thresholdImage( r64, "Kmeans", 3 ) - 1 r64Seg2 <- thresholdImage( r64, "Kmeans", 5 ) - 1 reg <- labelImageRegistration( list( r16Seg1, r16Seg2 ), list( r64Seg1, r64Seg2 ), fixedIntensityImages = r16, movingIntensityImages = r64, initialTransforms = 'affine', typeOfDeformableTransform = 'antsRegistrationSyNQuick[bo]', labelImageWeighting = c( 1.0, 2.0 ), verbose = TRUE ) ## End(Not run)## Not run: r16 <- antsImageRead( getANTsRData( "r16" ) ) r16Seg1 <- thresholdImage( r16, "Kmeans", 3 ) - 1 r16Seg2 <- thresholdImage( r16, "Kmeans", 5 ) - 1 r64 <- antsImageRead( getANTsRData( "r64" ) ) r64Seg1 <- thresholdImage( r64, "Kmeans", 3 ) - 1 r64Seg2 <- thresholdImage( r64, "Kmeans", 5 ) - 1 reg <- labelImageRegistration( list( r16Seg1, r16Seg2 ), list( r64Seg1, r64Seg2 ), fixedIntensityImages = r16, movingIntensityImages = r64, initialTransforms = 'affine', typeOfDeformableTransform = 'antsRegistrationSyNQuick[bo]', labelImageWeighting = c( 1.0, 2.0 ), verbose = TRUE ) ## End(Not run)
Wrapper for the ANTs funtion LabelOverlapMeasures. More documentaiton available here:
labelOverlapMeasures(sourceLabelImage, targetLabelImage)labelOverlapMeasures(sourceLabelImage, targetLabelImage)
sourceLabelImage |
label image for source image. |
targetLabelImage |
label image for target/reference image. |
https://www.insight-journal.org/browse/publication/707
data frame with overlap measures
Avants BB, Tustison NJ
sourceImage <- antsImageRead(getANTsRData("r16"), 2) sourceSegmentation <- kmeansSegmentation(sourceImage, 3)$segmentation referenceImage <- antsImageRead(getANTsRData("r16"), 2) referenceSegmentation <- kmeansSegmentation(referenceImage, 3)$segmentation overlap <- labelOverlapMeasures(sourceSegmentation, referenceSegmentation)sourceImage <- antsImageRead(getANTsRData("r16"), 2) sourceSegmentation <- kmeansSegmentation(sourceImage, 3)$segmentation referenceImage <- antsImageRead(getANTsRData("r16"), 2) referenceSegmentation <- kmeansSegmentation(referenceImage, 3)$segmentation overlap <- labelOverlapMeasures(sourceSegmentation, referenceSegmentation)
Convert a labeled image to an n x m binary matrix where n = number of voxels and m = number of labels. Only includes values inside the provided mask while including background ( img == 0 ) for consistency with timeseries2matrix and other image to matrix operations.
labels2matrix(img, mask, targetLabels = NULL, missingVal = NA)labels2matrix(img, mask, targetLabels = NULL, missingVal = NA)
img |
input label image |
mask |
defines domain of interest |
targetLabels |
defines target regions to be returned. if the target label does not exist in the input label image, then the matrix will contain a constant value of missingVal (default NA) in that row. |
missingVal |
for missing label values. |
matrix is output
Avants BB
fi <- antsImageRead(getANTsRData("r16"), 2) %>% resampleImage(c(60, 60), 1, 0) mask <- getMask(fi) labs <- kmeansSegmentation(fi, 3)$segmentation labmat <- labels2matrix(labs, mask)fi <- antsImageRead(getANTsRData("r16"), 2) %>% resampleImage(c(60, 60), 1, 0) mask <- getMask(fi) labs <- kmeansSegmentation(fi, 3)$segmentation labmat <- labels2matrix(labs, mask)
Get label statistics from image.
labelStats(image, labelImage)labelStats(image, labelImage)
image |
Image to calculate statistics from. |
labelImage |
Label image. |
Data frame with one row per label (including zero) and columns : LabelValues, Mean, Min, Max, Variance, Count, Volume
img <- antsImageRead(getANTsRData("r16"), 2) img <- resampleImage(img, c(64, 64), 1, 0) mask <- getMask(img) segs1 <- kmeansSegmentation(img, 3) labelStats(img, segs1$segmentation) testthat::expect_error(labelStats(img, as.array(segs1$segmentation))) testthat::expect_error(labelStats(img, as.array(segs1$segmentation))) sub_seg <- segs1$segmentation sub_seg <- as.antsImage(sub_seg[1:62, 1:62], reference = sub_seg) testthat::expect_error(labelStats(img, sub_seg))img <- antsImageRead(getANTsRData("r16"), 2) img <- resampleImage(img, c(64, 64), 1, 0) mask <- getMask(img) segs1 <- kmeansSegmentation(img, 3) labelStats(img, segs1$segmentation) testthat::expect_error(labelStats(img, as.array(segs1$segmentation))) testthat::expect_error(labelStats(img, as.array(segs1$segmentation))) sub_seg <- segs1$segmentation sub_seg <- as.antsImage(sub_seg[1:62, 1:62], reference = sub_seg) testthat::expect_error(labelStats(img, sub_seg))
Append an item to a list , creating a new list or combine two lists
lappend(lst, obj)lappend(lst, obj)
lst |
list to which you will append the 2nd item |
obj |
to be added to the list |
outputs the appended list
Avants BB, the internet
mat <- replicate(100, rnorm(20)) mat2 <- replicate(100, rnorm(20)) mylist <- list(mat) mylist <- lappend(mylist, mat2) mylist <- lappend(mat2, mylist) mylist <- lappend(mylist, mylist) lappend(1, 1)mat <- replicate(100, rnorm(20)) mat2 <- replicate(100, rnorm(20)) mylist <- list(mat) mylist <- lappend(mylist, mat2) mylist <- lappend(mat2, mylist) mylist <- lappend(mylist, mylist) lappend(1, 1)
Dynamically returns the names of all optimizer types with registered 'step.*' methods.
list_simlr_optimizers(torch = FALSE)list_simlr_optimizers(torch = FALSE)
torch |
Logical; if TRUE, returns a predefined list of optimizers compatible with torch. |
A character vector of optimizer names (e.g., "adam", "nadam", etc.)
Loads a previously saved ANTsR session or object. Simply point the function to the folder where you previously saved the data with save.ANTsR.
load.ANTsR(filename=file.path('.','.ANTsRsession'), env=as.environment(1))load.ANTsR(filename=file.path('.','.ANTsRsession'), env=as.environment(1))
filename |
path of the saved ANTsR session. If not specified, the default behavior is to search for the folder \".ANTsRsesssion\" in the current working directory. |
env |
the environment level. Don't change unless you know what are you doing. |
Dorian Pustina
A data frame label numbers and names for brain lobes.
lobeslobes
A data frame with columns: Label, Description, Side, SideNumber.
A data frame label numbers and names for lobes and brainstem regions.
lobes_brainstemlobes_brainstem
A data frame with columns: Label, Description, Side.
Estimate the gyrification index at a specific scale. This will produce images of local sulcification and gyrification as as well as the difference of these two measurements. The most gyral values are near 1 and most sulcal negative 1. The function is not limited to brain data and should work on any 3D shape. See the paper entitled the shape operator for differential image analysis.
localGyrificationIndex(segmentation, sigma = 3, k = 25, ksigma = 3)localGyrificationIndex(segmentation, sigma = 3, k = 25, ksigma = 3)
segmentation |
- potentially from antsCorticalThickness |
sigma |
- scale parameter |
k |
- size of neighborhood |
ksigma |
- sigma for k-neighborhood |
lGI image
Avants BB
## Not run: seg <- antsImageRead("segmentation.nii.gz") wm <- thresholdImage(seg, 3, 3) %>% morphology("dilate", 1) lgi <- localGyrificationIndex(wm) ## End(Not run)## Not run: seg <- antsImageRead("segmentation.nii.gz") wm <- thresholdImage(seg, 3, 3) %>% morphology("dilate", 1) lgi <- localGyrificationIndex(wm) ## End(Not run)
A local version of joint label fusion that focuses on one or more specific labels. This is primarily different from standard JLF because it performs registration on a per label basis and focuses JLF on the label(s) alone. It requires an initial segmentation of the target region which can be provided either by a manual or automated initialization. Registration by SyN is a good choice for the latter approach.
localJointLabelFusion( targetI, whichLabels, targetMask, initialLabel, atlasList, labelList, submaskDilation = 10, typeofTransform = "SyN", affMetric = "meansquares", synMetric = "mattes", synSampling = 32, regIterations = c(40, 20, 0), affIterations, localMaskTransform, maxLabelPlusOne = FALSE, noZeroes = FALSE, verbose = FALSE, ... )localJointLabelFusion( targetI, whichLabels, targetMask, initialLabel, atlasList, labelList, submaskDilation = 10, typeofTransform = "SyN", affMetric = "meansquares", synMetric = "mattes", synSampling = 32, regIterations = c(40, 20, 0), affIterations, localMaskTransform, maxLabelPlusOne = FALSE, noZeroes = FALSE, verbose = FALSE, ... )
targetI |
antsImage to be labeled |
whichLabels |
label number(s) from the library on which to focus |
targetMask |
a mask for the target image (optional), passed to joint fusion |
initialLabel |
the initial approximate label(s) for the target region. |
atlasList |
list containing antsImages with intensity images |
labelList |
list containing antsImages with segmentation labels |
submaskDilation |
amount to dilate initial mask to define region on which we perform focused registration |
typeofTransform |
passed to |
affMetric |
the metric for the affine part (GC, mattes, meansquares) |
synMetric |
the metric for the syn part (CC, mattes, meansquares, demons) |
synSampling |
the nbins or radius parameter for the syn metric |
regIterations |
vector of iterations for syn. we will set the smoothing
and multi-resolution parameters based on the length of this vector.
passed to |
affIterations |
vector of iterations for low-dimensional transforms. |
localMaskTransform |
type of transform for local mask initialization; would usually set to Rigid, Similarity or Affine |
maxLabelPlusOne |
boolean this will add max label plus one to the non-zero parts of each label where the target mask is greater than one. NOTE: this will have a side effect of adding to the original label images that are passed to the program. It also guarantees that every position in the labels have some label, rather than none. Ie it guarantees to explicitly parcellate the input data. |
noZeroes |
boolean will zero out target mask regions that have any zero label. this prevents JLF from computing a solution in regions not covered by the initial library. |
verbose |
boolean |
... |
extra parameters passed to JLF |
label probabilities and segmentations
Brian B. Avants
Produces a low rank version of the input matrix
lowrankRowMatrix(A, k = 2, faster = FALSE)lowrankRowMatrix(A, k = 2, faster = FALSE)
A |
input matrix |
k |
rank to use |
faster |
boolean |
matrix is output
Avants BB
mat <- matrix(rnorm(300), ncol = 50) lrmat <- lowrankRowMatrix(mat, 2)mat <- matrix(rnorm(300), ncol = 50) lrmat <- lowrankRowMatrix(mat, 2)
The make3ViewPNG function rotates the existing viewport according to 3 different rotation matrices passed in by the user. The output of these 3 views is munged together along the left/right edge and written to a png file.
make3ViewPNG(rotationView1, rotationView2, rotationView3, fnprefix)make3ViewPNG(rotationView1, rotationView2, rotationView3, fnprefix)
rotationView1 |
Leftmost view |
rotationView2 |
Center view |
rotationView3 |
Rightmost view |
fnprefix |
Output file name prefix. |
NA
Avants BB
## Not run: bm <- getMask(antsImageRead(getANTsRData("ch2"))) brain <- renderSurfaceFunction( surfimg = list(bm), alphasurf = 0.1, smoothsval = 1.5 ) make3ViewPNG(diag(4), diag(4), diag(4), tempfile(fileext = ".png")) ## End(Not run)## Not run: bm <- getMask(antsImageRead(getANTsRData("ch2"))) brain <- renderSurfaceFunction( surfimg = list(bm), alphasurf = 0.1, smoothsval = 1.5 ) make3ViewPNG(diag(4), diag(4), diag(4), tempfile(fileext = ".png")) ## End(Not run)
Creates an igraph object from a square input correlation matrix - only positive correlations are used. Based on the graph.adjacency function of igraph. gplot is helpful for visualization.
makeGraph( mat, graphdensity = 1, communityMethod = NA, getEfficiency = FALSE, inverseValuesAsWeights = FALSE )makeGraph( mat, graphdensity = 1, communityMethod = NA, getEfficiency = FALSE, inverseValuesAsWeights = FALSE )
mat |
input matrix |
graphdensity |
fraction of edges to keep |
communityMethod |
see igraph's community detection |
getEfficiency |
boolean, this is slow to compute |
inverseValuesAsWeights |
if TRUE, high correlations produce small
edge weights. This detail is important when using igraph algorithms as
different methods use weights in different ways. See igraph for its
|
a named list is output including the graph object, adjacency matrix and several graph metrics
Avants BB
mat <- matrix(c(1, 0.5, 0.2, -0.1, 1, 0.3, -0.2, 0.6, 1), ncol = 3) gobj <- makeGraph(mat, 0.5)mat <- matrix(c(1, 0.5, 0.2, -0.1, 1, 0.3, -0.2, 0.6, 1), ncol = 3) gobj <- makeGraph(mat, 0.5)
Make an image with given size and voxel value or given a mask and vector.
makeImage( imagesize, voxval = 0, spacing = c(NA), origin = c(NA), direction = c(NA), components = FALSE, pixeltype = "float" )makeImage( imagesize, voxval = 0, spacing = c(NA), origin = c(NA), direction = c(NA), components = FALSE, pixeltype = "float" )
imagesize |
input image size or mask |
voxval |
input image value or vector, size of mask |
spacing |
image spatial resolution |
origin |
image spatial origin |
direction |
direction matrix to convert from index to physical space |
components |
whether there are components per pixel or not |
pixeltype |
data type of image values |
antsImage is output
Avants BB
outimg <- makeImage(c(2, 10), 1) outimg <- makeImage(outimg, c(2, 10)) testthat::expect_error(makeImage(outimg, c(2, 10), components = 2))outimg <- makeImage(c(2, 10), 1) outimg <- makeImage(outimg, c(2, 10)) testthat::expect_error(makeImage(outimg, c(2, 10), components = 2))
Creates spherical points in the coordinate space of the target image based on the n-dimensional matrix of points that the user supplies. The image defines the dimensionality of the data so if the input image is 3D then the input points should be 2D or 3D.
makePointsImage(pts, mask, radius = 5)makePointsImage(pts, mask, radius = 5)
pts |
input powers points |
mask |
antsImage mask defining target space |
radius |
for the points |
antsImage is output
Avants BB, Duda JT
## Not run: mni <- antsImageRead(getANTsRData("mni")) %>% getMask() data("powers_areal_mni_itk", package = "ANTsR", envir = environment()) powersLabels <- makePointsImage(powers_areal_mni_itk[, 1:3], mni, radius = 3) ## End(Not run)## Not run: mni <- antsImageRead(getANTsRData("mni")) %>% getMask() data("powers_areal_mni_itk", package = "ANTsR", envir = environment()) powersLabels <- makePointsImage(powers_areal_mni_itk[, 1:3], mni, radius = 3) ## End(Not run)
Creates spherical points in the coordinate space of the target image.
makePowersPointsImage(pts, mask, radius = 5)makePowersPointsImage(pts, mask, radius = 5)
pts |
input powers points |
mask |
antsImage mask defining target space |
radius |
for the points |
antsImage is output
Avants BB, Duda JT
## Not run: mni <- antsImageRead(getANTsRData("mni")) %>% getMask() data("powers_areal_mni_itk", package = "ANTsR", envir = environment()) powersLabels <- makePowersPointsImage(powers_areal_mni_itk, mni) # if you have a different target space # pts = antsApplyTransformsToPoints( 3, powers_areal_mni_itk, # transformlist = concatenatedMaps$toTemplate, # whichtoinvert = concatenatedMaps$toTemplateInversion ) ## End(Not run)## Not run: mni <- antsImageRead(getANTsRData("mni")) %>% getMask() data("powers_areal_mni_itk", package = "ANTsR", envir = environment()) powersLabels <- makePowersPointsImage(powers_areal_mni_itk, mni) # if you have a different target space # pts = antsApplyTransformsToPoints( 3, powers_areal_mni_itk, # transformlist = concatenatedMaps$toTemplate, # whichtoinvert = concatenatedMaps$toTemplateInversion ) ## End(Not run)
Convert left/right variables to a measure of asymmetry
mapAsymVar( mydataframe, leftvar, leftname = "left", rightname = "right", replacer = "Asym" )mapAsymVar( mydataframe, leftvar, leftname = "left", rightname = "right", replacer = "Asym" )
mydataframe |
dataframe containing relevant variables |
leftvar |
left side variable names ie the full names of the variables to asym |
leftname |
the variable substring indicating left side |
rightname |
the variable substring indicating right side |
replacer |
string to replace left with in column names of output |
fixed x
Avants BB
Convert left/right variables to an average measurement
mapLRAverageVar( mydataframe, leftvar, leftname = "left", rightname = "right", replacer = "LRAVG" )mapLRAverageVar( mydataframe, leftvar, leftname = "left", rightname = "right", replacer = "LRAVG" )
mydataframe |
dataframe containing relevant variables |
leftvar |
left side variable names ie the full names of the variables to average |
leftname |
the variable substring indicating left side |
rightname |
the variable substring indicating right side |
replacer |
string to replace left with in column names of output |
fixed x
Avants BB
Takes in a mask and an image and then returns the values
mask_values(x, mask)mask_values(x, mask)
x |
Object of class |
mask |
object to subset the image. If missing, then all values of the image are plotted. |
Vector of values
img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 mask_values(img, mask) mask_values(img)img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 mask_values(img, mask) mask_values(img)
Mask an input image by a mask image. If the mask image has multiple labels, it is possible to specify which label(s) to mask at.
maskImage(img.in, img.mask, level = 1, binarize = FALSE)maskImage(img.in, img.mask, level = 1, binarize = FALSE)
img.in |
Input image. |
img.mask |
Mask or label image. |
level |
Level(s) at which to mask image. If vector or list of values, output image is non-zero at all locations where label image matches any of the levels specified. |
binarize |
binarize the output image? |
An object of type antsImage.
Kandel BM and Avants B.
myimg <- antsImageRead(getANTsRData("r16")) mask <- getMask(myimg) myimg.mask <- maskImage(myimg, mask, 3) myimg.mask <- maskImage(myimg, mask) seg <- kmeansSegmentation(myimg, 3) myimg.mask <- maskImage(myimg, seg$segmentation, c(1, 3))myimg <- antsImageRead(getANTsRData("r16")) mask <- getMask(myimg) myimg.mask <- maskImage(myimg, mask, 3) myimg.mask <- maskImage(myimg, mask) seg <- kmeansSegmentation(myimg, 3) myimg.mask <- maskImage(myimg, seg$segmentation, c(1, 3))
matrix2timeseriess converts a matrix to a 4D image.
matrix2timeseries(referenceImage, maskImage, timeSeriesMatrix)matrix2timeseries(referenceImage, maskImage, timeSeriesMatrix)
referenceImage |
reference 4D image |
maskImage |
mask image defining voxels of interest |
timeSeriesMatrix |
matrix to convert to image |
antsImage in 4D is output
Avants BB
Unmasks rows of a matrix and writes as images.
matrixToImages(dataMatrix, mask)matrixToImages(dataMatrix, mask)
dataMatrix |
A matrix such as that created by |
mask |
An |
Cook PA
## Not run: # mat = matrixToImages( aMat, mask ) ## End(Not run)## Not run: # mat = matrixToImages( aMat, mask ) ## End(Not run)
Overloaded Mean for antsImage objects
## S3 method for class 'antsImage' mean(x, ..., mask = NULL, na.rm = FALSE)## S3 method for class 'antsImage' mean(x, ..., mask = NULL, na.rm = FALSE)
x |
is an object of class |
... |
additional arguments to pass to |
mask |
binary mask of values to subset |
na.rm |
Remove missing values |
img <- makeImage(c(10, 10, 10), rnorm(1000)) mean(img) mean(img, na.rm = TRUE) mean(img > 0) mean(img > 0, na.rm = TRUE) mean(img, mask = img > 0) mean(img, mask = img > 0, na.rm = TRUE) arr <- as.array(img) arr[1, 1, 1] <- NA img <- as.antsImage(arr, reference = img) m <- mean(img) stopifnot(is.nan(m)) mean(img, na.rm = TRUE) m <- mean(0 < img) stopifnot(is.nan(m)) m <- mean(img > 0) # stopifnot(is.nan(m)) mean(img > 0, na.rm = TRUE) m <- mean(img, mask = img > 0) stopifnot(is.nan(m)) mean(img, mask = img > 0, na.rm = TRUE)img <- makeImage(c(10, 10, 10), rnorm(1000)) mean(img) mean(img, na.rm = TRUE) mean(img > 0) mean(img > 0, na.rm = TRUE) mean(img, mask = img > 0) mean(img, mask = img > 0, na.rm = TRUE) arr <- as.array(img) arr[1, 1, 1] <- NA img <- as.antsImage(arr, reference = img) m <- mean(img) stopifnot(is.nan(m)) mean(img, na.rm = TRUE) m <- mean(0 < img) stopifnot(is.nan(m)) m <- mean(img > 0) # stopifnot(is.nan(m)) mean(img > 0, na.rm = TRUE) m <- mean(img, mask = img > 0) stopifnot(is.nan(m)) mean(img, mask = img > 0, na.rm = TRUE)
Overloaded Median for antsImage objects
## S3 method for class 'antsImage' median(x, na.rm = FALSE, ..., mask = NULL)## S3 method for class 'antsImage' median(x, na.rm = FALSE, ..., mask = NULL)
x |
is an object of class |
na.rm |
a logical value indicating whether NA should be removed |
... |
additional arguments to send to |
mask |
is an object of class |
merge images into a multiChannel antsImage
mergeChannels(imageList)mergeChannels(imageList)
imageList |
a list of antsImage objects to merge |
A multiChannel antsImage object
Duda, JT
dims <- c(30, 30) n <- prod(dims) r <- floor(seq(n) / (n) * 255) dim(r) <- dims arr <- r r <- as.antsImage(r) g <- r * 0 b <- r * 0 rgbImage <- mergeChannels(list(r, g, b)) testthat::expect_error(mergeChannels(list(arr, arr)))dims <- c(30, 30) n <- prod(dims) r <- floor(seq(n) / (n) * 255) dim(r) <- dims arr <- r r <- as.antsImage(r) g <- r * 0 b <- r * 0 rgbImage <- mergeChannels(list(r, g, b)) testthat::expect_error(mergeChannels(list(arr, arr)))
This function will copy a list of d-1 images into a d-dimension target image.
This function reverses the operation performed by splitNDImageToList.
mergeListToNDImage(img, imgList)mergeListToNDImage(img, imgList)
img |
input image of class antsImage, last dimension will be split |
imgList |
input list to be merged back into dimension d space |
output list filled with d-1 volumes of class antsImage
Pustina D, Avants B
my4Dimage <- makeImage(c(5, 5, 5, 4), rnorm(5 * 5 * 5 * 4)) my3Dlist <- splitNDImageToList(my4Dimage) my4DimageR <- mergeListToNDImage(my4Dimage, my3Dlist)my4Dimage <- makeImage(c(5, 5, 5, 4), rnorm(5 * 5 * 5 * 4)) my3Dlist <- splitNDImageToList(my4Dimage) my4DimageR <- mergeListToNDImage(my4Dimage, my3Dlist)
This function simplifies calculating image-wide multivariate PCA maps. The model will minimize a matrix energy similar to norm( X - UVt - UranVrant ) where the U are standard design and random effect (intercept) design matrices. The random intercept matrix is only included if repeated measures are indicated.
mild( dataFrame, voxmats, basisK, myFormulaK, smoothingMatrix, iterations = 10, gamma = 1e-06, sparsenessQuantile = 0.5, positivity = c("positive", "negative", "either"), initializationStrategy = 0, repeatedMeasures = NA, orthogonalize = FALSE, verbose = FALSE )mild( dataFrame, voxmats, basisK, myFormulaK, smoothingMatrix, iterations = 10, gamma = 1e-06, sparsenessQuantile = 0.5, positivity = c("positive", "negative", "either"), initializationStrategy = 0, repeatedMeasures = NA, orthogonalize = FALSE, verbose = FALSE )
dataFrame |
This data frame contains all relevant predictors except for the matrices associated with the image variables. |
voxmats |
The named list of matrices that contains the changing predictors. |
basisK |
an integer determining the size of the basis. |
myFormulaK |
This is a character string that defines a valid regression
which in this case should include predictors named as |
smoothingMatrix |
allows parameter smoothing, should be square and same size as input matrix |
iterations |
number of gradient descent iterations |
gamma |
step size for gradient descent |
sparsenessQuantile |
quantile to control sparseness - higher is sparser |
positivity |
restrict to positive or negative solution (beta) weights. choices are positive, negative or either as expressed as a string. |
initializationStrategy |
optional initialization matrix or seed. seed should be a single number; matrix should be a n by k matrix. |
repeatedMeasures |
list of repeated measurement identifiers. this will allow estimates of per identifier intercept. |
orthogonalize |
boolean to control whether we orthogonalize the v |
verbose |
boolean to control verbosity of output |
A list of different matrices that contain names derived from the formula and the coefficients of the regression model.
BB Avants.
set.seed(1500) nsub <- 12 npix <- 100 outcome <- rnorm(nsub) covar <- rnorm(nsub) mat <- replicate(npix, rnorm(nsub)) mat2 <- replicate(npix, rnorm(nsub)) nk <- 3 myform <- paste( " vox2 ~ covar + vox + ", paste0("mildBasis", 1:nk, collapse = "+") ) # optional covariates df <- data.frame(outcome = outcome, covar = covar) result <- mild(df, list(vox = mat, vox2 = mat2), basisK = 3, myform, initializationStrategy = 10 ) result <- mild(df, list(vox = mat, vox2 = mat2), basisK = 3, myform, initializationStrategy = 4 ) myumat <- svd(mat2, nv = 0, nu = 3)$u result <- mild(df, list(vox = mat, vox2 = mat2), basisK = 3, myform, initializationStrategy = 0 )set.seed(1500) nsub <- 12 npix <- 100 outcome <- rnorm(nsub) covar <- rnorm(nsub) mat <- replicate(npix, rnorm(nsub)) mat2 <- replicate(npix, rnorm(nsub)) nk <- 3 myform <- paste( " vox2 ~ covar + vox + ", paste0("mildBasis", 1:nk, collapse = "+") ) # optional covariates df <- data.frame(outcome = outcome, covar = covar) result <- mild(df, list(vox = mat, vox2 = mat2), basisK = 3, myform, initializationStrategy = 10 ) result <- mild(df, list(vox = mat, vox2 = mat2), basisK = 3, myform, initializationStrategy = 4 ) myumat <- svd(mat2, nv = 0, nu = 3)$u result <- mild(df, list(vox = mat, vox2 = mat2), basisK = 3, myform, initializationStrategy = 0 )
This function simplifies calculating image-wide multivariate beta maps from linear models. Image-based variables are stored in the input matrix list. They should be named consistently in the input formula and in the image list. If they are not, an error will be thrown. All input matrices should have the same number of rows and columns. The model will minimize a matrix energy similar to norm( X - UVt - UranVrant ) where the U are standard design and random effect (intercept) design matrices. The random intercept matrix is only included if repeated measures are indicated.
milr( dataFrame, voxmats, myFormula, smoothingMatrix, iterations = 10, gamma = 1e-06, sparsenessQuantile, positivity = c("positive", "negative", "either"), repeatedMeasures = NA, orthogonalize = FALSE, verbose = FALSE )milr( dataFrame, voxmats, myFormula, smoothingMatrix, iterations = 10, gamma = 1e-06, sparsenessQuantile, positivity = c("positive", "negative", "either"), repeatedMeasures = NA, orthogonalize = FALSE, verbose = FALSE )
dataFrame |
This data frame contains all relevant predictors except for the matrices associated with the image variables. |
voxmats |
The named list of matrices that contains the changing predictors. |
myFormula |
This is a character string that defines a valid regression formula. |
smoothingMatrix |
allows parameter smoothing, should be square and same size as input matrix |
iterations |
number of gradient descent iterations |
gamma |
step size for gradient descent |
sparsenessQuantile |
quantile to control sparseness - higher is sparser |
positivity |
restrict to positive or negative solution (beta) weights. choices are positive, negative or either as expressed as a string. |
repeatedMeasures |
list of repeated measurement identifiers. this will allow estimates of per identifier intercept. |
orthogonalize |
boolean to control whether we orthogonalize the v |
verbose |
boolean to control verbosity of output |
A list of different matrices that contain names derived from the formula and the coefficients of the regression model.
BB Avants.
set.seed(1500) nsub <- 12 npix <- 100 outcome <- rnorm(nsub) covar <- rnorm(nsub) mat <- replicate(npix, rnorm(nsub)) mat2 <- replicate(npix, rnorm(nsub)) myform <- " vox2 ~ covar + vox " df <- data.frame(outcome = outcome, covar = covar) result <- milr(df, list(vox = mat, vox2 = mat2), myform) ## Not run: # a 2nd example with 3 modalities imageIDs <- c("r16", "r27", "r30", "r62", "r64", "r85") images <- list() feature1Images <- list() feature2Images <- list() feature3Images <- list() ref <- antsImageRead(getANTsRData("r16")) mask <- ref * 0 for (i in 1:length(imageIDs)) { cat("Processing image", imageIDs[i], "\n") tar <- antsImageRead(getANTsRData(imageIDs[i])) images[[i]] <- tar mask <- mask + tar feature1Images[[i]] <- iMath(images[[i]], "Grad", 1.0) feature2Images[[i]] <- iMath(images[[i]], "Laplacian", 1.0) feature3Images[[i]] <- reflectImage(tar, axis = 0, tx = "Affine")$warpedmovout } i <- 1 mask <- getMask(mask) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 23, sigma = 100.0) mat <- imageListToMatrix(images, mask) mat2 <- imageListToMatrix(feature1Images, mask) mat3 <- imageListToMatrix(feature3Images, mask) myscale <- function(x) { return(scale(x, center = TRUE, scale = T)) } x <- list(x1 = myscale(mat[-5, ]), x2 = myscale(mat2[-5, ]), x3 = myscale(mat3[-5, ])) df <- data.frame(m1 = rowMeans(x$x1), m2 = rowMeans(x$x2), m3 = rowMeans(x$x3)) myform <- " x1 ~ x2 + x3 + m2 + m3 " result <- milr(df, x, myform, iterations = 32, smoothingMatrix = smoomat, gamma = 1e-1, verbose = T ) k <- 1 mm <- makeImage(mask, (result$prediction[k, ])) %>% iMath("Normalize") tar <- makeImage(mask, x$x1[k, ]) plot(mm, doCropping = FALSE) plot(tar, doCropping = FALSE) cor.test(result$prediction[k, ], x$x1[k, ]) myol <- makeImage(mask, abs(result$v[, "x2"])) %>% iMath("Normalize") plot(tar, myol, doCropping = FALSE) myol <- makeImage(mask, abs(result$v[, "m3"])) %>% iMath("Normalize") plot(tar, myol, doCropping = FALSE) result <- milr(df, x, myform, iterations = 11, smoothingMatrix = smoomat, sparsenessQuantile = 0.5, positivity = "positive", gamma = 1e-2, verbose = T ) myol <- makeImage(mask, abs(result$v[, "x2"])) %>% iMath("Normalize") plot(tar, myol, doCropping = FALSE, window.overlay = c(0.1, 1)) mm <- makeImage(mask, (result$prediction[k, ])) %>% iMath("Normalize") tar <- makeImage(mask, x$x1[k, ]) plot(mm, doCropping = FALSE) plot(tar, doCropping = FALSE) cor.test(result$prediction[k, ], x$x1[k, ]) # univariate outcome myform <- " m1 ~ x2 + x3 + m2 + m3 " result <- milr(df, x, myform, iterations = 11, smoothingMatrix = smoomat, gamma = 1e-2, verbose = T ) ## End(Not run)set.seed(1500) nsub <- 12 npix <- 100 outcome <- rnorm(nsub) covar <- rnorm(nsub) mat <- replicate(npix, rnorm(nsub)) mat2 <- replicate(npix, rnorm(nsub)) myform <- " vox2 ~ covar + vox " df <- data.frame(outcome = outcome, covar = covar) result <- milr(df, list(vox = mat, vox2 = mat2), myform) ## Not run: # a 2nd example with 3 modalities imageIDs <- c("r16", "r27", "r30", "r62", "r64", "r85") images <- list() feature1Images <- list() feature2Images <- list() feature3Images <- list() ref <- antsImageRead(getANTsRData("r16")) mask <- ref * 0 for (i in 1:length(imageIDs)) { cat("Processing image", imageIDs[i], "\n") tar <- antsImageRead(getANTsRData(imageIDs[i])) images[[i]] <- tar mask <- mask + tar feature1Images[[i]] <- iMath(images[[i]], "Grad", 1.0) feature2Images[[i]] <- iMath(images[[i]], "Laplacian", 1.0) feature3Images[[i]] <- reflectImage(tar, axis = 0, tx = "Affine")$warpedmovout } i <- 1 mask <- getMask(mask) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 23, sigma = 100.0) mat <- imageListToMatrix(images, mask) mat2 <- imageListToMatrix(feature1Images, mask) mat3 <- imageListToMatrix(feature3Images, mask) myscale <- function(x) { return(scale(x, center = TRUE, scale = T)) } x <- list(x1 = myscale(mat[-5, ]), x2 = myscale(mat2[-5, ]), x3 = myscale(mat3[-5, ])) df <- data.frame(m1 = rowMeans(x$x1), m2 = rowMeans(x$x2), m3 = rowMeans(x$x3)) myform <- " x1 ~ x2 + x3 + m2 + m3 " result <- milr(df, x, myform, iterations = 32, smoothingMatrix = smoomat, gamma = 1e-1, verbose = T ) k <- 1 mm <- makeImage(mask, (result$prediction[k, ])) %>% iMath("Normalize") tar <- makeImage(mask, x$x1[k, ]) plot(mm, doCropping = FALSE) plot(tar, doCropping = FALSE) cor.test(result$prediction[k, ], x$x1[k, ]) myol <- makeImage(mask, abs(result$v[, "x2"])) %>% iMath("Normalize") plot(tar, myol, doCropping = FALSE) myol <- makeImage(mask, abs(result$v[, "m3"])) %>% iMath("Normalize") plot(tar, myol, doCropping = FALSE) result <- milr(df, x, myform, iterations = 11, smoothingMatrix = smoomat, sparsenessQuantile = 0.5, positivity = "positive", gamma = 1e-2, verbose = T ) myol <- makeImage(mask, abs(result$v[, "x2"])) %>% iMath("Normalize") plot(tar, myol, doCropping = FALSE, window.overlay = c(0.1, 1)) mm <- makeImage(mask, (result$prediction[k, ])) %>% iMath("Normalize") tar <- makeImage(mask, x$x1[k, ]) plot(mm, doCropping = FALSE) plot(tar, doCropping = FALSE) cor.test(result$prediction[k, ], x$x1[k, ]) # univariate outcome myform <- " m1 ~ x2 + x3 + m2 + m3 " result <- milr(df, x, myform, iterations = 11, smoothingMatrix = smoomat, gamma = 1e-2, verbose = T ) ## End(Not run)
This function computes a prediction or low-dimensional embedding, given
milr output. It will return a predictive model if the outcome variable
is a scalar. Otherwise, it will return a low-dimensional embedding without
a specific predictive model.
milr.predict( milrResult, dataFrameTrain, voxmatsTrain, dataFrameTest, voxmatsTest, myFormula )milr.predict( milrResult, dataFrameTrain, voxmatsTrain, dataFrameTest, voxmatsTest, myFormula )
milrResult |
This output form milr |
dataFrameTrain |
This data frame contains all relevant predictors in the training data except for the matrices associated with the image variables. |
voxmatsTrain |
The named list of matrices that contains the changing predictors. |
dataFrameTest |
This data frame contains all relevant predictors in the training data except for the matrices associated with the image variables in test data. |
voxmatsTest |
The named list of matrices that contains the changing predictors in test data. |
myFormula |
This is a character string that defines a valid regression formula. |
the predicted matrix.
BB Avants.
nsub <- 24 npix <- 100 outcome <- rnorm(nsub) covar <- rnorm(nsub) mat <- replicate(npix, rnorm(nsub)) mat2 <- replicate(npix, rnorm(nsub)) mat3 <- replicate(npix, rnorm(nsub)) myform <- " vox2 ~ covar + vox + vox3 " istr <- c(rep(TRUE, round(nsub * 2 / 3)), rep(FALSE, nsub - round(nsub * 2 / 3))) df <- data.frame(outcome = outcome, covar = covar) ltr <- list(vox = mat[istr, ], vox2 = mat2[istr, ], vox3 = mat3[istr, ]) lte <- list(vox = mat[!istr, ], vox2 = mat2[!istr, ], vox3 = mat3[!istr, ]) result <- milr(df[istr, ], ltr, myform) pred <- milr.predict(result, df[istr, ], ltr, df[!istr, ], lte, myform)nsub <- 24 npix <- 100 outcome <- rnorm(nsub) covar <- rnorm(nsub) mat <- replicate(npix, rnorm(nsub)) mat2 <- replicate(npix, rnorm(nsub)) mat3 <- replicate(npix, rnorm(nsub)) myform <- " vox2 ~ covar + vox + vox3 " istr <- c(rep(TRUE, round(nsub * 2 / 3)), rep(FALSE, nsub - round(nsub * 2 / 3))) df <- data.frame(outcome = outcome, covar = covar) ltr <- list(vox = mat[istr, ], vox2 = mat2[istr, ], vox3 = mat3[istr, ]) lte <- list(vox = mat[!istr, ], vox2 = mat2[!istr, ], vox3 = mat3[!istr, ]) result <- milr(df[istr, ], ltr, myform) pred <- milr.predict(result, df[istr, ], ltr, df[!istr, ], lte, myform)
mni2tal for converting from ch2/mni space to tal - very approximate.
mni2tal(xin = 0)mni2tal(xin = 0)
xin |
point in mni152 space. |
This is a standard approach but it's not very accurate.
output point in approximate Talairach space.
Matthew Brett, adapted for ANTsR by B Avants
http://imaging.mrc-cbu.cam.ac.uk/imaging/MniTalairach
mni2tal(c(10, 12, 14))mni2tal(c(10, 12, 14))
Apply imaage morphological operations
morphology( input, operation, radius, type = "binary", value = 1, shape = "ball", radiusIsParametric = FALSE, thickness = 1, lines = 3, includeCenter = FALSE )morphology( input, operation, radius, type = "binary", value = 1, shape = "ball", radiusIsParametric = FALSE, thickness = 1, lines = 3, includeCenter = FALSE )
input |
input image |
operation |
operation to apply
|
radius |
radius of structuring element |
type |
type of morphology
|
value |
value to operation on (type='binary' only) |
shape |
shape of the structuring element ( type='binary' only )
|
radiusIsParametric |
used parametric radius boolean (shape='ball' and shape='annulus' only) |
thickness |
thickness (shape='annulus' only) |
lines |
number of lines in polygon (shape='polygon' only) |
includeCenter |
include center of annulus boolean (shape='annulus' only) |
antsImage is output
Avants BB
fi <- antsImageRead(getANTsRData("r16"), 2) mask <- getMask(fi) dilatedBall <- morphology(mask, operation = "dilate", radius = 3, type = "binary", shape = "ball" ) erodedBox <- morphology(mask, operation = "erode", radius = 3, type = "binary", shape = "box" ) openedAnnulus <- morphology(mask, operation = "open", radius = 5, type = "binary", shape = "annulus", thickness = 2 ) out <- morphology(mask, operation = "open", radius = 5, type = "binary", shape = "polygon") out <- morphology(mask, operation = "open", radius = 5, type = "binary", shape = "cross") out <- morphology(mask, operation = "close", radius = 5, type = "binary", shape = "polygon") out <- morphology(mask, operation = "erode", radius = 5, type = "binary", shape = "polygon") out <- morphology(mask, operation = "dilate", radius = 5, type = "binary", shape = "polygon") testthat::expect_error(morphology(mask, operation = "open", radius = 5, shape = "hey"))fi <- antsImageRead(getANTsRData("r16"), 2) mask <- getMask(fi) dilatedBall <- morphology(mask, operation = "dilate", radius = 3, type = "binary", shape = "ball" ) erodedBox <- morphology(mask, operation = "erode", radius = 3, type = "binary", shape = "box" ) openedAnnulus <- morphology(mask, operation = "open", radius = 5, type = "binary", shape = "annulus", thickness = 2 ) out <- morphology(mask, operation = "open", radius = 5, type = "binary", shape = "polygon") out <- morphology(mask, operation = "open", radius = 5, type = "binary", shape = "cross") out <- morphology(mask, operation = "close", radius = 5, type = "binary", shape = "polygon") out <- morphology(mask, operation = "erode", radius = 5, type = "binary", shape = "polygon") out <- morphology(mask, operation = "dilate", radius = 5, type = "binary", shape = "polygon") testthat::expect_error(morphology(mask, operation = "open", radius = 5, shape = "hey"))
Represents multiscale feature images as a neighborhood and uses the features to build a random forest segmentation model from an image population
mrvnrfs( y, x, labelmasks, rad = NA, nsamples = 1, ntrees = 500, multiResSchedule = c(4, 2, 1), asFactors = TRUE, voxchunk = 50000, ... )mrvnrfs( y, x, labelmasks, rad = NA, nsamples = 1, ntrees = 500, multiResSchedule = c(4, 2, 1), asFactors = TRUE, voxchunk = 50000, ... )
y |
list of training labels. either an image or numeric value |
x |
a list of lists where each list contains feature images |
labelmasks |
a mask (or list of masks) used to define where the samples will come from. Note, two labels (e.g., GM and WM) will double the number of samples from each feature images. If the mask is binary, samples are selected randomly within 1 values. |
rad |
vector of dimensionality d define nhood radius |
nsamples |
(per subject to enter training) |
ntrees |
(for the random forest model) |
multiResSchedule |
an integer vector defining multi-res levels |
asFactors |
boolean - treat the y entries as factors |
voxchunk |
value of maximal voxels to predict at once. This value is used to split the prediction into smaller chunks such that memory requirements do not become too big |
... |
arguments to pass to |
list a 4-list with the rf model, training vector, feature matrix and the random mask
Avants BB, Tustison NJ, Pustina D
mask <- makeImage(c(10, 10), 0) mask[3:6, 3:6] <- 1 mask[5, 5:6] <- 2 ilist <- list() lablist <- list() inds <- 1:5 scl <- 0.33 # a noise parameter for (predtype in c("label", "scalar")) { for (i in inds) { img <- antsImageClone(mask) imgb <- antsImageClone(mask) limg <- antsImageClone(mask) if (predtype == "label") { # 4 class prediction img[3:6, 3:6] <- rnorm(16) * scl + (i %% 4) + scl * mean(rnorm(1)) imgb[3:6, 3:6] <- rnorm(16) * scl + (i %% 4) + scl * mean(rnorm(1)) limg[3:6, 3:6] <- (i %% 4) + 1 # the label image is constant } if (predtype == "scalar") { img[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) imgb[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) limg <- i^2.0 # a real outcome } ilist[[i]] <- list(img, imgb) # two features lablist[[i]] <- limg } rad <- rep(1, 2) mr <- c(1.5, 1) rfm <- mrvnrfs(lablist, ilist, mask, rad = rad, multiResSchedule = mr, asFactors = (predtype == "label") ) rfmresult <- mrvnrfs.predict(rfm$rflist, ilist, mask, rad = rad, asFactors = (predtype == "label"), multiResSchedule = mr ) if (predtype == "scalar") { print(cor(unlist(lablist), unlist(rfmresult$seg))) } } # end predtype loopmask <- makeImage(c(10, 10), 0) mask[3:6, 3:6] <- 1 mask[5, 5:6] <- 2 ilist <- list() lablist <- list() inds <- 1:5 scl <- 0.33 # a noise parameter for (predtype in c("label", "scalar")) { for (i in inds) { img <- antsImageClone(mask) imgb <- antsImageClone(mask) limg <- antsImageClone(mask) if (predtype == "label") { # 4 class prediction img[3:6, 3:6] <- rnorm(16) * scl + (i %% 4) + scl * mean(rnorm(1)) imgb[3:6, 3:6] <- rnorm(16) * scl + (i %% 4) + scl * mean(rnorm(1)) limg[3:6, 3:6] <- (i %% 4) + 1 # the label image is constant } if (predtype == "scalar") { img[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) imgb[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) limg <- i^2.0 # a real outcome } ilist[[i]] <- list(img, imgb) # two features lablist[[i]] <- limg } rad <- rep(1, 2) mr <- c(1.5, 1) rfm <- mrvnrfs(lablist, ilist, mask, rad = rad, multiResSchedule = mr, asFactors = (predtype == "label") ) rfmresult <- mrvnrfs.predict(rfm$rflist, ilist, mask, rad = rad, asFactors = (predtype == "label"), multiResSchedule = mr ) if (predtype == "scalar") { print(cor(unlist(lablist), unlist(rfmresult$seg))) } } # end predtype loop
Represents multiscale feature images as a neighborhood and uses the features to apply a random forest segmentation model to a new image
mrvnrfs.predict( rflist, x, labelmasks, rad = NA, multiResSchedule = c(4, 2, 1), asFactors = TRUE, voxchunk = 60000 )mrvnrfs.predict( rflist, x, labelmasks, rad = NA, multiResSchedule = c(4, 2, 1), asFactors = TRUE, voxchunk = 60000 )
rflist |
a list of random forest models from mrvnrfs |
x |
a list of lists where each list contains feature images |
labelmasks |
a mask (or list of masks) used to define the area to predict. This is used to save time by contstrain the prediction in within the brain. |
rad |
vector of dimensionality d define nhood radius |
multiResSchedule |
an integer vector defining multi-res levels |
asFactors |
boolean - treat the y entries as factors |
voxchunk |
value of maximal voxels to predict at once. This value is used to split the prediction into smaller chunks such that memory requirements do not become too big |
list a 4-list with the rf model, training vector, feature matrix and the random mask
Avants BB, Tustison NJ, Pustina D
A data frame label numbers and names for medial temporal lobe regions.
mtl_labelsmtl_labels
A data frame with columns: Label, Description.
Converts a set of multichannel images (e.g. deformation fields ) to a matrix to enable various forms of PCA. Returns the components of shape variability and variance explained. May employ different decomposition methods (WIP).
multichannelPCA( x, mask, k = NA, pcaOption = "PCA", auxiliaryModality, center = TRUE, sigma = NA, verbose = FALSE )multichannelPCA( x, mask, k = NA, pcaOption = "PCA", auxiliaryModality, center = TRUE, sigma = NA, verbose = FALSE )
x |
list containing multichannel images all of the same size |
mask |
mask to apply to the multichannel images |
k |
rank to use |
pcaOption |
currently only PCA and randPCA, latter being much faster. We also allow fastICA. |
auxiliaryModality |
if you pass this matrix, then will do CCA. This will only work with one option. |
center |
subtract the mean column vector. |
sigma |
parameter for kernel PCA. |
verbose |
produces more explanatory output. |
list of the pca output and conversion to multichannel images
Avants BB
img1 <- antsImageRead(getANTsRData("r16")) %>% resampleImage(c(4, 4)) img2 <- antsImageRead(getANTsRData("r64")) %>% resampleImage(c(4, 4)) img3 <- antsImageRead(getANTsRData("r27")) %>% resampleImage(c(4, 4)) img4 <- antsImageRead(getANTsRData("r30")) %>% resampleImage(c(4, 4)) reg1 <- antsRegistration(img1, img2, "SyN") reg2 <- antsRegistration(img1, img3, "SyN") reg3 <- antsRegistration(img1, img4, "SyN") w1 <- antsImageRead(reg1$fwdtransforms[1]) w2 <- antsImageRead(reg2$fwdtransforms[1]) w3 <- antsImageRead(reg3$fwdtransforms[1]) mask <- getMask(img1) x <- list(w1, w2, w3) dpca <- multichannelPCA(x, mask) warpTx <- antsrTransformFromDisplacementField(dpca$pcaWarps[[1]]) warped <- applyAntsrTransform(warpTx, data = img1, reference = img1)img1 <- antsImageRead(getANTsRData("r16")) %>% resampleImage(c(4, 4)) img2 <- antsImageRead(getANTsRData("r64")) %>% resampleImage(c(4, 4)) img3 <- antsImageRead(getANTsRData("r27")) %>% resampleImage(c(4, 4)) img4 <- antsImageRead(getANTsRData("r30")) %>% resampleImage(c(4, 4)) reg1 <- antsRegistration(img1, img2, "SyN") reg2 <- antsRegistration(img1, img3, "SyN") reg3 <- antsRegistration(img1, img4, "SyN") w1 <- antsImageRead(reg1$fwdtransforms[1]) w2 <- antsImageRead(reg2$fwdtransforms[1]) w3 <- antsImageRead(reg3$fwdtransforms[1]) mask <- getMask(img1) x <- list(w1, w2, w3) dpca <- multichannelPCA(x, mask) warpTx <- antsrTransformFromDisplacementField(dpca$pcaWarps[[1]]) warped <- applyAntsrTransform(warpTx, data = img1, reference = img1)
antsImage to a vector.Employs a mask to flatten each channel of a multi-channel image into a contiguous piece of a vector.
multichannelToVector(multichannelimage, mask)multichannelToVector(multichannelimage, mask)
multichannelimage |
input multichannel image |
mask |
mask of same dimensionality as multichannelimage |
vector is output
Avants BB
# see vectorToMultichannel# see vectorToMultichannel
Grep entries with a vector search parameters
multigrep(x, desc, intersect = FALSE)multigrep(x, desc, intersect = FALSE)
x |
a vector of search terms |
desc |
target vector of items to be searched |
intersect |
boolean whether to use intersection or union otherwise |
result of grep (indices of desc that match x)
Avants BB
Wraps calls to iMath binary morphology. Additionally, dilation and closing operations preserve pre-existing labels. The choices of operation are:
multiLabelMorphology( labelsIn, operation, radius, dilationMask = NULL, labelList = NA )multiLabelMorphology( labelsIn, operation, radius, dilationMask = NULL, labelList = NA )
labelsIn |
Input image should contain only 0 for background and positive integers for labels. |
operation |
One of |
radius |
radius of the morphological operation. |
dilationMask |
Optional binary mask to constrain dilation only (eg dilate cortical label into WM). |
labelList |
Optional list of labels, to perform operation upon. Defaults to all unique
intensities in |
Dilation: dilates all labels sequentially, but does not overwrite original labels. This reduces dependence on the intensity ordering of adjoining labels. Ordering dependence can still arise if two or more labels dilate into the same space - in this case, the label with the lowest intensity is retained. With a mask, dilated labels are multiplied by the mask and then added to the original label, thus restricting dilation to the mask region.
Erosion: Erodes labels independently, equivalent to calling iMath iteratively.
Closing: Close holes in each label sequentially, but does not overwrite original labels. Opening: Opens each label independently, equivalent to calling iMath iteratively.
processed labels, of type antsImage.
Cook PA
img <- antsImageRead(getANTsRData("r16"), 2) labels <- getMask(img, 1, 150) + getMask(img, 151, 225) * 2 labelsDilated <- multiLabelMorphology(labels, "MD", 2) # should see original label regions preserved in dilated version # label N should have mean N and 0 variance labelStats(labelsDilated, labels)img <- antsImageRead(getANTsRData("r16"), 2) labels <- getMask(img, 1, 150) + getMask(img, 151, 225) * 2 labelsDilated <- multiLabelMorphology(labels, "MD", 2) # should see original label regions preserved in dilated version # label N should have mean N and 0 variance labelStats(labelsDilated, labels)
Represents feature images as a neighborhood across scales to build a random forest prediction from an image population. A use case for this function is to predict cognition from multiple image features, e.g. from the voxelwise FA of the corpus callosum and, in parallel, voxelwise measurements of the volume of the inferior frontal gyrus.
multiResRandomForestRegression( y, x, labelmasks, rad = NA, nsamples = 10, multiResSchedule = c(0), ntrees = 500 )multiResRandomForestRegression( y, x, labelmasks, rad = NA, nsamples = 10, multiResSchedule = c(0), ntrees = 500 )
y |
vector of scalar values or labels. if a factor, do classification, otherwise regression. |
x |
a list of lists where each list contains feature images |
labelmasks |
a list of masks where each mask defines the image space for the given list and the number of parallel predictors. more labels means more predictors. alternatively, separate masks may be used for each feature in which case this should be a list of lists. see examples. |
rad |
vector of dimensionality d define nhood radius |
nsamples |
(per subject to enter training) |
multiResSchedule |
an integer vector defining multi-res levels |
ntrees |
(for the random forest model) |
list with a random forest model, a vector identifying which rows correspond to which subjects and a prediction vector.
Avants BB, Tustison NJ
Pustina, D, et al. Automated segmentation of chronic stroke lesions using LINDA: Lesion Identification with Neighborhood Data Analysis, Human Brain Mapping, 2016. (related work, not identical)
getMultiResFeatureMatrix mrvnrfs
mask <- makeImage(c(100, 100), 0) mask[30:60, 30:60] <- 1 mask[35:45, 50:60] <- 2 ilist <- list() masklist <- list() inds <- 1:8 yvec <- rep(0, length(inds)) scl <- 0.33 # a noise parameter for (i in inds) { img <- antsImageClone(mask) imgb <- antsImageClone(mask) limg <- antsImageClone(mask) img[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) imgb[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) ilist[[i]] <- list(img, imgb) # two features yvec[i] <- i^2.0 # a real outcome masklist[[i]] <- antsImageClone(mask) } r <- c(1, 1) mr <- c(2, 0) featMat <- getMultiResFeatureMatrix(ilist[[1]], masklist[[1]], rad = r, , multiResSchedule = mr ) rfm <- multiResRandomForestRegression( yvec, ilist, masklist, rad = r, multiResSchedule = mr ) preds <- predict(rfm, newdata = featMat) ## Not run: # data: https://github.com/ANTsX/ANTsTutorial/tree/master/phantomData fns <- Sys.glob("phantom*wmgm.jpg") ilist <- imageFileNames2ImageList(fns) masklist <- list() flist <- list() for (i in 1:length(fns)) { # 2 labels means 2 sets of side by side predictors and features at each scale locseg <- kmeansSegmentation(ilist[[i]], 2)$segmentation masklist[[i]] <- list(locseg, locseg %>% thresholdImage(2, 2), locseg) flist[[i]] <- list( ilist[[i]], ilist[[i]] %>% iMath("Laplacian", 1), ilist[[i]] %>% iMath("Grad", 1) ) } yvec <- factor(rep(c(1, 2), each = 4)) # classification r <- c(1, 1) mr <- c(2, 1, 0) ns <- 50 trn <- c(1:3, 6:8) ytrain <- yvec[trn] ftrain <- flist[trn] mtrain <- masklist[trn] mrrfr <- multiResRandomForestRegression(ytrain, ftrain, mtrain, rad = c(1, 1), nsamples = ns, multiResSchedule = mr ) mypreds <- rep(NA, length(fns)) mymode <- function(x) { ux <- unique(x) ux[which.max(tabulate(match(x, ux)))] } for (i in 4:5) # test set { fmat <- getMultiResFeatureMatrix(flist[[i]], masklist[[i]], rad = r, multiResSchedule = mr, nsamples = ns ) myp <- predict(mrrfr, newdata = fmat) mypreds[i] <- mymode(myp) # get the most frequent observation # use median or mean for continuous predictions } print("predicted") print(mypreds[-trn]) print("ground truth") print(yvec[-trn]) ## End(Not run)mask <- makeImage(c(100, 100), 0) mask[30:60, 30:60] <- 1 mask[35:45, 50:60] <- 2 ilist <- list() masklist <- list() inds <- 1:8 yvec <- rep(0, length(inds)) scl <- 0.33 # a noise parameter for (i in inds) { img <- antsImageClone(mask) imgb <- antsImageClone(mask) limg <- antsImageClone(mask) img[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) imgb[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) ilist[[i]] <- list(img, imgb) # two features yvec[i] <- i^2.0 # a real outcome masklist[[i]] <- antsImageClone(mask) } r <- c(1, 1) mr <- c(2, 0) featMat <- getMultiResFeatureMatrix(ilist[[1]], masklist[[1]], rad = r, , multiResSchedule = mr ) rfm <- multiResRandomForestRegression( yvec, ilist, masklist, rad = r, multiResSchedule = mr ) preds <- predict(rfm, newdata = featMat) ## Not run: # data: https://github.com/ANTsX/ANTsTutorial/tree/master/phantomData fns <- Sys.glob("phantom*wmgm.jpg") ilist <- imageFileNames2ImageList(fns) masklist <- list() flist <- list() for (i in 1:length(fns)) { # 2 labels means 2 sets of side by side predictors and features at each scale locseg <- kmeansSegmentation(ilist[[i]], 2)$segmentation masklist[[i]] <- list(locseg, locseg %>% thresholdImage(2, 2), locseg) flist[[i]] <- list( ilist[[i]], ilist[[i]] %>% iMath("Laplacian", 1), ilist[[i]] %>% iMath("Grad", 1) ) } yvec <- factor(rep(c(1, 2), each = 4)) # classification r <- c(1, 1) mr <- c(2, 1, 0) ns <- 50 trn <- c(1:3, 6:8) ytrain <- yvec[trn] ftrain <- flist[trn] mtrain <- masklist[trn] mrrfr <- multiResRandomForestRegression(ytrain, ftrain, mtrain, rad = c(1, 1), nsamples = ns, multiResSchedule = mr ) mypreds <- rep(NA, length(fns)) mymode <- function(x) { ux <- unique(x) ux[which.max(tabulate(match(x, ux)))] } for (i in 4:5) # test set { fmat <- getMultiResFeatureMatrix(flist[[i]], masklist[[i]], rad = r, multiResSchedule = mr, nsamples = ns ) myp <- predict(mrrfr, newdata = fmat) mypreds[i] <- mymode(myp) # get the most frequent observation # use median or mean for continuous predictions } print("predicted") print(mypreds[-trn]) print("ground truth") print(yvec[-trn]) ## End(Not run)
Maggioni's multi-scale SVD algorithm explores the dimensionality of a dataset by investigating the change in eigenvalues with respect to a scale parameter. The scale parameter is defined by the radius of a ball that sits at each point in the data. The ball, at each scale, is moved across the dataset and SVD is computed within the intersection of the ball and the data at each point. The shape in this collection of eigenvalues, with respect to scale, enables us to estimate both signal and noise dimensionality and scale. The estimate can be computed efficiently on large datasets if the sampling is chosen appropriately. The challenge, in this algorithm, is classifying the dimensions of noise, curvature and data. This classification currently uses variations on heuristics suggested in work by Maggioni et al.
multiscaleSVD(x, r, locn, nev, knn = 0, verbose = FALSE, plot = 0)multiscaleSVD(x, r, locn, nev, knn = 0, verbose = FALSE, plot = 0)
x |
input matrix, should be n (samples) by p (measurements) |
r |
radii to explore |
locn |
number of local samples to take at each scale |
nev |
maximum number of eigenvalues to compute |
knn |
randomly sample neighbors to assist with large datasets. set k with this value. |
verbose |
boolean to control verbosity of output |
plot |
boolean to control whether we plot results. its value determines which eigenvector off which to base the scale of the y-axis.' |
list with a vector of tangent, curvature, noise dimensionality and a a dataframe containing eigenvalues across scale, in correspondence with r:
The tangent, curvature and noise dimensionality vector. The data dimensionality is the first entry, the curvature dimensionality exists from the second to the first entry of the noise vector.
Dimensionalities where the noise may begin. These are candidate cutoffs but may contain some curvature information.'
eigenvalues across scale
data-driven clustering of the eigenvalues
Avants BB
Maggioni, M., et al. "Multiscale data geometry."
sphereDim <- 9 embeddDim <- 100 n <- 1000 if (usePkg("pracma")) { set.seed(20190919) sphereData <- pracma::rands(n, sphereDim, 1.) mysig <- 0.1 spherEmbed <- matrix(rnorm(n * embeddDim, 0, mysig), nrow = n, ncol = embeddDim) spherEmbed[, 1:ncol(sphereData)] <- spherEmbed[, 1:ncol(sphereData)] + sphereData myr <- seq(1.0, 2.2, 0.05) # scales at which to sample mymssvd <- multiscaleSVD(spherEmbed, myr, locn = 5, nev = 20, plot = 1) if (getRversion() < "3.6.0") { testthat::expect_equal(mymssvd$noiseCutoffs, c(10, 11)) cm <- unname(colMeans(mymssvd$evalsVsScale[11:25, ])) testthat::expect_equal( cm, c( 0.133651668406975, 0.0985695151401464, 0.0914110478052329, 0.086272017653314, 0.081188302173622, 0.0766100356616153, 0.0719736252996842, 0.067588745051721, 0.0622331185687704, 0.0415236318358749, 0.0192976885668337, 0.0183063537558787, 0.0174990088862745, 0.0170012938275551, 0.0163859378707545, 0.0158265354487181, 0.0153357773252783, 0.0147933538908736, 0.0143510807701235, 0.0140473978346935 ) ) } else { testthat::expect_equal(mymssvd$noiseCutoffs, c(11, 15)) cm <- unname(colMeans(mymssvd$evalsVsScale[13:25, ])) testthat::expect_equal( cm, c( 0.138511257441516, 0.106071822485487, 0.0989441114152412, 0.092910922851038, 0.0877970523897918, 0.0832570763653118, 0.0782599820599334, 0.0734433988152632, 0.0678992413676906, 0.0432283615430504, 0.0202481578919003, 0.0191747572787057, 0.0185718929604774, 0.0178301092823977, 0.0172423799670431, 0.0166981650233669, 0.0162072551503541, 0.015784555784915, 0.0153600119986575, 0.0149084240854556 ) ) } }sphereDim <- 9 embeddDim <- 100 n <- 1000 if (usePkg("pracma")) { set.seed(20190919) sphereData <- pracma::rands(n, sphereDim, 1.) mysig <- 0.1 spherEmbed <- matrix(rnorm(n * embeddDim, 0, mysig), nrow = n, ncol = embeddDim) spherEmbed[, 1:ncol(sphereData)] <- spherEmbed[, 1:ncol(sphereData)] + sphereData myr <- seq(1.0, 2.2, 0.05) # scales at which to sample mymssvd <- multiscaleSVD(spherEmbed, myr, locn = 5, nev = 20, plot = 1) if (getRversion() < "3.6.0") { testthat::expect_equal(mymssvd$noiseCutoffs, c(10, 11)) cm <- unname(colMeans(mymssvd$evalsVsScale[11:25, ])) testthat::expect_equal( cm, c( 0.133651668406975, 0.0985695151401464, 0.0914110478052329, 0.086272017653314, 0.081188302173622, 0.0766100356616153, 0.0719736252996842, 0.067588745051721, 0.0622331185687704, 0.0415236318358749, 0.0192976885668337, 0.0183063537558787, 0.0174990088862745, 0.0170012938275551, 0.0163859378707545, 0.0158265354487181, 0.0153357773252783, 0.0147933538908736, 0.0143510807701235, 0.0140473978346935 ) ) } else { testthat::expect_equal(mymssvd$noiseCutoffs, c(11, 15)) cm <- unname(colMeans(mymssvd$evalsVsScale[13:25, ])) testthat::expect_equal( cm, c( 0.138511257441516, 0.106071822485487, 0.0989441114152412, 0.092910922851038, 0.0877970523897918, 0.0832570763653118, 0.0782599820599334, 0.0734433988152632, 0.0678992413676906, 0.0432283615430504, 0.0202481578919003, 0.0191747572787057, 0.0185718929604774, 0.0178301092823977, 0.0172423799670431, 0.0166981650233669, 0.0162072551503541, 0.015784555784915, 0.0153600119986575, 0.0149084240854556 ) ) } }
Perform Multiview PCA on multiple datasets with an option for sparse PCA.
multiview_pca( views, n_components, sparse = 0.5, max_iter = 100, sparsenessAlg = "basic", verbose = FALSE )multiview_pca( views, n_components, sparse = 0.5, max_iter = 100, sparsenessAlg = "basic", verbose = FALSE )
views |
A list of data matrices for each view. |
n_components |
Number of principal components to compute. |
sparse |
vector of length views with values between zero and one |
max_iter |
Maximum number of iterations for the optimization. |
sparsenessAlg |
NA is default otherwise basic, spmp or orthorank |
verbose |
Logical, whether to print information about energy and sparsity. |
A list containing the common representation Z and transformation matrices W.
set.seed(123) n_samples <- 100 n_features_1 <- 50 n_features_2 <- 60 n_features_3 <- 70 n_components <- 5 view1 <- matrix(rnorm(n_samples * n_features_1), nrow = n_samples, ncol = n_features_1) view2 <- matrix(rnorm(n_samples * n_features_2), nrow = n_samples, ncol = n_features_2) view3 <- matrix(rnorm(n_samples * n_features_3), nrow = n_samples, ncol = n_features_3) result <- multiview_pca(list(view1, view2, view3), n_components, sparse = rep(0.5,3), verbose = TRUE) print(result)set.seed(123) n_samples <- 100 n_features_1 <- 50 n_features_2 <- 60 n_features_3 <- 70 n_components <- 5 view1 <- matrix(rnorm(n_samples * n_features_1), nrow = n_samples, ncol = n_features_1) view2 <- matrix(rnorm(n_samples * n_features_2), nrow = n_samples, ncol = n_features_2) view3 <- matrix(rnorm(n_samples * n_features_3), nrow = n_samples, ncol = n_features_3) result <- multiview_pca(list(view1, view2, view3), n_components, sparse = rep(0.5,3), verbose = TRUE) print(result)
Perform N3 bias field correction on the given image
n3BiasFieldCorrection(img, downsampleFactor, ...)n3BiasFieldCorrection(img, downsampleFactor, ...)
img |
antsImage to correct |
downsampleFactor |
integer e.g. 4 downsample by a factor of 4 |
... |
not used |
antsImage
Shrinidhi KL
img <- makeImage(c(10, 10), rnorm(100)) n3img <- n3BiasFieldCorrection(img, 1)img <- makeImage(c(10, 10), rnorm(100)) n3img <- n3BiasFieldCorrection(img, 1)
Perform N3 bias field correction on the given image
n3BiasFieldCorrection2( img, mask, rescaleIntensities = FALSE, shrinkFactor = 4, convergence = list(iters = 50, tol = 1e-07), splineParam = 200, numberOfFittingLevels = 4, weightMask = NULL, returnBiasField = FALSE, verbose = FALSE )n3BiasFieldCorrection2( img, mask, rescaleIntensities = FALSE, shrinkFactor = 4, convergence = list(iters = 50, tol = 1e-07), splineParam = 200, numberOfFittingLevels = 4, weightMask = NULL, returnBiasField = FALSE, verbose = FALSE )
img |
input antsImage |
mask |
input mask, if one is not passed one will be made |
rescaleIntensities |
At each iteration, a new intensity mapping is calculated and applied but there is nothing which constrains the new intensity range to be within certain values. The result is that the range can "drift" from the original at each iteration. This option rescales to the [min,max] range of the original image intensities within the user-specified mask. A mask is required to perform rescaling. Default is FALSE in ANTsR/ANTsPy but TRUE in ANTs. |
shrinkFactor |
Shrink factor for multi-resolution correction, typically integer less than 4 |
convergence |
List of: |
splineParam |
Parameter controlling number of control points in spline. Either single value, indicating how many control points, or vector with one entry per dimension of image, indicating the spacing in each direction. Default is a mesh size of 1 per dimension. |
numberOfFittingLevels |
Parameter controlling number of fitting levels. |
weightMask |
antsImage of weight mask |
returnBiasField |
bool, return the field instead of the corrected image. |
verbose |
enables verbose output. |
bias corrected image or bias field
Avants BB, Tustison NJ
dims <- c(50, 50) img <- makeImage(imagesize = dims, rnorm(prod(dims))) n3img <- n3BiasFieldCorrection2(img) n3img <- n3BiasFieldCorrection2(img, mask = img > 0) testthat::expect_error(n3BiasFieldCorrection2(img, weightMask = "somepath")) testthat::expect_error(n3BiasFieldCorrection2(img, splineParam = rep(200, 3))) # n3img<-n3BiasFieldCorrection2(img, splineParam = c(200, 20)) # long running rm(img) gc() rm(n3img) gc() fname <- getANTsRData("r16") in_img <- antsImageRead(fname) n3 <- n3BiasFieldCorrection2(in_img) rm(n3) gc() mask <- in_img > 0 mask2 <- antsImageClone(mask, out_pixeltype = "float") # fails mask sum(mask) ## Not run: n3 <- n3BiasFieldCorrection2(in_img, mask = mask, verbose = TRUE) # fails n3 <- n3BiasFieldCorrection2(in_img, mask = mask2) ## End(Not run)dims <- c(50, 50) img <- makeImage(imagesize = dims, rnorm(prod(dims))) n3img <- n3BiasFieldCorrection2(img) n3img <- n3BiasFieldCorrection2(img, mask = img > 0) testthat::expect_error(n3BiasFieldCorrection2(img, weightMask = "somepath")) testthat::expect_error(n3BiasFieldCorrection2(img, splineParam = rep(200, 3))) # n3img<-n3BiasFieldCorrection2(img, splineParam = c(200, 20)) # long running rm(img) gc() rm(n3img) gc() fname <- getANTsRData("r16") in_img <- antsImageRead(fname) n3 <- n3BiasFieldCorrection2(in_img) rm(n3) gc() mask <- in_img > 0 mask2 <- antsImageClone(mask, out_pixeltype = "float") # fails mask sum(mask) ## Not run: n3 <- n3BiasFieldCorrection2(in_img, mask = mask, verbose = TRUE) # fails n3 <- n3BiasFieldCorrection2(in_img, mask = mask2) ## End(Not run)
Perform N4 bias field correction on the given image
n4BiasFieldCorrection( img, mask, rescaleIntensities = FALSE, shrinkFactor = 4, convergence = list(iters = c(50, 50, 50, 50), tol = 1e-07), splineParam = 200, returnBiasField = FALSE, verbose = FALSE, weightMask = NULL )n4BiasFieldCorrection( img, mask, rescaleIntensities = FALSE, shrinkFactor = 4, convergence = list(iters = c(50, 50, 50, 50), tol = 1e-07), splineParam = 200, returnBiasField = FALSE, verbose = FALSE, weightMask = NULL )
img |
input antsImage |
mask |
input mask, if one is not passed one will be made |
rescaleIntensities |
At each iteration, a new intensity mapping is calculated and applied but there is nothing which constrains the new intensity range to be within certain values. The result is that the range can "drift" from the original at each iteration. This option rescales to the [min,max] range of the original image intensities within the user-specified mask. A mask is required to perform rescaling. Default is FALSE in ANTsR/ANTsPy but TRUE in ANTs. |
shrinkFactor |
Shrink factor for multi-resolution correction, typically integer less than 4. |
convergence |
List of: |
splineParam |
Parameter controlling number of control points in spline. Either single value, indicating how many control points, or vector with one entry per dimension of image, indicating the spacing in each direction. Default in ANTsR/ANTsPy is 200 mm per mesh element in each dimension. The ANTs default is a mesh size of 1 per dimension. |
returnBiasField |
bool, return the field instead of the corrected image. |
verbose |
enables verbose output. |
weightMask |
antsImage of weight mask |
bias corrected image or bias field
BB Avants
dims <- c(50, 50) img <- makeImage(imagesize = dims, rnorm(prod(dims))) n4img <- n4BiasFieldCorrection(img) n4img <- n4BiasFieldCorrection(img, mask = img > 0) testthat::expect_error(n4BiasFieldCorrection(img, weightMask = "somepath")) testthat::expect_error(n4BiasFieldCorrection(img, splineParam = rep(200, 3))) n4img <- n4BiasFieldCorrection(img, splineParam = c(200, 20)) rm(img) gc() rm(n4img) gc() fname <- getANTsRData("r16") in_img <- antsImageRead(fname) n4 <- n4BiasFieldCorrection(in_img) rm(n4) gc() mask <- in_img > 0 mask2 <- antsImageClone(mask, out_pixeltype = "float") # fails mask sum(mask) ## Not run: n4 <- n4BiasFieldCorrection(in_img, mask = mask, verbose = TRUE) # fails n4 <- n4BiasFieldCorrection(in_img, mask = mask2) ## End(Not run)dims <- c(50, 50) img <- makeImage(imagesize = dims, rnorm(prod(dims))) n4img <- n4BiasFieldCorrection(img) n4img <- n4BiasFieldCorrection(img, mask = img > 0) testthat::expect_error(n4BiasFieldCorrection(img, weightMask = "somepath")) testthat::expect_error(n4BiasFieldCorrection(img, splineParam = rep(200, 3))) n4img <- n4BiasFieldCorrection(img, splineParam = c(200, 20)) rm(img) gc() rm(n4img) gc() fname <- getANTsRData("r16") in_img <- antsImageRead(fname) n4 <- n4BiasFieldCorrection(in_img) rm(n4) gc() mask <- in_img > 0 mask2 <- antsImageClone(mask, out_pixeltype = "float") # fails mask sum(mask) ## Not run: n4 <- n4BiasFieldCorrection(in_img, mask = mask, verbose = TRUE) # fails n4 <- n4BiasFieldCorrection(in_img, mask = mask2) ## End(Not run)
A data frame label numbers and names for NBM3 regions.
nbm3_labelsnbm3_labels
A data frame with columns: Label, Description, Side.
Measures the extent to which a matrix violates nonnegativity constraints.
neg_violation(Y)neg_violation(Y)
Y |
Numeric matrix (p x k) to evaluate. |
Computes , the Frobenius norm of the negative part of Y, which quantifies
the magnitude of negative entries. Used to monitor nonnegativity enforcement in NSA-Flow.
Numeric scalar, the Frobenius norm of negative entries.
Y <- matrix(c(-1, 2, -3, 4), 2, 2) neg_violation(Y)Y <- matrix(c(-1, 2, -3, 4), 2, 2) neg_violation(Y)
Decomposes a matrix into sparse eigenevectors to maximize explained variance.
networkEiganat( Xin, sparseness = c(0.1, 0.1), nvecs = 5, its = 5, gradparam = 1, mask = NA, v, prior, pgradparam = 0.1, clustval = 0, downsample = 0, doscale = T, domin = T, verbose = F, dowhite = 0, timeme = T, addb = T, useregression = T )networkEiganat( Xin, sparseness = c(0.1, 0.1), nvecs = 5, its = 5, gradparam = 1, mask = NA, v, prior, pgradparam = 0.1, clustval = 0, downsample = 0, doscale = T, domin = T, verbose = F, dowhite = 0, timeme = T, addb = T, useregression = T )
Xin |
n by p input images , subjects or time points by row , spatial variable lies along columns |
sparseness |
sparseness pair c( 0.1 , 0.1 ) |
nvecs |
number of vectors |
its |
number of iterations |
gradparam |
gradient descent parameter for data |
mask |
optional antsImage mask |
v |
the spatial solultion |
prior |
the prior |
pgradparam |
gradient descent parameter for prior term |
clustval |
integer greater than or equal to zero |
downsample |
bool |
doscale |
bool |
domin |
bool |
verbose |
bool |
dowhite |
bool |
timeme |
bool |
addb |
bool |
useregression |
bool |
outputs a decomposition of a population or time series matrix
Avants BB
## Not run: mat <- replicate(100, rnorm(20)) mydecom <- networkEiganat(mat, nvecs = 5) ch1 <- usePkg("randomForest") ch2 <- usePkg("BGLR") if (ch1 & ch2) { data(mice) snps <- quantifySNPs(mice.X) numericalpheno <- as.matrix(mice.pheno[, c(4, 5, 13, 15)]) numericalpheno <- residuals(lm(numericalpheno ~ as.factor(mice.pheno$Litter))) phind <- 3 nfolds <- 6 train <- sample(rep(c(1:nfolds), 1800 / nfolds)) train <- (train < 4) lowr <- lowrankRowMatrix(as.matrix(snps[train, ]), 900) snpdS <- sparseDecom(lowr, nvecs = 2, sparseness = (-0.001), its = 3) snpdF <- sparseDecom(lowrankRowMatrix(as.matrix(snps[train, ]), 100), nvecs = 2, sparseness = (-0.001), its = 3 ) projmat <- as.matrix(snpdS$eig) projmat <- as.matrix(snpdF$eig) snpdFast <- networkEiganat(as.matrix(snps[train, ]), nvecs = 2, sparseness = c(1, -0.001), downsample = 45, verbose = T, its = 3, gradparam = 10 ) snpdSlow <- networkEiganat(as.matrix(snps[train, ]), nvecs = 2, sparseness = c(1, -0.001), downsample = 0, verbose = T, its = 3, gradparam = 10 ) snpd <- snpdSlow snpd <- snpdFast projmat <- as.matrix(snpd$v) snpdF <- sparseDecom(lowrankRowMatrix(as.matrix(snps[train, ]), 10), nvecs = 2, sparseness = (-0.001), its = 3 ) projmat <- as.matrix(snpdS$eig) snpse <- as.matrix(snps[train, ]) %*% projmat traindf <- data.frame(bmi = numericalpheno[train, phind], snpse = snpse) snpse <- as.matrix(snps[!train, ]) %*% projmat testdf <- data.frame(bmi = numericalpheno[!train, phind], snpse = snpse) myrf <- glm(bmi ~ ., data = traindf) preddf <- predict(myrf, newdata = testdf) cor.test(preddf, testdf$bmi) } # ch1 and ch2 ########### ## End(Not run)## Not run: mat <- replicate(100, rnorm(20)) mydecom <- networkEiganat(mat, nvecs = 5) ch1 <- usePkg("randomForest") ch2 <- usePkg("BGLR") if (ch1 & ch2) { data(mice) snps <- quantifySNPs(mice.X) numericalpheno <- as.matrix(mice.pheno[, c(4, 5, 13, 15)]) numericalpheno <- residuals(lm(numericalpheno ~ as.factor(mice.pheno$Litter))) phind <- 3 nfolds <- 6 train <- sample(rep(c(1:nfolds), 1800 / nfolds)) train <- (train < 4) lowr <- lowrankRowMatrix(as.matrix(snps[train, ]), 900) snpdS <- sparseDecom(lowr, nvecs = 2, sparseness = (-0.001), its = 3) snpdF <- sparseDecom(lowrankRowMatrix(as.matrix(snps[train, ]), 100), nvecs = 2, sparseness = (-0.001), its = 3 ) projmat <- as.matrix(snpdS$eig) projmat <- as.matrix(snpdF$eig) snpdFast <- networkEiganat(as.matrix(snps[train, ]), nvecs = 2, sparseness = c(1, -0.001), downsample = 45, verbose = T, its = 3, gradparam = 10 ) snpdSlow <- networkEiganat(as.matrix(snps[train, ]), nvecs = 2, sparseness = c(1, -0.001), downsample = 0, verbose = T, its = 3, gradparam = 10 ) snpd <- snpdSlow snpd <- snpdFast projmat <- as.matrix(snpd$v) snpdF <- sparseDecom(lowrankRowMatrix(as.matrix(snps[train, ]), 10), nvecs = 2, sparseness = (-0.001), its = 3 ) projmat <- as.matrix(snpdS$eig) snpse <- as.matrix(snps[train, ]) %*% projmat traindf <- data.frame(bmi = numericalpheno[train, phind], snpse = snpse) snpse <- as.matrix(snps[!train, ]) %*% projmat testdf <- data.frame(bmi = numericalpheno[!train, phind], snpse = snpse) myrf <- glm(bmi ~ ., data = traindf) preddf <- predict(myrf, newdata = testdf) cor.test(preddf, testdf$bmi) } # ch1 and ch2 ########### ## End(Not run)
This function processes multimodal data using SiMLR. It is designed to be flexible, allowing for various preprocessing steps and analysis options. The analysis can be adjusted through multiple parameters, offering control over the inclusion of certain data types, permutation testing, and more.
NNHEmbed( blaster, select_training_boolean, connect_cog, energy, nsimlr, constraint, covariates = "1", myseed = 3, doAsym = TRUE, returnidps = 0, restrictDFN = FALSE, resnetGradeThresh = 1.02, doperm = FALSE, exclusions = NULL, inclusions = NULL, sparseness = NULL, mixAlg = NULL, iterations = NULL, path_modeling = NULL, sparsenessAlg = "soft", optimizationStyle = NULL, domainMatrices = NULL, domainLambdas = NULL, verbose = FALSE )NNHEmbed( blaster, select_training_boolean, connect_cog, energy, nsimlr, constraint, covariates = "1", myseed = 3, doAsym = TRUE, returnidps = 0, restrictDFN = FALSE, resnetGradeThresh = 1.02, doperm = FALSE, exclusions = NULL, inclusions = NULL, sparseness = NULL, mixAlg = NULL, iterations = NULL, path_modeling = NULL, sparsenessAlg = "soft", optimizationStyle = NULL, domainMatrices = NULL, domainLambdas = NULL, verbose = FALSE )
blaster |
A dataframe containing multimodal data for analysis. |
select_training_boolean |
boolean vector to define which entries are in training data |
connect_cog |
Vector of column names to be treated as a special target matrix; often used for cognitive data and in a superivsed variant of simlr. Exclude this argument if this is unclear. |
energy |
The type of energy model to use for similarity analysis. Usually 'reg' or 'cca'. Other options include 'lrr', 'regression', 'nc', 'base.pca', 'base.spca', 'base.rand.1', and 'base.rand.0'. |
nsimlr |
Number of components. |
constraint |
orthogonality constraint of the form constraintxFloatWeightEnergyxFloatWeightGrad where constraints is ortho or nsaflow or none |
covariates |
any covariates to adjust training matrices. if covariates is set to 'mean' then the rowwise mean will be factored out of each matrix. this can be a vector e.g. |
myseed |
Seed for random number generation to ensure reproducibility. Defaults to 3. |
doAsym |
integer 0 for FALSE, 1 for TRUE and 2 for separate matrices for asymm variables. |
returnidps |
Integer indicating whether to return the idp names (1) or matrices (2) or neither (0). Defaults to 0. |
restrictDFN |
Logical indicating whether to restrict analysis to default network features. Defaults to FALSE. |
resnetGradeThresh |
image quality threshold (higher better). |
doperm |
Logical indicating whether to perform permutation tests. Defaults to FALSE. Will randomize image features in the training data and thus leads to "randomized" but still regularized projections. |
exclusions |
vector of strings to exclude from predictors |
inclusions |
vector of strings to include in predictors |
sparseness |
vector or scalar value to set sparseness. |
mixAlg |
string 'svd', 'ica', 'rrpca-l', 'rrpca-s', 'stochastic', 'pca', 'newton-schulz' or 'avg' denotes the algorithm employed when estimating the mixed modality bases |
iterations |
int value to set max iterations |
path_modeling |
the result of a call to |
sparsenessAlg |
NA is default otherwise basic, spmp or orthorank |
optimizationStyle |
see |
domainMatrices |
matrices containing domain knowledge length of |
domainLambdas |
weights for domain knowledge term length of |
verbose |
boolean |
A list containing the results of the similarity analysis and related data.
# Example usage: # result <- NNHEmbed(dataframe)# Example usage: # result <- NNHEmbed(dataframe)
This function updates residuals for SiMLR by applying different covariate transformations.
NNHEmbed_update_residuals( mats, x, covariate, blaster2, allnna, n.comp, opt = NULL )NNHEmbed_update_residuals( mats, x, covariate, blaster2, allnna, n.comp, opt = NULL )
mats |
A list of matrices. |
x |
An index to select a matrix from the list. |
covariate |
A character string specifying the covariate transformation to apply. |
blaster2 |
A data frame containing additional covariate data. |
allnna |
A logical vector indicating non-missing data points. |
n.comp |
An integer specifying the number of components. |
opt |
A character string. If set to "opt", the function will print available covariate options. |
The residual matrix after applying the specified covariate transformation. If 'opt' is set to "opt", the function will print available covariate options and return NULL.
## Not run: NNHEmbed_update_residuals(mats, 1, "whiten", blaster2, allnna, 5) NNHEmbed_update_residuals(opt = "opt") ## End(Not run)## Not run: NNHEmbed_update_residuals(mats, 1, "whiten", blaster2, allnna, 5) NNHEmbed_update_residuals(opt = "opt") ## End(Not run)
Performs optimization to balance fidelity to a target matrix and orthogonality of the solution matrix using a weighted objective function. The function supports multiple retraction methods and includes robust convergence checks. These constraints provide global control over column-wise sparseness by projecting the matrix onto the approximate Stiefel manifold.
nsa_flow( Y0, X0 = NULL, w = 0.5, retraction = c("soft_polar", "polar", "none"), max_iter = 500, tol = 1e-05, verbose = FALSE, seed = 42, apply_nonneg = TRUE, optimizer = "fast", initial_learning_rate = "brent", record_every = 1, window_size = 5, c1_armijo = 1e-06, simplified = FALSE, plot = FALSE )nsa_flow( Y0, X0 = NULL, w = 0.5, retraction = c("soft_polar", "polar", "none"), max_iter = 500, tol = 1e-05, verbose = FALSE, seed = 42, apply_nonneg = TRUE, optimizer = "fast", initial_learning_rate = "brent", record_every = 1, window_size = 5, c1_armijo = 1e-06, simplified = FALSE, plot = FALSE )
Y0 |
Numeric matrix of size |
X0 |
Numeric matrix of size |
w |
Numeric scalar in |
retraction |
Character string specifying the retraction method to enforce orthogonality constraints. |
max_iter |
Integer, maximum number of iterations. Default is 100. |
tol |
Numeric, tolerance for convergence based on relative gradient norm and energy stability. Default is 1e-6. |
verbose |
Logical, if |
seed |
Integer, random seed for reproducibility. If |
apply_nonneg |
Logical, if |
optimizer |
Character string, optimization algorithm to use. The "fast" option
will select the best option based on whether simplified = TRUE or FALSE.
otherwise, pass the names of optimizers supported by |
initial_learning_rate |
Numeric, initial learning rate for the optimizer.
Default is 1e-3 for non-neg and 1 for unconstrained. Otherwise, you can use |
record_every |
Integer, frequency of recording iteration metrics. Default is 1 (record every iteration). |
window_size |
Integer, size of the window for energy stability convergence check. Default is 5. |
c1_armijo |
Numeric, Armijo condition constant for line search. |
simplified |
Logical, if
.
If |
plot |
Logical, if |
The function minimizes a weighted objective combining fidelity to X0 and
orthogonality of Y, defined as:
where defect(Y) measures orthogonality deviation.
The optimization uses a Riemannian gradient descent approach with optional retraction to enforce orthogonality constraints. Convergence is checked via relative gradient norm and energy stability over a window of iterations.
A list containing:
Y: Numeric matrix, the best solution found (lowest total energy).
traces: Data frame with columns iter, time,
fidelity, orthogonality, and total_energy
for recorded iterations.
final_iter: Integer, number of iterations performed.
plot: ggplot object of the optimization trace
(if plot = TRUE), otherwise NULL.
best_total_energy: Numeric, the lowest total energy achieved.
set.seed(123) Y0 <- matrix(runif(20), 5, 4) X0 <- matrix(runif(20), 5, 4) # The original function relies on helper functions not shown here, such as: # create_optimizer, step, inv_sqrt_sym, symm, and invariant_orthogonality_defect. # The following example is conceptual: # result <- nsa_flow(Y0, X0, w = 0.0, max_iter = 10, verbose = TRUE, plot = TRUE) # print(result$plot) # print(result$traces)set.seed(123) Y0 <- matrix(runif(20), 5, 4) X0 <- matrix(runif(20), 5, 4) # The original function relies on helper functions not shown here, such as: # create_optimizer, step, inv_sqrt_sym, symm, and invariant_orthogonality_defect. # The following example is conceptual: # result <- nsa_flow(Y0, X0, w = 0.0, max_iter = 10, verbose = TRUE, plot = TRUE) # print(result$plot) # print(result$traces)
Mirror of Python 'nsa_flow_autograd()' but callable from R via reticulate. Uses the Python implementation (nsa_flow.nsa_flow_autograd) and returns R-friendly results (matrix, data.frame, ggplot).
nsa_flow_autograd( Y0, X0 = NULL, w = 0.5, retraction = c("soft_polar", "polar", "none"), max_iter = 500L, tol = 1e-06, verbose = FALSE, seed = 42L, apply_nonneg = TRUE, optimizer = "asgd", initial_learning_rate = NULL, lr_strategy = "bayes", aggression = 0.5, fidelity_type = "scale_invariant", orth_type = "scale_invariant", record_every = 1L, window_size = 10L, warmup_iters = 0L, plot = FALSE, precision = "float64" )nsa_flow_autograd( Y0, X0 = NULL, w = 0.5, retraction = c("soft_polar", "polar", "none"), max_iter = 500L, tol = 1e-06, verbose = FALSE, seed = 42L, apply_nonneg = TRUE, optimizer = "asgd", initial_learning_rate = NULL, lr_strategy = "bayes", aggression = 0.5, fidelity_type = "scale_invariant", orth_type = "scale_invariant", record_every = 1L, window_size = 10L, warmup_iters = 0L, plot = FALSE, precision = "float64" )
Y0 |
numeric matrix p x k initial guess |
X0 |
numeric matrix p x k target (or NULL to initialize from Y0) |
w |
numeric in [0,1] weighting fidelity vs orthogonality |
retraction |
character retraction method |
max_iter |
integer max iterations |
tol |
numeric convergence tolerance |
verbose |
logical |
seed |
integer random seed |
apply_nonneg |
logical or 'softplus'/'none' etc. |
optimizer |
character optimizer name (e.g. 'Adam','lars','sgdp') |
initial_learning_rate |
NULL (auto), numeric, or character strategy string |
lr_strategy |
character passed to Python if initial_learning_rate is NULL/'auto' |
aggression |
numeric controls aggressiveness of learning rate adaptation |
fidelity_type |
character ('basic','scale_invariant','symmetric','normalized') |
orth_type |
character ('basic','scale_invariant') |
record_every |
integer frequency of recording traces |
window_size |
integer window for energy stability |
warmup_iters |
integer number of warmup iterations |
plot |
logical produce ggplot (default FALSE) |
precision |
'float32' or 'float64' |
list: Y (matrix), traces (data.frame), final_iter, best_total_energy, best_Y_iteration, plot (ggplot or NULL), settings
This function creates a flowchart diagram representing the NSA-Flow FA process using the DiagrammeR package. The diagram illustrates the steps involved in the algorithm, including data input, regularization, iteration, convergence checks, and output.
nsa_flow_fa_diagram()nsa_flow_fa_diagram()
The diagram is generated using Graphviz syntax via DiagrammeR::grViz. It visualizes the flow
from input data through various processing steps to the final output. Ensure the DiagrammeR package
is installed to use this function.
A DiagrammeR graph object representing the flowchart.
## Not run: library(DiagrammeR) nsa_flow_fa_diagram() ## End(Not run)## Not run: library(DiagrammeR) nsa_flow_fa_diagram() ## End(Not run)
Generates a DiagrammeR flowchart summarizing the full NSA-Flow optimization pipeline, including initialization, gradient computation, Riemannian projection, descent, retraction, non-negativity, and convergence checks.
nsa_flow_flowchart( node_fill_color = "lightblue", node_font_color = "black", edge_color = "black", font_name = "Helvetica", node_shape = "rectangle", graph_rankdir = "TB", fontsize = 10 )nsa_flow_flowchart( node_fill_color = "lightblue", node_font_color = "black", edge_color = "black", font_name = "Helvetica", node_shape = "rectangle", graph_rankdir = "TB", fontsize = 10 )
node_fill_color |
Color for node fill (default: "lightblue"). |
node_font_color |
Color for node text (default: "black"). |
edge_color |
Color for edges (default: "black"). |
font_name |
Font for node labels (default: "Helvetica"). |
node_shape |
Node shape (default: "rectangle"). |
graph_rankdir |
Graph layout direction (default: "TB" = top to bottom). |
fontsize |
Font size (default: 10). |
A DiagrammeR graph object.
Performs sparse PCA using a proximal-gradient scheme with optional NSA-flow proximal regularization. This implementation preserves the stable behavior of the original 'sparse_pca_imp()' while improving efficiency by: - precomputing X'X, using it for gradient/energy, - in-place trial updates to reduce allocations, - retaining Armijo backtracking and adaptive LR scheduling.
nsa_flow_pca( X, k, lambda = 0.1, alpha = 1e-04, max_iter = 100, proximal_type = c("basic", "nsa_flow"), w_pca = 1, nsa_w = 0.5, apply_soft_thresh_in_nns = FALSE, tol = 1e-06, retraction = def_ret, grad_tol = 1e-04, nsa_flow_fn = nsa_flow_autograd, verbose = FALSE )nsa_flow_pca( X, k, lambda = 0.1, alpha = 1e-04, max_iter = 100, proximal_type = c("basic", "nsa_flow"), w_pca = 1, nsa_w = 0.5, apply_soft_thresh_in_nns = FALSE, tol = 1e-06, retraction = def_ret, grad_tol = 1e-04, nsa_flow_fn = nsa_flow_autograd, verbose = FALSE )
X |
numeric matrix (n x p), rows = observations, cols = variables |
k |
integer > 0 and <= min(n,p), number of components |
lambda |
non-negative numeric, L1 proximal weight |
alpha |
positive numeric, initial step size |
max_iter |
integer, maximum iterations |
proximal_type |
character, "basic" or "nsa_flow" |
w_pca |
positive numeric, weight for PCA fidelity |
nsa_w |
numeric in [0,1], weight parameter passed to nsa_flow |
apply_soft_thresh_in_nns |
logical (passed through if used) |
tol |
numeric, tolerance for relative parameter change convergence |
retraction |
retraction function or identifier (passed to nsa_flow) |
grad_tol |
numeric, gradient-norm tolerance for convergence |
nsa_flow_fn |
optional, nsa_flow function to use (default: nsa_flow) |
verbose |
logical, print iteration diagnostics |
list with components:
Y |
best p x k loading matrix found |
energy_trace |
vector of per-iteration energy/explained-variance records |
final_iter |
last iteration index |
best_energy |
best energy attained |
converged |
logical |
no_improve_count |
internal counter at exit |
lr_reductions |
number of LR reductions performed |
expl_var_ratio |
explained variance ratio for best_Y |
Optimize either a PCA objective (default) or a Factor Analysis (FA) objective in a single call. Armijo backtracking, optional NSA-flow proximal, adaptive LR scheduling, and optional rotation every iteration.
nsa_flow_pca_fa( X, k, lambda = 0.1, alpha = 0.01, max_iter = 100, proximal_type = c("basic", "nsa_flow"), w_pca = 1, tol = 1e-06, grad_tol = 1e-04, nsa_flow_fn = NULL, verbose = FALSE, objective = c("pca", "fa"), rotate = c("none", "varimax", "promax", "oblimin"), nsa_flow_args = list() )nsa_flow_pca_fa( X, k, lambda = 0.1, alpha = 0.01, max_iter = 100, proximal_type = c("basic", "nsa_flow"), w_pca = 1, tol = 1e-06, grad_tol = 1e-04, nsa_flow_fn = NULL, verbose = FALSE, objective = c("pca", "fa"), rotate = c("none", "varimax", "promax", "oblimin"), nsa_flow_args = list() )
X |
numeric matrix (n x p), rows = observations, cols = variables |
k |
integer > 0 and <= min(n,p), number of components |
lambda |
non-negative numeric, L1 proximal weight |
alpha |
positive numeric, initial step size |
max_iter |
integer, maximum iterations |
proximal_type |
character, "basic" or "nsa_flow" |
w_pca |
positive numeric, weight for PCA fidelity |
tol |
numeric, tolerance for relative parameter change convergence |
grad_tol |
numeric, gradient-norm tolerance for convergence |
nsa_flow_fn |
optional, nsa_flow function to use (default: nsa_flow) |
verbose |
logical, print iteration diagnostics |
objective |
character, either "pca" (default) or "fa". If "fa", the function optimizes a FA-like loss: reconstructing the sample covariance R with Y Y^T + diag(psi) where psi >= 0 is set to the diagonal of R - Y Y^T (clipped to a small positive eps). |
rotate |
character; one of "none","varimax","promax","oblimin". If not "none", the loadings are rotated every iteration (keeps shapes). |
nsa_flow_args |
list, optional additional args forwarded to nsa_flow_fn() |
list with components: Y, energy_trace, final_iter, best_energy, converged, no_improve_count, lr_reductions, expl_var_ratio
This function implements a proximal gradient descent algorithm for either Principal Component Analysis (PCA) or Factor Analysis (FA), with support for sparsity via L1 regularization or custom proximal operators (e.g., NSA flow). For PCA, it maximizes explained variance; for FA, it minimizes the least-squares reconstruction error of the covariance matrix using an alternating optimization over loadings and uniquenesses. Initialization uses SVD, and optional rotation is applied at the end.
nsa_flow_pca_fa_2( X, k, lambda = 0.1, alpha = 0.01, max_iter = 100, proximal_type = c("basic", "nsa_flow"), w_pca = 1, tol = 1e-06, grad_tol = 1e-04, nsa_flow_fn = NULL, verbose = FALSE, objective = c("pca", "fa"), rotate = c("none", "varimax", "promax", "oblimin"), nsa_flow_args = list() )nsa_flow_pca_fa_2( X, k, lambda = 0.1, alpha = 0.01, max_iter = 100, proximal_type = c("basic", "nsa_flow"), w_pca = 1, tol = 1e-06, grad_tol = 1e-04, nsa_flow_fn = NULL, verbose = FALSE, objective = c("pca", "fa"), rotate = c("none", "varimax", "promax", "oblimin"), nsa_flow_args = list() )
X |
Numeric matrix of data (n rows observations, p columns variables). |
k |
Integer number of components/factors (1 <= k <= min(n, p)). |
lambda |
Non-negative regularization parameter for L1 sparsity (default 0.1). |
alpha |
Positive initial step size for gradient descent (default 0.01). |
max_iter |
Maximum number of iterations (default 100). |
proximal_type |
Type of proximal operator: "basic" for soft-thresholding or "nsa_flow" for custom (default "basic"). |
w_pca |
Positive weight for PCA objective (default 1.0). |
tol |
Tolerance for convergence based on relative change (default 1e-6). |
grad_tol |
Tolerance for gradient norm (default 1e-4). |
nsa_flow_fn |
Function for NSA proximal operator (required if proximal_type = "nsa_flow"). |
verbose |
Logical; if TRUE, print iteration progress (default FALSE). |
objective |
Objective: "pca" or "fa" (default "pca"). |
rotate |
Rotation method: "none", "varimax", "promax", or "oblimin" (default "none"). |
nsa_flow_args |
List of additional arguments for nsa_flow_fn (default list()). |
A list containing:
Y: Optimized loadings matrix (unrotated).
loadings: Final loadings (possibly rotated).
communalities: Vector of communalities for each variable.
energy_trace: Vector of energy values per iteration.
final_iter: Number of iterations performed.
best_energy: Best (lowest) energy achieved.
converged: Logical indicating convergence.
no_improve_count: Count of iterations without improvement.
lr_reductions: Number of learning rate reductions.
expl_var_ratio: Explained variance ratio (PCA-style).
## Not run: data(iris) X <- as.matrix(iris[, 1:4]) res <- nsa_flow_pca_fa_2(X, k = 2, objective = "fa", verbose = TRUE) print(res$loadings) ## End(Not run)## Not run: data(iris) X <- as.matrix(iris[, 1:4]) res <- nsa_flow_pca_fa_2(X, k = 2, objective = "fa", verbose = TRUE) print(res$loadings) ## End(Not run)
Retraction onto the Stiefel Manifold
nsa_flow_retract(Y_cand, w_retract, retraction_type)nsa_flow_retract(Y_cand, w_retract, retraction_type)
Y_cand |
Candidate matrix. |
w_retract |
Weight for soft retraction. |
retraction_type |
Type of retraction ('polar', 'soft_polar', or 'none'). |
Retraction onto the Stiefel Manifold (soft-polar multiplicative, with adaptive inv-sqrt)
nsa_flow_retract_auto( Y_cand, w_retract = 1, retraction_type = c("polar", "soft_polar", "none"), eps_rf = 1e-08, inv_method = "diag", ns_iter = 1L, eig_thresh = 128L, diag_thresh = 8192L, verbose = FALSE )nsa_flow_retract_auto( Y_cand, w_retract = 1, retraction_type = c("polar", "soft_polar", "none"), eps_rf = 1e-08, inv_method = "diag", ns_iter = 1L, eig_thresh = 128L, diag_thresh = 8192L, verbose = FALSE )
Y_cand |
Candidate matrix. |
w_retract |
Weight for soft retraction. |
retraction_type |
Type of retraction ('polar', 'soft_polar', or 'none'). |
eps_rf |
Small numeric value for stability. |
inv_method |
Method for inverse square root. |
ns_iter |
Number of iterations for Newton-Schulz. |
eig_thresh |
Threshold for eigen-decomposition. |
diag_thresh |
Threshold for diagonal check. |
verbose |
Verbose output. |
Performs optimization to balance fidelity to a target matrix and orthogonality of the solution matrix using a weighted objective function. The function supports multiple retraction methods and includes robust convergence checks. These constraints provide global control over column-wise sparseness by projecting the matrix onto the approximate Stiefel manifold.
nsa_flow_torch( Y0, X0 = NULL, w = 0.5, retraction = c("soft_polar", "polar", "none"), max_iter = 500, tol = 1e-05, verbose = FALSE, seed = 42, apply_nonneg = TRUE, optimizer = "fast", initial_learning_rate = "default", record_every = 1, window_size = 5, c1_armijo = 1e-06, simplified = FALSE, project_full_gradient = FALSE, plot = FALSE, precision = "float64" )nsa_flow_torch( Y0, X0 = NULL, w = 0.5, retraction = c("soft_polar", "polar", "none"), max_iter = 500, tol = 1e-05, verbose = FALSE, seed = 42, apply_nonneg = TRUE, optimizer = "fast", initial_learning_rate = "default", record_every = 1, window_size = 5, c1_armijo = 1e-06, simplified = FALSE, project_full_gradient = FALSE, plot = FALSE, precision = "float64" )
Y0 |
Numeric matrix of size |
X0 |
Numeric matrix of size |
w |
Numeric scalar in |
retraction |
Character string specifying the retraction method to enforce orthogonality constraints. |
max_iter |
Integer, maximum number of iterations. Default is 100. |
tol |
Numeric, tolerance for convergence based on relative gradient norm and energy stability. Default is 1e-6. |
verbose |
Logical, if |
seed |
Integer, random seed for reproducibility. If |
apply_nonneg |
Logical, if |
optimizer |
Character string, optimization algorithm to use. The "fast" option
will select the best option based on whether simplified = TRUE or FALSE.
otherwise, pass the names of optimizers supported by |
initial_learning_rate |
Numeric, initial learning rate for the optimizer.
Default is 1e-3 for non-neg and 1 for unconstrained. Otherwise, you can use |
record_every |
Integer, frequency of recording iteration metrics. Default is 1 (record every iteration). |
window_size |
Integer, size of the window for energy stability convergence check. Default is 5. |
c1_armijo |
Numeric, Armijo condition constant for line search. |
simplified |
Logical, if
.
If |
project_full_gradient |
Logical, if |
plot |
Logical, if |
precision |
Character string, either 'float32' or 'float64' to set the precision |
The function minimizes a weighted objective combining fidelity to X0 and
orthogonality of Y, defined as:
where defect(Y) measures orthogonality deviation.
The optimization uses a Riemannian gradient descent approach with optional retraction to enforce orthogonality constraints. Convergence is checked via relative gradient norm and energy stability over a window of iterations.
A list containing:
Y: Numeric matrix, the best solution found (lowest total energy).
traces: Data frame with columns iter, time,
fidelity, orthogonality, and total_energy
for recorded iterations.
final_iter: Integer, number of iterations performed.
plot: ggplot object of the optimization trace
(if plot = TRUE), otherwise NULL.
best_total_energy: Numeric, the lowest total energy achieved.
set.seed(123) Y0 <- matrix(runif(20), 5, 4) X0 <- matrix(runif(20), 5, 4) # The original function relies on helper functions not shown here, such as: # create_optimizer, step, inv_sqrt_sym, symm, and invariant_orthogonality_defect. # The following example is conceptual: # result <- nsa_flow_torch(Y0, X0, w = 0.0, max_iter = 10, verbose = TRUE, plot = TRUE) # print(result$plot) # print(result$traces)set.seed(123) Y0 <- matrix(runif(20), 5, 4) X0 <- matrix(runif(20), 5, 4) # The original function relies on helper functions not shown here, such as: # create_optimizer, step, inv_sqrt_sym, symm, and invariant_orthogonality_defect. # The following example is conceptual: # result <- nsa_flow_torch(Y0, X0, w = 0.0, max_iter = 10, verbose = TRUE, plot = TRUE) # print(result$plot) # print(result$traces)
Performs optimization to balance fidelity to a target matrix and orthogonality of the solution matrix using a weighted objective function. The function supports multiple retraction methods and includes robust convergence checks. These constraints provide global control over column-wise sparseness by projecting the matrix onto the approximate Stiefel manifold.
nsa_flow_torch_ag( Y0, X0 = NULL, w = 0.5, retraction = c("soft_polar", "polar", "none"), max_iter = 500, tol = 1e-05, verbose = FALSE, seed = 42, apply_nonneg = TRUE, optimizer = "fast", initial_learning_rate = "default", record_every = 1, window_size = 5, c1_armijo = 1e-06, simplified = FALSE, project_full_gradient = FALSE, plot = FALSE, precision = "float64" )nsa_flow_torch_ag( Y0, X0 = NULL, w = 0.5, retraction = c("soft_polar", "polar", "none"), max_iter = 500, tol = 1e-05, verbose = FALSE, seed = 42, apply_nonneg = TRUE, optimizer = "fast", initial_learning_rate = "default", record_every = 1, window_size = 5, c1_armijo = 1e-06, simplified = FALSE, project_full_gradient = FALSE, plot = FALSE, precision = "float64" )
Y0 |
Numeric matrix of size |
X0 |
Numeric matrix of size |
w |
Numeric scalar in |
retraction |
Character string specifying the retraction method to enforce orthogonality constraints. |
max_iter |
Integer, maximum number of iterations. Default is 100. |
tol |
Numeric, tolerance for convergence based on relative gradient norm and energy stability. Default is 1e-6. |
verbose |
Logical, if |
seed |
Integer, random seed for reproducibility. If |
apply_nonneg |
Logical, if |
optimizer |
Character string, optimization algorithm to use. The "fast" option
will select the best option based on whether simplified = TRUE or FALSE.
otherwise, pass the names of optimizers supported by |
initial_learning_rate |
Numeric, initial learning rate for the optimizer.
Default is 1e-3 for non-neg and 1 for unconstrained. Otherwise, you can use |
record_every |
Integer, frequency of recording iteration metrics. Default is 1 (record every iteration). |
window_size |
Integer, size of the window for energy stability convergence check. Default is 5. |
c1_armijo |
Numeric, Armijo condition constant for line search. |
simplified |
Logical, if
.
If |
project_full_gradient |
Logical, if |
plot |
Logical, if |
precision |
Character string, either 'float32' or 'float64' to set the precision |
The function minimizes a weighted objective combining fidelity to X0 and
orthogonality of Y, defined as:
where defect(Y) measures orthogonality deviation.
The optimization uses a Riemannian gradient descent approach with optional retraction to enforce orthogonality constraints. Convergence is checked via relative gradient norm and energy stability over a window of iterations.
A list containing:
Y: Numeric matrix, the best solution found (lowest total energy).
traces: Data frame with columns iter, time,
fidelity, orthogonality, and total_energy
for recorded iterations.
final_iter: Integer, number of iterations performed.
plot: ggplot object of the optimization trace
(if plot = TRUE), otherwise NULL.
best_total_energy: Numeric, the lowest total energy achieved.
set.seed(123) Y0 <- matrix(runif(20), 5, 4) X0 <- matrix(runif(20), 5, 4) # The original function relies on helper functions not shown here, such as: # create_optimizer, step, inv_sqrt_sym, symm, and invariant_orthogonality_defect. # The following example is conceptual: # result <- nsa_flow_torch(Y0, X0, w = 0.0, max_iter = 10, verbose = TRUE, plot = TRUE) # print(result$plot) # print(result$traces)set.seed(123) Y0 <- matrix(runif(20), 5, 4) X0 <- matrix(runif(20), 5, 4) # The original function relies on helper functions not shown here, such as: # create_optimizer, step, inv_sqrt_sym, symm, and invariant_orthogonality_defect. # The following example is conceptual: # result <- nsa_flow_torch(Y0, X0, w = 0.0, max_iter = 10, verbose = TRUE, plot = TRUE) # print(result$plot) # print(result$traces)
Inverse of basic one-hot transformation of segmentations array
oneHotToSegmentation(oneHotArray, domainImage, channelFirstOrdering = FALSE)oneHotToSegmentation(oneHotArray, domainImage, channelFirstOrdering = FALSE)
oneHotArray |
an array where the channel dimension contains the one-hot encoding. |
domainImage |
image definining the geometry of the returned probability images. |
channelFirstOrdering |
Specifies the ordering of the dimensions. |
a list of probability images.
Tustison NJ
r16 <- antsImageRead( getANTsRData( "r16" ) ) seg <- kmeansSegmentation( r16, 3 )$segmentation oneHot <- segmentationToOneHot( as.array( seg ) ) oneHotInv <- oneHotToSegmentation( oneHot, seg ) r16 <- antsImageRead( getANTsRData( "r16" ) ) seg <- kmeansSegmentation( r16, 3 )$segmentation oneHot <- segmentationToOneHot( as.array( seg ), channelFirstOrdering = TRUE ) oneHotInv <- oneHotToSegmentation( oneHot, seg, channelFirstOrdering = TRUE )r16 <- antsImageRead( getANTsRData( "r16" ) ) seg <- kmeansSegmentation( r16, 3 )$segmentation oneHot <- segmentationToOneHot( as.array( seg ) ) oneHotInv <- oneHotToSegmentation( oneHot, seg ) r16 <- antsImageRead( getANTsRData( "r16" ) ) seg <- kmeansSegmentation( r16, 3 )$segmentation oneHot <- segmentationToOneHot( as.array( seg ), channelFirstOrdering = TRUE ) oneHotInv <- oneHotToSegmentation( oneHot, seg, channelFirstOrdering = TRUE )
This function generates multiple random candidate U matrices, evaluates their associated energy (without gradient descent), and returns the best-scoring initialization. A seed parameter ensures reproducibility across runs.
This function generates multiple random candidate U matrices, evaluates their associated energy (without gradient descent), and returns the best-scoring initialization. A seed parameter ensures reproducibility across runs.
optimal_simlr_initializer( data_matrices, n_init = 10, basisK, energyType = "acc", domainMatrices = NULL, domainLambdas = NULL, verbose = TRUE, seed = NULL ) optimal_simlr_initializer( data_matrices, n_init = 10, basisK, energyType = "acc", domainMatrices = NULL, domainLambdas = NULL, verbose = TRUE, seed = NULL )optimal_simlr_initializer( data_matrices, n_init = 10, basisK, energyType = "acc", domainMatrices = NULL, domainLambdas = NULL, verbose = TRUE, seed = NULL ) optimal_simlr_initializer( data_matrices, n_init = 10, basisK, energyType = "acc", domainMatrices = NULL, domainLambdas = NULL, verbose = TRUE, seed = NULL )
data_matrices |
A list of modality-specific data matrices. |
n_init |
Number of random initializations to try (default = 10). |
basisK |
Number of basis components (columns in U). |
energyType |
Energy function to evaluate. |
domainMatrices |
Optional list of domain priors (same length as data_matrices). |
domainLambdas |
Optional vector of domain weights. |
verbose |
Logical, whether to print progress. |
seed |
Optional numeric seed for reproducibility (default = NULL, no seed set). |
A list with elements:
List of U matrices (one per modality) for the best initialization.
List of corresponding V matrices.
Mean energy for the selected initialization.
A list with elements:
List of U matrices (one per modality) for the best initialization.
List of corresponding V matrices.
Mean energy for the selected initialization.
This function optimizes the sum of the matrix 'm * I', where 'I' is a binary indicator matrix with the constraint that each column may have only one non-zero entry. It ensures that the distribution of 1's is uniform across rows, softens the constraint to avoid infinite loops, and includes an optional verbose output to report the progress of the optimization.
optimize_indicator_matrix( m, max_iter = 1000, tol = 1e-06, preprocess = TRUE, verbose = FALSE )optimize_indicator_matrix( m, max_iter = 1000, tol = 1e-06, preprocess = TRUE, verbose = FALSE )
m |
A numeric matrix to optimize. |
max_iter |
The maximum number of iterations to avoid infinite loops. Default is 1000. |
tol |
A numeric value representing the tolerance for convergence. If the change in the objective function is less than this value, the loop stops. Default is 1e-6. |
preprocess |
Logical. If TRUE, flips the sign of each row where the entries are predominantly negative. |
verbose |
Logical. If TRUE, reports the objective value and convergence progress at each iteration. |
'm * I'
set.seed(123) m <- matrix(rnorm(500), nrow = 5) result <- optimize_indicator_matrix(m, max_iter = 1000, tol = 1e-6, verbose = TRUE) print(result)set.seed(123) m <- matrix(rnorm(500), nrow = 5) result <- optimize_indicator_matrix(m, max_iter = 1000, tol = 1e-6, verbose = TRUE) print(result)
Measures the scale-invariant orthogonality defect of a matrix, assessing deviation from orthonormality.
orth_residual(Y)orth_residual(Y)
Y |
Numeric matrix (p x k) to evaluate. |
The residual is computed as , where is
the normalized Gram matrix. This measures how far is from a scaled identity matrix, ignoring diagonal terms.
Numeric scalar, the orthogonality residual.
Y <- matrix(runif(10*5), 10, 5) orth_residual(Y)Y <- matrix(runif(10*5), 10, 5) orth_residual(Y)
This function takes a list of matrices (with the same number of columns) and iteratively updates them to make the columns within each matrix more orthogonal. It stops when the change in the total orthogonality error is below a given tolerance or when the maximum number of iterations is reached.
orthogonalize_feature_space( matrix_list, max_iterations = 100, learning_rate = 0.05, tolerance = 1e-04, verbose = TRUE )orthogonalize_feature_space( matrix_list, max_iterations = 100, learning_rate = 0.05, tolerance = 1e-04, verbose = TRUE )
matrix_list |
A list of numeric matrices. All matrices must have the same number of columns (e.g., k components). |
max_iterations |
The maximum number of gradient descent iterations to perform. |
learning_rate |
The step size for each update. |
tolerance |
The convergence threshold. The algorithm stops if the absolute change in the total orthogonality defect between iterations is less than this value. |
verbose |
If TRUE, prints the orthogonality error at each iteration. |
A list of orthogonalized matrices with the same dimensions as the input.
This function implements a quantile-based sparsification operation.
orthogonalizeAndQSparsify( v, sparsenessQuantile = 0.5, positivity = "either", orthogonalize = TRUE, softThresholding = FALSE, unitNorm = FALSE, sparsenessAlg = NA )orthogonalizeAndQSparsify( v, sparsenessQuantile = 0.5, positivity = "either", orthogonalize = TRUE, softThresholding = FALSE, unitNorm = FALSE, sparsenessAlg = NA )
v |
Input matrix |
sparsenessQuantile |
Quantile to control sparseness - higher is sparser |
positivity |
Restrict to positive or negative solution (beta) weights. Choices are "positive", "negative", or "either". |
orthogonalize |
Run Gram-Schmidt if TRUE. |
softThresholding |
Use soft thresholding if TRUE. |
unitNorm |
Normalize each vector to unit norm if TRUE. |
sparsenessAlg |
If specified, use a matrix partition algorithm ("orthorank", "spmp", "sum_preserving_matrix_partition" or "basic"). |
A sparsified and optionally orthogonalized matrix.
mat <- replicate(100, rnorm(20)) mat <- orthogonalizeAndQSparsify(mat)mat <- replicate(100, rnorm(20)) mat <- orthogonalizeAndQSparsify(mat)
This implements a quantile based sparsification operation
orthogonalizeAndQSparsifyOld( v, sparsenessQuantile = 0.5, positivity = "either", orthogonalize = TRUE, softThresholding = FALSE, unitNorm = FALSE, sparsenessAlg = NA )orthogonalizeAndQSparsifyOld( v, sparsenessQuantile = 0.5, positivity = "either", orthogonalize = TRUE, softThresholding = FALSE, unitNorm = FALSE, sparsenessAlg = NA )
v |
input matrix |
sparsenessQuantile |
quantile to control sparseness - higher is sparser |
positivity |
restrict to positive or negative solution (beta) weights. choices are positive, negative or either as expressed as a string. |
orthogonalize |
run gram-schmidt if TRUE. |
softThresholding |
use soft thresholding |
unitNorm |
set each vector to unit norm |
sparsenessAlg |
NA is default otherwise basic, spmp or orthorank |
matrix
Avants BB
mat <- replicate(100, rnorm(20)) mat <- orthogonalizeAndQSparsify(mat)mat <- replicate(100, rnorm(20)) mat <- orthogonalizeAndQSparsify(mat)
Pad image of size (x, y, z) to (x', y', z')} where
\code{(x', y', z') is a divisible by a user-specified factor.
padImageByFactor(image, factor)padImageByFactor(image, factor)
image |
Input ANTs image |
factor |
padding factor. Can be an integer or vector of size equal to the image dimensionality. |
a padded image
Tustison NJ, Avants BB
library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) image <- cropImage( image ) paddedImage <- padImageByFactor( image, 4 )library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) image <- cropImage( image ) paddedImage <- padImageByFactor( image, 4 )
Pad or crop image to a specified size
padOrCropImageToSize(image, size)padOrCropImageToSize(image, size)
image |
Input ANTs image |
size |
size of the output image. |
a padded/cropped image
Tustison NJ
library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) paddedImage <- padOrCropImageToSize( image, c( 333, 333 ) )library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) paddedImage <- padOrCropImageToSize( image, c( 333, 333 ) )
Computes a measure such as the RV coefficient between low-rank projections of all pairs of matrices in a list.
pairwise_matrix_similarity(mat_list, feat_list, FUN = adjusted_rvcoef)pairwise_matrix_similarity(mat_list, feat_list, FUN = adjusted_rvcoef)
mat_list |
List of matrices |
feat_list |
List of feature lists corresponding to each matrix |
FUN |
function to apply |
Matrix of RV coefficients, where each entry [i, j] represents the similarity between the low-rank projections of matrices i and j
Output contains the NImages x NImages matrix of c('PearsonCorrelation','Mattes') or any Image Metric values available in iMath. Similarity is computed after an affine registration is performed. You can also cluster the images via the dissimilarity measurement, i.e. the negated similarity metric. So, the estimated dissimilarity is returned in the matrix.
pairwiseImageDistanceMatrix( dim, myFileList, metrictype = "PearsonCorrelation", nclusters = NA )pairwiseImageDistanceMatrix( dim, myFileList, metrictype = "PearsonCorrelation", nclusters = NA )
dim |
imageDimension |
myFileList |
dd<-'MICCAI-2013-SATA-Challenge-Data/CAP/training-images/' myFileList<-list.files(path=dd, pattern = glob2rx('*nii.gz'),full.names = T,recursive = T) |
metrictype |
similarity function |
nclusters |
integer controlling max number of clusters to search over |
raw dissimilarity matrix is output, symmetrized matrix and clustering (optional) in a list
Avants BB
## Not run: # dsimdata<-pairwiseImageDistanceMatrix( 3, imagefilelist, nclusters = 5 ) ## End(Not run)## Not run: # dsimdata<-pairwiseImageDistanceMatrix( 3, imagefilelist, nclusters = 5 ) ## End(Not run)
This function performs a partial volume correction for ASL images by dividing the observed CBF by the gray matter and white matter probabilities, as described in Johnson et al., Radiology 2005: CBF_corrected = CBF_observed / (GM_prob + 0.4 * WM_prob)
partialVolumeCorrection(img, img.gm, img.wm, mask = NULL, proportion = 0.4)partialVolumeCorrection(img, img.gm, img.wm, mask = NULL, proportion = 0.4)
img |
Low-resolution image to be corrected. All input images can be either of type antsImage or numeric vectors (if numeric vectors, the mask is ignored). |
img.gm |
Gray matter probability image for partial volume correction. |
img.wm |
White matter probability image for partial volume correction. |
mask |
Brain mask for image. |
proportion |
Ratio of activity for white matter to gray matter. Assumed to be 0.4. |
Returns partial volume corrected antsImage.
Kandel BM
Method: Pattern of cerebral hypoperfusion in Alzheimer disease and mild cognitive impairment measured with arterial spin-labeling MR imaging: initial experience. Johnson NA, Jahng GH, Weiner MW, Miller BL, Chui HC, Jagust WJ, Gorno-Tempini ML, Schuff N. Radiology 2005.
Ratio of GM to WM activity: Quantitative magnetic resonance imaging of human brain perfusion at 1.5 T using steady-state inversion of arterial water. Roberts DA, Detre JA, Bolinger L, Insko EK, Leigh JS Jr. PNAS 1994.
activity.gm <- 10 activity.wm <- activity.gm * 0.4 percent.gm <- matrix(seq(0.1, 1, by = 0.1), nrow = 2) percent.wm <- -percent.gm + 1 activity.obs <- percent.gm * rnorm(n = length(percent.gm), mean = activity.gm, sd = 5) + rnorm(n = length(percent.wm), mean = activity.wm, sd = 5) activity.corrected <- partialVolumeCorrection(activity.obs, percent.gm, percent.wm)activity.gm <- 10 activity.wm <- activity.gm * 0.4 percent.gm <- matrix(seq(0.1, 1, by = 0.1), nrow = 2) percent.wm <- -percent.gm + 1 activity.obs <- percent.gm * rnorm(n = length(percent.gm), mean = activity.gm, sd = 5) + rnorm(n = length(percent.wm), mean = activity.wm, sd = 5) activity.corrected <- partialVolumeCorrection(activity.obs, percent.gm, percent.wm)
Estimate CBF using standard regression and optionally robust regression.
perfusionregression( mask_img, mat, xideal, nuis = NA, dorobust = 0, skip = 20, selectionValsForRegweights = NULL, useBayesian = 0 )perfusionregression( mask_img, mat, xideal, nuis = NA, dorobust = 0, skip = 20, selectionValsForRegweights = NULL, useBayesian = 0 )
mask_img |
Mask image selects the voxels where CBF will be estimated. Voxels corresponding to logical FALSE are not computed. |
mat |
Matrix with a column for every time-series voxel. Number of rows equals the number of time units in the series. |
xideal |
1D time-series signal to be used a ideal or model for regression. |
nuis |
Nuisance parameters obtained from '.get_perfusion_predictors'. |
dorobust |
Real value in interval from 0 to 1. If greater than 0, then robust regression will be performed. A typical value would be 0.95 i.e. use voxels with 95 percent confidence. |
skip |
skip / stride over this number of voxels to increase speed |
selectionValsForRegweights |
scalar function to guide parameter est. |
useBayesian |
if greater than zero, use a bayesian prior w/this weight |
Success – An object of type 'antsImage' containing the CBF estimate
for voxels corresponding to the mask input
Shrinidhi KL Avants BB
## Not run: # # cbf <- perfusionregression( mask_img, mat, xideal , nuis ) ## End(Not run)## Not run: # # cbf <- perfusionregression( mask_img, mat, xideal , nuis ) ## End(Not run)
The standardized uptake value (SUV) ratio (SUVR) is a semi-quantative transformation that is performed on a PET image before intepretation. This function will run rigid motion correction on the PET time series before computing SUVR. The implementation also requires an anatomical image and a segmentation that defines the reference region. This function will produce a mask, a motion corrected image and a PET suvr image mapped to the reference anatomical space.
petSUVR( petTime, anatomicalImage, anatomicalSegmentation, smoothingParameter = 2.5, labelValue = 0, subtractBackground = FALSE, mapToPet = TRUE, noMotionCorr = FALSE )petSUVR( petTime, anatomicalImage, anatomicalSegmentation, smoothingParameter = 2.5, labelValue = 0, subtractBackground = FALSE, mapToPet = TRUE, noMotionCorr = FALSE )
petTime |
pet time series antsImage or 3D image |
anatomicalImage |
antsImage that indicates the target anatomical image. one should choose this image carefully, as it will impact results. one might compare results with, for example, either whole head or whole brain targets. |
anatomicalSegmentation |
antsImage in the same space as anatomicalImage. This image should contain a whole brain mask in addition to a labeled reference region for computing SUVR. |
smoothingParameter |
physical space smoothing parameter see |
labelValue |
the integer value of the reference region as it appears in anatomicalSegmentation. If not set, we assume a binary segmentation. |
subtractBackground |
if TRUE, the method will attempt to estimate the background (non-anatomical) activation levels before computing SUVR. In this case, SUVR will be computed after subtracting this background value from the mean activation image. |
mapToPet |
boolean option causing pet to be used as fixed image in the rigid registration between anatomical and pet |
noMotionCorr |
boolean option activating simple and fast approach that may be better for dynamic data with insufficient per-frame information |
suvr antsImage
Avants BB
## Not run: suvr <- petSUVR(petTime, seg) ## End(Not run)## Not run: suvr <- petSUVR(petTime, seg) ## End(Not run)
pixeltype from antsImagesMethods that act on the slots of the
antsImage object
pixeltype(object) ## S4 method for signature 'antsImage' pixeltype(object) pixeltype(object) <- value ## S4 replacement method for signature 'antsImage' pixeltype(object) <- value components(object) ## S4 method for signature 'antsImage' components(object) components(object) <- value ## S4 replacement method for signature 'antsImage' components(object) <- value spacing(object) ## S4 method for signature 'antsImage' spacing(object) spacing(object) <- value ## S4 replacement method for signature 'antsImage' spacing(object) <- value direction(object) ## S4 method for signature 'antsImage' direction(object) direction(object) <- value ## S4 replacement method for signature 'antsImage' direction(object) <- value origin(object) ## S4 method for signature 'antsImage' origin(object) origin(object) <- value ## S4 replacement method for signature 'antsImage' origin(object) <- valuepixeltype(object) ## S4 method for signature 'antsImage' pixeltype(object) pixeltype(object) <- value ## S4 replacement method for signature 'antsImage' pixeltype(object) <- value components(object) ## S4 method for signature 'antsImage' components(object) components(object) <- value ## S4 replacement method for signature 'antsImage' components(object) <- value spacing(object) ## S4 method for signature 'antsImage' spacing(object) spacing(object) <- value ## S4 replacement method for signature 'antsImage' spacing(object) <- value direction(object) ## S4 method for signature 'antsImage' direction(object) direction(object) <- value ## S4 replacement method for signature 'antsImage' direction(object) <- value origin(object) ## S4 method for signature 'antsImage' origin(object) origin(object) <- value ## S4 replacement method for signature 'antsImage' origin(object) <- value
object |
is an object of class |
value |
is the value to assign to the slot. |
img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) stopifnot(is.character(pixeltype(img01))) pixeltype(img01) <- "float" testthat::expect_error({ pixeltype(img01) <- 1.5 }) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) stopifnot(components(img01) == 1) components(img01) <- 1L testthat::expect_error({ components(img01) <- 1.5 }) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) stopifnot(all(spacing(img01) == rep(1, 4))) spacing(img01) <- rep(1, 4) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) stopifnot(is.matrix(direction(img01))) direction(img01) <- diag(4) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) stopifnot(all(origin(img01) == rep(0, 4))) origin(img01) <- rep(0, 4)img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) stopifnot(is.character(pixeltype(img01))) pixeltype(img01) <- "float" testthat::expect_error({ pixeltype(img01) <- 1.5 }) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) stopifnot(components(img01) == 1) components(img01) <- 1L testthat::expect_error({ components(img01) <- 1.5 }) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) stopifnot(all(spacing(img01) == rep(1, 4))) spacing(img01) <- rep(1, 4) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) stopifnot(is.matrix(direction(img01))) direction(img01) <- diag(4) img01 <- as.antsImage(array(1:64, c(4, 4, 4, 1))) stopifnot(all(origin(img01) == rep(0, 4))) origin(img01) <- rep(0, 4)
Creates line plots showing the evolution of similarity, domain, and total energy across optimization iterations, for each modality. Energies are rescaled to [0,1] within each type for comparability.
plot_energy_decomposition(simlr_result, modality, show_weights = FALSE) plot_energy_decomposition(simlr_result, modality, show_weights = FALSE)plot_energy_decomposition(simlr_result, modality, show_weights = FALSE) plot_energy_decomposition(simlr_result, modality, show_weights = FALSE)
simlr_result |
A list returned by |
modality |
Character string giving the name of the modality to plot
(must match names in |
show_weights |
Logical, if TRUE also show weighted energies. |
A ggplot2 object.
A ggplot2 object.
## Not run: res <- simlr(...) plot_energy_decomposition(res, modality = "RNA") ## End(Not run) ## Not run: res <- simlr(...) plot_energy_decomposition(res, modality = "RNA") ## End(Not run)## Not run: res <- simlr(...) plot_energy_decomposition(res, modality = "RNA") ## End(Not run) ## Not run: res <- simlr(...) plot_energy_decomposition(res, modality = "RNA") ## End(Not run)
Create bar plots for each column in each data frame, showing only non-zero values. Normalize each feature s.t. max is one.
plot_features(data_list, take_abs = TRUE, n_limit = 12)plot_features(data_list, take_abs = TRUE, n_limit = 12)
data_list |
A list of data frames. |
take_abs |
boolean |
n_limit |
Integer, limit features to top n_limit with highest value |
A list of ggplot objects.
## Not run: # Simulate data set.seed(123) feature_names <- paste("Feature", 1:10) data_list <- list( df1 = data.frame(matrix(ifelse(runif(100) < 0.5, 0, runif(100)), nrow = 10)), df2 = data.frame(matrix(ifelse(runif(100) < 0.5, 0, runif(100)), nrow = 10)) ) # Set rownames rownames(data_list$df1) <- feature_names rownames(data_list$df2) <- feature_names # Use the function plots <- plot_features(data_list) # Display the plots for (i in 1:length(plots)) { print(plots[[i]]) } ## End(Not run)## Not run: # Simulate data set.seed(123) feature_names <- paste("Feature", 1:10) data_list <- list( df1 = data.frame(matrix(ifelse(runif(100) < 0.5, 0, runif(100)), nrow = 10)), df2 = data.frame(matrix(ifelse(runif(100) < 0.5, 0, runif(100)), nrow = 10)) ) # Set rownames rownames(data_list$df1) <- feature_names rownames(data_list$df2) <- feature_names # Use the function plots <- plot_features(data_list) # Display the plots for (i in 1:length(plots)) { print(plots[[i]]) } ## End(Not run)
This is a plotting utility for antsImage types with a background and color overlay option. Useful for displaying statistical results overlaid on a background image.
## S3 method for class 'antsImage' plot( x, y = NULL, color.img = "white", color.overlay = c("jet", "red", "blue", "green", "yellow", "viridis", "magma", "plasma", "inferno"), axis = 2, slices, colorbar = FALSE, title.colorbar, title.img, title.line = NA, color.colorbar, window.img, window.overlay, quality = 2, outname = NA, alpha = 1, direction = 1, begin = 0, end = 1, newwindow = FALSE, nslices = 10, domainImageMap = NULL, ncolumns = 4, useAbsoluteScale = FALSE, doCropping = TRUE, text, ... )## S3 method for class 'antsImage' plot( x, y = NULL, color.img = "white", color.overlay = c("jet", "red", "blue", "green", "yellow", "viridis", "magma", "plasma", "inferno"), axis = 2, slices, colorbar = FALSE, title.colorbar, title.img, title.line = NA, color.colorbar, window.img, window.overlay, quality = 2, outname = NA, alpha = 1, direction = 1, begin = 0, end = 1, newwindow = FALSE, nslices = 10, domainImageMap = NULL, ncolumns = 4, useAbsoluteScale = FALSE, doCropping = TRUE, text, ... )
x |
the reference image on which to overlay. |
y |
image or list of images to use as overlays. |
color.img |
color for main image. |
color.overlay |
the color for the overlay , e.g c('blue','red') length of this list should match the image list. |
axis |
the axis to slice (1 , 2 or 3) |
slices |
vector of slices to plot (e.g., c(10, 15, 20)) |
colorbar |
make colorbar? |
title.colorbar |
title for colorbar |
title.img |
title for main image (not displayed when file is saved with outname) |
title.line |
title vertical displacement (irrelevant when a file is saved with outname) |
color.colorbar |
color scale to use for colorbar |
window.img |
lower and upper thresholds for display of main image |
window.overlay |
lower and upper thresholds for display of overlay.
if you set |
quality |
integer quality magnification factor 1 => large (e.g. 10) |
outname |
name of output file if you want to write result to file, e.g.
|
alpha |
opacity |
direction |
Sets the order of colors in the scale. If 1, the default, colors are ordered from darkest to lightest. If -1, the order of colors is reversed. |
begin |
The (corrected) hue in [0,1] at which the viridis colormap begins. |
end |
The (corrected) hue in [0,1] at which the viridis colormap ends |
newwindow |
boolean controlling if we open a new device for this plot |
nslices |
number of slices to view |
domainImageMap |
this input antsImage or list contains a reference image
( |
ncolumns |
number of columns in plot |
useAbsoluteScale |
boolean determines whether dynamic range is maximized when visualizing overlays |
doCropping |
apply cropping, defaults to |
text |
vector containing x, y, label, cex and color values passed to
text command, e.g. |
... |
other parameters |
output is plot to standard R window
Avants BB
img <- makeImage(c(4, 4), rnorm(4 * 4)) mask <- makeImage( c(4, 4), as.matrix(c( 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0 ), nrow = 4) ) plot(img, list(mask)) txt <- list(x = 2.5, y = 1.5, label = "my text", cex = 4, col = "red") plot(img, list(mask), text = txt) testthat::expect_error(plot(multi_component_image)) ## Not run: img <- antsImageRead(getANTsRData("r16")) betaVals <- rnorm(prod(dim(img)), 0, 20) betaImg <- makeImage(dim(img), betaVals) %>% smoothImage(3.5) betaImg[abs(betaImg) < 1.5] <- 0 plot(img, betaImg, window.img = range(img), window.overlay = range(betaImg)) mnit <- getANTsRData("mni") mnit <- antsImageRead(mnit) mniafn <- getANTsRData("mnia") mnia <- antsImageRead(mniafn) mnia <- thresholdImage(mnia, 22, 25) mnia <- smoothImage(mnia, 1.5) mnia2 <- antsImageRead(mniafn) mnia2 <- thresholdImage(mnia2, 1, 4) mnia2 <- smoothImage(mnia2, 1.5) ofn <- paste(tempfile(), ".png", sep = "") # write directly to a file plot(mnit, list(mnia, mnia2), slices = seq(50, 140, by = 5), window.overlay = c(0.25, 1), axis = 2, color.overlay = c("red", "blue"), outname = ofn ) ## End(Not run)img <- makeImage(c(4, 4), rnorm(4 * 4)) mask <- makeImage( c(4, 4), as.matrix(c( 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0 ), nrow = 4) ) plot(img, list(mask)) txt <- list(x = 2.5, y = 1.5, label = "my text", cex = 4, col = "red") plot(img, list(mask), text = txt) testthat::expect_error(plot(multi_component_image)) ## Not run: img <- antsImageRead(getANTsRData("r16")) betaVals <- rnorm(prod(dim(img)), 0, 20) betaImg <- makeImage(dim(img), betaVals) %>% smoothImage(3.5) betaImg[abs(betaImg) < 1.5] <- 0 plot(img, betaImg, window.img = range(img), window.overlay = range(betaImg)) mnit <- getANTsRData("mni") mnit <- antsImageRead(mnit) mniafn <- getANTsRData("mnia") mnia <- antsImageRead(mniafn) mnia <- thresholdImage(mnia, 22, 25) mnia <- smoothImage(mnia, 1.5) mnia2 <- antsImageRead(mniafn) mnia2 <- thresholdImage(mnia2, 1, 4) mnia2 <- smoothImage(mnia2, 1.5) ofn <- paste(tempfile(), ".png", sep = "") # write directly to a file plot(mnit, list(mnia, mnia2), slices = seq(50, 140, by = 5), window.overlay = c(0.25, 1), axis = 2, color.overlay = c("red", "blue"), outname = ofn ) ## End(Not run)
takes an object output from renderSurfaceFunction and a list of centroids and plots the centroid network over the rendering object
plotBasicNetwork( centroids, brain, weights = NA, edgecolors = -1, backgroundColor = "white", nodecolors = "blue", nodetype = "s", edgeContrast = c(0, 1), quantileTransformWeights = FALSE, lwd = 2, minRadius = 0, maxRadius = 3, radius = NA, showOnlyConnectedNodes = TRUE )plotBasicNetwork( centroids, brain, weights = NA, edgecolors = -1, backgroundColor = "white", nodecolors = "blue", nodetype = "s", edgeContrast = c(0, 1), quantileTransformWeights = FALSE, lwd = 2, minRadius = 0, maxRadius = 3, radius = NA, showOnlyConnectedNodes = TRUE )
centroids |
input matrix of size N 3D points ( in rows ) by 3 ( in columns ), for N nodes. |
brain |
input rendering object which is output of renderSurfaceFunction. or a function derived from renderSurfaceFunction. |
weights |
edge weights, a symmetric matrix of size N. Weights should be non-negative. |
edgecolors |
a color(map) for edges. If a color map function, weights will be transformed
to the range [0,1], which is compatible with functions returned by |
backgroundColor |
background color. |
nodecolors |
a color or color vector for nodes. |
nodetype |
sphere or other node type supported by RGL. |
edgeContrast |
a vector of length 2, specifying the contrast range for edge colors.
Weights are normalized to the range [0,1].
The normalized weights can be rescaled with this parameter, eg |
quantileTransformWeights |
quantile transform the weights. |
lwd |
line width for drawing edges. |
minRadius |
minimum node radius. Ignored if the radius is specified explicitly with |
maxRadius |
maximum node radius. The node radius between |
radius |
a constant radius or vector of length nrow(centroids). If not specified, node radius is determined by the sum of edge weights connected to the node. |
showOnlyConnectedNodes |
boolean, if |
If edgecolors is not specified, a heat-like color palette is used. Weights
can be quantile transformed or clipped at a given quantile in order to improve
contrast.
If weights are not specified, only the nodes are plotted.
None
Avants BB, Duda JT, Cook PA
## Not run: # more complete example mnit <- getANTsRData("mni") mnit <- antsImageRead(mnit) mnia <- getANTsRData("mnia") mnia <- antsImageRead(mnia) mnit <- thresholdImage(mnit, 1, max(mnit)) mnit <- iMath(mnit, "FillHoles") mnit <- thresholdImage(mnit, 1, 2) cnt <- getCentroids(mnia, clustparam = 0) aalcnt <- cnt[1:90, 1:3] brain <- renderSurfaceFunction( surfimg = list(mnit), alphasurf = 0.1, smoothsval = 1.5 ) testweights <- matrix(rep(0, 90 * 90), nrow = 90) testweights[31, 37] <- 1 # ant cingulate to hipp testweights[31, 36] <- 2 # ant cingulate to post cingulate testweights[11, 65] <- 3 # broca to angular plotBasicNetwork(centroids = aalcnt, brain, weights = testweights, edgecolors = "red") id <- rgl::par3d("userMatrix") rid <- rotate3d(id, -pi / 2, 1, 0, 0) rid2 <- rotate3d(id, pi / 2, 0, 0, 1) rid3 <- rotate3d(id, -pi / 2, 0, 0, 1) rgl::par3d(userMatrix = id) dd <- make3ViewPNG(rid, id, rid2, paste("network1", sep = "")) rgl::par3d(userMatrix = id) # another example mni <- getANTsRData("mni") mni <- antsImageRead(mni) mnit <- thresholdImage(mni, 1, max(mni)) mnit <- iMath(mnit, "FillHoles") mniseg <- kmeansSegmentation(mni, 3)$segmentation wmbkgd <- thresholdImage(mniseg, 3, 3) %>% iMath("GetLargestComponent") %>% iMath("FillHoles") wmbkgd <- smoothImage(iMath(wmbkgd, "MD", 1), 2.0) brain <- renderSurfaceFunction( surfimg = list(wmbkgd), alphasurf = 0.8, smoothsval = 1.0 ) data(powers_areal_mni_itk) coords <- powers_areal_mni_itk[, 1:3] id <- rgl::par3d("userMatrix") rid <- rotate3d(id, -pi / 2, 1, 0, 0) rid2 <- rotate3d(id, pi / 2, 0, 0, 1) rid3 <- rotate3d(id, -pi / 2, 0, 0, 1) rgl::par3d(userMatrix = id) handMat2 <- t(matrix(c( -0.9998656511, 0.01626961, 0.00198165, 0, -0.0163816363, -0.99584705, -0.08955579, 0, 0.0005163439, -0.08957647, 0.99597979, 0, 0.0000000000, 0.00000000, 0.00000000, 1 ), ncol = 4)) loccolor <- as.character(powers_areal_mni_itk$Color) loccolor[loccolor == "Peach"] <- "sienna1" loccolor[loccolor == "Cyan"] <- "cyan" loccolor[loccolor == "Orange"] <- "orange" loccolor[loccolor == "Purple"] <- "darkorchid1" loccolor[loccolor == "Pink"] <- "deeppink" loccolor[loccolor == "Red"] <- "red" loccolor[loccolor == "Gray"] <- "gray74" loccolor[loccolor == "Teal"] <- "turquoise4" loccolor[loccolor == "Blue"] <- "blue" loccolor[loccolor == "Yellow"] <- "yellow" loccolor[loccolor == "Black"] <- "black" loccolor[loccolor == "Brown"] <- "brown" loccolor[loccolor == "Pale blue"] <- "steelblue1" loccolor[loccolor == "Green"] <- "green" tt <- plotBasicNetwork( centroids = coords, brain, nodecolors = loccolor, radius = 3 ) dd <- make3ViewPNG(handMat2, id, rid2, tempfile(fileext = ".png")) rgl::par3d(userMatrix = id) ## End(Not run)## Not run: # more complete example mnit <- getANTsRData("mni") mnit <- antsImageRead(mnit) mnia <- getANTsRData("mnia") mnia <- antsImageRead(mnia) mnit <- thresholdImage(mnit, 1, max(mnit)) mnit <- iMath(mnit, "FillHoles") mnit <- thresholdImage(mnit, 1, 2) cnt <- getCentroids(mnia, clustparam = 0) aalcnt <- cnt[1:90, 1:3] brain <- renderSurfaceFunction( surfimg = list(mnit), alphasurf = 0.1, smoothsval = 1.5 ) testweights <- matrix(rep(0, 90 * 90), nrow = 90) testweights[31, 37] <- 1 # ant cingulate to hipp testweights[31, 36] <- 2 # ant cingulate to post cingulate testweights[11, 65] <- 3 # broca to angular plotBasicNetwork(centroids = aalcnt, brain, weights = testweights, edgecolors = "red") id <- rgl::par3d("userMatrix") rid <- rotate3d(id, -pi / 2, 1, 0, 0) rid2 <- rotate3d(id, pi / 2, 0, 0, 1) rid3 <- rotate3d(id, -pi / 2, 0, 0, 1) rgl::par3d(userMatrix = id) dd <- make3ViewPNG(rid, id, rid2, paste("network1", sep = "")) rgl::par3d(userMatrix = id) # another example mni <- getANTsRData("mni") mni <- antsImageRead(mni) mnit <- thresholdImage(mni, 1, max(mni)) mnit <- iMath(mnit, "FillHoles") mniseg <- kmeansSegmentation(mni, 3)$segmentation wmbkgd <- thresholdImage(mniseg, 3, 3) %>% iMath("GetLargestComponent") %>% iMath("FillHoles") wmbkgd <- smoothImage(iMath(wmbkgd, "MD", 1), 2.0) brain <- renderSurfaceFunction( surfimg = list(wmbkgd), alphasurf = 0.8, smoothsval = 1.0 ) data(powers_areal_mni_itk) coords <- powers_areal_mni_itk[, 1:3] id <- rgl::par3d("userMatrix") rid <- rotate3d(id, -pi / 2, 1, 0, 0) rid2 <- rotate3d(id, pi / 2, 0, 0, 1) rid3 <- rotate3d(id, -pi / 2, 0, 0, 1) rgl::par3d(userMatrix = id) handMat2 <- t(matrix(c( -0.9998656511, 0.01626961, 0.00198165, 0, -0.0163816363, -0.99584705, -0.08955579, 0, 0.0005163439, -0.08957647, 0.99597979, 0, 0.0000000000, 0.00000000, 0.00000000, 1 ), ncol = 4)) loccolor <- as.character(powers_areal_mni_itk$Color) loccolor[loccolor == "Peach"] <- "sienna1" loccolor[loccolor == "Cyan"] <- "cyan" loccolor[loccolor == "Orange"] <- "orange" loccolor[loccolor == "Purple"] <- "darkorchid1" loccolor[loccolor == "Pink"] <- "deeppink" loccolor[loccolor == "Red"] <- "red" loccolor[loccolor == "Gray"] <- "gray74" loccolor[loccolor == "Teal"] <- "turquoise4" loccolor[loccolor == "Blue"] <- "blue" loccolor[loccolor == "Yellow"] <- "yellow" loccolor[loccolor == "Black"] <- "black" loccolor[loccolor == "Brown"] <- "brown" loccolor[loccolor == "Pale blue"] <- "steelblue1" loccolor[loccolor == "Green"] <- "green" tt <- plotBasicNetwork( centroids = coords, brain, nodecolors = loccolor, radius = 3 ) dd <- make3ViewPNG(handMat2, id, rid2, tempfile(fileext = ".png")) rgl::par3d(userMatrix = id) ## End(Not run)
PlotPrettyGraph given inputs from the makeGraph function. adapted from http://is-r.tumblr.com/.
plotPrettyGraph( adjacencyMatrix, functionToPlot, pngfn = tempfile(fileext = ".png"), scaleText = 0.5, vertexSize = NA, figScale = 11, layoutmode = "eigen", hueval = 0 )plotPrettyGraph( adjacencyMatrix, functionToPlot, pngfn = tempfile(fileext = ".png"), scaleText = 0.5, vertexSize = NA, figScale = 11, layoutmode = "eigen", hueval = 0 )
adjacencyMatrix |
igraph adjacencyMatrix |
functionToPlot |
igraph node-level graph value e.g. degree, page.rank, etc |
pngfn |
filename for output png or to screen if NA |
scaleText |
relative size of text to vertices |
vertexSize |
cex size of vertices |
figScale |
the figure will be of square size 2^figScale in pixels |
layoutmode |
see gplot.layout in sna package |
hueval |
controls the hue in hsv |
no output
Avants BB, Christopher DeSante and David Sparks
data("bold_correlation_matrix", package = "ANTsR") dmat <- data.matrix(bold_correlation_matrix) if (usePkg("igraph")) { gg <- makeGraph(dmat, 0.1) rownames(gg$adjacencyMatrix) <- colnames(bold_correlation_matrix) plotPrettyGraph(gg$adjacencyMatrix, gg$degree, figScale = 12, scaleText = 5) }data("bold_correlation_matrix", package = "ANTsR") dmat <- data.matrix(bold_correlation_matrix) if (usePkg("igraph")) { gg <- makeGraph(dmat, 0.1) rownames(gg$adjacencyMatrix) <- colnames(bold_correlation_matrix) plotPrettyGraph(gg$adjacencyMatrix, gg$degree, figScale = 12, scaleText = 5) }
Given data and factor loadings, this function computes factor scores, communalities, uniquenesses, and per-factor variance explained using linear modeling. It provides a convenient post-hoc summary of a factor analysis solution.
posthoc_fa_summary(data, loadings, scores = NULL, method = "PAF")posthoc_fa_summary(data, loadings, scores = NULL, method = "PAF")
data |
Numeric matrix or data.frame of observed variables (n x p). |
loadings |
Numeric matrix of factor loadings (p x k). |
scores |
Optional numeric matrix of factor scores (n x k). If NULL scores are computed by least squares regression. |
method |
Character string describing the extraction method (e.g., "PAF", "NSA-Flow", "ML"). |
A list with components:
Matrix of factor scores (n x k).
Named numeric vector of communalities for each variable.
Named numeric vector of uniquenesses (1 - communality).
Data frame with variance explained per factor.
Total proportion of variance explained across factors.
Reconstructed data from scores and loadings.
Matrix of residuals: data - reconstructed.
set.seed(42) n <- 100; p <- 6; k <- 2 scores_true <- matrix(rnorm(n * k), n, k) loadings <- matrix(runif(p * k, 0.5, 0.8), p, k) data <- scores_true %*% t(loadings) + matrix(rnorm(n * p, sd = 0.5), n, p) colnames(data) <- paste0("Var", 1:p) results <- posthoc_fa_summary(data, loadings, method = "PAF") str(results)set.seed(42) n <- 100; p <- 6; k <- 2 scores_true <- matrix(rnorm(n * k), n, k) loadings <- matrix(runif(p * k, 0.5, 0.8), p, k) data <- scores_true %*% t(loadings) + matrix(rnorm(n * p, sd = 0.5), n, p) colnames(data) <- paste0("Var", 1:p) results <- posthoc_fa_summary(data, loadings, method = "PAF") str(results)
A data frame providing coordinates for the nodes identified by Powers at al. Coordinates have been modified from nifti space to ITK space
powers_areal_mni_itkpowers_areal_mni_itk
A data frame listing the following variables.
xx coordinate
yy coordinate
zz coordinate
ROIunique integer for each node
SystemLabelunique integer for each system
SystemNameunique name for each system
Colorname of color for system
rred value for system
ggreen value for system
bblue value for system
Anatomyanatomical location as determined by OASIS labeling
Lobelobe location of node
BrodmannBroadmann area number
AALAAL region label
Power, J. D., et al. (2011). "Functional network organization of the human brain." Neuron 72(4): 665-678.
data(powers_areal_mni_itk) ## Not run: fixed <- antsImageRead(getANTsRData("ch2")) moving <- antsImageRead(getANTsRData("mni")) mytx <- antsRegistration( fixed = fixed, moving = moving, typeofTransform = c("SyN") ) data("powers_areal_mni_itk", package = "ANTsR", envir = environment()) coords <- powers_areal_mni_itk[, 1:3] ch2reg <- antsRegistration(fixed, moving, typeofTransform = "SyN") coordsw <- antsApplyTransformsToPoints( dim = 3, points = coords, transformlist = ch2reg$fwdtransforms, whichtoinvert = c(FALSE, FALSE) ) ptrd <- 3 powersLabels <- makePointsImage(coordsw, moving, radius = pard) plot(moving, powersLabels, axis = 3, nslices = 30) ## End(Not run)data(powers_areal_mni_itk) ## Not run: fixed <- antsImageRead(getANTsRData("ch2")) moving <- antsImageRead(getANTsRData("mni")) mytx <- antsRegistration( fixed = fixed, moving = moving, typeofTransform = c("SyN") ) data("powers_areal_mni_itk", package = "ANTsR", envir = environment()) coords <- powers_areal_mni_itk[, 1:3] ch2reg <- antsRegistration(fixed, moving, typeofTransform = "SyN") coordsw <- antsApplyTransformsToPoints( dim = 3, points = coords, transformlist = ch2reg$fwdtransforms, whichtoinvert = c(FALSE, FALSE) ) ptrd <- 3 powersLabels <- makePointsImage(coordsw, moving, radius = pard) plot(moving, powersLabels, axis = 3, nslices = 30) ## End(Not run)
ppmi template 500Parcels Yeo2011 17Networks 2023 homotopic
A data frame providing coordinates and names for the PPMI 500 parcels Yeo atlas.
ppmi_yeo_labelsppmi_yeo_labels
A data frame with columns: x, y, z, ROI, SystemName, AAL.
Obtains predictions from a fitted fusedRidge object on new data.
## S3 method for class 'fusedRidge' predict( object, newx, newcovs = NULL, type = c("link", "response"), topK = NULL, ... )## S3 method for class 'fusedRidge' predict( object, newx, newcovs = NULL, type = c("link", "response"), topK = NULL, ... )
object |
A fitted |
newx |
Matrix of new predictor variables. |
newcovs |
Optional matrix or data frame of new covariates. Must be provided if the model was trained with covariates. |
type |
Type of prediction. |
topK |
Optional integer. If provided, keeps only the |
... |
Additional arguments (not used). |
A matrix of predictions with dimensions nrow(newx) x length(thresholds).
Obtains predictions from a fitted fusedRidgeDirect object on new data.
## S3 method for class 'fusedRidgeDirect' predict( object, newx, newcovs = NULL, type = c("link", "response"), topK = NULL, ... )## S3 method for class 'fusedRidgeDirect' predict( object, newx, newcovs = NULL, type = c("link", "response"), topK = NULL, ... )
object |
A fitted |
newx |
Matrix of new predictor variables. |
newcovs |
Optional matrix or data frame of new covariates. Must be provided if the model was trained with covariates. |
type |
Type of prediction. |
topK |
Optional integer. If provided, keeps only the |
... |
Additional arguments (passed to |
A matrix of predictions with dimensions nrow(newx) x length(thresholds).
Obtains predictions from a fitted fusedRidgeTorch object on new data.
## S3 method for class 'fusedRidgeTorch' predict( object, newx, newcovs = NULL, type = c("link", "response"), topK = NULL, ... )## S3 method for class 'fusedRidgeTorch' predict( object, newx, newcovs = NULL, type = c("link", "response"), topK = NULL, ... )
object |
A fitted |
newx |
Matrix of new predictor variables. |
newcovs |
Optional matrix or data frame of new covariates. Must be provided if the model was trained with covariates. |
type |
Type of prediction. |
topK |
Optional integer. If provided, keeps only the |
... |
Additional arguments (passed to |
A matrix of predictions with dimensions nrow(newx) x length(thresholds).
predict output matrices from simlr solution
predictSimlr(x, simsol, targetMatrix, sourceMatrices, projectv = TRUE)predictSimlr(x, simsol, targetMatrix, sourceMatrices, projectv = TRUE)
x |
A list that contains the named matrices. |
simsol |
the simlr solution |
targetMatrix |
an optional index that sets a fixed target (outcome) matrix. If not set, each basis set will be used to predict its corresponding matrix. |
sourceMatrices |
an optional index vector that sets predictor matrices. If not set, each basis set will be used to predict its corresponding matrix. |
projectv |
boolean to determine whether raw u or x * v is used; default to TRUE which uses the x * v approach |
A list of variance explained, predicted matrices and error metrics:
Mean variance explained for u_i predicting x_i.
Predicted x_i matrix.
Initial matrix norm.
Matrix norm of the error term.
Summary t-stats for each matrix and each u_i.
Estimated order of the u_i predictors aggregated over all terms.
BB Avants.
# see simlr examples# see simlr examples
Preprocess fMRI data by performing compcor/motion correction, nuisance regression, band-pass filtering, and spatial smoothing.
preprocessfMRI( boldImage, maskImage = NULL, maskingMeanRatioThreshold = 0.75, initialNuisanceVariables, numberOfCompCorComponents = 6, doMotionCorrection = TRUE, useMotionCorrectedImage = FALSE, motionCorrectionAccuracyLevel = 1, meanBoldFixedImageForMotionCorrection = NULL, frequencyLowThreshold = NA, frequencyHighThreshold = NA, spatialSmoothingType = "none", spatialSmoothingParameters = 0, residualizeMatrix = TRUE )preprocessfMRI( boldImage, maskImage = NULL, maskingMeanRatioThreshold = 0.75, initialNuisanceVariables, numberOfCompCorComponents = 6, doMotionCorrection = TRUE, useMotionCorrectedImage = FALSE, motionCorrectionAccuracyLevel = 1, meanBoldFixedImageForMotionCorrection = NULL, frequencyLowThreshold = NA, frequencyHighThreshold = NA, spatialSmoothingType = "none", spatialSmoothingParameters = 0, residualizeMatrix = TRUE )
boldImage |
4-D ANTs image fMRI data. |
maskImage |
3-D ANTs image defining the region of interest. |
maskingMeanRatioThreshold |
If mask image is not specified, a mask image is created using the specified threshold which is in terms of the mean of the average image ie 0.8 means threshold at 0.8 of the mean. |
initialNuisanceVariables |
Optional initial nuisance variables. |
numberOfCompCorComponents |
Numer of CompCor nuisance components. |
doMotionCorrection |
Boolean indicating whether motion correction should be performed and used in nuisance regression. |
useMotionCorrectedImage |
Boolean indicating whether or not the motion corrected image should be used in the rest of the pipeline. This is off by default to avoid additional interpolation. |
motionCorrectionAccuracyLevel |
Accuracy for the motion correcting registration: 0 = fast/debug parameters, 1 = intrasession parameters, or 2 = intersession/intersubject parameters. |
meanBoldFixedImageForMotionCorrection |
Optional target fixed image for motion correction. |
frequencyLowThreshold |
Lower threshold for bandpass filtering. |
frequencyHighThreshold |
Upper threshold for bandpass filtering. |
spatialSmoothingType |
Either |
spatialSmoothingParameters |
For gaussian smoothing, this is a single
scalar designating the smoothing sigma (in mm). For perona-malik, a vector
needs to be specified with the conductance parameter and the number of
iterations, e.g. |
residualizeMatrix |
boolean |
List of:
Cleaned BOLD image.
mask image.
Framewise change in BOLD signal, as in Powers et al.
DVARS after cleaning image.
Framewise displacement.
Global signal.
Nuisance variables used in denoising.
Tustison NJ, Avants BB
Power et al. 2012, "Spurious but systematic correlations in functional connectivity MRI networks arise from subject motion." NeuroImage 59, 2142-2154.
Preprocess resting fMRI by performing compcor/motion correction, nuisance regression, band-pass filtering, and spatial smoothing.
preprocessRestingBOLD( boldImage, maskImage = NULL, maskingMeanRatioThreshold = 0.75, initialNuisanceVariables, denseFramewise = FALSE, numberOfCompCorComponents = 6, doMotionCorrection = TRUE, useMotionCorrectedImage = FALSE, motionCorrectionAccuracyLevel = 1, motionCorrectionIterations = 1, meanBoldFixedImageForMotionCorrection = NULL, frequencyLowThreshold = NA, frequencyHighThreshold = NA, spatialSmoothingType = "none", spatialSmoothingParameters = 0, residualizeMatrix = TRUE )preprocessRestingBOLD( boldImage, maskImage = NULL, maskingMeanRatioThreshold = 0.75, initialNuisanceVariables, denseFramewise = FALSE, numberOfCompCorComponents = 6, doMotionCorrection = TRUE, useMotionCorrectedImage = FALSE, motionCorrectionAccuracyLevel = 1, motionCorrectionIterations = 1, meanBoldFixedImageForMotionCorrection = NULL, frequencyLowThreshold = NA, frequencyHighThreshold = NA, spatialSmoothingType = "none", spatialSmoothingParameters = 0, residualizeMatrix = TRUE )
boldImage |
4-D ANTs image fMRI data. |
maskImage |
3-D ANTs image defining the region of interest. |
maskingMeanRatioThreshold |
If mask image is not specified, a mask image is created using the specified threshold which is in terms of the mean of the average image ie 0.8 means threshold at 0.8 of the mean. |
initialNuisanceVariables |
Optional initial nuisance variables. |
denseFramewise |
boolean for dense framewise stats |
numberOfCompCorComponents |
Numer of CompCor nuisance components. |
doMotionCorrection |
Boolean indicating whether motion correction should be performed and used in nuisance regression. |
useMotionCorrectedImage |
Boolean indicating whether or not the motion corrected image should be used in the rest of the pipeline. This is off by default to avoid additional interpolation. |
motionCorrectionAccuracyLevel |
Accuracy for the motion correcting registration: 0 = fast/debug parameters, 1 = intrasession parameters, or 2 = intersession/intersubject parameters. |
motionCorrectionIterations |
number of iteration for motion correction |
meanBoldFixedImageForMotionCorrection |
Optional target fixed image for motion correction. |
frequencyLowThreshold |
Lower threshold for bandpass filtering. |
frequencyHighThreshold |
Upper threshold for bandpass filtering. |
spatialSmoothingType |
Either |
spatialSmoothingParameters |
For gaussian smoothing, this is a single
scalar designating the smoothing sigma (in mm). For perona-malik, a vector
needs to be specified with the conductance parameter and the number of
iterations, e.g. |
residualizeMatrix |
boolean |
List of:
Cleaned BOLD image.
mask image.
Framewise change in BOLD signal, as in Powers et al.
DVARS after cleaning image.
Framewise displacement.
Global signal.
Nuisance variables used in denoising.
Tustison NJ, Avants BB
Power et al. 2012, "Spurious but systematic correlations in functional connectivity MRI networks arise from subject motion." NeuroImage 59, 2142-2154.
markov random field regularized, prior-based image segmentation that is a wrapper around atropos (see ANTs and related publications).
priorBasedSegmentation( img, priors, mask, priorWeight = 0.25, mrf = 0.1, iterations = 25, verbose = FALSE )priorBasedSegmentation( img, priors, mask, priorWeight = 0.25, mrf = 0.1, iterations = 25, verbose = FALSE )
img |
input image or image list for multivariate segmentation |
priors |
list of priors that cover the number of classes |
mask |
segment inside this mask |
priorWeight |
usually 0 (priors used for initialization only), 0.25 or 0.5. |
mrf |
regularization, higher is smoother, a numerical value in range 0.0 to 0.2 |
iterations |
maximum number of iterations. could be a large value eg 25. |
verbose |
maximum number of iterations. could be a large value eg 25. |
segmentation and probability images
Brian B. Avants
fi <- antsImageRead(getANTsRData("r16")) seg <- kmeansSegmentation(fi, 3) msk <- thresholdImage(seg$segmentation, 1, Inf) pseg <- priorBasedSegmentation(fi, seg$probabilityimages, msk, 0.25, 0.1, 3)fi <- antsImageRead(getANTsRData("r16")) seg <- kmeansSegmentation(fi, 3) msk <- thresholdImage(seg$segmentation, 1, Inf) pseg <- priorBasedSegmentation(fi, seg$probabilityimages, msk, 0.25, 0.1, 3)
Iteratively projects a non-negative matrix onto the intersection of non-negative matrices and matrices with orthonormal columns.
project_to_orthonormal_nonnegative( X, max_iter = 100, tol = 1e-04, constraint = "positive" )project_to_orthonormal_nonnegative( X, max_iter = 100, tol = 1e-04, constraint = "positive" )
X |
A square numeric matrix with non-negative entries. |
max_iter |
Maximum number of iterations for the alternating projection. |
tol |
Tolerance for convergence. The projection stops if the change in the matrix norm is below this tolerance, or if max_iter is reached. |
constraint |
either or positive |
A matrix Y that is non-negative and whose columns are orthonormal, closest to X in a sense defined by the alternating projections.
Iteratively projects a non-negative matrix towards the intersection of non-negative matrices and matrices with orthonormal columns. Allows control over the degree of orthonormality enforced.
project_to_partially_orthonormal_nonnegative( X, max_iter = 100, tol = 1e-06, constraint = "positive", ortho_strength = 1, epsilon = 1e-04 )project_to_partially_orthonormal_nonnegative( X, max_iter = 100, tol = 1e-06, constraint = "positive", ortho_strength = 1, epsilon = 1e-04 )
X |
A square or rectangular numeric matrix with non-negative entries. |
max_iter |
Maximum number of iterations for the alternating projection. |
tol |
Tolerance for convergence (Frobenius norm of change). |
constraint |
'positive' or 'either' (influences initial data preprocessing). |
ortho_strength |
A value between 0 and 1, controlling the degree of orthonormality enforced. 0 means no orthonormality enforcement (only non-negativity), 1 means full orthonormality. |
epsilon |
very small value for stability. |
A matrix Y that is non-negative and has columns that are controlled in their orthonormality by ortho_strength.
# Example matrix (non-negative) X_sample <- matrix(c( 1, 2, 0.1, 0.5, 1, 0.8, 0.2, 0.5, 1 ), nrow=3, byrow=TRUE) # Full orthonormality (ortho_strength = 1) Y_full_ortho = project_to_partially_orthonormal_nonnegative( X_sample, ortho_strength = 1, max_iter = 5) # No orthonormality enforcement (ortho_strength = 0) - # should just be pmax(X, 0) Y_no_ortho <- project_to_partially_orthonormal_nonnegative( X_sample, ortho_strength = 0, max_iter = 5) # Low iter for speed# Example matrix (non-negative) X_sample <- matrix(c( 1, 2, 0.1, 0.5, 1, 0.8, 0.2, 0.5, 1 ), nrow=3, byrow=TRUE) # Full orthonormality (ortho_strength = 1) Y_full_ortho = project_to_partially_orthonormal_nonnegative( X_sample, ortho_strength = 1, max_iter = 5) # No orthonormality enforcement (ortho_strength = 0) - # should just be pmax(X, 0) Y_no_ortho <- project_to_partially_orthonormal_nonnegative( X_sample, ortho_strength = 0, max_iter = 5) # Low iter for speed
Computes CBF from ASL - pasl or pcasl
quantifyCBF(perfusion, mask, parameters, M0val = NA, outlierValue = 0.02)quantifyCBF(perfusion, mask, parameters, M0val = NA, outlierValue = 0.02)
perfusion |
input asl matrix |
mask |
3D image mask (antsImage) |
parameters |
list with entries for sequence and m0 (at minimimum) |
M0val |
baseline M0 value (optional) |
outlierValue |
trim outliers by this fractional value (optional) |
a list is output with 3 types of cbf images
Avants BB, Kandel B, Duda JT
## Not run: if (!exists("fn")) { fn <- getANTsRData("pcasl") } # PEDS029_20101110_pcasl_1.nii.gz # high motion subject asl <- antsImageRead(fn) # image available at http://files.figshare.com/1701182/PEDS012_20131101.zip pcasl.bayesian <- aslPerfusion(asl, dorobust = 0., useDenoiser = 4, skip = 11, useBayesian = 1000, moreaccurate = 0, verbose = T, maskThresh = 0.5 ) # throw away lots of data # user might compare to useDenoiser=FALSE pcasl.parameters <- list(sequence = "pcasl", m0 = pcasl.bayesian$m0) cbf <- quantifyCBF( pcasl.bayesian$perfusion, pcasl.bayesian$mask, pcasl.parameters ) meancbf <- cbf$kmeancbf print(mean(meancbf[pcasl.bayesian$mask == 1])) antsImageWrite(meancbf, "temp.nii.gz") pcasl.processing <- aslPerfusion(asl, moreaccurate = 0, dorobust = 0.95, useDenoiser = NULL, skip = 5, useBayesian = 0 ) # user might compare to useDenoiser=FALSE pcasl.parameters <- list(sequence = "pcasl", m0 = pcasl.processing$m0) cbf <- quantifyCBF(pcasl.processing$perfusion, pcasl.processing$mask, pcasl.parameters) meancbf <- cbf$kmeancbf print(mean(meancbf[pcasl.processing$mask == 1])) antsImageWrite(meancbf, "temp2.nii.gz") plot(meancbf, slices = "1x50x1") ## End(Not run)## Not run: if (!exists("fn")) { fn <- getANTsRData("pcasl") } # PEDS029_20101110_pcasl_1.nii.gz # high motion subject asl <- antsImageRead(fn) # image available at http://files.figshare.com/1701182/PEDS012_20131101.zip pcasl.bayesian <- aslPerfusion(asl, dorobust = 0., useDenoiser = 4, skip = 11, useBayesian = 1000, moreaccurate = 0, verbose = T, maskThresh = 0.5 ) # throw away lots of data # user might compare to useDenoiser=FALSE pcasl.parameters <- list(sequence = "pcasl", m0 = pcasl.bayesian$m0) cbf <- quantifyCBF( pcasl.bayesian$perfusion, pcasl.bayesian$mask, pcasl.parameters ) meancbf <- cbf$kmeancbf print(mean(meancbf[pcasl.bayesian$mask == 1])) antsImageWrite(meancbf, "temp.nii.gz") pcasl.processing <- aslPerfusion(asl, moreaccurate = 0, dorobust = 0.95, useDenoiser = NULL, skip = 5, useBayesian = 0 ) # user might compare to useDenoiser=FALSE pcasl.parameters <- list(sequence = "pcasl", m0 = pcasl.processing$m0) cbf <- quantifyCBF(pcasl.processing$perfusion, pcasl.processing$mask, pcasl.parameters) meancbf <- cbf$kmeancbf print(mean(meancbf[pcasl.processing$mask == 1])) antsImageWrite(meancbf, "temp2.nii.gz") plot(meancbf, slices = "1x50x1") ## End(Not run)
quantifySNPs converts trinary snps to frequency data
quantifySNPs( snps, freqthresh = 0.1, shiftit = FALSE, replaceWithF = TRUE, traitvecin = NA, trainvec = NA )quantifySNPs( snps, freqthresh = 0.1, shiftit = FALSE, replaceWithF = TRUE, traitvecin = NA, trainvec = NA )
snps |
input matrix |
freqthresh |
remove snps below this frequency |
shiftit |
shift the snps to smooth the estimate |
replaceWithF |
replaces snps with frequency values |
traitvecin |
map snps to trait vector |
trainvec |
defines training data |
matrix is output
Avants BB
mat <- matrix(c(0, 1, 2, 0, 0, 1, 2, 2, 2), ncol = 3) wmat <- quantifySNPs(mat, freqthresh = 0)mat <- matrix(c(0, 1, 2, 0, 0, 1, 2, 2, 2), ncol = 3) wmat <- quantifySNPs(mat, freqthresh = 0)
Computes sample quantiles for an image, with the option of a mask.
## S3 method for class 'antsImage' quantile(x, ..., mask)## S3 method for class 'antsImage' quantile(x, ..., mask)
x |
Object of class |
... |
Arguments passed to |
mask |
object to subset the image. If missing, then all values of the image are used |
Output of quantile
img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 quantile(img, mask = mask)img <- makeImage(c(10, 10), rnorm(100)) mask <- img > 0 quantile(img, mask = mask)
uses random matrix to estimate cca results
randcca(x, y, k, seed = NA)randcca(x, y, k, seed = NA)
x |
input matrix |
y |
input matrix |
k |
rank to use |
seed |
for testing |
outputs a list containing:
low-rank whitened joint matrix
low-rank svd of joint matrix
Avants BB
set.seed(13) x <- matrix(rnorm(3000), nrow = 50) y <- x %*% matrix(rnorm(60 * 100), nrow = 60) k <- 10 dr <- randcca(x, y, k, 1)set.seed(13) x <- matrix(rnorm(3000), nrow = 50) y <- x %*% matrix(rnorm(60 * 100), nrow = 60) k <- 10 dr <- randcca(x, y, k, 1)
Apply rigid, affine and/or deformable maps to an input set of training images. The reference image domain defines the space in which this happens.
randomlyTransformImageData( referenceImage, inputImageList, segmentationImageList = NULL, numberOfSimulations = 10, transformType = "affine", sdAffine = 0.02, deformationTransformType = c("bspline", "exponential"), numberOfRandomPoints = 1000, sdNoise = 10, numberOfFittingLevels = 4, meshSize = 1, sdSmoothing = 4, inputImageInterpolator = "linear", segmentationImageInterpolator = "nearestNeighbor" )randomlyTransformImageData( referenceImage, inputImageList, segmentationImageList = NULL, numberOfSimulations = 10, transformType = "affine", sdAffine = 0.02, deformationTransformType = c("bspline", "exponential"), numberOfRandomPoints = 1000, sdNoise = 10, numberOfFittingLevels = 4, meshSize = 1, sdSmoothing = 4, inputImageInterpolator = "linear", segmentationImageInterpolator = "nearestNeighbor" )
referenceImage |
defines the spatial domain for all output images. If
the input images do not match the spatial domain of the reference image, we
internally resample the target to the reference image. This could have
unexpected consequences. Resampling to the reference domain is performed by
testing using |
inputImageList |
list of lists of input images to warp. The internal list sets contains one or more images (per subject) which are assumed to be mutually aligned. The outer list contains multiple subject lists which are randomly sampled to produce output image list. |
segmentationImageList |
list of segmentation images corresponding to the input image list (optional). |
numberOfSimulations |
number of output images. Default = 10. |
transformType |
one of the following options
|
sdAffine |
parameter dictating deviation amount from identity for random linear transformations. Default = 0.02. |
deformationTransformType |
one of the following options
|
numberOfRandomPoints |
number of displacement points for the deformation field. Default = 1000. |
sdNoise |
standard deviation of the displacement field noise (in mm). Default = 10.0. |
numberOfFittingLevels |
(bspline deformation only) number of fitting levels. Default = 4. |
meshSize |
(bspline deformation only) scalar or n-D vector determining fitting resolution. Default = 1. |
sdSmoothing |
(exponential deformation only) standard deviation of the Gaussian smoothing in mm. Default = 4.0. |
inputImageInterpolator |
one of the following options
|
segmentationImageInterpolator |
one of the following options
|
list (if no directory set) or boolean for success, failure
Avants BB, Tustison NJ
library( ANTsR ) image1 <- antsImageRead( getANTsRData( "r16" ) ) image2 <- antsImageRead( getANTsRData( "r64" ) ) segmentation1 <- thresholdImage( image1, "Otsu", 3 ) segmentation2 <- thresholdImage( image2, "Otsu", 3 ) data <- randomlyTransformImageData( image1, list( list( image1 ), list( image2 ) ), list( segmentation1, segmentation2 ) ) rm(segmentation1); gc() rm(segmentation2); gc() rm(image1); gc() rm(image2); gc()library( ANTsR ) image1 <- antsImageRead( getANTsRData( "r16" ) ) image2 <- antsImageRead( getANTsRData( "r64" ) ) segmentation1 <- thresholdImage( image1, "Otsu", 3 ) segmentation2 <- thresholdImage( image2, "Otsu", 3 ) data <- randomlyTransformImageData( image1, list( list( image1 ), list( image2 ) ), list( segmentation1, segmentation2 ) ) rm(segmentation1); gc() rm(segmentation2); gc() rm(image1); gc() rm(image2); gc()
Get a mask with a specific number of voxels randomly distributed on the input image/mask
randomMask(img, nsamples, perLabel = FALSE, seed)randomMask(img, nsamples, perLabel = FALSE, seed)
img |
an antsImage, either continuous or mask-like. This will define the space where to sample voxels from. If this image is continous (i.e., a T1), voxels will be sampled from all nonzero voxels. |
nsamples |
the number of random voxels to select from |
perLabel |
logical, if true the input image must be multi-label and the the output will have nsamples from each label (i.e., 200 samples from each label) |
seed |
random seed |
binary antsImage with random voxels set to 1
Pustina D
img <- antsImageRead(getANTsRData("r16")) randmask <- randomMask(img, 200)img <- antsImageRead(getANTsRData("r16")) randmask <- randomMask(img, 200)
uses random matrix to estimate svd results
randsvd(A, k, seed = NA)randsvd(A, k, seed = NA)
A |
input matrix |
k |
rank to use |
seed |
for testing |
randomized svd is output
Avants BB
N. Halko, P.G. Martinsson, J. Tropp "Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions" arXiv 0909.4061
A <- matrix(rnorm(3000), ncol = 50) k <- 10 dr <- randsvd(A, k)$d[1:k] dt <- svd(A)$d[1:k] cor(dr, dt)A <- matrix(rnorm(3000), ncol = 50) k <- 10 dr <- randsvd(A, k)$d[1:k] dt <- svd(A)$d[1:k] cor(dr, dt)
uses random matrix to whiten a matrix
randwhiten(A, k, seed = NA)randwhiten(A, k, seed = NA)
A |
input matrix |
k |
rank to use |
seed |
for testing |
whitened matrix is output
Avants BB
N. Halko, P.G. Martinsson, J. Tropp "Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions" arXiv 0909.4061
A <- matrix(rnorm(3000), ncol = 50) k <- 10 Aw <- randwhiten(A, k) # (Aw) %*% t(Aw)A <- matrix(rnorm(3000), ncol = 50) k <- 10 Aw <- randwhiten(A, k) # (Aw) %*% t(Aw)
rank-based segmentation of a matrix
rankBasedMatrixSegmentation( v, sparsenessQuantile, basic = FALSE, positivity = "positive", transpose = FALSE )rankBasedMatrixSegmentation( v, sparsenessQuantile, basic = FALSE, positivity = "positive", transpose = FALSE )
v |
input matrix |
sparsenessQuantile |
a value in zero to one |
basic |
simplest keep top k-entries in each row |
positivity |
one of positive, negative, either |
transpose |
work on the transpose |
matrix
Avants BB
mat <- matrix(1:200, nrow = 10) matr <- rankBasedMatrixSegmentation(mat, 0.9, basic = FALSE, positivity = "positive")mat <- matrix(1:200, nrow = 10) matr <- rankBasedMatrixSegmentation(mat, 0.9, basic = FALSE, positivity = "positive")
Rank transform the intensity of an image to reduce the impact of outliers; useful when using correlation-based metrics for registration and possibly for segmentation tasks. best used with a mask.
rankIntensity(x, mask, getMask = TRUE, method = "max")rankIntensity(x, mask, getMask = TRUE, method = "max")
x |
input image |
mask |
optional mask |
getMask |
boolean only used if mask is not present |
method |
optional method passed to |
image is output
Avants BB
fi <- makeImage(c(10, 10, 10), rnorm(1000)) rfi <- rankIntensity(fi)fi <- makeImage(c(10, 10, 10), rnorm(1000)) rfi <- rankIntensity(fi)
rapidlyInspectImageData collects basic statistics over a dataset and returns them in a dataframe.
rapidlyInspectImageData(myfiles)rapidlyInspectImageData(myfiles)
myfiles |
input list of filenames |
matrix is output
Avants BB
## Not run: fnl <- c( getANTsRData("r16"), getANTsRData("r27"), getANTsRData("r62"), getANTsRData("r64"), getANTsRData("r85") ) mm <- rapidlyInspectImageData(fnl) ## End(Not run)## Not run: fnl <- c( getANTsRData("r16"), getANTsRData("r27"), getANTsRData("r62"), getANTsRData("r64"), getANTsRData("r85") ) mm <- rapidlyInspectImageData(fnl) ## End(Not run)
Reconstructs SiMLR outputs written by write_simlr using the manifest
with relative paths for portability. Restores row names for matrices and data frames
from the CSV files.
read_simlr(dir)read_simlr(dir)
dir |
A character string specifying the directory with SiMLR outputs. |
A named list reconstructing the original SiMLR object.
This function reads a list of data frames from disk into a list, assuming the files are named with a common prefix and the names of the data frames. It converts the column named 'X' to the row names of the read data frame.
read_simlr_data_frames(file_prefix, data_names, verbose = FALSE)read_simlr_data_frames(file_prefix, data_names, verbose = FALSE)
file_prefix |
A character string used as the prefix for the filenames. |
data_names |
A character vector of names for the data frames. |
verbose |
boolean |
A list of data frames read from disk with the column named 'X' set as row names.
# data_names <- c("data1", "data2") # data_list <- read_simlr_data_frames(file_prefix = "output", data_names = data_names) # dim(data_list[[1]]) # dim(data_list[[2]])# data_names <- c("data1", "data2") # data_list <- read_simlr_data_frames(file_prefix = "output", data_names = data_names) # dim(data_list[[1]]) # dim(data_list[[2]])
read a transform from file
readAntsrTransform(filename, dimension = NA, precision = "float")readAntsrTransform(filename, dimension = NA, precision = "float")
filename |
filename of transform |
dimension |
spatial dimension of transform |
precision |
numerical precision of transform |
antsrTransform
trans <- c(3, 4, 5) tx <- createAntsrTransform(type = "Euler3DTransform", translation = trans) txfile <- tempfile(fileext = ".mat") writeAntsrTransform(tx, txfile) tx2 <- readAntsrTransform(txfile) testthat::expect_error(readAntsrTransform(txfile, 2), "space dim")trans <- c(3, 4, 5) tx <- createAntsrTransform(type = "Euler3DTransform", translation = trans) txfile <- tempfile(fileext = ".mat") writeAntsrTransform(tx, txfile) tx2 <- readAntsrTransform(txfile) testthat::expect_error(readAntsrTransform(txfile, 2), "space dim")
This function reads a file created by writeNormalizedPopulationData.
readNormalizedPopulationData(filename)readNormalizedPopulationData(filename)
filename |
input filename for hdf5 file. |
list containing demographics, imageMat, imageMask and imageBoolean
Avants BB
tfn <- system.file("extdata", "normpop.h5", package = "ANTsR") if (file.exists(tfn)) { dlist <- readNormalizedPopulationData(tfn) } ## Not run: ilist <- getANTsRData("population") mask <- getMask(ilist[[1]]) imat <- imageListToMatrix(ilist, mask) demog <- data.frame(age = c(11, 7, 18, 22), sex = c("M", "M", "F", "F")) ibool <- c(TRUE, TRUE, TRUE, FALSE) tfn <- tempfile(fileext = ".h5") if (usePkg("hdf5r")) writeNormalizedPopulationData(demog, imat, mask, ibool, tfn) if (usePkg("hdf5r")) { dlist <- readNormalizedPopulationData(tfn) all.equal(dlist$demographics, demog) all.equal(dlist$imageMat, imat) all.equal(as.array(dlist$imageMask), as.array(mask)) all.equal(dlist$imageBool, ibool) } ## End(Not run)tfn <- system.file("extdata", "normpop.h5", package = "ANTsR") if (file.exists(tfn)) { dlist <- readNormalizedPopulationData(tfn) } ## Not run: ilist <- getANTsRData("population") mask <- getMask(ilist[[1]]) imat <- imageListToMatrix(ilist, mask) demog <- data.frame(age = c(11, 7, 18, 22), sex = c("M", "M", "F", "F")) ibool <- c(TRUE, TRUE, TRUE, FALSE) tfn <- tempfile(fileext = ".h5") if (usePkg("hdf5r")) writeNormalizedPopulationData(demog, imat, mask, ibool, tfn) if (usePkg("hdf5r")) { dlist <- readNormalizedPopulationData(tfn) all.equal(dlist$demographics, demog) all.equal(dlist$imageMat, imat) all.equal(as.array(dlist$imageMask), as.array(mask)) all.equal(dlist$imageBool, ibool) } ## End(Not run)
Reconstruct image from a list of patches.
reconstructImageFromPatches( patches, domainImage, strideLength = 1, domainImageIsMask = FALSE )reconstructImageFromPatches( patches, domainImage, strideLength = 1, domainImageIsMask = FALSE )
patches |
List or array of patches defining an image. Patches are assumed
to have the same format as returned by |
domainImage |
Image or mask to define the geometric information of the reconstructed image. If this is a mask image, the reconstruction will only use patches in the mask. |
strideLength |
Defines the sequential patch overlap for
|
domainImageIsMask |
boolean specifying whether the domain image is a mask used to limit the region of reconstruction from the patches. |
an ANTs image.
Tustison NJ
library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) patchSet <- extractImagePatches( image, c( 64, 64 ), "all", c( 8, 8 ) ) imageReconstructed <- reconstructImageFromPatches( patchSet, image, c( 8, 8 ) ) testthat::expect_equal(as.array(image), as.array(imageReconstructed)) rm(image); gc() rm(patchSet); gc() rm(imageReconstructed); gc()library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) patchSet <- extractImagePatches( image, c( 64, 64 ), "all", c( 8, 8 ) ) imageReconstructed <- reconstructImageFromPatches( patchSet, image, c( 8, 8 ) ) testthat::expect_equal(as.array(image), as.array(imageReconstructed)) rm(image); gc() rm(patchSet); gc() rm(imageReconstructed); gc()
reflects an image along its axis
reflectImage(img1, axis = NA, tx = NA, metric = "mattes", verbose = TRUE, ...)reflectImage(img1, axis = NA, tx = NA, metric = "mattes", verbose = TRUE, ...)
img1 |
input object, an antsImage |
axis |
which dimension to reflect across, numbered from 0 to imageDimension-1 |
tx |
transformation type to estimate after reflection |
metric |
similarity metric for image registration. see |
verbose |
print diagnostic messages, passed to
|
... |
Additional options to pass to |
BB Avants
fi <- antsImageRead(getANTsRData("r16"), 2) axis <- 2 asym <- reflectImage(fi, axis, "Affine")$warpedmovout asym <- asym - fifi <- antsImageRead(getANTsRData("r16"), 2) axis <- 2 asym <- reflectImage(fi, axis, "Affine")$warpedmovout asym <- asym - fi
return a filename pointing to a reflection matrix
reflectionMatrix(img1, axis = NA, reflectionMatrixFilename)reflectionMatrix(img1, axis = NA, reflectionMatrixFilename)
img1 |
input object, an antsImage |
axis |
which dimension to reflect across, numbered from 0 to imageDimension-1 |
reflectionMatrixFilename |
a filename ending in .mat |
BB Avants
Image intensity normalization by regressing the image intensities of the reference image with the source image.
regressionMatchImage( sourceImage, referenceImage, mask = NULL, polyOrder = 1, truncate = TRUE )regressionMatchImage( sourceImage, referenceImage, mask = NULL, polyOrder = 1, truncate = TRUE )
sourceImage |
image whose intensities we will match to the
|
referenceImage |
defines the reference intensity function. |
mask |
Defines voxels for regression modeling. |
polyOrder |
of polynomial fit. Default is 1 (linear fit). |
truncate |
boolean which turns on/off the clipping of intensities. |
the sourceImage matched to the referenceImage.
Avants BB
library(ANTsRCore) sourceImage <- antsImageRead( getANTsRData( "r16" ) ) referenceImage <- antsImageRead( getANTsRData( "r64" ) ) matchedImage <- regressionMatchImage( sourceImage, referenceImage ) bad_source = sourceImage[1:200, 1:200] testthat::expect_error(regressionMatchImage( bad_source, referenceImage ))library(ANTsRCore) sourceImage <- antsImageRead( getANTsRData( "r16" ) ) referenceImage <- antsImageRead( getANTsRData( "r64" ) ) matchedImage <- regressionMatchImage( sourceImage, referenceImage ) bad_source = sourceImage[1:200, 1:200] testthat::expect_error(regressionMatchImage( bad_source, referenceImage ))
Perform regression on a training set of images, projected onto (provided) eigenvectors, and test on testing images.
regressProjections( input.train, input.test, demog.train, demog.test, eigenvectors, mask, outcome, covariates = "1", model.function = glm, which.eigenvectors = "all", ... )regressProjections( input.train, input.test, demog.train, demog.test, eigenvectors, mask, outcome, covariates = "1", model.function = glm, which.eigenvectors = "all", ... )
input.train |
Masked imaging data from training set of type
|
input.test |
Masked imaging data from testing set of type
|
demog.train |
Data frame of demographics information for training images. |
demog.test |
Data frame of demographics information for testing images. |
eigenvectors |
List of eigenvector images for dimensionality reduction. |
mask |
Mask image of type |
outcome |
Name of outcome variable to be predicted. Must be present in
|
covariates |
List of names of covariates to be used for the prediction.
All names must be present in |
model.function |
Modeling function for predicting outcome from input
data. Can be any function that has |
which.eigenvectors |
Method for selecting eigenvectors. Can be either
|
... |
Additional arguments for input to |
regressProjections is a convenient way to perform training and
testing of predictions of demographic information from imaging data. It
takes as input demographics information, imaging data, and eigenvectors, and
performs prediction of the outcome variable from the projection of the
imaging data on the eigenvectors.
A list of diagnostic and statistical information generated from the
prediction, including: stats: Statistics on computed fits. For
numeric outcomes, mean squared error, correlation coefficients, and p-value
of prediction for training and testing data. For factor outcomes,
misclassification rate and p-value of classification model.
outcome.comparison: Data frame comparing real vs. predicted values
for testing data. eigenvectors: List of eigenvectors retained in
model building.
Kandel BM and Avants B
# generate simulated outcome nsubjects <- 100 x1 <- seq(1, 10, length.out = nsubjects) + rnorm(nsubjects, sd = 2) x2 <- seq(25, 15, length.out = nsubjects) + rnorm(nsubjects, sd = 2) outcome <- 3 * x1 + 4 * x2 + rnorm(nsubjects, sd = 1) # generate simulated images with outcome predicted # by sparse subset of voxels voxel.1 <- 3 * x1 + rnorm(nsubjects, sd = 2) voxel.2 <- rnorm(nsubjects, sd = 2) voxel.3 <- 2 * x2 + rnorm(nsubjects, sd = 2) voxel.4 <- rnorm(nsubjects, sd = 3) input <- cbind(voxel.1, voxel.2, voxel.3, voxel.4) # simulate eigenvectors and mask mydecom <- sparseDecom(input, sparseness = 0.25, nvecs = 4) mask <- as.antsImage(matrix(c(1, 1, 1, 1), nrow = 2)) # generate sample demographics that do not explain outcome age <- runif(nsubjects, 50, 75) demog <- data.frame(outcome = outcome, age = age) # randomly divide data into training and testing data.split <- splitData(demog, 2 / 3, return.rows = TRUE) eanatimages <- matrixToImages(mydecom$eig, mask) result <- regressProjections( input[data.split$rows.in, ], input[data.split$rows.out, ], data.split$data.in, data.split$data.out, eanatimages, mask, "outcome" )# generate simulated outcome nsubjects <- 100 x1 <- seq(1, 10, length.out = nsubjects) + rnorm(nsubjects, sd = 2) x2 <- seq(25, 15, length.out = nsubjects) + rnorm(nsubjects, sd = 2) outcome <- 3 * x1 + 4 * x2 + rnorm(nsubjects, sd = 1) # generate simulated images with outcome predicted # by sparse subset of voxels voxel.1 <- 3 * x1 + rnorm(nsubjects, sd = 2) voxel.2 <- rnorm(nsubjects, sd = 2) voxel.3 <- 2 * x2 + rnorm(nsubjects, sd = 2) voxel.4 <- rnorm(nsubjects, sd = 3) input <- cbind(voxel.1, voxel.2, voxel.3, voxel.4) # simulate eigenvectors and mask mydecom <- sparseDecom(input, sparseness = 0.25, nvecs = 4) mask <- as.antsImage(matrix(c(1, 1, 1, 1), nrow = 2)) # generate sample demographics that do not explain outcome age <- runif(nsubjects, 50, 75) demog <- data.frame(outcome = outcome, age = age) # randomly divide data into training and testing data.split <- splitData(demog, 2 / 3, return.rows = TRUE) eanatimages <- matrixToImages(mydecom$eig, mask) result <- regressProjections( input[data.split$rows.in, ], input[data.split$rows.out, ], data.split$data.in, data.split$data.out, eanatimages, mask, "outcome" )
Automatically produce regularization matrices for simlr
regularizeSimlr(x, knn, fraction = 0.1, sigma, kPackage = "FNN")regularizeSimlr(x, knn, fraction = 0.1, sigma, kPackage = "FNN")
x |
A list that contains the named matrices.
Note: the optimization will likely perform much more smoothly if the input
matrices are each scaled to zero mean unit variance e.g. by the |
knn |
A vector of knn values (integers, same length as matrices) |
fraction |
optional single scalar value to determine knn |
sigma |
optional sigma vector for regularization (same length as matrices) |
kPackage |
name of package to use for knn. FNN is reproducbile but RcppHNSW is much faster (with nthreads controlled by enviornment variable ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS) for larger problems. For large problems, compute the regularization once and save to disk; load for repeatability. |
A list of regularization matrices.
BB Avants.
# see simlr examples# see simlr examples
regional homogeneity for a time series image
reho(rsfmri, mask, shifter = 1, method = "kendall", maxDistance = 1.1)reho(rsfmri, mask, shifter = 1, method = "kendall", maxDistance = 1.1)
rsfmri |
antsImage usually 4D |
mask |
antsImage binary mask |
shifter |
size of neighborhood |
method |
one of kendall, spearman or pearson |
maxDistance |
maximum distance from center voxel |
antsImage is output
Tustison, N.
Zang, Y., Jiang, T., Lu, Y., He, Y., Tian, L., 2004. Regional homogeneity approach to fMRI data analysis. Neuroimage 22, 394-400.
## Not run: rehoimg <- reho(rsfmri) ## End(Not run)## Not run: rehoimg <- reho(rsfmri) ## End(Not run)
Probability image lists should sum to one at every voxel. Smoothing or other common operations may break this constraint. This function allows one to easily ensure a list of proability images sums to one everywhere. It also allows one prioritize specific images in the probability set such that its probability is maintained while others are normalized with respect to the prioritized value. Will also set values less than zero, to zero.
renormalizeProbabilityImages(probs, mask, k = NA)renormalizeProbabilityImages(probs, mask, k = NA)
probs |
list of images |
mask |
image |
k |
which image, if any, to prioritize |
list is output
Avants BB
mat <- t(matrix(rnorm(4000), ncol = 10)) mask <- makeImage(c(20, 20), 1) plist <- matrixToImages(mat, mask) rplist <- renormalizeProbabilityImages(plist, mask) rplist2 <- renormalizeProbabilityImages(plist, mask, 2)mat <- t(matrix(rnorm(4000), ncol = 10)) mask <- makeImage(c(20, 20), 1) plist <- matrixToImages(mat, mask) rplist <- renormalizeProbabilityImages(plist, mask) rplist2 <- renormalizeProbabilityImages(plist, mask, 2)
align along a specific axis
reorientImage(img, axis1, axis2 = NA, doreflection = 0, doscale = 0, txfn = NA)reorientImage(img, axis1, axis2 = NA, doreflection = 0, doscale = 0, txfn = NA)
img |
antsImage |
axis1 |
vector of size dim, might need to play w/axis sign |
axis2 |
vector of size dim for 3D |
doreflection |
boolean |
doscale |
scalar value, 1 allows automated estimate of scaling |
txfn |
file name for transformation |
reoriented image
Brian B. Avants
Resample image by spacing or number of voxels with various interpolators. Works with multi-channel images.
resampleImage( image, resampleParams, useVoxels = FALSE, interpType = "nearestneighbor" )resampleImage( image, resampleParams, useVoxels = FALSE, interpType = "nearestneighbor" )
image |
input antsImage |
resampleParams |
vector of size dimension with numeric values |
useVoxels |
true means interpret resample params as voxel counts |
interpType |
one of 0 (linear), 1 (nearestNeighbor), 2 (gaussian), 3 (windowedSinc), 4 (bspline). The user can pass either a numeric or character argument here. |
output antsImage
Avants BB
fi <- antsImageRead(getANTsRData("r16")) r <- range(fi) finn <- resampleImage(fi, c(50, 60), TRUE, 0) range(finn) stopifnot(diff(range(finn)) > 0) filin <- resampleImage(fi, c(1.5, 1.5), FALSE, 1) range(filin) stopifnot(diff(range(filin)) > 0) pixeltype(fi) <- "float" arr <- as.array(fi) arr <- floor(arr) class(arr) <- "integer" fi <- as.antsImage(arr, pixeltype = "unsigned int") filin <- resampleImage(fi, c(1.5, 1.5), FALSE, 1) fi <- as.antsImage(arr > 14, pixeltype = "unsigned char") filin <- resampleImage(fi, c(1.5, 1.5), FALSE, 1) fi <- antsImageRead(getANTsRData("multi_component_image")) filin <- resampleImage(fi, c(2, 2), FALSE, 1)fi <- antsImageRead(getANTsRData("r16")) r <- range(fi) finn <- resampleImage(fi, c(50, 60), TRUE, 0) range(finn) stopifnot(diff(range(finn)) > 0) filin <- resampleImage(fi, c(1.5, 1.5), FALSE, 1) range(filin) stopifnot(diff(range(filin)) > 0) pixeltype(fi) <- "float" arr <- as.array(fi) arr <- floor(arr) class(arr) <- "integer" fi <- as.antsImage(arr, pixeltype = "unsigned int") filin <- resampleImage(fi, c(1.5, 1.5), FALSE, 1) fi <- as.antsImage(arr > 14, pixeltype = "unsigned char") filin <- resampleImage(fi, c(1.5, 1.5), FALSE, 1) fi <- antsImageRead(getANTsRData("multi_component_image")) filin <- resampleImage(fi, c(2, 2), FALSE, 1)
Resample image by using another image as target reference. This function uses antsApplyTransform with an identity matrix to achieve proper resampling.
resampleImageToTarget( image, target, interpType = "linear", imagetype = 0, verbose = FALSE, ... )resampleImageToTarget( image, target, interpType = "linear", imagetype = 0, verbose = FALSE, ... )
image |
image to resample |
target |
image of reference, the output will be in this space |
interpType |
Choice of interpolator. Supports partial matching.
|
imagetype |
choose 0/1/2/3 mapping to scalar/vector/tensor/time-series |
verbose |
print command and run verbose application of transform. |
... |
additional arugment passed to |
output antsImage resampled with target's resolution/origin/orientation/direction
Pustina D
fname <- getANTsRData("r16") fi <- antsImageRead(fname) fi2mm <- resampleImage(fi, c(2, 2), useVoxels = 0, interpType = "linear") resampled <- resampleImageToTarget(fi2mm, fi) testthat::expect_error(resampleImageToTarget(fi2mm))fname <- getANTsRData("r16") fi <- antsImageRead(fname) fi2mm <- resampleImage(fi, c(2, 2), useVoxels = 0, interpType = "linear") resampled <- resampleImageToTarget(fi2mm, fi) testthat::expect_error(resampleImageToTarget(fi2mm))
Utilize the estimated FWHM to find the resels per voxel
resels(mask, fwhm)resels(mask, fwhm)
mask |
statistical value (typically the maxima of a cluster or statistical field) |
fwhm |
the full width at half maxima measurement |
Interprets a given antsImage mask (binarized so as to only contain 0s and 1s) into resolutions elements (as opposed to voxels). Doing so emphasizes the interdependent nature of voxels when undergoing RFT based statistical analyses. Optimized for three dimensions (2D has not yet been tested yet).
A vector of resels for dimensions 0:D
Zachary P. Christensen
Worlsey K.J., (1996) A Unified Statistical Approach for Determining Significant Signals in Images of Cerebral Activation.
rftPval, euler, rftResults
mask <- getMask(antsImageRead(getANTsRData("r16"))) myresels <- resels(mask, c(1, 1))mask <- getMask(antsImageRead(getANTsRData("r16"))) myresels <- resels(mask, c(1, 1))
Resets the internal state (momentum, second moments, etc.) of an optimizer. Useful when the optimization needs to restart from a previous best state.
reset_optimizer_state(optimizer, vmats)reset_optimizer_state(optimizer, vmats)
optimizer |
The optimizer object. |
vmats |
The current V matrices to get the correct dimensions. |
The optimizer object with reset state.
Unsupervised image segmentation via random forests. An example.
rfSegmentation( featureMatrix, mask, labelimg = NULL, ntrees = 100, verbose = FALSE )rfSegmentation( featureMatrix, mask, labelimg = NULL, ntrees = 100, verbose = FALSE )
featureMatrix |
input matrix of features matched to mask size n predictors in rf |
mask |
input antsImage mask |
labelimg |
input antsImage labelimage, optional for supervised seg |
ntrees |
number of rf trees |
verbose |
boolean |
list of n-probability images is output where n is number of classes
Tustison NJ, Avants BB
## Not run: if (usePkg("randomForest")) { img <- antsImageRead(getANTsRData("r16")) %>% iMath("Normalize") mask <- getMask(img) segs <- kmeansSegmentation(img, k = 3, kmask = mask) fmat0 <- t(antsrimpute(getNeighborhoodInMask(img, mask, c(2, 2)))) fmat1 <- t(antsrimpute(getNeighborhoodInMask( segs$probabilityimages[[1]], mask, c(2, 2) ))) fmat2 <- t(antsrimpute(getNeighborhoodInMask( segs$probabilityimages[[2]], mask, c(2, 2) ))) fmat3 <- t(antsrimpute(getNeighborhoodInMask( segs$probabilityimages[[3]], mask, c(2, 2) ))) fmat <- cbind(fmat0, fmat1, fmat2, fmat3) # produces proximity between all voxel pairs rfsegs <- rfSegmentation(fmat, verbose = FALSE) lrr <- lowrankRowMatrix(rfsegs, 10, faster = TRUE) nv <- eanatSelect( inmat = lrr, mask = mask, selectorScale = 1.2, cthresh = 50, verbose = T, smooth = 1 ) ee <- eanatDef(lrr, mask, nvecs = nv, smooth = 0., cthresh = 50, its = 2, verbose = TRUE ) eseg <- eigSeg(mask, ee) plot(img, eseg) } ## End(Not run)## Not run: if (usePkg("randomForest")) { img <- antsImageRead(getANTsRData("r16")) %>% iMath("Normalize") mask <- getMask(img) segs <- kmeansSegmentation(img, k = 3, kmask = mask) fmat0 <- t(antsrimpute(getNeighborhoodInMask(img, mask, c(2, 2)))) fmat1 <- t(antsrimpute(getNeighborhoodInMask( segs$probabilityimages[[1]], mask, c(2, 2) ))) fmat2 <- t(antsrimpute(getNeighborhoodInMask( segs$probabilityimages[[2]], mask, c(2, 2) ))) fmat3 <- t(antsrimpute(getNeighborhoodInMask( segs$probabilityimages[[3]], mask, c(2, 2) ))) fmat <- cbind(fmat0, fmat1, fmat2, fmat3) # produces proximity between all voxel pairs rfsegs <- rfSegmentation(fmat, verbose = FALSE) lrr <- lowrankRowMatrix(rfsegs, 10, faster = TRUE) nv <- eanatSelect( inmat = lrr, mask = mask, selectorScale = 1.2, cthresh = 50, verbose = T, smooth = 1 ) ee <- eanatDef(lrr, mask, nvecs = nv, smooth = 0., cthresh = 50, its = 2, verbose = TRUE ) eseg <- eigSeg(mask, ee) plot(img, eseg) } ## End(Not run)
Predict image segmentation via random forests.
rfSegmentationPredict( rfSegmentationModel, featureMatrix, mask, verbose = FALSE )rfSegmentationPredict( rfSegmentationModel, featureMatrix, mask, verbose = FALSE )
rfSegmentationModel |
input rf model |
featureMatrix |
input feature matrix |
mask |
antsImage mask |
verbose |
bool |
segmentation is output
Tustison NJ, Avants BB
if (usePkg("randomForest")) { img <- antsImageRead(getANTsRData("r16")) mask <- getMask(img) mask2 <- getMask(img) mask[129:255, 1:255] <- 0 mask2[2:128, 1:255] <- 0 segs <- kmeansSegmentation(img, k = 3, kmask = mask) fmat <- t(antsrimpute(getNeighborhoodInMask(img, mask, c(2, 2)))) rfsegs <- rfSegmentation(fmat, mask, segs$segmentation, ntrees = 100) fmat2 <- t(antsrimpute(getNeighborhoodInMask(img, mask2, c(2, 2)))) rfseg2 <- rfSegmentationPredict(rfsegs$rfModel, fmat2, mask2) }if (usePkg("randomForest")) { img <- antsImageRead(getANTsRData("r16")) mask <- getMask(img) mask2 <- getMask(img) mask[129:255, 1:255] <- 0 mask2[2:128, 1:255] <- 0 segs <- kmeansSegmentation(img, k = 3, kmask = mask) fmat <- t(antsrimpute(getNeighborhoodInMask(img, mask, c(2, 2)))) rfsegs <- rfSegmentation(fmat, mask, segs$segmentation, ntrees = 100) fmat2 <- t(antsrimpute(getNeighborhoodInMask(img, mask2, c(2, 2)))) rfseg2 <- rfSegmentationPredict(rfsegs$rfModel, fmat2, mask2) }
Calculates p-values of a statistical field using random field theory
rftPval(D, c, k, u, n, resels, df, fieldType)rftPval(D, c, k, u, n, resels, df, fieldType)
D |
image dimensions |
c |
Threshold |
k |
spatial extent in resels (minimum cluster size in resels) |
u |
Number of clusters |
n |
number of statistical field in conjunction |
resels |
resel measurements of the search region |
df |
degrees of freedom expressed as df = c(degrees of interest, degrees of error) |
fieldType |
|
This function calculates p-values of a thresholded statistical field at various levels:
set-level rft.pval(D, c, k, u, n, resels, df, fieldType)
cluster-level rft.pval(D, 1, k, u, n, resels, df, fieldType)
peak-level rft.pval(D, 1, 0, u, n, resels, df, fieldType)
Where set-level refers to obtaining the set of clusters, cluster-level refers to a specific cluster, and peak-level refers to the maximum (or peak) of a single cluster.
The probability of obtaining the specified cluster
corrected p-value
uncorrected p-value
expected number of clusters
expected number of resels per cluster
Zachary P. Christensen
Friston K.J., (1994) Assessing the Significance of Focal Activations Using Their Spatial Extent.
Friston K.J., (1996) Detecting Activations in PET and fMRI: Levels of Inference and Power.
Worlsey K.J., (1996) A Unified Statistical Approach for Determining Significant Signals in Images of Cerebral Activation.
rftResults, resels
## Not run: # using rftPval for hypothetical 3D t-statistical image # assume resels have been calculated and df = c(dfi, dfe) # peak RFT p-value (peak = the maximum of a specific cluster) peakP <- rftPval(3, 1, 0, peak, 1, resels, df, fieldType = "T")$Pcor # cluster RFT p-value (u = the value the statistical field was threshold at # and k = the size of the cluster in resels) clusterP <- rftPval(3, 1, k, u, 1, resels, df, fieldType = "T")$Pcor # set RFT p-value setP <- rftPval(3, numberOfClusters, minimumClusterSize, u, 1, resels, df, fieldType = "T" )$Pcor ## End(Not run)## Not run: # using rftPval for hypothetical 3D t-statistical image # assume resels have been calculated and df = c(dfi, dfe) # peak RFT p-value (peak = the maximum of a specific cluster) peakP <- rftPval(3, 1, 0, peak, 1, resels, df, fieldType = "T")$Pcor # cluster RFT p-value (u = the value the statistical field was threshold at # and k = the size of the cluster in resels) clusterP <- rftPval(3, 1, k, u, 1, resels, df, fieldType = "T")$Pcor # set RFT p-value setP <- rftPval(3, numberOfClusters, minimumClusterSize, u, 1, resels, df, fieldType = "T" )$Pcor ## End(Not run)
Returns RFT based statistical results for a single statistical image
rftResults( x, resels, fwhm, df, fieldType, RPVImg = NULL, k = 1, threshType = "pRFT", pval = 0.05, pp = 0.001, n = 1, statdir = NULL, verbose = FALSE )rftResults( x, resels, fwhm, df, fieldType, RPVImg = NULL, k = 1, threshType = "pRFT", pval = 0.05, pp = 0.001, n = 1, statdir = NULL, verbose = FALSE )
x |
statistical field image of class antsImage |
resels |
resel values for the mask |
fwhm |
full width at half maxima |
df |
degrees of freedom expressed as df = c(degrees of interest, degrees of error) |
fieldType |
|
RPVImg |
resels per voxel image |
k |
minimum desired cluster size (default = 1) |
threshType |
a numeric value to threshTypeold the statistical field or a character of the following methods:
|
pval |
the p-value for estimating the threshTypeold (default = .05) |
pp |
the primary (initial) p-value for threshTypeolding (only used for FDR methods; default = .001) |
n |
number of images in conjunction |
statdir |
directory where output is saved (if not specified images are not saved) |
verbose |
enables verbose output |
rftPval is used to compute all family-wise error (FWE) corrected
statistics while p.adjust is used to compute all false-discovery rate
based statistics. All statistics herein involve implementation of random
field theory (RFT) to some extent.
Both cluster-level and peak-level statistics are described by the
uncorrected
p-value along with the FDR and FWE corrected p-values for each cluster.
Peak-level statistics are described by the maximum statistical value in each
cluster and the comparable Z statistic. The ClusterStats table also contains
coordinates for each cluster and the number of voxels therein. By default
threshType = "pRFT" and pval=.05. Alternatively, the user may use a
specific numeric value for threshTypeolding the statistical field.
statFieldThresh more fully describes using appropriate threshTypeolds
for statistical fields and how pp plays a role in FDR
threshTypeolding.
Outputs a statistical value to be used for threshTypeold a statistical field image
set-level statistics and number of clusters
cluster-level statistics and descriptors
peak-level statistics and descriptor"
image of labeled clusters
the threshTypeold used
Zachary P. Christensen
Chumbley J., (2010) Topological FDR for neuroimaging
Friston K.J., (1996) Detecting Activations in PET and fMRI: Levels of Inference and Power
Worsley K.J., (1992) A Three-Dimensional Statistical Analysis for CBF Activation Studies in Human Brain.
## Not run: mnit1 <- antsImageRead(getANTsRData("mni")) mask <- getMask(mnit1) ilist <- list() for (i in 1:10) { ilist <- lappend(ilist, antsImageClone(mnit1) * rnorm(1)) } response <- rnorm(10) imat <- imageListToMatrix(ilist, mask) residuals <- matrix(nrow = nrow(imat), ncol = ncol(imat)) tvals <- matrix(nrow = nrow(imat), ncol = ncol(imat)) for (i in 1:ncol(imat)) { fit <- lm(response ~ imat[, i]) tvals <- coefficients(fit)[2] residuals[, i] <- residuals(fit) } myfwhm <- estSmooth(residuals, mask, fit$df.residual) res <- resels(mask, myfwhm$fwhm) timg <- makeImage(mask, tvals) # threshold to create peak values with p-value of .05 (default) results1 <- rftResults(timg, res, myfwhm$fwhm, df, fieldType = "T", threshType = "pRFT", pval = .05 ) # threshold to create clusters with p-value of .05 results2 <- rftResults(timg, res, myfwhm$fwhm, df, fieldType = "T", threshType = "cRFT", pval = .05 ) # initial threshold at p-value of .001 followed by peak FDR threshTypeold at # p-value of .05 results3 <- rftResults(timg, res, myfwhm$fwhm, df, fieldType = "T", threshType = "pFDR", pval = .05, pp = .01 ) # initial threshold at p-value of .001 followed by cluster FDR threshold at # p-value of .05 results4 <- rftResults(timg, res, myfwhm$fwhm, df, fieldType = "T", threshType = "cFDR", pval = .05, pp = .01 ) # correcting for non-isotropic results5 <- rftResults(timg, res, myfwhm$fwhm, df, fieldType = "T", fwhm$RPVImg ) ## End(Not run)## Not run: mnit1 <- antsImageRead(getANTsRData("mni")) mask <- getMask(mnit1) ilist <- list() for (i in 1:10) { ilist <- lappend(ilist, antsImageClone(mnit1) * rnorm(1)) } response <- rnorm(10) imat <- imageListToMatrix(ilist, mask) residuals <- matrix(nrow = nrow(imat), ncol = ncol(imat)) tvals <- matrix(nrow = nrow(imat), ncol = ncol(imat)) for (i in 1:ncol(imat)) { fit <- lm(response ~ imat[, i]) tvals <- coefficients(fit)[2] residuals[, i] <- residuals(fit) } myfwhm <- estSmooth(residuals, mask, fit$df.residual) res <- resels(mask, myfwhm$fwhm) timg <- makeImage(mask, tvals) # threshold to create peak values with p-value of .05 (default) results1 <- rftResults(timg, res, myfwhm$fwhm, df, fieldType = "T", threshType = "pRFT", pval = .05 ) # threshold to create clusters with p-value of .05 results2 <- rftResults(timg, res, myfwhm$fwhm, df, fieldType = "T", threshType = "cRFT", pval = .05 ) # initial threshold at p-value of .001 followed by peak FDR threshTypeold at # p-value of .05 results3 <- rftResults(timg, res, myfwhm$fwhm, df, fieldType = "T", threshType = "pFDR", pval = .05, pp = .01 ) # initial threshold at p-value of .001 followed by cluster FDR threshold at # p-value of .05 results4 <- rftResults(timg, res, myfwhm$fwhm, df, fieldType = "T", threshType = "cFDR", pval = .05, pp = .01 ) # correcting for non-isotropic results5 <- rftResults(timg, res, myfwhm$fwhm, df, fieldType = "T", fwhm$RPVImg ) ## End(Not run)
r16, r27, r30, r62, r64, r85 are t1-weighted MRI slices of the human brain that have been around for a long time. We use them for quick registration, segmentation and other processing tests. This function will return these images to the user.
ri(x)ri(x)
x |
one of 16, 27, 30, 62, 64, 85 or 'all'. values 1 through 6 are also acceptable. |
image or image list is output
Avants BB
r16 <- ri(16)r16 <- ri(16)
Patch-based and rotation invariant image decomposition. This
is similar to patch-based dictionary learning in N-dimensions. Warning:
there may be an overlow/underflow error in the C++ underlying this function
that appears to occur when insufficient patchSamples are selected.
ripmmarc( img, mask, patchRadius = 3, patchSamples = 1000, patchVarEx = 0.95, meanCenter = TRUE, canonicalFrame = NULL, evecBasis = NULL, rotationInvariant = TRUE, regressProjections = TRUE, verbose = FALSE )ripmmarc( img, mask, patchRadius = 3, patchSamples = 1000, patchVarEx = 0.95, meanCenter = TRUE, canonicalFrame = NULL, evecBasis = NULL, rotationInvariant = TRUE, regressProjections = TRUE, verbose = FALSE )
img |
Image to decompose |
mask |
Binary mask defining regions in which to decompose. |
patchRadius |
Scalar radius defining the patch size. |
patchSamples |
Scalar defining the number of random patches to sample. |
patchVarEx |
Scalar defining the target variance explained. If this is greater than one, then it defines the number of eigenvectors. Otherwise, it defines the target variance explained. |
meanCenter |
boolean whether we mean center the patches. |
canonicalFrame |
pass in an existing canonicalFrame. |
evecBasis |
pass in an existing eigenvector basis. |
rotationInvariant |
boolean sets whether patches are rotationInvariant. |
regressProjections |
boolean return reconstruction parameters. |
verbose |
boolean sets verbosity. |
list including the canonical frame, the matrix basis, the patches for the full image, the projection coefficients for the full image, the variance explained and a reconstructed image.
Kandel BM, Avants BB
img <- antsImageRead(getANTsRData("r16")) msk <- getMask(img) %>% iMath("ME", 1) lap <- iMath(img, "Laplacian", 2) mskTestTrain <- antsImageClone(msk) mskTestTrain[1:128, 1:256] <- 2 mskTestTrain <- mskTestTrain * msk pr <- 2 nv <- 15 ripped <- ripmmarc(img, thresholdImage(mskTestTrain, 2, 2), patchRadius = pr, patchSamples = 5000, patchVarEx = nv, rotationInvariant = FALSE ) ipatches <- ripped$imagePatchMat ibasis <- scale(ripped$basisMat) k <- 5 kk <- lm(ipatches[k, ] ~ t(ibasis[1:10, ])) rimg <- ripmmarcBasisImage(ripped$canonicalFrame, ipatches[k, ]) # plot( rimg, doCropping=FALSE ) bimg <- ripmmarcBasisImage(ripped$canonicalFrame, ibasis[5, ]) # plot( bimg, doCropping=FALSE ) rippedTest <- ripmmarc(img, thresholdImage(mskTestTrain, 1, 1), patchRadius = pr, evecBasis = ripped$basisMat, canonicalFrame = ripped$canonicalFrame, patchSamples = 500, patchVarEx = nv, rotationInvariant = FALSE ) lapTrainVox <- lap[mskTestTrain == 2] lapTestVox <- lap[mskTestTrain == 1] mydftr <- data.frame(lap = lapTrainVox, t1feats = ripped$evecCoeffs) mydfte <- data.frame(lap = lapTestVox, t1feats = rippedTest$evecCoeffs) mdl <- lm(lap ~ ., data = mydftr) preds <- predict(mdl, newdata = mydfte) # cor.test( preds, mydfte$lap )img <- antsImageRead(getANTsRData("r16")) msk <- getMask(img) %>% iMath("ME", 1) lap <- iMath(img, "Laplacian", 2) mskTestTrain <- antsImageClone(msk) mskTestTrain[1:128, 1:256] <- 2 mskTestTrain <- mskTestTrain * msk pr <- 2 nv <- 15 ripped <- ripmmarc(img, thresholdImage(mskTestTrain, 2, 2), patchRadius = pr, patchSamples = 5000, patchVarEx = nv, rotationInvariant = FALSE ) ipatches <- ripped$imagePatchMat ibasis <- scale(ripped$basisMat) k <- 5 kk <- lm(ipatches[k, ] ~ t(ibasis[1:10, ])) rimg <- ripmmarcBasisImage(ripped$canonicalFrame, ipatches[k, ]) # plot( rimg, doCropping=FALSE ) bimg <- ripmmarcBasisImage(ripped$canonicalFrame, ibasis[5, ]) # plot( bimg, doCropping=FALSE ) rippedTest <- ripmmarc(img, thresholdImage(mskTestTrain, 1, 1), patchRadius = pr, evecBasis = ripped$basisMat, canonicalFrame = ripped$canonicalFrame, patchSamples = 500, patchVarEx = nv, rotationInvariant = FALSE ) lapTrainVox <- lap[mskTestTrain == 2] lapTestVox <- lap[mskTestTrain == 1] mydftr <- data.frame(lap = lapTrainVox, t1feats = ripped$evecCoeffs) mydfte <- data.frame(lap = lapTestVox, t1feats = rippedTest$evecCoeffs) mdl <- lm(lap ~ ., data = mydftr) preds <- predict(mdl, newdata = mydfte) # cor.test( preds, mydfte$lap )
This function converts a vectorized image patch back into an antsImage such that it may be displayed in its extrinsic dimensionality.
ripmmarcBasisImage(canonicalFrame, patchBasisVector, eps = 1e-12)ripmmarcBasisImage(canonicalFrame, patchBasisVector, eps = 1e-12)
canonicalFrame |
canonical frame image generated by ripmmarc |
patchBasisVector |
the basis vector to convert to image space |
eps |
small value threshold to help generate mask from canonicalFrame |
antsImage
Kandel BM, Avants BB
img <- antsImageRead(getANTsRData("rand")) img <- resampleImage(img, c(32, 32)) msk <- thresholdImage(img, quantile(img[img > 0], 0.5)[1], max(img)) ripped <- ripmmarc(img, msk, patchRadius = 1, patchSamples = 20, patchVarEx = 2) bimg <- ripmmarcBasisImage(ripped$canonicalFrame, ripped$basisMat[1, ])img <- antsImageRead(getANTsRData("rand")) img <- resampleImage(img, c(32, 32)) msk <- thresholdImage(img, quantile(img[img > 0], 0.5)[1], max(img)) ripped <- ripmmarc(img, msk, patchRadius = 1, patchSamples = 20, patchVarEx = 2) bimg <- ripmmarcBasisImage(ripped$canonicalFrame, ripped$basisMat[1, ])
Patch-based and rotation invariant image decomposition. This is similar to patch-based dictionary learning in N-dimensions. This implementation is more efficient for building a basis from image populations.
ripmmarcPop( ilist, mask, patchRadius = 3, patchSamples = 1000, patchVarEx = 0.95, meanCenter = TRUE, seed )ripmmarcPop( ilist, mask, patchRadius = 3, patchSamples = 1000, patchVarEx = 0.95, meanCenter = TRUE, seed )
ilist |
list of antsImages from which to learn basis |
mask |
Binary mask defining regions in which to decompose or a list of masks corresponding to ilist. |
patchRadius |
Scalar radius defining the patch size. |
patchSamples |
Scalar defining the number of random patches to sample. |
patchVarEx |
Scalar defining the target variance explained. If this is greater than one, then it defines the number of eigenvectors. Otherwise, it defines the target variance explained. |
meanCenter |
boolean whether we mean center the patches. |
seed |
seed to pass to |
list including the canonical frame, the matrix basis and its eigenvalues
Kandel BM, Avants BB
pop <- getANTsRData("population") # list of example images popmasks <- list() for (i in 1:length(pop)) { popmasks[[i]] <- getMask(pop[[i]]) } set.seed(1234) rp <- ripmmarcPop(pop, popmasks, patchRadius = 3, meanCenter = TRUE, patchSamples = 1000 ) set.seed(1234) rp2 <- ripmmarcPop(pop, popmasks, patchRadius = 3, meanCenter = TRUE, patchSamples = 1000 ) testthat::expect_equal(rp, rp2) rp3 <- ripmmarcPop(pop, popmasks, patchRadius = 3, meanCenter = TRUE, patchSamples = 1000, seed = 1234 ) testthat::expect_failure(testthat::expect_equal(rp, rp3)) ## Not run: nv <- 15 rippedTest <- ripmmarc(pop[[3]], popmasks[[3]], patchRadius = 3, evecBasis = rp$basisMat[1:nv, ], patchVarEx = nv, meanCenter = TRUE, canonicalFrame = rp$canonicalFrame, regressProjections = TRUE ) mm <- makeImage(popmasks[[3]], rippedTest$evecCoeffs[, 1]) ## End(Not run)pop <- getANTsRData("population") # list of example images popmasks <- list() for (i in 1:length(pop)) { popmasks[[i]] <- getMask(pop[[i]]) } set.seed(1234) rp <- ripmmarcPop(pop, popmasks, patchRadius = 3, meanCenter = TRUE, patchSamples = 1000 ) set.seed(1234) rp2 <- ripmmarcPop(pop, popmasks, patchRadius = 3, meanCenter = TRUE, patchSamples = 1000 ) testthat::expect_equal(rp, rp2) rp3 <- ripmmarcPop(pop, popmasks, patchRadius = 3, meanCenter = TRUE, patchSamples = 1000, seed = 1234 ) testthat::expect_failure(testthat::expect_equal(rp, rp3)) ## Not run: nv <- 15 rippedTest <- ripmmarc(pop[[3]], popmasks[[3]], patchRadius = 3, evecBasis = rp$basisMat[1:nv, ], patchVarEx = nv, meanCenter = TRUE, canonicalFrame = rp$canonicalFrame, regressProjections = TRUE ) mm <- makeImage(popmasks[[3]], rippedTest$evecCoeffs[, 1]) ## End(Not run)
Transform a matrix such that each column has rank-ordered entries where rank #' is determined by the column values.
robustMatrixTransform(mat)robustMatrixTransform(mat)
mat |
input matrix |
matrix is output
Avants BB
mat <- replicate(100, rnorm(20)) rmat <- robustMatrixTransform(mat)mat <- replicate(100, rnorm(20)) rmat <- robustMatrixTransform(mat)
Uses a target function to denoise resting bold data
rsfDenoise( boldmatrix, targety, motionparams = NA, selectionthresh = 0.1, maxnoisepreds = 1:12, debug = FALSE, polydegree = 4, crossvalidationgroups = 4, tr = 1, scalemat = F, noisepoolfun = max )rsfDenoise( boldmatrix, targety, motionparams = NA, selectionthresh = 0.1, maxnoisepreds = 1:12, debug = FALSE, polydegree = 4, crossvalidationgroups = 4, tr = 1, scalemat = F, noisepoolfun = max )
boldmatrix |
input bold matrix |
targety |
target to predict |
motionparams |
motion parameters / nuisance variables |
selectionthresh |
e.g. 0.1 take 10 percent worst variables for noise estimation |
maxnoisepreds |
integer search range e.g 1:10 |
debug |
boolean |
polydegree |
eg 4 for polynomial nuisance variables |
crossvalidationgroups |
prior defined or integer valued |
tr |
bold tr |
scalemat |
boolean |
noisepoolfun |
function to help select noise pool e.g. max |
matrix is output
Avants BB
## Not run: # if (!exists("fn") ) fn<-getANTsRData("pcasl") # bold <- antsImageRead( fn ) # avgbold<-getAverageOfTimeSeries(bold) # boldmask<-getMask( avgbold ) # roimask<-antsImageRead("roi.nii.gz") # timeselect<-10:(dim(bold)[4]-10) # # can do this if you like its approach # cleanfMRI <- preprocessfMRI( bold, maskImage=boldmask, # frequencyLowThreshold = 0.01, frequencyHighThreshold = 0.1, # spatialSmoothingType = "gaussian", spatialSmoothingParameters = 2, # residualizeMatrix=TRUE, numberOfCompCorComponents=2 ) # boldmat<-timeseries2matrix( cleanfMRI$cleanBoldImage, cleanfMRI$maskImage ) # roimat<-timeseries2matrix( cleanfMRI$cleanBoldImage, roimask ) # roimean<-rowMeans( roimat ) # svd instead? # roimat<-matrix( roimean, ncol=1) # dnz<-rsfDenoise( boldmat[timeselect,] , # roimat[timeselect,1], motionparams=NA, # polydegree=1, crossvalidationgroups = 8, maxnoisepreds=c(2:4), debug=F ) # # might iterate over above to further refine noise variables # mdl<-bigLMStats( lm( boldmat[timeselect,] ~ roimean[timeselect] + # dnz$polys + dnz$noiseu ), 0.001 ) # betas<-mdl$beta.t[1,] # sum(betas[betas > 3]) # betaimg<-antsImageClone( boldmask ) # betaimg[ boldmask == 1 ]<-betas # antsImageWrite( betaimg, "betas2.nii.gz" ) # # # more complex # bold<-antsImageRead("bold.nii.gz") # boldmask<-antsImageRead("meanboldmask.nii.gz") # aalimg<-antsImageRead("meanboldAALmask.nii.gz") # data("aal",package="ANTsR") # dmnlabels<-aal$label_num[aal$isdmn>0] # aalvec<-aalimg > 0 # whichregion<-3 # for ( i in 1:max(aalimg) ) # { # if ( ! ( i %in% dmnlabels[whichregion] ) ) # { # aalimg[ aalimg == as.numeric(i) ]<-0 # } # } # maskvec<-boldmask > 0 & aalimg == whichregion # boldmask[ maskvec ]<-0 # timeselect<-10:dim(bold)[4] # if ( ! exists("moco") ) { # moco<-.motion_correction(bold,moreaccurate=1) # moco<-as.matrix( moco$moco_params )[timeselect,3:ncol(moco$moco_params)] # } # boldmat<-timeseries2matrix(bold,boldmask) # boldmat<-boldmat[timeselect,] # aalimg[aalimg > 0 ]<-1 # dmnvec<-rowMeans(timeseries2matrix(bold,aalimg))[timeselect] # dmnvec<-(stl(ts(dmnvec, frequency = 4),"per")$time.series)[,2] # dmnvec2<-(stl(ts(dmnvec, frequency = 100),"per")$time.series)[,2] # dmnvec<-ts(as.numeric(dmnvec)-as.numeric(dmnvec2)) # dmnmat<-matrix( dmnvec, ncol=1) # dnz<-rsfDenoise( boldmat , dmnmat[,1], motionparams=moco, polydegree=4, # crossvalidationgroups = 8, maxnoisepreds=1:4, debug=F ) # print(paste("Best number of noise regressors",dnz$n)) # # now recompute the matrix using the full mask # boldmask<-antsImageRead("meanboldmask.nii.gz") # boldmat<-timeseries2matrix(bold,boldmask) # boldmat<-boldmat[timeselect,] # mdl<-bigLMStats( lm( boldmat ~ dmnmat[,1] + dnz$polys + dnz$noiseu ), 0.001 ) # betas<-mdl$beta.t[1,] ## End(Not run)## Not run: # if (!exists("fn") ) fn<-getANTsRData("pcasl") # bold <- antsImageRead( fn ) # avgbold<-getAverageOfTimeSeries(bold) # boldmask<-getMask( avgbold ) # roimask<-antsImageRead("roi.nii.gz") # timeselect<-10:(dim(bold)[4]-10) # # can do this if you like its approach # cleanfMRI <- preprocessfMRI( bold, maskImage=boldmask, # frequencyLowThreshold = 0.01, frequencyHighThreshold = 0.1, # spatialSmoothingType = "gaussian", spatialSmoothingParameters = 2, # residualizeMatrix=TRUE, numberOfCompCorComponents=2 ) # boldmat<-timeseries2matrix( cleanfMRI$cleanBoldImage, cleanfMRI$maskImage ) # roimat<-timeseries2matrix( cleanfMRI$cleanBoldImage, roimask ) # roimean<-rowMeans( roimat ) # svd instead? # roimat<-matrix( roimean, ncol=1) # dnz<-rsfDenoise( boldmat[timeselect,] , # roimat[timeselect,1], motionparams=NA, # polydegree=1, crossvalidationgroups = 8, maxnoisepreds=c(2:4), debug=F ) # # might iterate over above to further refine noise variables # mdl<-bigLMStats( lm( boldmat[timeselect,] ~ roimean[timeselect] + # dnz$polys + dnz$noiseu ), 0.001 ) # betas<-mdl$beta.t[1,] # sum(betas[betas > 3]) # betaimg<-antsImageClone( boldmask ) # betaimg[ boldmask == 1 ]<-betas # antsImageWrite( betaimg, "betas2.nii.gz" ) # # # more complex # bold<-antsImageRead("bold.nii.gz") # boldmask<-antsImageRead("meanboldmask.nii.gz") # aalimg<-antsImageRead("meanboldAALmask.nii.gz") # data("aal",package="ANTsR") # dmnlabels<-aal$label_num[aal$isdmn>0] # aalvec<-aalimg > 0 # whichregion<-3 # for ( i in 1:max(aalimg) ) # { # if ( ! ( i %in% dmnlabels[whichregion] ) ) # { # aalimg[ aalimg == as.numeric(i) ]<-0 # } # } # maskvec<-boldmask > 0 & aalimg == whichregion # boldmask[ maskvec ]<-0 # timeselect<-10:dim(bold)[4] # if ( ! exists("moco") ) { # moco<-.motion_correction(bold,moreaccurate=1) # moco<-as.matrix( moco$moco_params )[timeselect,3:ncol(moco$moco_params)] # } # boldmat<-timeseries2matrix(bold,boldmask) # boldmat<-boldmat[timeselect,] # aalimg[aalimg > 0 ]<-1 # dmnvec<-rowMeans(timeseries2matrix(bold,aalimg))[timeselect] # dmnvec<-(stl(ts(dmnvec, frequency = 4),"per")$time.series)[,2] # dmnvec2<-(stl(ts(dmnvec, frequency = 100),"per")$time.series)[,2] # dmnvec<-ts(as.numeric(dmnvec)-as.numeric(dmnvec2)) # dmnmat<-matrix( dmnvec, ncol=1) # dnz<-rsfDenoise( boldmat , dmnmat[,1], motionparams=moco, polydegree=4, # crossvalidationgroups = 8, maxnoisepreds=1:4, debug=F ) # print(paste("Best number of noise regressors",dnz$n)) # # now recompute the matrix using the full mask # boldmask<-antsImageRead("meanboldmask.nii.gz") # boldmat<-timeseries2matrix(bold,boldmask) # boldmat<-boldmat[timeselect,] # mdl<-bigLMStats( lm( boldmat ~ dmnmat[,1] + dnz$polys + dnz$noiseu ), 0.001 ) # betas<-mdl$beta.t[1,] ## End(Not run)
This function automatically selects the fastest algorithm based on data dimensions.
rvcoef(X, Y)rvcoef(X, Y)
X |
A numeric matrix (n observations, p variables). |
Y |
A numeric matrix (n observations, q variables). |
A single scalar value for the RV-coefficient.
This function automatically selects the fastest algorithm based on data dimensions. Internal Dispatcher: Returns all components from the fastest method.
rvcoef_components(X, Y)rvcoef_components(X, Y)
X |
A numeric matrix (n observations, p variables). |
Y |
A numeric matrix (n observations, q variables). |
values.
Computes the RV-Coefficient (Internal) Gram Matrix Method for Tall data
rvcoef_gram_impl(X_centered, Y_centered)rvcoef_gram_impl(X_centered, Y_centered)
X_centered |
A numeric matrix (n observations, p variables). |
Y_centered |
A numeric matrix (n observations, q variables). |
values.
Computes the RV-Coefficient (Internal) Trace Method for Wide data
rvcoef_trace_impl(X_centered, Y_centered)rvcoef_trace_impl(X_centered, Y_centered)
X_centered |
A numeric matrix (n observations, p variables). |
Y_centered |
A numeric matrix (n observations, q variables). |
values.
Performs PCA after automatically detecting and fixing problematic columns (e.g., zero variance, NA-only, partial NAs) in a deterministic way. Ensures that the output dimensions match those from a clean dataset.
safe_pca(X, nc = min(dim(X)), center = TRUE, scale = TRUE)safe_pca(X, nc = min(dim(X)), center = TRUE, scale = TRUE)
X |
A numeric matrix or data frame. |
nc |
Number of components to return. |
center |
Logical, whether to center columns. |
scale |
Logical, whether to scale columns to unit variance. |
A list with the same structure as prcomp,
with rotation, sdev, x, etc.
set.seed(123) mat <- matrix(rnorm(50), nrow = 10) mat[, 3] <- 1 # zero variance col mat[, 5] <- NA # all NA col # result <- safe_pca(mat, nc = 3) # result$rotationset.seed(123) mat <- matrix(rnorm(50), nrow = 10) mat[, 3] <- 1 # zero variance col mat[, 5] <- NA # all NA col # result <- safe_pca(mat, nc = 3) # result$rotation
Use this function to save an object or a full R session for later use. Any object can be saved (list, antsImage, data frame, etc.). The function will save all antsImage objects as nifti files with random filenames (to avoid using (sub)variable names, which can be identical). These files is what load.ANTsR uses later to fill back the original antsImage variables. For variables that contain filenames, you can choose to copy those files in your saved folder so you can completely recreate the environment even if you change computer or the temporary folder is deleted.
save.ANTsR( filename = file.path(".", ".ANTsRsession"), objects = NA, env = as.environment(1), overwrite = FALSE, clonediskfiles = TRUE, ... )save.ANTsR( filename = file.path(".", ".ANTsRsession"), objects = NA, env = as.environment(1), overwrite = FALSE, clonediskfiles = TRUE, ... )
filename |
Prefix for folder to store data. |
objects |
Vector of character names of objects to store. Can be antsImages. |
env |
Environment to save from or load to. |
overwrite |
logical to select whether overwriting existing data is allowed. |
clonediskfiles |
logical enables the copying of disk files that are not loaded in workspace but where character variables point. Set to TRUE if moving sessions from one computer to another or if you save antsRegistration() outputs. Set to FALSE if you save temporary sessions to continue later on the same computer. |
... |
Additional arguments to pass to |
Dorian Pustina
## Not run: # causes problems with devtools::run_examples() # a <- 1 # b <- c( 2, 3, 4) # save.ANTsR(objects=c('b', 'a')) # load.ANTsR("./.ANTsRsession") ## End(Not run)## Not run: # causes problems with devtools::run_examples() # a <- 1 # b <- c( 2, 3, 4) # save.ANTsR(objects=c('b', 'a')) # load.ANTsR("./.ANTsRsession") ## End(Not run)
Deploy a multiscale laplacian blob detector on an image. The function will return the blob descriptors as an image and data frame. NOTE: you will get different features running on the raw image versus its negation.
scaleSpaceFeatureDetection( image, numberOfBlobsToExtract, minScale, maxScale, stepsPerOctave = 10, negate = FALSE )scaleSpaceFeatureDetection( image, numberOfBlobsToExtract, minScale, maxScale, stepsPerOctave = 10, negate = FALSE )
image |
the input image |
numberOfBlobsToExtract |
the estimated blob count |
minScale |
the minimum amount of smoothing in scale space |
maxScale |
the maximum amount of smoothing in scale space |
stepsPerOctave |
the number of steps to take over scale space octaves |
negate |
boolean to compute features from both image and its negation |
list of antsImage and dataframe for blob descriptors
Avants BB
# WIP: should explore effect of parameters further blob1 <- scaleSpaceFeatureDetection(ri(1), 50) blob2 <- scaleSpaceFeatureDetection(max(ri(1)) - ri(1), 50)# WIP: should explore effect of parameters further blob1 <- scaleSpaceFeatureDetection(ri(1), 50) blob2 <- scaleSpaceFeatureDetection(max(ri(1)) - ri(1), 50)
Calculates the SD of an image
Overloaded SD for antsImage objects
sd(x, na.rm = FALSE, ...) ## Default S3 method: sd(x, na.rm = FALSE, ...) ## S3 method for class 'antsImage' sd(x, na.rm = FALSE, ..., mask = NULL)sd(x, na.rm = FALSE, ...) ## Default S3 method: sd(x, na.rm = FALSE, ...) ## S3 method for class 'antsImage' sd(x, na.rm = FALSE, ..., mask = NULL)
x |
an object for which we want to compute the SD |
na.rm |
a logical value indicating whether NA should be removed |
... |
Any additional arguments to be passed to
|
mask |
is an object of class |
img <- antsImageRead(getANTsRData("r16")) sd(img) sd(img, mask = img > 0)img <- antsImageRead(getANTsRData("r16")) sd(img) sd(img, mask = img > 0)
A random forest implementation of the corrective learning wrapper introduced in Wang, et al., Neuroimage 2011 (https://pubmed.ncbi.nlm.nih.gov/21237273). The prediction process involves using the label-specific training models to refine an initial segmentation.
segmentationRefinement.predict( segmentationImage, labelSet, labelModels, featureImages, featureImageNames, dilationRadius = 2, neighborhoodRadius = 0, normalizeSamplesPerLabel = TRUE, useEntireLabeledRegion = TRUE )segmentationRefinement.predict( segmentationImage, labelSet, labelModels, featureImages, featureImageNames, dilationRadius = 2, neighborhoodRadius = 0, normalizeSamplesPerLabel = TRUE, useEntireLabeledRegion = TRUE )
segmentationImage |
image to refine via corrective learning. |
labelSet |
a vector specifying the labels of interest. Must be specified. |
labelModels |
a list of models. Each element of the labelSet requires a model. |
featureImages |
a list of feature images. |
featureImageNames |
is a vector of character strings naming the set of features. Must be specified. |
dilationRadius |
specifies the dilation radius for determining the ROI for each label using binary morphology. Alternatively, the user can specify a float distance value, e.g., "dilationRadius = '2.75mm'", to employ an isotropic dilation based on physical distance. For the latter, the distance value followed by the character string 'mm' (for millimeters) is necessary. |
neighborhoodRadius |
specifies which voxel neighbors should be included in prediction. The user can specify a scalar or vector but it must match with what was used for training. |
normalizeSamplesPerLabel |
if TRUE, the samples from each ROI are normalized by the mean of the voxels in that ROI. Can be a vector (one element per feature). |
useEntireLabeledRegion |
if TRUE, estimation is performed on the
full dilated ROI for each label. If FALSE, estimation is performed on the
combined inner and outer boundary region determined by the
|
a list consisting of the refined segmentation estimate (RefinedSegmentationImage) and a list of the foreground probability images (ForegroundProbabilityImages).
Tustison NJ
## Not run: library(ANTsR) library(ggplot2) imageIDs <- c("r16", "r27", "r30", "r62", "r64", "r85") # Perform simple 3-tissue segmentation. For convenience we are # going to use atropos segmentation to define the "ground-truth" # segmentations and the kmeans to define the segmentation we # want to "correct". We collect feature images for each image. # The gradient and laplacian images chosen below as feature # images are simply selected for convenience. segmentationLabels <- c(1, 2, 3) featureImageNames <- c("T1", "Gradient", "Laplacian") images <- list() kmeansSegs <- list() atroposSegs <- list() featureImages <- list() for (i in 1:length(imageIDs)) { cat("Processing image", imageIDs[i], "\n") images[[i]] <- antsImageRead(getANTsRData(imageIDs[i])) mask <- getMask(images[[i]]) kmeansSegs[[i]] <- kmeansSegmentation(images[[i]], length(segmentationLabels), mask, mrf = 0.0 )$segmentation atroposSegs[[i]] <- atropos(images[[i]], mask, i = "KMeans[3]", m = "[0.25,1x1]", c = "[5,0]" )$segmentation featureImageSetPerImage <- list() featureImageSetPerImage[[1]] <- images[[i]] featureImageSetPerImage[[2]] <- iMath(images[[i]], "Grad", 1.0) featureImageSetPerImage[[3]] <- iMath(images[[i]], "Laplacian", 1.0) featureImages[[i]] <- featureImageSetPerImage } # Perform training. We train on images "r27", "r30", # "r62", "r64", "r85" and # test/predict on image "r16". cat("\nTraining\n\n") segLearning <- segmentationRefinement.train( featureImages = featureImages[2:6], truthLabelImages = atroposSegs[2:6], segmentationImages = kmeansSegs[2:6], featureImageNames = featureImageNames, labelSet = segmentationLabels, maximumNumberOfSamplesOrProportionPerClass = 100, dilationRadius = 1, neighborhoodRadius = c(1, 1), normalizeSamplesPerLabel = TRUE, useEntireLabeledRegion = FALSE ) cat("\nPrediction\n\n") refinement <- segmentationRefinement.predict( segmentationImage = kmeansSegs[[1]], labelSet = segmentationLabels, segLearning$LabelModels, featureImages[[1]], featureImageNames, dilationRadius = 1, neighborhoodRadius = c(1, 1), normalizeSamplesPerLabel = TRUE ) # Compare "ground truth" = atroposSegs[[1]] with # refinement$RefinedSegmentationImage antsImageWrite( refinement$RefinedSegmentationImage, "r16RefinedSegmentation.nii.gz" ) ## End(Not run)## Not run: library(ANTsR) library(ggplot2) imageIDs <- c("r16", "r27", "r30", "r62", "r64", "r85") # Perform simple 3-tissue segmentation. For convenience we are # going to use atropos segmentation to define the "ground-truth" # segmentations and the kmeans to define the segmentation we # want to "correct". We collect feature images for each image. # The gradient and laplacian images chosen below as feature # images are simply selected for convenience. segmentationLabels <- c(1, 2, 3) featureImageNames <- c("T1", "Gradient", "Laplacian") images <- list() kmeansSegs <- list() atroposSegs <- list() featureImages <- list() for (i in 1:length(imageIDs)) { cat("Processing image", imageIDs[i], "\n") images[[i]] <- antsImageRead(getANTsRData(imageIDs[i])) mask <- getMask(images[[i]]) kmeansSegs[[i]] <- kmeansSegmentation(images[[i]], length(segmentationLabels), mask, mrf = 0.0 )$segmentation atroposSegs[[i]] <- atropos(images[[i]], mask, i = "KMeans[3]", m = "[0.25,1x1]", c = "[5,0]" )$segmentation featureImageSetPerImage <- list() featureImageSetPerImage[[1]] <- images[[i]] featureImageSetPerImage[[2]] <- iMath(images[[i]], "Grad", 1.0) featureImageSetPerImage[[3]] <- iMath(images[[i]], "Laplacian", 1.0) featureImages[[i]] <- featureImageSetPerImage } # Perform training. We train on images "r27", "r30", # "r62", "r64", "r85" and # test/predict on image "r16". cat("\nTraining\n\n") segLearning <- segmentationRefinement.train( featureImages = featureImages[2:6], truthLabelImages = atroposSegs[2:6], segmentationImages = kmeansSegs[2:6], featureImageNames = featureImageNames, labelSet = segmentationLabels, maximumNumberOfSamplesOrProportionPerClass = 100, dilationRadius = 1, neighborhoodRadius = c(1, 1), normalizeSamplesPerLabel = TRUE, useEntireLabeledRegion = FALSE ) cat("\nPrediction\n\n") refinement <- segmentationRefinement.predict( segmentationImage = kmeansSegs[[1]], labelSet = segmentationLabels, segLearning$LabelModels, featureImages[[1]], featureImageNames, dilationRadius = 1, neighborhoodRadius = c(1, 1), normalizeSamplesPerLabel = TRUE ) # Compare "ground truth" = atroposSegs[[1]] with # refinement$RefinedSegmentationImage antsImageWrite( refinement$RefinedSegmentationImage, "r16RefinedSegmentation.nii.gz" ) ## End(Not run)
A random forest implementation of the corrective learning wrapper introduced in Wang, et al., Neuroimage 2011 (https://pubmed.ncbi.nlm.nih.gov/21237273). The training process involves building two sets of models from training data for each label in the initial segmentation data.
segmentationRefinement.train( featureImages, truthLabelImages, segmentationImages, featureImageNames = c(), labelSet = c(), maximumNumberOfSamplesOrProportionPerClass = 1, dilationRadius = 2, neighborhoodRadius = 0, normalizeSamplesPerLabel = TRUE, useEntireLabeledRegion = TRUE )segmentationRefinement.train( featureImages, truthLabelImages, segmentationImages, featureImageNames = c(), labelSet = c(), maximumNumberOfSamplesOrProportionPerClass = 1, dilationRadius = 2, neighborhoodRadius = 0, normalizeSamplesPerLabel = TRUE, useEntireLabeledRegion = TRUE )
featureImages |
a list of lists of feature images. Each list of feature images corresponds to a single subject. Possibilities are outlined in the above-cited paper. |
truthLabelImages |
a list of "ground-truth" segmentation images, one for each set of feature images. |
segmentationImages |
a list of estimated segmentation images, one for each set of feature images. |
featureImageNames |
a vector of character strings naming the set of features. This parameter is optional but does help in investigating the relative importance of specific features. |
labelSet |
a vector specifying the labels of interest. If not specified, the full set is determined from the truthLabelImages. |
maximumNumberOfSamplesOrProportionPerClass |
specified the maximum number of samples used to build the model for each element of the labelSet. If <= 1, we use it as as a proportion of the total number of voxels. |
dilationRadius |
specifies the dilation radius for determining the ROI for each label using binary morphology. Alternatively, the user can specify a float distance value, e.g., "dilationRadius = '2.75mm'", to employ an isotropic dilation based on physical distance. For the latter, the distance value followed by the character string 'mm' (for millimeters) is necessary. |
neighborhoodRadius |
specifies which voxel neighbors should be included in building the model. The user can specify a scalar or vector. |
normalizeSamplesPerLabel |
if TRUE, the samples from each ROI are normalized by the mean of the voxels in that ROI. Can also specify as a vector to normalize per feature image. |
useEntireLabeledRegion |
if TRUE, samples are taken from the full
dilated ROI for each label. If FALSE, samples are taken only from the
combined inner and outer boundary region determined by the
|
list with the models per label (LabelModels), the label set (LabelSet), and the feature image names (FeatureImageNames).
Tustison NJ
## Not run: library(ANTsR) library(ggplot2) imageIDs <- c("r16", "r27", "r30", "r62", "r64", "r85") # Perform simple 3-tissue segmentation. For convenience we are # going to use atropos segmentation to define the "ground-truth" # segmentations and the kmeans to define the segmentation we # want to "correct". We collect feature images for each image. # The gradient and laplacian images chosen below as feature # images are simply selected for convenience. segmentationLabels <- c(1, 2, 3) featureImageNames <- c("T1", "Gradient", "Laplacian") images <- list() kmeansSegs <- list() atroposSegs <- list() featureImages <- list() for (i in 1:length(imageIDs)) { cat("Processing image", imageIDs[i], "\n") images[[i]] <- antsImageRead(getANTsRData(imageIDs[i])) mask <- getMask(images[[i]]) kmeansSegs[[i]] <- kmeansSegmentation(images[[i]], length(segmentationLabels), mask, mrf = 0.0 )$segmentation atroposSegs[[i]] <- atropos(images[[i]], mask, i = "KMeans[3]", m = "[0.25,1x1]", c = "[5,0]" )$segmentation featureImageSetPerImage <- list() featureImageSetPerImage[[1]] <- images[[i]] featureImageSetPerImage[[2]] <- iMath(images[[i]], "Grad", 1.0) featureImageSetPerImage[[3]] <- iMath(images[[i]], "Laplacian", 1.0) featureImages[[i]] <- featureImageSetPerImage } # Perform training. We train on images "r27", "r30", "r62", "r64", # "r85" and test/predict # on image "r16". cat("\nTraining\n\n") segLearning <- segmentationRefinement.train( featureImages = featureImages[2:6], truthLabelImages = atroposSegs[2:6], segmentationImages = kmeansSegs[2:6], featureImageNames = featureImageNames, labelSet = segmentationLabels, maximumNumberOfSamplesOrProportionPerClass = 100, dilationRadius = 1, normalizeSamplesPerLabel = TRUE, useEntireLabeledRegion = FALSE ) ## End(Not run)## Not run: library(ANTsR) library(ggplot2) imageIDs <- c("r16", "r27", "r30", "r62", "r64", "r85") # Perform simple 3-tissue segmentation. For convenience we are # going to use atropos segmentation to define the "ground-truth" # segmentations and the kmeans to define the segmentation we # want to "correct". We collect feature images for each image. # The gradient and laplacian images chosen below as feature # images are simply selected for convenience. segmentationLabels <- c(1, 2, 3) featureImageNames <- c("T1", "Gradient", "Laplacian") images <- list() kmeansSegs <- list() atroposSegs <- list() featureImages <- list() for (i in 1:length(imageIDs)) { cat("Processing image", imageIDs[i], "\n") images[[i]] <- antsImageRead(getANTsRData(imageIDs[i])) mask <- getMask(images[[i]]) kmeansSegs[[i]] <- kmeansSegmentation(images[[i]], length(segmentationLabels), mask, mrf = 0.0 )$segmentation atroposSegs[[i]] <- atropos(images[[i]], mask, i = "KMeans[3]", m = "[0.25,1x1]", c = "[5,0]" )$segmentation featureImageSetPerImage <- list() featureImageSetPerImage[[1]] <- images[[i]] featureImageSetPerImage[[2]] <- iMath(images[[i]], "Grad", 1.0) featureImageSetPerImage[[3]] <- iMath(images[[i]], "Laplacian", 1.0) featureImages[[i]] <- featureImageSetPerImage } # Perform training. We train on images "r27", "r30", "r62", "r64", # "r85" and test/predict # on image "r16". cat("\nTraining\n\n") segLearning <- segmentationRefinement.train( featureImages = featureImages[2:6], truthLabelImages = atroposSegs[2:6], segmentationImages = kmeansSegs[2:6], featureImageNames = featureImageNames, labelSet = segmentationLabels, maximumNumberOfSamplesOrProportionPerClass = 100, dilationRadius = 1, normalizeSamplesPerLabel = TRUE, useEntireLabeledRegion = FALSE ) ## End(Not run)
Basic one-hot transformation of segmentations array.
segmentationToOneHot( segmentationsArray, segmentationLabels = NULL, channelFirstOrdering = FALSE )segmentationToOneHot( segmentationsArray, segmentationLabels = NULL, channelFirstOrdering = FALSE )
segmentationsArray |
multi-label numpy array |
segmentationLabels |
vector of segmentation labels. Note that a background label (typically 0) needs to be included. |
channelFirstOrdering |
Specifies the ordering of the dimensions. |
an n-D array of shape where the segmentation labels are expanded in a one-hot fashion in the channels dimension.
Tustison NJ
r16 <- antsImageRead( getANTsRData( "r16" ) ) seg <- kmeansSegmentation( r16, 3 )$segmentation oneHot <- segmentationToOneHot( as.array( seg ) ) r16 <- antsImageRead( getANTsRData( "r16" ) ) seg <- kmeansSegmentation( r16, 3 )$segmentation oneHot <- segmentationToOneHot( as.array( seg ), channelFirstOrdering = TRUE )r16 <- antsImageRead( getANTsRData( "r16" ) ) seg <- kmeansSegmentation( r16, 3 )$segmentation oneHot <- segmentationToOneHot( as.array( seg ) ) r16 <- antsImageRead( getANTsRData( "r16" ) ) seg <- kmeansSegmentation( r16, 3 )$segmentation oneHot <- segmentationToOneHot( as.array( seg ), channelFirstOrdering = TRUE )
takes an image and a shape and relates the 2nd with the first to yield a feature image - the function is user modifiable but defaults to cor
segmentShapeFromImage( img, shape, mask = NULL, rad = NA, scfun, maskZeroes = TRUE )segmentShapeFromImage( img, shape, mask = NULL, rad = NA, scfun, maskZeroes = TRUE )
img |
antsImage |
shape |
to define features |
mask |
with values 1 or 0 |
rad |
max radius ( optional, not recommended ) |
scfun |
function to apply to create feature image (defaults to cor) |
maskZeroes |
if TRUE (default), zeroes will not influence the result |
feature image
Brian B. Avants
set.seed(123) fi <- makeImage(c(20, 20), rnorm(400, mean = 1, sd = 0.1)) mask <- getMask(fi, 0.8, Inf, 0) segs <- kmeansSegmentation(fi, 3, mask)$segmentation segs[segs != 1] <- 0 shp <- labelClusters(segs, 1) shp[shp != 1] <- 0 fimg <- segmentShapeFromImage(fi, shp, mask)set.seed(123) fi <- makeImage(c(20, 20), rnorm(400, mean = 1, sd = 0.1)) mask <- getMask(fi, 0.8, Inf, 0) segs <- kmeansSegmentation(fi, 3, mask)$segmentation segs[segs != 1] <- 0 shp <- labelClusters(segs, 1) shp[shp != 1] <- 0 fimg <- segmentShapeFromImage(fi, shp, mask)
This function determines a single optimal number of components (k) to represent a multi-view dataset by analyzing the joint variance explained curve. It offers multiple methods for selecting k and includes a built-in self-test to verify its own correctness.
select_joint_k( mat_list = NULL, method = c("pca", "spca"), k_max = NULL, sparsity = 0.5, selection_method = c("elbow", "threshold"), variance_threshold = 0.9, self_test = FALSE )select_joint_k( mat_list = NULL, method = c("pca", "spca"), k_max = NULL, sparsity = 0.5, selection_method = c("elbow", "threshold"), variance_threshold = 0.9, self_test = FALSE )
mat_list |
A list of numeric matrices [subjects x features]. Required unless 'self_test = TRUE'. |
method |
The decomposition method. One of '"pca"' (fast SVD-based) or '"spca"'. |
k_max |
The maximum number of components to consider. |
sparsity |
A single sparsity parameter (0-1) for SPCA. Ignored for PCA. |
selection_method |
The method for choosing k. One of '"elbow"' (point of maximum deviation from a straight line of improvement) or '"threshold"'. |
variance_threshold |
The proportion of variance (0-1) to be explained. Only used when 'selection_method = "threshold"'. |
self_test |
Logical. If TRUE, the function will ignore all other inputs, run a built-in suite of tests on simulated data, and print the results. This is for verifying the function's integrity. Defaults to FALSE. |
If 'self_test = FALSE', a list containing:
'optimal_k': The selected optimal number of components.
'joint_variance_curve': A tibble with 'k' and the cumulative proportion of variance explained at each 'k'.
'plot': A ggplot object visualizing the results.
If 'self_test = TRUE', it prints test results and returns invisibly.
Set ANTs deterministic behavior
setANTsDeterministic(on = TRUE, seedValue = 123)setANTsDeterministic(on = TRUE, seedValue = 123)
on |
Set deterministic behavior. |
seedValue |
Assign random seed value. |
No return value, called for side effects.
setANTsDeterministic(TRUE)setANTsDeterministic(TRUE)
Set parameters of transform
setAntsrTransformFixedParameters(transform, parameters)setAntsrTransformFixedParameters(transform, parameters)
transform |
antsrTransform |
parameters |
array of parameters' |
TRUE
tx <- new("antsrTransform") params <- getAntsrTransformFixedParameters(tx) setAntsrTransformFixedParameters(tx, params * 2)tx <- new("antsrTransform") params <- getAntsrTransformFixedParameters(tx) setAntsrTransformFixedParameters(tx, params * 2)
Set parameters of transform
setAntsrTransformParameters(transform, parameters)setAntsrTransformParameters(transform, parameters)
transform |
antsrTransform |
parameters |
array of parameters |
TRUE
tx <- new("antsrTransform") params <- getAntsrTransformParameters(tx) setAntsrTransformParameters(tx, params * 2)tx <- new("antsrTransform") params <- getAntsrTransformParameters(tx) setAntsrTransformParameters(tx, params * 2)
This function sets the random number generator seed based on the current time, with a fine resolution of seconds. This ensures a different seed is used each time the function is called, provided calls are at least one second apart.
setSeedBasedOnTime()setSeedBasedOnTime()
The numeric value used as the seed, derived from the current time in seconds.
seedValue <- setSeedBasedOnTime() print(seedValue)seedValue <- setSeedBasedOnTime() print(seedValue)
shorter antspymm names
shorten_pymm_names(x)shorten_pymm_names(x)
x |
string or strings |
string
Avants BB
simlr minimizes reconstruction error across related modalities. That is, simlr will reconstruct each modality matrix from a basis set derived from the other modalities. The basis set can be derived from SVD, ICA or a simple sum of basis representations. This function produces dataset-wide multivariate beta maps for each of the related matrices. The multivariate beta maps are regularized by user input matrices that encode relationships between variables. The idea is overall similar to canonical correlation analysis but generalizes the basis construction and to arbitrary numbers of modalities.
simlr( data_matrices, smoothingMatrices, iterations = 500, sparsenessQuantiles = NULL, positivities = NULL, initialUMatrix = NULL, mixAlg = c("svd", "ica", "avg", "rrpca-l", "rrpca-s", "pca", "stochastic", "newton-schulz", "ica-newton"), repeatedMeasures = NA, lineSearchRange = c(-500, 500), lineSearchTolerance = 1e-12, randomSeed = 0, constraint = c("nsaflowx0.5x10", "orthox0x1", "Grassmannx0", "Stiefelx0", "none"), energyType = c("cca", "regression", "normalized", "ucca", "lowRank", "lowRankRegression", "normalized_correlation", "acc", "nc", "dat", "lrr", "reconorm", "logcosh", "exp", "kurtosis", "gauss"), vmats = NULL, connectors = NULL, optimizationStyle = c("bidirectional_lookahead", "armijo_gradient", "lookahead", "bidirectional_armijo_gradient"), scale = c("center", "eigenvalue"), expBeta = 0.9, jointInitialization = TRUE, sparsenessAlg = "soft", orthogonalizeU = FALSE, domainMatrices = NULL, domainLambdas = NULL, sparse_gradient = TRUE, verbose = FALSE )simlr( data_matrices, smoothingMatrices, iterations = 500, sparsenessQuantiles = NULL, positivities = NULL, initialUMatrix = NULL, mixAlg = c("svd", "ica", "avg", "rrpca-l", "rrpca-s", "pca", "stochastic", "newton-schulz", "ica-newton"), repeatedMeasures = NA, lineSearchRange = c(-500, 500), lineSearchTolerance = 1e-12, randomSeed = 0, constraint = c("nsaflowx0.5x10", "orthox0x1", "Grassmannx0", "Stiefelx0", "none"), energyType = c("cca", "regression", "normalized", "ucca", "lowRank", "lowRankRegression", "normalized_correlation", "acc", "nc", "dat", "lrr", "reconorm", "logcosh", "exp", "kurtosis", "gauss"), vmats = NULL, connectors = NULL, optimizationStyle = c("bidirectional_lookahead", "armijo_gradient", "lookahead", "bidirectional_armijo_gradient"), scale = c("center", "eigenvalue"), expBeta = 0.9, jointInitialization = TRUE, sparsenessAlg = "soft", orthogonalizeU = FALSE, domainMatrices = NULL, domainLambdas = NULL, sparse_gradient = TRUE, verbose = FALSE )
data_matrices |
A list that contains the named matrices. Note: the optimization will likely perform much more smoothly if the input matrices are each scaled to zero mean unit variance e.g. by the |
smoothingMatrices |
list of (sparse) matrices that allow parameter smoothing/regularization. These should be square and same order and size of input matrices. |
iterations |
number of gradient descent iterations |
sparsenessQuantiles |
vector of quantiles to control sparseness - higher is sparser |
positivities |
vector that sets for each matrix if we restrict to positive or negative solution (beta) weights. choices are positive, negative or either as expressed as a string. |
initialUMatrix |
list of initialization matrix size |
mixAlg |
'svd', 'ica', 'rrpca-l', 'rrpca-s', 'stochastic', 'pca', 'newton-schulz', 'ica-newton' or 'avg' denotes the algorithm employed when estimating the mixed modality bases |
repeatedMeasures |
list of repeated measurement identifiers. this will allow estimates of per identifier intercept. |
lineSearchRange |
lower and upper limit used in |
lineSearchTolerance |
tolerance used in |
randomSeed |
controls repeatability of ica-based decomposition |
constraint |
one of none, Grassmann, GrassmannInv or Stiefel |
energyType |
one of regression, normalized, lowRank, cca or ucca |
vmats |
optional initial |
connectors |
a list ( length of projections or number of modalities ) that indicates which modalities should be paired with current modality |
optimizationStyle |
the simlr optimizer |
scale |
options to standardize each matrix. e.g. divide by the square root of its number of variables (Westerhuis, Kourti, and MacGregor 1998), divide by the number of variables or center or center and scale or ... (see code). can be a vector which will apply each strategy in order. |
expBeta |
if greater than zero, use exponential moving average on gradient and mixing (default 0.9). |
jointInitialization |
boolean for initialization options, default TRUE |
sparsenessAlg |
NA is default otherwise basic, spmp or orthorank |
orthogonalizeU |
boolean controlling whether we orthogonalize the U matrices |
domainMatrices |
matrices containing domain knowledge length of |
domainLambdas |
weights for domain knowledge term length of |
sparse_gradient |
boolean default TRUE |
verbose |
boolean to control verbosity of output - set to level |
A list of u, x, y, z etc related matrices.
BB Avants.
## Not run: set.seed(1500) nsub <- 25 npix <- c(100, 200, 133) nk <- 5 outcome <- matrix(rnorm(nsub * nk), ncol = nk) outcome1 <- matrix(rnorm(nsub * nk), ncol = nk) outcome2 <- matrix(rnorm(nsub * nk), ncol = nk) outcome3 <- matrix(rnorm(nsub * nk), ncol = nk) view1tx <- matrix(rnorm(npix[1] * nk), nrow = nk) view2tx <- matrix(rnorm(npix[2] * nk), nrow = nk) view3tx <- matrix(rnorm(npix[3] * nk), nrow = nk) mat1 <- (outcome %*% t(outcome1) %*% (outcome1)) %*% view1tx mat2 <- (outcome %*% t(outcome2) %*% (outcome2)) %*% view2tx mat3 <- (outcome %*% t(outcome3) %*% (outcome3)) %*% view3tx matlist <- list(vox = mat1, vox2 = mat2, vox3 = mat3) result <- simlr(matlist) p1 <- mat1 %*% (result$v[[1]]) p2 <- mat2 %*% (result$v[[2]]) p3 <- mat3 %*% (result$v[[3]]) regs <- regularizeSimlr(matlist) result2 <- simlr(matlist) pred1 <- predictSimlr(matlist, result) pred2 <- predictSimlr(matlist, result2) # compare to permuted data s1 <- sample(1:nsub) s2 <- sample(1:nsub) resultp <- simlr(list(vox = mat1, vox2 = mat2[s1, ], vox3 = mat3[s2, ])) p1p <- mat1 %*% (resultp$v[[1]]) p2p <- mat2[s1, ] %*% (resultp$v[[2]]) p3p <- mat3[s2, ] %*% (resultp$v[[3]]) # compare to SVD svd1 <- svd(mat1, nu = nk, nv = 0)$u svd2 <- svd(mat2, nu = nk, nv = 0)$u svd3 <- svd(mat3, nu = nk, nv = 0)$u # real range(cor(p1, p2)) range(cor(p1, p3)) range(cor(p3, p2)) # permuted range(cor(p1p, p2p)) range(cor(p1p, p3p)) range(cor(p3p, p2p)) # svd print(range(cor(svd1, svd2))) resultp <- simlr(list(vox = mat1, vox2 = mat2[s1, ], vox3 = mat3[s2, ]), initialUMatrix = nk, verbose = TRUE, iterations = 5, energyType = "normalized" ) ## End(Not run)## Not run: set.seed(1500) nsub <- 25 npix <- c(100, 200, 133) nk <- 5 outcome <- matrix(rnorm(nsub * nk), ncol = nk) outcome1 <- matrix(rnorm(nsub * nk), ncol = nk) outcome2 <- matrix(rnorm(nsub * nk), ncol = nk) outcome3 <- matrix(rnorm(nsub * nk), ncol = nk) view1tx <- matrix(rnorm(npix[1] * nk), nrow = nk) view2tx <- matrix(rnorm(npix[2] * nk), nrow = nk) view3tx <- matrix(rnorm(npix[3] * nk), nrow = nk) mat1 <- (outcome %*% t(outcome1) %*% (outcome1)) %*% view1tx mat2 <- (outcome %*% t(outcome2) %*% (outcome2)) %*% view2tx mat3 <- (outcome %*% t(outcome3) %*% (outcome3)) %*% view3tx matlist <- list(vox = mat1, vox2 = mat2, vox3 = mat3) result <- simlr(matlist) p1 <- mat1 %*% (result$v[[1]]) p2 <- mat2 %*% (result$v[[2]]) p3 <- mat3 %*% (result$v[[3]]) regs <- regularizeSimlr(matlist) result2 <- simlr(matlist) pred1 <- predictSimlr(matlist, result) pred2 <- predictSimlr(matlist, result2) # compare to permuted data s1 <- sample(1:nsub) s2 <- sample(1:nsub) resultp <- simlr(list(vox = mat1, vox2 = mat2[s1, ], vox3 = mat3[s2, ])) p1p <- mat1 %*% (resultp$v[[1]]) p2p <- mat2[s1, ] %*% (resultp$v[[2]]) p3p <- mat3[s2, ] %*% (resultp$v[[3]]) # compare to SVD svd1 <- svd(mat1, nu = nk, nv = 0)$u svd2 <- svd(mat2, nu = nk, nv = 0)$u svd3 <- svd(mat3, nu = nk, nv = 0)$u # real range(cor(p1, p2)) range(cor(p1, p3)) range(cor(p3, p2)) # permuted range(cor(p1p, p2p)) range(cor(p1p, p3p)) range(cor(p3p, p2p)) # svd print(range(cor(svd1, svd2))) resultp <- simlr(list(vox = mat1, vox2 = mat2[s1, ], vox3 = mat3[s2, ]), initialUMatrix = nk, verbose = TRUE, iterations = 5, energyType = "normalized" ) ## End(Not run)
This function calculates the average invariant orthogonality defect for a list of features, using the 'invariant_orthogonality_defect' function. The orthogonality defect measures the deviation of feature vectors from orthogonality.
simlr_feature_orth(p)simlr_feature_orth(p)
p |
A list of matrices (or data frames), each representing a set of feature vectors. |
The function iterates over each matrix in the list 'p' and applies the 'invariant_orthogonality_defect' function to calculate the orthogonality defect for each matrix. The final result is the average orthogonality defect across all matrices.
A numeric value representing the average invariant orthogonality defect across all the provided feature matrices.
# Example data: Two sets of feature matrices feature1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2) feature2 <- matrix(c(7, 8, 9, 10, 11, 12), nrow = 2) feature_list <- list(feature1, feature2) # Calculate the average orthogonality defect avg_orthogonality_defect <- simlr_feature_orth(feature_list) print(avg_orthogonality_defect)# Example data: Two sets of feature matrices feature1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2) feature2 <- matrix(c(7, 8, 9, 10, 11, 12), nrow = 2) feature_list <- list(feature1, feature2) # Calculate the average orthogonality defect avg_orthogonality_defect <- simlr_feature_orth(feature_list) print(avg_orthogonality_defect)
Impute missing SiMLR data in a specified column based on other columns
simlr_impute( dataframe, nms, vecnum, toimpute, separator = "PC", family = "gaussian" )simlr_impute( dataframe, nms, vecnum, toimpute, separator = "PC", family = "gaussian" )
dataframe |
A data frame containing the data to impute. |
nms |
A vector of base column names. |
vecnum |
A numeric value to append to the column names. |
toimpute |
The base name of the target column to be imputed. |
separator |
A string specifying the separator between the column name and feature. |
family |
A string specifying the GLM family (default is 'gaussian'). |
A data frame with imputed values.
set.seed(123) n=50 df <- data.frame( t1PC1 = rnorm(n), t1aPC1 = rnorm(n), dtPC1 = rnorm(n), dtaPC1 = rnorm(n), rsfPC1 = rnorm(n), perfPC1 = rnorm(n) ) df[ sample(1:nrow(df),20),6 ]=NA nms <- c("t1", "t1a", "dt", "dta", "rsf", "perf") vecnum <- 1 toimpute <- "perf" df = simlr_impute(df, nms, vecnum, toimpute, family = 'gaussian')set.seed(123) n=50 df <- data.frame( t1PC1 = rnorm(n), t1aPC1 = rnorm(n), dtPC1 = rnorm(n), dtaPC1 = rnorm(n), rsfPC1 = rnorm(n), perfPC1 = rnorm(n) ) df[ sample(1:nrow(df),20),6 ]=NA nms <- c("t1", "t1a", "dt", "dta", "rsf", "perf") vecnum <- 1 toimpute <- "perf" df = simlr_impute(df, nms, vecnum, toimpute, family = 'gaussian')
Creates the list that should be passed to the connectors argument to simlr. the different options are default (0) which connects each to all others but not itself, a single integer > 0 which forces modeling to focus on a given target and then a pca like option.
simlr_path_models(n, type = 0)simlr_path_models(n, type = 0)
n |
The length of the output list. |
type |
The type of modeling. Can be one of the following: - 0: "Exclude self" - each entry contains all integers except the one corresponding to its position. - Integer greater than 0: "focus on a target" - each entry contains the target integer, except for the entry at the target position, which contains all integers except the target. - 'pca': "Identity" - each entry contains its own position number. |
A list of length n with contents based on the input type.
Applies smoothing and sparsity constraints to a matrix or vector as used in SIMLR or manifold learning, followed by optional L1 feature normalization depending on the energy type.
simlr_sparseness( v, constraint_type = c("none", "ortho", "nsaflow"), smoothing_matrix = NULL, positivity = "positive", sparseness_quantile = 0.8, constraint_weight = NA, constraint_iterations = 1, sparseness_alg = "soft", energy_type = "acc" )simlr_sparseness( v, constraint_type = c("none", "ortho", "nsaflow"), smoothing_matrix = NULL, positivity = "positive", sparseness_quantile = 0.8, constraint_weight = NA, constraint_iterations = 1, sparseness_alg = "soft", energy_type = "acc" )
v |
A numeric matrix or vector to be transformed. |
constraint_type |
Character. Type of manifold constraint; one of '"nsaflow"' or '"None"'. |
smoothing_matrix |
Optional numeric matrix. If provided, |
positivity |
Character positive, negative or either. |
sparseness_quantile |
Numeric between 0 and 1. Fraction of elements to sparsify using quantile thresholding. |
constraint_weight |
Numeric. Weight for the constraint, used in orthogonalization. |
constraint_iterations |
Numeric. Number of iterations for the orthogonalization optimization. |
sparseness_alg |
Character. Sparsity algorithm to use (relevant for Stiefel and Grassmann). . ensemble or nnorth are test options. |
energy_type |
Character. If set to one of '"acc"', '"cca"', '"nc"', '"normalized_correlation"', '"lowRankRegression"', or '"lrr"',
then the returned matrix is normalized using |
A numeric matrix of the same dimensions as v, with applied smoothing, sparsity, and optional normalization.
This function creates and optionally subsets all possible combinations of input parameters for use in a SIMLR grid search.
simlr.parameters( nsimlr_options, prescaling_options, objectiver_options, mixer_options, sparval_options, expBeta_options, positivities_options, optimus_options, constraint_options = list("none"), sparsenessAlg = list("soft"), num_samples = 10, search_type = c("random", "deterministic", "full") )simlr.parameters( nsimlr_options, prescaling_options, objectiver_options, mixer_options, sparval_options, expBeta_options, positivities_options, optimus_options, constraint_options = list("none"), sparsenessAlg = list("soft"), num_samples = 10, search_type = c("random", "deterministic", "full") )
nsimlr_options |
A list of options for the 'nsimlr' parameter. |
prescaling_options |
A list of options for the 'prescaling' parameter. |
objectiver_options |
A list of options for the 'objectiver' parameter. |
mixer_options |
A list of options for the 'mixer' parameter. |
sparval_options |
A list of options for the 'sparval' parameter. |
expBeta_options |
A list of options for the 'ebber' parameter. |
positivities_options |
A list of options for the 'pizzer' parameter. |
optimus_options |
A list of options for the 'optimus' parameter. |
constraint_options |
A list of options for the 'constraint' parameter, default is 'list("none")'. |
sparsenessAlg |
A list of options for the 'sparsenessAlg' parameter, default is 'list(NA)'. |
num_samples |
if not full, then the size of the subset space |
search_type |
string vector either full random or deterministic |
A list containing all (or a subset of) combinations of the provided parameters. Each row in the data frame represents a unique combination of the parameters.
The columns of the returned data frame include:
nsimlr: Values corresponding to the 'nsimlr' parameter.
prescaling: Values corresponding to the 'prescaling' parameter.
objectiver: Values corresponding to the 'objectiver' parameter.
mixer: Values corresponding to the 'mixer' parameter.
constraint: Values corresponding to the 'constraint' parameter.
sparval: Values corresponding to the 'sparval' parameter.
ebber: Values corresponding to the 'ebber' parameter.
pizzer: Values corresponding to the 'pizzer' parameter.
optimus: Values corresponding to the 'optimus' parameter.
Each row represents a specific set of parameters that can be passed to the 'simlr.search' function for evaluation. The returned data frame is intended for use in parameter tuning and optimization.
This function performs permutation tests to assess the significance of a SiMLR analysis. For more detail on input parameters, see the original function.
simlr.perm( data_matrices, smoothingMatrices = NULL, iterations = 10, sparsenessQuantiles = NULL, positivities = NULL, initialUMatrix = NULL, mixAlg = c("svd", "ica", "avg", "rrpca-l", "rrpca-s", "pca", "stochastic"), orthogonalizeU = FALSE, repeatedMeasures = NA, lineSearchRange = c(-500, 500), lineSearchTolerance = 1e-12, randomSeed = 0, constraint = c("nsaflowx0.5x10", "orthox0.001x1", "Grassmannx0", "Stiefelx0", "none"), energyType = c("cca", "regression", "normalized", "acc", "dat", "lowRank", "lowRankRegression", "normalized_correlation", "logcosh", "exp", "kurtosis", "gauss"), vmats = NULL, connectors = NULL, optimizationStyle = "adam", scale = c("centerAndScale", "eigenvalue"), expBeta = 0, jointInitialization = TRUE, sparsenessAlg = NA, verbose = FALSE, nperms = 50, FUN = adjusted_rvcoef, cores = 1 )simlr.perm( data_matrices, smoothingMatrices = NULL, iterations = 10, sparsenessQuantiles = NULL, positivities = NULL, initialUMatrix = NULL, mixAlg = c("svd", "ica", "avg", "rrpca-l", "rrpca-s", "pca", "stochastic"), orthogonalizeU = FALSE, repeatedMeasures = NA, lineSearchRange = c(-500, 500), lineSearchTolerance = 1e-12, randomSeed = 0, constraint = c("nsaflowx0.5x10", "orthox0.001x1", "Grassmannx0", "Stiefelx0", "none"), energyType = c("cca", "regression", "normalized", "acc", "dat", "lowRank", "lowRankRegression", "normalized_correlation", "logcosh", "exp", "kurtosis", "gauss"), vmats = NULL, connectors = NULL, optimizationStyle = "adam", scale = c("centerAndScale", "eigenvalue"), expBeta = 0, jointInitialization = TRUE, sparsenessAlg = NA, verbose = FALSE, nperms = 50, FUN = adjusted_rvcoef, cores = 1 )
data_matrices |
A list of voxel matrices. |
smoothingMatrices |
A list of smoothing matrices. |
iterations |
Number of iterations. Default is 10. |
sparsenessQuantiles |
A vector of sparseness quantiles. |
positivities |
A vector of positivity constraints. |
initialUMatrix |
Initial U matrix for the algorithm. |
mixAlg |
The mixing algorithm to use. Default is 'svd'. |
orthogonalizeU |
Logical indicating whether to orthogonalize U. Default is FALSE. |
repeatedMeasures |
Repeated measures data. Default is NA. |
lineSearchRange |
Range for line search. Default is c(-1e+10, 1e+10). |
lineSearchTolerance |
Tolerance for line search. Default is 1e-08. |
randomSeed |
Seed for random number generation. |
constraint |
The constraint type. Default is 'none'. |
energyType |
The energy type. Default is 'cca'. |
vmats |
List of V matrices - optional initialization matrices |
connectors |
List of connectors. Default is NULL. |
optimizationStyle |
The simlr optimizer. |
scale |
Scaling method. Default is 'centerAndScale'. |
expBeta |
Exponential beta value. Default is 0.9. |
jointInitialization |
Logical indicating joint initialization. Default is TRUE. |
sparsenessAlg |
Sparseness algorithm. Default is NA. |
verbose |
Logical indicating whether to print verbose output. Default is FALSE. values > 1 lead to more verbosity |
nperms |
Number of permutations for significance testing. Default is 50. |
FUN |
function for summarizing variance explained |
cores |
number of cores to use |
A data frame containing p-values for each permutation.
This version runs parameter sets in parallel using all available CPU cores (minus one by default), and shows a progress bar with ETA.
simlr.search( mats, regs, options_df, maxits = 100, connectors = NULL, nperms = 1, verbose = 0, FUN = rvcoef, cores = 1 )simlr.search( mats, regs, options_df, maxits = 100, connectors = NULL, nperms = 1, verbose = 0, FUN = rvcoef, cores = 1 )
mats |
List of input matrices for SIMLR. |
regs |
List of regularization parameters for SIMLR. |
options_df |
Data frame of parameter combinations. |
maxits |
Maximum iterations for SIMLR. |
connectors |
List of connectors for modalities. |
nperms |
Number of permutations for significance test. |
verbose |
Verbosity level. |
FUN |
Evaluation function. |
cores |
Number of CPU cores to use (default: detectCores() - 1). |
List with best SIMLR result, significance, best parameters, and search table.
simlr minimizes reconstruction error across related modalities. One crucial component of the reconstruction is the low-dimensional cross-modality basis. This function computes that basis, given a mixing algorithm.
simlrU( projections, mixingAlgorithm, initialW, orthogonalize = FALSE, connectors = NULL, expBeta = 0 )simlrU( projections, mixingAlgorithm, initialW, orthogonalize = FALSE, connectors = NULL, expBeta = 0 )
projections |
A list that contains the low-dimensional projections. |
mixingAlgorithm |
the elected mixing algorithm. see |
initialW |
initialization matrix size |
orthogonalize |
boolean |
connectors |
a list ( length of projections or number of modalities ) that indicates which modalities should be paired with current modality |
expBeta |
exponential moving average beta |
u matrix for modality i
BB Avants.
set.seed(1500) nsub <- 25 npix <- c(100, 200, 133) nk <- 5 outcome <- matrix(rnorm(nsub * nk), ncol = nk) outcome1 <- matrix(rnorm(nsub * nk), ncol = nk) outcome2 <- matrix(rnorm(nsub * nk), ncol = nk) u <- simlrU(list(outcome, outcome1, outcome2), 2, "avg")set.seed(1500) nsub <- 25 npix <- c(100, 200, 133) nk <- 5 outcome <- matrix(rnorm(nsub * nk), ncol = nk) outcome1 <- matrix(rnorm(nsub * nk), ncol = nk) outcome2 <- matrix(rnorm(nsub * nk), ncol = nk) u <- simlrU(list(outcome, outcome1, outcome2), 2, "avg")
Low frequency, spatial varying simulated random bias field using random points and B-spline fitting.
simulateBiasField( domainImage, numberOfPoints = 10, sdBiasField = 1, numberOfFittingLevels = 4, meshSize = 1 )simulateBiasField( domainImage, numberOfPoints = 10, sdBiasField = 1, numberOfFittingLevels = 4, meshSize = 1 )
domainImage |
image to define the spatial domain of the bias field. |
numberOfPoints |
number of randomly defined points to define the bias field (default = 10). |
sdBiasField |
characterize the standard deviation of the amplitude (default = 1). |
numberOfFittingLevels |
B-spline fitting parameter. |
meshSize |
B-spline fitting parameter (scalar or vector of size image dimension). |
simulated bias field
Tustison NJ
library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) logField <- simulateBiasField(image, numberOfPoints = 10, sdBiasField = 1.0, numberOfFittingLevels = 2, meshSize = 10 ) %>% iMath( "Normalize" ) logField <- ( exp( logField ) )^4 image <- image * logField rm(image); gc() rm(logField); gc()library( ANTsR ) image <- antsImageRead( getANTsRData( "r16" ) ) logField <- simulateBiasField(image, numberOfPoints = 10, sdBiasField = 1.0, numberOfFittingLevels = 2, meshSize = 10 ) %>% iMath( "Normalize" ) logField <- ( exp( logField ) )^4 image <- image * logField rm(image); gc() rm(logField); gc()
Simulate a displacement field using random points with B-spline smoothing
simulateDisplacementField( domainImage, fieldType = c("bspline", "exponential"), numberOfRandomPoints = 1000, sdNoise = 10, enforceStationaryBoundary = TRUE, numberOfFittingLevels = 4, meshSize = 1, sdSmoothing = 4 )simulateDisplacementField( domainImage, fieldType = c("bspline", "exponential"), numberOfRandomPoints = 1000, sdNoise = 10, enforceStationaryBoundary = TRUE, numberOfFittingLevels = 4, meshSize = 1, sdSmoothing = 4 )
domainImage |
image to define the domain of the field. |
fieldType |
either "bspline" or "exponential". |
numberOfRandomPoints |
number of displacement points. Default = 1000. |
sdNoise |
standard deviation of the displacement field noise (in mm). Default = 10.0. |
enforceStationaryBoundary |
boolean determining fixed boundary conditions. Default = TRUE. |
numberOfFittingLevels |
(bspline only) number of fitting levels. Default = 4. |
meshSize |
(bspline only) scalar or n-D vector determining fitting resolution. Default = 1. |
sdSmoothing |
(exponential only) standard deviation of the Gaussian smoothing in mm. Default = 4.0. |
ANTsR displacement field.
NJ Tustison
domainImage <- antsImageRead(getANTsRData("r16"), 2) expField <- simulateDisplacementField(domainImage, fieldType = "exponential") bsplineField <- simulateDisplacementField(domainImage, fieldType = "bspline") warp <- antsrTransformFromDisplacementField(bsplineField * 3) wimg <- applyAntsrTransformToImage(warp, domainImage, domainImage)domainImage <- antsImageRead(getANTsRData("r16"), 2) expField <- simulateDisplacementField(domainImage, fieldType = "exponential") bsplineField <- simulateDisplacementField(domainImage, fieldType = "bspline") warp <- antsrTransformFromDisplacementField(bsplineField * 3) wimg <- applyAntsrTransformToImage(warp, domainImage, domainImage)
Employ a topologically constrained label propagation tool in order to thin an existing segmentation into a skeleton. The function will perform better if the initial segmentation is well-composed.
skeletonize(x, laplacianThreshold = 0.25, propagationOption = 1)skeletonize(x, laplacianThreshold = 0.25, propagationOption = 1)
x |
input binary image |
laplacianThreshold |
between zero and one, controls the speed image |
propagationOption |
either 0 (none), 1 (well-composed) or 2 (topological) constraint |
output binary image
Avants BB
img <- antsImageRead(getANTsRData("r16")) %>% thresholdImage("Otsu", 3) skel <- skeletonize(thresholdImage(img, 3, 3))img <- antsImageRead(getANTsRData("r16")) %>% thresholdImage("Otsu", 3) skel <- skeletonize(thresholdImage(img, 3, 3))
This implements a sparse and graph-regularized version of CCA based on the AppGrad style of implementation by Ma, Lu and Foster, 2015.
smoothAppGradCCA( x, y, smoox = NA, smooy = NA, sparsenessQuantile = 0.5, positivity = "either", k = 2, iterations = 10, stochastic = NA, initialization = "randxy", verbose = FALSE )smoothAppGradCCA( x, y, smoox = NA, smooy = NA, sparsenessQuantile = 0.5, positivity = "either", k = 2, iterations = 10, stochastic = NA, initialization = "randxy", verbose = FALSE )
x |
input view 1 matrix |
y |
input view 2 matrix |
smoox |
smoothingMatrix for x |
smooy |
smoothingMatrix for y |
sparsenessQuantile |
quantile to control sparseness - higher is sparser |
positivity |
restrict to positive or negative solution (beta) weights. choices are positive, negative or either as expressed as a string. |
k |
number of basis vectors to compute |
iterations |
number of gradient descent iterations |
stochastic |
size of subset to use for stocastic gradient descent |
initialization |
type of initialization, currently only supports a
character |
verbose |
boolean option |
list with matrices each of size p or q by k
Avants BB
mat <- replicate(100, rnorm(20)) mat2 <- replicate(100, rnorm(20)) mat <- scale(mat) mat2 <- scale(mat2) wt <- 0.666 mat3 <- mat * wt + mat2 * (1 - wt) jj <- smoothAppGradCCA(mat, mat3)mat <- replicate(100, rnorm(20)) mat2 <- replicate(100, rnorm(20)) mat <- scale(mat) mat2 <- scale(mat2) wt <- 0.666 mat3 <- mat * wt + mat2 * (1 - wt) jj <- smoothAppGradCCA(mat, mat3)
Smooth image or multi-channel image
smoothImage( inimg, sigma, sigmaInPhysicalCoordinates = TRUE, FWHM = FALSE, max_kernel_width = 70 )smoothImage( inimg, sigma, sigmaInPhysicalCoordinates = TRUE, FWHM = FALSE, max_kernel_width = 70 )
inimg |
Image to smooth |
sigma |
Smoothing factor. Can be scalar, in which case the same sigma
is applied to each dimension, or a vector of length |
sigmaInPhysicalCoordinates |
If true, the smoothing factor is in millimeters; if false, it is in pixels. |
FWHM |
If true, sigma is interpreted as the full-width-half-max (FWHM) of the filter, not the sigma of a Gaussian kernel. |
max_kernel_width |
Maximum kernel width |
antsImage smoothed image
Kandel BM, Avants BB
set.seed(1234) img <- makeImage(c(5, 5), rnorm(25)) simg <- smoothImage(img, c(1.2, 1.5)) testthat::expect_equal(sum(simg), -5.59352651424706) testthat::expect_error(smoothImage(img, c(1.2, 1.5, 3))) simg2 <- smoothImage(img, c(1.2, 1.5), FWHM = TRUE) multi <- antsImageRead(getANTsRData("multi_component_image")) smulti <- smoothImage(multi, c(1.2, 1.5)) means <- sapply(splitChannels(smulti), mean) testthat::expect_equal(means, c(86.0794883092244, 81.913664855957, 85.519760093689))set.seed(1234) img <- makeImage(c(5, 5), rnorm(25)) simg <- smoothImage(img, c(1.2, 1.5)) testthat::expect_equal(sum(simg), -5.59352651424706) testthat::expect_error(smoothImage(img, c(1.2, 1.5, 3))) simg2 <- smoothImage(img, c(1.2, 1.5), FWHM = TRUE) multi <- antsImageRead(getANTsRData("multi_component_image")) smulti <- smoothImage(multi, c(1.2, 1.5)) means <- sapply(splitChannels(smulti), mean) testthat::expect_equal(means, c(86.0794883092244, 81.913664855957, 85.519760093689))
Reconstruct a n by p matrix given n by k basis functions or predictors. The reconstruction can be regularized. # norm( x - uv^t ) # d/dv ... leads to ( -u, x - uv^t ) # u^t u v^t - u^t x
smoothMatrixPrediction( x, basisDf, modelFormula = as.formula(" x ~ ."), iterations = 10, gamma = 1e-06, sparsenessQuantile = 0.5, positivity = c("positive", "negative", "either"), smoothingMatrix = NA, repeatedMeasures = NA, rowWeights = NA, LRR = NA, doOrth = FALSE, verbose = FALSE )smoothMatrixPrediction( x, basisDf, modelFormula = as.formula(" x ~ ."), iterations = 10, gamma = 1e-06, sparsenessQuantile = 0.5, positivity = c("positive", "negative", "either"), smoothingMatrix = NA, repeatedMeasures = NA, rowWeights = NA, LRR = NA, doOrth = FALSE, verbose = FALSE )
x |
input matrix to be predicted. |
basisDf |
data frame for basis predictors |
modelFormula |
a formula object which has, on the left, the variable x and the prediction formula on the right. |
iterations |
number of gradient descent iterations |
gamma |
step size for gradient descent |
sparsenessQuantile |
quantile to control sparseness - higher is sparser. |
positivity |
restrict to positive or negative solution (beta) weights. choices are positive, negative or either as expressed as a string. |
smoothingMatrix |
allows parameter smoothing, should be square and same size as input matrix |
repeatedMeasures |
list of repeated measurement identifiers. this will allow estimates of per identifier intercept. |
rowWeights |
vectors of weights with size n (assumes diagonal covariance) |
LRR |
integer value sets rank for fast version exploiting matrix approximation |
doOrth |
boolean enforce gram-schmidt orthonormality |
verbose |
boolean option |
matrix of size p by k is output
Avants BB
## Not run: mask <- getMask(antsImageRead(getANTsRData("r16"))) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 5, sigma = 1.0) mat <- matrix(rnorm(sum(mask) * 50), ncol = sum(mask), nrow = 50) mat[1:25, 100:10000] <- mat[1:25, 100:10000] + 1 age <- rnorm(1:nrow(mat)) for (i in c(5000:6000, 10000:11000, 16000:17000)) { mat[, i] <- age * 0.1 + mat[, i] } gen <- c(rep("M", 25), rep("F", 12), rep("T", 13)) repmeas <- rep(c("A", "B", "C", "D", "E", "F", "G"), nrow(mat))[1:nrow(mat)] mydf <- data.frame(age = scale(age), gen = gen) fit <- smoothMatrixPrediction( x = mat, basisDf = mydf, iterations = 10, gamma = 1.e-6, sparsenessQuantile = 0.5, smoothingMatrix = smoomat, repeatedMeasures = repmeas, verbose = T ) tt <- mat %*% fit$v print(cor.test(mydf$age, tt[, 1])) print(cor.test(fit$u[, "genM"], tt[, 2])) vimg <- makeImage(mask, (fit$v[, 1])) print(range(vimg) * 10) plot(mask, vimg, window.overlay = range(abs(vimg))) vimg <- makeImage(mask, (fit$v[, 2])) print(range(vimg) * 10) plot(mask, vimg, window.overlay = range(abs(vimg))) ## End(Not run)## Not run: mask <- getMask(antsImageRead(getANTsRData("r16"))) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 5, sigma = 1.0) mat <- matrix(rnorm(sum(mask) * 50), ncol = sum(mask), nrow = 50) mat[1:25, 100:10000] <- mat[1:25, 100:10000] + 1 age <- rnorm(1:nrow(mat)) for (i in c(5000:6000, 10000:11000, 16000:17000)) { mat[, i] <- age * 0.1 + mat[, i] } gen <- c(rep("M", 25), rep("F", 12), rep("T", 13)) repmeas <- rep(c("A", "B", "C", "D", "E", "F", "G"), nrow(mat))[1:nrow(mat)] mydf <- data.frame(age = scale(age), gen = gen) fit <- smoothMatrixPrediction( x = mat, basisDf = mydf, iterations = 10, gamma = 1.e-6, sparsenessQuantile = 0.5, smoothingMatrix = smoomat, repeatedMeasures = repmeas, verbose = T ) tt <- mat %*% fit$v print(cor.test(mydf$age, tt[, 1])) print(cor.test(fit$u[, "genM"], tt[, 2])) vimg <- makeImage(mask, (fit$v[, 1])) print(range(vimg) * 10) plot(mask, vimg, window.overlay = range(abs(vimg))) vimg <- makeImage(mask, (fit$v[, 2])) print(range(vimg) * 10) plot(mask, vimg, window.overlay = range(abs(vimg))) ## End(Not run)
Reconstruct a n by k vector given n by p matrix of predictors.
smoothMultiRegression( x, y, iterations = 10, sparsenessQuantile = 0.5, positivity = FALSE, smoothingMatrixX = NA, smoothingMatrixY = NA, nv = 2, extraPredictors, verbose = FALSE )smoothMultiRegression( x, y, iterations = 10, sparsenessQuantile = 0.5, positivity = FALSE, smoothingMatrixX = NA, smoothingMatrixY = NA, nv = 2, extraPredictors, verbose = FALSE )
x |
input matrix on which prediction is based |
y |
target matrix |
iterations |
number of gradient descent iterations |
sparsenessQuantile |
quantile to control sparseness - higher is sparser. |
positivity |
restrict to positive or negative solution (beta) weights. choices are positive, negative or either as expressed as a string. |
smoothingMatrixX |
allows parameter smoothing, should be square and same size as input matrix |
smoothingMatrixY |
allows parameter smoothing, should be square and same size as input matrix |
nv |
number of predictor spatial vectors |
extraPredictors |
additional column predictors |
verbose |
boolean option |
vector of size p is output
Avants BB
## Not run: mask <- getMask(antsImageRead(getANTsRData("r16"))) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 200, sigma = 1.0) mat <- matrix(rnorm(sum(mask) * 50), ncol = sum(mask), nrow = 50) mat[1:25, 100:10000] <- mat[1:25, 100:10000] + 1 age <- matrix(rnorm(nrow(mat) * 2), ncol = 2) for (i in c(5000:6000, 10000:11000, 16000:17000)) { mat[, i] <- age[, 1] * 0.1 + mat[, i] } sel <- 1:25 fit <- smoothMultiRegression( x = mat[sel, ], y = age[sel, ], iterations = 10, sparsenessQuantile = 0.5, smoothingMatrixX = smoomat, smoothingMatrixY = NA, verbose = T ) tt <- mat %*% fit$v print(cor.test(age[-sel, 1], tt[-sel, 1])) vimg <- makeImage(mask, (fit$v[, 1])) print(range(vimg) * 10) plot(mask, vimg, window.overlay = range(abs(vimg))) ## End(Not run)## Not run: mask <- getMask(antsImageRead(getANTsRData("r16"))) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 200, sigma = 1.0) mat <- matrix(rnorm(sum(mask) * 50), ncol = sum(mask), nrow = 50) mat[1:25, 100:10000] <- mat[1:25, 100:10000] + 1 age <- matrix(rnorm(nrow(mat) * 2), ncol = 2) for (i in c(5000:6000, 10000:11000, 16000:17000)) { mat[, i] <- age[, 1] * 0.1 + mat[, i] } sel <- 1:25 fit <- smoothMultiRegression( x = mat[sel, ], y = age[sel, ], iterations = 10, sparsenessQuantile = 0.5, smoothingMatrixX = smoomat, smoothingMatrixY = NA, verbose = T ) tt <- mat %*% fit$v print(cor.test(age[-sel, 1], tt[-sel, 1])) vimg <- makeImage(mask, (fit$v[, 1])) print(range(vimg) * 10) plot(mask, vimg, window.overlay = range(abs(vimg))) ## End(Not run)
Reconstruct a n by 1 vector given n by p matrix of predictors.
smoothRegression( x, y, iterations = 10, sparsenessQuantile = 0.5, positivity = FALSE, smoothingMatrix = NA, nv = 2, extraPredictors, verbose = FALSE )smoothRegression( x, y, iterations = 10, sparsenessQuantile = 0.5, positivity = FALSE, smoothingMatrix = NA, nv = 2, extraPredictors, verbose = FALSE )
x |
input matrix on which prediction is based |
y |
target vector |
iterations |
number of gradient descent iterations |
sparsenessQuantile |
quantile to control sparseness - higher is sparser. |
positivity |
restrict to positive or negative solution (beta) weights. choices are positive, negative or either as expressed as a string. |
smoothingMatrix |
allows parameter smoothing, should be square and same size as input matrix |
nv |
number of predictor spatial vectors |
extraPredictors |
additional column predictors |
verbose |
boolean option |
vector of size p is output
Avants BB
## Not run: mask <- getMask(antsImageRead(getANTsRData("r16"))) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 200, sigma = 1.0) mat <- matrix(rnorm(sum(mask) * 50), ncol = sum(mask), nrow = 50) mat[1:25, 100:10000] <- mat[1:25, 100:10000] + 1 age <- rnorm(1:nrow(mat)) for (i in c(5000:6000, 10000:11000, 16000:17000)) { mat[, i] <- age * 0.1 + mat[, i] } sel <- 1:25 fit <- smoothRegression( x = mat[sel, ], y = age[sel], iterations = 10, sparsenessQuantile = 0.5, smoothingMatrix = smoomat, verbose = T ) tt <- mat %*% fit$v print(cor.test(age[-sel], tt[-sel, 1])) vimg <- makeImage(mask, (fit$v[, 1])) print(range(vimg) * 10) plot(mask, vimg, window.overlay = range(abs(vimg))) ## End(Not run)## Not run: mask <- getMask(antsImageRead(getANTsRData("r16"))) spatmat <- t(imageDomainToSpatialMatrix(mask, mask)) smoomat <- knnSmoothingMatrix(spatmat, k = 200, sigma = 1.0) mat <- matrix(rnorm(sum(mask) * 50), ncol = sum(mask), nrow = 50) mat[1:25, 100:10000] <- mat[1:25, 100:10000] + 1 age <- rnorm(1:nrow(mat)) for (i in c(5000:6000, 10000:11000, 16000:17000)) { mat[, i] <- age * 0.1 + mat[, i] } sel <- 1:25 fit <- smoothRegression( x = mat[sel, ], y = age[sel], iterations = 10, sparsenessQuantile = 0.5, smoothingMatrix = smoomat, verbose = T ) tt <- mat %*% fit$v print(cor.test(age[-sel], tt[-sel, 1])) vimg <- makeImage(mask, (fit$v[, 1])) print(range(vimg) * 10) plot(mask, vimg, window.overlay = range(abs(vimg))) ## End(Not run)
Decomposes a matrix into sparse eigenevectors to maximize explained variance. Note: we do not scale the matrices internally. We leave scaling choices to the user.
sparseDecom( inmatrix = NA, inmask = NULL, sparseness = 0.1, nvecs = 10, its = 5, cthresh = 50, statdir = NA, z = 0, smooth = 0, initializationList = list(), mycoption = 0, robust = 0, ell1 = 1, getSmall = 0, verbose = FALSE, powerit = 0, priorWeight = 0, maxBased = FALSE )sparseDecom( inmatrix = NA, inmask = NULL, sparseness = 0.1, nvecs = 10, its = 5, cthresh = 50, statdir = NA, z = 0, smooth = 0, initializationList = list(), mycoption = 0, robust = 0, ell1 = 1, getSmall = 0, verbose = FALSE, powerit = 0, priorWeight = 0, maxBased = FALSE )
inmatrix |
n by p input images , subjects or time points by row , spatial variable lies along columns |
inmask |
optional antsImage mask |
sparseness |
lower values equal more sparse |
nvecs |
number of vectors |
its |
number of iterations |
cthresh |
cluster threshold |
statdir |
place on disk to save results |
z |
u penalty, experimental |
smooth |
smoothness eg 0.5 |
initializationList |
see initializeEigenanatomy |
mycoption |
0, 1 or 2 all produce different output 0 is combination of 1 (spatial orthogonality) and 2 (subject space orthogonality) |
robust |
rank transform input data - good for data checking |
ell1 |
the ell1 grad descent param |
getSmall |
try to get smallest evecs (bool) |
verbose |
activates verbose output |
powerit |
alternative power iteration implementation, faster |
priorWeight |
scalar weight typically in range zero to two |
maxBased |
boolean that chooses max-based thresholding |
outputs a decomposition of a population or time series matrix
Avants BB
mat <- replicate(100, rnorm(20)) mydecom <- sparseDecom(mat) mat <- scale(mat) mydecom2 <- sparseDecom(mat) # params that lead to algorithm similar to NMF mydecom3 <- sparseDecom(mat, z = 1, sparseness = 1) ## Not run: # for prediction if (usePkg("randomForest") & usePkg("spls") & usePkg("BGLR")) { data(lymphoma) # from spls training <- sample(rep(c(TRUE, FALSE), 31)) sp <- 0.02 myz <- 0 ldd <- sparseDecom(lymphoma$x[training, ], nvecs = 5, sparseness = (sp), mycoption = 1, z = myz ) # NMF style traindf <- data.frame( lclass = as.factor(lymphoma$y[training]), eig = lymphoma$x[training, ] %*% as.matrix(ldd$eigenanatomyimages) ) testdf <- data.frame( lclass = as.factor(lymphoma$y[!training]), eig = lymphoma$x[!training, ] %*% as.matrix(ldd$eigenanatomyimages) ) myrf <- randomForest(lclass ~ ., data = traindf) predlymp <- predict(myrf, newdata = testdf) print(paste( "N-errors:", sum(abs(testdf$lclass != predlymp)), " non-zero ", sum(abs(ldd$eigenanatomyimages) > 0) )) # compare to http://arxiv.org/pdf/0707.0701v2.pdf # now SNPs data(mice) snps <- quantifySNPs(mice.X, shiftit = TRUE) numericalpheno <- as.matrix(mice.pheno[, c(4, 5, 13, 15)]) nfolds <- 6 train <- sample(rep(c(1:nfolds), 1800 / nfolds)) train <- (train < 4) lrmat <- lowrankRowMatrix(as.matrix(snps[train, ]), 50) lrmat <- scale(lrmat) snpd <- sparseDecom(lrmat - min(lrmat), nvecs = 20, sparseness = (0.001), z = -1) projmat <- as.matrix(snpd$eig) snpse <- as.matrix(snps[train, ]) %*% projmat traindf <- data.frame(bmi = numericalpheno[train, 3], snpse = snpse) snpse <- as.matrix(snps[!train, ]) %*% projmat testdf <- data.frame(bmi = numericalpheno[!train, 3], snpse = snpse) myrf <- randomForest(bmi ~ ., data = traindf) preddf <- predict(myrf, newdata = testdf) cor.test(preddf, testdf$bmi) plot(preddf, testdf$bmi) } # check for packages # prior-based example set.seed(123) ref <- antsImageRead(getANTsRData("r16")) ref <- iMath(ref, "Normalize") mi <- antsImageRead(getANTsRData("r27")) mi2 <- antsImageRead(getANTsRData("r30")) mi3 <- antsImageRead(getANTsRData("r62")) mi4 <- antsImageRead(getANTsRData("r64")) mi5 <- antsImageRead(getANTsRData("r85")) refmask <- getMask(ref) refmask <- iMath(refmask, "ME", 2) # just to speed things up ilist <- list(mi, mi2, mi3, mi4, mi5) for (i in 1:length(ilist)) { ilist[[i]] <- iMath(ilist[[i]], "Normalize") mytx <- antsRegistration( fixed = ref, moving = ilist[[i]], typeofTransform = c("Affine") ) mywarpedimage <- antsApplyTransforms( fixed = ref, moving = ilist[[i]], transformlist = mytx$fwdtransforms ) ilist[[i]] <- mywarpedimage } mat <- imageListToMatrix(ilist, refmask) kmseg <- kmeansSegmentation(ref, 3, refmask) initlist <- list() for (k in 1:3) { initlist[[k]] <- thresholdImage(kmseg$probabilityimages[[k]], 0.1, Inf) * kmseg$probabilityimages[[k]] } eanat <- sparseDecom(mat, inmask = refmask, ell1 = 0.1, sparseness = 0.0, smooth = 0.5, verbose = 1, initializationList = initlist, cthresh = 25, nvecs = 3, priorWeight = 0.5 ) ee <- matrixToImages(eanat$eigenanatomyimages, refmask) eseg <- eigSeg(refmask, ee) priormat <- imageListToMatrix(initlist, refmask) cor(t(eanat$eigenanatomyimages), t(priormat)) plot(ref, eseg) ## End(Not run)mat <- replicate(100, rnorm(20)) mydecom <- sparseDecom(mat) mat <- scale(mat) mydecom2 <- sparseDecom(mat) # params that lead to algorithm similar to NMF mydecom3 <- sparseDecom(mat, z = 1, sparseness = 1) ## Not run: # for prediction if (usePkg("randomForest") & usePkg("spls") & usePkg("BGLR")) { data(lymphoma) # from spls training <- sample(rep(c(TRUE, FALSE), 31)) sp <- 0.02 myz <- 0 ldd <- sparseDecom(lymphoma$x[training, ], nvecs = 5, sparseness = (sp), mycoption = 1, z = myz ) # NMF style traindf <- data.frame( lclass = as.factor(lymphoma$y[training]), eig = lymphoma$x[training, ] %*% as.matrix(ldd$eigenanatomyimages) ) testdf <- data.frame( lclass = as.factor(lymphoma$y[!training]), eig = lymphoma$x[!training, ] %*% as.matrix(ldd$eigenanatomyimages) ) myrf <- randomForest(lclass ~ ., data = traindf) predlymp <- predict(myrf, newdata = testdf) print(paste( "N-errors:", sum(abs(testdf$lclass != predlymp)), " non-zero ", sum(abs(ldd$eigenanatomyimages) > 0) )) # compare to http://arxiv.org/pdf/0707.0701v2.pdf # now SNPs data(mice) snps <- quantifySNPs(mice.X, shiftit = TRUE) numericalpheno <- as.matrix(mice.pheno[, c(4, 5, 13, 15)]) nfolds <- 6 train <- sample(rep(c(1:nfolds), 1800 / nfolds)) train <- (train < 4) lrmat <- lowrankRowMatrix(as.matrix(snps[train, ]), 50) lrmat <- scale(lrmat) snpd <- sparseDecom(lrmat - min(lrmat), nvecs = 20, sparseness = (0.001), z = -1) projmat <- as.matrix(snpd$eig) snpse <- as.matrix(snps[train, ]) %*% projmat traindf <- data.frame(bmi = numericalpheno[train, 3], snpse = snpse) snpse <- as.matrix(snps[!train, ]) %*% projmat testdf <- data.frame(bmi = numericalpheno[!train, 3], snpse = snpse) myrf <- randomForest(bmi ~ ., data = traindf) preddf <- predict(myrf, newdata = testdf) cor.test(preddf, testdf$bmi) plot(preddf, testdf$bmi) } # check for packages # prior-based example set.seed(123) ref <- antsImageRead(getANTsRData("r16")) ref <- iMath(ref, "Normalize") mi <- antsImageRead(getANTsRData("r27")) mi2 <- antsImageRead(getANTsRData("r30")) mi3 <- antsImageRead(getANTsRData("r62")) mi4 <- antsImageRead(getANTsRData("r64")) mi5 <- antsImageRead(getANTsRData("r85")) refmask <- getMask(ref) refmask <- iMath(refmask, "ME", 2) # just to speed things up ilist <- list(mi, mi2, mi3, mi4, mi5) for (i in 1:length(ilist)) { ilist[[i]] <- iMath(ilist[[i]], "Normalize") mytx <- antsRegistration( fixed = ref, moving = ilist[[i]], typeofTransform = c("Affine") ) mywarpedimage <- antsApplyTransforms( fixed = ref, moving = ilist[[i]], transformlist = mytx$fwdtransforms ) ilist[[i]] <- mywarpedimage } mat <- imageListToMatrix(ilist, refmask) kmseg <- kmeansSegmentation(ref, 3, refmask) initlist <- list() for (k in 1:3) { initlist[[k]] <- thresholdImage(kmseg$probabilityimages[[k]], 0.1, Inf) * kmseg$probabilityimages[[k]] } eanat <- sparseDecom(mat, inmask = refmask, ell1 = 0.1, sparseness = 0.0, smooth = 0.5, verbose = 1, initializationList = initlist, cthresh = 25, nvecs = 3, priorWeight = 0.5 ) ee <- matrixToImages(eanat$eigenanatomyimages, refmask) eseg <- eigSeg(refmask, ee) priormat <- imageListToMatrix(initlist, refmask) cor(t(eanat$eigenanatomyimages), t(priormat)) plot(ref, eseg) ## End(Not run)
Decomposes two matrices into paired sparse eigenevectors to maximize canonical correlation. Note: we do not scale the matrices internally. We leave scaling choices to the user.
sparseDecom2( inmatrix, inmask = list(NULL, NULL), sparseness = c(0.01, 0.01), nvecs = 3, its = 20, cthresh = c(0, 0), statdir = NA, perms = 0, uselong = 0, z = 0, smooth = 0, robust = 0, mycoption = 0, initializationList = list(), initializationList2 = list(), ell1 = 10, priorWeight = 0, verbose = FALSE, rejector = 0, maxBased = FALSE )sparseDecom2( inmatrix, inmask = list(NULL, NULL), sparseness = c(0.01, 0.01), nvecs = 3, its = 20, cthresh = c(0, 0), statdir = NA, perms = 0, uselong = 0, z = 0, smooth = 0, robust = 0, mycoption = 0, initializationList = list(), initializationList2 = list(), ell1 = 10, priorWeight = 0, verbose = FALSE, rejector = 0, maxBased = FALSE )
inmatrix |
input as inmatrix=list(mat1,mat2). n by p input matrix and n by q input matrix , spatial variable lies along columns. |
inmask |
optional pair of antsImage masks |
sparseness |
a c(.,.) pair of values e.g c(0.01,0.1) enforces an unsigned 99 percent and 90 percent sparse solution for each respective view |
nvecs |
number of eigenvector pairs |
its |
number of iterations, 10 or 20 usually sufficient |
cthresh |
cluster threshold pair |
statdir |
temporary directory if you want to look at full output |
perms |
number of permutations. settings permutations greater than 0 will estimate significance per vector empirically. For small datasets, these may be conservative. p-values depend on how one scales the input matrices. |
uselong |
enforce solutions of both views to be the same - requires matrices to be the same size |
z |
subject space (low-dimensional space) sparseness value |
smooth |
smooth the data (only available when mask is used) |
robust |
rank transform input matrices |
mycoption |
enforce 1 - spatial orthogonality, 2 - low-dimensional orthogonality or 0 - both |
initializationList |
initialization for first view |
initializationList2 |
initialization for 2nd view |
ell1 |
gradient descent parameter, if negative then l0 otherwise use l1 |
priorWeight |
Scalar value weight on prior between 0 (prior is weak) and 1 (prior is strong). Only engaged if initialization is used |
verbose |
activates verbose output to screen |
rejector |
rejects small correlation solutions |
maxBased |
boolean that chooses max-based thresholding |
outputs a decomposition of a pair of matrices
Avants BB
mat <- replicate(100, rnorm(20)) mat2 <- replicate(100, rnorm(20)) mat <- scale(mat) mat2 <- scale(mat2) mydecom <- sparseDecom2( inmatrix = list(mat, mat2), sparseness = c(0.1, 0.3), nvecs = 3, its = 3, perms = 0 ) wt <- 0.666 mat3 <- mat * wt + mat2 * (1 - wt) mydecom <- sparseDecom2( inmatrix = list(mat, mat3), sparseness = c(0.2, 0.2), nvecs = 5, its = 10, perms = 5 ) ## Not run: # a masked example im <- antsImageRead(getANTsRData("r64")) mask <- thresholdImage(im, 250, Inf) dd <- sum(mask == 1) mat1 <- matrix(rnorm(dd * 10), nrow = 10) mat2 <- matrix(rnorm(dd * 10), nrow = 10) initlist <- list() for (nvecs in 1:2) { init1 <- antsImageClone(mask) init1[mask == 1] <- rnorm(dd) initlist <- lappend(initlist, init1) } ff <- sparseDecom2( inmatrix = list(mat1, mat2), inmask = list(mask, mask), sparseness = c(0.1, 0.1), nvecs = length(initlist), smooth = 1, cthresh = c(0, 0), initializationList = initlist, ell1 = 11 ) ### now SNPs ### rf <- usePkg("randomForest") bg <- usePkg("BGLR") if (bg & rf) { data(mice) snps <- mice.X numericalpheno <- as.matrix(mice.pheno[, c(4, 5, 13, 15)]) numericalpheno <- residuals(lm(numericalpheno ~ as.factor(mice.pheno$Litter))) nfolds <- 6 train <- sample(rep(c(1:nfolds), 1800 / nfolds)) train <- (train < 4) snpd <- sparseDecom2( inmatrix = list( (as.matrix(snps[train, ])), numericalpheno[train, ] ), nvecs = 20, sparseness = c(0.001, -0.5), its = 3, ell1 = 0.1, z = -1 ) for (j in 3:3) { traindf <- data.frame( bmi = numericalpheno[train, j], snpse = as.matrix(snps[train, ]) %*% as.matrix(snpd$eig1) ) testdf <- data.frame( bmi = numericalpheno[!train, j], snpse = as.matrix(snps[!train, ]) %*% as.matrix(snpd$eig1) ) myrf <- randomForest(bmi ~ ., data = traindf) preddf <- predict(myrf, newdata = testdf) print(cor.test(preddf, testdf$bmi)) plot(preddf, testdf$bmi) } } # check bg and rf ## End(Not run)mat <- replicate(100, rnorm(20)) mat2 <- replicate(100, rnorm(20)) mat <- scale(mat) mat2 <- scale(mat2) mydecom <- sparseDecom2( inmatrix = list(mat, mat2), sparseness = c(0.1, 0.3), nvecs = 3, its = 3, perms = 0 ) wt <- 0.666 mat3 <- mat * wt + mat2 * (1 - wt) mydecom <- sparseDecom2( inmatrix = list(mat, mat3), sparseness = c(0.2, 0.2), nvecs = 5, its = 10, perms = 5 ) ## Not run: # a masked example im <- antsImageRead(getANTsRData("r64")) mask <- thresholdImage(im, 250, Inf) dd <- sum(mask == 1) mat1 <- matrix(rnorm(dd * 10), nrow = 10) mat2 <- matrix(rnorm(dd * 10), nrow = 10) initlist <- list() for (nvecs in 1:2) { init1 <- antsImageClone(mask) init1[mask == 1] <- rnorm(dd) initlist <- lappend(initlist, init1) } ff <- sparseDecom2( inmatrix = list(mat1, mat2), inmask = list(mask, mask), sparseness = c(0.1, 0.1), nvecs = length(initlist), smooth = 1, cthresh = c(0, 0), initializationList = initlist, ell1 = 11 ) ### now SNPs ### rf <- usePkg("randomForest") bg <- usePkg("BGLR") if (bg & rf) { data(mice) snps <- mice.X numericalpheno <- as.matrix(mice.pheno[, c(4, 5, 13, 15)]) numericalpheno <- residuals(lm(numericalpheno ~ as.factor(mice.pheno$Litter))) nfolds <- 6 train <- sample(rep(c(1:nfolds), 1800 / nfolds)) train <- (train < 4) snpd <- sparseDecom2( inmatrix = list( (as.matrix(snps[train, ])), numericalpheno[train, ] ), nvecs = 20, sparseness = c(0.001, -0.5), its = 3, ell1 = 0.1, z = -1 ) for (j in 3:3) { traindf <- data.frame( bmi = numericalpheno[train, j], snpse = as.matrix(snps[train, ]) %*% as.matrix(snpd$eig1) ) testdf <- data.frame( bmi = numericalpheno[!train, j], snpse = as.matrix(snps[!train, ]) %*% as.matrix(snpd$eig1) ) myrf <- randomForest(bmi ~ ., data = traindf) preddf <- predict(myrf, newdata = testdf) print(cor.test(preddf, testdf$bmi)) plot(preddf, testdf$bmi) } } # check bg and rf ## End(Not run)
Decomposes two matrices into paired sparse eigenevectors to maximize canonical correlation.
sparseDecom2boot( inmatrix, inmask = c(NULL, NULL), sparseness = c(0.01, 0.01), nvecs = 50, its = 5, cthresh = c(0, 0), statdir = NA, perms = 0, uselong = 0, z = 0, smooth = 0, robust = 0, mycoption = 1, initializationList = list(), initializationList2 = list(), ell1 = 0.05, nboot = 10, nsamp = 1, doseg = FALSE, priorWeight = 0, verbose = FALSE, estimateSparseness = 0.2 )sparseDecom2boot( inmatrix, inmask = c(NULL, NULL), sparseness = c(0.01, 0.01), nvecs = 50, its = 5, cthresh = c(0, 0), statdir = NA, perms = 0, uselong = 0, z = 0, smooth = 0, robust = 0, mycoption = 1, initializationList = list(), initializationList2 = list(), ell1 = 0.05, nboot = 10, nsamp = 1, doseg = FALSE, priorWeight = 0, verbose = FALSE, estimateSparseness = 0.2 )
inmatrix |
input as inmatrix=list(mat1,mat2). n by p input matrix and n by q input matrix , spatial variable lies along columns. |
inmask |
optional pair of antsImage masks |
sparseness |
a c(.,.) pair of values e.g c(0.01,0.1) enforces an unsigned 99 percent and 90 percent sparse solution for each respective view |
nvecs |
number of eigenvector pairs |
its |
number of iterations, 10 or 20 usually sufficient |
cthresh |
cluster threshold pair |
statdir |
temporary directory if you want to look at full output |
perms |
number of permutations |
uselong |
enforce solutions of both views to be the same - requires matrices to be the same size |
z |
subject space (low-dimensional space) sparseness value |
smooth |
smooth the data (only available when mask is used) |
robust |
rank transform input matrices |
mycoption |
enforce 1 - spatial orthogonality, 2 - low-dimensional orthogonality or 0 - both |
initializationList |
initialization for first view |
initializationList2 |
initialization for 2nd view |
ell1 |
gradient descent parameter, if negative then l0 otherwise use l1 |
nboot |
n bootstrap runs |
nsamp |
number of samples e.g. 0.9 indicates 90 percent of data |
doseg |
boolean to control matrix orthogonality during bootstrap |
priorWeight |
Scalar value weight on prior between 0 (prior is weak) and 1 (prior is strong). Only engaged if initialization is used |
verbose |
activates verbose output to screen |
estimateSparseness |
effect size to estimate sparseness per vector |
outputs a decomposition of a pair of matrices
Avants BB
## Not run: mat <- replicate(100, rnorm(20)) mat2 <- replicate(100, rnorm(20)) mydecom <- sparseDecom2boot( inmatrix = list(mat, mat2), sparseness = c(0.1, 0.3), nvecs = 3, its = 3, perms = 0 ) wt <- 0.666 mat3 <- mat * wt + mat2 * (1 - wt) mydecom <- sparseDecom2boot( inmatrix = list(mat, mat3), sparseness = c(0.2, 0.2), nvecs = 5, its = 10, perms = 200 ) ## End(Not run)## Not run: mat <- replicate(100, rnorm(20)) mat2 <- replicate(100, rnorm(20)) mydecom <- sparseDecom2boot( inmatrix = list(mat, mat2), sparseness = c(0.1, 0.3), nvecs = 3, its = 3, perms = 0 ) wt <- 0.666 mat3 <- mat * wt + mat2 * (1 - wt) mydecom <- sparseDecom2boot( inmatrix = list(mat, mat3), sparseness = c(0.2, 0.2), nvecs = 5, its = 10, perms = 200 ) ## End(Not run)
Decomposes a matrix into sparse eigenevectors to maximize explained variance.
sparseDecomboot( inmatrix, inmask = NULL, sparseness = 0.01, nvecs = 50, its = 5, cthresh = 250, z = 0, smooth = 0, initializationList = list(), mycoption = 0, nboot = 10, nsamp = 0.9, robust = 0, doseg = TRUE )sparseDecomboot( inmatrix, inmask = NULL, sparseness = 0.01, nvecs = 50, its = 5, cthresh = 250, z = 0, smooth = 0, initializationList = list(), mycoption = 0, nboot = 10, nsamp = 0.9, robust = 0, doseg = TRUE )
inmatrix |
n by p input images , subjects or time points by row , spatial variable lies along columns |
inmask |
optional antsImage mask |
sparseness |
lower values equal more sparse |
nvecs |
number of vectors |
its |
number of iterations |
cthresh |
cluster threshold |
z |
u penalty, experimental |
smooth |
smoothness eg 0.5 |
initializationList |
see initializeEigenanatomy |
mycoption |
0, 1 or 2 all produce different output 0 is combination of 1 (spatial orthogonality) and 2 (subject space orthogonality) |
nboot |
boostrap integer e.g. 10 equals 10 boostraps |
nsamp |
value less than or equal to 1, e.g. 0.9 means 90 percent of data will be used in each boostrap resampling |
robust |
boolean |
doseg |
orthogonalize bootstrap results |
Avants BB
mat <- replicate(100, rnorm(20)) mydecom <- sparseDecomboot(mat, nboot = 5, nsamp = 0.9, nvecs = 2) ## Not run: # for prediction if (usePkg("randomForest") & usePkg("spls")) { data(lymphoma) training <- sample(rep(c(TRUE, FALSE), 31)) sp <- 0.001 myz <- 0 nv <- 5 ldd <- sparseDecomboot(lymphoma$x[training, ], nvecs = nv, sparseness = (sp), mycoption = 1, z = myz, nsamp = 0.9, nboot = 50 ) # NMF style outmat <- as.matrix(ldd$eigenanatomyimages) # outmat<-t(ldd$cca1outAuto) traindf <- data.frame( lclass = as.factor(lymphoma$y[training]), eig = lymphoma$x[training, ] %*% t(outmat) ) testdf <- data.frame( lclass = as.factor(lymphoma$y[!training]), eig = lymphoma$x[!training, ] %*% t(outmat) ) myrf <- randomForest(lclass ~ ., data = traindf) predlymp <- predict(myrf, newdata = testdf) print(paste( "N-errors:", sum(abs(testdf$lclass != predlymp)), "non-zero ", sum(abs(outmat) > 0) )) for (i in 1:nv) { print(paste(" non-zero ", i, " is: ", sum(abs(outmat[i, ]) > 0))) } } # end dontrun ## End(Not run)mat <- replicate(100, rnorm(20)) mydecom <- sparseDecomboot(mat, nboot = 5, nsamp = 0.9, nvecs = 2) ## Not run: # for prediction if (usePkg("randomForest") & usePkg("spls")) { data(lymphoma) training <- sample(rep(c(TRUE, FALSE), 31)) sp <- 0.001 myz <- 0 nv <- 5 ldd <- sparseDecomboot(lymphoma$x[training, ], nvecs = nv, sparseness = (sp), mycoption = 1, z = myz, nsamp = 0.9, nboot = 50 ) # NMF style outmat <- as.matrix(ldd$eigenanatomyimages) # outmat<-t(ldd$cca1outAuto) traindf <- data.frame( lclass = as.factor(lymphoma$y[training]), eig = lymphoma$x[training, ] %*% t(outmat) ) testdf <- data.frame( lclass = as.factor(lymphoma$y[!training]), eig = lymphoma$x[!training, ] %*% t(outmat) ) myrf <- randomForest(lclass ~ ., data = traindf) predlymp <- predict(myrf, newdata = testdf) print(paste( "N-errors:", sum(abs(testdf$lclass != predlymp)), "non-zero ", sum(abs(outmat) > 0) )) for (i in 1:nv) { print(paste(" non-zero ", i, " is: ", sum(abs(outmat[i, ]) > 0))) } } # end dontrun ## End(Not run)
Exploit k-nearest neighbor algorithms to estimate a sparse similarity matrix. Critical to the validity of this function is the basic mathematical relationships between euclidean distance and correlation and between correlation and covariance. For applications of such matrices, one may see relevant publications by Mauro Maggioni and other authors.
sparseDistanceMatrix( x, k = 3, r = Inf, sigma = NA, kmetric = c("euclidean", "correlation", "covariance", "gaussian"), eps = 1e-06, ncores = NA, sinkhorn = FALSE, kPackage = "RcppHNSW", verbose = FALSE )sparseDistanceMatrix( x, k = 3, r = Inf, sigma = NA, kmetric = c("euclidean", "correlation", "covariance", "gaussian"), eps = 1e-06, ncores = NA, sinkhorn = FALSE, kPackage = "RcppHNSW", verbose = FALSE )
x |
input matrix, should be n (samples) by p (measurements) |
k |
number of neighbors |
r |
radius of epsilon-ball |
sigma |
parameter for kernel PCA. |
kmetric |
similarity or distance metric determining k nearest neighbors |
eps |
epsilon error for rapid knn |
ncores |
number of cores to use |
sinkhorn |
boolean |
kPackage |
name of package to use for knn. FNN is reproducbile but RcppHNSW is much faster (with nthreads controlled by enviornment variable ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS) for larger problems. For large problems, compute the regularization once and save to disk; load for repeatability. |
verbose |
verbose output |
matrix sparse p by p matrix is output with p by k nonzero entries
Avants BB
Maggioni, M., et al. "Multiscale data geometry."
## Not run: set.seed(120) mat <- matrix(rnorm(60), ncol = 10) smat <- sparseDistanceMatrix(mat, 2) r16 <- antsImageRead(getANTsRData("r16")) mask <- getMask(r16) mat <- getNeighborhoodInMask( image = r16, mask = mask, radius = c(0, 0), physical.coordinates = TRUE, spatial.info = TRUE ) smat <- sparseDistanceMatrix(t(mat$indices), 10) # close points testthat::expect_is(smat, "Matrix") testthat::expect_is(smat, "dgCMatrix") testthat::expect_equal(sum(smat), 18017) ## End(Not run)## Not run: set.seed(120) mat <- matrix(rnorm(60), ncol = 10) smat <- sparseDistanceMatrix(mat, 2) r16 <- antsImageRead(getANTsRData("r16")) mask <- getMask(r16) mat <- getNeighborhoodInMask( image = r16, mask = mask, radius = c(0, 0), physical.coordinates = TRUE, spatial.info = TRUE ) smat <- sparseDistanceMatrix(t(mat$indices), 10) # close points testthat::expect_is(smat, "Matrix") testthat::expect_is(smat, "dgCMatrix") testthat::expect_equal(sum(smat), 18017) ## End(Not run)
Exploit k-nearest neighbor algorithms to estimate a sparse matrix measuring the distance, correlation or covariance between two matched datasets. Critical to the validity of this function is the basic mathematical relationships between euclidean distance and correlation and between correlation and covariance. For applications of such matrices, one may see relevant publications by Mauro Maggioni and other authors.
sparseDistanceMatrixXY( x, y, k = 3, r = Inf, sigma = NA, kmetric = c("euclidean", "correlation", "covariance", "gaussian"), eps = 1e-06, kPackage = "RcppHNSW", ncores = NA, verbose = FALSE )sparseDistanceMatrixXY( x, y, k = 3, r = Inf, sigma = NA, kmetric = c("euclidean", "correlation", "covariance", "gaussian"), eps = 1e-06, kPackage = "RcppHNSW", ncores = NA, verbose = FALSE )
x |
input matrix, should be n (samples) by p (measurements) |
y |
input matrix second view, should be n (samples) by q (measurements) |
k |
number of neighbors |
r |
radius of epsilon-ball |
sigma |
parameter for kernel PCA. |
kmetric |
similarity or distance metric determining k nearest neighbors |
eps |
epsilon error for rapid knn |
kPackage |
name of package to use for knn. FNN is reproducbile but RcppHNSW is much faster (with nthreads controlled by enviornment variable ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS) for larger problems. For large problems, compute the regularization once and save to disk; load for repeatability. |
ncores |
number of cores to use |
verbose |
verbose output |
matrix sparse p by q matrix is output with p by k nonzero entries
Avants BB
Maggioni, M., et al. "Multiscale data geometry."
## Not run: set.seed(120) mat <- matrix(rnorm(60), nrow = 6) mat2 <- matrix(rnorm(120), nrow = 6) smat <- sparseDistanceMatrixXY(mat, mat2, 3) smat2 <- sparseDistanceMatrixXY(mat2, mat, 3) testthat::expect_is(smat, "Matrix") testthat::expect_is(smat, "dgCMatrix") testthat::expect_is(smat2, "Matrix") testthat::expect_is(smat2, "dgCMatrix") testthat::expect_equal(sum(smat), 154.628961265087) testthat::expect_equal(sum(smat2), 63.7344262003899) ## End(Not run)## Not run: set.seed(120) mat <- matrix(rnorm(60), nrow = 6) mat2 <- matrix(rnorm(120), nrow = 6) smat <- sparseDistanceMatrixXY(mat, mat2, 3) smat2 <- sparseDistanceMatrixXY(mat2, mat, 3) testthat::expect_is(smat, "Matrix") testthat::expect_is(smat, "dgCMatrix") testthat::expect_is(smat2, "Matrix") testthat::expect_is(smat2, "dgCMatrix") testthat::expect_equal(sum(smat), 154.628961265087) testthat::expect_equal(sum(smat2), 63.7344262003899) ## End(Not run)
Compute a sparse, spatially coherent regression from a set of input images (with mask) to an outcome variable.
sparseRegression( inmatrix, demog, outcome, mask = NULL, sparseness = 0.05, nvecs = 10, its = 5, cthresh = 250, statdir = NA, z = 0, smooth = 0 )sparseRegression( inmatrix, demog, outcome, mask = NULL, sparseness = 0.05, nvecs = 10, its = 5, cthresh = 250, statdir = NA, z = 0, smooth = 0 )
inmatrix |
Input data matrix, with dimension number of subjects by number of voxels. |
demog |
Input demographics data frame. Contains outcome variable to regress against. |
outcome |
Name of column in |
mask |
Mask for reconstructing |
sparseness |
Level of sparsity desired. |
nvecs |
Number of eigenvectors to return. |
its |
Number of cross-validation folds to run. |
cthresh |
Cluster threshold. |
statdir |
Where to put results. If not provided, a temp directory is created. |
z |
Row (subject-wise) sparseness. |
smooth |
Amount of smoothing. |
A list of values:
eigenanatomyimages |
Coefficient vector images. |
umatrix |
Projections of input images on the sparse regression vectors. Can be used for, e.g., subsequent classification/predictions. |
projections |
Predicted values of outcome variable. |
Kandel BM, Avants BB.
Kandel B.M., D. Wolk, J. Gee, and B. Avants. Predicting Cognitive Data from Medical Images Using Sparse Linear Regression. Information Processing in Medical Imaging, 2013. literature/web site here ~
nsubj <- 50 prop.train <- 1 / 2 subj.train <- sample(1:nsubj, prop.train * nsubj, replace = FALSE) input <- t(replicate(nsubj, rnorm(125))) outcome <- seq(1, 5, length.out = nsubj) demog <- data.frame(outcome = outcome) input[, 40:60] <- 30 + outcome + rnorm(length(input[, 40:60]), sd = 2) input.train <- input[subj.train, ] input.test <- input[-subj.train, ] demog.train <- data.frame(outcome = demog[subj.train, ]) demog.test <- data.frame(outcome = demog[-subj.train, ]) mymask <- as.antsImage(array(rep(1, 125), dim = c(5, 5, 5))) myregression <- sparseRegression(input.train, demog.train, "outcome", mymask, sparseness = 0.05, nvecs = 5, its = 3, cthresh = 250 ) # visualization of results sample <- rep(0, 125) sample[40:60] <- 1 signal.img <- as.antsImage(array(rep(0, 125), dim = c(5, 5, 5))) signal.img[signal.img >= 0] <- sample # plot( signal.img, axis=2, slices='1x5x1') # actual source of signal # compare against first learned regression vector myimgs <- list() for (i in 1:5) { myarray <- as.array(myregression$eigenanatomyimages[[i]]) myarray <- myarray / max(abs(myarray)) # normalize for visualization myimgs[[i]] <- antsImageClone(myregression$eigenanatomyimages[[i]]) myimgs[[i]][mymask > 0] <- myarray } # plot(myimgs[[1]], axis=2, slices='1x5x1') # use learned eigenvectors for prediction result <- regressProjections( input.train, input.test, demog.train, demog.test, myregression$eigenanatomyimages, mymask, "outcome" ) # plot(result$outcome.comparison$real, result$outcome.comparison$predicted)nsubj <- 50 prop.train <- 1 / 2 subj.train <- sample(1:nsubj, prop.train * nsubj, replace = FALSE) input <- t(replicate(nsubj, rnorm(125))) outcome <- seq(1, 5, length.out = nsubj) demog <- data.frame(outcome = outcome) input[, 40:60] <- 30 + outcome + rnorm(length(input[, 40:60]), sd = 2) input.train <- input[subj.train, ] input.test <- input[-subj.train, ] demog.train <- data.frame(outcome = demog[subj.train, ]) demog.test <- data.frame(outcome = demog[-subj.train, ]) mymask <- as.antsImage(array(rep(1, 125), dim = c(5, 5, 5))) myregression <- sparseRegression(input.train, demog.train, "outcome", mymask, sparseness = 0.05, nvecs = 5, its = 3, cthresh = 250 ) # visualization of results sample <- rep(0, 125) sample[40:60] <- 1 signal.img <- as.antsImage(array(rep(0, 125), dim = c(5, 5, 5))) signal.img[signal.img >= 0] <- sample # plot( signal.img, axis=2, slices='1x5x1') # actual source of signal # compare against first learned regression vector myimgs <- list() for (i in 1:5) { myarray <- as.array(myregression$eigenanatomyimages[[i]]) myarray <- myarray / max(abs(myarray)) # normalize for visualization myimgs[[i]] <- antsImageClone(myregression$eigenanatomyimages[[i]]) myimgs[[i]][mymask > 0] <- myarray } # plot(myimgs[[1]], axis=2, slices='1x5x1') # use learned eigenvectors for prediction result <- regressProjections( input.train, input.test, demog.train, demog.test, myregression$eigenanatomyimages, mymask, "outcome" ) # plot(result$outcome.comparison$real, result$outcome.comparison$predicted)
This function applies a "winner-take-all" sparsity model. For each column, it finds the single most significant entry based on specified sign constraints and sets all other entries in that column to zero.
sparsify_by_column_winner( X, first_column_constraint = c("none", "either", "positive", "negative"), default_constraint = c("either", "positive", "negative"), ensure_row_membership = TRUE )sparsify_by_column_winner( X, first_column_constraint = c("none", "either", "positive", "negative"), default_constraint = c("either", "positive", "negative"), ensure_row_membership = TRUE )
X |
A numeric matrix [p_features x k_components]. |
first_column_constraint |
How to treat the first column. One of:
|
default_constraint |
How to treat all other columns (from the second onwards). Takes the same options as 'first_column_constraint'. Defaults to '"either"'. |
ensure_row_membership |
Logical. If TRUE, ensures every feature is represented in at least one component by "reviving" the single most significant entry for any row that becomes all-zero after sparsity. |
It includes special handling for the first column, which often represents a main effect that may not require the same constraints as subsequent components.
A sparsified matrix with the same dimensions as X.
set.seed(123) mat <- matrix(c( -5, 0.1, 0.2, 0.3, 0.4, # Col 1: Large negative value 1, 2.0, 0.1, 0.2, 0.3, # Col 2: Large positive value -1, -0.2, -3, -0.4, -0.5, # Col 3: Only negative values 1, -2, 3, -4, 5 # Col 4: Mixed signs ), nrow = 5, ncol = 4) res1 <- sparsify_by_column_winner(mat, 'positive', 'positive')set.seed(123) mat <- matrix(c( -5, 0.1, 0.2, 0.3, 0.4, # Col 1: Large negative value 1, 2.0, 0.1, 0.2, 0.3, # Col 2: Large positive value -1, -0.2, -3, -0.4, -0.5, # Col 3: Only negative values 1, -2, 3, -4, 5 # Col 4: Mixed signs ), nrow = 5, ncol = 4) res1 <- sparsify_by_column_winner(mat, 'positive', 'positive')
Take a standard lm result and use bayesian regression to impose spatial regularity.
spatialbayesianlm( mylm, ymat, mask, smth = 1, priorWeight = 1, nhood = NA, regweights = NA, smoothcoeffmat = NA )spatialbayesianlm( mylm, ymat, mask, smth = 1, priorWeight = 1, nhood = NA, regweights = NA, smoothcoeffmat = NA )
mylm |
standard lm result of the form mylm<-lm(ymat~.) |
ymat |
outcome matrix - usually from imaging data |
mask |
mask with non-zero entries n-columns of ymat |
smth |
smoothness parameter |
priorWeight |
weight on the prior |
nhood |
size of neighborhood |
regweights |
weights on rows - size of ymat |
smoothcoeffmat |
prior coefficient matrix |
bayesian regression solution is output as a list of images
Avants BB
# make some simple data ## Not run: if (!exists("fn")) fn <- getANTsRData("pcasl") asl <- antsImageRead(fn) tr <- antsGetSpacing(asl)[4] aslmean <- getAverageOfTimeSeries(asl) aslmask <- getMask(aslmean, lowThresh = mean(aslmean), cleanup = TRUE) pcaslpre <- aslPerfusion(asl, dorobust = 0, useDenoiser = NULL, skip = 1, useBayesian = 0, moreaccurate = 0, verbose = T, mask = aslmask ) # user might compare to useDenoiser=FALSE pcasl.parameters <- list(sequence = "pcasl", m0 = pcaslpre$m0) aslmat <- timeseries2matrix(asl, aslmask) tc <- as.factor(rep(c("C", "T"), nrow(aslmat) / 2)) dv <- computeDVARS(aslmat) perfmodel <- lm(aslmat ~ tc + stats::poly(dv, 4)) # standard model ssp <- spatialbayesianlm(perfmodel, aslmat, aslmask, priorWeight = 1.e2, smth = 1.6, nhood = rep(2, 3) ) plot(ssp[[1]], slices = "2x16x2", axis = 3) ## End(Not run)# make some simple data ## Not run: if (!exists("fn")) fn <- getANTsRData("pcasl") asl <- antsImageRead(fn) tr <- antsGetSpacing(asl)[4] aslmean <- getAverageOfTimeSeries(asl) aslmask <- getMask(aslmean, lowThresh = mean(aslmean), cleanup = TRUE) pcaslpre <- aslPerfusion(asl, dorobust = 0, useDenoiser = NULL, skip = 1, useBayesian = 0, moreaccurate = 0, verbose = T, mask = aslmask ) # user might compare to useDenoiser=FALSE pcasl.parameters <- list(sequence = "pcasl", m0 = pcaslpre$m0) aslmat <- timeseries2matrix(asl, aslmask) tc <- as.factor(rep(c("C", "T"), nrow(aslmat) / 2)) dv <- computeDVARS(aslmat) perfmodel <- lm(aslmat ~ tc + stats::poly(dv, 4)) # standard model ssp <- spatialbayesianlm(perfmodel, aslmat, aslmask, priorWeight = 1.e2, smth = 1.6, nhood = rep(2, 3) ) plot(ssp[[1]], slices = "2x16x2", axis = 3) ## End(Not run)
split a multichannel antsImage into a list of scalar antsImages
splitChannels(image)splitChannels(image)
image |
a multichannel antsImage to split |
list of scalar antsImages
Duda, JT
r <- floor(seq(1:(64 * 64)) / (64 * 64) * 255) dim(r) <- c(64, 64) r <- as.antsImage(r) g <- r * 0 b <- r * 0 testthat::expect_error(splitChannels(r)) rgbImage <- mergeChannels(list(r, g, b)) imgList <- splitChannels(rgbImage) testthat::expect_length(imgList, 3) sapply(imgList, function(x) { testthat::expect_s4_class(x, class = "antsImage") }) testthat::expect_error(splitChannels("hey"))r <- floor(seq(1:(64 * 64)) / (64 * 64) * 255) dim(r) <- c(64, 64) r <- as.antsImage(r) g <- r * 0 b <- r * 0 testthat::expect_error(splitChannels(r)) rgbImage <- mergeChannels(list(r, g, b)) imgList <- splitChannels(rgbImage) testthat::expect_length(imgList, 3) sapply(imgList, function(x) { testthat::expect_s4_class(x, class = "antsImage") }) testthat::expect_error(splitChannels("hey"))
Split data into testing and training sets for cross-validation.
splitData(data.source, ratio, return.rows = FALSE)splitData(data.source, ratio, return.rows = FALSE)
data.source |
Data frame or matrix of input data to be split. |
ratio |
If greater than one, number of folds to split data into.
Otherwise, proportion of rows in training data. See |
return.rows |
If |
A list containing the input data, split into testing and training
sets. If ratio is greater than one, returns a list with ratio
entries, each with 1/ratio of the input data in the testing set
(data.out) and the rest in the training set (data.in).
Otherwise, returns a list with one split of the data, with ratio of
the input data in the testing set and the rest in the training set.
Kandel BM and Avants B
## Not run: n <- 30 ratio <- 2 / 3 data.source <- data.frame(value = 1:n) out <- splitData(data.source, ratio) ## End(Not run)## Not run: n <- 30 ratio <- 2 / 3 data.source <- data.frame(value = 1:n) out <- splitData(data.source, ratio) ## End(Not run)
split a mask into n labeled sub-masks
splitMask(mask, n = NA, voxchunk = NA)splitMask(mask, n = NA, voxchunk = NA)
mask |
antsImage mask |
n |
number of mask chunks (if voxchunk is not set) |
voxchunk |
number of voxels per chunk (if n is not set) |
relabeledMask
Avants BB, Tustison NJ, Pustina D
mask <- getMask(antsImageRead(getANTsRData("r16"))) smask <- splitMask(mask, 10)mask <- getMask(antsImageRead(getANTsRData("r16"))) smask <- splitMask(mask, 10)
This function splits the dimensionality d input image into a list of images with dimensonality d-1 by slicing the input image along its last dimension.
splitNDImageToList(img)splitNDImageToList(img)
img |
input image of class antsImage, last dimension will be split |
output list filled with d-1 volumes of class antsImage
Pustina D, Avants B
my4Dimage <- makeImage(c(5, 5, 5, 4)) my3Dlist <- splitNDImageToList(my4Dimage)my4Dimage <- makeImage(c(5, 5, 5, 4)) my3Dlist <- splitNDImageToList(my4Dimage)
Produces a threshold value based on cluster or voxel level statistics
statFieldThresh( x, pval, nvox, n, fwhm, resels, df, fieldType, threshType, pp = 0.001, verbose = FALSE )statFieldThresh( x, pval, nvox, n, fwhm, resels, df, fieldType, threshType, pp = 0.001, verbose = FALSE )
x |
statistical map of class antsImage |
pval |
p-value for determining threshold |
nvox |
minimum desired cluster size (in voxels) |
n |
number of images in conjunction |
fwhm |
full width at half maxima |
resels |
resolution elements in search region |
df |
degrees of freedom expressed as df = c(degrees of interest, degrees of error) |
fieldType |
|
threshType |
|
pp |
primary (initial) p-value threshold used in FDR methods |
verbose |
enables verbose output |
A statistical threshold level is determined using the estimated p-value pval
given the provided parameters. "cRFT" and "pRFT" specify the method of estimation
should use RFT cluster and peak statistic estimates respectively.
In addition to RFT based thresholds the user may choose to utilize false-discovery rate
(FDR) based thresholds. These use a primary p-value threshold (default pp = .001)
to create suprathreshold clusters which in turn are used to determine a final threshold
(utilizing pval at this point). If the estimated peak-FDR statistic is used ("pFDR")
then all suprathreshold voxels are FDR corrected to determine the threshold. If the
estimated cluster-FDR statistic is used then the cluster maxima are FDR corrected in order
to determine the threshold.
It is important that the user recognize that when statistical analyses are computed using RFT that the threshold level plays a role in predicting the p-value. This is because the probability of obtaining results is weighted against the probability of any occurence given the threshold. For example, if two clusters where exactly the same but had one was obtained using a lower threshold it would have a lower p-value. This has been shown with a power analysis using similar parameters to those presented herein with the additional variable of signal characteristics to demonstrate the effect of image modality on analysis (Friston et al., 1996). Therefore, parameters should be chosen according to the type of analysis being performed (fMRI, PET, or VBM) and the hypothesis being tested. Due to widely varying oppinions on appropriate thresholding procedures no specific recommendations are made here. This function simply facilitates the use of several approaches that users may utilize after consulting available literature.
Outputs a statistical value to be used for threshold a SPM
Zachary P. Christensen
Chumbley J., (2010) Topological FDR for neuroimaging
Friston K.J., (1994) Assessing the Significance of Focal Activations Using Their Spatial Extent
Friston K.J., (1996) Detecting Activations in PET and fMRI: Levels of Inference and Power
## Not run: # threshold according to estimated peak height thresh_image <- statFieldThresh(timg, .05, 10, 1, mysmooth$fwhm, c(1, fit$df.residual), fieldType = "T", threshType = pRFT ) ## End(Not run)## Not run: # threshold according to estimated peak height thresh_image <- statFieldThresh(timg, .05, 10, 1, mysmooth$fwhm, c(1, fit$df.residual), fieldType = "T", threshType = pRFT ) ## End(Not run)
This is a generic S3 function that dispatches to the correct update rule based on the optimizer's class.
step(optimizer, i, V_current, descent_gradient, ...)step(optimizer, i, V_current, descent_gradient, ...)
optimizer |
The optimizer object from 'create_optimizer()'. |
i |
The index of the modality currently being updated. |
V_current |
The current V matrix for modality 'i'. |
descent_gradient |
The Riemannian DESCENT gradient (-grad(E)) for V_current. |
... |
Additional arguments required by the specific method (e.g., 'full_energy_function' for line searches, 'learning_rate' for others). |
A list containing 'updated_V' and the updated 'optimizer' object.
SubgradientL1Regression solves y approx x beta
subgradientL1Regression( y, x, s = 0.01, percentvals = 0.1, nits = 100, betas = NA, sparval = NA )subgradientL1Regression( y, x, s = 0.01, percentvals = 0.1, nits = 100, betas = NA, sparval = NA )
y |
outcome variable |
x |
predictor matrix |
s |
gradient descent parameter |
percentvals |
percent of values to use each iteration |
nits |
number of iterations |
betas |
initial guess at solution |
sparval |
sparseness |
output has a list of summary items
Avants BB
mat <- replicate(1000, rnorm(200)) y <- rnorm(200) wmat <- subgradientL1Regression(y, mat, percentvals = 0.05) print(wmat$resultcorr)mat <- replicate(1000, rnorm(200)) y <- rnorm(200) wmat <- subgradientL1Regression(y, mat, percentvals = 0.05) print(wmat$resultcorr)
SubjectDataToGroupDataFrames take a list of subject-level csv files of the same type and converts them to a data frame with consistent column naming for the values and where rows correspond to subjects.
subjectDataToGroupDataFrame(csvlist, usecol, mycolname = NA, datarownames = NA)subjectDataToGroupDataFrame(csvlist, usecol, mycolname = NA, datarownames = NA)
csvlist |
input list of csv files eg by Sys.glob ... |
usecol |
a column name or number e.g. 1 or 'Volume' |
mycolname |
rename the column by this string (optional) |
datarownames |
the desired now names (optional) |
data frame is output
Avants BB
## Not run: # data(aal,package="ANTsR") # csvlist<-Sys.glob("*md*csv") # mypopulationdataframe<-subjectDataToGroupDataFrame( csvlist , "Mean" , # datarownames=aal$label_name ) # should have each ROI value for each subject listed in a large data frame ## End(Not run)## Not run: # data(aal,package="ANTsR") # csvlist<-Sys.glob("*md*csv") # mypopulationdataframe<-subjectDataToGroupDataFrame( csvlist , "Mean" , # datarownames=aal$label_name ) # should have each ROI value for each subject listed in a large data frame ## End(Not run)
Returns subsets of antsImage objects as vectors
## S3 method for class 'antsImage' subset(x, subset, ...)## S3 method for class 'antsImage' subset(x, subset, ...)
x |
antsImage object |
subset |
logical expression of subset |
... |
further arguments to be passed to or from other methods. |
This function takes a matrix as input and partitions each column such that only one entry in each row is non-zero, and the sums of each row are roughly equivalent.
sum_preserving_matrix_partition(X, option = 2, tol = 0.001)sum_preserving_matrix_partition(X, option = 2, tol = 0.001)
X |
A matrix of size p x k |
option |
An integer indicating whether to allow +/- values (option 1) or only + values (option 2). Default is 1. |
tol |
A numeric value indicating the tolerance for the row sums. Default is 0.1. |
The function uses a greedy algorithm to select the entry with the maximum absolute value (or maximum positive value) in each column. The rows are then normalized to ensure that the sums are roughly equivalent.
A matrix with segmented rows
X <- matrix(rnorm(3000), nrow = 1000) Y <- sum_preserving_matrix_partition(X, option = 1) Y <- sum_preserving_matrix_partition(X, option = 2)X <- matrix(rnorm(3000), nrow = 1000) Y <- sum_preserving_matrix_partition(X, option = 1) Y <- sum_preserving_matrix_partition(X, option = 2)
Computes the symmetric part of a matrix by averaging it with its transpose.
symm(A)symm(A)
A |
Numeric matrix to symmetrize. |
The symmetric part is defined as , ensuring the result is symmetric.
This is used in computing the Riemannian gradient for the Stiefel manifold.
Numeric matrix, the symmetric part (A + A^T)/2.
A <- matrix(c(1, 2, 3, 4), 2, 2) symm(A)A <- matrix(c(1, 2, 3, 4), 2, 2) symm(A)
This function iterates through each column of a numeric matrix. If a column contains only zero and positive values, or only zero and negative values, the absolute value of that column is taken. Otherwise, the column is returned as is.
take_abs_unsigned(m)take_abs_unsigned(m)
m |
A numeric matrix. |
A matrix with absolute values taken for unsigned columns.
Input 4D time series matrix. (Perform slice timing correction externally). Estimate hemodynamicRF from block design. Compute brain mask on average bold image. Get nuisance variables : motion , compcor , globalsignal. High-frequency filter the time series ( externally ). Correct for autocorrelation using bullmore 1996 MRM and AR(2) model with parameters derived from global residual signal. Estimate final glm.
taskFMRI( mat, hrf, myvars, correctautocorr = FALSE, residualizedesignmatrix = FALSE, myformula = NA )taskFMRI( mat, hrf, myvars, correctautocorr = FALSE, residualizedesignmatrix = FALSE, myformula = NA )
mat |
input matrix |
hrf |
input hrf |
myvars |
output of getfMRInuisanceVariables |
correctautocorr |
correction auto correlation boolean |
residualizedesignmatrix |
boolean |
myformula |
statistical equation to be assessed at each voxel |
list of betas and other names entries is output
Avants BB
## Not run: # read the fmri image in and maybe do slice timing correction fmri <- getANTsRData("pcasl") fmri <- antsImageRead(fmri) # fmri<-iMath(fmri,"SliceTimingCorrection","bspline") # optional myvars <- getfMRInuisanceVariables(fmri, moreaccurate = 0, maskThresh = 100) mat <- myvars$matrixTimeSeries mat <- frequencyFilterfMRI(mat, 2.5, freqLo = 0.01, freqHi = 0.1, opt = "butt") blockfing <- c(0, 36, 72) hrf <- hemodynamicRF( scans = dim(fmri)[4], onsets = blockfing, durations = rep(12, length(blockfing)), rt = 2.5 ) activationBeta <- taskFMRI(mat, hrf, myvars) ## End(Not run)## Not run: # read the fmri image in and maybe do slice timing correction fmri <- getANTsRData("pcasl") fmri <- antsImageRead(fmri) # fmri<-iMath(fmri,"SliceTimingCorrection","bspline") # optional myvars <- getfMRInuisanceVariables(fmri, moreaccurate = 0, maskThresh = 100) mat <- myvars$matrixTimeSeries mat <- frequencyFilterfMRI(mat, 2.5, freqLo = 0.01, freqHi = 0.1, opt = "butt") blockfing <- c(0, 36, 72) hrf <- hemodynamicRF( scans = dim(fmri)[4], onsets = blockfing, durations = rep(12, length(blockfing)), rt = 2.5 ) activationBeta <- taskFMRI(mat, hrf, myvars) ## End(Not run)
Temporally whitens the input matrix using autoregression and returns the result.
temporalwhiten(mat, myord = 2)temporalwhiten(mat, myord = 2)
mat |
input matrix |
myord |
integer order value |
matrix is output
Avants BB
mat <- replicate(100, rnorm(20)) wmat <- temporalwhiten(mat)mat <- replicate(100, rnorm(20)) wmat <- temporalwhiten(mat)
This tests each eigenanatomy region in order invisibly to the user and stops when testing stops conserving power. The algorithm returns NA if there is no good testing procedure, given the statistical target. The basic idea is to test the variables that explain the most variance first and continue testing as long as (a) there is no significant relationship yet found or (b) the existing significant relationship remains significant, given the correction for multiple comparisons.
testEanat(mymdl, myvar, sigthresh = 0.05, method = "BH")testEanat(mymdl, myvar, sigthresh = 0.05, method = "BH")
mymdl |
input model from |
myvar |
name of variable in model to test |
sigthresh |
significance threshold, for example 0.05 |
method |
a method for |
nvecs is output, analogous to nvecs in
svd(mat,nu=0,nv=nvecs)
Avants BB, Tustison NJ
Avants BB, Hackman D, LM Betancourt, GM Lawson, H Hurt, MJ Farah #' Relation of Childhood Home Environment to Cortical Thickness in Late Adolescence: Specificity of Experience and Timing, PloS one, 2015
mat <- matrix(rnorm(300), ncol = 3) n <- nrow(mat) g <- factor(c(rep(1, n / 2), rep(0, n / 2))) mydf <- data.frame(gen = g, a = rnorm(n)) mymdl <- lm(mat ~ a + g, data = mydf) nv <- testEanat(mymdl, myvar = "g1") mat[1:(n / 2), 3] <- mat[1:(n / 2), 3] + 2 mymdl <- lm(mat ~ a + g, data = mydf) nv <- testEanat(mymdl, myvar = "g1")mat <- matrix(rnorm(300), ncol = 3) n <- nrow(mat) g <- factor(c(rep(1, n / 2), rep(0, n / 2))) mydf <- data.frame(gen = g, a = rnorm(n)) mymdl <- lm(mat ~ a + g, data = mydf) nv <- testEanat(mymdl, myvar = "g1") mat[1:(n / 2), 3] <- mat[1:(n / 2), 3] + 2 mymdl <- lm(mat ~ a + g, data = mydf) nv <- testEanat(mymdl, myvar = "g1")
converts a scalar image into a binary image by thresholding operations
thresholdImage(inimg, lothresh, hithresh, inval=1, outval=0)thresholdImage(inimg, lothresh, hithresh, inval=1, outval=0)
inimg |
Input image to operate on |
lothresh |
Lower edge of threshold window |
hithresh |
Higher edge of threshold window |
inval |
Output value for image voxels in between |
outval |
Output value for image voxels lower than |
antsImage
Shrinidhi KL
set.seed(1234) img <- makeImage(c(5, 5), rnorm(25) + 0.5) imgt <- thresholdImage(img, 0.5, Inf) testthat::expect_equal(sum(imgt), 9) imgt <- thresholdImage(img > 0.5, 0.1, Inf) testthat::expect_equal(sum(imgt), 9)set.seed(1234) img <- makeImage(c(5, 5), rnorm(25) + 0.5) imgt <- thresholdImage(img, 0.5, Inf) testthat::expect_equal(sum(imgt), 9) imgt <- thresholdImage(img > 0.5, 0.1, Inf) testthat::expect_equal(sum(imgt), 9)
Extract a matrix from a time-series image after applying a mask.
timeseries2matrix(img, mask)timeseries2matrix(img, mask)
img |
Input image of type 'antsImage' or R array. |
mask |
Input mask of type 'antsImage' or R array. In either case, the number of voxels in the mask may be either equal to that of input image 'img' or equal to number of voxels in one time unit of input image 'img'. In the second case, the mask is reused for every time unit of the 'img'. A mask of n-labels will cause the function to return a matrix containing the mean time series within each label. |
Success – an R matrix of dimensions ( dim(img)[length(dim(img))] ,
sum(mask==1) )
Shrinidhi KL
img <- makeImage(c(10, 10, 10, 5), 0) # or use antsImageRead ... mask <- array(1, dim(img)[1:3]) mat <- timeseries2matrix(img, mask)img <- makeImage(c(10, 10, 10, 5), 0) # or use antsImageRead ... mask <- array(1, dim(img)[1:3]) mat <- timeseries2matrix(img, mask)
Repeatedly run N3 on slices of time series and return image
timeseriesN3(boldimg, mask, ncorrections = c(2, 2))timeseriesN3(boldimg, mask, ncorrections = c(2, 2))
boldimg |
input matrix |
mask |
mask to use |
ncorrections |
levels at which to apply n3 |
antsImage is output
Avants BB
bold <- makeImage(c(10, 10, 10, 4), rnorm(4000)) mask <- getMask(getAverageOfTimeSeries(bold)) boldn3 <- timeseriesN3(bold, mask, c(4, 2))bold <- makeImage(c(10, 10, 10, 4), rnorm(4000)) mask <- getMask(getAverageOfTimeSeries(bold)) boldn3 <- timeseriesN3(bold, mask, c(4, 2))
Extract a matrix from a time-series image after applying a mask where each row is a space-time vector
timeserieswindow2matrix( timeseriesmatrix, mask, eventlist, timewindow, zeropadvalue = 0, spacing = NA )timeserieswindow2matrix( timeseriesmatrix, mask, eventlist, timewindow, zeropadvalue = 0, spacing = NA )
timeseriesmatrix |
Input timeseriesmatrix from timeseries2matrix |
mask |
Input mask of type 'antsImage' ... the mask will be replicated into a 4D image of length timewindow + zeropadvalue. |
eventlist |
time indices for the events to extract |
timewindow |
n-timepoints around each event, forward in time. |
zeropadvalue |
pads the mask by this amount fwd and bwd in time. |
spacing |
optional 4d spacing vector that will impact smoothing parameters |
Success – an R matrix of dimensions
ntimewindow*sizeofnonzerovaluesinmask*nevents
Avants BB
img <- makeImage(c(10, 10, 10, 50), 0) mask <- as.antsImage(array(1, dim(img)[1:3])) mat <- timeseries2matrix(img, mask) mat <- timeserieswindow2matrix(mat, mask, c(1, 4, 5), 2, 0) print(dim(mat$eventmatrix)) print(dim(mat$mask4d)) ##### another approach dim4 <- c(20, 30, 10, 100) i1 <- 10:15 i2 <- 11:18 i3 <- 4:8 i4 <- 10:90 arr3d <- array(data = 0, dim = dim4[1:3]) arr3d[i1, i2, i3] <- 1 arr <- array(data = 0, dim = dim4) for (t in i4) arr[, , , t] <- t nois <- which(arr > 0) noisv <- rnorm(length(nois)) arr[nois] <- arr[nois] + noisv * 0.0 msk <- as.antsImage(arr3d) img <- as.antsImage(arr) mat <- timeseries2matrix(img, msk) eanat <- sparseDecom(mat, msk, sparseness = 0.1, z = 0.5, nvecs = 2, its = 5, cthresh = 0, mycoption = 1) eanat2 <- sparseDecom(mat, sparseness = 0.1, z = 0.5, nvecs = 2, its = 5, cthresh = 0, mycoption = 1) enomask <- eanat2$eigenanatomyimages[1, ] emask <- eanat$eigenanatomyimages[1, ] print(enomask[31:40]) print(emask[31:40]) # same thing with event matrices .... ttt <- timeserieswindow2matrix(mat, msk, c(20, 40, 60, 70), 6, 0) tte <- ttt$eventmatrix eanat <- sparseDecom(tte, ttt$mask4d, sparseness = -0.9, z = 0.5, nvecs = 2, its = 5, cthresh = 0, mycoption = 1) eanat2 <- sparseDecom(tte, sparseness = -0.9, z = 0.5, nvecs = 2, its = 5, cthresh = 0, mycoption = 1) enomask <- eanat2$eigenanatomyimages[, 1] # back to timematrix tmat <- matrix(enomask, nrow = 6) # back to image eimg <- antsImageClone(msk) eimg[msk == 1] <- tmat[1, ] # convert image space to evec space emat <- eanat2$eigenanatomyimages # convert emat to events FIXME this does not currently work # eavent<-timeserieswindow2matrix( data.matrix(emat) , msk, 1 , 6, 0 ) # emask<-eavent$eventmatrix[1,] #############################img <- makeImage(c(10, 10, 10, 50), 0) mask <- as.antsImage(array(1, dim(img)[1:3])) mat <- timeseries2matrix(img, mask) mat <- timeserieswindow2matrix(mat, mask, c(1, 4, 5), 2, 0) print(dim(mat$eventmatrix)) print(dim(mat$mask4d)) ##### another approach dim4 <- c(20, 30, 10, 100) i1 <- 10:15 i2 <- 11:18 i3 <- 4:8 i4 <- 10:90 arr3d <- array(data = 0, dim = dim4[1:3]) arr3d[i1, i2, i3] <- 1 arr <- array(data = 0, dim = dim4) for (t in i4) arr[, , , t] <- t nois <- which(arr > 0) noisv <- rnorm(length(nois)) arr[nois] <- arr[nois] + noisv * 0.0 msk <- as.antsImage(arr3d) img <- as.antsImage(arr) mat <- timeseries2matrix(img, msk) eanat <- sparseDecom(mat, msk, sparseness = 0.1, z = 0.5, nvecs = 2, its = 5, cthresh = 0, mycoption = 1) eanat2 <- sparseDecom(mat, sparseness = 0.1, z = 0.5, nvecs = 2, its = 5, cthresh = 0, mycoption = 1) enomask <- eanat2$eigenanatomyimages[1, ] emask <- eanat$eigenanatomyimages[1, ] print(enomask[31:40]) print(emask[31:40]) # same thing with event matrices .... ttt <- timeserieswindow2matrix(mat, msk, c(20, 40, 60, 70), 6, 0) tte <- ttt$eventmatrix eanat <- sparseDecom(tte, ttt$mask4d, sparseness = -0.9, z = 0.5, nvecs = 2, its = 5, cthresh = 0, mycoption = 1) eanat2 <- sparseDecom(tte, sparseness = -0.9, z = 0.5, nvecs = 2, its = 5, cthresh = 0, mycoption = 1) enomask <- eanat2$eigenanatomyimages[, 1] # back to timematrix tmat <- matrix(enomask, nrow = 6) # back to image eimg <- antsImageClone(msk) eimg[msk == 1] <- tmat[1, ] # convert image space to evec space emat <- eanat2$eigenanatomyimages # convert emat to events FIXME this does not currently work # eavent<-timeserieswindow2matrix( data.matrix(emat) , msk, 1 , 6, 0 ) # emask<-eavent$eventmatrix[1,] #############################
A data frame label numbers and names for tissue types.
tissuestissues
A data frame with columns: Label, Description, ProbabilityNumber.
A data frame label numbers and names for the white matter tracts labels.
tractstracts
A data frame listing the following variables.
label_numNumerical label value.
label_nameShorthand anatomical value.
https://pubmed.ncbi.nlm.nih.gov/18407524
data(tracts)data(tracts)
Applies centering, scaling, and/or normalization transforms to prepare data for optimization or learning-rate estimation.
transform_matrix( X, method = c("none", "center", "zscore", "minmax", "l2", "frob", "frob_zscore") )transform_matrix( X, method = c("none", "center", "zscore", "minmax", "l2", "frob", "frob_zscore") )
X |
Numeric matrix. |
method |
Character string specifying the transformation:
|
A list with:
Xs: transformed matrix
params: list of learned transform parameters
Given a vector (or a matrix) representing a curve (or set of curves, columnwise), the area (or set of areas) is calculated using the trapezoidal rule.
trapz(x, y)trapz(x, y)
x |
vector of samples for the dependent variable. |
y |
vector or matrix of samples for the independent variable. In the case of the latter, curves are organized column-wise. |
area (areas) under the sampled curve (curves).
Tustison NJ
x <- seq(0, 1, by = 0.0001) y <- exp(x) # Compare with true area of exp( 1 ) - 1 = 1.718282... areaEstimate <- trapz(x, y)x <- seq(0, 1, by = 0.0001) y <- exp(x) # Compare with true area of exp( 1 ) - 1 = 1.718282... areaEstimate <- trapz(x, y)
Undo a previously applied matrix transform
undo_transform_matrix(Xs, params)undo_transform_matrix(Xs, params)
Xs |
Transformed matrix. |
params |
List of parameters returned by |
The untransformed (original scale) matrix.
Overloaded uniqueness operation for antsImage objects
## S3 method for class 'antsImage' unique(x, incomparables = FALSE, mask = NULL, ...)## S3 method for class 'antsImage' unique(x, incomparables = FALSE, mask = NULL, ...)
x |
is an object of class |
incomparables |
a vector of values that cannot be compared. |
mask |
binary mask of values to subset |
... |
additional arguments passed to |
img <- antsImageRead(getANTsRData("r16")) img[img > 5] <- 0 sort(unique(img))img <- antsImageRead(getANTsRData("r16")) img[img > 5] <- 0 sort(unique(img))
Use any package. If package is not installed, this will install from CRAN.
usePkg(packageName, allowInstall = FALSE)usePkg(packageName, allowInstall = FALSE)
packageName |
Name of package as *string*. |
allowInstall |
let the package be installed from CRAN |
TRUE if package successfully loaded, FALSE otherwise.
Benjamin M. Kandel, BB Avants
usePkg("randomForest") usePkg("stats", allowInstall = TRUE)usePkg("randomForest") usePkg("stats", allowInstall = TRUE)
Calculates the variance of an image
var(x, ...) ## Default S3 method: var(x, ...) ## S3 method for class 'antsImage' var(x, ..., na.rm = FALSE, mask = NULL)var(x, ...) ## Default S3 method: var(x, ...) ## S3 method for class 'antsImage' var(x, ..., na.rm = FALSE, mask = NULL)
x |
an object for which we want to compute the variance |
... |
Any additional arguments to be passed to
|
na.rm |
a logical value indicating whether NA should be removed |
mask |
is an object of class |
img <- antsImageRead(getANTsRData("r16")) var(img)img <- antsImageRead(getANTsRData("r16")) var(img)
Convert a Vector to a Data Frame
vector_to_df(vector, column_name)vector_to_df(vector, column_name)
vector |
The input vector |
column_name |
The base name for the columns |
A data frame with one row and columns determined by the length of the vector
vector_to_df(1:10, "nm")vector_to_df(1:10, "nm")
antsImage.Converts a vector of size n-entries in mask times number of channels to a multi-channel image with the same dimensionality as the mask.
vectorToMultichannel(v, mask)vectorToMultichannel(v, mask)
v |
input multichannel vector |
mask |
mask of same dimensionality as multichannelimage |
multichannelimage is output
Avants BB
fi <- antsImageRead(getANTsRData("r16")) %>% resampleImage(c(60, 60), 1, 0) mi <- antsImageRead(getANTsRData("r64")) %>% resampleImage(c(60, 60), 1, 0) mytx <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) mcimg <- antsImageRead(mytx$fwd[1]) msk <- getMask(fi) vv <- multichannelToVector(mcimg, msk) mcimg2 <- vectorToMultichannel(vv, msk) vv2 <- multichannelToVector(mcimg2, msk) cor.test(vv2, vv) stopifnot(all(mcimg2[30, 30] == mcimg[30, 30]))fi <- antsImageRead(getANTsRData("r16")) %>% resampleImage(c(60, 60), 1, 0) mi <- antsImageRead(getANTsRData("r64")) %>% resampleImage(c(60, 60), 1, 0) mytx <- antsRegistration(fixed = fi, moving = mi, typeofTransform = c("SyN")) mcimg <- antsImageRead(mytx$fwd[1]) msk <- getMask(fi) vv <- multichannelToVector(mcimg, msk) mcimg2 <- vectorToMultichannel(vv, msk) vv2 <- multichannelToVector(mcimg2, msk) cor.test(vv2, vv) stopifnot(all(mcimg2[30, 30] == mcimg[30, 30]))
Visualize Low-Rank Relationships
visualize_lowrank_relationships( X1, X2, V1, V2, plot_title = NULL, nm1 = "X1", nm2 = "X2", max_pairs = 5 )visualize_lowrank_relationships( X1, X2, V1, V2, plot_title = NULL, nm1 = "X1", nm2 = "X2", max_pairs = 5 )
X1 |
First matrix (Subjects x Features) |
X2 |
Second matrix (Subjects x Features) |
V1 |
First feature loading matrix (Features x Components) |
V2 |
Second feature loading matrix (Features x Components) |
plot_title |
Title of the plot |
nm1 |
Label for view 1 |
nm2 |
Label for view 2 |
max_pairs |
Maximum components to include in the pairs plot (Safety cap) |
This function visualizes the results of a permutation test by plotting a histogram of the permutation test statistics. A red dotted line indicates the location of the original unpermuted test statistic.
visualize_permutation_test( permutation_results, original_stat, stat_name, plot_title, bin_width = 0.1 )visualize_permutation_test( permutation_results, original_stat, stat_name, plot_title, bin_width = 0.1 )
permutation_results |
A numeric vector of permutation test statistics. |
original_stat |
A numeric value representing the original unpermuted test statistic. |
stat_name |
A character string representing the name of the test statistic. |
plot_title |
string for plot title |
bin_width |
optional bin width for the histogram |
A ggplot object showing the histogram of permutation test statistics with the original test statistic marked.
## Not run: set.seed(123) n_perms <- 1000 permutation_results <- rnorm(n_perms, mean = 0, sd = 1) original_stat <- 2 visualize_permutation_test(permutation_results, original_stat, "Simulated Statistic") ## End(Not run)## Not run: set.seed(123) n_perms <- 1000 permutation_results <- rnorm(n_perms, mean = 0, sd = 1) original_stat <- 2 visualize_permutation_test(permutation_results, original_stat, "Simulated Statistic") ## End(Not run)
Represents feature images as a neighborhood and uses the features to build a random forest prediction from an image population
vwnrfs( y, x, labelmasks, rad = NA, nsamples = 8, ntrees = 500, asFactors = TRUE, reduceFactor = 1, ... )vwnrfs( y, x, labelmasks, rad = NA, nsamples = 8, ntrees = 500, asFactors = TRUE, reduceFactor = 1, ... )
y |
list of training label images, can be a factor or numeric vector this can also be a regular old vector |
x |
a list of lists where each list contains feature images |
labelmasks |
a list of masks where each mask defines the image space for the given list. that is, the nth mask indexes the nth feature set. multi-label masks will try to balance sampling for each label. |
rad |
vector of dimensionality d define nhood radius |
nsamples |
(per subject to enter training) |
ntrees |
(for the random forest model) |
asFactors |
boolean - treat the y entries as factors |
reduceFactor |
integer factor by which to reduce (imaging) data resolution |
... |
arguments to pass to |
list a 4-list with the rf model, training vector, feature matrix and the random mask
Avants BB, Tustison NJ, Pustina D
mask <- makeImage(c(10, 10), 0) mask[3:6, 3:6] <- 1 mask[5, 5:6] <- 2 ilist <- list() lablist <- list() masklist <- list() inds <- 1:5 scl <- 0.33 # a noise parameter for (predtype in c("label", "scalar")) { for (i in inds) { img <- antsImageClone(mask) imgb <- antsImageClone(mask) limg <- antsImageClone(mask) if (predtype == "label") { # 4 class prediction img[3:6, 3:6] <- rnorm(16) * scl + (i %% 4) + scl * mean(rnorm(1)) imgb[3:6, 3:6] <- rnorm(16) * scl + (i %% 4) + scl * mean(rnorm(1)) limg[3:6, 3:6] <- (i %% 4) + 1 # the label image is constant } if (predtype == "scalar") { img[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) imgb[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) limg <- i^2.0 # a real outcome } ilist[[i]] <- list(img, imgb) # two features lablist[[i]] <- limg masklist[[i]] <- mask } rfm <- vwnrfs(lablist, ilist, masklist[[1]], rad = c(2, 2)) # use single mask rfm <- vwnrfs(lablist, ilist, masklist, rad = c(2, 2)) if (predtype == "label") { print(sum(rfm$tv != predict(rfm$rfm))) } if (predtype == "scalar") { print(cor(as.numeric(rfm$tv), as.numeric(predict(rfm$rfm)))) } } # end predtype loopmask <- makeImage(c(10, 10), 0) mask[3:6, 3:6] <- 1 mask[5, 5:6] <- 2 ilist <- list() lablist <- list() masklist <- list() inds <- 1:5 scl <- 0.33 # a noise parameter for (predtype in c("label", "scalar")) { for (i in inds) { img <- antsImageClone(mask) imgb <- antsImageClone(mask) limg <- antsImageClone(mask) if (predtype == "label") { # 4 class prediction img[3:6, 3:6] <- rnorm(16) * scl + (i %% 4) + scl * mean(rnorm(1)) imgb[3:6, 3:6] <- rnorm(16) * scl + (i %% 4) + scl * mean(rnorm(1)) limg[3:6, 3:6] <- (i %% 4) + 1 # the label image is constant } if (predtype == "scalar") { img[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) imgb[3:6, 3:6] <- rnorm(16, 1) * scl * (i) + scl * mean(rnorm(1)) limg <- i^2.0 # a real outcome } ilist[[i]] <- list(img, imgb) # two features lablist[[i]] <- limg masklist[[i]] <- mask } rfm <- vwnrfs(lablist, ilist, masklist[[1]], rad = c(2, 2)) # use single mask rfm <- vwnrfs(lablist, ilist, masklist, rad = c(2, 2)) if (predtype == "label") { print(sum(rfm$tv != predict(rfm$rfm))) } if (predtype == "scalar") { print(cor(as.numeric(rfm$tv), as.numeric(predict(rfm$rfm)))) } } # end predtype loop
Takes a model created with vwnrfs and builds a prediction based on similar features used to train vwnrfs
vwnrfs.predict( rfm, x, labelmasks, rad = NA, asFactors = TRUE, voxchunk = 30000, reduceFactor = 1 )vwnrfs.predict( rfm, x, labelmasks, rad = NA, asFactors = TRUE, voxchunk = 30000, reduceFactor = 1 )
rfm |
random forest model trained with vwnrfs with certain number of features. |
x |
a list of lists. Each list contains the list of feature images required to predict a response or an image. The features must be the same used during training. I.e., if you train on T1 and T2 images, those should be the same features used for prediction, in the same exact order for each subject. |
labelmasks |
a list of masks where each mask defines the space to predict from. These can be individual masks for each subject (i.e., custom brain masks) or a single antsImage that will be used for all subjects. |
rad |
vector of dimensionality d define the neighborhood radius. Must be the same radius with which the model was trained, i.e., c(1,1,1) |
asFactors |
boolean - treat the y entries as factors. If this is true, the prediction will be a classification, and the output will produce images. If this is false, the prediction will be a regression, and the output will produce a single response value. |
voxchunk |
value of maximal voxels to predict at once. This value is used to split the prediction into smaller chunks such that memory requirements do not become too big. |
reduceFactor |
value of resolution reduction (i.e., for 1mm voxels and reduceFactor=3) the model will be trained on ~3mm images. |
list a 2-list with the rf model, training vector, feature matrix and the random mask
Pustina D
## Do not run ## vwnrfs.predict(rfm, x=x, labelmasks=labelmasks, ## rad=rad, asFactors=TRUE, voxchunk=voxchunk, ## reduceFactor = mr)mask<-makeImage( c(10,10), 0 ) ## End do not run## Do not run ## vwnrfs.predict(rfm, x=x, labelmasks=labelmasks, ## rad=rad, asFactors=TRUE, voxchunk=voxchunk, ## reduceFactor = mr)mask<-makeImage( c(10,10), 0 ) ## End do not run
uses the weingarten map to estimate image mean or gaussian curvature
weingartenImageCurvature(image, sigma = 1, opt = "mean", labeled = FALSE)weingartenImageCurvature(image, sigma = 1, opt = "mean", labeled = FALSE)
image |
antsImage |
sigma |
smoothing parameter |
opt |
mean by default, otherwise use string gaussian or characterize |
labeled |
boolean if TRUE then assume image contains labels which denote the surface on which curvature is to be calculated. in this case, the surface should hold integer value 1; the background should be zero; the interior of the surface should be greater than 1 (e.g. 2). |
image
Brian B. Avants
Avants, B, J. Gee, and B. Avants. Shape operator for differential image analysis Information Processing in Medical Imaging, 2003.
img <- makeImage(c(10, 10, 10), rnorm(1000)) fik <- weingartenImageCurvature(img) ## Not run: fi <- antsImageRead(getANTsRData("mni")) fik <- weingartenImageCurvature(fi) ## End(Not run)img <- makeImage(c(10, 10, 10), rnorm(1000)) fik <- weingartenImageCurvature(img) ## Not run: fi <- antsImageRead(getANTsRData("mni")) fik <- weingartenImageCurvature(fi) ## End(Not run)
Whitens the input matrix using SVD and returns the result.
whiten(x, k = NULL, reducex = FALSE)whiten(x, k = NULL, reducex = FALSE)
x |
input matrix |
k |
rank to use |
reducex |
reduce the input matrix to k-size subspace |
matrix is output
Avants BB
mat <- matrix(rnorm(300), ncol = 50) wmat <- whiten(mat) wmat2 <- whiten(mat, 2, TRUE)mat <- matrix(rnorm(300), ncol = 50) wmat <- whiten(mat) wmat2 <- whiten(mat, 2, TRUE)
This function performs matrix whitening on the input matrix 'X' using Singular Value Decomposition (SVD). Whitening transforms the input matrix into one where the covariance matrix is the identity matrix.
whiten_matrix(X)whiten_matrix(X)
X |
A numeric matrix to be whitened. The matrix should have observations as rows and features as columns. |
A list containing:
whitened_matrix |
The whitened matrix where the covariance matrix is the identity matrix. |
whitening_matrix |
The whitening transformation matrix used to whiten the input matrix. |
set.seed(123) X <- matrix(rnorm(1000), nrow = 20, ncol = 50) # Example with p = 50 and n = 20 result <- whiten_matrix(X) X_whitened <- result$whitened_matrix whitening_matrix <- result$whitening_matrix # Verify that the covariance matrix of the whitened matrix is close to identity cov_X_whitened <- cov(X_whitened) print(round(cov_X_whitened, 2))set.seed(123) X <- matrix(rnorm(1000), nrow = 20, ncol = 50) # Example with p = 50 and n = 20 result <- whiten_matrix(X) X_whitened <- result$whitened_matrix whitening_matrix <- result$whitening_matrix # Verify that the covariance matrix of the whitened matrix is close to identity cov_X_whitened <- cov(X_whitened) print(round(cov_X_whitened, 2))
A data frame label numbers and names for major white matter tracts.
wm_major_tractswm_major_tracts
A data frame with columns: Label, Description, side.
A data frame describing WMH evidence features.
wmh_evidencewmh_evidence
A data frame with columns: Value, Description.
Saves SiMLR outputs to a structured directory with relative paths for portability. Matrices and data frames are written as CSV files with row names included and stored in the manifest. Other R objects are saved as '.rds'. NULL components are recorded without files.
write_simlr(simlr_object, file_prefix, clear_dir = FALSE)write_simlr(simlr_object, file_prefix, clear_dir = FALSE)
simlr_object |
A named list containing SiMLR outputs (e.g., 'mysim$simlrX'). |
file_prefix |
A character string used as the prefix for the output directory. |
clear_dir |
Logical: if TRUE, clear the output directory before writing (default: FALSE). |
No return value, called for side effects.
This function writes each data frame in a list to a separate CSV file on disk, using the names of each data frame to create unique filenames.
write_simlr_data_frames(data_list, file_prefix)write_simlr_data_frames(data_list, file_prefix)
data_list |
A list of data frames to write to disk. |
file_prefix |
A character string to use as the prefix for the filenames. |
No return value, called for side effects.
mysim <- list(simlrX = list(v = list( data1 = data.frame(matrix(rnorm(147 * 171), nrow = 147, ncol = 171)), data2 = data.frame(matrix(rnorm(156 * 171), nrow = 156, ncol = 171)) ))) write_simlr_data_frames(mysim$simlrX$v, "output")mysim <- list(simlrX = list(v = list( data1 = data.frame(matrix(rnorm(147 * 171), nrow = 147, ncol = 171)), data2 = data.frame(matrix(rnorm(156 * 171), nrow = 156, ncol = 171)) ))) write_simlr_data_frames(mysim$simlrX$v, "output")
write antsrTransform to disk
writeAntsrTransform(transform, filename)writeAntsrTransform(transform, filename)
transform |
antsrTransform |
filename |
filename of transform (file extension is ".mat" for affine transforms) |
TRUE
trans <- c(3, 4, 5) tx <- createAntsrTransform(type = "Euler3DTransform", translation = trans) txfile <- tempfile(fileext = ".mat") writeAntsrTransform(tx, txfile)trans <- c(3, 4, 5) tx <- createAntsrTransform(type = "Euler3DTransform", translation = trans) txfile <- tempfile(fileext = ".mat") writeAntsrTransform(tx, txfile)
This function simplifies the steps of saving a population (image) analysis into an efficient hdf5 file, using the h5 library or to a directory. The population image data is stored as a matrix. Along with the matrix will be a data frame with population demographics. The number of matrix columns will be defined by a mask that the user should also supply. Finally, a boolean vector should be passed in that matches the images to the demographics. This function cannot check if the matching between demographics and images is correct and, as such, the user should take care in creating the inputs. WARNING: when using h5, the demographics file will currently be cast to a data.matrix so one should not reuse this file as the reference demographics file.
writeNormalizedPopulationData( demographics, imageMat, imageMask, imageBoolean, filename )writeNormalizedPopulationData( demographics, imageMat, imageMask, imageBoolean, filename )
demographics |
data frame that identifies the variables of interest. |
imageMat |
a matrix that stores the normalized image data. |
imageMask |
mask with number of non-zero entries defining the matrix columns. |
imageBoolean |
a vector of booleans with length equal to the number of rows in the demographics data frame and number of true values equal to the number of rows in the image matrix. |
filename |
output filename for hdf5 file (if .h5) or directory name. |
successOrFailure boolean
Avants BB
# read below will test out writing as well ## Not run: ilist <- getANTsRData("population") mask <- getMask(ilist[[1]]) imat <- imageListToMatrix(ilist, mask) demog <- data.frame( id = c("A", "B", "C", NA), age = c(11, 7, 18, 22), sex = c("M", "M", "F", "F") ) ibool <- c(TRUE, TRUE, TRUE, FALSE) tfn <- tempfile(fileext = ".h5") if (usePkg("hdf5r")) { demographics <- demog imageMat <- imat imageMask <- mask imageBoolean <- ibool filename <- tfn writeNormalizedPopulationData( demog, imat, mask, ibool, tfn ) } ## End(Not run)# read below will test out writing as well ## Not run: ilist <- getANTsRData("population") mask <- getMask(ilist[[1]]) imat <- imageListToMatrix(ilist, mask) demog <- data.frame( id = c("A", "B", "C", NA), age = c(11, 7, 18, 22), sex = c("M", "M", "F", "F") ) ibool <- c(TRUE, TRUE, TRUE, FALSE) tfn <- tempfile(fileext = ".h5") if (usePkg("hdf5r")) { demographics <- demog imageMat <- imat imageMask <- mask imageBoolean <- ibool filename <- tfn writeNormalizedPopulationData( demog, imat, mask, ibool, tfn ) } ## End(Not run)