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.

templates

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:

NameDescription
BrainSpaceConfigImmutable MNI template configuration.
TemplateMatchResult of matching a data affine to a template.

Methods:

NameDescription
fetch_resourceReturn a local path to a file from the nltools/niftis HF dataset.
get_bg_imageGet a background image path matching a data resolution.
get_brainspaceReturn the current global brain-space configuration.
is_standard_spaceCheck whether an affine is compatible with our MNI templates.
list_resourcesList files available in the nltools/niftis HF dataset.
match_resolutionFind the best matching template for a given affine matrix.
reset_brainspaceReset the global brain-space configuration to defaults.
resolve_pathsBuild mask/brain/plot paths for a template + resolution.
resolve_template_nameResolve a template name string to a file path.
set_brainspaceSet the global brain-space configuration.
with_brainspaceTemporarily change the global brain-space configuration.

Modules:

NameDescription
configGlobal brain-space configuration: frozen dataclass + set/get/with API.
fetchLazy fetcher for files hosted in the nltools/niftis HF dataset.
matchingAffine-based template matching and background-image selection.
pathsPure path-resolution helpers for MNI template files.
registryStatic 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) -> None

Immutable MNI template configuration.

Attributes:

NameTypeDescription
templateTemplateNameTemplate variant ('default', 'nilearn', 'fmriprep').
resolutionResolutionResolution in mm (1, 2, or 3).

TemplateMatch

TemplateMatch(template: str, resolution: int, mask_path: str, brain_path: str, plot_path: str, match_distance: float) -> None

Result of matching a data affine to a template.

Attributes:

NameTypeDescription
templatestrBest-matching template name.
resolutionintBest-matching resolution in mm.
mask_pathstrPath to the matched mask file.
brain_pathstrPath to the matched brain file.
plot_pathstrPath to the matched T1/plot file.
match_distancefloatAbsolute difference in mm between detected data resolution and the selected template resolution (0 for exact).

Methods

fetch_resource

fetch_resource(relpath: str) -> str

Return a local path to a file from the nltools/niftis HF dataset.

Parameters:

NameTypeDescriptionDefault
relpathstrPath 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:

TypeDescription
strAbsolute path to the cached file on disk. The returned path drops
strstraight into anything that takes a NIfTI path — nilearn plotting
strand 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) -> str

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

NameTypeDescriptionDefault
affinendarray4x4 affine matrix from a BrainData’s masker.required
img_typestr'brain' for brain-extracted image or 'plot' for full T1.‘brain’
configBrainSpaceConfig | NoneOptional explicit config; defaults to current global.None

Returns:

TypeDescription
strPath to the template image file.

get_brainspace

get_brainspace() -> BrainSpaceConfig

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

NameTypeDescriptionDefault
affinendarray4x4 affine matrix from a NIfTI image (typically bd.mask.affine).required
configBrainSpaceConfig | NoneOptional explicit BrainSpaceConfig; defaults to the current global brain space (only the supported resolution set is consulted).None

Returns:

TypeDescription
bool(True, None) if compatible; otherwise (False, reason) with
str | Nonereason 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:

NameTypeDescriptionDefault
prefixstr | NoneOptional path prefix to filter by (e.g., 'masks/', 'default/', 'fmriprep/'). Matches with str.startswith.None

Returns:

TypeDescription
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) -> TemplateMatch

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

NameTypeDescriptionDefault
affinendarray4x4 affine matrix from a NIfTI image.required
prefer_exactboolIf True, prefer an exact resolution match.True
warn_resampleboolIf True, emit a warning when data resolution doesn’t exactly match the selected template.True

Returns:

TypeDescription
TemplateMatchA TemplateMatch.

reset_brainspace

reset_brainspace() -> BrainSpaceConfig

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

NameTypeDescriptionDefault
templatestrTemplate name ('default', 'nilearn', 'fmriprep').required
resolutionintResolution in mm.required

Returns:

TypeDescription
dict [ str , str ]Dict with keys 'mask', 'brain', 'plot'.

resolve_template_name

resolve_template_name(template_name: str, file_type: str = 'mask') -> str

Resolve a template name string to a file path.

Supports names of the form '{res}mm-MNI152-2009{version}'.

Parameters:

NameTypeDescriptionDefault
template_namestre.g. '2mm-MNI152-2009c', '3mm-MNI152-2009a'.required
file_typestr'mask', 'brain', or 'T1'.‘mask’

Returns:

TypeDescription
strAbsolute path to the requested template file.

set_brainspace

set_brainspace(template: TemplateName | None = None, resolution: Resolution | None = None) -> BrainSpaceConfig

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

NameTypeDescriptionDefault
templateTemplateName | NoneTemplate name to set. If None, keeps current.None
resolutionResolution | NoneResolution to set. If None, keeps current.None

Returns:

TypeDescription
BrainSpaceConfigThe 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:

NameTypeDescriptionDefault
templateTemplateName | NoneTemplate name for the duration of the block.None
resolutionResolution | NoneResolution for the duration of the block.None

Yields:

TypeDescription
BrainSpaceConfigThe BrainSpaceConfig active inside the block.

Modules

config

Global brain-space configuration: frozen dataclass + set/get/with API.

Classes:

NameDescription
BrainSpaceConfigImmutable MNI template configuration.

Methods:

NameDescription
get_brainspaceReturn the current global brain-space configuration.
reset_brainspaceReset the global brain-space configuration to defaults.
set_brainspaceSet the global brain-space configuration.
with_brainspaceTemporarily change the global brain-space configuration.

Classes

BrainSpaceConfig
BrainSpaceConfig(template: TemplateName = 'default', resolution: Resolution = 2) -> None

