siibra.volumes

Package handling variety of volumes and volume operations

Submodules

Attributes

Classes

Map

Parent class encapsulating commonalities of the basic siibra concept like atlas, parcellation, space, region.

Volume

A volume is a specific mesh or 3D array,

Functions

from_array(data, affine, space[, name, time, cache]) → Union[Volume, TimeSeriesVolume]

Build a siibra volume from an array and affine matrix.

from_file(files, space[, name, format, time])

Build a volume from local files.

from_nifti(nifti, space, name[, time]) → Union[Volume, TimeSeriesVolume]

Build a siibra volume from a NIfTI image.

from_pointcloud(points[, label, target, normalize, ...]) → Volume

Build a kernel-density volume from a point cloud.

from_url(urls, space[, name, format, time])

Build a volume from files served from online (https) sources.

Package Contents

class siibra.volumes.Map(identifier: str, name: str, space_spec: dict, parcellation_spec: dict, indices: Dict[str, List[Dict]], volumes: list = [], shortname: str = '', description: str = '', modality: str = None, publications: list = [], datasets: list = [], prerelease: bool = False)
Inheritance diagram of siibra.volumes.Map

Parent class encapsulating commonalities of the basic siibra concept like atlas, parcellation, space, region. These concepts have an id, name, and key, and they are bootstrapped from metadata stored in an online resources. Typically, they are linked with one or more datasets that can be retrieved from the same or another online resource, providing data files or additional metadata descriptions on request.

__iter__()
__len__()
as_nilearn_masker(strategy: Literal['mean', 'median', 'sum', 'minimum', 'maximum', 'standard_deviation', 'variance'] = 'mean', surface_variant: str = None, **masker_kwargs) → nilearn.maskers.NiftiLabelsMasker | nilearn.maskers.SurfaceLabelsMasker
assign(item: siibra.locations.location.Location, minsize_voxel: int = 1, lower_threshold: float = 0.0, *, split_components: bool = True, **kwargs) → pandas.DataFrame

Assign an input Location to brain regions.

The input is assumed to be defined in the same coordinate space as this parcellation map.

Parameters:
  • item (Location) – A spatial object defined in the same physical reference space as this parcellation map, which could be a point, set of points, or image volume. If it is an image, it will be resampled to the same voxel space if its affine transformation differs from that of the parcellation map. Resampling will use linear interpolation for float image types, otherwise nearest neighbor.

  • minsize_voxel (int, default: 1) – Input image components with at most this many voxels are skipped. The default skips single-voxel components; 0 keeps all components.

  • lower_threshold (float, default: 0) – Lower threshold on the values of statistical maps. Only map values above the threshold are taken into account: point inputs are assigned to maps whose value at the point exceeds it, and for image inputs, map values at or below it are set to zero before the comparison. Must be 0 for labelled maps.

  • split_components (bool, default: True) – For image inputs: whether to split the input into connected components and assign each separately.

  • **kwargs – Deprecated. Other keyword arguments are ignored with a FutureWarning; from siibra 1.0.1-alpha.28 on, they raise TypeError.

Returns:

One row per input element (coordinate or image component) and brain region it is assigned to. Columns that are empty in all rows are dropped.

  • input structure: index of the input coordinate, or label of the input image component, numbered from 1. An input that is not split into components has label 1.

  • time: time point of a time series input.

  • centroid: centroid of the input coordinate or image component, in physical coordinates of the map’s space.

  • volume, fragment: map index of the region.

  • region: the assigned brain region.

  • map value: for point inputs, the map value at the coordinate. For image inputs, the label of the region (labelled maps) or the maximum value of the regional map within its overlap with the input (statistical maps). Uncertain coordinates, assigned as Gaussian kernel images, get the value for image inputs.

  • correlation: Pearson correlation coefficient between the regional map and the input, over the bounding box of both (the regional map taken before thresholding). NaN if either is constant there. Statistical maps only: the regional maps of labelled maps are binary masks.

  • intersection over union: of the nonzero voxels of the regional map and the input.

  • map containedness: fraction of the nonzero voxels of the regional map that lie within the input.

  • input containedness: fraction of the nonzero voxels of the input that lie within the regional map.

  • map weighted mean: mean of the regional map values, weighted by the input values.

  • input weighted mean: mean of the input values, weighted by the regional map values.

Rows are ordered by input coordinate or image component, then by map. The scores from “correlation” onwards are computed for image inputs only. Coordinates with an uncertainty of 3 voxels or more are assigned as images of a Gaussian kernel and receive them too.

Return type:

pandas.DataFrame

