Skip to content

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.

Each image is flattened to its in-mask voxels, so a stack of images is a 2D (n_images, n_voxels) array. This representation makes it easier to perform data manipulation and analyses.

Parameters:

Name Type Description Default
data None | BrainData | list | str | Path | Nifti1Image | ndarray

Neuroimaging data. Accepts None (an empty BrainData), another BrainData, a list of BrainData objects or file paths, a file path to .nii/.nii.gz/.h5/.hdf5, a nibabel Nifti1Image, a URL to download from, or a numpy array (1D (n_voxels,) for a single image or 2D (n_images, n_voxels) for a stack). Array input requires mask, whose in-mask voxel count must match the array's last axis.

None
mask None | Nifti1Image | str | Path

Brain mask. None uses the MNI template; otherwise a nibabel Nifti1Image, a file 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
masker nilearn masker | None

nilearn masker object (e.g. ROI or searchlight extractor). Default None loads data as voxels.

None
Y DataFrame | ndarray | str | None

Optional 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
X DataFrame | ndarray | str | None

Optional 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_compression str

Compression filter used when writing HDF5 (.h5/.hdf5) output, 'gzip' (default) or 'lzf'.

'gzip'
verbose bool

Emit informational messages during loading and other operations. Default False.

False
resample bool

Whether to automatically resample data to mask space. If True (default), data is resampled to match the mask's spatial characteristics. If False, data must already be in mask space.

True
interpolation str

Interpolation method for resampling. 'auto' (default) detects based on data type — 'nearest' for discrete data like atlases/masks and 'continuous' for stat maps; 'nearest' (nearest-neighbor, preserves discrete values), 'linear' (linear interpolation), or 'continuous' (higher-order spline, use for stat maps).

'auto'

Attributes:

Name Type Description
data ndarray

In-mask voxel values, shape (n_voxels,) for a single image or (n_images, n_voxels) for a stack.

mask Nifti1Image

The brain mask every image is flattened against.

masker nilearn masker | None

Masker used to extract data, or None when data are plain voxels.

verbose bool

Whether informational messages are emitted.

X DataFrame

Design matrix / per-image covariates (possibly empty).

Y DataFrame

Per-image targets (possibly empty).

dtype dtype

Data type of data.

is_empty bool

Whether data holds no elements.

shape tuple[int, ...]

Images-by-voxels shape of data.

size int

Total number of elements in data (numpy convention).

Methods:

Name Description
align

Align BrainData instance to target object using functional alignment.

append

Append data to BrainData instance.

apply_mask

Restrict the data to a mask's support, leaving the grid unchanged.

astype

Cast BrainData.data as type.

bootstrap

Bootstrap a statistic and its uncertainty, on CPU workers or a GPU.

cluster_report

Generate a cluster report with anatomical labels.

compute_contrasts

Compute contrasts on a fitted GLM.

copy

Create an independent snapshot of a BrainData instance.

create_empty

Create a copy of BrainData with empty data array.

decompose

Decompose BrainData object.

detrend

Remove 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

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

find_spikes

Identify spikes from Time Series Data.

fit

Fit a model to brain imaging data.

iplot

Interactive WebGL brain viewer powered by niivue.

mean

Get mean of each voxel or image.

median

Get median of each voxel or image.

multivariate_similarity

Predict a BrainData spatial distribution from a linear combination.

plot

Plot BrainData instance using nilearn visualization or matplotlib.

plot_flatmap

Plot brain data on cortical flatmap.

plot_surf

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

predict

Predict voxel responses from a fitted model, or decode labels with MVPA.

r_to_z

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

regions

Extract brain connected regions into separate regions.

resample

Resample onto a new voxel grid, carrying the mask along.

scale

Scale data via mean scaling.

similarity

Calculate similarity to a single BrainData or nibabel image.

smooth

Apply spatial smoothing using nilearn smooth_img().

standardize

Standardize data by centering it, optionally scaling to unit variance.

std

Get standard deviation of each voxel or image.

sum

Get sum of each voxel or image.

temporal_resample

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

threshold

Threshold BrainData instance with optional cluster filtering.

to_nifti

Convert BrainData Instance into Nifti Object.

transform_pairwise

Transform data into pairwise comparisons.

ttest

Run a one-sample voxelwise t-test across images (axis 0).

upload_neurovault

Upload BrainData images and metadata to NeuroVault.

write

Write out BrainData object to Nifti or HDF5 File.

z_to_r

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

Attributes

X property writable

X

Design matrix / per-image covariates as a polars DataFrame.

Y property writable

Y

Per-image targets as a polars DataFrame.

dtype property

dtype

Get data type of BrainData.data.

is_empty property

is_empty: bool

Check if BrainData.data is empty.

shape property

shape

Get images by voxels shape.

size property

size

Total number of elements in BrainData.data (numpy convention).

Methods:

align

align(
    target,
    method="procrustes",
    axis=0,
    *,
    spatial_scale: str = "whole_brain",
    roi_mask=None,
)

Align BrainData instance to target object using functional alignment.

Parameters:

Name Type Description Default
target BrainData

Object to align to.

required
method str

Alignment method: 'probabilistic_srm', 'deterministic_srm', or 'procrustes'. Default 'procrustes'.

'procrustes'
axis int

Axis to align on. Default 0.

0
spatial_scale str

'whole_brain' (default) or 'roi' (per-parcel transforms + reassembly, requires roi_mask).

'whole_brain'
roi_mask BrainData | Nifti1Image | str | Path | None

