Skip to content

confusius.atlas

atlas

Brain atlases and region-aware utilities.

An atlas is an xarray.Dataset with a registered .atlas accessor. Fetch one from BrainGlobe with fetch_brainglobe_atlas, save/load it with save_atlas / load_atlas, and operate on it through ds.atlas.* (see AtlasAccessor). The core operations are also exposed as standalone functions that take the Dataset as their first argument — get_atlas_mesh, get_atlas_masks, and search_atlas — each of which validates its input as an atlas first.

Classes:

  • AtlasAccessor

    Brain-atlas operations on an atlas xarray.Dataset.

Functions:

  • get_atlas_masks

    Return integer region masks stacked along a mask dimension.

  • get_atlas_mesh

    Return vertex coordinates and face indices for a region's mesh.

  • search_atlas

    Search an atlas Dataset's structures by name or acronym.

AtlasAccessor

Brain-atlas operations on an atlas xarray.Dataset.

Registered as the .atlas namespace on any Dataset produced by fetch_brainglobe_atlas or load_atlas. Dataset.attrs["structures"] holds the BrainGlobe StructuresDict directly, so structural queries keep working for as long as that attribute rides along (xarray drops attrs on many ops by default; use xarray.set_options(keep_attrs=True) in pipelines).

Parameters:

  • ds

    (Dataset) –

    Atlas Dataset with reference, annotation, and hemispheres data variables as VoxelData arrays on a common k/j/i grid, and the atlas metadata in attrs.

Methods:

  • ancestors

    Return the ancestor nodes of region, from root down (exclusive).

  • get_masks

    Return integer region masks stacked along a mask dimension.

  • get_mesh

    Return vertex coordinates and face indices for a region's mesh.

  • resample

    Resample the atlas onto an explicit output grid.

  • resample_like

    Resample the atlas onto reference's VoxelData grid.

  • search

    Search structures by name or acronym.

  • show_tree

    Print the structure hierarchy tree.

Attributes:

annotation property

annotation: DataArray

Region annotations VoxelData array.

attrs["rgb_lookup"] carries a {id: [r, g, b]} dict used for colormap construction.

Returns:

  • DataArray

    The region annotation VoxelData array with integer labels.

cmap property

ListedColormap derived from annotation.attrs["rgb_lookup"].

Returns:

hemispheres property

hemispheres: DataArray

Hemisphere map VoxelData array (1 = left, 2 = right).

Returns:

  • DataArray

    The hemisphere map VoxelData array.

lookup property

lookup: DataFrame

DataFrame with columns acronym, name, rgb_triplet.

The DataFrame is indexed by structure index.

Returns:

  • DataFrame

    The structure lookup DataFrame. Cached on first access.

norm property

BoundaryNorm derived from annotation.attrs["rgb_lookup"].

Returns:

reference property

reference: DataArray

Reference template VoxelData array.

Returns:

  • DataArray

    The reference template VoxelData array.

structures property

structures: StructuresDict

BrainGlobe structure dictionary held in Dataset.attrs["structures"].

Returns:

  • StructuresDict

    The structure dictionary with its hierarchy tree.

Raises:

  • KeyError

    If Dataset.attrs has no structures entry (e.g. after an xarray op that dropped attrs; wrap the pipeline in xarray.set_options(keep_attrs=True)).

ancestors

ancestors(region: int | str) -> list[Node]

Return the ancestor nodes of region, from root down (exclusive).

Parameters:

  • region
    (int or str) –

    Structure index or acronym.

Returns:

  • list[Node]

    Ancestor nodes ordered from root toward region, not including region itself.

get_masks

get_masks(
    regions: int | str | Sequence[int | str],
    sides: Literal["left", "right", "both"]
    | Sequence[Literal["left", "right", "both"]] = "both",
) -> DataArray

Return integer region masks stacked along a mask dimension.

Each layer along mask has values in {0, region_id}; voxels belonging to the requested region (including all descendants in the hierarchy) carry the region's index, all others are zero.

Parameters:

  • regions
    (int or str or sequence of int or str) –

    One or more regions, each given as a structure index or acronym.

  • sides
    ((left, right, both), default: "left" ) –

    Hemisphere filter. Pass a scalar to apply the same side to all regions, or a sequence of the same length as regions for per-region control.

Returns:

  • DataArray

    Integer VoxelData array with dims ["mask", *annotation.dims]. The mask coordinate holds the region acronym for each layer, suffixed with _L/_R when the corresponding side is "left"/"right" (left/right requests for the same region would otherwise share an acronym).

Raises:

  • TypeError

    If ds is not a well-formed atlas Dataset.

  • KeyError

    If any requested region acronym or index is not found in the atlas.

  • ValueError

    If sides is a sequence whose length does not match regions, or if any element of sides is not "left", "right", or "both".

Examples:

>>> ds.atlas.get_masks("VISp")
>>> ds.atlas.get_masks("VISp", sides="left")
>>> ds.atlas.get_masks(["VISp", "AUDp", "MOp"])
>>> ds.atlas.get_masks(["VISp", "AUDp"], sides=["left", "both"])
>>> ds.atlas.get_masks(["VISp", "VISp"], sides=["left", "right"]).coords["mask"].values
array(['VISp_L', 'VISp_R'], dtype=object)

get_mesh

get_mesh(
    region: int | str,
    side: Literal["left", "right", "both"] = "both",
    *,
    clip: bool = True,
) -> tuple[NDArray[float64], NDArray[int32]]

Return vertex coordinates and face indices for a region's mesh.

Reads the region's mesh, transforms its vertices from micron space to the DataArrays' current world space (millimetres), then optionally drops out-of-grid vertices and clips to one hemisphere. The mesh comes from the structure's mesh_filename: for a freshly fetched atlas this points into the BrainGlobe cache; for an atlas loaded with load_atlas it points at the mesh bundled inside the store.

Parameters:

  • region
    (int or str) –

    Structure index or acronym.

  • side
    ((left, right, both), default: "left" ) –

    Hemisphere to include. "both" keeps the full mesh. "left" and "right" keep only vertices whose nearest hemispheres voxel carries that side's label (hemispheres.attrs["left"] / ["right"]), sampled in the current world space. Faces are kept only when all three of their vertices survive, so the cut face is not closed. Sampling the hemisphere map makes this orientation-agnostic and correct after an arbitrary resample.

  • clip
    (bool, default: True ) –

    Whether to clip the final mesh to the current reference grid. If False, the mesh will still be transformed to the current world space, but the bounding box will not be respected.

Returns:

  • vertices ( (ndarray, shape(N, 3)) ) –

    Vertex coordinates in the current world space (millimetres). After a nonlinear resample, vertices warped outside the reference grid are dropped.

  • faces ( (ndarray, shape(M, 3)) ) –

    Zero-indexed triangle face indices (int32).

Raises:

  • TypeError

    If ds is not a well-formed atlas Dataset.

  • KeyError

    If the requested region is not found in the atlas.

  • ValueError

    If the region has no mesh file, or the mesh file cannot be located.

resample

Resample the atlas onto an explicit output grid.

The atlas reference volume is resampled with interpolation; annotation and hemispheres are always resampled with nearest-neighbor interpolation to preserve integer labels. The returned Dataset stores the composed pull transform from its new world space back to the atlas base space in attrs["world_to_base"].

Parameters:

  • transform
    ((4, 4) numpy.ndarray or xarray.DataArray) –

    Pull transform mapping output world coordinates to current atlas world coordinates.

  • output_sizes
    (mapping of str to int) –

    Number of voxels along output axes, read by k/j/i keys.

  • output_spacing
    (mapping of str to float) –

    World distance between output positions, read by k/j/i keys.

  • output_origin
    (mapping of str to float) –

    World location of output position (0, 0, 0), read by z/y/x keys.

  • output_direction
    ((3, 3) numpy.ndarray) –

    Unit world-space direction columns for native k/j/i output axes.

  • interpolation
    ((linear, nearest, bspline), default: "linear" ) –

    Interpolation used for the atlas reference volume.

  • sitk_threads
    (int, default: -1 ) –

    Number of SimpleITK threads.

Returns:

  • Dataset

    Resampled atlas Dataset on the requested grid. Meshes returned by get_mesh are transformed through the composed world_to_base attribute.

resample_like

resample_like(
    reference: DataArray,
    transform: WorldToBaseTransform,
    *,
    interpolation: Literal[
        "linear", "nearest", "bspline"
    ] = "linear",
    sitk_threads: int = -1,
) -> Dataset

Resample the atlas onto reference's VoxelData grid.

Parameters:

  • reference
    (DataArray) –

    VoxelData array defining the target grid. Only its k/j/i grid (sizes/spacing/origin/direction) is used, so a time dimension, if present, is ignored. Must not have a pose or extra non-spatial dimension.

  • transform
    ((4, 4) numpy.ndarray or xarray.DataArray) –

    Pull transform mapping reference world coordinates to atlas world coordinates.

  • interpolation
    ((linear, nearest, bspline), default: "linear" ) –

    Interpolation used for the atlas reference volume.

  • sitk_threads
    (int, default: -1 ) –

    Number of SimpleITK threads.

Returns:

  • Dataset

    Resampled atlas Dataset with exactly reference's voxel labels and voxel-to-world affine. Meshes returned by get_mesh are transformed through the composed world_to_base attribute.

Raises:

  • ValueError

    If reference has a pose or extra non-spatial dimension, or is not a VoxelData array.

search

search(
    pattern: str,
    field: Literal["all", "acronym", "name"] = "all",
) -> DataFrame

Search structures by name or acronym.

Parameters:

  • pattern
    (str) –

    Substring or regex pattern.

  • field
    ((all, acronym, name), default: "all" ) –

    Which column to search.

    • "all": case-insensitive regex search on both acronym and name.
    • "acronym" / "name": case-insensitive full regex match on that column only.

Returns:

Examples:

>>> ds.atlas.search("visual cortex")
>>> ds.atlas.search("VISp", field="acronym")

