templates¶
Global MNI brain-space configuration for nltools.
This module manages the default MNI template used by BrainData and
related classes when no explicit mask is provided. Set it once (e.g., at
the top of a notebook) and all subsequent operations pick it up
automatically.
Classes:
| Name | Description |
|---|---|
BrainSpaceConfig | Immutable MNI template configuration. |
TemplateMatch | Result of matching a data affine to a template. |
Methods:
| Name | Description |
|---|---|
fetch_resource | Return a local path to a file from the nltools/niftis HF dataset. |
get_bg_image | Get a background image path matching a data resolution. |
get_brainspace | Return the current global brain-space configuration. |
is_standard_space | Check whether an affine is compatible with our MNI templates. |
list_resources | List files available in the nltools/niftis HF dataset. |
match_resolution | Find the best matching template for a given affine matrix. |
reset_brainspace | Reset the global brain-space configuration to defaults. |
resolve_paths | Build mask/brain/plot paths for a template + resolution. |
resolve_template_name | Resolve a template name string to a file path. |
set_brainspace | Set the global brain-space configuration. |
with_brainspace | Temporarily change the global brain-space configuration. |
Modules:
| Name | Description |
|---|---|
config | Global brain-space configuration: frozen dataclass + set/get/with API. |
fetch | Lazy fetcher for files hosted in the nltools/niftis HF dataset. |
matching | Affine-based template matching and background-image selection. |
paths | Pure path-resolution helpers for MNI template files. |
registry | Static registry of supported MNI templates. |
Examples:
Set the global brain space:
import nltools
nltools.set_brainspace(template="fmriprep", resolution=2)Inspect the current configuration:
cfg = nltools.get_brainspace()
print(cfg.mask)Scope a change to a block:
with nltools.with_brainspace(resolution=1):
brain = BrainData(...)Classes¶
BrainSpaceConfig¶
BrainSpaceConfig(template: TemplateName = 'default', resolution: Resolution = 2) -> NoneImmutable MNI template configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
template | TemplateName | Template variant ('default', 'nilearn', 'fmriprep'). |
resolution | Resolution | Resolution in mm (1, 2, or 3). |
TemplateMatch¶
TemplateMatch(template: str, resolution: int, mask_path: str, brain_path: str, plot_path: str, match_distance: float) -> NoneResult of matching a data affine to a template.
Attributes:
| Name | Type | Description |
|---|---|---|
template | str | Best-matching template name. |
resolution | int | Best-matching resolution in mm. |
mask_path | str | Path to the matched mask file. |
brain_path | str | Path to the matched brain file. |
plot_path | str | Path to the matched T1/plot file. |
match_distance | float | Absolute difference in mm between detected data resolution and the selected template resolution (0 for exact). |
Methods¶
fetch_resource¶
fetch_resource(relpath: str) -> strReturn a local path to a file from the nltools/niftis HF dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relpath | str | Path within the dataset repo, e.g. 'default/2mm-MNI152-2009fsl-mask.nii.gz' or 'masks/k88_parcel_names.csv'. Use list_resources to enumerate what’s available. | required |
Returns:
| Type | Description |
|---|---|
str | Absolute path to the cached file on disk. The returned path drops |
str | straight into anything that takes a NIfTI path — nilearn plotting |
str | and masking helpers, nibabel.load, and BrainData(path). |
Note
Resolution is memoized per relpath for the session — repeated calls (e.g. every default-mask BrainData construction) return the cached path with no work. On the first call for a file already in the HF cache we resolve it with local_files_only=True so we never make a network round-trip to revalidate an ETag; only a genuine cache miss touches the network.
get_bg_image¶
get_bg_image(affine: np.ndarray, img_type: str = 'brain', config: BrainSpaceConfig | None = None) -> strGet a background image path matching a data resolution.
Uses config (or the current global brain space) and finds the
matching resolution from the affine. Used by plotting functions to pick
an appropriate background anatomical.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
affine | ndarray | 4x4 affine matrix from a BrainData’s masker. | required |
img_type | str | 'brain' for brain-extracted image or 'plot' for full T1. | ‘brain’ |
config | BrainSpaceConfig | None | Optional explicit config; defaults to current global. | None |
Returns:
| Type | Description |
|---|---|
str | Path to the template image file. |
get_brainspace¶
get_brainspace() -> BrainSpaceConfigReturn the current global brain-space configuration.
is_standard_space¶
is_standard_space(affine: np.ndarray, *, config: BrainSpaceConfig | None = None) -> tuple[bool, str | None]Check whether an affine is compatible with our MNI templates.
A “standard space” affine has isotropic voxels at one of the supported
template resolutions (the union of SUPPORTED_RESOLUTIONS). Plotting
surfaces (glass brain, flatmap, surface montage) and template-driven
background lookup all assume this — non-isotropic or off-grid data
would render in misleading positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
affine | ndarray | 4x4 affine matrix from a NIfTI image (typically bd.mask.affine). | required |
config | BrainSpaceConfig | None | Optional explicit BrainSpaceConfig; defaults to the current global brain space (only the supported resolution set is consulted). | None |
Returns:
| Type | Description |
|---|---|
bool | (True, None) if compatible; otherwise (False, reason) with |
str | None | reason a one-line human-readable explanation suitable for |
tuple [ bool , str | None] | embedding in an error message. |
list_resources¶
list_resources(prefix: str | None = None) -> list[str]List files available in the nltools/niftis HF dataset.
Companion to fetch_resource — surfaces what’s downloadable
without forcing users to remember relpath strings or visit the HF
web UI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix | str | None | Optional path prefix to filter by (e.g., 'masks/', 'default/', 'fmriprep/'). Matches with str.startswith. | None |
Returns:
| Type | Description |
|---|---|
list [ str ] | Sorted list of relative paths usable with fetch_resource. |
Note
Hits the HF API once per session (cached).
match_resolution¶
match_resolution(affine: np.ndarray, prefer_exact: bool = True, warn_resample: bool = True) -> TemplateMatchFind the best matching template for a given affine matrix.
Searches available templates by priority and returns the one whose resolution most closely matches the data’s voxel size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
affine | ndarray | 4x4 affine matrix from a NIfTI image. | required |
prefer_exact | bool | If True, prefer an exact resolution match. | True |
warn_resample | bool | If True, emit a warning when data resolution doesn’t exactly match the selected template. | True |
Returns:
| Type | Description |
|---|---|
TemplateMatch | A TemplateMatch. |
reset_brainspace¶
reset_brainspace() -> BrainSpaceConfigReset the global brain-space configuration to defaults.
resolve_paths¶
resolve_paths(template: str, resolution: int) -> dict[str, str]Build mask/brain/plot paths for a template + resolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template | str | Template name ('default', 'nilearn', 'fmriprep'). | required |
resolution | int | Resolution in mm. | required |
Returns:
| Type | Description |
|---|---|
dict [ str , str ] | Dict with keys 'mask', 'brain', 'plot'. |
resolve_template_name¶
resolve_template_name(template_name: str, file_type: str = 'mask') -> strResolve a template name string to a file path.
Supports names of the form '{res}mm-MNI152-2009{version}'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template_name | str | e.g. '2mm-MNI152-2009c', '3mm-MNI152-2009a'. | required |
file_type | str | 'mask', 'brain', or 'T1'. | ‘mask’ |
Returns:
| Type | Description |
|---|---|
str | Absolute path to the requested template file. |
set_brainspace¶
set_brainspace(template: TemplateName | None = None, resolution: Resolution | None = None) -> BrainSpaceConfigSet the global brain-space configuration.
Call with no arguments to return the current config without mutating it. Call with one or both arguments to mutate the global state; unspecified fields retain their current value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template | TemplateName | None | Template name to set. If None, keeps current. | None |
resolution | Resolution | None | Resolution to set. If None, keeps current. | None |
Returns:
| Type | Description |
|---|---|
BrainSpaceConfig | The new (or unchanged) current BrainSpaceConfig. |
with_brainspace¶
with_brainspace(template: TemplateName | None = None, resolution: Resolution | None = None) -> Iterator[BrainSpaceConfig]Temporarily change the global brain-space configuration.
Restores the previous configuration on exit, even if an exception is raised inside the block.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template | TemplateName | None | Template name for the duration of the block. | None |
resolution | Resolution | None | Resolution for the duration of the block. | None |
Yields:
| Type | Description |
|---|---|
BrainSpaceConfig | The BrainSpaceConfig active inside the block. |
Modules¶
config¶
Global brain-space configuration: frozen dataclass + set/get/with API.
Classes:
| Name | Description |
|---|---|
BrainSpaceConfig | Immutable MNI template configuration. |
Methods:
| Name | Description |
|---|---|
get_brainspace | Return the current global brain-space configuration. |
reset_brainspace | Reset the global brain-space configuration to defaults. |
set_brainspace | Set the global brain-space configuration. |
with_brainspace | Temporarily change the global brain-space configuration. |
Classes¶
BrainSpaceConfig¶
BrainSpaceConfig(template: TemplateName = 'default', resolution: Resolution = 2) -> NoneImmutable MNI template configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
template | TemplateName | Template variant ('default', 'nilearn', 'fmriprep'). |
resolution | Resolution | Resolution in mm (1, 2, or 3). |
####### Attributes##
brain¶
brain: strPath to the brain-extracted image.
######## mask
mask: strPath to the brain mask file.
######## plot
plot: strPath to the full T1 image used for plotting.
######## resolution
resolution: Resolution = 2######## template
template: TemplateName = 'default'Methods¶
get_brainspace¶
get_brainspace() -> BrainSpaceConfigReturn the current global brain-space configuration.
reset_brainspace¶
reset_brainspace() -> BrainSpaceConfigReset the global brain-space configuration to defaults.
set_brainspace¶
set_brainspace(template: TemplateName | None = None, resolution: Resolution | None = None) -> BrainSpaceConfigSet the global brain-space configuration.
Call with no arguments to return the current config without mutating it. Call with one or both arguments to mutate the global state; unspecified fields retain their current value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template | TemplateName | None | Template name to set. If None, keeps current. | None |
resolution | Resolution | None | Resolution to set. If None, keeps current. | None |
Returns:
| Type | Description |
|---|---|
BrainSpaceConfig | The new (or unchanged) current BrainSpaceConfig. |
with_brainspace¶
with_brainspace(template: TemplateName | None = None, resolution: Resolution | None = None) -> Iterator[BrainSpaceConfig]Temporarily change the global brain-space configuration.
Restores the previous configuration on exit, even if an exception is raised inside the block.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template | TemplateName | None | Template name for the duration of the block. | None |
resolution | Resolution | None | Resolution for the duration of the block. | None |
Yields:
| Type | Description |
|---|---|
BrainSpaceConfig | The BrainSpaceConfig active inside the block. |
fetch¶
Lazy fetcher for files hosted in the nltools/niftis HF dataset.
Covers MNI templates, parcellation label maps, the parcel-names CSV, and
any other resources living under huggingface~/.cache/huggingface/hub by default); subsequent calls return the
cached path without touching the network.
Attributes:
| Name | Type | Description |
|---|---|---|
REPO_ID | ||
REVISION |
Methods:
| Name | Description |
|---|---|
fetch_resource | Return a local path to a file from the nltools/niftis HF dataset. |
list_resources | List files available in the nltools/niftis HF dataset. |
Methods¶
fetch_resource¶
fetch_resource(relpath: str) -> strReturn a local path to a file from the nltools/niftis HF dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relpath | str | Path within the dataset repo, e.g. 'default/2mm-MNI152-2009fsl-mask.nii.gz' or 'masks/k88_parcel_names.csv'. Use list_resources to enumerate what’s available. | required |
Returns:
| Type | Description |
|---|---|
str | Absolute path to the cached file on disk. The returned path drops |
str | straight into anything that takes a NIfTI path — nilearn plotting |
str | and masking helpers, nibabel.load, and BrainData(path). |
Note
Resolution is memoized per relpath for the session — repeated calls (e.g. every default-mask BrainData construction) return the cached path with no work. On the first call for a file already in the HF cache we resolve it with local_files_only=True so we never make a network round-trip to revalidate an ETag; only a genuine cache miss touches the network.
list_resources¶
list_resources(prefix: str | None = None) -> list[str]List files available in the nltools/niftis HF dataset.
Companion to fetch_resource — surfaces what’s downloadable
without forcing users to remember relpath strings or visit the HF
web UI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix | str | None | Optional path prefix to filter by (e.g., 'masks/', 'default/', 'fmriprep/'). Matches with str.startswith. | None |
Returns:
| Type | Description |
|---|---|
list [ str ] | Sorted list of relative paths usable with fetch_resource. |
Note
Hits the HF API once per session (cached).
matching¶
Affine-based template matching and background-image selection.
Classes:
| Name | Description |
|---|---|
TemplateMatch | Result of matching a data affine to a template. |
Methods:
| Name | Description |
|---|---|
detect_resolution | Detect voxel resolution (mm) and isotropy from a NIfTI affine. |
get_bg_image | Get a background image path matching a data resolution. |
is_standard_space | Check whether an affine is compatible with our MNI templates. |
match_resolution | Find the best matching template for a given affine matrix. |
Classes¶
TemplateMatch¶
TemplateMatch(template: str, resolution: int, mask_path: str, brain_path: str, plot_path: str, match_distance: float) -> NoneResult of matching a data affine to a template.
Attributes:
| Name | Type | Description |
|---|---|---|
template | str | Best-matching template name. |
resolution | int | Best-matching resolution in mm. |
mask_path | str | Path to the matched mask file. |
brain_path | str | Path to the matched brain file. |
plot_path | str | Path to the matched T1/plot file. |
match_distance | float | Absolute difference in mm between detected data resolution and the selected template resolution (0 for exact). |
####### Attributes##
brain_path¶
brain_path: str######## mask_path
mask_path: str######## match_distance
match_distance: float######## plot_path
plot_path: str######## resolution
resolution: int######## template
template: strMethods¶
detect_resolution¶
detect_resolution(affine: np.ndarray) -> tuple[float, bool]Detect voxel resolution (mm) and isotropy from a NIfTI affine.
Voxels are treated as isotropic when the per-axis sizes agree to within three decimals. The reported resolution is that shared isotropic size, or the mean of the per-axis sizes when non-isotropic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
affine | ndarray | 4x4 affine matrix from a NIfTI image. | required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple | tuple [ float , bool ] | (resolution_mm, is_isotropic). |
get_bg_image¶
get_bg_image(affine: np.ndarray, img_type: str = 'brain', config: BrainSpaceConfig | None = None) -> strGet a background image path matching a data resolution.
Uses config (or the current global brain space) and finds the
matching resolution from the affine. Used by plotting functions to pick
an appropriate background anatomical.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
affine | ndarray | 4x4 affine matrix from a BrainData’s masker. | required |
img_type | str | 'brain' for brain-extracted image or 'plot' for full T1. | ‘brain’ |
config | BrainSpaceConfig | None | Optional explicit config; defaults to current global. | None |
Returns:
| Type | Description |
|---|---|
str | Path to the template image file. |
is_standard_space¶
is_standard_space(affine: np.ndarray, *, config: BrainSpaceConfig | None = None) -> tuple[bool, str | None]Check whether an affine is compatible with our MNI templates.
A “standard space” affine has isotropic voxels at one of the supported
template resolutions (the union of SUPPORTED_RESOLUTIONS). Plotting
surfaces (glass brain, flatmap, surface montage) and template-driven
background lookup all assume this — non-isotropic or off-grid data
would render in misleading positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
affine | ndarray | 4x4 affine matrix from a NIfTI image (typically bd.mask.affine). | required |
config | BrainSpaceConfig | None | Optional explicit BrainSpaceConfig; defaults to the current global brain space (only the supported resolution set is consulted). | None |
Returns:
| Type | Description |
|---|---|
bool | (True, None) if compatible; otherwise (False, reason) with |
str | None | reason a one-line human-readable explanation suitable for |
tuple [ bool , str | None] | embedding in an error message. |
match_resolution¶
match_resolution(affine: np.ndarray, prefer_exact: bool = True, warn_resample: bool = True) -> TemplateMatchFind the best matching template for a given affine matrix.
Searches available templates by priority and returns the one whose resolution most closely matches the data’s voxel size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
affine | ndarray | 4x4 affine matrix from a NIfTI image. | required |
prefer_exact | bool | If True, prefer an exact resolution match. | True |
warn_resample | bool | If True, emit a warning when data resolution doesn’t exactly match the selected template. | True |
Returns:
| Type | Description |
|---|---|
TemplateMatch | A TemplateMatch. |
paths¶
Pure path-resolution helpers for MNI template files.
Resolves logical (template, resolution, file_type) tuples to local paths.
Files are fetched on first use from the nltools/niftis HF dataset; see
nltools.templates.fetch.
Methods:
| Name | Description |
|---|---|
resolve_paths | Build mask/brain/plot paths for a template + resolution. |
resolve_template_name | Resolve a template name string to a file path. |
Methods¶
resolve_paths¶
resolve_paths(template: str, resolution: int) -> dict[str, str]Build mask/brain/plot paths for a template + resolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template | str | Template name ('default', 'nilearn', 'fmriprep'). | required |
resolution | int | Resolution in mm. | required |
Returns:
| Type | Description |
|---|---|
dict [ str , str ] | Dict with keys 'mask', 'brain', 'plot'. |
resolve_template_name¶
resolve_template_name(template_name: str, file_type: str = 'mask') -> strResolve a template name string to a file path.
Supports names of the form '{res}mm-MNI152-2009{version}'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template_name | str | e.g. '2mm-MNI152-2009c', '3mm-MNI152-2009a'. | required |
file_type | str | 'mask', 'brain', or 'T1'. | ‘mask’ |
Returns:
| Type | Description |
|---|---|
str | Absolute path to the requested template file. |
registry¶
Static registry of supported MNI templates.
Attributes:
| Name | Type | Description |
|---|---|---|
Resolution | ||
SUPPORTED_RESOLUTIONS | dict [ str , list [ int ]] | |
TEMPLATE_PRIORITY | list [ str ] | |
TemplateName | ||
VERSION_MAP | dict [ str , str ] | |
VERSION_TO_TEMPLATE | dict [ str , str ] |