Immutable MNI template configuration.

Attributes:

NameTypeDescription
templateTemplateNameTemplate variant ('default', 'nilearn', 'fmriprep').
resolutionResolutionResolution in mm (1, 2, or 3).

####### Attributes##

brain
brain: str

Path to the brain-extracted image.

######## mask

mask: str

Path to the brain mask file.

######## plot

plot: str

Path to the full T1 image used for plotting.

######## resolution

resolution: Resolution = 2

######## template

template: TemplateName = 'default'

Methods

get_brainspace
get_brainspace() -> BrainSpaceConfig

Return the current global brain-space configuration.

reset_brainspace
reset_brainspace() -> BrainSpaceConfig

Reset the global brain-space configuration to defaults.

set_brainspace
set_brainspace(template: TemplateName | None = None, resolution: Resolution | None = None) -> BrainSpaceConfig

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

NameTypeDescriptionDefault
templateTemplateName | NoneTemplate name to set. If None, keeps current.None
resolutionResolution | NoneResolution to set. If None, keeps current.None

Returns:

TypeDescription
BrainSpaceConfigThe 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:

NameTypeDescriptionDefault
templateTemplateName | NoneTemplate name for the duration of the block.None
resolutionResolution | NoneResolution for the duration of the block.None

Yields:

TypeDescription
BrainSpaceConfigThe 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.co/datasets/nltools/niftis. First call for a given file downloads it into the local HF cache (~/.cache/huggingface/hub by default); subsequent calls return the cached path without touching the network.

Attributes:

NameTypeDescription
REPO_ID
REVISION

Methods:

NameDescription
fetch_resourceReturn a local path to a file from the nltools/niftis HF dataset.
list_resourcesList files available in the nltools/niftis HF dataset.

Methods

fetch_resource
fetch_resource(relpath: str) -> str

Return a local path to a file from the nltools/niftis HF dataset.

Parameters:

NameTypeDescriptionDefault
relpathstrPath 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:

TypeDescription
strAbsolute path to the cached file on disk. The returned path drops
strstraight into anything that takes a NIfTI path — nilearn plotting
strand 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:

NameTypeDescriptionDefault
prefixstr | NoneOptional path prefix to filter by (e.g., 'masks/', 'default/', 'fmriprep/'). Matches with str.startswith.None

Returns:

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

NameDescription
TemplateMatchResult of matching a data affine to a template.

Methods:

NameDescription
detect_resolutionDetect voxel resolution (mm) and isotropy from a NIfTI affine.
get_bg_imageGet a background image path matching a data resolution.
is_standard_spaceCheck whether an affine is compatible with our MNI templates.
match_resolutionFind 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) -> None

Result of matching a data affine to a template.

Attributes:

NameTypeDescription
templatestrBest-matching template name.
resolutionintBest-matching resolution in mm.
mask_pathstrPath to the matched mask file.
brain_pathstrPath to the matched brain file.
plot_pathstrPath to the matched T1/plot file.
match_distancefloatAbsolute 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: str

Methods

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:

NameTypeDescriptionDefault
affinendarray4x4 affine matrix from a NIfTI image.required

Returns:

NameTypeDescription
tupletuple [ float , bool ](resolution_mm, is_isotropic).
get_bg_image
get_bg_image(affine: np.ndarray, img_type: str = 'brain', config: BrainSpaceConfig | None = None) -> str

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

NameTypeDescriptionDefault
affinendarray4x4 affine matrix from a BrainData’s masker.required
img_typestr'brain' for brain-extracted image or 'plot' for full T1.‘brain’
configBrainSpaceConfig | NoneOptional explicit config; defaults to current global.None

Returns:

TypeDescription
strPath 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:

NameTypeDescriptionDefault
affinendarray4x4 affine matrix from a NIfTI image (typically bd.mask.affine).required
configBrainSpaceConfig | NoneOptional explicit BrainSpaceConfig; defaults to the current global brain space (only the supported resolution set is consulted).None

Returns:

TypeDescription
bool(True, None) if compatible; otherwise (False, reason) with
str | Nonereason 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) -> TemplateMatch

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

NameTypeDescriptionDefault
affinendarray4x4 affine matrix from a NIfTI image.required
prefer_exactboolIf True, prefer an exact resolution match.True
warn_resampleboolIf True, emit a warning when data resolution doesn’t exactly match the selected template.True

Returns:

TypeDescription
TemplateMatchA 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:

NameDescription
resolve_pathsBuild mask/brain/plot paths for a template + resolution.
resolve_template_nameResolve 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:

NameTypeDescriptionDefault
templatestrTemplate name ('default', 'nilearn', 'fmriprep').required
resolutionintResolution in mm.required

Returns:

TypeDescription
dict [ str , str ]Dict with keys 'mask', 'brain', 'plot'.
resolve_template_name
resolve_template_name(template_name: str, file_type: str = 'mask') -> str

Resolve a template name string to a file path.

Supports names of the form '{res}mm-MNI152-2009{version}'.

Parameters:

NameTypeDescriptionDefault
template_namestre.g. '2mm-MNI152-2009c', '3mm-MNI152-2009a'.required
file_typestr'mask', 'brain', or 'T1'.‘mask’

Returns:

TypeDescription
strAbsolute path to the requested template file.

registry

Static registry of supported MNI templates.

Attributes:

NameTypeDescription
Resolution
SUPPORTED_RESOLUTIONSdict [ str , list [ int ]]
TEMPLATE_PRIORITYlist [ str ]
TemplateName
VERSION_MAPdict [ str , str ]
VERSION_TO_TEMPLATEdict [ str , str ]