Skip to content

Index

lacuna.assets.masks

Brain mask assets.

Binary brain masks per coordinate space and resolution, redistributed via OSF and downloaded/cached on first use. See :func:load_brain_mask.

BrainMaskMetadata dataclass

Bases: SpatialAssetMetadata

Metadata for a binary brain mask.

Attributes:

Name Type Description
space str

Coordinate space (e.g. "MNI152NLin6Asym").

resolution float

Voxel resolution in mm (1.0 or 2.0).

url str

Download URL (fetched and cached on first use).

sha256 str

Expected SHA-256 of the file (verified on download).

source str

Origin of the mask data.

Source code in src/lacuna/assets/masks/registry.py
@dataclass(frozen=True)
class BrainMaskMetadata(SpatialAssetMetadata):
    """Metadata for a binary brain mask.

    Attributes
    ----------
    space : str
        Coordinate space (e.g. "MNI152NLin6Asym").
    resolution : float
        Voxel resolution in mm (1.0 or 2.0).
    url : str
        Download URL (fetched and cached on first use).
    sha256 : str
        Expected SHA-256 of the file (verified on download).
    source : str
        Origin of the mask data.
    """

    url: str = ""
    sha256: str = ""
    source: str = "templateflow"

load_brain_mask(space, resolution, *, validate=True)

Load a binary brain mask for space/resolution, caching on first use.

Anatomically identical spaces (e.g. MNI152NLin2009[abc]Asym) are normalized to their canonical form before lookup.

Parameters:

Name Type Description Default
space str

Coordinate space identifier (e.g. "MNI152NLin6Asym").

required
resolution float

Voxel resolution in mm (1.0 or 2.0).

required
validate bool

Verify the downloaded file is a binary 3D mask on the canonical grid.

True

Returns:

Type Description
Path

Path to the locally cached brain mask (.nii.gz).

Raises:

Type Description
KeyError

If no mask is registered for the space/resolution.

FileNotFoundError

If the mask has no URL or the download fails.

ValueError

If validation fails.

Source code in src/lacuna/assets/masks/loader.py
def load_brain_mask(space: str, resolution: float, *, validate: bool = True) -> Path:
    """Load a binary brain mask for ``space``/``resolution``, caching on first use.

    Anatomically identical spaces (e.g. MNI152NLin2009[abc]Asym) are normalized to
    their canonical form before lookup.

    Parameters
    ----------
    space : str
        Coordinate space identifier (e.g. "MNI152NLin6Asym").
    resolution : float
        Voxel resolution in mm (1.0 or 2.0).
    validate : bool, default True
        Verify the downloaded file is a binary 3D mask on the canonical grid.

    Returns
    -------
    Path
        Path to the locally cached brain mask (.nii.gz).

    Raises
    ------
    KeyError
        If no mask is registered for the space/resolution.
    FileNotFoundError
        If the mask has no URL or the download fails.
    ValueError
        If validation fails.
    """
    canonical_space = _canonicalize_space_variant(space)
    name = mask_name(canonical_space, float(resolution))
    metadata = BRAIN_MASK_REGISTRY.get(name)  # KeyError if unknown

    if not metadata.url:
        raise FileNotFoundError(f"Brain mask '{name}' has no download URL registered.")

    try:
        import pooch
    except ImportError as e:  # pragma: no cover - pooch is a hard dependency
        raise ImportError(
            "pooch is required to download brain masks. Install with: pip install pooch"
        ) from e

    from lacuna.utils.cache import get_cache_dir

    cache_dir = Path(get_cache_dir()) / "masks"
    logger.debug(f"Loading brain mask {name} from {metadata.url}")
    try:
        path = pooch.retrieve(
            url=metadata.url,
            known_hash=f"sha256:{metadata.sha256}" if metadata.sha256 else None,
            fname=f"{name}_desc-brain_mask.nii.gz",
            path=cache_dir,
            progressbar=True,
        )
    except Exception as e:
        raise FileNotFoundError(
            f"Failed to download brain mask '{name}' from {metadata.url}: {e}"
        ) from e

    path = Path(path)
    if validate:
        _validate_mask(path, canonical_space, float(resolution))
    return path

mask_name(space, resolution)

Registry key for a brain mask, e.g. MNI152NLin6Asym_2mm.

Source code in src/lacuna/assets/masks/registry.py
def mask_name(space: str, resolution: float) -> str:
    """Registry key for a brain mask, e.g. ``MNI152NLin6Asym_2mm``."""
    return f"{space}_{resolution:g}mm"