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
maskdimension. -
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, andhemispheresdata variables as VoxelData arrays on a commonk/j/igrid, and the atlas metadata inattrs.
Methods:
-
ancestors–Return the ancestor nodes of
region, from root down (exclusive). -
get_masks–Return integer region masks stacked along a
maskdimension. -
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(DataArray) –Region annotations VoxelData array.
-
cmap(ListedColormap) –ListedColormapderived fromannotation.attrs["rgb_lookup"]. -
hemispheres(DataArray) –Hemisphere map VoxelData array (1 = left, 2 = right).
-
lookup(DataFrame) –DataFrame with columns
acronym,name,rgb_triplet. -
norm(BoundaryNorm) –BoundaryNormderived fromannotation.attrs["rgb_lookup"]. -
reference(DataArray) –Reference template VoxelData array.
-
structures(StructuresDict) –BrainGlobe structure dictionary held in
Dataset.attrs["structures"].
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
¶
cmap: ListedColormap
ListedColormap derived from annotation.attrs["rgb_lookup"].
Returns:
-
ListedColormap–The colormap to use for atlas rendering.
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
¶
norm: BoundaryNorm
BoundaryNorm derived from annotation.attrs["rgb_lookup"].
Returns:
-
BoundaryNorm–The norm to use for atlas rendering.
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.attrshas nostructuresentry (e.g. after an xarray op that droppedattrs; wrap the pipeline inxarray.set_options(keep_attrs=True)).
ancestors ¶
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
regionsfor per-region control.
Returns:
-
DataArray–Integer VoxelData array with dims
["mask", *annotation.dims]. Themaskcoordinate holds the region acronym for each layer, suffixed with_L/_Rwhen the correspondingsideis"left"/"right"(left/right requests for the same region would otherwise share an acronym).
Raises:
-
TypeError–If
dsis not a well-formed atlas Dataset. -
KeyError–If any requested region acronym or index is not found in the atlas.
-
ValueError–If
sidesis a sequence whose length does not matchregions, or if any element ofsidesis 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 nearesthemispheresvoxel 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
dsis 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(
transform: WorldToBaseTransform,
*,
output_sizes: Mapping[Hashable, SupportsIndex],
output_spacing: Mapping[
Hashable, SupportsFloat | SupportsIndex
],
output_origin: Mapping[
Hashable, SupportsFloat | SupportsIndex
],
output_direction: ArrayLike,
interpolation: Literal[
"linear", "nearest", "bspline"
] = "linear",
sitk_threads: int = -1,
) -> Dataset
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/ikeys. -
(output_spacing¶mapping of str to float) –World distance between output positions, read by
k/j/ikeys. -
(output_origin¶mapping of str to float) –World location of output position
(0, 0, 0), read byz/y/xkeys. -
(output_direction¶(3, 3) numpy.ndarray) –Unit world-space direction columns for native
k/j/ioutput 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_meshare transformed through the composedworld_to_baseattribute.
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/igrid (sizes/spacing/origin/direction) is used, so atimedimension, if present, is ignored. Must not have aposeor 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 byget_meshare transformed through the composedworld_to_baseattribute.
Raises:
-
ValueError–If
referencehas aposeor extra non-spatial dimension, or is not a VoxelData array.
search ¶
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 bothacronymandname."acronym"/"name": case-insensitive full regex match on that column only.
Returns:
Examples:
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
regionsfor per-region control.
Returns:
-
DataArray–Integer VoxelData array with dims
["mask", *annotation.dims]. Themaskcoordinate holds the region acronym for each layer, suffixed with_L/_Rwhen the correspondingsideis"left"/"right"(left/right requests for the same region would otherwise share an acronym).
Raises:
-
TypeError–If
dsis not a well-formed atlas Dataset. -
KeyError–If any requested region acronym or index is not found in the atlas.
-
ValueError–If
dsis not a well-formed atlas, ifsidesis a sequence whose length does not matchregions, or if any element ofsidesis not"left","right", or"both".
Examples:
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 nearesthemispheresvoxel 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
dsis not a well-formed atlas Dataset. -
KeyError–If the requested region is not found in the atlas.
-
ValueError–If
dsis 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:
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 bothacronymandname."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
dsis not a well-formed atlas Dataset. -
ValueError–If
dsis not a well-formed atlas Dataset.
Examples: