Skip to content

loader

lacuna.assets.transforms.loader

Transform loading.

Loads spatial transforms between template spaces. The nonlinear warps between MNI152NLin6Asym and MNI152NLin2009cAsym are generated by TemplateFlow and redistributed via OSF; they are downloaded (with SHA-256 verification) and cached locally on first use via pooch.

is_transform_cached(name)

Check if a transform is already cached locally (without downloading).

Parameters:

Name Type Description Default
name str

Transform name from registry.

required

Returns:

Type Description
bool

True if the transform file is already present in the local cache.

Source code in src/lacuna/assets/transforms/loader.py
def is_transform_cached(name: str) -> bool:
    """Check if a transform is already cached locally (without downloading).

    Parameters
    ----------
    name : str
        Transform name from registry.

    Returns
    -------
    bool
        True if the transform file is already present in the local cache.
    """
    parts = name.split("_to_")
    if len(parts) == 2:
        normalized_name = (
            f"{_canonicalize_space_variant(parts[0])}_to_"
            f"{_canonicalize_space_variant(parts[1])}"
        )
    else:
        normalized_name = name

    try:
        from lacuna.utils.cache import get_cache_dir

        cache_path = Path(get_cache_dir()) / "transforms" / f"{normalized_name}.h5"
        return cache_path.exists() and cache_path.stat().st_size > 0
    except Exception:
        return False

load_transform(name)

Load a spatial transform by name, downloading and caching on first use.

Supports space equivalence: anatomically identical spaces like MNI152NLin2009[abc]Asym are automatically normalized to their canonical form (cAsym) before lookup.

Parameters:

Name Type Description Default
name str

Transform name from registry (e.g., "MNI152NLin6Asym_to_MNI152NLin2009cAsym").

required

Returns:

Type Description
Path

Path to the locally cached transform (.h5) file.

Raises:

Type Description
KeyError

If the transform is not found in the registry.

FileNotFoundError

If the transform has no download URL or the download fails.

Examples:

>>> from lacuna.assets.transforms import load_transform
>>> transform_path = load_transform("MNI152NLin6Asym_to_MNI152NLin2009cAsym")
>>> print(transform_path.exists())
True
Source code in src/lacuna/assets/transforms/loader.py
def load_transform(name: str) -> Path:
    """Load a spatial transform by name, downloading and caching on first use.

    Supports space equivalence: anatomically identical spaces like
    MNI152NLin2009[abc]Asym are automatically normalized to their canonical
    form (cAsym) before lookup.

    Parameters
    ----------
    name : str
        Transform name from registry
        (e.g., "MNI152NLin6Asym_to_MNI152NLin2009cAsym").

    Returns
    -------
    Path
        Path to the locally cached transform (.h5) file.

    Raises
    ------
    KeyError
        If the transform is not found in the registry.
    FileNotFoundError
        If the transform has no download URL or the download fails.

    Examples
    --------
    >>> from lacuna.assets.transforms import load_transform
    >>> transform_path = load_transform("MNI152NLin6Asym_to_MNI152NLin2009cAsym")
    >>> print(transform_path.exists())
    True
    """
    # Normalize the requested transform name to handle space aliases,
    # e.g. "MNI152NLin2009aAsym_to_X" -> "MNI152NLin2009cAsym_to_X".
    parts = name.split("_to_")
    if len(parts) == 2:
        from_space, to_space = parts
        normalized_name = (
            f"{_canonicalize_space_variant(from_space)}_to_"
            f"{_canonicalize_space_variant(to_space)}"
        )
    else:
        normalized_name = name

    if normalized_name != name:
        logger.info(
            f"Using space equivalence: {name} → {normalized_name} "
            f"(anatomically identical spaces)"
        )

    # Look up metadata (raises KeyError if unknown).
    metadata = TRANSFORM_REGISTRY.get(normalized_name)

    if not metadata.url:
        raise FileNotFoundError(f"Transform '{normalized_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 spatial transforms. " "Install with: pip install pooch"
        ) from e

    from lacuna.utils.cache import get_cache_dir

    cache_dir = Path(get_cache_dir()) / "transforms"

    logger.debug(f"Loading transform {normalized_name} from {metadata.url}")
    try:
        path = pooch.retrieve(
            url=metadata.url,
            known_hash=f"sha256:{metadata.sha256}" if metadata.sha256 else None,
            fname=f"{normalized_name}.h5",
            path=cache_dir,
            progressbar=True,
        )
    except Exception as e:
        raise FileNotFoundError(
            f"Failed to download transform '{normalized_name}' from {metadata.url}: {e}"
        ) from e

    return Path(path)