Title: | Routines for Common fMRI Processing Tasks |
---|---|
Description: | Supports fMRI (functional magnetic resonance imaging) analysis tasks including reading in 'CIFTI', 'GIFTI' and 'NIFTI' data, temporal filtering, nuisance regression, and aCompCor (anatomical Components Correction) (Muschelli et al. (2014) <doi:10.1016/j.neuroimage.2014.03.028>). |
Authors: | Amanda Mejia [aut, cre],
Damon Pham [aut] |
Maintainer: | Amanda Mejia <[email protected]> |
License: | GPL-3 |
Version: | 0.4.7 |
Built: | 2025-01-26 02:40:04 UTC |
Source: | https://github.com/mandymejia/fmritools |
Check if a data vector or matrix is all zeroes and ones. Option to also accept logical values.
all_binary(x, logical_ok = TRUE)
all_binary(x, logical_ok = TRUE)
x |
The data vector or matrix |
logical_ok |
Is a logical vector or matrix also acceptable? Default:
|
Logical. Is x
binary data?
Check if a data vector or matrix is all integers.
all_integers(x)
all_integers(x)
x |
The data vector or matrix |
Logical. Is x
all integers?
matrixConvert CIFTI, NIFTI, or GIFTI input to a matrix by
reading it in with the corresponding package and then separating the data
from the metadata. Also works with the intermediate R objects created from
reading these files:
"xifti"
objects from ciftiTools
,
"gifti"
objects from gifti
,
"nifti"
or "niftiExtension"
objects from oro.nifti
, and
"niftiImage"
objects from RNifti
.
For CIFTI files, only intents supported by ciftiTools
are supported:
dscalar
, dtseries
, and dlabel
. For NIFTI file or
NIFTI-intermediate R objects, the data will be vectorized/masked.
as.matrix_ifti( x, meta = FALSE, sortSub = FALSE, TbyV = TRUE, verbose = FALSE, ... )
as.matrix_ifti( x, meta = FALSE, sortSub = FALSE, TbyV = TRUE, verbose = FALSE, ... )
x |
The object to coerce to a matrix |
meta |
Return metadata too? Default: |
sortSub |
For CIFTI format input only. Sort subcortex by labels?
Default: |
TbyV |
Return the data matrix in |
verbose |
Print updates? Default: |
... |
If |
If !meta
, x
as a matrix. If meta
, a list of
length two: the first entry is x
as a matrix, and the second entry is
the metadata of x
.
Filter out frequencies within a given range using a Chebyshev Type II
stopband. Essentially a convenience wrapper for the
cheby2
function.
bandstop_filter(X, TR, f1, f2, Rs = 20)
bandstop_filter(X, TR, f1, f2, Rs = 20)
X |
A numeric matrix, with each column being a timeseries to apply
the stopband filter. For fMRI data, |
TR |
The time step between adjacent rows of |
f1 , f2
|
The frequency limits for the filter, in Hz. |
Rs |
The amount of attenuation of the stopband ripple, in dB |
The filtered data
if (requireNamespace("gsignal", quietly=TRUE)) { n_voxels = 1e4 n_timepoints = 100 X = cbind(arima.sim(n=100, list(ar=.6)), arima.sim(n=100, list(ar=.6))) Y = bandstop_filter(X, .72, .31, .43) }
if (requireNamespace("gsignal", quietly=TRUE)) { n_voxels = 1e4 n_timepoints = 100 X = cbind(arima.sim(n=100, list(ar=.6)), arima.sim(n=100, list(ar=.6))) Y = bandstop_filter(X, .72, .31, .43) }
Plot a matrix with graphics::image
. For fMRI data, this is the
"carpetplot" or grayplot coined by (Power, 2017). The graphics
and
grDevices
packages are required.
carpetplot( x, qcut = 0.1, fname = NULL, center = TRUE, scale = FALSE, colors = "gray255", sortSub = TRUE, ... )
carpetplot( x, qcut = 0.1, fname = NULL, center = TRUE, scale = FALSE, colors = "gray255", sortSub = TRUE, ... )
x |
The |
qcut |
Sets blackpoint at the Must be between 0 and .49. If |
fname |
A |
center , scale
|
Center and scale the data? If |
colors |
Colors will be assigned from the lowest to the highest data value, after
any clamping of the data values by |
sortSub |
If |
... |
Additional arguments to |
The image or NULL, invisibly
if a file was written.
Power, J. D. A simple but useful way to assess fMRI scan qualities. NeuroImage 154, 150-158 (2017).
Stacks carpetplots on top of one another by rbinding the matrices.
carpetplot_stack( x_list, center = TRUE, scale = FALSE, qcut = 0.1, match_scale = TRUE, nsep = 0, ... )
carpetplot_stack( x_list, center = TRUE, scale = FALSE, qcut = 0.1, match_scale = TRUE, nsep = 0, ... )
x_list |
List of data matrices |
center , scale
|
Center and scale the data? If |
qcut |
Sets blackpoint at the Must be between 0 and .49. If |
match_scale |
Match the scales of the carpetplots? Default: |
nsep |
Equivalent number of data locations for size of gap between carpetplots. Default: zero (no gap). |
... |
Additional arguments to |
NULL
, invisibly
Efficiently center columns of a matrix. (Faster than base::scale
.)
colCenter(X)
colCenter(X)
X |
The data matrix. Its columns will be centered. |
The centered data
Color palettes for fMRI data analysis tasks
color_palette(pal = "Beach")
color_palette(pal = "Beach")
pal |
|
A data.frame with two columns: "col"
has the hex code of color,
and "val"
has the placement of colors between zero and one.
The aCompCor algorithm for denoising fMRI data using noise ROIs data
CompCor( X, ROI_data = "infer", ROI_noise = NULL, noise_nPC = 5, noise_erosion = NULL, center = TRUE, scale = TRUE, nuisance = NULL )
CompCor( X, ROI_data = "infer", ROI_noise = NULL, noise_nPC = 5, noise_erosion = NULL, center = TRUE, scale = TRUE, nuisance = NULL )
X |
Wide numeric data matrix ( Or, a 4D array or NIFTI or file path to a NIFTI ( Or, a |
ROI_data |
Indicates the data ROI. Allowed arguments depend on If If If If |
ROI_noise |
Indicates the noise ROIs for aCompCor. Should be a list where
each entry corresponds to a distinct noise ROI. The names of the list should
be the ROI names, e.g. For all types of If If (If |
noise_nPC |
The number of principal components to compute for each noise ROI. Alternatively, values between 0 and 1, in which case they will represent the minimum proportion of variance explained by the PCs used for each noise ROI. The smallest number of PCs will be used to achieve this proportion of variance explained. Should be a list or numeric vector with the same length as |
noise_erosion |
The number of voxel layers to erode the noise ROIs by.
Should be a list or numeric vector with the same length as |
center , scale
|
Center the columns of the noise ROI data by their medians,
and scale by their MADs? Default: |
nuisance |
Nuisance signals to regress from each data column in addition
to the noise ROI PCs. Should be a |
First, the principal components (PCs) of each noise region of interest (ROI)
are calculated. For each ROI, voxels are centered and scaled
(can be disabled with the arguments center
and scale
),
and then the PCs are calculated via the singular value decomposition.
Next, aCompCor is performed to remove the shared variation between the noise ROI
PCs and each location in the data. This is accomplished by a nuisance regression
using a design matrix with the noise ROI PCs, any additional regressors specified
by nuisance
, and an intercept term. (To detrend the data and perform aCompCor
in the same regression, nuisance
can be set to DCT bases obtained with
the function dct_bases
.)
A list with entries "data"
, "noise"
, and potentially
"ROI_data"
.
The entry "data"
will be a V x T
matrix where each row corresponds to a
data location (if it was originally an array, the locations will be voxels in spatial
order). Each row will be a time series with each noise PC regressed from it. This entry
will be NULL
if there was no data.
The entry "noise"
is a list of noise PC scores, their corresponding variance,
and their ROI mask, for each noise ROI.
If the data ROI is not all TRUE
, the entry "ROI_data"
will have
the ROI mask for the data.
Behzadi, Y., Restom, K., Liau, J. & Liu, T. T. A component based noise correction method (CompCor) for BOLD and perfusion based fMRI. NeuroImage 37, 90-101 (2007).
Muschelli, J. et al. Reduction of motion-related artifacts in resting state fMRI using aCompCor. NeuroImage 96, 22-35 (2014).
CompCor_HCP
Wrapper to CompCor
for HCP-format data. Can be used to clean
the surface-based CIFTI data with aCompCor using the noise PCs and ROIs
calculated from the NIFTI fMRI data and NIFTI mask. Can also be used to just
obtain the noise PCs and ROIs without performing aCompCor, if the CIFTI
data is not provided.
CompCor_HCP( nii, nii_labels, ROI_noise = c("wm_cort", "csf"), noise_nPC = 5, noise_erosion = NULL, idx = NULL, cii = NULL, brainstructures = c("left", "right"), center = TRUE, scale = TRUE, DCT = 0, nuisance_too = NULL, verbose = FALSE )
CompCor_HCP( nii, nii_labels, ROI_noise = c("wm_cort", "csf"), noise_nPC = 5, noise_erosion = NULL, idx = NULL, cii = NULL, brainstructures = c("left", "right"), center = TRUE, scale = TRUE, DCT = 0, nuisance_too = NULL, verbose = FALSE )
nii |
|
nii_labels |
|
ROI_noise |
A list of numeric vectors. Each entry should represent labels
in
These default ROIs are based on this forum post: https://www.mail-archive.com/[email protected]/msg00931.html Default: |
noise_nPC |
The number of principal components to compute for each noise ROI. Alternatively, values between 0 and 1, in which case they will represent the minimum proportion of variance explained by the PCs used for each noise ROI. The smallest number of PCs will be used to achieve this proportion of variance explained. Should be a list or numeric vector with the same length as |
noise_erosion |
The number of voxel layers to erode the noise ROIs by.
Should be a list or numeric vector with the same length as |
idx |
A numeric vector indicating the timepoints to use, or
|
cii |
|
brainstructures |
Choose among "left", "right", and "subcortical".
Default: |
center , scale
|
Center the columns of the data by median, and scale the
columns of the data by MAD? Default: |
DCT |
Add DCT bases to the nuisance regression? Use an integer to
indicate the number of cosine bases. Use The data must be centered, either before input or with |
nuisance_too |
A matrix of nuisance signals to add to the nuisance
regression. Should have |
verbose |
Should occasional updates be printed? Default: |
The noise components, and if cii
is provided, the cleaned
surface-based data as a "xifti"
object.
Behzadi, Y., Restom, K., Liau, J. & Liu, T. T. A component based noise correction method (CompCor) for BOLD and perfusion based fMRI. NeuroImage 37, 90-101 (2007).
Muschelli, J. et al. Reduction of motion-related artifacts in resting state fMRI using aCompCor. NeuroImage 96, 22-35 (2014).
CompCor
Converts a sparse coordinate list to its non-sparse volumetric representation.
coordlist_to_vol(coords, fill = FALSE)
coordlist_to_vol(coords, fill = FALSE)
coords |
The sparse coordinate list. Should be a |
fill |
Logical or numeric fill value for the volume. Default:
|
The volumetric data
Remove empty (zero-valued) edge slices from a 3D array.
crop_vol(x)
crop_vol(x)
x |
The numeric 3D array to crop. |
A list of length two: "data"
, the cropped array, and
"padding"
, the number of slices removed from each edge of each
dimension.
Generate cosine bases for the DCT
dct_bases(T_, n)
dct_bases(T_, n)
T_ |
Length of timeseries |
n |
Number of cosine bases |
Matrix with cosine bases along columns
Convert between number of DCT bases and Hz of highpass filter
dct_convert(T_, TR, n = NULL, f = NULL) dct2Hz(T_, TR, n) Hz2dct(T_, TR, f)
dct_convert(T_, TR, n = NULL, f = NULL) dct2Hz(T_, TR, n) Hz2dct(T_, TR, f)
T_ |
Length of timeseries (number of timepoints) |
TR |
TR of the fMRI scan, in seconds (the time between timepoints) |
n |
Number of cosine bases |
f |
Hz of highpass filter |
Provide either n
or f
to calculate the other.
If only the total length of the scan is known, you can set that to TR
and use T_=1
.
If n
was provided, the highpass filter cutoff (Hz) is returned.
Otherwise, if f
was provided, the number of cosine bases is returned.
The result should be rounded before passing to dct_bases
Identify and interpolate outliers. See the AFNI documentation for 3dDespike for additional information.
despike_3D(Yt, c1 = 2.5, c2 = 4)
despike_3D(Yt, c1 = 2.5, c2 = 4)
Yt |
The data vector. |
c1 |
spike threshold. Default: |
c2 |
upper range of the acceptable deviation from the fit. Default:
|
if (requireNamespace("fda", quietly=TRUE) && requireNamespace("quantreg", quietly=TRUE)) { y <- rnorm(99) + cos(seq(99)/15)*3 y[20] <- 20 despike_3D(y) }
if (requireNamespace("fda", quietly=TRUE) && requireNamespace("quantreg", quietly=TRUE)) { y <- rnorm(99) + cos(seq(99)/15)*3 y[20] <- 20 despike_3D(y) }
Detrending with DCT or FFT
detrend(X, TR, f = 0.008, method = c("DCT", "FFT"))
detrend(X, TR, f = 0.008, method = c("DCT", "FFT"))
X |
A numeric matrix, with each column being a timeseries to detrend.
For fMRI data, |
TR |
The time step between adjacent rows of |
f |
The frequency of the highpass filter, in Hertz. Default: |
method |
|
Detrended X
detrend(matrix(rnorm(700), nrow=100), TR=.72)
detrend(matrix(rnorm(700), nrow=100), TR=.72)
Dilate a volumetric mask by a certain number of voxel layers. For each layer, any out-of-mask voxel adjacent to at least one in-mask voxel is added to the mask.
dilate_mask_vol(vol, n_dilate = 1, out_of_mask_val = NA, new_val = 1)
dilate_mask_vol(vol, n_dilate = 1, out_of_mask_val = NA, new_val = 1)
vol |
The 3D array to dilate. The mask to dilate is defined by all
values not in |
n_dilate |
The number of layers to dilate the mask by. Default:
|
out_of_mask_val |
A voxel is not included in the mask if and only if its
value is in this vector. Default: |
new_val |
Value for voxels newly added to the mask. Default: |
Diagonal voxels are not considered adjacent, i.e. the voxel at (0,0,0) is not adjacent to the voxels at (1,1,0) or (1,1,1), although it is adjacent to (1,0,0).
The dilated vol
. It is the same as vol
, but dilated
voxels are replaced with new_val
.
Performs dimension reduction and prewhitening based on probabilistic PCA using SVD. If dimensionality is not specified, it is estimated using the method described in Minka (2008).
dim_reduce(X, Q = NULL, Q_max = 100)
dim_reduce(X, Q = NULL, Q_max = 100)
X |
A numeric matrix, with each column being a centered timeseries.
For fMRI data, |
Q |
Number of latent dimensions to estimate. If |
Q_max |
Maximal number of principal components for automatic
dimensionality selection with PESEL. Default: |
A list containing the dimension-reduced data (data_reduced
, a
matrix), prewhitening/dimension reduction matrix (
H
,
a matrix) and its (pseudo-)inverse (
Hinv
, a
matrix), the noise variance (
sigma_sq
), the correlation matrix of the
dimension-reduced data (C_diag
, a matrix), and the
dimensionality (
Q
).
nT <- 30 nV <- 400 nQ <- 7 X <- matrix(rnorm(nV*nQ), nrow=nV) %*% diag(seq(nQ, 1)) %*% matrix(rnorm(nQ*nT), nrow=nQ) dim_reduce(X, Q=nQ)
nT <- 30 nV <- 400 nQ <- 7 X <- matrix(rnorm(nV*nQ), nrow=nV) %*% diag(seq(nQ, 1)) %*% matrix(rnorm(nQ*nT), nrow=nQ) dim_reduce(X, Q=nQ)
Dual Regression
dual_reg( BOLD, GICA, scale = c("local", "global", "none"), scale_sm_xifti = NULL, scale_sm_FWHM = 2, TR = NULL, hpf = 0.01, GSR = FALSE )
dual_reg( BOLD, GICA, scale = c("local", "global", "none"), scale_sm_xifti = NULL, scale_sm_FWHM = 2, TR = NULL, hpf = 0.01, GSR = FALSE )
BOLD |
Subject-level fMRI data matrix ( |
GICA |
Group-level independent components ( |
scale |
|
scale_sm_xifti , scale_sm_FWHM
|
Only applies if |
TR |
The temporal resolution of the data, i.e. the time between volumes,
in seconds. |
hpf |
The frequency at which to apply a highpass filter to the data
during pre-processing, in Hertz. Default: The highpass filter serves to detrend the data, since low-frequency variance is associated with noise. Highpass filtering is accomplished by nuisance regression of discrete cosine transform (DCT) bases. Note the |
GSR |
Center BOLD across columns (each image)? This
is equivalent to performing global signal regression. Default:
|
A list containing
the subject-level independent components S (),
and subject-level mixing matrix A (
).
nT <- 30 nV <- 400 nQ <- 7 mU <- matrix(rnorm(nV*nQ), nrow=nV) mS <- mU %*% diag(seq(nQ, 1)) %*% matrix(rnorm(nQ*nT), nrow=nQ) BOLD <- mS + rnorm(nV*nT, sd=.05) GICA <- mU dual_reg(BOLD=BOLD, GICA=mU, scale="local")
nT <- 30 nV <- 400 nQ <- 7 mU <- matrix(rnorm(nV*nQ), nrow=nV) mS <- mU %*% diag(seq(nQ, 1)) %*% matrix(rnorm(nQ*nT), nrow=nQ) BOLD <- mS + rnorm(nV*nT, sd=.05) GICA <- mU dual_reg(BOLD=BOLD, GICA=mU, scale="local")
Multiple regression for parcel data
dual_reg_parc( BOLD, parc, parc_vals, scale = c("local", "global", "none"), scale_sm_xifti = NULL, scale_sm_FWHM = 2, TR = NULL, hpf = 0.01, GSR = FALSE )
dual_reg_parc( BOLD, parc, parc_vals, scale = c("local", "global", "none"), scale_sm_xifti = NULL, scale_sm_FWHM = 2, TR = NULL, hpf = 0.01, GSR = FALSE )
BOLD |
Subject-level fMRI data matrix ( |
parc |
The parcellation as an integer vector. |
parc_vals |
The parcel values (keys) in desired order, e.g.
|
scale |
|
scale_sm_xifti , scale_sm_FWHM
|
Only applies if |
TR |
The temporal resolution of the data, i.e. the time between volumes,
in seconds. |
hpf |
The frequency at which to apply a highpass filter to the data
during pre-processing, in Hertz. Default: The highpass filter serves to detrend the data, since low-frequency variance is associated with noise. Highpass filtering is accomplished by nuisance regression of discrete cosine transform (DCT) bases. Note the |
GSR |
Center BOLD across columns (each image)? This
is equivalent to performing global signal regression. Default:
|
A list containing
the subject-level independent components S (),
and subject-level mixing matrix A (
).
Erode a volumetric mask by a certain number of voxel layers. For each layer, any in-mask voxel adjacent to at least one out-of-mask voxel is removed from the mask.
erode_mask_vol(vol, n_erosion = 1, out_of_mask_val = NA)
erode_mask_vol(vol, n_erosion = 1, out_of_mask_val = NA)
vol |
The 3D array to erode. The mask to erode is defined by all values
not in |
n_erosion |
The number of layers to erode the mask by. Default:
|
out_of_mask_val |
A voxel is not included in the mask if and only if its
value is in this vector. The first value of this vector will be used to
replace eroded voxels. Default: |
Diagonal voxels are not considered adjacent, i.e. the voxel at (0,0,0) is not adjacent to the voxels at (1,1,0) or (1,1,1), although it is adjacent to (1,0,0).
The eroded vol
. It is the same as vol
, but eroded
voxels are replaced with out_of_mask_val[1]
.
See help(package="fMRItools")
for a list of functions.
Maintainer: Amanda Mejia [email protected]
Authors:
Damon Pham [email protected] (ORCID)
Other contributors:
Mark Fiecas [email protected] [contributor]
Useful links:
Report bugs at https://github.com/mandymejia/fMRItools/issues
bptf
function from FSLCopy of bptf
highpass filter from FSL. The results are very similar
but not identical.
fsl_bptf(orig_data, HP_sigma = 2000)
fsl_bptf(orig_data, HP_sigma = 2000)
orig_data |
|
HP_sigma |
The frequency parameter for the highpass filter |
Sources: https://cpb-us-w2.wpmucdn.com/sites.udel.edu/dist/7/4542/files/2016/09/fsl_temporal_filt-15sywxn.m https://github.com/rordenlab/niimath/blob/master/src/core32.c
The data with detrended columns
Jenkinson, M., Beckmann, C. F., Behrens, T. E. J., Woolrich, M. W. & Smith, S. M. FSL. NeuroImage 62, 782-790 (2012).
fsl_bptf(matrix(rnorm(700), nrow=100))
fsl_bptf(matrix(rnorm(700), nrow=100))
Get the hat matrix from a design matrix.
hat_matrix(design)
hat_matrix(design)
design |
The |
Uses the QR decomposition.
The by
hat matrix
hat_matrix(cbind(seq(100), 1))
hat_matrix(cbind(seq(100), 1))
Infer fMRI data format
infer_format_ifti(BOLD, verbose = FALSE)
infer_format_ifti(BOLD, verbose = FALSE)
BOLD |
The fMRI data |
verbose |
Print the format? Default: |
A length-two vector. The first element indicates the format:
"CIFTI"
file path, "xifti"
object,
"GIFTI"
file path, "gifti"
object,
"NIFTI"
file path, "nifti"
object,
"RDS"
file path, or "data"
.
The second element indicates
the sub-format if relevant; i.e. the type of CIFTI or GIFTI file/object.
Vectorized version of infer_format_ifti
. Expects all inputs
to have the same format.
infer_format_ifti_vec(BOLD, verbose = FALSE)
infer_format_ifti_vec(BOLD, verbose = FALSE)
BOLD |
The vector of fMRI data, expected to be of one format |
verbose |
Print the format? Default: |
Raises an error if the elements of BOLD
do not share the same format.
A length-two vector. The first element indicates the format:
"CIFTI"
file path, "xifti"
object,
"GIFTI"
file path, "gifti"
object,
"NIFTI"
file path, "nifti"
object,
"RDS"
file path, or "data"
. The second element indicates
the sub-format if relevant; i.e. the type of CIFTI or GIFTI file/object.
Is this object the expected data type, and length one?
is_1(x, dtype = c("numeric", "logical", "character"))
is_1(x, dtype = c("numeric", "logical", "character"))
x |
The value to check |
dtype |
The data type. Default: |
TRUE
if x
is dtype
and length one.
Is this numeric vector constant?
is_constant(x, TOL = 1e-08)
is_constant(x, TOL = 1e-08)
x |
The numeric vector |
TOL |
minimum range of |
Is x
constant?
Is this an integer?
is_integer(x, nneg = FALSE)
is_integer(x, nneg = FALSE)
x |
The putative integer |
nneg |
Require |
Logical indicating whether x
is an integer
Is this object a positive number? (Or non-negative)
is_posNum(x, zero_ok = FALSE)
is_posNum(x, zero_ok = FALSE)
x |
The value to check |
zero_ok |
Is a value of zero ok? |
Logical indicating if x
is a single positive or non-negative
number
Returns the vectorized upper triangle of a square matrix
mat2UT(x)
mat2UT(x)
x |
A square matrix |
The vectorized upper triangle of x.
Checks if a user-defined character vector matches an expected character
vector. That is, they share the same lengths and entries in the same order.
For vectors of the same lengths, the result is all(a == b)
.
match_exactly( user, expected, fail_action = c("message", "warning", "stop", "nothing") )
match_exactly( user, expected, fail_action = c("message", "warning", "stop", "nothing") )
user |
Character vector of user input. |
expected |
Character vector of expected/allowed values. |
fail_action |
If any value in |
Attributes are ignored.
Logical. Do user
and expected
match?
Match each user input to an expected/allowed value. Raise a warning if either
several user inputs match the same expected value, or at least one could not
be matched to any expected value. ciftiTools
uses this function to
match keyword arguments for a function call. Another use is to match
brainstructure labels ("left", "right", or "subcortical").
match_input( user, expected, fail_action = c("stop", "warning", "message", "nothing"), user_value_label = NULL )
match_input( user, expected, fail_action = c("stop", "warning", "message", "nothing"), user_value_label = NULL )
user |
Character vector of user input. These will be matched to
|
expected |
Character vector of expected/allowed values. |
fail_action |
If any value in |
user_value_label |
How to refer to the user input in a stop or warning
message. If |
The matched user inputs.
Compute mean squares from variance decomposition
mean_squares(vd)
mean_squares(vd)
vd |
The variance decomposition |
The mean squares
Get mode of a data vector. But use the median instead of the mode if all data values are unique.
Mode(x)
Mode(x)
x |
The data vector |
The mode
Center the data across space and/or time, detrend, and scale, in that order. For dual regression, row centering is required and column centering is not recommended. Scaling and detrending depend on the user preference.
norm_BOLD( BOLD, center_rows = TRUE, center_cols = FALSE, scale = c("local", "global", "none"), scale_sm_xifti = NULL, scale_sm_FWHM = 2, TR = NULL, hpf = 0.01 )
norm_BOLD( BOLD, center_rows = TRUE, center_cols = FALSE, scale = c("local", "global", "none"), scale_sm_xifti = NULL, scale_sm_FWHM = 2, TR = NULL, hpf = 0.01 )
BOLD |
fMRI numeric data matrix ( |
center_rows , center_cols
|
Center BOLD data across rows (each data
location's time series) or columns (each time point's image)? Default:
|
scale |
|
scale_sm_xifti , scale_sm_FWHM
|
Only applies if |
TR |
The temporal resolution of the data, i.e. the time between volumes,
in seconds. |
hpf |
The frequency at which to apply a highpass filter to the data
during pre-processing, in Hertz. Default: The highpass filter serves to detrend the data, since low-frequency variance is associated with noise. Highpass filtering is accomplished by nuisance regression of discrete cosine transform (DCT) bases. Note the |
Normalized BOLD data matrix ()
Performs nuisance regression. Important note: the data and design matrix must both be centered, or an intercept must be included in the design matrix.
nuisance_regression(Y, design)
nuisance_regression(Y, design)
Y |
The |
design |
The |
The data after nuisance regression.
Y <- matrix(rnorm(700), nrow=100) design <- cbind(seq(100), 1) nuisance_regression(Y, design)
Y <- matrix(rnorm(700), nrow=100) design <- cbind(seq(100), 1) nuisance_regression(Y, design)
Pad a 3D array by a certain amount in each direction, along each dimension. This operation is like the opposite of cropping.
pad_vol(x, padding, fill = NA) uncrop_vol(x, padding, fill = NA)
pad_vol(x, padding, fill = NA) uncrop_vol(x, padding, fill = NA)
x |
A 3D array, e.g.
|
padding |
A |
fill |
Value to pad with. Default: |
The padded array
x <- array(seq(24), dim=c(2,3,4)) y <- pad_vol(x, array(1, dim=c(3,2)), 0) stopifnot(all(dim(y) == dim(x)+2)) stopifnot(sum(y) == sum(x)) z <- crop_vol(y)$data stopifnot(identical(dim(x), dim(z))) stopifnot(max(abs(z - x))==0)
x <- array(seq(24), dim=c(2,3,4)) y <- pad_vol(x, array(1, dim=c(3,2)), 0) stopifnot(all(dim(y) == dim(x)+2)) stopifnot(sum(y) == sum(x)) z <- crop_vol(y)$data stopifnot(identical(dim(x), dim(z))) stopifnot(max(abs(z - x))==0)
Efficient PCA for a tall matrix (many more rows than columns). Uses the SVD
of the covariance matrix. The dimensionality of the result can be preset
with Q
or estimated with PESEL.
PCA(X, center = TRUE, Q = NULL, Q_max = 100, Vdim = 0)
PCA(X, center = TRUE, Q = NULL, Q_max = 100, Vdim = 0)
X |
The tall numeric matrix for which to compute the PCA. For fMRI data,
|
center |
Center the columns of |
Q |
Number of latent dimensions to estimate. If |
Q_max |
Maximal number of principal components for automatic
dimensionality selection with PESEL. Default: |
Vdim |
Number of principal directions to obtain. Default: |
The SVD decomposition
U <- matrix(rnorm(900), nrow=300, ncol=3) V <- matrix(rnorm(15), nrow=3, ncol=5) PCA(U %*% V)
U <- matrix(rnorm(900), nrow=300, ncol=3) V <- matrix(rnorm(15), nrow=3, ncol=5) PCA(U %*% V)
Convert data values to percent signal.
pct_sig(X, center = median, by = c("column", "all"))
pct_sig(X, center = median, by = c("column", "all"))
X |
a |
center |
A function that computes the center of a numeric vector.
Default: |
by |
Should the center be measured individually for each |
X
with its columns normalized to percent signal. (A value of
85 will represent a -15% signal change.)
Plot a functional connectivity matrix.
plot_FC( FC, zlim = c(-1, 1), diag_val = NULL, title = "FC matrix", cols = color_palette("Beach"), cleg_ticks_by = diff(zlim)/2, cleg_digits = NULL, labels = NULL, lines = NULL, lines_col = "black", lines_lwd = 1, cex = 0.8 )
plot_FC( FC, zlim = c(-1, 1), diag_val = NULL, title = "FC matrix", cols = color_palette("Beach"), cleg_ticks_by = diff(zlim)/2, cleg_digits = NULL, labels = NULL, lines = NULL, lines_col = "black", lines_lwd = 1, cex = 0.8 )
FC |
The functional connectivity matrix, a square numeric matrix with values between -1 and 1. |
zlim |
The minimum and maximum range of the color scale. Default:
|
diag_val |
Set to |
title |
(Optional) Plot title. |
cols |
Character vector of colors for the color scale. Default:
|
cleg_ticks_by |
Spacing between ticks on the color legend. Default:
|
cleg_digits |
How many decimal digits for the color legend. Default:
|
labels |
A character vector of length |
lines |
Add lines to divide the FC matrix into submatrices? Default:
|
lines_col , lines_lwd
|
Color and line width of the |
cex |
Text size. Default: |
Tries RNifti::readNifti
, then oro.nifti::readNIfTI
. If
neither package is available an error is raised.
read_nifti(nifti_fname)
read_nifti(nifti_fname)
nifti_fname |
The file name of the NIFTI. |
For oro.nifti::readNIFTI
the argument
reorient=FALSE
will be used.
The NIFTI
Scale the columns of a matrix by dividing each column by its highest-magnitude value, and then subtracting its mean.
scale_design_mat(x, doRows = FALSE)
scale_design_mat(x, doRows = FALSE)
x |
A |
doRows |
Scale the rows instead? Default: |
The scaled design matrix
scale_design_mat(cbind(seq(7), 1, rnorm(7)))
scale_design_mat(cbind(seq(7), 1, rnorm(7)))
Centers and scales the columns of a matrix robustly
scale_med(mat, TOL = 1e-08, drop_const = TRUE, doRows = FALSE)
scale_med(mat, TOL = 1e-08, drop_const = TRUE, doRows = FALSE)
mat |
A numeric matrix. Its columns will be centered and scaled. |
TOL |
Columns with MAD below this value will be considered constant.
Default: |
drop_const |
Drop constant columns? Default: |
doRows |
Center and scale the rows instead? Default: |
Centers each column on its median, and scales each column by its median
absolute deviation (MAD). If there are constant-valued columns, they are
removed if drop_const
or set to NA
if !drop_const
, and
a warning is raised. If all columns are constant, an error is raised.
The input matrix with its columns centered and scaled.
Scale the BOLD timeseries
scale_timeseries( BOLD, scale = c("auto", "mean", "sd", "none"), transpose = TRUE )
scale_timeseries( BOLD, scale = c("auto", "mean", "sd", "none"), transpose = TRUE )
BOLD |
fMRI data as a locations by time ( |
scale |
Option for scaling the BOLD response. \code{"auto"} (default) will use \code{"mean"} scaling except if demeaned data is detected (if any mean is less than one), in which case \code{"mean"} scaling will scale the data to percent local signal change. \code{"sd"} scaling will scale the data by local standard deviation. \code{"none"} will only center the data, not scale it. |
transpose |
Transpose |
Scale to units of percent local signal change and centers
Flips all source signal estimates (S) to positive skew
sign_flip(x)
sign_flip(x)
x |
The ICA results: a list with entries |
x
but with positive skew source signals
Does the vector have a positive skew?
skew_pos(x)
skew_pos(x)
x |
The numeric vector for which to calculate the skew. Can also be a matrix, in which case the skew of each column will be calculated. |
TRUE
if the skew is positive or zero. FALSE
if the
skew is negative.
For each voxel in a 3D logical or numeric array, sum the values of the six neighboring voxels.
sum_neighbors_vol(arr, pad = 0)
sum_neighbors_vol(arr, pad = 0)
arr |
The 3D array. |
pad |
In order to compute the sum, the array is temporarily padded along
each edge with the value of |
Diagonal voxels are not considered adjacent, i.e. the voxel at (0,0,0) is not adjacent to the voxels at (1,1,0) or (1,1,1), although it is adjacent to (1,0,0).
An array with the same dimensions as arr
. Each voxel value
will be the sum across the immediate neighbors. If arr
was a logical
array, this value will be between 0 and 6.
Insert empty rows or columns to a matrix. For example, medial wall vertices can be added back to the cortex data matrix.
unmask_mat(x, mask, mask_dim = 1, fill = NA)
unmask_mat(x, mask, mask_dim = 1, fill = NA)
x |
The data matrix to unmask. |
mask |
The logical mask: the number of |
mask_dim |
Rows, |
fill |
The fill value for the inserted rows/columns. Default: |
The unmasked matrix.
From a matrix of vectorized data and an
image mask with
in-mask locations, create a list of
data arrays in which the mask locations are filled
in with the vectorized data values.
Consider using abind::abind
to merge the result into a single
array.
unvec_mat(x, mask, fill_value = NA)
unvec_mat(x, mask, fill_value = NA)
x |
|
mask |
|
fill_value |
Out-of-mask value in the output image. Default:
|
A list of masked values from x
x <- unvec_mat( cbind(seq(3), seq(2,4), seq(3,5)), matrix(c(rep(TRUE, 3), FALSE), ncol=2), 0 ) y <- array(c(1,2,3,0,2,3,4,0,3,4,5,0), dim=c(2,2,3)) stopifnot(identical(x[[1]], y[,,1])) stopifnot(identical(x[[2]], y[,,2])) stopifnot(identical(x[[3]], y[,,3]))
x <- unvec_mat( cbind(seq(3), seq(2,4), seq(3,5)), matrix(c(rep(TRUE, 3), FALSE), ncol=2), 0 ) y <- array(c(1,2,3,0,2,3,4,0,3,4,5,0), dim=c(2,2,3)) stopifnot(identical(x[[1]], y[,,1])) stopifnot(identical(x[[2]], y[,,2])) stopifnot(identical(x[[3]], y[,,3]))
Un-applies a mask to vectorized data to yield its volumetric representation.
The mask and data should have compatible dimensions: the number of rows in
dat
should equal the number of locations within the mask
.
unvec_vol(dat, mask, fill = NA)
unvec_vol(dat, mask, fill = NA)
dat |
Data matrix with locations along the rows and measurements along the columns. If only one set of measurements were made, this may be a vector. |
mask |
Volumetric binary mask. |
fill |
The value for locations outside the mask. Default: |
The 3D or 4D unflattened volume array
Returns the symmatric square matrix from a vector containing the upper triangular elements
UT2mat(x, diag = 0, LT = 0)
UT2mat(x, diag = 0, LT = 0)
x |
A vector containing the upper triangular elements of a square, symmetric matrix. |
diag |
A scalar value to use for the diagonal values of the matrix, or
|
LT |
A scalar value to use for the lower triangular values of the
matrix. Default: |
A symmetric matrix with the values of x
in the upper and
lower triangles and the value diag
on the diagonal.
Coerces design
to a numeric matrix, and optionally checks that the
number of rows is as expected. Sets constant-valued columns to 1, and scales
all other columns.
validate_design_mat(design, T_ = NULL)
validate_design_mat(design, T_ = NULL)
design |
The design matrix |
T_ |
the expected number of rows in |
The (modified) design matrix
Calculate the various ANOVA sums of squares for repeated measures data.
var_decomp(x, verbose = FALSE)
var_decomp(x, verbose = FALSE)
x |
The data as a 3D array: measurements by subjects by variables. (Alternatively, a matrix that is measurements by subjects, if only one variable exists.) |
verbose |
If |
The variance decomposition
Made for obtaining voxel locations in 3D space from the subcortical metadata of CIFTI data: the volumetric mask, the transformation matrix and the spatial units.
vox_locations(mask, trans_mat, trans_units = NULL)
vox_locations(mask, trans_mat, trans_units = NULL)
mask |
3D logical mask |
trans_mat |
Transformation matrix from array indices to spatial coordinates. |
trans_units |
Units for the spatial coordinates (optional). |
A list: coords
and trans_units
.