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') -> NoneParallel, 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:
Per-subject ops route through
execution._applyand return a lightweight clone viaself._clone(...)over the same cache root.Path-backed by default after parallel ops;
cache='auto'follows source state.cache=is only accepted on collection-returning ops.load/unloadare the only methods that mutateself.
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:
| Name | Type | Description |
|---|---|---|
cache_root | Path | Run-scoped cache directory shared by clones. Raises if unset. |
designs | list | Per-subject paired designs (a copy of the list; None where unpaired). |
is_loaded | list [ bool ] | Per-item flag — True iff the slot holds a BrainData (not a path). |
mask | Nifti1Image | Shared mask image for the collection. Raises if the mask is unset. |
metadata | DataFrame | Per-subject metadata as a polars DataFrame (one row per item). |
n_subjects | int | Number of subjects (items) in the collection. |
n_voxels | int | Voxel count from the mask. Raises if mask is unset. |
shape | tuple [ 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:
| Name | Description |
|---|---|
align | Functionally align subjects into a common space via LocalAlignment. |
anova | One-way ANOVA across subjects grouped by groups. |
apply | Call BrainData.<op>(*args, **kwargs) on every item in parallel. |
cleanup | Remove cache_root and invalidate every clone derived from self. |
cleanup_all | Remove every .nltools_cache/{run_id}/ under directory. |
compute_contrasts | Compute per-subject contrast maps from fit-bundle items. |
concat | Stack all subject maps into a single BrainData (subjects as rows). |
detrend | Detrend every subject’s image in parallel (delegates to BrainData.detrend). |
filter | Filter to a subset by predicate, polars expression, or boolean array. |
fit | Per-subject fit; returns a path-backed collection of HDF5 fit bundles. |
from_bids | Auto-pair BOLD with events.tsv (→ DesignMatrix) and confounds.tsv. |
from_glob | Build a collection by glob-matching brain images (and optional designs). |
from_paths | Build a collection from explicit lists of brain (and design) paths. |
isc | Inter-subject correlation (ISC) across the time dimension. |
isc_test | Bootstrap inference on ISC (per-voxel p-values). |
iter_pairs | Yield ``(BrainData, DesignMatrix |
load | Materialize path-backed items in place. Returns self for chaining. |
map | Apply an arbitrary fn(BrainData) -> BrainData to each item in parallel. |
max | Voxelwise maximum across subjects as a single BrainData. |
mean | Voxelwise mean across subjects as a single BrainData. |
median | Voxelwise median across subjects as a single BrainData. |
memory_estimate | Human-readable RAM estimate if every item were loaded into memory. |
min | Voxelwise minimum across subjects as a single BrainData. |
permutation_test | One-sample sign-flipping permutation test across subjects. |
permutation_test2 | Two-sample permutation test between this collection and other. |
predict | Per-subject decoding (y) or predict-after-fit (X_new). |
predict_group | Group MVPA: subjects as samples → one model → Predict. |
read | Read a collection previously saved by write(). |
resample | Resample every subject’s image to a target space in parallel. |
smooth | Spatially smooth every subject’s image in parallel (delegates to BrainData.smooth). |
standardize | Standardize every subject’s image in parallel (delegates to BrainData.standardize). |
std | Voxelwise standard deviation across subjects as a single BrainData. |
steps | Step subdirs that produced this collection’s items, oldest to newest. |
sum | Voxelwise sum across subjects as a single BrainData. |
threshold | Threshold every subject’s image in parallel (delegates to BrainData.threshold). |
transform_designs | Map fn(dm) -> DesignMatrix over each paired design. |
ttest | One-sample t-test across subjects (delegates to inference.ttest). |
ttest2 | Two-sample t-test between this collection and other (subject-level). |
unload | Drop in-memory data for items with backing paths. Returns self. |
var | Voxelwise variance across subjects as a single BrainData. |
write | Write 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:
| Name | Type | Description | Default |
|---|---|---|---|
method | str | Alignment solver (e.g. 'procrustes'). | ‘procrustes’ |
spatial_scale | str | Alignment spatial scale — 'searchlight' (default, overlapping spheres) or 'roi' (non-overlapping parcels). Whole-brain alignment is not supported at the collection level. | ‘searchlight’ |
radius_mm | float | Searchlight sphere radius in mm (spatial_scale='searchlight'). | 10.0 |
roi_mask | Nifti1Image | None | Parcellation/ROI mask (used when spatial_scale='roi'). | None |
n_features | int | None | Optional target feature count for the common space. | None |
n_iter | int | LocalAlignment solver iteration count (not a permutation count). | 3 |
device | str | Backend selector ('cpu'/'gpu'). | ‘cpu’ |
return_model | bool | If True, also return the fitted LocalAlignment. | False |
n_jobs | int | Parallel worker count (-1 uses all cores). | -1 |
progress_bar | bool | If True, show a progress bar. | False |
cache | Literal [‘auto’, True, False] | Cache policy for the result ('auto' follows source state). | ‘auto’ |
Returns:
| Type | Description |
|---|---|
A new BrainCollection of aligned data, or a | |
(BrainCollection, LocalAlignment) tuple when | |
return_model=True. |
anova¶
anova(groups: str | list | np.ndarray) -> dictOne-way ANOVA across subjects grouped by groups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
groups | str | list | ndarray | A metadata column name, or a list/ndarray of length n_subjects giving each subject’s group label. | required |
Returns:
| Type | Description |
|---|---|
dict | Dict with {'F', 'p'} BrainData maps plus df_between and |
dict | df_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]) -> BrainCollectionCall 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() -> NoneRemove 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 = '.') -> NoneRemove 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:
| Type | Description |
|---|---|
BrainCollection | dict [ str , BrainCollection ] | dict [ str , dict [ str , BrainCollection ]] | single contrast + single statistic → BrainCollection |
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() -> BrainDataStack 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') -> BrainCollectionDetrend every subject’s image in parallel (delegates to BrainData.detrend).
filter¶
filter(predicate: Callable[[Any], Any] | list | np.ndarray | pl.Series | pd.Series) -> BrainCollectionFilter 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]) -> BrainCollectionPer-subject fit; returns a path-backed collection of HDF5 fit bundles.
X resolution priority:
None→ useself.designs(must be set per subject)DesignMatrix→ shared across all subjectslist→ per-subject (len == n_subjects)callable→fn(ctx: _DesignContext) -> DesignMatrix
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') -> BrainCollectionAuto-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') -> BrainCollectionBuild a collection by glob-matching brain images (and optional designs).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern | str | Glob pattern matching the per-subject brain image files. | required |
mask | Nifti1Image | Path | str | Shared mask image, path, or nltools template name. | required |
design_pattern | str | None | Optional glob matching per-subject design files, paired positionally with the brain images. | None |
pattern_groups | dict [ str , int ] | str | None | Regex capture-group spec used to extract metadata (e.g. subject/run) from each matched path. | None |
sort | bool | If True, sort matched paths before pairing (stable ordering). | True |
cache_dir | Path | str | None | Cache-directory precedence: explicit arg → NLTOOLS_CACHE_DIR env → ./.nltools_cache; None for a temp dir. | ‘./.nltools_cache’ |
Returns:
| Type | Description |
|---|---|
BrainCollection | A 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') -> BrainCollectionBuild a collection from explicit lists of brain (and design) paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
brain_paths | list | Per-subject brain image paths. | required |
mask | Nifti1Image | Path | str | Shared mask image, path, or nltools template name. | required |
design_paths | list | None | Optional per-subject design paths, aligned positionally with brain_paths (length must match, None entries allowed). | None |
metadata | DataFrame | DataFrame | dict | None | Optional per-subject metadata (polars/pandas DataFrame or dict-of-columns), one row per path. | None |
cache_dir | Path | str | None | Cache-directory precedence: explicit arg → NLTOOLS_CACHE_DIR env → ./.nltools_cache; None for a temp dir. | ‘./.nltools_cache’ |
Returns:
| Type | Description |
|---|---|
BrainCollection | A lazy, path-backed BrainCollection. |
isc¶
isc(*, method: str = 'loo', roi_mask: nib.Nifti1Image | Path | str | None = None, summary: str = 'median') -> dictInter-subject correlation (ISC) across the time dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method | str | 'loo' (leave-one-out template) or 'pairwise' (all subject pairs). | ‘loo’ |
roi_mask | Nifti1Image | Path | str | None | Optional 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 |
summary | str | Aggregation across subjects/pairs (e.g. 'median'). | ‘median’ |
Returns:
| Type | Description |
|---|---|
dict | Dict {'isc', 'per_subject'} for method='loo' or |
dict | {'isc', 'pairs'} for method='pairwise' ('isc' is a |
dict | BrainData 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) -> dictBootstrap 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:
| Name | Type | Description | Default |
|---|---|---|---|
method | str | 'loo' or 'pairwise' (matches isc). | ‘loo’ |
roi_mask | Nifti1Image | Path | str | None | Optional 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_samples | int | Number of bootstrap resamples. | 5000 |
summary | str | Aggregation across subjects/pairs (e.g. 'median'). | ‘median’ |
tail | int | str | 2 | ‘two’ (two-tailed, default) or 1 |
random_state | int | None | Seed for the bootstrap RNG. | None |
Returns:
| Type | Description |
|---|---|
dict | Dict {'isc', 'p', 'null_dist'} ('isc' and 'p' are |
dict | BrainData maps). |
iter_pairs¶
iter_pairs() -> Iterator[tuple]Yield (BrainData, DesignMatrix | None) pairs.
load¶
load(indices: list[int] | None = None) -> BrainCollectionMaterialize 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') -> BrainCollectionApply an arbitrary fn(BrainData) -> BrainData to each item in parallel.
max¶
max() -> BrainDataVoxelwise maximum across subjects as a single BrainData.
mean¶
mean() -> BrainDataVoxelwise mean across subjects as a single BrainData.
median¶
median() -> BrainDataVoxelwise median across subjects as a single BrainData.
memory_estimate¶
memory_estimate() -> strHuman-readable RAM estimate if every item were loaded into memory.
Returns:
| Type | Description |
|---|---|
str | A string reporting n_subjects, the per-item shape (or “unknown” |
str | for path-backed items not yet loaded), and an estimated float32 |
str | total in MB/GB. |
min¶
min() -> BrainDataVoxelwise 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) -> dictOne-sample sign-flipping permutation test across subjects.
Delegates to the inference engine’s one_sample_permutation_test
over the stacked subject data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_permute | int | Number of sign-flip permutations. | 5000 |
tail | int | str | 1 for one-tailed, 2 for two-tailed. | 2 |
device | str | Execution backend — None (single-threaded numpy), 'cpu' (joblib parallel), or 'gpu' (PyTorch). | ‘cpu’ |
return_null | bool | If True, include the null distribution in the result. | False |
n_jobs | int | CPU workers when device='cpu' (-1 = all cores). | -1 |
random_state | int | None | Seed for the sign-flip RNG. | None |
progress_bar | bool | Whether to display a progress bar. | False |
Returns:
| Type | Description |
|---|---|
dict | Dict {'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) -> dictTwo-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:
| Name | Type | Description | Default |
|---|---|---|---|
other | BrainCollection | The second collection to compare against. | required |
n_permute | int | Number of label-shuffle permutations. | 5000 |
tail | int | str | 1 for one-tailed, 2 for two-tailed. | 2 |
device | str | Execution backend — None (single-threaded numpy), 'cpu' (joblib parallel), or 'gpu' (PyTorch). | ‘cpu’ |
return_null | bool | If True, include the null distribution in the result. | False |
n_jobs | int | CPU workers when device='cpu' (-1 = all cores). | -1 |
random_state | int | None | Seed for the shuffling RNG. | None |
progress_bar | bool | Whether to display a progress bar. | False |
Returns:
| Type | Description |
|---|---|
dict | Dict {'mean', 'p'} of BrainData maps (mean is the group |
dict | difference), 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:
Per-subject decoding (
y, or omitted with stored labels): mapsBrainData.predictover subjects — one model per subject, cross-validated within that subject’s own rows — and returns aPredictCollectioncarrying the collection’s metadata. Stack the per-subject decoder maps for second-level inference viaresult.weight_maps.Predict-after-fit (
X_new): map each subject’s fitted ridge model over a new design matrix, returning aBrainCollectionof 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:
| Name | Type | Description | Default |
|---|---|---|---|
y | str | list | ndarray | None | Per-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_new | ndarray | None | New design matrix for predict-after-fit (mode 2). | None |
spatial_scale | str | 'whole_brain' | 'roi' |
model | str | Model name or sklearn estimator (see BrainData.predict). | ‘svm’ |
cv | int | str | Within-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 |
groups | str | list | ndarray | None | Within-subject grouping variable — a .Y column name, one shared array, or a list of per-subject arrays. | None |
roi_mask | Nifti1Image | Path | str | None | Atlas image for spatial_scale='roi'. | None |
radius_mm | float | Searchlight radius. | 10.0 |
scoring | str | 'auto' → accuracy (classifier) / r2 (regressor). | ‘auto’ |
standardize | bool | Standardize features within each CV fold. | True |
n_jobs | int | CPU workers (subject-level; each subject decodes with n_jobs=1 to avoid nested parallelism). | -1 |
random_state | int | None | Seed for shuffled int-cv folds. | None |
progress_bar | bool | Whether to display a progress bar. | False |
cache | Literal [‘auto’, True, False] | 'auto' (cache when the source is path-backed) | True |
Returns:
| Type | Description |
|---|---|
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:
| Name | Type | Description | Default |
|---|---|---|---|
y | str | list | ndarray | Labels/targets, one per subject — an array/list, or the name of a metadata column. | required |
spatial_scale | str | 'whole_brain' | 'roi' |
model | str | Model name (see BrainData.predict). | ‘svm’ |
cv | int | 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’ |
groups | str | ndarray | None | Group 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_mask | Nifti1Image | Path | str | None | Restrict to an ROI. | None |
radius_mm | float | Searchlight radius. | 10.0 |
scoring | str | 'auto' → accuracy (classifier) / r2 (regressor). | ‘auto’ |
standardize | bool | Standardize features within each CV fold. | True |
n_permute | int | If > 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_jobs | int | CPU workers. | -1 |
random_state | int | None | Seed for the permutation-null label shuffling. | None |
progress_bar | bool | Whether to display a progress bar. | False |
Returns:
| Type | Description |
|---|---|
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') -> BrainCollectionRead 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') -> BrainCollectionResample every subject’s image to a target space in parallel.
Delegates to BrainData.resample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target | Resampling target (image, affine/shape spec, or template) passed through to BrainData.resample. | required | |
interpolation | str | Interpolation method ('continuous', 'linear', 'nearest'). | ‘continuous’ |
n_jobs | int | Parallel worker count (-1 uses all cores). | -1 |
progress_bar | bool | If True, show a progress bar. | False |
cache | Literal [‘auto’, True, False] | Cache policy for the result ('auto' follows source state). | ‘auto’ |
Returns:
| Type | Description |
|---|---|
BrainCollection | A new BrainCollection of resampled items. |
smooth¶
smooth(fwhm: float, *, n_jobs: int = -1, progress_bar: bool = False, cache: Literal['auto', True, False] = 'auto') -> BrainCollectionSpatially 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') -> BrainCollectionStandardize every subject’s image in parallel (delegates to BrainData.standardize).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis | int | Axis along which to standardize (0 = across observations). | 0 |
method | str | Standardization variant (e.g. 'center', 'zscore'). | ‘center’ |
n_jobs | int | Parallel worker count (-1 uses all cores). | -1 |
progress_bar | bool | If True, show a progress bar. | False |
cache | Literal [‘auto’, True, False] | Cache policy for the result ('auto' follows source state). | ‘auto’ |
Returns:
| Type | Description |
|---|---|
BrainCollection | A new BrainCollection of standardized items. |
std¶
std() -> BrainDataVoxelwise 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() -> BrainDataVoxelwise 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') -> BrainCollectionThreshold every subject’s image in parallel (delegates to BrainData.threshold).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lower | float | None | Values below this are zeroed (or set NaN); None disables. | None |
upper | float | None | Values above this are zeroed (or set NaN); None disables. | None |
binarize | bool | If True, set surviving voxels to 1. | False |
coerce_nan | bool | If True, coerce thresholded-out voxels to NaN instead of 0. | True |
n_jobs | int | Parallel worker count (-1 uses all cores). | -1 |
progress_bar | bool | If True, show a progress bar. | False |
cache | Literal [‘auto’, True, False] | Cache policy for the result ('auto' follows source state). | ‘auto’ |
Returns:
| Type | Description |
|---|---|
BrainCollection | A 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') -> BrainCollectionMap 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) -> dictOne-sample t-test across subjects (delegates to inference.ttest).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
popmean | float | Null-hypothesis population mean to test against. | 0.0 |
tail | int | str | 2 | ‘two’ (two-tailed, default) or 1 |
Returns:
| Type | Description |
|---|---|
dict | Dict {'mean', 't', 'z', 'p'} of BrainData maps. |
ttest2¶
ttest2(other: BrainCollection, *, equal_var: bool = True, tail: int | str = 2) -> dictTwo-sample t-test between this collection and other (subject-level).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other | BrainCollection | The second collection to compare against. | required |
equal_var | bool | If True, pooled-variance t-test; if False, Welch’s test. | True |
tail | int | str | 2 | ‘two’ (two-tailed, default) or 1 |
Returns:
| Type | Description |
|---|---|
dict | Dict {'mean', 't', 'z', 'p'} of BrainData maps (mean is the |
dict | group difference). |
unload¶
unload(indices: list[int] | None = None) -> BrainCollectionDrop in-memory data for items with backing paths. Returns self.
var¶
var() -> BrainDataVoxelwise 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:
| Name | Type | Description | Default |
|---|---|---|---|
directory | Path | str | Output directory (created if missing). | required |
pattern | str | Filename template per item, formatted with i (item index). | ‘image_{i:04d}.nii.gz’ |
metadata_file | str | None | CSV filename for the metadata table, or None to skip. | ‘metadata.csv’ |
Returns:
| Type | Description |
|---|---|
list [ Path ] | List of written NIfTI paths, in item order. |