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

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

BrainCollection

BrainCollection

BrainCollection(brains: list, *, mask: nib.Nifti1Image | Path | str, designs: list | None = None, metadata: pl.DataFrame | pd.DataFrame | dict | None = None, lazy: bool = True, cache_dir: Path | str | None = './.nltools_cache') -> None

Parallel, lazy iterator of BrainData whose API mirrors BrainData.

Constructed via __init__ (explicit lists) or one of the classmethod factories (from_bids, from_glob, from_paths, read).

See docs/development/execution-model.md for the full contract; key invariants:

Internal state (mutable list at top level; per-item slots are parallel):

_items list[BrainData | Path] per-item brain data _mask nib.Nifti1Image shared mask (by reference) _designs list[DesignMatrix | Path | None] _confounds list[pd.DataFrame | None] _sample_masks list[np.ndarray | None] _metadata pl.DataFrame simple-typed columns only _cache_root Path | None shared by clones _step_id str | None this collection’s step id _parent_step_id str | None upstream step id (lineage) _step_dirs list[Path] lineage of step subdirs that produced these items _source_paths list[Path | None] per-item backing path (None for in-memory only)

Attributes:

NameTypeDescription
cache_rootPathRun-scoped cache directory shared by clones. Raises if unset.
designslistPer-subject paired designs (a copy of the list; None where unpaired).
is_loadedlist [ bool ]Per-item flag — True iff the slot holds a BrainData (not a path).
maskNifti1ImageShared mask image for the collection. Raises if the mask is unset.
metadataDataFramePer-subject metadata as a polars DataFrame (one row per item).
n_subjectsintNumber of subjects (items) in the collection.
n_voxelsintVoxel count from the mask. Raises if mask is unset.
shapetuple [ int , int | None, int ]Collection shape as (n_subjects, n_obs_or_None_if_ragged, n_voxels).

cache_dir precedence: explicit arg → NLTOOLS_CACHE_DIR env → ./.nltools_cache. Pass None for an auto-cleaned tempdir. Resolved at construction and frozen on the instance.

Methods:

