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 on a common(z, y, x)grid, 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 the grid of
reference. -
search–Search structures by name or acronym.
-
show_tree–Print the structure hierarchy tree.
Attributes:
-
annotation(DataArray) –Region annotations DataArray.
-
cmap(ListedColormap) –ListedColormapderived fromannotation.attrs["rgb_lookup"]. -
hemispheres(DataArray) –Hemisphere map DataArray (1 = left, 2 = right).
-
lookup(DataFrame) –DataFrame with columns
acronym,name,rgb_triplet. -
norm(BoundaryNorm) –BoundaryNormderived fromannotation.attrs["rgb_lookup"]. -
reference(DataArray) –Reference template DataArray.
-
structures(StructuresDict) –BrainGlobe structure dictionary held in
Dataset.attrs["structures"].
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
¶
cmap: ListedColormap
ListedColormap derived from annotation.attrs["rgb_lookup"].
Returns:
-
ListedColormap–The colormap to use for atlas rendering.
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
¶
norm: BoundaryNorm
BoundaryNorm derived from annotation.attrs["rgb_lookup"].
Returns:
-
BoundaryNorm–The norm to use for atlas rendering.
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.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 DataArray 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:
-
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 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 nearesthemispheresvoxel 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
dimsorder. -
(spacing¶sequence of float) –Voxel spacing along each output axis, in
dimsorder. -
(origin¶sequence of float) –Physical origin along each output axis, in
dimsorder. -
(dims¶sequence of str) –Dimension names of the output atlas grid.
-
(reference_interpolation¶(linear, nearest, bspline), default:"linear") –Interpolation used for the
referencevolume. -
(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 withreference_interpolation.annotationandhemispheres: resampled with nearest-neighbour to preserve integer labels.- Meshes returned by
get_meshwill 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
timedimension. -
(transform¶(N+1, N+1) numpy.ndarray or xarray.DataArray) –Pull/inverse transform returned by
register_volume, mappingreferencephysical coordinates to atlas physical coordinates.- Affine (
numpy.ndarray): homogeneous matrix. - B-spline (
xarray.DataArray): control-point DataArray. - Displacement field (
xarray.DataArray): dense field withattrs["type"] == "displacement_field_transform".
- Affine (
-
(reference_interpolation¶(linear, nearest, bspline), default:"linear") –Interpolation used for the
referencevariable. -
(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 theattrs["physical_to_base"]attribute — a numpy affine, or a displacement-field DataArray whentransform(or a previously composed one) is nonlinear.
Examples:
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 DataArray 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:
-
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 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 nearesthemispheresvoxel 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
dsis not a well-formed atlas, if the region has no mesh file, or if the mesh file cannot be located.
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: