Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

BrainData

BrainData

BrainData(data = None, *, Y = None, X = None, mask = None, masker = None, h5_compression = 'gzip', verbose = False, resample = True, interpolation = 'auto')

Represent neuroimaging data as vectors instead of three-dimensional matrices.

This representation makes it easier to perform data manipulation and analyses.

Parameters:

NameTypeDescriptionDefault
dataNeuroimaging data. Can be: - None (empty BrainData) - BrainData object - List of BrainData objects or file paths - File path (str/Path) to .nii/.nii.gz/.h5/.hdf5 - nibabel Nifti1Image object - URL to download data from - numpy array (1D (n_voxels,) for a single image or 2D (n_images, n_voxels) for a stack). The mask argument is required and must define the same number of in-mask voxels.None
maskBrain mask. Can be None (uses MNI template), a nibabel Nifti1Image, a file path (str/Path) to a mask file, or a template name string like '2mm-MNI152-2009c' (version: ‘fsl’ for default/, ‘a’ for nilearn/, ‘c’ for fmriprep/).None
maskernilearn masker object (e.g. ROI or searchlight extractor). Default will load data as voxels.None
YOptional per-image target/label values, stored as a polars DataFrame (.Y). Default None. If data is a BrainData with a .Y, that value is inherited when this is None.None
XOptional per-image design/feature values, stored as a polars DataFrame (.X). Default None. If data is a BrainData with an .X, that value is inherited when this is None.None
h5_compressionstr, default=‘gzip’Compression filter used when writing HDF5 (.h5/.hdf5) output.‘gzip’
verbosebool, default=FalseEmit informational messages during loading and other operations.False
resamplebool, default=TrueWhether to automatically resample data to mask space. If True, data is resampled to match mask spatial characteristics. If False, data must already be in mask space. Default True preserves backward compatibility with v0.5.1.True
interpolationstr, default=‘auto’Interpolation method for resampling. Options: ‘auto’ (detect based on data type; uses ‘nearest’ for discrete data like atlases/masks and ‘continuous’ for stat maps), ‘nearest’ (nearest-neighbor, preserves discrete values), ‘linear’ (linear interpolation), ‘continuous’ (higher-order spline, use for stat maps).‘auto’

Attributes:

NameTypeDescription
XDesign matrix / per-image covariates as a polars DataFrame.
YPer-image targets as a polars DataFrame.
data
design_matrix
dtypeGet data type of BrainData.data.
is_emptyboolCheck if BrainData.data is empty.
masker
shapeGet images by voxels shape.
sizeTotal number of elements in BrainData.data (numpy convention).
verbose

Methods:

NameDescription
alignAlign BrainData instance to target object using functional alignment.
appendAppend data to BrainData instance.
apply_maskMask BrainData instance using nilearn functionality.
astypeCast BrainData.data as type.
bootstrapBootstrap statistics using efficient online algorithms.
cluster_reportGenerate a cluster report with anatomical labels.
compute_contrastsCompute contrasts from fitted GLM results.
copyCreate a copy of a BrainData instance (data deep-copied).
create_emptyCreate a copy of BrainData with empty data array.
decomposeDecompose BrainData object.
detrendRemove linear trend from each voxel.
distanceCalculate distance between images within a BrainData() instance.
extract_roiExtract activity from mask or ROI atlas using NiftiLabelsMasker.
filterApply a Butterworth filter to data (wraps nilearn.signal.clean).
find_spikesIdentify spikes from Time Series Data.
fitFit a model to brain imaging data.
iplotInteractive WebGL brain viewer powered by niivue.
meanGet mean of each voxel or image.
medianGet median of each voxel or image.
multivariate_similarityPredict a BrainData spatial distribution from a linear combination.
plotPlot BrainData instance using nilearn visualization or matplotlib.
plot_flatmapPlot brain data on cortical flatmap.
plot_surfRender this BrainData on fsaverage surfaces as a tight 2×2 montage.
predictPredict voxel timeseries (encoding) or decode labels (MVPA).
r_to_zApply Fisher’s r-to-z transformation to each data element.
regionsExtract brain connected regions into separate regions.
reportGenerate a nilearn HTML report for a fitted GLM.
resample_toResample BrainData to match target image or resolution.
scaleScale data via mean scaling.
similarityCalculate similarity to a single BrainData or nibabel image.
smoothApply spatial smoothing using nilearn smooth_img().
standardizeStandardize BrainData() instance.
stdGet standard deviation of each voxel or image.
sumGet sum of each voxel or image.
temporal_resampleResample BrainData timeseries to a new target frequency or number of samples.
thresholdThreshold BrainData instance with optional cluster filtering.
to_niftiConvert BrainData Instance into Nifti Object.
transform_pairwiseTransform data into pairwise comparisons.
ttestOne-sample voxelwise t-test across images (axis 0).
ttest2Two-sample voxelwise t-test between two BrainData stacks.
upload_neurovaultUpload BrainData images and metadata to NeuroVault.
writeWrite out BrainData object to Nifti or HDF5 File.
z_to_rConvert z score back into r value for each element of data object.

Methods

align

align(target, method = 'procrustes', axis = 0, *, spatial_scale: str = 'whole_brain', roi_mask: str = None, radius_mm: float = 10.0)

Align BrainData instance to target object using functional alignment.

Parameters:

NameTypeDescriptionDefault
target(BrainData) object to align to.required
method(str) alignment method to use [‘probabilistic_srm’,‘deterministic_srm’,‘procrustes’]‘procrustes’
axis(int) axis to align on0
spatial_scalestr'whole_brain' (default), 'roi', or 'searchlight'. 'roi' is supported (per-parcel transforms + reassembly, requires roi_mask). 'searchlight' is not yet implemented (overlapping spheres have no canonical per-voxel transform).‘whole_brain’
roi_maskAtlas image used when spatial_scale='roi'.None
radius_mmfloatReserved for spatial_scale='searchlight'.10.0