colorize(values: dict | pandas.Series | pandas.DataFrame, background_label: int | float = 0, **masker_kwargs)

Colorize the map with the provided regional values.

Parameters:

values (dict) – Dictionary mapping regions to values

Return type:

Nifti1Image

compress(**kwargs) → Map

Convert this map into an equivalent map whose labels are unique across the whole image or surface, re-labelling regions sequentially from 1.

Volumetric maps are merged into a single labelled volume on the grid of the space template. Surface maps keep their fragments, since a vertex belongs to exactly one of them, and are relabelled so that a label identifies one region rather than one region per hemisphere.

The compressed image is built and kept as a memory-mapped array on disk, so neither building nor using it holds the full volume in RAM. Results are also cached per instance, keyed by the fetch arguments.

Note

Labels that no region claims are dropped to background. Surface maps sometimes carry such labels for technical reasons (e.g. a brainstem label so the map loads in freesurfer) and they have no name to report.

Parameters:

**kwargs – Fetch arguments applied both to the space template, which defines the output grid, and to the mapped volumes, so that sources are read at the same resolution and resampling is usually unnecessary. variant is passed to the template only.

Return type:

parcellationmap.Map

Raises:
compute_centroids(split_components: bool = True, **fetch_kwargs) → Dict[str, siibra.locations.pointcloud.PointCloud]

Compute a dictionary of all regions in this map to their centroids. By default, the regional masks will be split to connected components and each point in the PointCloud corresponds to a region component.

Parameters:

split_components (bool, default: True) – If True, finds the spatial properties for each connected component found by skimage.measure.label.

Returns:

Region names as keys and computed centroids as items.

Return type:

Dict[str, point.Point]

extract_signals_with_nilearn(volume: siibra.volumes.volume.Volume, strategy: Literal['mean', 'median', 'sum', 'minimum', 'maximum', 'standard_deviation', 'variance'] = 'mean', confounds: numpy.ndarray = None, sample_mask: numpy.ndarray = None, surface_variant: str = None, **masker_kwargs) → pandas.DataFrame

Extract region-wise signals from a 3D/4D volume using nilearn.

The regions defined in this map are used to summarize the input volume with nilearn.maskers.NiftiLabelsMasker (labelled volumetric maps), nilearn.maskers.SurfaceLabelsMasker (labelled surface maps), or nilearn.maskers.NiftiMapsMasker (statistical maps). Maps with several volumes or fragments are compressed into a single labelled map first.

Parameters:
  • volume (Volume) – Input 3D or 4D volume from which signals should be extracted, typically an fMRI image. Both NIfTI and timeseries GIFTI sources are supported.

  • strategy (str, default: "mean") – How voxels or vertices are summarized within each region. Only applies to labelled maps; it is ignored for statistical maps, since NiftiMapsMasker projects the data onto the (overlapping, continuous) maps by least squares instead of summarizing discrete regions.

  • confounds (array-like, optional) – Confounds to regress out during extraction. See nilearn.maskers.BaseMasker.transform.

  • sample_mask (array-like, optional) – Mask of samples to include when extracting signals. See nilearn.maskers.BaseMasker.transform.

  • surface_variant (str, optional) – Template surface variant to use for surface maps, e.g. “inflated”.

  • **masker_kwargs – Passed on to the nilearn masker constructor.

Returns:

One column per region mapped in this map, one row per sample. The index is the time axis of volume when it has one and no sample_mask was given, otherwise a range index.

Return type:

pandas.DataFrame

Notes

Region names are taken from the BIDS lookup table generated by to_BIDS_lookup_table(). Regions that disappear when the map is resampled onto the input volume are reported and filled with zeros; nilearn’s keep_masked_labels does not prevent them from being dropped, and it is deprecated since nilearn 0.14.

fetch(region: str | siibra.core.region.Region = None, *, index: siibra.commons.MapIndex = None, **fetch_kwargs)

Fetches one particular volume of this parcellation map.

If there’s only one volume, this is the default, otherwise further specification is requested: - the volume index, - the MapIndex (which results in a regional map being returned)

You might also consider fetch_iter() to iterate the volumes, or compress() to produce a single-volume parcellation map.

Parameters:
  • region (str, Region) – Specification of a region name, resulting in a regional map (mask or statistical map) to be returned.

  • index (MapIndex) – Explicit specification of the map index, typically resulting in a regional map (mask or statistical map) to be returned. Note that supplying ‘region’ will result in retrieving the map index of that region automatically.

  • **fetch_kwargs –

    • resolution_mm: resolution in millimeters as float or a tuple of floats

    • format: the format of the volume, like “mesh” or “nii”

    • voi: a BoundingBox of interest

    Not all keyword arguments are supported for volume formats. Format is restricted by available formats (check formats property).

Return type:

An image or mesh

fetch_iter(**kwargs)

Returns an iterator to fetch all mapped volumes sequentially.

All arguments are passed on to function Map.fetch(). By default, it will go through all fragments as well.

find_indices(region: str | siibra.core.region.Region)

Returns the volume/label indices in this map which match the given region specification.

Parameters:

region (str or Region)

Returns:

  • keys: MapIndex

  • values: region name

Return type:

dict

get_colormap(region_specs: Iterable = None, *, fill_uncolored: bool = False)

Generate a matplotlib colormap from known rgb values of label indices.

Parameters:
  • region_specs (iterable(regions), optional) – Optional parameter to only color the desired regions.

  • fill_uncolored (bool , optional) – If a region has no preconfigured color, a color will be randomly (reproducible) created.

Return type:

ListedColormap

get_index(region: str | siibra.core.region.Region)

Returns the unique index corresponding to the specified region.

Tip

Use find_indices() method for a less strict search returning all matches.

Parameters:

region (str or Region)

Return type:

MapIndex

Raises:

NonUniqueIndexError – If not unique or not defined in this parcellation map.

get_region(label: int = None, volume: int = 0, index: siibra.commons.MapIndex = None)

Returns the region mapped by the given index, if any.

Tip

Use get_index() or find_indices() methods to obtain the MapIndex.

Parameters:
  • label (int, default: None)

  • volume (int, default: 0)

  • index (MapIndex, default: None)

Returns:

A region object defined in the parcellation map.

Return type:

Region

get_resampled_template(**fetch_kwargs) → siibra.volumes.volume.Volume

Resample the reference space template to fetched map image. Uses nilearn.image.resample_to_img to resample the template.

Parameters:

**fetch_kwargs (takes the arguments of Map.fetch())

Return type:

Volume

get_volume(region: str | siibra.core.region.Region = None, *, index: siibra.commons.MapIndex = None, **kwargs) → siibra.volumes.volume.Volume | siibra.volumes.volume.FilteredVolume | siibra.volumes.volume.Subvolume
sample_locations(regionspec, numpoints: int)

Sample 3D locations inside a given region.

The probability distribution is approximated from the region mask based on the squared distance transform.

Parameters:
  • regionspec (Region or str) – Region to be used

  • numpoints (int) – Number of samples to draw

Returns:

Sample points in physical coordinates corresponding to this parcellationmap

Return type:

PointCloud

to_BIDS_lookup_table() → pandas.DataFrame

Generate a BIDS-compatible lookup table for the labelled map.

The lookup table associates voxel labels with region names and optional RGB colors derived from the corresponding parcellation regions.

If the map consists of multiple fragments, the fragments are first compressed into a single labelled image and relabelled to ensure BIDS compatibility.

Parameters:

filepath (str, optional) – Path to a .tsv file where the lookup table should be written. If provided, the table is saved in tab-separated format.

Returns:

A lookup table with the following columns: - index: Integer label value in the image. - name: Name of the corresponding brain region. - color: Hexadecimal RGB color code associated with the region,

or None if no color is defined.

Return type:

pandas.DataFrame

Raises:

Notes

BIDS lookup tables require a single labelled volume. Maps distributed across multiple fragments are therefore compressed and relabelled before generating the table.

to_sparse()

Creates a SparseMap object from this parcellation map object.

Return type:

SparseMap

property affine
property formats
property fragments
property has_unique_labels: bool

True if every mapped region carries a distinct label across all volumes and fragments. Surface and fragmented volumetric maps are commonly labelled per hemisphere, so the same label may denote two different regions.

property is_labelled
property key
property labels

The set of all label indices defined in this map, including “None” if not defined for one or more regions.

property maptype: siibra.commons.MapType
property parcellation
property provides_image
property provides_mesh
property regions
property space
property species: siibra.commons.Species
volumes: List[siibra.volumes.volume.Volume] = []
class siibra.volumes.Volume(space_spec: dict, providers: List[siibra.volumes.providers.provider.VolumeProvider], name: str = '', variant: str = None, datasets: List[siibra.retrieval.datasets.EbrainsDataset] = [], bbox: siibra.locations.boundingbox.BoundingBox = None)
Inheritance diagram of siibra.volumes.Volume

A volume is a specific mesh or 3D array, which can be accessible via multiple providers in different formats.

__eq__(other: Volume)
__hash__()
__repr__()
__str__()
compute_spatial_props(split_components: bool = True, **fetch_kwargs) → List[ComponentSpatialProperties]

Find the center of this volume in its (non-zero) voxel space and and its volume.

Parameters:

split_components (bool, default: True) – If True, finds the spatial properties for each connected component found by skimage.measure.label.

draw_samples(N: int, sample_size: int = 100, e: float = 1, sigma_mm=None, invert=False, **kwargs)

Draw samples from the volume, by interpreting its values as an unnormalized empirical probability distributions. Any keyword arguments are passed over to fetch()

evaluate_points(points: siibra.locations.point.Point | siibra.locations.pointcloud.PointCloud, outside_value: int | float = 0, **fetch_kwargs) → numpy.ndarray

Evaluate the image at the positions of the given points.

Note

Uses nearest neighbor interpolation. Other interpolation schemes are not yet implemented.

Note

If points are not on the same space as the map, they will be warped to the space of the volume.

Parameters:
  • points (PointCloud)

  • outside_value (int, float. Default: 0)

  • fetch_kwargs (dict) – Any additional arguments are passed to the fetch() call for retrieving the image data.

Returns:

values – The values of the volume at the voxels points correspond to.

Return type:

numpy.ndarray

Raises:

SpaceWarpingFailedError – If warping of the points fails.

fetch(format: str = None, **kwargs)

Fetch a volumetric or surface representation from one of the providers.

Parameters:
  • format (str, default=None) –

    Requested format. If None, the first supported format matching in self.formats is tried, starting with volumetric formats. It can be explicitly specified as:

    • ’surface’ or ‘mesh’ to fetch a surface format

    • ’volumetric’ or ‘voxel’ to fetch a volumetric format

    • supported format types, see SUPPORTED_FORMATS. This includes

    ’nii’, ‘zip/nii’, ‘neuroglancer/precomputed’, ‘gii-mesh’, ‘neuroglancer/precompmesh’, ‘gii-label’

  • **kwargs –

    • resolution_mm: resolution in millimeters as float or a tuple of floats

    • format: the format of the volume, like “mesh” or “nii”

    • voi: a BoundingBox of interest

Returns:

An image (Nifti1Image) or mesh (Dict[‘verts’

Return type:

ndarray, ‘faces’: ndarray, ‘labels’: ndarray])

fetch_connected_components(**fetch_kwargs)

Provide an generator over masks of connected components in the volume

find_peaks(mindist=5, sigma_mm=0, **kwargs)

Find local peaks in the volume. Additional keyword arguments are passed over to fetch()

get_boundingbox(clip: bool = True, background: float = 0.0, **fetch_kwargs) → siibra.locations.boundingbox.BoundingBox

Obtain the bounding box in physical coordinates of this volume.

Parameters:
  • clip (bool, default: True) – Whether to clip the background of the volume.

  • background (float, default: 0.0) – The background value to clip. .. note:: To use it, clip must be True.

  • fetch_kwargs – key word arguments that are used for fetching volumes, such as voi or resolution_mm. Currently, only possible for Neuroglancer volumes except for format.

Raises:

RuntimeError – If the volume provider does not have a bounding box calculator.

intersection(other: siibra.core.structure.BrainStructure, **fetch_kwargs) → siibra.core.structure.BrainStructure

Compute the intersection of a location with this volume. This will fetch actual image data. Any additional arguments are passed to fetch.