show_tree

show_tree(**kwargs: object) -> None

Print the structure hierarchy tree.

Parameters:

  • **kwargs
    (object, default: {} ) –

    Additional keyword arguments forwarded to [treelib.Tree.show][].

Returns:

  • None

    The tree is printed to standard output.

get_atlas_masks

get_atlas_masks(
    ds: Dataset,
    regions: int | str | Sequence[int | str],
    sides: Literal["left", "right", "both"]
    | Sequence[Literal["left", "right", "both"]] = "both",
) -> DataArray

Return integer region masks stacked along a mask dimension.

Each layer along mask has values in {0, region_id}; voxels belonging to the requested region (including all descendants in the hierarchy) carry the region's index, all others are zero.

Parameters:

  • ds

    (Dataset) –

    Atlas Dataset; validated as an atlas before use.

  • regions

    (int or str or sequence of int or str) –

    One or more regions, each given as a structure index or acronym.

  • sides

    ((left, right, both), default: "left" ) –

    Hemisphere filter. Pass a scalar to apply the same side to all regions, or a sequence of the same length as regions for per-region control.

Returns:

  • DataArray

    Integer VoxelData array with dims ["mask", *annotation.dims]. The mask coordinate holds the region acronym for each layer, suffixed with _L/_R when the corresponding side is "left"/"right" (left/right requests for the same region would otherwise share an acronym).

Raises:

  • TypeError

    If ds is not a well-formed atlas Dataset.

  • KeyError

    If any requested region acronym or index is not found in the atlas.

  • ValueError

    If ds is not a well-formed atlas, if sides is a sequence whose length does not match regions, or if any element of sides is not "left", "right", or "both".

Examples:

>>> import confusius as cf
>>> cf.atlas.get_atlas_masks(ds, "VISp")
>>> cf.atlas.get_atlas_masks(ds, ["VISp", "AUDp"], sides=["left", "both"])

get_atlas_mesh

get_atlas_mesh(
    ds: Dataset,
    region: int | str,
    side: Literal["left", "right", "both"] = "both",
    *,
    clip: bool = True,
) -> tuple[NDArray[float64], NDArray[int32]]

Return vertex coordinates and face indices for a region's mesh.

Reads the region's mesh, transforms its vertices from micron space to the atlas's world space (millimetres), then optionally drops out-of-grid vertices and clips to one hemisphere. The mesh comes from the structure's mesh_filename: for a freshly fetched atlas this points into the BrainGlobe cache; for an atlas loaded with load_atlas it points at the mesh bundled inside the store.

Parameters:

  • ds

    (Dataset) –

    Atlas Dataset; validated as an atlas before use.

  • region

    (int or str) –

    Structure index or acronym.

  • side

    ((left, right, both), default: "left" ) –

    Hemisphere to include. "both" keeps the full mesh. "left" and "right" keep only vertices whose nearest hemispheres voxel carries that side's label (hemispheres.attrs["left"] / ["right"]), sampled in the atlas's world space. Faces are kept only when all three of their vertices survive, so the cut face is not closed. Sampling the hemisphere map makes this orientation-agnostic and correct after an arbitrary resample.

  • clip

    (bool, default: True ) –

    Whether to clip the final mesh to the reference grid. If False, the mesh is still transformed to the atlas's world space, but the bounding box is not respected.

Returns:

  • vertices ( (ndarray, shape(N, 3)) ) –

    Vertex coordinates in the atlas's world space (millimetres). After a nonlinear resample, vertices warped outside the reference grid are dropped.

  • faces ( (ndarray, shape(M, 3)) ) –

    Zero-indexed triangle face indices (int32).

Raises:

  • TypeError

    If ds is not a well-formed atlas Dataset.

  • KeyError

    If the requested region is not found in the atlas.

  • ValueError

    If ds is not a well-formed atlas, or if the region has no mesh file.

  • RuntimeError

    If the region's mesh cannot be downloaded or read.

Examples:

>>> import confusius as cf
>>> vertices, faces = cf.atlas.get_atlas_mesh(ds, "root")

search_atlas

search_atlas(
    ds: Dataset,
    pattern: str,
    field: Literal["all", "acronym", "name"] = "all",
) -> DataFrame

Search an atlas Dataset's structures by name or acronym.

Parameters:

  • ds

    (Dataset) –

    Atlas Dataset to search; validated as an atlas before use.

  • pattern

    (str) –

    Substring or regex pattern.

  • field

    ((all, acronym, name), default: "all" ) –

    Which column to search.

    • "all": case-insensitive regex search on both acronym and name.
    • "acronym" / "name": case-insensitive full regex match on that column only.

Returns:

  • DataFrame

    Filtered view of the atlas structure lookup table matching the search criteria.

Raises:

  • TypeError

    If ds is not a well-formed atlas Dataset.

  • ValueError

    If ds is not a well-formed atlas Dataset.

Examples:

>>> import confusius as cf
>>> cf.atlas.search_atlas(ds, "visual cortex")
>>> cf.atlas.search_atlas(ds, "VISp", field="acronym")