neurolang.atlases#

Atlases: a label image, its affine, a label table and a space.

An Atlas is what .load_atlas, add_atlas_set and the atlases: of an engine load: the regions of the relation name(label, region) of the engine, the centres of their voxels, and what the engine tracts indexes streamlines by. This module owns the loaders (a FreeSurfer colour LUT, a BIDS dseg.tsv, a TSV, a CSV, a nilearn fetcher, the fetchers of the atlases of the engines), the normalisation of label names, the inference of the hemisphere of a label, the space tag and the content hash.

It needs numpy, pandas and nibabel only, and nilearn when an atlas is fetched, so that the core of the engine tracts may import it: it imports no other module of NeuroLang but neurolang.utils.nilearn_compat, lazily, to fetch (.importlinter).

Module Attributes

Space

A free-form tag naming a coordinate space, e.g. "MNI152NLin2009cAsym" or "subject:100307".

HEMISPHERES

The hemisphere of a label.

HEMISPHERE_RULES

The default, ordered rules; the first that matches wins: FreeSurfer Left-/Right-, ctx-lh-/ctx-rh- and a2009s ctx_lh_/ctx_rh_ (ctx lh `` as :func:`label_name` writes them), the suffixes ``_L/_R (AAL), lh./rh., .left/.right, the prefixes Left ``/``Right `` (Harvard-Oxford) and ``L ``/``R `` (nilearn's Destrieux), and the suffixes ``-lh/-rh (Tian's subcortex), `` lh``/`` rh`` as label_name() writes them, and Schaefer's 17Networks_LH_/ _RH_ (``17Networks LH ``).

FREESURFER_LUT_URL

FreeSurfer's colours of its labels, those of the Destrieux atlas (aparc.a2009s, ctx_lh_G_and_S_frontomargin...) among them.

DESTRIEUX_TO_MNI152

The millimetres of nilearn's Destrieux atlas to those of the MNI152 template: derived from FreeSurfer's fsaverage, it is 1.3 to 2.6% smaller than the template and off by about a millimetre.

TIAN_COLOURS_URL

The label files of the authors with the colours of the regions: those of the atlases of the cortex and the subcortex together.

FETCHERS

The fetchers of the deterministic atlases of the engines, by the kind of .load_atlas: each returns maps (a path) and labels, as nilearn's fetchers.

Functions

check_same_space(atlas_space, other_space[, ...])

Raise SpaceMismatchError unless the spaces are equal.

fetch_destrieux(**kwargs)

The Destrieux 2009 atlas of nilearn, on the MNI152 template (DESTRIEUX_TO_MNI152): maps, labels and lut, with FreeSurfer's colours of its regions in its color column when they can be fetched (freesurfer_colours()).

fetch_schaefer(**kwargs)

The Schaefer 2018 atlas of nilearn: maps and labels.

fetch_tian([scale, data_dir])

Fetch the Melbourne subcortex atlas (Tian et al., 2020, Nat Neurosci, doi:10.1038/s41593-020-00711-6), 3T, at scale 1 to 4 (16, 32, 50 or 54 regions), on the 2 mm grid of the MNI152 2009c asymmetric template, from the authors' repository.

freesurfer_colours(data_dir)

The colour of each label of FreeSurfer's look-up table, by name, fetched into data_dir/freesurfer.

infer_hemispheres(names[, rules])

The hemisphere of label names, by the first rule that matches.

label_colours(labels)

The colour, #rrggbb, of each label id of a look-up table with a color column, as nilearn's fetchers (and those of FETCHERS) give it in lut; {} for labels without colours.

label_name(value)

A raw label name as the fetched atlases name their regions: a string, decoded if bytes, whose - and _ are spaces ("L G_and_S_frontomargin" is "L G and S frontomargin").

label_table(labels)

The id, name table of labels as nilearn's fetchers (and those of FETCHERS) give them: a DataFrame with index and name (a look-up table), a dict id -> name, a list whose position is the id, or pairs (id, name).