IMAGE_FORMATS = ['nii', 'zip/nii', 'neuroglancer/precomputed', 'tif/2d']
MESH_FORMATS = ['neuroglancer/precompmesh', 'neuroglancer/precompmesh/surface', 'gii-mesh', 'gii-label',...
SUPPORTED_FORMATS = ['nii', 'zip/nii', 'neuroglancer/precomputed', 'tif/2d', 'neuroglancer/precompmesh',...
datasets = []
property formats: Set[str]
property fragments: Dict[str, List[str]]
property name

Allows derived classes to implement a lazy name specification.

property providers
property provides_image
property provides_mesh
property space
property species
variant = None
siibra.volumes.from_array(data: numpy.ndarray, affine: numpy.ndarray, space: str | Dict[str, str], name: str = None, time: numpy.ndarray = None, *, cache: bool = True) → Volume | TimeSeriesVolume

Build a siibra volume from an array and affine matrix.

The array is converted to a NIfTI image, written to the local siibra cache, and returned as a file-backed volume. The volume keeps the full-precision affine, although NIfTI files store it in single precision. If name is not provided, a stable name is generated from the array values, shape, dtype, and optional time axis.

Parameters:
  • data (numpy.ndarray) – Voxel data of the volume.

  • affine (numpy.ndarray) – 4x4 affine matrix mapping voxel coordinates to world coordinates.

  • space (str or dict[str, str]) – Reference space of the volume. If a mapping is provided, the first value is used as the space specification.

  • name (str, optional) – Name assigned to the resulting volume. If omitted, a deterministic name is generated from data and time.

  • time (numpy.ndarray, optional) – Time axis for 4D or time-resolved data. If given, a TimeSeriesVolume is returned.

  • cache (bool) – Cache it on disk

Returns:

File-backed siibra volume using a cached NIfTI image.

Return type:

Volume or TimeSeriesVolume

siibra.volumes.from_file(files: str | pathlib.Path | Dict[str, str | pathlib.Path], space: str, name: str = None, *, format: str = 'nii', time: numpy.ndarray = None)

Build a volume from local files.

Parameters:
  • files (str, pathlib.Path, or dict[str, str | pathlib.Path]) – Local image file, or a mapping from fragment names to local image files. A single file is internally treated as an unfragmented image.

  • space (str) – Reference space of the volume.

  • format (str, default: "nii") – Examples include "nii", "gii-timeseries", "gii-label", and "gii-mesh". See Volume.SUPPORTED_FORMATS.

  • time (numpy.ndarray, optional) – Time axis. If given, a TimeSeriesVolume is returned.

Returns:

TimeSeriesVolume if time values are provided, otherwise a Volume

Return type:

Volume

siibra.volumes.from_nifti(nifti: nibabel.Nifti1Image, space: str, name: str, time: numpy.ndarray = None) → Volume | TimeSeriesVolume

Build a siibra volume from a NIfTI image.

The image is written to the local siibra cache and returned as a file-backed volume. This avoids storing the image array directly in the provider and can reduce memory pressure for large or proxy-backed NIfTI images. The cache file is identified by the name, space, affine, and image data, so the image data is read once to compute its digest.

NIfTI files store the affine in single precision. The returned volume therefore uses the full-precision affine of nifti instead of the one read from the cached file.

Parameters:
  • nifti (nibabel.Nifti1Image) – NIfTI image to wrap as a siibra volume.

  • space (str) – Reference space of the volume.

  • name (str) – Name assigned to the resulting volume. Must be non-empty.

  • time (numpy.ndarray, optional) – Time axis for 4D or time-resolved data. If given, a TimeSeriesVolume is returned.

Returns:

File-backed siibra volume using a cached NIfTI image.

Return type:

Volume or TimeSeriesVolume

Raises:

ValueError – If name is empty.

siibra.volumes.from_pointcloud(points: siibra.locations.pointcloud.PointCloud, label: int = None, target: Volume = None, normalize: bool = True, *, clip_out_of_bounds: bool = False, **kwargs) → Volume

Build a kernel-density volume from a point cloud.

The point coordinates are transformed into the voxel space of a target volume. A voxel-count image is created, smoothed with a Gaussian kernel using the average point uncertainty as bandwidth, optionally normalized, and returned as a cached file-backed siibra volume.

Parameters:
  • points (pointcloud.PointCloud) – Point cloud used to generate the kernel-density estimate.

  • label (int, optional) – If provided, only points with this label are used. If omitted, all points are used.

  • target (Volume, optional) – Target volume defining the output grid and affine. If omitted, the template of points.space is used.

  • normalize (bool, default: True) – If True, divide the smoothed density image by its sum.

  • clip_out_of_bounds (bool, default: False) – If False, raise an error when transformed points fall outside the target volume. If True, discard out-of-bounds points.

  • **kwargs – Additional keyword arguments passed to target.fetch.

Returns:

File-backed siibra volume containing the point-cloud KDE.

Return type:

Volume

Raises:
  • ValueError – If label is provided but no points with that label are found.

  • ValueError – If transformed points are outside the target volume and clip_out_of_bounds is False.

siibra.volumes.from_url(urls: str | Dict[str, str], space: str, name: str = None, *, format: str = 'nii', time: numpy.ndarray = None)

Build a volume from files served from online (https) sources.

Parameters:
  • urls (str or dict[str, str]) – URL to the online image data, or a mapping from fragment names to URLs. A single URL is internally treated as an unfragmented image.

  • space (str) – Reference space of the volume.

  • format (str, default: "nii") – Examples include "nii", "gii-timeseries", "gii-label", and "gii-mesh". See Volume.SUPPORTED_FORMATS.

  • time (numpy.ndarray, optional) – Time axis. If given, a TimeSeriesVolume is returned.

Returns:

TimeSeriesVolume if time values are provided, otherwise a Volume

Return type:

Volume

siibra.volumes.logger