NameDescription
alignFunctionally align subjects into a common space via LocalAlignment.
anovaOne-way ANOVA across subjects grouped by groups.
applyCall BrainData.<op>(*args, **kwargs) on every item in parallel.
cleanupRemove cache_root and invalidate every clone derived from self.
cleanup_allRemove every .nltools_cache/{run_id}/ under directory.
compute_contrastsCompute per-subject contrast maps from fit-bundle items.
concatStack all subject maps into a single BrainData (subjects as rows).
detrendDetrend every subject’s image in parallel (delegates to BrainData.detrend).
filterFilter to a subset by predicate, polars expression, or boolean array.
fitPer-subject fit; returns a path-backed collection of HDF5 fit bundles.
from_bidsAuto-pair BOLD with events.tsv (→ DesignMatrix) and confounds.tsv.
from_globBuild a collection by glob-matching brain images (and optional designs).
from_pathsBuild a collection from explicit lists of brain (and design) paths.
iscInter-subject correlation (ISC) across the time dimension.
isc_testBootstrap inference on ISC (per-voxel p-values).
iter_pairsYield ``(BrainData, DesignMatrix
loadMaterialize path-backed items in place. Returns self for chaining.
mapApply an arbitrary fn(BrainData) -> BrainData to each item in parallel.
maxVoxelwise maximum across subjects as a single BrainData.
meanVoxelwise mean across subjects as a single BrainData.
medianVoxelwise median across subjects as a single BrainData.
memory_estimateHuman-readable RAM estimate if every item were loaded into memory.
minVoxelwise minimum across subjects as a single BrainData.
permutation_testOne-sample sign-flipping permutation test across subjects.
permutation_test2Two-sample permutation test between this collection and other.
predictPer-subject decoding (y) or predict-after-fit (X_new).
predict_groupGroup MVPA: subjects as samples → one model → Predict.
readRead a collection previously saved by write().
resampleResample every subject’s image to a target space in parallel.
smoothSpatially smooth every subject’s image in parallel (delegates to BrainData.smooth).
standardizeStandardize every subject’s image in parallel (delegates to BrainData.standardize).
stdVoxelwise standard deviation across subjects as a single BrainData.
stepsStep subdirs that produced this collection’s items, oldest to newest.
sumVoxelwise sum across subjects as a single BrainData.
thresholdThreshold every subject’s image in parallel (delegates to BrainData.threshold).
transform_designsMap fn(dm) -> DesignMatrix over each paired design.
ttestOne-sample t-test across subjects (delegates to inference.ttest).
ttest2Two-sample t-test between this collection and other (subject-level).
unloadDrop in-memory data for items with backing paths. Returns self.
varVoxelwise variance across subjects as a single BrainData.
writeWrite a clean, portable copy of the collection outside the cache root.

Methods

align

align(*, method: str = 'procrustes', spatial_scale: str = 'searchlight', radius_mm: float = 10.0, roi_mask: nib.Nifti1Image | None = None, n_features: int | None = None, n_iter: int = 3, device: str = 'cpu', return_model: bool = False, n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto')

Functionally align subjects into a common space via LocalAlignment.

Materializes all subjects (algorithm constraint in v0.6.0).

Parameters:

NameTypeDescriptionDefault
methodstrAlignment solver (e.g. 'procrustes').‘procrustes’
spatial_scalestrAlignment spatial scale — 'searchlight' (default, overlapping spheres) or 'roi' (non-overlapping parcels). Whole-brain alignment is not supported at the collection level.‘searchlight’
radius_mmfloatSearchlight sphere radius in mm (spatial_scale='searchlight').10.0
roi_maskNifti1Image | NoneParcellation/ROI mask (used when spatial_scale='roi').None
n_featuresint | NoneOptional target feature count for the common space.None
n_iterintLocalAlignment solver iteration count (not a permutation count).3
devicestrBackend selector ('cpu'/'gpu').‘cpu’
return_modelboolIf True, also return the fitted LocalAlignment.False
n_jobsintParallel worker count (-1 uses all cores).-1
progress_barboolIf True, show a progress bar.False
cacheLiteral [‘auto’, True, False]Cache policy for the result ('auto' follows source state).‘auto’

Returns:

TypeDescription
A new BrainCollection of aligned data, or a
(BrainCollection, LocalAlignment) tuple when
return_model=True.

anova

anova(groups: str | list | np.ndarray) -> dict

One-way ANOVA across subjects grouped by groups.

Parameters:

NameTypeDescriptionDefault
groupsstr | list | ndarrayA metadata column name, or a list/ndarray of length n_subjects giving each subject’s group label.required

Returns:

TypeDescription
dictDict with {'F', 'p'} BrainData maps plus df_between and
dictdf_within degrees of freedom.

apply

apply(op: str, *args: str, n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto', **kwargs: Literal['auto', True, False]) -> BrainCollection

Call BrainData.<op>(*args, **kwargs) on every item in parallel.

All per-subject methods (smooth, standardize, ...) reduce to this. Centralizes the _apply plumbing and the cache-knob handling. op is named op (not method) to avoid colliding with BrainData methods that themselves take a method= kwarg (standardize, detrend, ...).

cleanup

cleanup() -> None

Remove cache_root and invalidate every clone derived from self.

Idempotent — calling twice is a no-op. Path-backed items in any clone become unloadable after this; use bc.write(...) first to materialize a portable copy if needed.

cleanup_all

cleanup_all(directory: Path | str = '.') -> None

Remove every .nltools_cache/{run_id}/ under directory.

Wide brush — can kill sibling sessions in the same cwd. Prefer bc.cleanup() for surgical removal.

compute_contrasts

compute_contrasts(contrasts: str | list[str] | dict[str, np.ndarray], *, statistic: str = 'beta', n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto') -> BrainCollection | dict[str, BrainCollection] | dict[str, dict[str, BrainCollection]]

Compute per-subject contrast maps from fit-bundle items.

Returns:

TypeDescription
BrainCollection | dict [ str , BrainCollection ] | dict [ str , dict [ str , BrainCollection ]]single contrast + single statisticBrainCollection
BrainCollection | dict [ str , BrainCollection ] | dict [ str , dict [ str , BrainCollection ]]multiple contrasts (single type) → dict[str, BrainCollection]
BrainCollection | dict [ str , BrainCollection ] | dict [ str , dict [ str , BrainCollection ]]statistic='all' (single contrast) → ``dict[‘beta’
BrainCollection | dict [ str , BrainCollection ] | dict [ str , dict [ str , BrainCollection ]]multiple contrasts + statistic='all' → nested dict[name, dict[stat, BrainCollection]]

Each per-subject NIfTI gets a JSON sidecar with lineage attrs (step_id, parent_step_id, op, kwargs, nltools_version).

concat

concat() -> BrainData

Stack all subject maps into a single BrainData (subjects as rows).

detrend

detrend(*, method: str = 'linear', n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto') -> BrainCollection

Detrend every subject’s image in parallel (delegates to BrainData.detrend).

filter

filter(predicate: Callable[[Any], Any] | list | np.ndarray | pl.Series | pd.Series) -> BrainCollection

Filter to a subset by predicate, polars expression, or boolean array.

fit

fit(model: str = 'glm', X: DesignMatrix | list | Callable | None = None, *, scale: bool | str = 'auto', standardize: str | None = 'auto', n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto', **model_kwargs: Literal['auto', True, False]) -> BrainCollection

Per-subject fit; returns a path-backed collection of HDF5 fit bundles.

X resolution priority:

from_bids

from_bids(root: Path | str | Any, *, mask: nib.Nifti1Image | Path | str, task: str | None = None, space: str | None = None, sub_labels: list[str] | None = None, img_filters: list[tuple[str, str]] | None = None, derivatives_folder: str = 'derivatives', pair_events: bool = True, confounds_strategy: str | tuple[str, ...] | None = None, confounds_kwargs: dict | None = None, TR: float | str = 'infer', cache_dir: Path | str | None = './.nltools_cache') -> BrainCollection

Auto-pair BOLD with events.tsv (→ DesignMatrix) and confounds.tsv.

Full design and edge cases: see docs/development/execution-model.md.

from_glob

from_glob(pattern: str, *, mask: nib.Nifti1Image | Path | str, design_pattern: str | None = None, pattern_groups: dict[str, int] | str | None = None, sort: bool = True, cache_dir: Path | str | None = './.nltools_cache') -> BrainCollection

Build a collection by glob-matching brain images (and optional designs).

Parameters:

NameTypeDescriptionDefault
patternstrGlob pattern matching the per-subject brain image files.required
maskNifti1Image | Path | strShared mask image, path, or nltools template name.required
design_patternstr | NoneOptional glob matching per-subject design files, paired positionally with the brain images.None
pattern_groupsdict [ str , int ] | str | NoneRegex capture-group spec used to extract metadata (e.g. subject/run) from each matched path.None
sortboolIf True, sort matched paths before pairing (stable ordering).True
cache_dirPath | str | NoneCache-directory precedence: explicit arg → NLTOOLS_CACHE_DIR env → ./.nltools_cache; None for a temp dir.‘./.nltools_cache’

Returns:

TypeDescription
BrainCollectionA lazy, path-backed BrainCollection.

from_paths

from_paths(brain_paths: list, *, mask: nib.Nifti1Image | Path | str, design_paths: list | None = None, metadata: pl.DataFrame | pd.DataFrame | dict | None = None, cache_dir: Path | str | None = './.nltools_cache') -> BrainCollection

Build a collection from explicit lists of brain (and design) paths.

Parameters:

NameTypeDescriptionDefault
brain_pathslistPer-subject brain image paths.required
maskNifti1Image | Path | strShared mask image, path, or nltools template name.required
design_pathslist | NoneOptional per-subject design paths, aligned positionally with brain_paths (length must match, None entries allowed).None
metadataDataFrame | DataFrame | dict | NoneOptional per-subject metadata (polars/pandas DataFrame or dict-of-columns), one row per path.None
cache_dirPath | str | NoneCache-directory precedence: explicit arg → NLTOOLS_CACHE_DIR env → ./.nltools_cache; None for a temp dir.‘./.nltools_cache’

Returns:

TypeDescription
BrainCollectionA lazy, path-backed BrainCollection.

isc

isc(*, method: str = 'loo', roi_mask: nib.Nifti1Image | Path | str | None = None, summary: str = 'median') -> dict

Inter-subject correlation (ISC) across the time dimension.

Parameters:

NameTypeDescriptionDefault
methodstr'loo' (leave-one-out template) or 'pairwise' (all subject pairs).‘loo’
roi_maskNifti1Image | Path | str | NoneOptional ROI/atlas mask restricting the computation to those voxels. The returned maps carry the ROI mask. If None, ISC is computed across the collection’s whole-brain mask.None
summarystrAggregation across subjects/pairs (e.g. 'median').‘median’

Returns:

TypeDescription
dictDict {'isc', 'per_subject'} for method='loo' or
dict{'isc', 'pairs'} for method='pairwise' ('isc' is a
dictBrainData map).

isc_test

isc_test(*, method: str = 'loo', roi_mask: nib.Nifti1Image | Path | str | None = None, n_samples: int = 5000, summary: str = 'median', tail: int | str = 2, random_state: int | None = None) -> dict

Bootstrap inference on ISC (per-voxel p-values).

Resamples subjects with replacement, recomputes ISC each draw, and derives a per-voxel p-value from the null centered at 0.

Parameters:

NameTypeDescriptionDefault
methodstr'loo' or 'pairwise' (matches isc).‘loo’
roi_maskNifti1Image | Path | str | NoneOptional ROI/atlas mask restricting the computation to those voxels. The returned maps carry the ROI mask. If None, ISC is computed across the collection’s whole-brain mask.None
n_samplesintNumber of bootstrap resamples.5000
summarystrAggregation across subjects/pairs (e.g. 'median').‘median’
tailint | str2‘two’ (two-tailed, default) or 1
random_stateint | NoneSeed for the bootstrap RNG.None

Returns:

TypeDescription
dictDict {'isc', 'p', 'null_dist'} ('isc' and 'p' are
dictBrainData maps).

iter_pairs

iter_pairs() -> Iterator[tuple]

Yield (BrainData, DesignMatrix | None) pairs.

load

load(indices: list[int] | None = None) -> BrainCollection

Materialize path-backed items in place. Returns self for chaining.

map

map(fn: Callable, *, n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto') -> BrainCollection

Apply an arbitrary fn(BrainData) -> BrainData to each item in parallel.

max

max() -> BrainData

Voxelwise maximum across subjects as a single BrainData.

mean

mean() -> BrainData

Voxelwise mean across subjects as a single BrainData.

median

median() -> BrainData

Voxelwise median across subjects as a single BrainData.

memory_estimate

memory_estimate() -> str

Human-readable RAM estimate if every item were loaded into memory.

Returns:

TypeDescription
strA string reporting n_subjects, the per-item shape (or “unknown”
strfor path-backed items not yet loaded), and an estimated float32
strtotal in MB/GB.

min

min() -> BrainData

Voxelwise minimum across subjects as a single BrainData.

permutation_test

permutation_test(*, n_permute: int = 5000, tail: int | str = 2, device: str = 'cpu', return_null: bool = False, n_jobs: int = -1, random_state: int | None = None, progress_bar: bool = False) -> dict

One-sample sign-flipping permutation test across subjects.

Delegates to the inference engine’s one_sample_permutation_test over the stacked subject data.

Parameters:

NameTypeDescriptionDefault
n_permuteintNumber of sign-flip permutations.5000
tailint | str1 for one-tailed, 2 for two-tailed.2
devicestrExecution backend — None (single-threaded numpy), 'cpu' (joblib parallel), or 'gpu' (PyTorch).‘cpu’
return_nullboolIf True, include the null distribution in the result.False
n_jobsintCPU workers when device='cpu' (-1 = all cores).-1
random_stateint | NoneSeed for the sign-flip RNG.None
progress_barboolWhether to display a progress bar.False

Returns:

TypeDescription
dictDict {'mean', 'p'} of BrainData maps, plus
dict'null_dist' when return_null=True.

permutation_test2

permutation_test2(other: BrainCollection, *, n_permute: int = 5000, tail: int | str = 2, device: str = 'cpu', return_null: bool = False, n_jobs: int = -1, random_state: int | None = None, progress_bar: bool = False) -> dict

Two-sample permutation test between this collection and other.

Uses random label shuffling of the pooled subjects, delegating to the inference engine’s two_sample_permutation_test.

Parameters:

NameTypeDescriptionDefault
otherBrainCollectionThe second collection to compare against.required
n_permuteintNumber of label-shuffle permutations.5000
tailint | str1 for one-tailed, 2 for two-tailed.2
devicestrExecution backend — None (single-threaded numpy), 'cpu' (joblib parallel), or 'gpu' (PyTorch).‘cpu’
return_nullboolIf True, include the null distribution in the result.False
n_jobsintCPU workers when device='cpu' (-1 = all cores).-1
random_stateint | NoneSeed for the shuffling RNG.None
progress_barboolWhether to display a progress bar.False

Returns:

TypeDescription
dictDict {'mean', 'p'} of BrainData maps (mean is the group
dictdifference), plus 'null_dist' when return_null=True.

predict

predict(y: str | list | np.ndarray | None = None, *, X_new: np.ndarray | None = None, spatial_scale: str = 'whole_brain', model: str = 'svm', cv: int | str = 5, groups: str | list | np.ndarray | None = None, roi_mask: nib.Nifti1Image | Path | str | None = None, radius_mm: float = 10.0, scoring: str = 'auto', standardize: bool = True, n_jobs: int = -1, random_state: int | None = None, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto')

Per-subject decoding (y) or predict-after-fit (X_new).

The per-subject counterpart to every other method on this class — one operation per subject, no cross-subject mixing. (For group MVPA — subjects as samples, one model across the collection — use predict_group.) Dispatched by which argument is provided:

  1. Per-subject decoding (y, or omitted with stored labels): maps BrainData.predict over subjects — one model per subject, cross-validated within that subject’s own rows — and returns a PredictCollection carrying the collection’s metadata. Stack the per-subject decoder maps for second-level inference via result.weight_maps.

  2. Predict-after-fit (X_new): map each subject’s fitted ridge model over a new design matrix, returning a BrainCollection of predicted maps. Requires ridge fit-bundle items (.fit(model='ridge', cache=True)).

Labels travel with the data: with y omitted, each subject decodes its own single-column .Y; y='name' picks a column of each subject’s .Y, and groups='name' does the same for a within-subject grouping variable (e.g. run). Alternatively pass one shared label array (applied to every subject) or a list of arrays (one per subject, in collection order).

Parameters:

NameTypeDescriptionDefault
ystr | list | ndarray | NonePer-subject decoding targets — None (each subject’s single-column .Y), a .Y column name, one shared array, or a list of per-subject arrays.None
X_newndarray | NoneNew design matrix for predict-after-fit (mode 2).None
spatial_scalestr'whole_brain''roi'
modelstrModel name or sklearn estimator (see BrainData.predict).‘svm’
cvint | strWithin-subject CV — an int fold count (default 5, honoring groups via the Group variants), 'loo', 'logo' (with groups, e.g. leave-one-run-out), or an sklearn splitter.5
groupsstr | list | ndarray | NoneWithin-subject grouping variable — a .Y column name, one shared array, or a list of per-subject arrays.None
roi_maskNifti1Image | Path | str | NoneAtlas image for spatial_scale='roi'.None
radius_mmfloatSearchlight radius.10.0
scoringstr'auto' → accuracy (classifier) / r2 (regressor).‘auto’
standardizeboolStandardize features within each CV fold.True
n_jobsintCPU workers (subject-level; each subject decodes with n_jobs=1 to avoid nested parallelism).-1
random_stateint | NoneSeed for shuffled int-cv folds.None
progress_barboolWhether to display a progress bar.False
cacheLiteral [‘auto’, True, False]'auto' (cache when the source is path-backed)True

Returns:

TypeDescription
PredictCollection (mode 1) or BrainCollection (mode 2).

predict_group

predict_group(y: str | list | np.ndarray, *, spatial_scale: str = 'whole_brain', model: str = 'svm', cv: int | str = 'logo', groups: str | np.ndarray | None = None, roi_mask: nib.Nifti1Image | Path | str | None = None, radius_mm: float = 10.0, scoring: str = 'auto', standardize: bool = True, n_permute: int = 0, n_jobs: int = -1, random_state: int | None = None, progress_bar: bool = False)

Group MVPA: subjects as samples → one model → Predict.

Stacks the collection into a (n_subjects, n_voxels) matrix and trains a single model with subjects as samples (unlike the per-subject methods, this deliberately collapses across subjects). Requires single-map-per-subject items — run compute_contrasts(...) first for GLM/ridge bundles.

Parameters:

NameTypeDescriptionDefault
ystr | list | ndarrayLabels/targets, one per subject — an array/list, or the name of a metadata column.required
spatial_scalestr'whole_brain''roi'
modelstrModel name (see BrainData.predict).‘svm’
cvint | str'logo' (leave-one-group-out, default — with the default groups this is leave-one-subject-out), 'loo' (leave-one-out), an int fold count, or an sklearn splitter. An int spec honors groups: it resolves to StratifiedGroupKFold (classifiers) / GroupKFold (regressors) so a group never straddles a train/test boundary.‘logo’
groupsstr | ndarray | NoneGroup labels, or a metadata column name. Defaults to one group per subject; pass groups='run' (or any metadata column) for e.g. leave-one-run-out under cv='logo'.None
roi_maskNifti1Image | Path | str | NoneRestrict to an ROI.None
radius_mmfloatSearchlight radius.10.0
scoringstr'auto' → accuracy (classifier) / r2 (regressor).‘auto’
standardizeboolStandardize features within each CV fold.True
n_permuteintIf > 0, also build a label-permutation null of the CV score — shuffle y and re-score the identical CV (scoring only; no refit/weight-map work) — attached as permutation_scores and permutation_pvalue (Phipson-Smyth upper-tail). Forms by spatial_scale: whole_brain → null (n_permute,), p float; roi → null (n_permute, n_rois), p (n_rois,); searchlight → null (n_permute, n_voxels), p a BrainData map (NaN where the observed accuracy map is NaN). Default 0 (no null).0
n_jobsintCPU workers.-1
random_stateint | NoneSeed for the permutation-null label shuffling.None
progress_barboolWhether to display a progress bar.False

Returns:

TypeDescription
Predict with CV attributes; plus the permutation-null fields
when n_permute > 0.

read

read(directory: Path | str, *, mask: nib.Nifti1Image | Path | str, cache_dir: Path | str | None = './.nltools_cache') -> BrainCollection

Read a collection previously saved by write().

Note

Does not recover from cache subdirs in v0.6.0.

resample

resample(target, *, interpolation: str = 'continuous', n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto') -> BrainCollection

Resample every subject’s image to a target space in parallel.

Delegates to BrainData.resample.

Parameters:

NameTypeDescriptionDefault
targetResampling target (image, affine/shape spec, or template) passed through to BrainData.resample.required
interpolationstrInterpolation method ('continuous', 'linear', 'nearest').‘continuous’
n_jobsintParallel worker count (-1 uses all cores).-1
progress_barboolIf True, show a progress bar.False
cacheLiteral [‘auto’, True, False]Cache policy for the result ('auto' follows source state).‘auto’

Returns:

TypeDescription
BrainCollectionA new BrainCollection of resampled items.

smooth

smooth(fwhm: float, *, n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto') -> BrainCollection

Spatially smooth every subject’s image in parallel (delegates to BrainData.smooth).

standardize

standardize(*, axis: int = 0, method: str = 'center', n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto') -> BrainCollection

Standardize every subject’s image in parallel (delegates to BrainData.standardize).

Parameters:

NameTypeDescriptionDefault
axisintAxis along which to standardize (0 = across observations).0
methodstrStandardization variant (e.g. 'center', 'zscore').‘center’
n_jobsintParallel worker count (-1 uses all cores).-1
progress_barboolIf True, show a progress bar.False
cacheLiteral [‘auto’, True, False]Cache policy for the result ('auto' follows source state).‘auto’

Returns:

TypeDescription
BrainCollectionA new BrainCollection of standardized items.

std

std() -> BrainData

Voxelwise standard deviation across subjects as a single BrainData.

steps

steps() -> list[Path]

Step subdirs that produced this collection’s items, oldest to newest.

Lineage chain accumulated through clones (one entry per upstream cached op). Empty when the collection was constructed directly or no ancestor wrote to disk.

sum

sum() -> BrainData

Voxelwise sum across subjects as a single BrainData.

threshold

threshold(*, lower: float | None = None, upper: float | None = None, binarize: bool = False, coerce_nan: bool = True, n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto') -> BrainCollection

Threshold every subject’s image in parallel (delegates to BrainData.threshold).

Parameters:

NameTypeDescriptionDefault
lowerfloat | NoneValues below this are zeroed (or set NaN); None disables.None
upperfloat | NoneValues above this are zeroed (or set NaN); None disables.None
binarizeboolIf True, set surviving voxels to 1.False
coerce_nanboolIf True, coerce thresholded-out voxels to NaN instead of 0.True
n_jobsintParallel worker count (-1 uses all cores).-1
progress_barboolIf True, show a progress bar.False
cacheLiteral [‘auto’, True, False]Cache policy for the result ('auto' follows source state).‘auto’

Returns:

TypeDescription
BrainCollectionA new BrainCollection of thresholded items.

transform_designs

transform_designs(fn: Callable, *, n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto') -> BrainCollection

Map fn(dm) -> DesignMatrix over each paired design.

Items with no paired design are skipped (kept as None). Runs in the parent process — designs are small. n_jobs/progress_bar/ cache are accepted for surface consistency but ignored.

ttest

ttest(*, popmean: float = 0.0, tail: int | str = 2) -> dict

One-sample t-test across subjects (delegates to inference.ttest).

Parameters:

NameTypeDescriptionDefault
popmeanfloatNull-hypothesis population mean to test against.0.0
tailint | str2‘two’ (two-tailed, default) or 1

Returns:

TypeDescription
dictDict {'mean', 't', 'z', 'p'} of BrainData maps.

ttest2

ttest2(other: BrainCollection, *, equal_var: bool = True, tail: int | str = 2) -> dict

Two-sample t-test between this collection and other (subject-level).

Parameters:

NameTypeDescriptionDefault
otherBrainCollectionThe second collection to compare against.required
equal_varboolIf True, pooled-variance t-test; if False, Welch’s test.True
tailint | str2‘two’ (two-tailed, default) or 1

Returns:

TypeDescription
dictDict {'mean', 't', 'z', 'p'} of BrainData maps (mean is the
dictgroup difference).

unload

unload(indices: list[int] | None = None) -> BrainCollection

Drop in-memory data for items with backing paths. Returns self.

var

var() -> BrainData

Voxelwise variance across subjects as a single BrainData.

write

write(directory: Path | str, *, pattern: str = 'image_{i:04d}.nii.gz', metadata_file: str | None = 'metadata.csv') -> list[Path]

Write a clean, portable copy of the collection outside the cache root.

Inverse of BrainCollection.read. Writes one NIfTI per item plus an optional metadata CSV, skipping the internal cache layout so the result is shareable/archival.

Parameters:

NameTypeDescriptionDefault
directoryPath | strOutput directory (created if missing).required
patternstrFilename template per item, formatted with i (item index).‘image_{i:04d}.nii.gz’
metadata_filestr | NoneCSV filename for the metadata table, or None to skip.‘metadata.csv’

Returns:

TypeDescription
list [ Path ]List of written NIfTI paths, in item order.