label_voxel_indices(data, labels)

Voxel coordinates of each label of a labelled array, in one pass.

load_label_table_bids_dseg(path)

Read a BIDS *_dseg.tsv (columns index and name).

load_label_table_csv(path, **read_csv)

Read a table whose first two columns are the id and the name of each label, whatever their headers, with pandas.read_csv(path, **read_csv) (what .load_atlas reads from a URL).

load_label_table_freesurfer_lut(path)

Read a FreeSurfer colour LUT (FreeSurferColorLUT.txt).

load_label_table_tsv(path)

Read a TSV with columns id, name and optionally hemi.

registered_image(path, transform)

The image path with its millimetres moved by transform, a 4×4 matrix, in a file of its own next to it (x_mni152.nii.gz), written once: its voxels are those of path, only its affine changes.

Classes

Atlas(name, labels, affine, table[, space, ...])

A deterministic atlas: label volume + affine + label table + space.

HemisphereRule(pattern, hemi)

Infer the hemisphere of a label name.

Exceptions

SpaceMismatchError

Two objects, e.g. an atlas and a tractogram, are not in one space.

class neurolang.atlases.Atlas(name, labels, affine, table, space='unspecified', background=0, hemisphere_rules=(HemisphereRule(pattern='Left[- ].+', hemi='left'), HemisphereRule(pattern='Right[- ].+', hemi='right'), HemisphereRule(pattern='ctx[-_ ]lh[-_ ].+', hemi='left'), HemisphereRule(pattern='ctx[-_ ]rh[-_ ].+', hemi='right'), HemisphereRule(pattern='.+_L', hemi='left'), HemisphereRule(pattern='.+_R', hemi='right'), HemisphereRule(pattern='lh\\..+', hemi='left'), HemisphereRule(pattern='rh\\..+', hemi='right'), HemisphereRule(pattern='.+\\.left', hemi='left'), HemisphereRule(pattern='.+\\.right', hemi='right'), HemisphereRule(pattern='L .+', hemi='left'), HemisphereRule(pattern='R .+', hemi='right'), HemisphereRule(pattern='.+[- ]lh', hemi='left'), HemisphereRule(pattern='.+[- ]rh', hemi='right'), HemisphereRule(pattern='\\d+Networks[_ ]LH[_ ].+', hemi='left'), HemisphereRule(pattern='\\d+Networks[_ ]RH[_ ].+', hemi='right')), kind=None, image=None)#

A deterministic atlas: label volume + affine + label table + space.

Parameters:
namestr

The atlas’s identifier, unique in an engine.

labelsnumpy.ndarray

3D volume of non-negative integer labels (floats with integral values are accepted); background marks voxels outside any region.

affinenumpy.ndarray

4x4, voxel indices (ijk) to the space’s world coordinates in mm (RAS+, as nibabel): the affine maps an index to the centre of its voxel.

tablepandas.DataFrame

Columns id, name and optionally hemi (left, right, none or empty). Ids of the table absent from the volume are dropped, with a warning; ids of the volume absent from the table (other than the background) are no region, with a warning (unlisted_labels).

spaceSpace

The space tag, "unspecified" by default.

backgroundint

The label that means “no region” (default 0): it has no region and no point, but keeps its row of the table if it has one.

hemisphere_rulesSequence[HemisphereRule]

Rules to infer the hemisphere from the name, where the table does not say it. Defaults to HEMISPHERE_RULES; () infers nothing.

kindstr, optional

How it was loaded: the kind of .load_atlas (freesurfer, destrieux…; nilearn:<fetcher> for a nilearn fetcher).

imageoptional

The nibabel image the volume was read from, kept as image.

Parameters:

Notes

self.table is the resolved label table: columns id (int32), name, hemi, by id, for the ids of the table in the volume. The hemisphere of a label is the hemi of the table, if not empty, else the inference by hemisphere_rules (hemispheres()).

check_same_space(other, allow_mismatch=False)#

Raise SpaceMismatchError unless other (an atlas, or anything with a space) is in the same space as this atlas; with allow_mismatch, warn.

Parameters:
  • other (Any)

  • allow_mismatch (bool)

Return type:

None

content_hash()#

Hash of the volume, affine, label table, background and space, not of the name nor of the kind.

Return type:

str

classmethod fetch(name, kind, data_dir, space='MNI152', **options)#

The atlas of an engine of kind destrieux, schaefer or tian (FETCHERS), fetched into data_dir with the options of its fetcher (n_rois=100 of schaefer, scale=2 of tian), its label names normalised (label_name()).

Parameters:
Return type:

Atlas

classmethod from_bids_dseg(name, image, dseg_tsv, space='unspecified', **kwargs)#

From a label image and its BIDS dseg.tsv.

Parameters:
Return type:

Atlas

classmethod from_csv(name, image, labels_csv, space='unspecified', read_csv=None, **kwargs)#

From a label image and a table whose first two columns are the id and the name of each label, read by pandas.read_csv with the options read_csv (load_label_table_csv()).

Parameters:
Return type:

Atlas

classmethod from_freesurfer(name, image, lut, space='unspecified', **kwargs)#

From a label image (path or nibabel image) and a FreeSurfer LUT.

Keyword arguments are those of the constructor.

Parameters:
Return type:

Atlas

classmethod from_labels(name, image, labels, space='unspecified', normalise=False, **kwargs)#

From a label image and its labels as nilearn’s fetchers give them: a look-up table (DataFrame with index and name), a dict id -> name, a list whose position is the id (with a leading Background), or pairs (id, name). The row of the background, if any, is dropped. With normalise, the names are those of label_name(), as the engines name the regions of the atlases they fetch.

Parameters:
Return type:

Atlas

classmethod from_nilearn(name, fetcher, space='MNI152', background=0, hemisphere_rules=(HemisphereRule(pattern='Left[- ].+', hemi='left'), HemisphereRule(pattern='Right[- ].+', hemi='right'), HemisphereRule(pattern='ctx[-_ ]lh[-_ ].+', hemi='left'), HemisphereRule(pattern='ctx[-_ ]rh[-_ ].+', hemi='right'), HemisphereRule(pattern='.+_L', hemi='left'), HemisphereRule(pattern='.+_R', hemi='right'), HemisphereRule(pattern='lh\\..+', hemi='left'), HemisphereRule(pattern='rh\\..+', hemi='right'), HemisphereRule(pattern='.+\\.left', hemi='left'), HemisphereRule(pattern='.+\\.right', hemi='right'), HemisphereRule(pattern='L .+', hemi='left'), HemisphereRule(pattern='R .+', hemi='right'), HemisphereRule(pattern='.+[- ]lh', hemi='left'), HemisphereRule(pattern='.+[- ]rh', hemi='right'), HemisphereRule(pattern='\\d+Networks[_ ]LH[_ ].+', hemi='left'), HemisphereRule(pattern='\\d+Networks[_ ]RH[_ ].+', hemi='right')), **options)#

The atlas nilearn.datasets.fetch_atlas_<fetcher>(**options) fetches (destrieux_2009, harvard_oxford with atlas_name=..., schaefer_2018 with n_rois=...), its label names normalised (label_name()), as the engines name those of the atlases they fetch. Its kind is nilearn:<fetcher>.

Parameters:
  • name (str)

  • fetcher (str)

  • space (Space)

  • background (int)

  • options (Any)

Return type:

Atlas

classmethod from_tsv(name, image, tsv, space='unspecified', **kwargs)#

From a label image and a TSV (id, name``[, ``hemi]).

Parameters:
Return type:

Atlas

hemispheres(hints=None)#

The hemisphere of each label of table, in its order.

It is, in order of precedence: the hemi of the label table, if not empty; the hint for its name, if any and not empty; the inference by the hemisphere rules. A warning names each label for which two of these disagree (the inference counting only when it is not none); with hints, only those where a hint is one of them.

