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
|
mask
|
None | Nifti1Image | str | Path
|
Brain mask. |
None
|
masker
|
nilearn masker | None
|
nilearn masker object (e.g. ROI or
searchlight extractor). Default |
None
|
Y
|
DataFrame | ndarray | str | None
|
Optional per-image target/label
values, stored as a polars DataFrame ( |
None
|
X
|
DataFrame | ndarray | str | None
|
Optional per-image design/feature
values, stored as a polars DataFrame ( |
None
|
h5_compression
|
str
|
Compression filter used when writing HDF5
( |
'gzip'
|
verbose
|
bool
|
Emit informational messages during loading and other
operations. Default |
False
|
resample
|
bool
|
Whether to automatically resample data to mask space.
If |
True
|
interpolation
|
str
|
Interpolation method for resampling. |
'auto'
|
Attributes:
| Name | Type | Description |
|---|---|---|
data |
ndarray
|
In-mask voxel values, shape |
mask |
Nifti1Image
|
The brain mask every image is flattened against. |
masker |
nilearn masker | None
|
Masker used to extract data, or |
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 |
is_empty |
bool
|
Whether |
shape |
tuple[int, ...]
|
Images-by-voxels shape of |
size |
int
|
Total number of elements in |
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 |
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¶
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: |
'procrustes'
|
axis
|
int
|
Axis to align on. Default 0. |
0
|
spatial_scale
|
str
|
|
'whole_brain'
|
roi_mask
|
BrainData | Nifti1Image | str | Path | None
|
Atlas image
used when |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a value that must be returned as a |
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 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 ¶
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 |
astype ¶
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:
|
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 |
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 |
0.95
|
device
|
str
|
Compute device for the Ridge refits: |
'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
|
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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).
|
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 |
None
|
prob_threshold
|
float
|
Drop probabilistic-atlas regions below this %. |
5.0
|
Returns:
| Type | Description |
|---|---|
ClusterReport
|
Report with |
compute_contrasts ¶
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 |
False
|
Returns:
| Type | Description |
|---|---|
BrainData | ContrastResult | dict
|
An effect map for one contrast,
or a |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no model has been fitted. |
ValueError
|
If the fitted model is not a |
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 ¶
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 a copy of BrainData with empty data array.
Returns:
| Type | Description |
|---|---|
BrainData
|
A copy of this object with an empty data array. |
decompose ¶
Decompose BrainData object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Decomposition algorithm: |
'pca'
|
axis
|
str
|
Dimension to decompose: |
'voxels'
|
n_components
|
int | None
|
Number of components. If |
None
|
**kwargs
|
dict
|
Forwarded to the underlying sklearn decomposition estimator. |
{}
|
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary of decomposition parameters. |
detrend ¶
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 |
'euclidean'
|
spatial_scale
|
str
|
One of |
'whole_brain'
|
roi_mask
|
BrainData | Nifti1Image | str | Path | None
|
Atlas image
for |
None
|
radius
|
float
|
Searchlight radius in mm. Default 10.0. |
10.0
|
**kwargs
|
dict
|
Additional metric options forwarded to
|
{}
|
Returns:
| Type | Description |
|---|---|
Adjacency
|
Single pairwise distance matrix for |
extract_roi ¶
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'
|
n_components
|
int | None
|
Number of components to return when
|
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If, after resampling onto this object's grid, |
Examples:
filter ¶
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 |
{}
|
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 |
None
|
sampling_freq
|
float | None
|
Sampling frequency in Hz (= 1/TR). See |
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 |
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'
|
X
|
DesignMatrix | array - like | Mapping
|
A precomputed
|
None
|
ridge_alpha
|
float | Sequence[float]
|
Ridge only. A positive
scalar fits a fixed α and requires |
1.0
|
ridge_cv
|
int | sklearn splitter | None
|
Ridge only.
Cross-validation specification; |
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)
|
ridge_device
|
str
|
Ridge only. |
'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'
|
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 |
True
|
random_state
|
int | None
|
Seed shared by both estimators. |
None
|
Returns:
| Type | Description |
|---|---|
BrainData
|
Self when |
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:
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'
|
threshold
|
float | str | None
|
Convenience symmetric magnitude floor (→ |
None
|
lower
|
float | str | None
|
Window floor (→ |
None
|
upper
|
float | str | None
|
Window ceiling (→ |
None
|
autoscale
|
bool
|
Robust default window for the edges not set above.
|
True
|
symmetric
|
bool | Literal['auto']
|
|
'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
|
atlas
|
str | Atlas | None
|
Atlas overlay — a registry name (e.g. |
None
|
opacity
|
float
|
Stat-map (and filled-atlas) opacity in |
1.0
|
outline
|
float
|
|
0.0
|
colorbar
|
bool
|
Show the stat-map colorbar (default |
True
|
controls
|
bool
|
Render an in-widget threshold slider above the viewer
(default |
True
|
**kwargs
|
dict
|
Passed as niivue options. |
{}
|
Returns:
| Type | Description |
|---|---|
NiivueViewer
|
An |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
mean ¶
median ¶
multivariate_similarity ¶
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
|
Returns:
| Type | Description |
|---|---|
dict
|
Regression statistics as BrainData instances, keyed
|
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 |
'z'
|
cut_coords
|
list or dict
|
Cut coordinates for
multi-slice views. Takes precedence over |
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 |
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 |
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'
|
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 aPredict; - an explicit
X=predicts from the fittedGlmorRidgeand returns a new, independently ownedBrainData; - with neither argument and a fitted model, an independent copy of the stored training predictions;
- with neither argument, no fitted model, and exactly one
.Ycolumn, 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 |
None
|
y
|
array - like | str
|
Labels (classification) or
continuous targets (regression), shape |
None
|
estimator
|
str | sklearn estimator
|
A built-in shortcut —
|
'linear_svc'
|
cv
|
int | sklearn splitter
|
|
None
|
groups
|
array - like | str
|
Group labels passed to the
splitter (e.g. |
None
|
scoring
|
str | callable
|
Follows scikit-learn's
single-metric scoring contract. |
None
|
spatial_scale
|
str
|
MVPA dispatch — |
'whole_brain'
|
roi_mask
|
Nifti1Image | path - like
|
Atlas image; required
by, and only valid for, |
None
|
radius
|
float
|
Searchlight sphere radius in millimeters; only
valid for |
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
|
progress_bar
|
bool
|
Show a progress bar for searchlight and ROI. |
False
|
Returns:
| Type | Description |
|---|---|
Predict | BrainData
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
On both |
TypeError
|
On a removed keyword, an |
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:
regions ¶
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 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:
|
None
|
Returns:
| Type | Description |
|---|---|
BrainData
|
New BrainData instance with resampled data and mask. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If both |
TypeError
|
If |
Examples:
scale ¶
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
|
Returns:
| Type | Description |
|---|---|
BrainData
|
New BrainData instance with scaled data. |
similarity ¶
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'
|
Returns:
| Type | Description |
|---|---|
float or ndarray
|
Similarity value(s). |
smooth ¶
standardize ¶
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'
|
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 |
std ¶
sum ¶
temporal_resample ¶
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 |
None
|
target_type
|
str
|
How to read |
'hz'
|
Returns:
| Type | Description |
|---|---|
BrainData
|
Resampled BrainData instance. |
threshold ¶
Threshold BrainData instance with optional cluster filtering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upper
|
float | str | None
|
Upper cutoff for thresholding; a
percentile string like |
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 ¶
Convert BrainData Instance into Nifti Object.
Returns:
| Type | Description |
|---|---|
Nifti1Image
|
Brain data as a NIfTI image. |
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 |
False
|
n_permute
|
int
|
Number of permutations, used only when
|
5000
|
tail
|
int | str
|
|
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
|
|
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 |
None
|
img_type
|
str
|
NeuroVault |
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. |