analysis¶
BrainData analysis functions.
Standalone functions extracted from BrainData class methods for similarity, distance, masking, ROI extraction, filtering, thresholding, decomposition, alignment, smoothing, and other analytical operations.
Methods:
| Name | Description |
|---|---|
align | Align a BrainData instance to a target using functional alignment. |
align_per_roi | Per-parcel functional alignment + voxel-space reassembly. |
apply_mask | Mask BrainData instance using nilearn functionality. |
check_masks | Ensure two datasets use compatible masks, creating a union mask if needed. |
decompose | Decompose a BrainData object. |
detrend_data | Remove the linear trend from each voxel. |
distance | Calculate distance between images within a BrainData() instance. |
extract_roi | Extract activity from mask or ROI atlas using NiftiLabelsMasker. |
filter_data | Apply a Butterworth filter to data (wraps nilearn.signal.clean). |
find_spikes_data | Identify spikes from time-series data; see find_spikes. |
multivariate_similarity | Predict a BrainData spatial distribution from a linear combination. |
r_to_z | Apply Fisher’s r-to-z transformation to each data element. |
reduce_per_roi | Apply a reducer within each parcel and paint results back to voxel space. |
regions | Extract brain connected regions into separate regions. |
scale_data | Scale data via mean scaling. |
similarity | Calculate similarity to a single BrainData or nibabel image. |
smooth | Apply spatial smoothing using nilearn’s smooth_img. |
standardize | Standardize BrainData() instance. |
temporal_resample | Resample a BrainData time series to a target frequency or sample count. |
threshold_data | Threshold BrainData instance with optional cluster filtering. |
transform_pairwise_data | Transform BrainData into pairwise comparisons. |
z_to_r | Convert z score back into r value for each element of data object. |
Methods¶
align¶
align(bd, target, method = 'procrustes', axis = 0)Align a BrainData instance to a target using functional alignment.
Alignment type can be hyperalignment or Shared Response Model. When
using hyperalignment, target image can be another subject or an
already estimated common model. When using SRM, target must be a previously
estimated common model stored as a numpy array. Transformed data can be back
projected to original data using Transformation matrix.
See nltools.algorithms.align for aligning multiple BrainData instances
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
target | (BrainData) object to align to. | required | |
method | (str) alignment method to use [‘probabilistic_srm’,‘deterministic_srm’,‘procrustes’] | ‘procrustes’ | |
axis | (int) axis to align on (default: 0) | 0 |
Returns:
| Name | Type | Description |
|---|---|---|
out | (dict) a dictionary containing transformed object, transformation matrix, and the shared response matrix |
Examples:
Hyperalign using procrustes transform:
out = data.align(target, method=‘procrustes’)
Align using shared response model:
out = data.align(target, method=‘probabilistic_srm’, n_features=None)
Project aligned data into original data:
original_data = np.dot(out[‘transformed’].data,out[‘transformation_matrix’].T)
align_per_roi¶
align_per_roi(bd, target, *, method, axis, roi_mask)Per-parcel functional alignment + voxel-space reassembly.
For each atlas parcel, runs align() on the slice of bd and
target restricted to that parcel’s voxels and collects results.
The transformed field is reassembled into a single
BrainData of the same shape as the input (each voxel filled
with its parcel’s transformed value per image; voxels outside any
parcel = NaN). Per-parcel transform matrices and common-model
objects are kept as dicts keyed by atlas label, since matrices over
different voxel subsets can’t be painted into one image.
apply_mask¶
apply_mask(bd, mask, resample_mask_to_brain = False)Mask BrainData instance using nilearn functionality.
Note target data will be resampled into the same space as the mask. If you would like the mask resampled into the BrainData space, then set resample_mask_to_brain=True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
mask | (BrainData or nifti object) mask to apply to BrainData object. | required | |
resample_mask_to_brain | (bool) Will resample mask to brain space before applying mask (default=False). | False |
Returns:
| Name | Type | Description |
|---|---|---|
masked | (BrainData) masked BrainData object |
Note
Uses nilearn.masking.apply_mask for efficient, validated masking. Simplified from 47-line manual implementation to leverage nilearn’s Cython-optimized code with better validation and memory management.
check_masks¶
check_masks(bd, image)Ensure two datasets use compatible masks, creating a union mask if needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance | required | |
image | BrainData instance to compare masks with | required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple | (data2, image2) arrays with compatible masks |
decompose¶
decompose(bd, *, method = 'pca', axis = 'voxels', n_components = None, **kwargs)Decompose a BrainData object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
method | (str) Algorithm to perform decomposition types=[‘pca’,‘ica’,‘nnmf’,‘fa’,‘dictionary’,‘kernelpca’] | ‘pca’ | |
axis | dimension to decompose [‘voxels’,‘images’] | ‘voxels’ | |
n_components | (int) number of components. If None then retain as many as possible (default: None). | None | |
**kwargs | Additional keyword arguments passed to the decomposition algorithm. | {} |
Returns:
| Name | Type | Description |
|---|---|---|
output | a dictionary of decomposition parameters |
detrend_data¶
detrend_data(bd, method = 'linear')Remove the linear trend from each voxel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
method | (‘linear’,‘constant’, optional) type of detrending | ‘linear’ |
Returns:
| Name | Type | Description |
|---|---|---|
out | (BrainData) detrended BrainData instance |
distance¶
distance(bd, metric = 'euclidean', *, spatial_scale: str = 'whole_brain', roi_mask: str = None, radius_mm: float = 10.0, **kwargs: float)Calculate distance between images within a BrainData() instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
metric | (str) type of distance metric (can use any scipy.spatial.distance metric supported by cdist, e.g., ‘euclidean’, ‘cityblock’, ‘cosine’, ‘correlation’, ‘hamming’, ‘jaccard’, etc.) | ‘euclidean’ | |
spatial_scale | str | 'whole_brain' (default), 'roi', or 'searchlight'. See BrainData.distance. | ‘whole_brain’ |
roi_mask | Atlas for spatial_scale='roi'. | None | |
radius_mm | float | Searchlight radius for spatial_scale='searchlight'. | 10.0 |
**kwargs | Additional arguments passed to scipy.spatial.distance.cdist. | {} |
Returns:
| Name | Type | Description |
|---|---|---|
dist | (Adjacency) Whole-brain pairwise distance matrix, or a stacked Adjacency (one per parcel/searchlight) with spatial_scale provenance set. |
extract_roi¶
extract_roi(bd, mask, method = 'mean', n_components = None)Extract activity from mask or ROI atlas using NiftiLabelsMasker.
This method now uses nilearn’s NiftiLabelsMasker for efficient ROI extraction when dealing with labeled atlases (multiple ROIs).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
mask | BrainData, nibabel image, or file path. Can be: - Binary mask (extracts from single ROI) - Labeled atlas (extracts from multiple ROIs) | required | |
method | Extraction method (‘mean’, ‘median’, ‘pca’). Default: ‘mean’ Note: ‘median’ and ‘pca’ require additional computation after extraction | ‘mean’ | |
n_components | If method=‘pca’, number of components to return | None |
Returns:
| Type | Description |
|---|---|
| For binary mask: - Single image: scalar value - Multiple images: 1D array of values | |
| For labeled atlas: - Single image: 1D array (one value per ROI) - Multiple images: 2D array (images x ROIs) - If method=‘pca’: returns components array |
Examples:
>>> # Extract mean from binary mask
>>> roi_values = brain.extract_roi(binary_mask)
>>> # Extract from atlas
>>> atlas_values = brain.extract_roi(atlas_mask)
>>> # PCA extraction
>>> components = brain.extract_roi(mask, method='pca', n_components=5)filter_data¶
filter_data(bd, *, sampling_freq = None, high_pass = None, low_pass = None, **kwargs)Apply a Butterworth filter to data (wraps nilearn.signal.clean).
Does not default to detrending and standardizing like nilearn implementation, but this can be overridden using kwargs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
sampling_freq | Sampling freq in hertz (i.e. 1 / TR). Default: None. | None | |
high_pass | High pass cutoff frequency. Default: None. | None | |
low_pass | Low pass cutoff frequency. Default: None. | None | |
**kwargs | Additional arguments passed to nilearn.signal.clean Common options: - confounds: Confound timeseries to remove - sample_mask: Volumes to exclude (scrubbing) - detrend: Enable detrending (default False) - standardize: Enable standardization (default False) - ensure_finite: Replace NaN/inf (default False) | {} |
Returns:
| Name | Type | Description |
|---|---|---|
BrainData | Filtered BrainData instance |
See Also
nilearn.signal.clean documentation for all available options
find_spikes_data¶
find_spikes_data(bd, global_spike_cutoff = 3, diff_spike_cutoff = 3, *, TR = None, sampling_freq = None)Identify spikes from time-series data; see find_spikes.
multivariate_similarity¶
multivariate_similarity(bd, images, method = 'ols', tail = 2)Predict a BrainData spatial distribution from a linear combination.
The predictors may be other BrainData instances or nibabel images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance of data to be applied | required | |
images | BrainData instance of weight map | required | |
method | str | Regression method. Default: ‘ols’. | ‘ols’ |
Returns:
| Name | Type | Description |
|---|---|---|
out | dictionary of raw regression statistics (numpy arrays/scalars, not BrainData) with keys {‘beta’,‘t’,‘p’,‘df’,‘sigma’,‘residual’} |
r_to_z¶
r_to_z(bd)Apply Fisher’s r-to-z transformation to each data element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required |
Returns:
| Name | Type | Description |
|---|---|---|
BrainData | Transformed BrainData instance. |
reduce_per_roi¶
reduce_per_roi(bd, reducer, *, roi_mask)Apply a reducer within each parcel and paint results back to voxel space.
This performs spatial smoothing via parcellation using a reducer such as
np.mean.
For each image i and each parcel p, computes
reducer(bd.data[i, voxels-in-p]) and assigns that scalar to every
voxel in parcel p for image i. Voxels outside any parcel get
NaN. Output is a BrainData of the same shape as the input.
Used by BrainData.{mean,std,median}(spatial_scale='roi').
regions¶
regions(bd, *, min_region_size = 1350, method = 'local_regions', smoothing_fwhm = 6, is_mask = False)Extract brain connected regions into separate regions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
min_region_size | int | Minimum volume in mm3 for a region to be kept. | 1350 |
method | str | Type of extraction method [‘connected_components’, ‘local_regions’]. If ‘connected_components’, each component/region in the image is extracted automatically by labelling each region based upon the presence of unique features in their respective regions. If ‘local_regions’, each component/region is extracted based on their maximum peak value to define a seed marker and then using random walker segementation algorithm on these markers for region separation. | ‘local_regions’ |
smoothing_fwhm | scalar | Smooth an image to extract more sparser regions. Only works for method=‘local_regions’. | 6 |
is_mask | bool | Whether the BrainData instance should be treated as a boolean mask and if so, calls connected_label_regions instead. Default: False. | False |
Returns:
| Name | Type | Description |
|---|---|---|
BrainData | BrainData instance with extracted ROIs as data. |
scale_data¶
scale_data(bd, scale_val = 100.0, axis = None)Scale data via mean scaling.
Two scaling modes are available:
Grand-mean scaling (axis=None, default): Divides all values by the global mean across all voxels and timepoints. This is consistent with FSL and SPM behavior. Use scale_val=10000 for FSL-style scaling.
Voxel-wise scaling (axis=0): Divides each voxel’s time-series by its own temporal mean. This is AFNI-style scaling and can be useful when voxels have very different baseline intensities. Voxels with zero or near-zero mean are set to zero to avoid NaN/Inf.
When scale_val=100 (default), the result can be interpreted as something akin to (but not exactly) “percent signal change.”
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
scale_val | (int/float) Target value for the mean after scaling. Default 100. | 100.0 | |
axis | (int or None) Axis along which to compute the mean. None for grand-mean scaling (default, FSL/SPM style). 0 for voxel-wise scaling (AFNI style, each voxel scaled by its own temporal mean). | None |
Returns:
| Name | Type | Description |
|---|---|---|
BrainData | New BrainData instance with scaled data. |
Examples:
>>> # Grand-mean scaling (default)
>>> scaled = brain.scale(100.0)
>>>
>>> # Voxel-wise scaling (AFNI style)
>>> scaled = brain.scale(100.0, axis=0)similarity¶
similarity(bd, image, metric = 'correlation')Calculate similarity to a single BrainData or nibabel image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
image | (BrainData, nifti) image to evaluate similarity | required | |
metric | (str) Type of similarity [‘correlation’, ‘pearson’, ‘rank_correlation’, ‘spearman’, ‘dot_product’, ‘cosine’] | ‘correlation’ |
Returns:
| Type | Description |
|---|---|
| np.ndarray: Similarity values. |
smooth¶
smooth(bd, fwhm)Apply spatial smoothing using nilearn’s smooth_img.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
fwhm | (float) full width half maximum of gaussian spatial filter | required |
Returns:
| Type | Description |
|---|---|
| BrainData instance (copy with smoothed data) |
standardize¶
standardize(bd, *, axis = 0, method = 'center', suppress_warnings = False)Standardize BrainData() instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
axis | 0 for observations 1 for voxels (default: 0) | 0 | |
method | [‘center’,‘zscore’] (default: ‘center’) | ‘center’ | |
suppress_warnings | If True, suppress sklearn numerical warnings that occur when voxels have near-zero variance. (default: False) | False |
Returns:
| Name | Type | Description |
|---|---|---|
BrainData | Standardized BrainData instance. |
temporal_resample¶
temporal_resample(bd, *, sampling_freq = None, target = None, target_type = 'hz')Resample a BrainData time series to a target frequency or sample count.
Resample BrainData timeseries to a new target frequency or number of samples using Piecewise Cubic Hermite Interpolating Polynomial (PCHIP) interpolation. This function can up- or down-sample data.
Note: this function can use quite a bit of RAM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required | |
sampling_freq | (float) sampling frequency of data in hertz (default: None) | None | |
target | (float) upsampling target (default: None) | None | |
target_type | (str) type of target can be [samples,seconds,hz] (default: ‘hz’) | ‘hz’ |
Returns:
| Type | Description |
|---|---|
| upsampled BrainData instance |
threshold_data¶
threshold_data(bd, *, upper = None, lower = None, binarize = False, coerce_nan = True, cluster_threshold = 0)Threshold BrainData instance with optional cluster filtering.
Provide upper and lower values or percentages to perform two-sided thresholding. Binarize will return a mask image respecting thresholds if provided, otherwise respecting every non-zero value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upper | (float or str) Upper cutoff for thresholding. A string like '98%' resolves as a percentile over the finite nonzero voxels (via nltools.utils.resolve_threshold — zeros on a masked map are absence of data and would skew the percentile); can be None for one-sided thresholding. | None | |
lower | (float or str) Lower cutoff for thresholding. Same percentile semantics as upper; can be None for one-sided thresholding. | None | |
bd | BrainData instance. | required | |
binarize | bool | return binarized image respecting thresholds if provided, otherwise binarize on every non-zero value; default False | False |
coerce_nan | bool | coerce nan values to 0s; default True | True |
cluster_threshold | int | Minimum cluster size in voxels. If > 0, uses nilearn.image.threshold_img with cluster filtering. Band-pass filtering (both upper AND lower) not supported with cluster thresholding. Default 0 (disabled). | 0 |
Returns:
| Type | Description |
|---|---|
| Thresholded BrainData object. |
Note
When cluster_threshold=0 (default), uses fast path for basic thresholding. When cluster_threshold>0, uses nilearn for cluster filtering. Band-pass filtering (unique nltools feature) preserved when cluster_threshold=0.
transform_pairwise_data¶
transform_pairwise_data(bd)Transform BrainData into pairwise comparisons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required |
Returns:
| Name | Type | Description |
|---|---|---|
BrainData | BrainData instance transformed into pairwise comparisons. |
z_to_r¶
z_to_r(bd)Convert z score back into r value for each element of data object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bd | BrainData instance. | required |
Returns:
| Name | Type | Description |
|---|---|---|
BrainData | Transformed BrainData instance. |