Parameters:
hintsdict, optional

A label name -> left, right, none or "", e.g. the hemi of a term mapping of the engine tracts.

Parameters:

hints (Dict[str, str] | None)

Return type:

Series

property image#

The nibabel image of the atlas: the one it was read from, if any, else one of its volume and affine.

label_values()#

The ids of each region, by name (a name may have several).

Return type:

Dict[str, List[int]]

label_voxels()#

The voxel indices (ijk) of each region, by id, found in one pass (label_voxel_indices()).

Return type:

Dict[int, ndarray]

points()#

The centre of every voxel of a region, in mm through the affine, and its name: columns x, y, z, label, in the (C) order of the voxels.

Return type:

DataFrame

present_labels#

the sorted ids of the labels of the volume (with the background)

region_names()#

The name of each region, by id: the labels of the table but the background.

Return type:

Dict[int, str]

property shape#

The shape of the volume.

neurolang.atlases.FETCHERS = {'destrieux': <function fetch_destrieux>, 'schaefer': <function fetch_schaefer>, 'tian': <function fetch_tian>}#

The fetchers of the deterministic atlases of the engines, by the kind of .load_atlas: each returns maps (a path) and labels, as nilearn’s fetchers.

neurolang.atlases.HEMISPHERES = ('left', 'right', 'none')#

The hemisphere of a label.

neurolang.atlases.HEMISPHERE_RULES: Sequence[HemisphereRule] = (HemisphereRule(pattern='Left[- ].+', hemi='left'), HemisphereRule(pattern='Right[- ].+', hemi='right'), HemisphereRule(pattern='ctx[-_ ]lh[-_ ].+', hemi='left'), HemisphereRule(pattern='ctx[-_ ]rh[-_ ].+', hemi='right'), HemisphereRule(pattern='.+_L', hemi='left'), HemisphereRule(pattern='.+_R', hemi='right'), HemisphereRule(pattern='lh\\..+', hemi='left'), HemisphereRule(pattern='rh\\..+', hemi='right'), HemisphereRule(pattern='.+\\.left', hemi='left'), HemisphereRule(pattern='.+\\.right', hemi='right'), HemisphereRule(pattern='L .+', hemi='left'), HemisphereRule(pattern='R .+', hemi='right'), HemisphereRule(pattern='.+[- ]lh', hemi='left'), HemisphereRule(pattern='.+[- ]rh', hemi='right'), HemisphereRule(pattern='\\d+Networks[_ ]LH[_ ].+', hemi='left'), HemisphereRule(pattern='\\d+Networks[_ ]RH[_ ].+', hemi='right'))#

