siibra.commons

Constants, functions, and classes used commonly across siibra.

Module Contents

Classes

CompareMapsResult

InstanceTable

Lookup table for instances of a given class by name/id.

LoggingContext

MapIndex

Identifies a unique region in a ParcellationMap, combining its labelindex (the "color") and mapindex (the number of the 3Dd map, in case multiple are provided).

MapType

Generic enumeration.

PolyLine

Simple polyline representation which allows equidistant sampling..

Species

Generic enumeration.

TypePublication

A simple typed namespace. At runtime it is equivalent to a plain dict.

Functions

MI(arr1, arr2[, nbins, normalized])

Compute the mutual information between two 3D arrays, which need to have the same shape.

affine_scaling(affine)

Estimate approximate isotropic scaling factor of an affine matrix.

argmax_dim4(img[, dim])

Given a nifti image object with four dimensions, returns a modified object

clear_name(name)

clean up a region name to the for matching

compare_arrays(arr1, affine1, arr2, affine2)

Compare two arrays in physical space as defined by the given affine matrices.

connected_components(→ Generator[Tuple[int, ...)

Provide an iterator over connected components in the array. If the image

create_gaussian_kernel([sigma, sigma_point])

Compute a 3D Gaussian kernel of the given bandwidth.

create_key(name)

Creates an uppercase identifier string that includes only alphanumeric

generate_uuid(string)

is_mesh(structure)

merge_meshes(meshes[, labels])

nonzero_coordinates(arr)

resample_array_to_array(→ numpy.ndarray)

Returns the source data resampled to match the target data

set_log_level(level)

siibra_tqdm([iterable])

snake2camel(s)

Converts a string in snake_case into CamelCase.

translation_matrix(tx, ty, tz)

Construct a 3D homoegneous translation matrix.

unify_stringlist(L)

Adds asterisks to strings that appear multiple times, so the resulting

y_rotation_matrix(alpha)

Construct a 3D y axis rotation matrix.

Attributes

HBP_AUTH_TOKEN

KEYCLOAK_CLIENT_ID

KEYCLOAK_CLIENT_SECRET

NZCACHE

QUIET

REMOVE_FROM_NAME

REPLACE_IN_NAME

ROOT_DIR

SIIBRA_CACHEDIR

SIIBRA_DEFAULT_MAPTYPE

SIIBRA_DEFAULT_MAP_THRESHOLD

SIIBRA_LOG_LEVEL

SIIBRA_MAX_FETCH_SIZE_GIB

SIIBRA_USE_CONFIGURATION

SIIBRA_USE_LOCAL_SNAPSPOT

SKIP_CACHEINIT_MAINTENANCE

T

VERBOSE

__version__

ch

formatter

logger

class siibra.commons.CompareMapsResult
correlation: float
intersection_over_first: float
intersection_over_second: float
intersection_over_union: float
weighted_mean_of_first: float
weighted_mean_of_second: float
class siibra.commons.InstanceTable(matchfunc=lambda a, b: ..., elements=None)
Inheritance diagram of siibra.commons.InstanceTable

Lookup table for instances of a given class by name/id. Provide attribute-access and iteration to a set of named elements, given by a dictionary with keys of ‘str’ type.

property dataframe
__contains__(key: str | T) bool

Test wether the given key or element is defined by the registry.

__dir__() Iterable[str]

List of all object keys in the registry

__getattr__(index) T

Access elements by using their keys as attributes. Keys are auto-generated from the provided names to be uppercase, with words delimited using underscores.

__getitem__(spec) T
__iter__() Iterator[T]

Iterate over all objects in the registry

__len__() int

Return the number of elements in the registry

__repr__()

Return repr(self).

__str__() str

Return str(self).

__sub__(obj) InstanceTable[T]

remove an object from the registry

add(key: str, value: T) None

Add a key/value pair to the registry.

Parameters:
  • (string) (key) –

  • (object) (value) –

find(spec) List[T]

Return a list of items matching the given specification, which could be either the name or a specification that works with the matchfunc of the Glossary.

get(spec) T

Give access to objects in the registry by sequential index, exact key, or keyword matching. If the keywords match multiple objects, the first in sorted order is returned. If the specification does not match, a RuntimeError is raised.

Parameters:

spec (int, str) – Index or string specification of an object

Return type:

Matched object

provides(spec) bool

Returns True if an element that matches the given specification can be found (using find(), thus going beyond the matching of names only as __contains__ does)

values()
class siibra.commons.LoggingContext(level)
__enter__()
__exit__(et, ev, tb)
class siibra.commons.MapIndex(volume: int = None, label: int = None, fragment: str = None)

Identifies a unique region in a ParcellationMap, combining its labelindex (the “color”) and mapindex (the number of the 3Dd map, in case multiple are provided).

__eq__(other)

Return self==value.

__hash__()

Return hash(self).

__repr__()

Return repr(self).

__str__()

Return str(self).

classmethod from_dict(spec: dict)
class siibra.commons.MapType
Inheritance diagram of siibra.commons.MapType

Generic enumeration.

Derive from this class to define new enumerations.

LABELLED = 1
STATISTICAL = 2
class siibra.commons.PolyLine(pts)

Simple polyline representation which allows equidistant sampling..

length()
sample(d)
class siibra.commons.Species
Inheritance diagram of siibra.commons.Species

Generic enumeration.

Derive from this class to define new enumerations.

CHLOROCEBUS_AETHIOPS_SABAEUS = 7
HOMO_SAPIENS = 1
MACACA_FASCICULARIS = 4
MACACA_FUSCATA = 6
MACACA_MULATTA = 5
MUS_MUSCULUS = 3
RATTUS_NORVEGICUS = 2
UNSPECIFIED_SPECIES = 999
__repr__()

Return repr(self).

__str__()

Return str(self).

classmethod decode(spec: str | Species | dict, fail_if_not_successful=True)
static key_to_name(key: str)
static name_to_key(name: str)
class siibra.commons.TypePublication
Inheritance diagram of siibra.commons.TypePublication

A simple typed namespace. At runtime it is equivalent to a plain dict.

TypedDict creates a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage:

class Point2D(TypedDict):
    x: int
    y: int
    label: str

a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check

assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')

The type info can be accessed via Point2D.__annotations__. TypedDict supports two additional equivalent forms:

Point2D = TypedDict('Point2D', x=int, y=int, label=str)
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})

By default, all keys must be present in a TypedDict. It is possible to override this by specifying totality. Usage:

class point2D(TypedDict, total=False):
    x: int
    y: int

This means that a point2D TypedDict can have any of the keys omitted.A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body be required.

The class syntax is only supported in Python 3.6+, while two other syntax forms work for Python 2.7 and 3.2+

citation: str
url: str
siibra.commons.MI(arr1, arr2, nbins=100, normalized=True)

Compute the mutual information between two 3D arrays, which need to have the same shape.

Parameters:
  • arr1 (np.ndarray) – First 3D array

  • arr2 (np.ndarray) – Second 3D array

  • nbins (int) – number of bins to use for computing the joint histogram (applies to intensity range)

  • normalized (Boolean. Default: True) – if True, the normalized MI of arrays X and Y will be returned, leading to a range of values between 0 and 1. Normalization is achieved by NMI = 2*MI(X,Y) / (H(X) + H(Y)), where H(x) is the entropy of X

siibra.commons.affine_scaling(affine)

Estimate approximate isotropic scaling factor of an affine matrix.

siibra.commons.argmax_dim4(img, dim=-1)

Given a nifti image object with four dimensions, returns a modified object with 3 dimensions that is obtained by taking the argmax along one of the four dimensions (default: the last one). To distinguish the pure background voxels from the foreground voxels of channel 0, the argmax indices are incremented by 1 and label index 0 is kept to represent the background.

siibra.commons.clear_name(name)

clean up a region name to the for matching