Atlas image used when spatial_scale='roi'.

None

Returns:

Type Description
dict

'transformed', 'transformation_matrix' and 'common_model', plus 'disparity' and 'scale' for method='procrustes'. A value is a BrainData when its columns are a voxel axis matching the mask it carries, and a raw np.ndarray otherwise. 'procrustes' therefore returns all three as independently owned BrainData, with float 'disparity' and 'scale'. The SRM methods return 'transformed' (n_images, n_features) and 'common_model' (n_model_rows, n_features) as raw np.ndarray, since both span the common model's feature axis rather than voxels, and 'transformation_matrix' as a BrainData of n_features voxel maps. With axis=1 the transformation matrix spans images on its column axis for either method, so it is a raw np.ndarray too. With spatial_scale='roi' the result also carries 'roi_labels', 'transformed' is one stitched BrainData, 'transformation_matrix' and 'common_model' are dicts keyed by atlas label whose values follow the same rule on that parcel's mask, and 'disparity' and 'scale' are one-per-parcel arrays.

Raises:

Type Description
ValueError

If a value that must be returned as a BrainData has a column count other than the mask support — for example a 'procrustes' target with more voxels than the source, which zero-pads the source data to the target's width.

Examples:

# Hyperalign using procrustes transform
out = data.align(target, method='procrustes')

# Align using shared response model
out = data.align(target, method='probabilistic_srm')

# Project procrustes-aligned data back into original voxel space
original = np.dot(
    out['transformed'].data, out['transformation_matrix'].data.T
)

append

append(data, *, ignore_attrs=False)

Append data to BrainData instance.

Parameters:

Name Type Description Default
data BrainData

BrainData instance to append.

required
ignore_attrs bool

Clear both X and Y on the result when True. Otherwise, each metadata frame must be empty on both inputs or have compatible columns on both inputs. Default False.

False

Returns:

Type Description
BrainData

Independently owned data with concatenated row metadata.

Raises:

Type Description
ValueError

Metadata is present on only one input or has incompatible columns.

apply_mask

apply_mask(mask)

Restrict the data to a mask's support, leaving the grid unchanged.

The mask must be a single three-dimensional image on the same grid and with the same affine as this object. A mismatch raises: resample the mask or the data with resample() first, rather than relying on an implicit resample here.

Support is every voxel of mask greater than zero, and the mask defines the result's voxel axis on its own. Where it reaches past this object's current support the result gains those voxels with zero values, so a mask larger than self.mask widens the array rather than intersecting with it.

Parameters:

Name Type Description Default
mask BrainData | Nifti1Image | str | Path

Mask to apply.

required

Returns:

Type Description
BrainData

Masked BrainData object.

Raises:

Type Description
ValueError

If the mask is not a single 3-D image, or its shape or affine differs from this object's.

TypeError

If mask is not a BrainData, nibabel image, or file path.

astype

astype(dtype)

Cast BrainData.data as type.

Parameters:

Name Type Description Default
dtype dtype | type | str

Datatype to convert to.

required

Returns:

Type Description
BrainData

BrainData instance with new datatype.

bootstrap

bootstrap(
    statistic,
    *,
    X=None,
    X_test=None,
    n_samples=5000,
    confidence_level=0.95,
    device="cpu",
    memory_budget_gb=None,
    return_samples=False,
    n_jobs=-1,
    random_state=None,
    progress_bar: bool = False,
)

Bootstrap a statistic and its uncertainty, on CPU workers or a GPU.

Resamples rows with replacement and aggregates the replicates as they complete, into a running Welford variance plus just enough retained order statistics per output element to reproduce the exact percentile interval. What the run holds is that retained tail — about (1 - confidence_level) of the replicates per element — plus one dispatch window, rather than all n_samples maps. This is memory-efficient, not constant-memory: the tail still grows with n_samples, and return_samples=True keeps the whole distribution.

A Ridge bootstrap resamples the training features you pass as X together with self.data, using the same row indices for every feature space, and refits with the fitted model's selected alpha_ — and, for a banded model, its feature_space_weights_ — held fixed. It never reruns cross-validation or the banded random search. Fitting keeps no hidden copy of the training features, so X is required even when the same features were passed to fit.

Parameters:

Name Type Description Default
statistic str

Statistic to bootstrap. Basic aggregates: 'mean', 'median', 'std', 'sum', 'min', 'max' — each the corresponding NumPy reduction over rows, with 'std' at ddof=0. Model statistics (require a fitted Ridge): 'weights' or 'predict'.

required
X ndarray | Mapping[str, ndarray] | None

Training features in their original row order — a matrix for ordinary Ridge, a mapping with exactly the fitted feature-space names for banded Ridge. Required by both model statistics; rejected by the basic ones.

None
X_test ndarray | Mapping[str, ndarray] | None

Evaluation features for statistic='predict', in the same structure as X. Any row count is allowed.

None
n_samples int

Number of bootstrap replicates, at least two. Default 5000.

5000
confidence_level float

Confidence level of the reported interval, strictly between zero and one. Default 0.95. The bounds are the central percentile interval by linear interpolation, and they are elementwise marginal: the nominal level applies separately to each voxel, feature, or test row, with no simultaneous-coverage claim. A different level needs a new run unless return_samples=True kept the distribution.

0.95
device str

Compute device for the Ridge refits: 'cpu' (default) or 'gpu' (PyTorch on CUDA/MPS, or an error when neither is available). Basic statistics reject 'gpu'.

'cpu'
memory_budget_gb float | None

Working-memory budget in GB. It governs the output preflight and CPU-worker planning for every statistic, and GPU batch sizing for the Ridge ones. None (default) measures the device.

None
return_samples bool

Retain and return every replicate. Default False. It changes retention only, never interval semantics.

False
n_jobs int

CPU worker ceiling. -1 (default) means all cores; the planner may use fewer.

-1
random_state int | None

Random seed for reproducibility.

None
progress_bar bool

If True, show a progress bar. Default False.

False

Returns:

Type Description
BootstrapResult

estimate (the statistic on the unresampled full sample — for 'weights' the fitted coefficients, for 'predict' the full-data model at X_test), standard_error (the ddof=1 deviation across replicates), ci_lower and ci_upper, all BrainData of identical shape, plus samples as a NumPy array with the bootstrap axis first when return_samples=True.

Raises:

Type Description
ValueError

If statistic is unknown, a basic statistic is given X, X_test or device='gpu', a Ridge statistic is missing its features, the fitted model is not a Ridge, an argument is out of range, or the retained output cannot fit the memory budget.

Examples:

boot = brain.bootstrap('mean', n_samples=1000)
boot.estimate.plot()

brain.fit(model='ridge', X=features, ridge_alpha=1.0)
boot = brain.bootstrap('weights', X=features, n_samples=1000)
Note

This is an IID row bootstrap. Rows must be exchangeable for the interval to be meaningful; it implements no grouped, clustered, stratified, or block resampling, so an autocorrelated fMRI time series must not be treated as IID rows.

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:

Name Type Description Default
stat_threshold float | None

Voxel-level threshold (e.g. z- or t-cutoff). None treats self as already thresholded.

3.0
cluster_threshold int

Minimum cluster size in voxels.

10
two_sided bool

Report negative clusters separately.

True
min_distance float

Minimum mm between sub-peaks within a cluster.

8.0
atlas str | Sequence[str] | None

Atlas name or list of names (see list_atlases). Defaults to ("harvard_oxford", "aal", "schaefer_200").

None
prob_threshold float

Drop probabilistic-atlas regions below this %.

5.0

Returns:

Type Description
ClusterReport

Report with peaks and clusters (polars DataFrames) and stat_img (BrainData).

compute_contrasts

compute_contrasts(contrasts, *, inference=False)

Compute contrasts on a fitted GLM.

Call after fit(model='glm', X=design). The fitted Glm owns contrast parsing and inference; this method forwards each definition unchanged and wraps the results as BrainData maps.

A contrast is a string naming design columns with optional coefficients ("conditionA - conditionB", "2*A - B - C") or a numeric vector with one weight per column ([1, -1, 0, 0]). A mapping of names to those forms computes several at once and is the only batch form.

Parameters:

Name Type Description Default
contrasts str | array - like | Mapping

One contrast definition, or a mapping of names to definitions.

required
inference bool

If True, return ContrastResult records carrying effect, variance, standard error, t-statistic, z-score, one-sided p-value, and degrees of freedom. Default False.

False

Returns:

Type Description
BrainData | ContrastResult | dict

An effect map for one contrast, or a ContrastResult of maps when inference=True; a dictionary with the same keys for a mapping.

Raises:

Type Description
RuntimeError

If no model has been fitted.

ValueError

If the fitted model is not a Glm, or a contrast is invalid (see Glm.compute_contrasts).

Examples:

brain.fit(model='glm', X=design)

# Effect maps — what a second-level model consumes
effect = brain.compute_contrasts("conditionA - conditionB")
effects = brain.compute_contrasts({
    "A_vs_B": "conditionA - conditionB",
    "avg": [0, 0.5, 0.5],
})

# First-level inference
result = brain.compute_contrasts("conditionA - conditionB", inference=True)
result.statistic.plot(threshold=3.09)
Note

Contrast p-values are one-sided, following the nilearn/SPM directional-contrast convention; negate the contrast to test the other direction.

copy

copy()

Create an independent snapshot of a BrainData instance.

Data, metadata, mask state, and any fitted model/results are copied. Mutating either object after copying does not affect the other. Python's copy.copy() and copy.deepcopy() have the same semantics.

Returns:

Type Description
BrainData

An independent copy, including fitted state.

create_empty

create_empty()

Create a copy of BrainData with empty data array.

Returns:

Type Description
BrainData

A copy of this object with an empty data array.

decompose

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

Decompose BrainData object.

Parameters:

Name Type Description Default
method str

Decomposition algorithm: 'pca', 'ica', 'nnmf', 'fa', 'dictionary', or 'kernelpca'. Default 'pca'.

'pca'
axis str

Dimension to decompose: 'voxels' (default) or 'images'.

'voxels'
n_components int | None

Number of components. If None then retain as many as possible.

None
**kwargs dict

Forwarded to the underlying sklearn decomposition estimator.

{}

Returns:

Type Description
dict

A dictionary of decomposition parameters.

detrend

detrend(method='linear')

Remove linear trend from each voxel.

Parameters:

Name Type Description Default
method str

Type of detrending: 'linear' (default) or 'constant'.

'linear'

Returns:

Type Description
BrainData

Detrended BrainData instance.

distance

distance(
    metric="euclidean",
    *,
    spatial_scale: str = "whole_brain",
    roi_mask=None,
    radius: float = 10.0,
    **kwargs,
)

Calculate distance between images within a BrainData() instance.

Parameters:

Name Type Description Default
metric str

Distance metric — any scipy.spatial.distance metric supported by cdist. Default 'euclidean'.

'euclidean'
spatial_scale str

One 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 sorted nonzero atlas label present inside the source mask after nearest-neighbor resampling. 'searchlight' returns one RDM per source-mask voxel in mask order.

'whole_brain'
roi_mask BrainData | Nifti1Image | str | Path | None

Atlas image for spatial_scale='roi'.

None
radius float

Searchlight radius in mm. Default 10.0.

10.0
**kwargs dict

Additional metric options forwarded to scipy.spatial.distance.cdist (e.g. p for minkowski).

{}

Returns:

Type Description
Adjacency

Single pairwise distance matrix for 'whole_brain'; ordinary stack for 'roi' / 'searchlight'. Map per-matrix values externally using roi_to_brain_from_atlas with the aligned atlas and sorted surviving ROI labels, or nilearn.masking.unmask with the source mask for searchlights. Subset the mapping whenever selecting matrices from the returned stack.

extract_roi

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

Extract activity from mask or ROI atlas using NiftiLabelsMasker.

The mask may be binary (a single ROI) or a labeled atlas (one value per region, extracting from every ROI at once). Unlike apply_mask, this is an extraction convenience: mask is resampled onto this object's own grid with nearest-neighbor interpolation before extracting, so it need not already share this object's grid.

Parameters:

Name Type Description Default
mask BrainData | Nifti1Image | str | Path

Binary mask or labeled atlas to extract from, on any grid.

required
method str

Extraction method: 'mean' (default), 'median', or 'pca'.

'mean'
n_components int | None

Number of components to return when method='pca'.

None

Returns:

Type Description
float | ndarray

For a binary mask, a scalar (single image) or 1D array (multiple images). For a labeled atlas, a 1D array (single image), a 2D array of images x ROIs (multiple images), or the PCA components array when method='pca'.

Raises:

Type Description
ValueError

If, after resampling onto this object's grid, mask has no overlap with it.

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:

Name Type Description Default
sampling_freq float | None

Sampling frequency in hertz (i.e. 1 / TR).

None
high_pass float | None

High-pass cutoff frequency in hertz.

None
low_pass float | None

Low-pass cutoff frequency in hertz.

None
**kwargs dict

Additional arguments passed to nilearn.signal.clean.

{}

Returns:

Type Description
BrainData

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

Name Type Description Default
global_spike_cutoff int or None

cutoff to identify spikes in global signal in standard deviations, or None to skip.

3
diff_spike_cutoff int or None

cutoff to identify spikes in average frame difference in standard deviations, or None to skip.

3
TR float | None

Repetition time in seconds. Sets the returned DesignMatrix's sampling_freq for downstream .append(...) / .convolve(). Pass exactly one of TR or sampling_freq.

None
sampling_freq float | None

Sampling frequency in Hz (= 1/TR). See TR.

None

Returns:

Type Description
DesignMatrix

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,
    ridge_alpha=1.0,
    ridge_cv=None,
    ridge_search_iterations=100,
    ridge_dirichlet_concentration=(0.1, 1.0),
    ridge_device="cpu",
    ridge_memory_budget_gb=None,
    ridge_per_target_alpha=True,
    ridge_prefer_conservative_alpha=False,
    ridge_progress_bar=False,
    glm_noise_model="ols",
    glm_bins=100,
    glm_n_jobs=1,
    inplace=True,
    random_state=None,
)

Fit a model to brain imaging data.

self.data is always the response. The fitted estimator and its results are stored for later use with predict and, for a GLM, compute_contrasts.

Every model-specific option carries a glm_ or ridge_ prefix naming the estimator it configures; random_state keeps its bare name because both estimators accept it. Supplying a non-default option belonging to the estimator model did not select raises ValueError.

fit does not preprocess the response. Compose scale and standardize before calling it when you want them, so the fitted object stays in the response space you supplied.

Parameters:

Name Type Description Default
model str

'glm' (default) or 'ridge'.

'glm'
X DesignMatrix | array - like | Mapping

A precomputed DesignMatrix for a GLM; a feature matrix for ridge, or a mapping of feature-space names to matrices for banded ridge. Required.

None
ridge_alpha float | Sequence[float]

Ridge only. A positive scalar fits a fixed α and requires ridge_cv=None; a sequence selects α by cross-validation and requires ridge_cv. Default 1.0.

1.0
ridge_cv int | sklearn splitter | None

Ridge only. Cross-validation specification; int → unshuffled KFold(cv). Generators are rejected. Default None.

None
ridge_search_iterations int

Ridge only, banded. Sampled feature-space weight vectors. Default 100.

100
ridge_dirichlet_concentration float | Sequence[float]

Ridge only, banded. Dirichlet concentration for those candidate weights. Default (0.1, 1.0).

(0.1, 1.0)
ridge_device str

Ridge only. 'cpu' (default) or 'gpu'.

'cpu'
ridge_memory_budget_gb float | None

Ridge only. Working-memory budget in GB for the solver's internal batching. Default None (measure the device).

None
ridge_per_target_alpha bool

Ridge only. Select α per voxel (default True) or one shared α.

True
ridge_prefer_conservative_alpha bool

Ridge only. Select the largest α within one standard deviation of the best score. Default False.

False
ridge_progress_bar bool

Ridge only. Show a progress bar over the banded search. Default False.

False
glm_noise_model str

GLM only. 'ols' (default) or 'arN' for Nilearn's autoregressive model of order N.