The default, ordered rules; the first that matches wins: FreeSurfer Left-/Right-, ctx-lh-/ctx-rh- and a2009s ctx_lh_/ctx_rh_ (ctx lh `` as :func:`label_name` writes them), the suffixes ``_L/_R (AAL), lh./rh., .left/.right, the prefixes Left ``/``Right `` (Harvard-Oxford) and ``L ``/``R `` (nilearn's Destrieux), and the suffixes ``-lh/-rh (Tian’s subcortex), `` lh``/`` rh`` as label_name() writes them, and Schaefer’s 17Networks_LH_/ _RH_ (``17Networks LH ``).

class neurolang.atlases.HemisphereRule(pattern, hemi)#

Infer the hemisphere of a label name.

Attributes:
patternstr

A regular expression that must match the whole name.

hemistr

"left" or "right".

Parameters:
exception neurolang.atlases.SpaceMismatchError#

Two objects, e.g. an atlas and a tractogram, are not in one space.

add_note()#

Exception.add_note(note) – add a note to the exception

with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

neurolang.atlases.check_same_space(atlas_space, other_space, allow_mismatch=False)#

Raise SpaceMismatchError unless the spaces are equal.

Parameters:
atlas_space, other_spaceSpace

The tags of the atlas and of the other object, e.g. a tractogram.

allow_mismatchbool

The explicit override: if True, warn instead of raising. The caller asserts that the two are aligned by other means.

Parameters:
  • atlas_space (Space)

  • other_space (Space)

  • allow_mismatch (bool)

Return type:

None

neurolang.atlases.infer_hemispheres(names, rules=(HemisphereRule(pattern='Left[- ].+', hemi='left'), HemisphereRule(pattern='Right[- ].+', hemi='right'), HemisphereRule(pattern='ctx[-_ ]lh[-_ ].+', hemi='left'), HemisphereRule(pattern='ctx[-_ ]rh[-_ ].+', hemi='right'), HemisphereRule(pattern='.+_L', hemi='left'), HemisphereRule(pattern='.+_R', hemi='right'), HemisphereRule(pattern='lh\\..+', hemi='left'), HemisphereRule(pattern='rh\\..+', hemi='right'), HemisphereRule(pattern='.+\\.left', hemi='left'), HemisphereRule(pattern='.+\\.right', hemi='right'), HemisphereRule(pattern='L .+', hemi='left'), HemisphereRule(pattern='R .+', hemi='right'), HemisphereRule(pattern='.+[- ]lh', hemi='left'), HemisphereRule(pattern='.+[- ]rh', hemi='right'), HemisphereRule(pattern='\\d+Networks[_ ]LH[_ ].+', hemi='left'), HemisphereRule(pattern='\\d+Networks[_ ]RH[_ ].+', hemi='right')))#

The hemisphere of label names, by the first rule that matches.

Returns:
pandas.Series

"left", "right" or "none" for each name, in order.

Parameters:
Return type:

Series

neurolang.atlases.label_colours(labels)#

The colour, #rrggbb, of each label id of a look-up table with a color column, as nilearn’s fetchers (and those of FETCHERS) give it in lut; {} for labels without colours.

Parameters:

labels (Any)

Return type:

Dict[int, str]

neurolang.atlases.label_name(value)#

A raw label name as the fetched atlases name their regions: a string, decoded if bytes, whose - and _ are spaces ("L G_and_S_frontomargin" is "L G and S frontomargin").

Parameters:

value (Any)

Return type:

str

neurolang.atlases.label_table(labels)#

The id, name table of labels as nilearn’s fetchers (and those of FETCHERS) give them: a DataFrame with index and name (a look-up table), a dict id -> name, a list whose position is the id, or pairs (id, name).

Parameters:

labels (Any)

Return type:

DataFrame

neurolang.atlases.label_voxel_indices(data, labels)#

Voxel coordinates of each label of a labelled array, in one pass.

Parameters:
datanumpy.ndarray

labelled array.

labelsiterable

label values to look up.

Returns:
dict

mapping each label to an (n, data.ndim) integer array with the coordinates of the voxels equal to it, in the same (C) order as numpy.nonzero(data == label).

neurolang.atlases.load_label_table_bids_dseg(path)#

Read a BIDS *_dseg.tsv (columns index and name).

Parameters:

path (str | PathLike)

Return type:

DataFrame

neurolang.atlases.load_label_table_csv(path, **read_csv)#

Read a table whose first two columns are the id and the name of each label, whatever their headers, with pandas.read_csv(path, **read_csv) (what .load_atlas reads from a URL).

Parameters:
Return type:

DataFrame

neurolang.atlases.load_label_table_freesurfer_lut(path)#

Read a FreeSurfer colour LUT (FreeSurferColorLUT.txt).

Returns:
pandas.DataFrame

Columns id (int64) and name; the colours are ignored.

Parameters:

path (str | PathLike)

Return type:

DataFrame

neurolang.atlases.load_label_table_tsv(path)#

Read a TSV with columns id, name and optionally hemi.

Empty hemi cells are "" (the hemisphere is then inferred).

Parameters:

path (str | PathLike)

Return type:

DataFrame