siibra.commons.compare_arrays(arr1: numpy.ndarray, affine1: numpy.ndarray, arr2: numpy.ndarray, affine2: numpy.ndarray)

Compare two arrays in physical space as defined by the given affine matrices. Matrices map voxel coordinates to physical coordinates. This function uses the object id to cache extraction of the nonzero coordinates. Repeated calls involving the same map will therefore be much faster as they will only access the image array if overlapping pixels are detected.

It is recommended to install the indexed-gzip package, which will further speed this up.

siibra.commons.connected_components(imgdata: numpy.ndarray, background: int = 0, connectivity: int = 2, threshold: float = 0.0) Generator[Tuple[int, numpy.ndarray], None, None]

Provide an iterator over connected components in the array. If the image data is float (such as probability maps), it will convert to a mask and then find the connected components.

Note

Uses skimage.measure.label() to determine foreground compenents.

Parameters:
  • imgdata (np.ndarray) –

  • background_value (int, Default: 0) –

  • connectivity (int, Default: 2) –

  • threshold (float, Default: 0.0) – The threshold used to create mask from probability maps, i.e, anything below set to 0 and rest to 1.

Yields:

Generator[Tuple[int, np.ndarray], None, None] – tuple of integer label of the component and component as an nd.array in the shape of the original image.

siibra.commons.create_gaussian_kernel(sigma=1, sigma_point=3)

Compute a 3D Gaussian kernel of the given bandwidth.

siibra.commons.create_key(name: str)

Creates an uppercase identifier string that includes only alphanumeric characters and underscore from a natural language name.

siibra.commons.generate_uuid(string: str)
siibra.commons.is_mesh(structure: list | dict)
siibra.commons.merge_meshes(meshes: list, labels: list = None)
siibra.commons.nonzero_coordinates(arr)
siibra.commons.resample_array_to_array(source_data: numpy.ndarray, source_affine: numpy.ndarray, target_data: numpy.ndarray, target_affine: numpy.ndarray) numpy.ndarray

Returns the source data resampled to match the target data according to their affines.

siibra.commons.set_log_level(level)
siibra.commons.siibra_tqdm(iterable: Iterable[T] = None, *args, **kwargs)
siibra.commons.snake2camel(s: str)

Converts a string in snake_case into CamelCase. For example: JULICH_BRAIN -> JulichBrain

siibra.commons.translation_matrix(tx: float, ty: float, tz: float)

Construct a 3D homoegneous translation matrix.

siibra.commons.unify_stringlist(L: list)

Adds asterisks to strings that appear multiple times, so the resulting list has only unique strings but still the same length, order, and meaning. For example:

unify_stringlist([‘a’,’a’,’b’,’a’,’c’]) -> [‘a’,’a*’,’b’,’a**’,’c’]

siibra.commons.y_rotation_matrix(alpha: float)

Construct a 3D y axis rotation matrix.

siibra.commons.HBP_AUTH_TOKEN
siibra.commons.KEYCLOAK_CLIENT_ID
siibra.commons.KEYCLOAK_CLIENT_SECRET
siibra.commons.NZCACHE
siibra.commons.QUIET
siibra.commons.REMOVE_FROM_NAME = ['hemisphere', ' -', '-brain', 'both', 'Both']
siibra.commons.REPLACE_IN_NAME
siibra.commons.ROOT_DIR
siibra.commons.SIIBRA_CACHEDIR
siibra.commons.SIIBRA_DEFAULT_MAPTYPE
siibra.commons.SIIBRA_DEFAULT_MAP_THRESHOLD = 0.0
siibra.commons.SIIBRA_LOG_LEVEL
siibra.commons.SIIBRA_MAX_FETCH_SIZE_GIB
siibra.commons.SIIBRA_USE_CONFIGURATION
siibra.commons.SIIBRA_USE_LOCAL_SNAPSPOT
siibra.commons.SKIP_CACHEINIT_MAINTENANCE
siibra.commons.T
siibra.commons.VERBOSE
siibra.commons.__version__
siibra.commons.ch
siibra.commons.formatter
siibra.commons.logger