'ols'
glm_bins int

GLM only. Nilearn's discretization of the estimated AR coefficients. Default 100.

100
glm_n_jobs int

GLM only. CPUs Nilearn uses for autoregressive groups; the default OLS fit does not use this path. Default 1.

1
inplace bool

If True (default), mutate self and return self. If False, fit and return an independent BrainData copy while leaving every part of self untouched.

True
random_state int | None

Seed shared by both estimators.

None

Returns:

Type Description
BrainData

Self when inplace=True; otherwise an independently owned fitted copy.

Note

A GLM fit attaches model_, glm_betas (one map per design column), glm_residual, glm_predicted, and glm_r2. glm_r2 is Nilearn's whitened variance ratio: conventional R-squared for an OLS fit whose design has an intercept, and a pseudo-R-squared in the whitened space for an autoregressive one. A GLM fit does not compute eager per-regressor t, p, or standard-error maps: ask for them one contrast at a time with compute_contrasts(..., inference=True), which uses the full per-voxel parameter covariance and is therefore correct for contrasts spanning several regressors.

Examples:

brain_data.fit(model='glm', X=design)
effect = brain_data.compute_contrasts('conditionA - conditionB')

fitted = brain_data.fit(
    model='ridge', 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 = True,
    symmetric: bool | Literal["auto"] = "auto",
    cmap: str | None = None,
    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,
)

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 uses positive and negative display limbs. cal_min is the magnitude floor and cal_max the positive saturation point; niivue receives the negative endpoints explicitly. By default, mixed maps use symmetric limbs while each sign in a one-sided map determines its own ceiling. The window is computed in Python, and the two controls show the shared floor and positive-limb ceiling.

Parameters:

Name Type Description Default
view str

"ortho" (default), "axial", "coronal", "sagittal", or "render" (3D volume render). "surface" is no longer supported — use "render" or plot_flatmap / plot_surf.

'ortho'
threshold float | str | None

Convenience symmetric magnitude floor (→ cal_min). Accepts a percentile string ("95%") resolved over the finite nonzero magnitudes, consistent with threshold.

None
lower float | str | None

Window floor (→ cal_min). Overrides threshold. Accepts a percentile string.

None
upper float | str | None

Window ceiling (→ cal_max). Overrides threshold. Accepts a percentile string.

None
autoscale bool

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 — and an epsilon floor, never above the smallest nonzero magnitude, so zeros render transparent and every real voxel stays visible (threshold up from there). False: the raw magnitude range from zero to the largest absolute value. For a custom percentile window pass lower/upper (e.g. lower="60%", upper="98%").

True
symmetric bool | Literal['auto']

"auto" (default) mirrors mixed-signed maps but lets each sign in a one-sided map determine its own ceiling. True always mirrors; False scales positive and negative limbs independently.

'auto'
cmap str | None

niivue colormap for the positive limb. The default uses niivue's red positive and blue negative palettes. Common matplotlib names are auto-mapped with a warning.

None
bg_img str | bool | None

None/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
atlas str | Atlas | None

Atlas overlay — a registry name (e.g. "aal"), a loaded Atlas, or None. Deterministic atlases only; probabilistic atlases raise.

None
opacity float

Stat-map (and filled-atlas) opacity in 0..1.

1.0
outline float

> 0 draws atlas region boundaries of that width (stat map stays visible); 0 draws filled regions.

0.0
colorbar bool

Show the stat-map colorbar (default True). An explicit is_colorbar kwarg overrides this.

True
controls bool

Render 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
**kwargs dict

Passed as niivue options. height configures the canvas and is_colorbar overrides colorbar.

{}

Returns:

Type Description
NiivueViewer

An anywidget.AnyWidget whose threshold window is reactive via the cal_min and cal_max traits.

Raises:

Type Description
TypeError

If autoscale is not a bool or symmetric is not True, False, or "auto".

mean

mean(axis=0)

Get mean of each voxel or image.

Parameters:

Name Type Description Default
axis int

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

0

Returns:

Type Description
float | ndarray | BrainData

Mean values.

median

median(axis=0)

Get median of each voxel or image.

Parameters:

Name Type Description Default
axis int

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

0

Returns:

Type Description
float | ndarray | BrainData

Median values.

multivariate_similarity