Returns:

NameTypeDescription
out(dict) a dictionary containing transformed object, transformation matrix, and the shared response matrix

Examples:

>>> out = data.align(target, method='procrustes')
>>> out = data.align(target, method='probabilistic_srm')

append

append(data, ignore_attrs = False, **kwargs)

Append data to BrainData instance.

Parameters:

NameTypeDescriptionDefault
dataBrainData instance to append.required
ignore_attrs(bool) If True, skip concatenation of X and Y attributes. Useful when appending images where .X or .Y have different column counts. Default False.False
kwargsCurrently ignored. X/Y are concatenated with polars’ pl.concat(..., how="vertical_relaxed"), which takes no caller-supplied options.{}

Returns:

NameTypeDescription
BrainDataNew appended BrainData instance.

apply_mask

apply_mask(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:

NameTypeDescriptionDefault
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:

NameTypeDescription
masked(BrainData) masked BrainData object

astype

astype(dtype)

Cast BrainData.data as type.

Parameters:

NameTypeDescriptionDefault
dtypedatatype to convertrequired

Returns:

NameTypeDescription
BrainDataBrainData instance with new datatype

bootstrap

bootstrap(stat, *, n_samples = 5000, save_boots = False, percentiles = (2.5, 97.5), X_test = None, device = 'cpu', max_gpu_memory_gb = None, tail = 2, n_jobs = -1, random_state = None, progress_bar: bool = False)

Bootstrap statistics using efficient online algorithms.

Uses memory-efficient bootstrap infrastructure with CPU parallelization or GPU acceleration. Supports simple aggregation statistics and fitted model statistics (Ridge).

Parameters:

NameTypeDescriptionDefault
stat(str) Statistic to bootstrap. Options: Simple stats (‘mean’, ‘median’, ‘std’, ‘sum’, ‘min’, ‘max’) or Model stats (‘weights’ requires fitted Ridge model, ‘predict’ requires fitted Ridge model + X_test).required
n_samples(int) Number of bootstrap iterations. Default: 50005000
save_boots(bool) If True, store all bootstrap samples. Default: FalseFalse
percentiles(tuple) Percentiles for confidence intervals. Default: (2.5, 97.5)(2.5, 97.5)
X_test(np.ndarray, optional) Test features for ‘predict’ bootstrap.None
device(str) Compute device for Ridge bootstrap: ‘cpu’ (default), ‘gpu’ (PyTorch on CUDA/MPS if available), or ‘auto’ (GPU if present, else CPU). Ignored for simple stats. Default: ‘cpu’‘cpu’
max_gpu_memory_gb(float, optional) Explicit GPU memory budget in GB when device is ‘gpu’ or ‘auto’. None (default) measures the device.None
n_jobs(int) Number of CPU cores for parallelization. -1 means all CPUs.-1
random_state(int, optional) Random seed for reproducibilityNone
progress_barbool(bool) If True, show a progress bar. Default: FalseFalse

Returns:

TypeDescription
BrainData or dict: - For simple stats: Returns BrainData with bootstrap mean - For model stats: Returns dict with keys: ‘mean’, ‘std’, ‘Z’, ‘p’, ‘ci_lower’, ‘ci_upper’ (all BrainData objects) - If save_boots=True: Returns dict with ‘samples’ key containing all samples

Examples:

>>> boot = brain.bootstrap(stat='mean', n_samples=1000)
>>> brain.fit(X=dm, model='ridge', alpha=1.0)
>>> boot = brain.bootstrap(stat='weights', n_samples=1000)

cluster_report

cluster_report(*, stat_threshold: float | None = 3.0, cluster_threshold: int = 10, two_sided: bool = True, min_distance: float = 8.0, atlas: str | Sequence[str] | None = None, prob_threshold: float = 5.0) -> ClusterReport

Generate a cluster report with anatomical labels.

Identifies surviving clusters in the stat map (after voxel + extent thresholding), reports peak coordinates and sub-peaks, and labels each peak/cluster against one or more atlases.

Parameters:

NameTypeDescriptionDefault
stat_thresholdfloat | NoneVoxel-level threshold (e.g. z- or t-cutoff). None treats self as already thresholded.3.0
cluster_thresholdintMinimum cluster size in voxels.10
two_sidedboolReport negative clusters separately.True
min_distancefloatMinimum mm between sub-peaks within a cluster.8.0
atlasstr | Sequence [ str ] | NoneAtlas name or list of names (see list_atlases). Defaults to ("harvard_oxford", "aal", "schaefer_200").None
prob_thresholdfloatDrop probabilistic-atlas regions below this %.5.0

Returns:

TypeDescription
ClusterReportClusterReport with peaks,
ClusterReportclusters (polars DataFrames), and stat_img (BrainData).

compute_contrasts

compute_contrasts(contrasts, statistic = 't')

Compute contrasts from fitted GLM results.

This method computes contrasts as linear combinations of the GLM beta coefficients. Must be called after .fit(model=‘glm’, X=design_matrix) has been run.

Parameters:

NameTypeDescriptionDefault
contrastsCan be:
- str: A string specifying the contrast using column names e.g., “conditionA - conditionB” or “2*conditionA - conditionB - conditionC” - dict: Dictionary with contrast names as keys and contrast strings/vectors as values e.g., {“main_effect”: “conditionA - conditionB”, “interaction”: [1, -1, -1, 1]} - array: Numeric contrast vector matching the number of regressors e.g., [1, -1, 0, 0] for a 4-regressor model
required
statisticstrWhich statistic to return per contrast. One of "t" (default, t-statistic map), "z" (z-score), "p" (p-value), "beta" / "effect_size" (effect-size β map — use this when feeding a second-level group analysis), or "all" (a bundle dict {"beta", "t", "z", "p", "se"} of maps for one contrast). Default: "t".‘t’

Returns:

TypeDescription
BrainData or dict: A single contrast with a scalar statistic returns a BrainData map; with statistic="all" it returns a flat dict keyed by "beta"/"t"/"z"/"p"/"se". A dict of contrasts returns a dict keyed by contrast name (nested under the five keys when statistic="all").

Examples:

>>> brain.fit(model='glm', X=design_matrix)
>>> contrast1 = brain.compute_contrasts([0, 1, -1])
>>> contrast2 = brain.compute_contrasts("conditionA - conditionB")
>>> results = brain.compute_contrasts({
...     "A_vs_B": "conditionA - conditionB",
...     "avg_effect": [0, 0.5, 0.5],
... })
Note
  • String contrasts support coefficients: “2A - B" or "0.5A + 0.5*B”

  • Column names must match design matrix columns exactly (case-sensitive)

  • Contrast weights should sum to zero for proper inference in most cases

copy

copy()

Create a copy of a BrainData instance (data deep-copied).

The data array and most attributes are deep-copied, so mutating the copy’s data leaves the original untouched. Fitted state is shared, not copied: model_, X_, every glm_*/ridge_* result, and mask/ masker are held by reference (this avoids pickling unpicklable Backend objects — see __deepcopy__). Mutating those on the copy mutates the original; refit the copy if you need independent fit results.

Returns:

NameTypeDescription
BrainDataA copy with independent data but shared fitted state.

create_empty

create_empty()

Create a copy of BrainData with empty data array.

Returns:

NameTypeDescription
BrainDataA copy of this object with an empty data array.

decompose

decompose(*, method = 'pca', axis = 'voxels', n_components = None, **kwargs)

Decompose BrainData object.

Parameters:

NameTypeDescriptionDefault
method(str) Algorithm to perform decomposition types=[‘pca’,‘ica’,‘nnmf’,‘fa’,‘dictionary’,‘kernelpca’]‘pca’
axisdimension to decompose [‘voxels’,‘images’]‘voxels’
n_components(int) number of components. If None then retain as many as possible.None
**kwargsforwarded to the underlying sklearn decomposition estimator.{}

Returns:

NameTypeDescription
outputa dictionary of decomposition parameters

detrend

detrend(method = 'linear')

Remove linear trend from each voxel.

Parameters:

NameTypeDescriptionDefault
method(‘linear’,‘constant’, optional) type of detrending‘linear’

Returns:

NameTypeDescription
out(BrainData) detrended BrainData instance

distance

distance(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:

NameTypeDescriptionDefault
metric(str) type of distance metric (can use any scipy.spatial.distance metric supported by cdist)‘euclidean’
**kwargsAdditional metric options forwarded to scipy.spatial.distance.cdist (e.g. p for minkowski).{}
spatial_scalestrOne of 'whole_brain' (default), 'roi', or 'searchlight'. 'whole_brain' returns a single pairwise distance Adjacency between images. 'roi' requires roi_mask and returns a stacked Adjacency with one RDM per parcel and spatial_scale provenance attached for back-projection via Adjacency.to_brain(). 'searchlight' requires radius_mm (and is not yet implemented in this slice).‘whole_brain’
roi_maskAtlas image (BrainData / Nifti1Image / path) for spatial_scale='roi'.None
radius_mmfloatSearchlight radius in mm. Default 10.0.10.0

Returns:

NameTypeDescription
AdjacencySingle pairwise distance matrix for 'whole_brain'; stacked Adjacency (one matrix per parcel/searchlight) with spatial_scale set for 'roi' / 'searchlight'.

extract_roi

extract_roi(mask, method = 'mean', n_components = None)

Extract activity from mask or ROI atlas using NiftiLabelsMasker.

Parameters:

NameTypeDescriptionDefault
maskBrainData, nibabel image, or file path. Can be:
- Binary mask (extracts from single ROI) - Labeled atlas (extracts from multiple ROIs)
required
methodExtraction method (‘mean’, ‘median’, ‘pca’). Default: ‘mean’‘mean’
n_componentsIf method=‘pca’, number of components to returnNone

Returns:

TypeDescription
For binary mask: scalar or 1D array.
For labeled atlas: 1D or 2D array, or PCA components.

Examples:

>>> roi_values = brain.extract_roi(binary_mask)
>>> atlas_values = brain.extract_roi(atlas_mask)
>>> components = brain.extract_roi(mask, method='pca', n_components=5)

filter

filter(*, sampling_freq = None, high_pass = None, low_pass = None, **kwargs)

Apply a Butterworth filter to data (wraps nilearn.signal.clean).

Note

Unlike nilearn’s default, does not detrend or standardize. Pass detrend=True or standardize=True via kwargs to enable.

Parameters:

NameTypeDescriptionDefault
sampling_freqSampling freq in hertz (i.e. 1 / TR)None
high_passHigh pass cutoff frequencyNone
low_passLow pass cutoff frequencyNone
**kwargsAdditional arguments passed to nilearn.signal.clean{}

Returns:

NameTypeDescription
BrainDataFiltered BrainData instance

find_spikes

find_spikes(global_spike_cutoff = 3, diff_spike_cutoff = 3, *, TR: float | None = None, sampling_freq: float | None = None)

Identify spikes from Time Series Data.

Parameters:

NameTypeDescriptionDefault
global_spike_cutoffint or Nonecutoff to identify spikes in global signal in standard deviations, or None to skip.3
diff_spike_cutoffint or Nonecutoff to identify spikes in average frame difference in standard deviations, or None to skip.3
TRfloat | NoneRepetition time in seconds. Sets the returned DesignMatrix’s sampling_freq for downstream .append(...) / .convolve(). Pass exactly one of TR or sampling_freq.None
sampling_freqfloat | NoneSampling frequency in Hz (= 1/TR). See TR.None

Returns:

TypeDescription
DesignMatrix with one indicator column per detected spike TR, with
all spike columns pre-marked as confounds. A TR flagged by both
detectors yields a single column (named global_spike*); the
colliding detections are bitwise identical, so only the retained
name differs.

fit

fit(model = 'glm', *, X = None, cv = None, device = 'cpu', local_alpha = True, fit_intercept = False, inplace = True, scale = 'auto', standardize = 'auto', progress_bar = False, **kwargs)

Fit a model to brain imaging data.

Creates and fits a model from string specification. The brain data (self.data) is always used as the target variable. Model and results are stored for later use with predict().

Parameters:

NameTypeDescriptionDefault
modelstrModel type: ‘ridge’, ‘glm’, or future model names‘glm’
Xarray - like or DataFrameDesign matrix or feature matrixNone
cvint or sklearn CV splitterCross-validation specification (Ridge only). int → KFold(cv); pass a splitter object (e.g. KFold(5, shuffle=True), GroupKFold(8)) for non-contiguous folds. Generators (splitter.split(X)) are rejected.None
devicestr, default=‘cpu’Ridge only. Compute device for the ridge solve/CV: 'cpu' (NumPy), 'gpu' (PyTorch on CUDA/MPS when available), or 'auto' (GPU if present, else CPU). Ignored when model='glm'.‘cpu’
local_alphabool, default=TrueRidge only. If True, select α independently per voxel via solve_ridge_cv. If False, pick a single α shared across all voxels.True
fit_interceptbool, default=FalseRidge only. Forwarded to the Ridge model — center X and y on the training fold mean per fold and recover the intercept after.False
inplacebool, default=TrueIf True, mutate self and return self. If False, return a Fit dataclass with the results. self.data and the result attributes (ridge_* / glm_* / cv_results_) are left unchanged, but self.model_ and self.X_ (plus self.design_matrix for GLM) ARE updated on self so predict() / compute_contrasts() still work.True
scalebool or ‘auto’, default=‘auto’Apply percent-signal-change scaling before fitting via nilearn’s per-voxel mean_scaling. 'auto' → False for both models (PSC is opt-in). Redundant with standardize='zscore' (warns). Applied before standardize.‘auto’
standardizestr or None or ‘auto’, default=‘auto’Standardize each voxel across observations after scaling. 'center', 'zscore', or None. 'auto''zscore' for ridge, None for glm.‘auto’
progress_barboolDisplay a progress bar during fitting. Default: False.False
**kwargsdictAdditional arguments passed to model constructor{}

Returns:

TypeDescription
BrainData or Fit: If inplace=True, returns self (fitted BrainData). If inplace=False, returns Fit dataclass with results.
Note

After model="glm", the following per-regressor BrainData attributes are populated — one map per design-matrix column:

  • glm_betas: effect-size (β) maps.

  • glm_t: marginal t-statistic for each regressor.

  • glm_p: marginal p-value.

  • glm_se: standard error of β.

  • glm_r2: voxel-wise R².

glm_t[i] is a valid t-map for the trivial one-hot contrast on regressor i only. For contrasts across regressors ("A - B", [1, -1, 0, ...]) use compute_contrasts — you cannot correctly combine these per-regressor maps by hand because t-statistic arithmetic requires the off-diagonal elements of the parameter covariance matrix, which are not stored. Pass statistic="all" to get β/t/z/p/se for one contrast in a single call.

Examples:

>>> brain_data.fit(model='ridge', alpha=1.0, cv=5, X=features)
>>> fit = brain_data.fit(model='ridge', alpha=1.0, X=features, inplace=False)

iplot

iplot(*, view: str = 'ortho', threshold: float | str | None = None, lower: float | str | None = None, upper: float | str | None = None, autoscale: bool | tuple[float, float] = True, cmap: str = 'warm', bg_img: str | bool | None = None, atlas: str | Atlas | None = None, opacity: float = 1.0, outline: float = 0.0, colorbar: bool = True, controls: bool = True, **kwargs: bool)

Interactive WebGL brain viewer powered by niivue.

Renders inline in a live kernel (Jupyter, marimo) with live windowing (right-drag to set the threshold/contrast), slice scrolling, native 4D frame scrubbing, true 3D rendering, a stat-map colorbar, and optional nltools-atlas overlays. Static-built docs (plain Markdown) are not interactive; use plot there.

Returns a NiivueViewer widget. By default (controls=True) it renders an in-widget threshold slider above the viewer; the window is reactive through the cal_min / cal_max traits. Pass controls=False to hide the slider (right-drag windowing still works).

Thresholding is a divergent magnitude window: cal_min is the display floor (sub-floor voxels render transparent), cal_max the saturation point, with the positive limb using cmap and the negative limb its mirrored partner. Precedence: lower/upper win; otherwise threshold sets the floor; any unset edge comes from autoscale. The window is always computed in Python and passed to niivue explicitly, so the slider handles show exactly the window being rendered.

Parameters:

NameTypeDescriptionDefault
viewstr"ortho" (default), "axial", "coronal", "sagittal", or "render" (3D volume render). "surface" is no longer supported — use "render" or plot_flatmap / plot_surf.‘ortho’
thresholdfloat | str | NoneConvenience symmetric magnitude floor (→ cal_min). Accepts a percentile string ("95%") resolved over the finite nonzero magnitudes, consistent with threshold.None
lowerfloat | str | NoneWindow floor (→ cal_min). Overrides threshold. Accepts a percentile string.None
upperfloat | str | NoneWindow ceiling (→ cal_max). Overrides threshold. Accepts a percentile string.None
autoscalebool | tuple [ float , float ]Robust default window for the edges not set above. True (default): ceiling at the 98th percentile of the finite nonzero magnitudes — a couple of outlier voxels no longer wash out the whole map — with an epsilon floor (everything nonzero visible; threshold up from there). (lo_pct, hi_pct): floor/ceiling at those magnitude percentiles. False: the raw data extremes (the old behavior, made explicit).True
cmapstrniivue colormap for the positive limb (default "warm"). Common matplotlib names are auto-mapped with a warning.‘warm’
bg_imgstr | bool | NoneNone/True auto-loads the matching MNI template when the data is in standard space (else none); False disables the background; a path string uses that image.None
atlasstr | Atlas | NoneAtlas overlay — a registry name (e.g. "aal"), a loaded Atlas, or None. Deterministic atlases only; probabilistic atlases raise.None
opacityfloatStat-map (and filled-atlas) opacity in 0..1.1.0
outlinefloat> 0 draws atlas region boundaries of that width (stat map stays visible); 0 draws filled regions.0.0
colorbarboolShow the stat-map colorbar (default True). An explicit is_colorbar kwarg overrides this.True
controlsboolRender an in-widget threshold slider above the viewer (default True). False hides it; the viewer still supports niivue’s right-drag windowing. No extra dependency either way — the slider is native to the widget frontend.True
**kwargsForwarded verbatim to new Niivue(opts) (e.g. height, ConfigOptions like is_colorbar).{}

Returns:

TypeDescription
A NiivueViewer widget (an anywidget.AnyWidget). Its threshold
window is reactive via the cal_min / cal_max traits.

mean

mean(axis = 0, *, spatial_scale: str = 'whole_brain', roi_mask: str = None)

Get mean of each voxel or image.

Parameters:

NameTypeDescriptionDefault
axis0 = across images (default, returns BrainData), 1 = within images (returns array). Ignored when spatial_scale='roi'.0
spatial_scalestr'whole_brain' (default) preserves existing behavior. 'roi' requires roi_mask and returns a BrainData of the same shape with each voxel painted with its parcel’s mean per image (parcellation smoothing).‘whole_brain’
roi_maskAtlas image for spatial_scale='roi'.None

Returns:

TypeDescription
float/np.array/BrainData: Mean values.

median

median(axis = 0, *, spatial_scale: str = 'whole_brain', roi_mask: str = None)

Get median of each voxel or image.

Parameters:

NameTypeDescriptionDefault
axis0 = across images (default, returns BrainData), 1 = within images (returns array). Ignored when spatial_scale='roi'.0
spatial_scalestr'whole_brain' (default) or 'roi' (paints each voxel with its parcel’s median per image).‘whole_brain’
roi_maskAtlas image for spatial_scale='roi'.None

Returns:

TypeDescription
float/np.array/BrainData: Median values.

multivariate_similarity

multivariate_similarity(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:

NameTypeDescriptionDefault
imagesBrainData instance of weight maprequired
methodstrRegression method. Default: ‘ols’.‘ols’
tail2‘two’ (two-tailed, default) or 1

Returns:

NameTypeDescription
outdictionary of regression statistics in BrainData instances {‘beta’,‘t’,‘p’,‘df’,‘residual’}

plot

plot(*, method = 'glass', upper = None, lower = None, threshold = None, view = 'z', cut_coords = None, cmap = None, bg_img = None, ax = None, figsize = (8, 6), title = None, colorbar = True, save = None, stat = 'mean', limit = 3, **kwargs)

Plot BrainData instance using nilearn visualization or matplotlib.

Parameters:

NameTypeDescriptionDefault
methodstrVisualization type: ‘glass’, ‘slices’, ‘timeseries’, ‘histogram’‘glass’
upperstr / floatUpper threshold.None
lowerstr / floatLower threshold.None
thresholdfloatConvenience parameter for thresholding.None
viewstrFor method="slices", any non-empty combination of "x", "y", "z" (e.g. "xyz", "xz", "y"). Default: "z".‘z’
cut_coordslist or dictCut coordinates for multi-slice views. Takes precedence over view-based defaults. Either a list matching len(view) or a dict keyed by axis letter.None
cmapstrColormap name.None
bg_imgstr/nibabel imageBackground image.None
axAxesMatplotlib axis.None
figsizetupledefault figure size if no axis (8, 6)(8, 6)
titlestrPlot title.None
colorbarboolWhether to show colorbar. Default: True.True
savestrPath to save figure(s).None
statstrStatistic for timeseries plots. Default: ‘mean’.‘mean’
limitintMaximum number of images to render when this BrainData contains multiple maps and method is "glass" or "slices". Default: 3. Warns when more images exist than limit.3
**kwargsAdditional arguments passed to nilearn plot functions.{}

Returns:

TypeDescription
matplotlib.figure.Figure or list[matplotlib.figure.Figure]: A
single figure for single-image data; a list of figures for
multi-image data with method in {"glass", "slices"}
(one per image for glass; one per image-and-view pair for
slices).

plot_flatmap

plot_flatmap(*, threshold = None, cmap = 'RdBu_r', vmax = None, vmin = None, template = 'fsaverage5', with_curvature = True, curvature_contrast = 0.5, curvature_brightness = 0.5, transparency = 'auto', colorbar = True, colorbar_orientation = 'horizontal', figsize = (12, 6), title = None, radius_mm = 3.0, interpolation = 'linear', axes = None, save = None)

Plot brain data on cortical flatmap.

Parameters:

NameTypeDescriptionDefault
thresholdfloatValues below this absolute threshold are masked.None
cmapstrMatplotlib colormap. Default: ‘RdBu_r’.‘RdBu_r’
vmaxfloatMaximum value for colormap.None
vminfloatMinimum value for colormap.None
templatestrFreesurfer surface resolution. Default: ‘fsaverage5’.‘fsaverage5’
with_curvatureboolShow sulcal/gyral pattern. Default: True.True
curvature_contrastfloatContrast of curvature overlay. Default: 0.5.0.5
curvature_brightnessfloatMean brightness of curvature overlay. Default: 0.5.0.5
transparencyBrainData, Nifti1Image, str, or “auto”Binary mask used to render vertices outside the mask as transparent. "auto" (default) uses the instance’s .mask; pass None to disable masking.‘auto’
colorbarboolShow colorbar. Default: True.True
colorbar_orientationstr‘horizontal’ or ‘vertical’. Default: ‘horizontal’.‘horizontal’
figsizetupleFigure size as (width, height). Default: (12, 6).(12, 6)
titlestrFigure title.None
radius_mmfloatSampling radius in mm. Default: 3.0.3.0
interpolationstrInterpolation method. Default: ‘linear’.‘linear’
axesAxesExisting axes to plot on.None
savestrFile path to save figure.None

Returns:

TypeDescription
matplotlib.figure.Figure

plot_surf

plot_surf(*, hemi = 'both', view = 'montage', surface = 'pial', template = 'fsaverage5', threshold = None, cmap = 'RdBu_r', vmin = None, vmax = None, transparency = 'auto', bg_on_data = False, colorbar = True, colorbar_orientation = 'horizontal', figsize = (10, 8), title = None, radius_mm = 3.0, interpolation = 'linear', zoom = 1.2, axes = None, save = None)

Render this BrainData on fsaverage surfaces as a tight 2×2 montage.

Facade over plot_surf. See that function’s docstring for the full argument reference. Notable defaults: surface="pial", zoom=1.2, transparency="auto" (uses this instance’s .mask).

Returns:

TypeDescription
matplotlib.figure.Figure

predict

predict(*, y: np.ndarray | str | None = None, X: np.ndarray | None = None, spatial_scale: str = 'whole_brain', model: str = 'svm', cv: int | str = 5, standardize: bool = True, reduce: str | None = None, n_components: int | None = None, scoring: str = 'auto', groups: np.ndarray | str | None = None, roi_mask: np.ndarray | str | None = None, radius_mm: float = 10.0, inplace: bool = False, n_jobs: int = 1, random_state: int | None = None, progress_bar: bool = False)

Predict voxel timeseries (encoding) or decode labels (MVPA).

Dispatched by which of X or y is provided:

  1. Timeseries prediction (X provided): use a fitted ridge / GLM encoding model on self to predict voxel responses. Returns a fresh BrainData whose .data holds the predicted timeseries (composes directly with .plot(), .standardize() etc.). inplace has no effect in this mode.

  2. MVPA decoding (y provided, or resolvable from .Y): train a classifier or regressor with cross-validation. Returns a Predict dataclass. Spatial fields (weight_map, fold_weight_maps, final_weight_map, accuracy_map) are BrainData objects so result.weight_map.plot() works directly. Drop down to numpy via result.weight_map.data.

Labels travel with the data: when y is omitted and this object carries a single-column .Y frame, that column is decoded (y='name' picks a column of a multi-column .Y; groups accepts a .Y column name the same way). An object with both a fitted encoding model and a stored .Y refuses the no-argument call as ambiguous — pass y= or X= explicitly.

Field shapes by spatial_scale=:

With inplace=True, fields are attached to self with a predict_ prefix (e.g. self.predict_weight_map, self.predict_accuracy_map), mirroring bd.fit()'s glm_* / ridge_* naming.

Why weight_map is the all-data refit, not the CV mean: the mean of K per-fold coef_ vectors doesn’t correspond to any actual fitted estimator (each fold saw a different subset). The all-data refit is a single legitimate model with all the information used. CV gives the honest score; the refit gives the publishable map. The CV-mean is one line away if you want it: result.fold_weight_maps.data.mean(axis=0).

Parameters:

NameTypeDescriptionDefault
y( array - like , str )Labels (classification) or continuous targets (regression), shape (n_samples,), or the name of a .Y column. Triggers MVPA mode; omitted, it falls back to a single-column .Y.None
Xarray - likeFeatures for timeseries prediction, shape (n_samples, n_features). Triggers encoding mode.None
spatial_scalestrMVPA dispatch — 'whole_brain', 'searchlight', or 'roi'.‘whole_brain’
modelstr or sklearn estimatorAlgorithm. String shortcuts:
- Classification: 'svm' (LinearSVC), 'logistic', 'lda', 'ridge_classifier'. - Regression: 'ridge', 'lasso', 'svr'.
Or pass any sklearn estimator / Pipeline (e.g., make_pipeline(StandardScaler(), SelectKBest(k=500), LinearSVC())). When model is a sklearn Pipeline, standardize is auto-defaulted to False (with a warning) so we don’t wrap another StandardScaler around your pipeline. Pass standardize=True explicitly to override.
‘svm’
cvint, str, or sklearn CV splitterint → shuffled KFold (regression) or StratifiedKFold (classification), honoring groups via the Group variants; 'loo' (leave-one-out); 'logo' (leave-one-group-out — pass the grouping variable via groups, e.g. runs for leave-one-run-out); or any sklearn splitter.5
standardizeboolZ-score features per fold before fitting. Default True. Auto-flipped to False when model is a sklearn Pipeline (see model above).True
reducestrPer-fold dimensionality reduction. Currently only 'pca' supported. Default None. Weight maps are back-projected through PCA to voxel space.None
n_componentsintPCA components when reduce='pca'.None
scoringstrSklearn scoring string. Default 'auto''accuracy' if classifier, 'r2' if regressor.‘auto’
groups( array - like , str )Group labels for CV splitters that need them (e.g., leave-one-run-out), or the name of a .Y column holding them.None
roi_maskNifti1Image or path - likeAtlas image for spatial_scale='roi'.None
radius_mmfloatSearchlight radius in mm. Default 10.0.10.0
inplaceboolIf True, populate result fields as predict_* attributes on self and return self. Default False returns a fresh Predict.False
n_jobsintParallel jobs for searchlight / ROI. Default 1; searchlight on a real brain at higher n_jobs can be memory-heavy.1
random_stateintSeed for the shuffled fold splitter when cv is an int (MVPA mode). Default None (unseeded shuffle each call). Ignored when cv is a splitter object — set its own random_state instead.None
progress_barboolShow progress bar for searchlight / ROI.False

Returns:

TypeDescription
PredictBrainData: Predict dataclass when inplace=False; self (mutated, with predict_* attrs) when inplace=True.

Examples:

>>> result = brain.predict(y=labels, spatial_scale='whole_brain', cv=5)
>>> result.weight_map.plot()       # publishable map (all-data fit)
>>> result.mean_score              # honest CV-derived accuracy
>>> new_pred = result.estimator.predict(new_X)  # apply to new data
>>> result = brain.predict(y=labels, spatial_scale='searchlight',
...                        radius_mm=8.0, n_jobs=4)
>>> result.accuracy_map.plot()
>>> result = brain.predict(y=labels, spatial_scale='roi', roi_mask=atlas)
>>> top = result.roi_labels[result.mean_score.argsort()[::-1][:10]]
>>> result.accuracy_map.plot()  # brain-space view of the same map

Custom sklearn pipeline as model — standardize auto-defaults to False because we detect the Pipeline:

from sklearn.feature_selection import SelectKBest
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
pipe = make_pipeline(StandardScaler(), SelectKBest(k=500),
                     LinearSVC())
result = brain.predict(y=labels, model=pipe)

r_to_z

r_to_z()

Apply Fisher’s r-to-z transformation to each data element.

regions

regions(*, min_region_size = 1350, method = 'local_regions', smoothing_fwhm = 6, is_mask = False)

Extract brain connected regions into separate regions.

Parameters:

NameTypeDescriptionDefault
min_region_sizeintMinimum volume in mm3 for a region to be kept.1350
methodstrType of extraction method [‘connected_components’, ‘local_regions’].‘local_regions’
smoothing_fwhmscalarSmooth an image to extract more sparser regions.6
is_maskboolWhether to treat as boolean mask.False

Returns:

NameTypeDescription
BrainDataBrainData instance with extracted ROIs as data.

report

report(contrasts = None, **kwargs)

Generate a nilearn HTML report for a fitted GLM.

Must be called after fit(model='glm', ...). Renders the design matrix, requested contrast maps, and model parameters as a self-contained HTML report.

Parameters:

NameTypeDescriptionDefault
contrastsstr, list, or dictContrast(s) to render, same forms as compute_contrasts.None
**kwargsForwarded to nilearn’s generate_report (e.g. title, threshold, alpha).{}

Returns:

NameTypeDescription
HTMLReportnilearn report; call .save_as_html(path) or display it in a notebook.

Examples:

>>> brain.fit(model='glm', X=design_matrix)
>>> brain.report(contrasts='conditionA - conditionB').save_as_html('report.html')

resample_to

resample_to(*, img = None, resolution = None, interpolation = None)

Resample BrainData to match target image or resolution.

Parameters:

NameTypeDescriptionDefault
imgTarget image for resampling (nibabel Nifti1Image, str/Path, or None).None
resolutionTarget voxel size in mm (float/int for isotropic, or None).None
interpolationInterpolation method (‘nearest’, ‘linear’, ‘continuous’, or None).None

Returns:

NameTypeDescription
BrainDataNew BrainData instance with resampled data

scale

scale(scale_val = 100.0, axis = None)

Scale data via mean scaling.

Two scaling modes are available:

Parameters:

NameTypeDescriptionDefault
scale_val(int/float) Target value for the mean after scaling. Default 100.100.0
axis(int or None) None for grand-mean scaling (default), 0 for voxel-wise scaling.None

Returns:

NameTypeDescription
BrainDataNew BrainData instance with scaled data.

similarity

similarity(image, metric = 'correlation')

Calculate similarity to a single BrainData or nibabel image.

Parameters:

NameTypeDescriptionDefault
image(BrainData, nifti) image to evaluate similarityrequired
metric(str) Type of similarity [‘correlation’,‘pearson’,‘rank_correlation’,‘spearman’,‘dot_product’,‘cosine’]‘correlation’

Returns:

TypeDescription
float or np.ndarray: Similarity value(s).

smooth

smooth(fwhm)

Apply spatial smoothing using nilearn smooth_img().

Parameters:

NameTypeDescriptionDefault
fwhm(float) full width half maximum of gaussian spatial filterrequired

Returns:

TypeDescription
BrainData instance (copy with smoothed data)

standardize

standardize(*, axis = 0, method = 'center', suppress_warnings = False)

Standardize BrainData() instance.

Parameters:

NameTypeDescriptionDefault
axisint0 standardizes each voxel across observations (default). 1 standardizes each observation across voxels.0
methodstr‘center’ subtracts the mean (default). ‘zscore’ subtracts the mean and divides by standard deviation.‘center’
suppress_warningsboolIf True, suppress sklearn numerical warnings that occur when voxels have near-zero variance. Default: False.False

Returns:

NameTypeDescription
BrainDataStandardized BrainData instance.

std

std(axis = 0, *, spatial_scale: str = 'whole_brain', roi_mask: str = None)

Get standard deviation of each voxel or image.

Parameters:

NameTypeDescriptionDefault
axis0 = across images (default, returns BrainData), 1 = within images (returns array). Ignored when spatial_scale='roi'.0
spatial_scalestr'whole_brain' (default) or 'roi' (paints each voxel with its parcel’s std per image).‘whole_brain’
roi_maskAtlas image for spatial_scale='roi'.None

Returns:

TypeDescription
float/np.array/BrainData: Standard deviation values.

sum

sum(axis = 0)

Get sum of each voxel or image.

Parameters:

NameTypeDescriptionDefault
axis0 = across images (default, returns BrainData), 1 = within images (returns array)0

Returns:

TypeDescription
float/np.array/BrainData: Sum values.

temporal_resample

temporal_resample(*, sampling_freq = None, target = None, target_type = 'hz')

Resample BrainData timeseries to a new target frequency or number of samples.

Parameters:

NameTypeDescriptionDefault
sampling_freq(float) sampling frequency of data in hertzNone
target(float) upsampling targetNone
target_type(str) type of target can be [samples,seconds,hz]‘hz’

Returns:

TypeDescription
upsampled BrainData instance

threshold

threshold(*, upper = None, lower = None, binarize = False, coerce_nan = True, cluster_threshold = 0)

Threshold BrainData instance with optional cluster filtering.

Parameters:

NameTypeDescriptionDefault
upper(float or str) Upper cutoff for thresholding.None
lower(float or str) Lower cutoff for thresholding.None
binarizeboolreturn binarized image. Default False.False
coerce_nanboolcoerce nan values to 0s. Default True.True
cluster_thresholdintMinimum cluster size in voxels. Default 0.0

Returns:

TypeDescription
Thresholded BrainData object.

to_nifti

to_nifti()

Convert BrainData Instance into Nifti Object.

Returns:

TypeDescription
nibabel.Nifti1Image: Brain data as a NIfTI image.

transform_pairwise

transform_pairwise()

Transform data into pairwise comparisons.

Returns:

NameTypeDescription
BrainDataBrainData instance transformed into pairwise comparisons

ttest

ttest(*, popmean = 0.0, permutation = False, n_permute = 5000, tail = 2, return_null = False, n_jobs = -1, random_state = None)

One-sample voxelwise t-test across images (axis 0).

Tests whether the per-voxel mean across images differs from popmean. Operates on a stack of images (e.g. subject-level contrast maps) with shape (n_samples, n_voxels).

Parameters:

NameTypeDescriptionDefault
popmeanPopulation mean to test against. Default 0.0.0.0
permutationIf True, use sign-flip permutation test via one_sample_permutation_test.False
n_permuteNumber of permutations (used only when permutation=True). Default 5000.5000
tail2‘two’ (two-tailed, default) or 1
return_nullIf True, also return the null distribution. Default False.False
n_jobsNumber of parallel jobs. Default -1 (all cores).-1
random_stateRandom seed for reproducibility.None

Returns:

TypeDescription
dict with four BrainData keys:
- "mean": voxelwise mean across images (effect size). - "t": parametric one-sample t-statistic. - "z": signed z-score, sign(t) * norm.isf(p/2) — matches nilearn’s output_type='z_score'. - "p": parametric p-value, or empirical p when permutation=True.
The effect size is always returned alongside the inferential maps
so group-level code never has to recompute the mean.

Examples:

>>> # Stack of subject-level contrast maps
>>> result = contrast_maps.ttest()
>>> sig = result["p"].data < 0.05
>>> effect = result["mean"]       # for reporting magnitude
>>> z_map = result["z"]           # for nilearn-style thresholding
>>> # Permutation-based p-values; still reports t/z/mean
>>> result = contrast_maps.ttest(permutation=True, n_permute=5000)

ttest2

ttest2(other, equal_var = True, tail = 2)

Two-sample voxelwise t-test between two BrainData stacks.

Parameters:

NameTypeDescriptionDefault
otherBrainData to compare against. Must have the same number of voxels.required
equal_varIf True (default), standard two-sample t-test. If False, Welch’s t-test.True
tail2‘two’ (two-tailed, default) or 1

Returns:

NameTypeDescription
dict{"t": BrainData, "p": BrainData}.

upload_neurovault

upload_neurovault(*, access_token = None, collection_name = None, collection_id = None, img_type = None, img_modality = None, **kwargs)

Upload BrainData images and metadata to NeuroVault.

Adds any columns in self.X to image metadata. The index is used as the image name.

Parameters:

NameTypeDescriptionDefault
access_token(str, Required) Neurovault api access tokenNone
collection_name(str, Optional) name of new collection to createNone
collection_id(int, Optional) neurovault collection_id if adding images to existing collectionNone
img_type(str, Required) Neurovault map_typeNone
img_modality(str, Required) Neurovault image modalityNone

Returns:

NameTypeDescription
collection(pd.DataFrame) neurovault collection information

write

write(file_name)

Write out BrainData object to Nifti or HDF5 File.

Parameters:

NameTypeDescriptionDefault
file_namestr or PathOutput file path (.nii/.nii.gz for NIfTI, .h5/.hdf5 for HDF5).required

z_to_r

z_to_r()

Convert z score back into r value for each element of data object.