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 on a common (z, y, x) 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 the grid of reference.

  • search

    Search structures by name or acronym.

  • show_tree

    Print the structure hierarchy tree.

Attributes:

annotation property

annotation: DataArray

Region annotations DataArray.

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

Returns:

  • DataArray

    The region annotation DataArray with integer labels.

cmap property

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

Returns:

hemispheres property

hemispheres: DataArray

Hemisphere map DataArray (1 = left, 2 = right).

Returns:

  • DataArray

    The hemisphere map data variable.

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 DataArray.

Returns:

  • DataArray

    The reference template DataArray.

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

  • 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 OBJ mesh, transforms its vertices from micron space to the DataArrays' current physical 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 physical 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 physical space, but the bounding box will not be respected.

Returns:

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

    Vertex coordinates in the current physical 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:

  • 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(
    transform: PhysicalToBaseTransform,
    *,
    shape: Sequence[int],
    spacing: Sequence[float],
    origin: Sequence[float],
    dims: Sequence[str],
    reference_interpolation: Literal[
        "linear", "nearest", "bspline"
    ] = "linear",
    sitk_threads: int = -1,
) -> Dataset

Resample the atlas onto an explicit output grid.

Mirrors confusius.registration.resample_volume for atlas Datasets by constructing a temporary reference grid and delegating to resample_like.

Parameters:

  • transform
    ((N+1, N+1) numpy.ndarray or xarray.DataArray) –

    Pull transform mapping output physical coordinates to the current atlas physical coordinates. Affine, B-spline, or displacement-field, as for resample_like.

  • shape
    (sequence of int) –

    Number of voxels along each output axis, in dims order.

  • spacing
    (sequence of float) –

    Voxel spacing along each output axis, in dims order.

  • origin
    (sequence of float) –

    Physical origin along each output axis, in dims order.

  • dims
    (sequence of str) –

    Dimension names of the output atlas grid.

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

    Interpolation used for the reference volume.

  • sitk_threads
    (int, default: -1 ) –

    Number of SimpleITK threads.

Returns:

  • Dataset

    Resampled atlas Dataset on the requested grid.

resample_like

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

Resample the atlas onto the grid of reference.

Mirrors confusius.registration.resample_like. Returns a new atlas Dataset whose variables live on reference's grid.

  • reference: resampled with reference_interpolation.
  • annotation and hemispheres: resampled with nearest-neighbour to preserve integer labels.
  • Meshes returned by get_mesh will also be in the new physical space.

reference and any DataArray transform must use the same physical coordinate units when such metadata is defined.

Parameters:

  • reference
    (DataArray) –

    Target grid. Must be 2D or 3D and must not have a time dimension.

  • transform
    ((N+1, N+1) numpy.ndarray or xarray.DataArray) –

    Pull/inverse transform returned by register_volume, mapping reference physical coordinates to atlas physical coordinates.

    • Affine (numpy.ndarray): homogeneous matrix.
    • B-spline (xarray.DataArray): control-point DataArray.
    • Displacement field (xarray.DataArray): dense field with attrs["type"] == "displacement_field_transform".
  • reference_interpolation
    ((linear, nearest, bspline), default: "linear" ) –

    Interpolation used for the reference variable.

  • sitk_threads
    (int, default: -1 ) –

    Number of SimpleITK threads. Negative values use max(1, cpu_count + 1 + sitk_threads).

Returns:

  • Dataset

    New atlas Dataset on reference's grid. The composed physical→base pull transform is stored in the attrs["physical_to_base"] attribute — a numpy affine, or a displacement-field DataArray when transform (or a previously composed one) is nonlinear.

Examples:

>>> _, affine = atlas.atlas.reference.fusi.register.to_volume(
...     fusi_mean, metric="mattes_mi", transform="affine"
... )
>>> atlas_fusi = atlas.atlas.resample_like(fusi_mean, affine)

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

  • 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 OBJ mesh, transforms its vertices from micron space to the atlas's physical 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 physical 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 physical space, but the bounding box is not respected.

Returns:

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

    Vertex coordinates in the atlas's physical 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:

  • KeyError

    If the requested region is not found in the atlas.

  • ValueError

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

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")