multivariate_similarity(images, 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
images BrainData | Nifti1Image | list

Predictor image(s) — a BrainData stack of weight maps or nibabel images.

required
tail int | str

2 or 'two' for two-tailed (default); 1 or 'one' for one-tailed (positive direction) regression p-values.

2

Returns:

Type Description
dict

Regression statistics as BrainData instances, keyed '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:

Name Type Description Default
method str

Visualization type: 'glass', 'slices', 'timeseries', 'histogram'

'glass'
upper str / float

Upper threshold.

None
lower str / float

Lower threshold.

None
threshold float | str

Absolute transparency cutoff. Percentile strings resolve over finite, nonzero magnitudes.

None
view str

For method="slices", any non-empty combination of "x", "y", "z" (e.g. "xyz", "xz", "y"). Default: "z".

'z'
cut_coords list or dict

Cut 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
cmap str

Colormap name. Defaults are sign-aware.

None
bg_img str/nibabel image

Background image.

None
ax Axes

Matplotlib axis.

None
figsize tuple

default figure size if no axis (8, 6)

(8, 6)
title str

Plot title.

None
colorbar bool

Whether to show colorbar. Default: True.

True
save str

Path to save figure(s).

None
stat str

Statistic for timeseries plots. Default: 'mean'.

'mean'
limit int

Maximum 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
**kwargs dict

Additional arguments passed to nilearn plot functions.

{}

Returns:

Type Description
Figure | list[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=None,
    vmax=None,
    vmin=None,
    template="fsaverage5",
    transparency="auto",
    colorbar=True,
    figsize=(12, 6),
    title=None,
    save=None,
)

Plot brain data on cortical flatmap.

Parameters:

Name Type Description Default
threshold float | str

Absolute cutoff or percentile string.

None
cmap str

Matplotlib colormap. Defaults are sign-aware.

None
vmax float

Maximum value; inferred from displayed data.

None
vmin float

Minimum value; inferred from displayed data.

None
template str

Freesurfer surface resolution. Default: 'fsaverage5'.

'fsaverage5'
transparency BrainData, 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'
colorbar bool

Show colorbar. Default: True.

True
figsize tuple

Figure size as (width, height). Default: (12, 6).

(12, 6)
title str

Figure title.

None
save str

File path to save figure.

None

Returns:

Type Description
Figure

The rendered figure.

plot_surf

plot_surf(
    *,
    hemi="both",
    view="montage",
    surface="pial",
    template="fsaverage5",
    threshold=None,
    cmap=None,
    vmin=None,
    vmax=None,
    transparency="auto",
    colorbar=True,
    figsize=(10, 8),
    title=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", transparency="auto" (uses this instance's .mask).

Returns:

Type Description
Figure

The rendered figure.

predict

predict(
    *,
    X: DesignMatrix | ndarray | Mapping[str, ndarray],
    y: None = None,
    estimator: str | BaseEstimator = "linear_svc",
    cv: int | BaseCrossValidator | None = None,
    groups: ndarray | str | None = None,
    scoring: str | Callable | None = None,
    spatial_scale: Literal[
        "whole_brain", "roi", "searchlight"
    ] = "whole_brain",
    roi_mask: Nifti1Image | str | Path | None = None,
    radius: float = 10.0,
    n_jobs: int = 1,
    progress_bar: bool = False,
) -> BrainData
predict(
    *,
    X: None = None,
    y: ndarray | str | None = None,
    estimator: str | BaseEstimator = "linear_svc",
    cv: int | BaseCrossValidator | None = None,
    groups: ndarray | str | None = None,
    scoring: str | Callable | None = None,
    spatial_scale: Literal[
        "whole_brain", "roi", "searchlight"
    ] = "whole_brain",
    roi_mask: Nifti1Image | str | Path | None = None,
    radius: float = 10.0,
    n_jobs: int = 1,
    progress_bar: bool = False,
) -> Predict
predict(
    *,
    X: DesignMatrix
    | ndarray
    | Mapping[str, ndarray]
    | None = None,
    y: ndarray | str | None = None,
    estimator: str | BaseEstimator = "linear_svc",
    cv: int | BaseCrossValidator | None = None,
    groups: ndarray | str | None = None,
    scoring: str | Callable | None = None,
    spatial_scale: Literal[
        "whole_brain", "roi", "searchlight"
    ] = "whole_brain",
    roi_mask: Nifti1Image | str | Path | None = None,
    radius: float = 10.0,
    n_jobs: int = 1,
    progress_bar: bool = False,
)

Predict voxel responses from a fitted model, or decode labels with MVPA.

Exactly one mode is resolved before any work happens:

  • an explicit y= runs MVPA decoding and returns a Predict;
  • an explicit X= predicts from the fitted Glm or Ridge and returns a new, independently owned BrainData;
  • with neither argument and a fitted model, an independent copy of the stored training predictions;
  • with neither argument, no fitted model, and exactly one .Y column, MVPA on that column.

Supplying both X and y, or a decoding argument on a fitted-model call, raises before prediction begins. A fitted model wins over an attached .Y on the no-argument call — pass y= explicitly to decode instead. predict never mutates the source and attaches nothing to it.

Labels travel with the data: y='name' picks a column of .Y, and groups accepts a .Y column name the same way. With an explicit X=, the estimator validates and aligns it: a DesignMatrix whose column names Glm.predict matches to the fitted order, or, for a banded Ridge, a mapping with exactly the fitted feature-space names in any order.

Parameters:

Name Type Description Default
X DesignMatrix | array - like | Mapping

Features for fitted-model prediction, shape (n_samples, n_features), or a mapping of feature-space names to matrices for a banded Ridge.

None
y array - like | str

Labels (classification) or continuous targets (regression), shape (n_samples,), or the name of a .Y column. Must be one-dimensional with one value per row; multioutput and multilabel targets are not accepted.

None
estimator str | sklearn estimator

A built-in shortcut — 'linear_svc', 'logistic_regression', 'linear_discriminant_analysis', 'ridge_classifier', 'ridge', 'lasso', 'linear_svr' — or any sklearn estimator or Pipeline, which is used exactly as supplied. Default 'linear_svc'. Every shortcut standardizes voxels inside each fold and then fits a linear estimator; a classification shortcut on a multiclass target is wrapped in OneVsRestClassifier, so every class gets its own signed map. A caller-supplied estimator is never wrapped and never has its multiclass strategy overridden — pass a OneVsRestClassifier to get one. Every preprocessing step, in every spatial scale, must be one of StandardScaler, PCA, VarianceThreshold, GenericUnivariateSelect, SelectPercentile, SelectKBest, SelectFpr, SelectFdr, SelectFwe, SelectFromModel, RFE, RFECV, SequentialFeatureSelector, None, or 'passthrough'. Whole-brain and ROI pipelines must also end in an estimator exposing coef_, since those two scales extract a weight map; searchlight builds none and does not require it.

'linear_svc'
cv int | sklearn splitter

None (the default) is a deterministic five-fold KFold (regression) or StratifiedKFold (classification); an int selects that many folds; an sklearn splitter is used as supplied. Test folds must partition the rows, so shuffle-split and repeated splitters raise. Rows ordered by condition make unshuffled contiguous folds degenerate — pass a shuffled splitter to control that, e.g. cv=KFold(n_splits=5, shuffle=True, random_state=0).

None
groups array - like | str

Group labels passed to the splitter (e.g. LeaveOneGroupOut for leave-one-run-out), one value per row, or the name of a .Y column holding them.

None
scoring str | callable

Follows scikit-learn's single-metric scoring contract. None (the default) uses the estimator's own score method; a scoring name or callable overrides it. Multimetric mappings are not accepted.

None
spatial_scale str

MVPA dispatch — 'whole_brain', 'roi', or 'searchlight'.

'whole_brain'
roi_mask Nifti1Image | path - like

Atlas image; required by, and only valid for, spatial_scale='roi'.

None
radius float

Searchlight sphere radius in millimeters; only valid for spatial_scale='searchlight'. Default 10.0.

10.0
n_jobs int

Parallel workers for the outer independent work of the selected spatial scale — cross-validation folds for whole-brain, parcels for ROI, spheres for searchlight. Default 1; every worker holds a copy of the data, so a real brain at higher n_jobs can be memory-heavy.

1
progress_bar bool

Show a progress bar for searchlight and ROI.

False

Returns:

Type Description
Predict | BrainData

A Predict record for MVPA; a new BrainData holding the predicted timeseries for fitted-model prediction. The record's spatial_scale says which of its fields carry values: whole-brain fills predictions, cv_folds, scores, estimator and weight_map; ROI fills scores, roi_labels, score_map and weight_map; searchlight fills score_map alone. classes accompanies any classifier and scoring records the scoring specification in every mode. mean_score and std_score are computed from scores on demand and do not exist for a searchlight result. weight_map holds one coefficient map for regression and binary classification (the signed map for classes[1] versus classes[0]) and one map per class, in classes order, for multiclass — never an average across classes. It is projected back to voxel units through the pipeline's fitted preprocessing, but centering is not undone, so raw_data @ weight_map does not reproduce the decision function; use result.estimator to predict.

Raises:

Type Description
ValueError

On both X and y, a decoding argument on a fitted-model call, an unknown estimator shortcut or spatial scale, a target or group vector that is not one value per row, cross-validation folds that do not partition the rows, a preprocessing step outside the supported set, or — for whole-brain and ROI decoding — a pipeline whose coefficients cannot be projected back onto the voxel axis.

TypeError

On a removed keyword, an estimator that is neither a shortcut name nor an object with fit/predict, or a cv that is neither None, an int, nor a splitter.

Examples:

Whole-brain decoding:

result = brain.predict(y=labels, cv=5)
result.weight_map.plot()   # the all-data refit — the publishable map
result.mean_score          # the cross-validated score
new_pred = result.estimator.predict(new_X)

Searchlight and ROI decoding:

result = brain.predict(
    y=labels, spatial_scale='searchlight', radius=8.0, n_jobs=4
)
result.score_map.plot()    # one score per sphere center

result = brain.predict(y=labels, spatial_scale='roi', roi_mask=atlas)
result.mean_score          # one score per parcel
result.score_map.plot()    # those scores painted into voxel space

Prediction from a fitted encoding model:

brain.fit(model='ridge', X=features)
predicted = brain.predict(X=new_features)

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:

Name Type Description Default
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'].

'local_regions'
smoothing_fwhm scalar

Smooth an image to extract more sparser regions.

6
is_mask bool

Whether to treat as boolean mask.

False

Returns:

Type Description
BrainData

BrainData instance with extracted ROIs as data.

resample

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

Resample onto a new voxel grid, carrying the mask along.

Exactly one of img or resolution is required. An img supplies only the target grid: its intensity values never define the output mask. The current mask is resampled onto the target grid with nearest-neighbor interpolation, so the result's voxel support is the source support expressed on the new grid. Row-aligned X and Y survive; fitted state does not.

Parameters:

Name Type Description Default
img Nifti1Image | str | Path | None

Target image supplying the grid to match.

None
resolution float | int | None

Target isotropic voxel size in mm.

None
interpolation str | None

Interpolation method for the data: 'nearest', 'linear', 'continuous', or None to use the instance's setting.

None

Returns:

Type Description
BrainData

New BrainData instance with resampled data and mask.

Raises:

Type Description
ValueError

If both img and resolution are None, both are provided, or resolution is not positive.

TypeError

If img is not a valid image type.

Examples:

coarse = brain.resample(resolution=3.0)
on_atlas_grid = brain.resample(img=atlas_img)

scale

scale(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. Voxel-wise scaling (axis=0) divides each voxel's time-series by its own temporal mean.

Parameters:

Name Type Description Default
scale_val int | float

Target value for the mean after scaling. Default 100.

100.0
axis int | None

None for grand-mean scaling (default), 0 for voxel-wise scaling.

None

Returns:

Type Description
BrainData

New BrainData instance with scaled data.

similarity

similarity(data, *, metric='correlation')

Calculate similarity to a single BrainData or nibabel image.

Parameters:

Name Type Description Default
data BrainData | Nifti1Image

Image to evaluate similarity against.

required
metric str

Type of similarity: 'correlation' (default), 'pearson', 'rank_correlation', 'spearman', 'dot_product', or 'cosine'.

'correlation'

Returns:

Type Description
float or ndarray

Similarity value(s).

smooth

smooth(fwhm)

Apply spatial smoothing using nilearn smooth_img().

Parameters:

Name Type Description Default
fwhm float

Full width at half maximum of the Gaussian spatial filter, in mm.

required

Returns:

Type Description
BrainData

Copy with smoothed data.

standardize

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

Standardize data by centering it, optionally scaling to unit variance.

Constant voxels (or observations) z-score to 0 rather than NaN.

Parameters:

Name Type Description Default
method str

'center' subtracts the mean (default); 'zscore' subtracts the mean and divides by the standard deviation.

'center'
axis int

0 standardizes each voxel across observations (default). 1 standardizes each observation across voxels.

0

Returns:

Type Description
BrainData

Standardized BrainData instance.

Raises:

Type Description
ValueError

If method is neither 'center' nor 'zscore'.

std

std(axis=0)

Get standard deviation of each voxel or image.

Parameters:

Name Type Description Default
axis int

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

0

Returns:

Type Description
float | ndarray | BrainData

Standard deviation values.

sum

sum(axis=0)

Get sum of each voxel or image.

Parameters:

Name Type Description Default
axis int

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

0

Returns:

Type Description
float | ndarray | 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:

Name Type Description Default
sampling_freq float | None

Sampling frequency of the data in hertz.

None
target float | None

Resampling target, interpreted per target_type.

None
target_type str

How to read target: 'hz' (default), 'samples', or 'seconds'.

'hz'

Returns:

Type Description
BrainData

Resampled BrainData instance.

threshold

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

Threshold BrainData instance with optional cluster filtering.

Parameters:

Name Type Description Default
upper float | str | None

Upper cutoff for thresholding; a percentile string like '95%' is accepted.

None
lower float | str | None

Lower cutoff for thresholding; a percentile string is accepted.

None
binarize bool

Return a binarized image. Default False.

False
coerce_nan bool

Coerce NaN values to 0s. Default True.

True
cluster_threshold int

Minimum cluster size in voxels. Default 0.

0

Returns:

Type Description
BrainData

Thresholded BrainData object.

to_nifti

to_nifti()

Convert BrainData Instance into Nifti Object.

Returns:

Type Description
Nifti1Image

Brain data as a NIfTI image.

transform_pairwise

transform_pairwise()

Transform data into pairwise comparisons.

Returns:

Type Description
BrainData

BrainData 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,
    progress_bar: bool = False,
)

Run a one-sample voxelwise t-test across images (axis 0).

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

Parameters:

Name Type Description Default
popmean float

Population mean to test against. Default 0.0.

0.0
permutation bool

If True, take p from a sign-flip permutation test on images - popmean. The reported t stays the observed parametric statistic. Default False.

False
n_permute int

Number of permutations, used only when permutation=True. Default 5000.

5000
tail int | str

2 or 'two' for two-tailed (default); 1 or 'one' for one-tailed (mean > popmean).

2
return_null bool

If True, also return the permutation null. Has no effect on the parametric path, which computes no null. Default False.

False
n_jobs int

Number of parallel jobs. Default -1 (all cores).

-1
random_state int | None

Random seed for reproducibility.

None
progress_bar bool

If True, show a progress bar. Default False.

False

Returns:

Type Description
dict

"mean", "t", "z" and "p" as independent BrainData images with observation metadata cleared. "mean" is the voxelwise mean minus popmean — the effect relative to the tested null, equal to the raw mean only when popmean=0. "t" is the observed one-sample t-statistic on both paths. "p" is parametric, or the empirical sign-flip p-value when permutation=True. "z" is the tail-aware normal score of p (sign(t) * norm.isf(p/2) two-tailed), matching nilearn's output_type='z_score'. With permutation=True and return_null=True the dict also holds "null_dist", an owned (n_permute, n_voxels) array of centered means in the units of "mean". Maps are unthresholded. Apply a cutoff or a multiple-comparison correction afterwards.

Raises:

Type Description
ValueError

If this BrainData contains fewer than 2 images.

Examples:

# Stack of subject-level contrast maps
result = contrast_maps.ttest()
effect = result["mean"]  # magnitude, for reporting
z_map = result["z"]  # for nilearn-style thresholding

# Threshold after testing, never inside it
from nltools.algorithms import threshold

z_thresh = threshold(result["z"], result["p"], thr=0.001)

# Permutation p-values, keeping the null for a custom correction
perm = contrast_maps.ttest(
    permutation=True, n_permute=5000, return_null=True, random_state=0
)
perm["null_dist"].shape  # → (5000, n_voxels)

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:

Name Type Description Default
access_token str

NeuroVault API access token. Required.

None
collection_name str | None

Name of a new collection to create.

None
collection_id int | None

NeuroVault collection_id when adding images to an existing collection.

None
img_type str

NeuroVault map_type. Required.

None
img_modality str

NeuroVault image modality. Required.

None
**kwargs dict

Additional image metadata forwarded to the NeuroVault API.

{}

Returns:

Type Description
dict

NeuroVault collection information.

write

write(file_name)

Write out BrainData object to Nifti or HDF5 File.

Parameters:

Name Type Description Default
file_name str or Path

Output 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.