siibra.commons

Contents

siibra.commons

Constants, functions, and classes used commonly across siibra.

Attributes

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

Create a collection of name/value pairs.

Species

Create a collection of name/value pairs.

TypePublication

dict() -> new empty dictionary

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_img_to_img(→ nibabel.Nifti1Image)

Resamples to source image to match the target image according to target's

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.

Module Contents

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.

__contains__(key: str | T) bool

Test whether 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__()
__str__() str
__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()
property dataframe
class siibra.commons.LoggingContext(level)
__enter__()
__exit__(et, ev, tb)
level
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)
__hash__()
__repr__()
__str__()
classmethod from_dict(spec: dict)
fragment = None
label = None
volume = None
class siibra.commons.MapType(*args, **kwds)
Inheritance diagram of siibra.commons.MapType

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

>>> Color.RED
<Color.RED: 1>
  • value lookup:

>>> Color(1)
<Color.RED: 1>
  • name lookup:

>>> Color['RED']
<Color.RED: 1>

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

LABELLED = 1
STATISTICAL = 2
class siibra.commons.Species(*args, **kwds)
Inheritance diagram of siibra.commons.Species

Create a collection of name/value pairs.

Example enumeration:

>>> class Color(Enum):
...     RED = 1
...     BLUE = 2
...     GREEN = 3

Access them by:

  • attribute access:

>>> Color.RED
<Color.RED: 1>
  • value lookup:

>>> Color(1)
<Color.RED: 1>
  • name lookup:

>>> Color['RED']
<Color.RED: 1>

Enumerations can be iterated over, and know how many members they have:

>>> len(Color)
3
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.

__repr__()
__str__()
classmethod decode(spec: str | Species | dict, fail_if_not_successful=True)
static key_to_name(key: str)
static name_to_key(name: str)
CALLITHRIX_JACCHUS = 8
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
class siibra.commons.TypePublication
Inheritance diagram of siibra.commons.TypePublication

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s

(key, value) pairs

dict(iterable) -> new dictionary initialized as if via:

d = {} for k, v in iterable:

d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs

in the keyword argument list. For example: dict(one=1, two=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 components.

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 ndarray 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_img_to_img(source_img: nibabel.Nifti1Image, target_img: nibabel.Nifti1Image, interpolation: str = '') nibabel.Nifti1Image

Resamples to source image to match the target image according to target’s affine. (A wrapper of nilearn.image.resample_to_img.)

Parameters:
  • source_img (Nifti1Image)

  • target_img (Nifti1Image)

  • interpolation (str, Default: "nearest" if the source image is a mask otherwise "linear".) – Can be ‘continuous’, ‘linear’, or ‘nearest’. Indicates the resample method.

Return type:

Nifti1Image

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_LOG_LEVEL
siibra.commons.SIIBRA_MAX_FETCH_SIZE_BYTES
siibra.commons.SIIBRA_NG_VOL_USE_CACHE
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