braian
AllenBrainOntology
AllenBrainOntology(allen_json, blacklisted_acronyms=[], name=None, version=None)
Crates an ontology of brain regions based on Allen Institute's structure graphs.
To know more where to get the structure graphs, read the
official guide
from Allen Institute.
However, the ontology differs from the region annotations depeding on the version of the common coordinate
framework (CCF). This happens when a new CCF version changes a branch in the ontoloy to reflect a new scientific consesus.
In Allen's website, the "old" brain region can be identified in grey italic text:
If you want to clean the ontology based on a particular version of the CCF, you can provide a valid value for version
Parameters:
-
allen_json:str | Path | dictThe path to an Allen structural graph json
-
blacklisted_acronyms:Iterable, default=[]Acronyms of branches from the onthology to exclude completely from the analysis
-
name:str | None, default=Nonethe name of a Allen-compatible mouse brain atlas from BrainGlobe
-
version:str | None, default=NoneMust be
"CCFv1","CCFv2","CCFv3","CCFv4"orNone. The version of the Common Coordinates Framework to which the onthology is synchronised
direct_subregions
instance-attribute
A dictionary mappin region's acronyms to a list of direct subregions.
Examples:
>>> braian.utils.cache("ontology.json", "http://api.brain-map.org/api/v2/structure_graph_download/1.json")
>>> brain_ontology = braian.AllenBrainOntology("ontology.json", [])
>>> brain_ontology.direct_subregions["ACA"]
["ACAv", "ACAd"] # dorsal and ventral part
>>> brain_ontology.direct_subregions["ACAv"]
["ACAv5", "ACAv2/3", "ACAv6a", "ACAv1", "ACAv6b"] # all layers in ventral part
full_name
instance-attribute
A dictionary mapping a regions' acronym to its full name.
is_region
is_region(r, key='acronym')
Check whether a region is recognised in the current ontology or not
Parameters:
-
r:int | strA value that uniquely indentifies a brain region (e.g. its acronym)
-
key:str, default='acronym'The key in Allen's structural graph used to identify
r
Returns:
-
bool–True, if a region identifiable by
rexists in the ontoloy. False otherwise.
are_regions
are_regions(a, key='acronym')
contains_all_children
contains_all_children(parent, regions)
minimimum_treecover
minimimum_treecover(acronyms)
Returns the minimum set of regions that covers all the given regions, and not more.
Parameters:
Returns:
Examples:
>>> braian.utils.cache("ontology.json", "http://api.brain-map.org/api/v2/structure_graph_download/1.json")
>>> brain_ontology = braian.AllenBrainOntology("ontology.json", [])
>>> sorted(brain_ontology.minimimum_treecover(['P', 'MB', 'TH', 'MY', 'CB', 'HY']))
['BS', 'CB']
>>> sorted(brain_ontology.minimimum_treecover(["RE", "Xi", "PVT", "PT", "TH"]))
['MTN', 'TH']
blacklist_regions
blacklist_regions(regions, key='acronym', has_reference=True)
Blacklists from further analysis the given regions the ontology, as well as all their sub-regions.
If the reason of blacklisting is that regions no longer exist in the used version of the
Common Coordinate Framework, set has_reference=False
Parameters:
-
regions:IterableRegions to blacklist
-
key:str, default='acronym'The key in Allen's structural graph used to identify the
regionsto blacklist -
has_reference:bool, default=TrueIf
regionsexist in the used version of the CCF or not
Raises:
-
ValueError–If it can't find at least one of the
regionsin the ontology
get_blacklisted_trees
get_blacklisted_trees(key='acronym')
select_at_depth
select_at_depth(depth)
Select all non-overlapping brain regions at the same depth in the ontology. If a brain region is above the given depth but has no sub-regions, it is selected anyway.
Parameters:
-
depth:intThe desired depth in the ontology to select
select_at_structural_level
select_at_structural_level(level)
Select all non-overlapping brain regions at the same structural level in the ontology.
The structural level is an attribute given to each region by Allen,
defining different level of granularity to study the brain.
If a brain region is above the given level and has no sub-regions, it is not selected.
Parameters:
-
level:intThe structural level in the ontology to select
select_leaves
select_leaves()
Select all th enon-overlapping smallest brain regions in the ontology. A region is also selected if it's not the smallest possible, but all of its sub-regions are blacklisted
select_summary_structures
select_summary_structures()
Select all summary structures in the ontology. The list of Summary Structures is defined by Allen as a set of non-overlapping, finer divisions, independent of their exact depth in the tree. They are a set of brain regions often used in the literature.
Summary Structures can be retrieved from Table S2 of this article: https://www.sciencedirect.com/science/article/pii/S0092867420304025
select_regions
select_regions(regions, key='acronym')
Select the given regions in the ontology
Parameters:
-
regions:IterableThe brain regions to select
-
key:str, default='acronym'The key in Allen's structural graph used to indentify the regions
Raises:
-
ValueError–If it can't find at least one of the
regionsin the ontology
add_to_selection
add_to_selection(regions, key='acronym')
Add the given brain regions to the current selection in the ontology
Parameters:
has_selection
has_selection()
Check whether the current ontology is currently selecting any brain region.
Returns:
-
bool–True, if the current ontology had a selection method previosuly called. Otherwise, False.
get_selected_regions
get_selected_regions(key='acronym')
unselect_all
unselect_all()
Resets the selection in the ontology
get_regions
get_regions(selection_method)
Returns a list of acronyms of non-overlapping regions based on the selection method.
Parameters:
-
selection_method:strMust be "summary structure", "major divisions", "leaves", "depth
" or "structural level "
Returns:
Raises:
-
ValueError–If
selection_methodis not recognised
ids_to_acronym
ids_to_acronym(ids, mode='depth')
Converts the given brain regions IDs into their corresponding acronyms.
Parameters:
-
ids:Container[int]The brain regions' IDs to convert
-
mode:str, default='depth'If None, it returns the acronyms in the same order as the given
ids. Otherwise, it must be either "breadth"—for breadth-first—or "depth"—for depth-first order.
Returns:
Raises:
-
ValueError–If given
modeis not supported -
ValueError–If it can't find at least one of the
idsin the ontology
acronyms_to_id
acronyms_to_id(acronyms, mode='depth')
Converts the given brain regions acronyms into ther corresponding IDs
Parameters:
-
acronyms:Container[str]the brain regons' acronyms to convert
-
mode:str, default='depth'If None, it returns the IDs in the same order as the given
acronyms. Otherwise, it must be either "breadth"—for breadth-first—or "depth"—for depth-first order.
Returns:
Raises:
-
ValueError–If given
modeis not supported -
ValueError–If it can't find at least one of the
acronymsin the ontology
get_sibiling_regions
get_sibiling_regions(region, key='acronym')
Get all brain regions that, combined, make the whole parent of the given region
It does not take into account blacklisted regions
Parameters:
-
region:str | intA brain region
-
key:str, default='acronym'The key in Allen's structural graph used to indentify the regions
Returns:
-
list–All
region's sibilings, including itself
Raises:
-
ValueError–If it can't find a parent for the given
region
get_parent_regions
get_parent_regions(regions, key='acronym')
Finds, for each of the given brain regions, their parent region in the ontology
It does not take into account blacklisted regions
Parameters:
-
regions:IterableThe brain regions to search the parent for
-
key:str, default='acronym'The key in Allen's structural graph used to indentify the regions
Returns:
-
dict–A dicrtionary mapping region→parent
Raises:
-
ValueError–If it can't find the parent of one of the given
regions
list_all_subregions
list_all_subregions(acronym, mode='breadth')
Lists all subregions of a brain region, at all hierarchical levels.
It does not take into account blacklisted regions
Parameters:
-
acronym:strThe acronym of the brain region
-
mode:str, default='breadth'Must be eithe "breadth" or "depth". The order in which the returned acronyms will be: breadth-first or depth-first
Returns:
-
list–A list of subregions of
acronym
Raises:
-
ValueError–If given
modeis not supported -
ValueError–If it can't find
acronymin the ontology
get_regions_above
get_regions_above(acronym)
get_corresponding_md
get_corresponding_md(acronym, *acronyms)
Finds the corresponding major division for each on the the acronyms.
The returned dictionary is sorted in depth-first-search order.
It does not take into account blacklisted regions
Parameters:
-
acronym:strAcronym of the brain region of which you want to know the corresponding major division
Returns:
-
OrderedDict[str, str]–An OrderedDict mapping \(\text{region acronym}→\text{major division}\)
Raises:
-
ValueError–If it can't find some of the given
acronymin the ontology.
get_layer1
get_layer1()
get_region_colors
get_region_colors()
BrainSlice
BrainSlice(data, animal, name, is_split, units, brain_ontology=None, atlas=None)
Creates a BrainSlice from a DataFrame. Each row representes the data
of a single brain region, whose acronym is used as index. If the data was collected
distinguishing between the two hemispheres, the index is expected to be either Left: <ACRONYM>
or Right: <ACRONYM>. The DataFrame is expected to have at least two columns: one named "area"
corresponding to the size specified in units, and the others corresponding to the markers used to
measure brain activity.
Parameters:
-
data:pd.DataFrameThe data extracted from a brain slice.
-
animal:strThe name of the animal from which the slice was cut.
-
name:strThe name of hte brain slice.
-
is_split:boolWhether the data was extracted distinguishing between the two hemispheres or not.
-
units:dictThe units of measurement corresponding to each columns in
data. -
brain_ontology:AllenBrainOntology | None, default=NoneIf specified, it checks the brain regions in
dataagainst the given ontology and it sorts the rows in depth-first order in ontology's hierarchy.
Raises:
-
InvalidRegionsHemisphereError–If
is_split=Truebut some rows' indices don't start with"Left: "or with"Right: ". -
ValueError–If a specified unit of measurment in
unitsis unknown.
animal
instance-attribute
The name of the animal from which the current BrainSlice is from.
name
instance-attribute
The name of the image that captured the section from which the data of the current BrainSlice are from.
atlas
instance-attribute
The name of the brain atlas used to align the section. If None, it means that the cell-segmented data didn't specify it.
is_split
instance-attribute
Whether the data of the current BrainSlice make a distinction between right and left hemisphere.
markers
property
The name of the markers for which the current BrainSlice has data.
from_qupath
staticmethod
from_qupath(csv, ch2marker, atlas=None, *args, **kwargs)
Creates a BrainSlice from a file exported with
qupath-extension-braian.
Additional arguments are passed to BrainSlice's constructor.
Parameters:
-
csv:str | Path | pd.DataFrameThe path to file exported with
AtlasManager.saveResults(). If it ends with ".csv", it treats the file as a comma-separated table. Otherwise, it assuems it is tab-separated. It can also be a DataFrame. -
ch2marker:dict[str, str]A dictionary mapping the QuPath channel names to markers. A cell segmentation algorithm must have previously run on each of the given channels.
-
atlas:str, default=NoneThe name of the brain atlas used to align the section. If None, it won't use it as a sanity check of the
csvdata. -
*argsOther arguments are passed to
BrainSliceconstructor. -
**kwargsOther keyword arguments are passed to
BrainSliceconstructor.
Returns:
-
Self–
Raises:
-
EmptyResultsError–If the given
csvis empty -
InvalidResultsError–If the given
csvis an invalid file. Probably because it was not exported throughqupath-extension-braian. -
NanResultsError–If the number of total detections in all brain regions, exported from QuPath, is undefined
-
MissingResultsColumnError–If
csvis missing reporting the number of detection in at least onedetected_channels.
read_qupath_exclusions
staticmethod
read_qupath_exclusions(file_path)
Reads the regions to exclude from the analysis of a BrainSlice
from a file exported with qupath-extension-braian.
Parameters:
-
file_path:Path | strThe path to file exported with
AtlasManager.saveExcludedRegions().
Returns:
Raises:
-
ExcludedRegionsNotFoundError–If the
file_pathwas not found.
exclude_regions
exclude_regions(excluded_regions, brain_ontology, exclude_parent_regions)
Takes care of the regions to be excluded from the analysis.
If exclude_parent_regions is False, for each region:
- the cell counts of that region is subtracted fromm all its parent regions
- its cell counts are deleted from the current
BrainSlice, along with all of its subregions
If exclude_parent_regions is True, the parent regions of an excluded region is also
deleted from the current BrainSlice since its cell count is determined also by that same region.
NOTE: Netherless, if a Layer 1 region is explicitly excluded, it won't impact (i.e. remove) the parent regions. This decision was taken because Layer 1 is often mis-aligned but with few detection. We don't want to delete too much data and we reckon that this exception does not impact too much on the data of the whole Isocortex.
Parameters:
-
excluded_regions:Iterable[str]a list of acronyms of the regions to be excluded from the analysis.
-
brain_ontology:AllenBrainOntologyan ontology against whose version the brain section was aligned.
-
exclude_parent_regions:boolWhether the cell counts of the parent regions are excluded or subtracted.
Raises:
-
InvalidExcludedRegionsHemisphereError–if
BrainSlice.is_splitbut a region inexcluded_regionsis not considering left/right hemisphere distinction. -
UnknownBrainRegionsError–if a region in
excluded_regionsis not recognised frombrain_ontology. -
ExcludedAllRegionsError–if there is no cell count left after the exclusion is done.
merge_hemispheres
merge_hemispheres()
For each brain region, sums the data of left and right hemispheres into one single datum
Parameters:
-
sliceA brain section to merge
Returns:
-
Self–A new
BrainSlicewith no hemisphere distinction. Ifsliceis already merged, it return the same instance with no changes.
SlicedBrain
SlicedBrain(name, slices, markers)
A SlicedBrain is a collection of BrainSlice, and it is
an basic structure from which AnimalBrain are reconstructed.
Parameters:
-
name:strThe name of the animal.
-
slices:Iterable[BrainSlice]The list of
BrainSlicethat makes up a sample of a brain. -
markers:Iterable[str]The list of markers in used in all
BrainSlices.
Raises:
-
EmptyBrainError–If
slicesis empty.
is_split
instance-attribute
Whether the data of the current SlicedBrain makes a distinction between right and left hemisphere.
name
property
writable
The name of the animal.
slices
property
The list of slices making up the SlicedBrain.
from_qupath
staticmethod
from_qupath(name, animal_dir, brain_ontology, ch2marker, exclude_parent_regions=False, results_subdir='results', results_suffix='_regions.tsv', exclusions_subdir='regions_to_exclude', exclusions_suffix='_regions_to_exclude.txt')
Creates a SlicedBrain from all the per-image files exported with
qupath-extension-braian
inside animal_dir. It assumes that cell counts and exclusions files have the following naming structure:
<IDENTIFIER><SUFFIX>.<EXTENSION>. The identifier must be common in files relatives
to the same image. The suffix must be common to files of the same kind (i.e. cell counts
or exclusions). The extension defines whether the table
is comma-separated or tab-separated.
Parameters:
-
name:strThe name of the animal.
-
animal_dir:str | PathThe path to where all the reports of the brain sections were saved from QuPath. Both per-region results and exclusions.
-
brain_ontology:AllenBrainOntologyAn ontology against whose version the brain was aligned.
-
ch2marker:dict[str, str]A dictionary mapping QuPath channel names to markers.
-
exclude_parent_regions:bool, default=Falseexclude_parent_regionsfromBrainSlice.exclude_regions. -
results_subdir:str, default='results'The name of the subfolder in
animal_dirthat contains all cell counts files of each brain section.
It can beNoneif no subfolder is used. -
results_suffix:str, default='_regions.tsv'The suffix used to identify cell counts files saved in
results_subdir. It includes the file extension. -
exclusions_subdir:str, default='regions_to_exclude'The name of the subfolder in
animal_dirthat contains all regions to exclude from further analysis of each brain section.
It can beNoneif no subfolder is used. -
exclusions_suffix:str, default='_regions_to_exclude.txt'The suffix used to identify exclusion files saved in
results_subdir. It includes the file extension.
Returns:
-
Self–A
SlicedBrain.
concat_slices
concat_slices(densities=False)
Combines all the BrainSlice making up the current
SlicedBrain into a DataFrame.
Parameters:
-
densities:bool, default=FalseIf True, the result is a
DataFrameof slices marker densities. Otherwise, the result will contain the cell counts.
Returns:
-
pd.DataFrame–A
DataFrameof the data from allSlicedBrain.slices.
count
count(brain_ontology=None)
Counts the number of slices that contains data for each brain region.
Parameters:
-
brain_ontology:AllenBrainOntology, default=NoneIf specified, it sorts and check the regions accordingly to the given atlas ontology.
Returns:
-
BrainData–A
BrainDatawith the number of slices per region.
merge_hemispheres
merge_hemispheres()
Creates a new SlicedBrain from all merged BrainSlice
in sliced_brain.
Parameters:
-
sliced_brainA sliced brain to merge.
Returns:
-
Self–A new
SlicedBrainwith no hemisphere distinction. Ifsliced_brainis already merged, it return the same instance with no changes.
See also
BrainData
BrainData(data, name, metric, units, brain_ontology=None, fill_nan=False)
This class is the base structure for managing any data that associates values to brain regions. You can access its interanal representation through BrainData.data.
Parameters:
-
data:pd.SeriesA pandas Series associating brain region acronyms (i.e. the index) to brain data (i.e. the values).
-
name:strA name identifying
data. -
metric:strThe metric used to extract
data. If they no metric was previosuly used, useRAW_TYPE. -
units:strThe units of measurment of the values in
data. -
brain_ontology:AllenBrainOntology | None, default=NoneThe ontology against which the extracted data was aligned. It is used to check that all
datais attributable to a region in the ontology and to sort it accordingly.
If left empty, no check or sorting is performed. -
fill_nanIf ontology is not
None, it fills withNAthe value of the regions inontologyand missing fromdata.
See also
RAW_TYPE
class-attribute
instance-attribute
The identifier used to specify the nature of raw data as 'metric' attribute in BrainData.
data
instance-attribute
The internal representation of the current brain data.
is_split
instance-attribute
Whether the data of the current BrainData makes a distinction between right and left hemisphere.
data_name
instance-attribute
The name of the current BrainData.
metric
instance-attribute
The name of the metric used to compute the data.
Equals to RAW_TYPE if no previous normalization was preformed.
units
instance-attribute
The units of measurement of the current BrainData.
regions
property
The list of region acronyms for which the current instance records data.
reduce
staticmethod
Reduces two (or more) BrainData into a single one based on a given function.
It fails if the given data don't all have the same metric.
Parameters:
-
first:SelfThe first data to reduce.
-
*others:Self, default=()Any number of additional brain data to reduce.
-
op:Callable[[pd.DataFrame], pd.Series], default=pd.DataFrame.meanA function that maps a
DataFrameinto aSeries. It must include anaxisparameter. -
nameThe name of the resulting BrainData.
If not specified, it builds a name joining all given data names. -
op_nameThe name of the reduction function. If not specified, it uses
opname. -
same_unitsWhether it should enforce the same units of measurement for all
BrainData. -
**kwargsOther keyword arguments are passed to
op.
Returns:
-
Self–A new
BrainDataresult of the reduction of all the given data.
mean
staticmethod
mean(*data, **kwargs)
Computes the mean for each brain region between all data.
Parameters:
-
*data:Self, default=()The
BrainDatato average. -
**kwargsOther keyword arguments are passed to
BrainData.reduce.
Returns:
-
Self–The mean of all
data.
minimum
staticmethod
minimum(*data, **kwargs)
Computes the minimum value for each brain region between all data.
Parameters:
-
*data:Self, default=()The
BrainDatato search the minimum from. -
**kwargsOther keyword arguments are passed to
BrainData.reduce.
Returns:
-
Self–The minimum value of all
data.
maximum
staticmethod
maximum(*data, **kwargs)
Computes the maximum value for each brain region between all data.
Parameters:
-
*data:Self, default=()The
BrainDatato search the maximum from. -
**kwargsOther keyword arguments are passed to
BrainData.reduce.
Returns:
-
Self–The maximum value of all
data.
sort_by_ontology
sort_by_ontology(brain_ontology, fill_nan=False, inplace=False)
Sorts the data in depth-first search order with respect to brain_ontology's hierarchy.
Parameters:
-
brain_ontology:AllenBrainOntologyThe ontology to which the current data was registered against.
-
fill_nanIf True, it sets the value to
NaNfor all the regions inbrain_ontologymissing in the currentAnimalBrain. -
inplaceIf True, it applies the sorting to the current instance.
Returns:
-
Self–Brain data sorted accordingly to
brain_ontology. Ifinplace=Trueit returns the same instance.
root
root(hemisphere=None)
Retrieves the value associated to the whole brain.
Parameters:
-
hemisphere:str, default=NoneAnything between "left", "L", "right" and "R".
If the currentBrainDatais split, it defines for which hemisphere to retrieve the data. Otherwise, this parameter is ignored.
Returns:
-
float–The value of the root.
Raises:
-
ValueError–If
hemispherewas not specified but the currentBrainDatais split. -
ValueError–If there is no data for the 'root' brain region.
min
min(skipna=True, skiinf=False)
max
max(skipna=True, skiinf=False)
remove_region
remove_region(region, *regions, inplace=False, fill_nan=False)
Removes one or multiple regions from the current BrainData.
Parameters:
-
region:strAcronyms of the brain regions to remove.
-
*regions:strAcronyms of the brain regions to remove.
-
inplace:bool, default=FalseIf True, it removes the region(s) from the current instance.
-
fill_nan:bool, default=FalseIf True, instead of removing the region(s), it sets their value to
NA
Returns:
-
Self–Brain data with
regionsremoved. Ifinplace=Trueit returns the same instance.
set_regions
Assign a new value to the given brain_regions. It checks that each of the given
brain region exists in the given brain_ontology.
Parameters:
-
brain_regions:Collection[str]The acronym of the brain regions to set the value for.
-
brain_ontology:AllenBrainOntologyThe ontology to which the current data was registered against.
-
fill:Number | Collection[Number], default=pd.NAIf a number, it sets the same value for all
brain_regions.
If a collection the same length asbrain_region, it sets each brain region to the respective value infill. -
overwrite:bool, default=FalseIf False, it fails if
brain_regionscontains region acronyms for which a value is already assigned. -
inplace:bool, default=FalseIf True, it sets the regions for the current instance.
Returns:
-
Self–Brain data with
brain_regionsadded. Ifinplace=Trueit returns the same instance.
Raises:
-
ValueError–if
fillis a collection of different length thanbrain_regions. -
UnkownBrainRegionsError–if any of
brain_regionsis missing inbrain_ontology.
missing_regions
missing_regions()
select_from_list
select_from_list(brain_regions, fill_nan=False, inplace=False)
Filters the data from a given list of regions.
Parameters:
-
brain_regions:Sequence[str]The acronyms of the regions to select from the data.
-
fill_nanIf True, the regions missing from the current data are filled with
NA. Otherwise, if the data from some regions are missing, they are ignored. -
inplaceIf True, it applies the filtering to the current instance.
Returns:
-
Self–A brain data filtered accordingly to the given
brain_regions. Ifinplace=Trueit returns the same instance.
select_from_ontology
select_from_ontology(brain_ontology, *args, **kwargs)
Filters the data from a given ontology, accordingly to a non-overlapping list of regions
previously selected in brain_ontology.
It fails if no selection method was called on the ontology.
Parameters:
-
brain_ontology:AllenBrainOntologyThe ontology to which the current data was registered against.
-
*argsOther arguments are passed to
select_from_list. -
**kwargsOther arguments are passed to
select_from_list.
Returns:
-
Self–A brain data filtered accordingly to the given ontology selection.
See also
AllenBrainOntology.get_selected_regions
AllenBrainOntology.unselect_all
AllenBrainOntology.add_to_selection
AllenBrainOntology.select_at_depth
AllenBrainOntology.select_at_structural_level
AllenBrainOntology.select_leaves
AllenBrainOntology.select_summary_structures
AllenBrainOntology.select_regions
AllenBrainOntology.get_regions
SliceMetrics
Bases: Enum
Enum of the metrics used to reduce region data from SlicedBrain
into a AnimalBrain.
Attributes:
-
SUM–Computes the sum of all the sections data from the same region into a single value
-
MEAN–Computes the average \(\mu\) of all the sections data from the same region into a single value
-
STD–Computes the standard deviation \(\sigma\) between all the sections data from the same region into a single value
-
CVAR–Computes the coefficient of variation \(\frac \mu \sigma\) between all the sections data from the same region into a single value
AnimalBrain
AnimalBrain(markers_data, sizes, raw=False)
Associates BrainData coming from a single subject,
for each marker and for each brain region.
Parameters:
-
markers_data:dict[str, BrainData]A dictionary that associates the name of a marker to a
BrainData -
sizes:BrainDataA
BrainDatawith the size of the subject's brain regions. -
raw:bool, default=FalseWhether the data can be considered raw (e.g., contains simple cell positive counts) or not.
sizes
instance-attribute
The data corresponding to the size of each brain region of the current AnimalBrain.
raw
instance-attribute
Whether the data can be considered raw (e.g., contains simple cell positive counts) or not.
markers
property
The name of the markers for which the current AnimalBrain has data.
metric
property
The name of the metric used to compute current data.
Equals to RAW_TYPE if no previous normalization was preformed.
is_split
property
Whether the data of the current AnimalBrain makes a distinction between right and left hemisphere.
name
property
The name of the animal.
regions
property
The list of region acronyms for which the current AnimalBrain has data.
from_slices
staticmethod
from_slices(sliced_brain, metric=SliceMetrics.SUM, min_slices=0, hemisphere_distinction=True, densities=False)
Crates a cohesive AnimalBrain from data coming from brain sections.
Parameters:
-
sliced_brain:SlicedBrainA sectioned brain.
-
metric:SliceMetrics | str, default=SliceMetrics.SUMThe metric used to reduce sections data from the same region into a single value.
-
min_slices:int, default=0The minimum number of sections for a reduction to be valid. If a region has not enough sections, it will disappear from the dataset.
-
hemisphere_distinction:bool, default=Trueif False and
sliced_brainis split between left/right hemispheres, it first merges, for each section, the hemispheric data. -
densities:bool, default=FalseIf True, it computes the reduction on the section density (i.e., marker/area) instead of doing it on the raw cell counts.
Returns:
-
Self–An
AnimalBrain.
Raises:
-
EmptyBrainError–when
sliced_brainhas not enough sections or whenmin_slicesfilters out all brain regions.
__getitem__
__getitem__(marker)
remove_region
remove_region(region, *regions, fill_nan=True)
remove_missing
remove_missing()
Removes the regions for which there is no data about the size.
sort_by_ontology
sort_by_ontology(brain_ontology, fill_nan=False, inplace=False)
Sorts the data in depth-first search order with respect to brain_ontology's hierarchy.
Parameters:
-
brain_ontology:AllenBrainOntologyThe ontology to which the current data was registered against.
-
fill_nan:bool, default=FalseIf True, it sets the value to
NAfor all the regions inbrain_ontologymissing in the currentAnimalBrain. -
inplace:bool, default=FalseIf True, it applies the sorting to the current instance.
Returns:
-
Self–A brain with data sorted accordingly to
brain_ontology. Ifinplace=Trueit returns the same instance.
select_from_list
select_from_list(regions, fill_nan=False, inplace=False)
Filters the data from a given list of regions.
Parameters:
-
regions:Sequence[str]The acronyms of the regions to select from the data.
-
fill_nan:bool, default=FalseIf True, the regions missing from the current data are filled with
NA. Otherwise, if the data from some regions are missing, they are ignored. -
inplace:bool, default=FalseIf True, it applies the filtering to the current instance.
Returns:
-
Self–A brain with data filtered accordingly to the given
regions. Ifinplace=Trueit returns the same instance.
See also
select_from_ontology
select_from_ontology(brain_ontology, fill_nan=False, inplace=False)
Filters the data from a given ontology, accordingly to a non-overlapping list of regions
previously selected in brain_ontology.
It fails if no selection method was called on the ontology.
Parameters:
-
brain_ontology:AllenBrainOntologyThe ontology to which the current data was registered against.
-
fill_nan:bool, default=FalseIf True, the regions missing from the current data are filled with
NA. Otherwise, if the data from some regions are missing, they are ignored. -
inplace:bool, default=FalseIf True, it applies the filtering to the current instance.
Returns:
-
Self–A brain with data filtered accordingly to the given ontology selection. If
inplace=Trueit returns the same instance.
See also
AnimalBrain.select_from_list
AllenBrainOntology.get_selected_regions
AllenBrainOntology.unselect_all
AllenBrainOntology.add_to_selection
AllenBrainOntology.select_at_depth
AllenBrainOntology.select_at_structural_level
AllenBrainOntology.select_leaves
AllenBrainOntology.select_summary_structures
AllenBrainOntology.select_regions
AllenBrainOntology.get_regions
get_units
get_units(marker=None)
merge_hemispheres
merge_hemispheres()
Creates a new AnimalBrain from the current instance with no hemisphere distinction.
Returns:
-
Self–A new
AnimalBrainwith no hemisphere distinction. If it is already merged, it return the same instance with no changes.
See also
to_pandas
to_pandas(units=False, missing_as_nan=False)
Converts the current AnimalBrain to a DataFrame. T
Parameters:
-
units:bool, default=FalseWhether the columns should include the units of measurement or not.
-
missing_as_nan:bool, default=False
Returns:
-
pd.DataFrame–A DataFrame where the rows are the brain regions, the first column is the size of the regions, while the other columns contains the data for each marker. The columns' name is the name of the metric used.
See also
to_csv
to_csv(output_path, sep=',', overwrite=False)
Write the current AnimalBrain to a comma-separated values (CSV) file in output_path.
Parameters:
-
output_path:Path | strAny valid string path is acceptable. It also accepts any os.PathLike.
-
sep:str, default=','Character to treat as the delimiter.
-
overwrite:bool, default=FalseIf True, it overwrite any conflicting file in
output_path.
Returns:
-
str–The file path to the saved CSV file.
Raises:
-
FileExistsError–If
overwrite=Falseand there is a conflicting file inoutput_path.
See also
is_raw
staticmethod
is_raw(metric)
from_pandas
staticmethod
from_pandas(df, animal_name)
from_csv
staticmethod
from_csv(filepath, name, sep=',')
Reads a comma-separated values (CSV) file into AnimalBrain.
Parameters:
-
filepath:Path | strAny valid string path is acceptable. It also accepts any os.PathLike.
-
name:strName of the animal associated to the data.
-
sep:str, default=','Character or regex pattern to treat as the delimiter.
Returns:
-
Self–An instance of
AnimalBrainthat corresponds to the data in the CSV file
See also
AnimalGroup
AnimalGroup(name, animals, hemisphere_distinction=True, brain_ontology=None, fill_nan=True)
Creates an experimental cohort from a set of AnimalBrain.
In order for a cohort to be valid, it must consist of brains with
the same type of data (i.e. metric),
the same markers and
the data must all be hemisphere-aware or not (i.e. AnimalBrain.is_split).
Data for regions missing in one animal but present in others will be always
filled with NA.
Parameters:
-
name:strThe name of the cohort.
-
animals:Sequence[AnimalBrain]The animals part of the group.
-
hemisphere_distinction:bool, default=TrueIf False, it merges, for each region, the data from left/right hemispheres into a single value.
-
brain_ontology:AllenBrainOntology, default=NoneThe ontology to which the brains' data was registered against. If specified, it sorts the data in depth-first search order with respect to
brain_ontology's hierarchy. -
fill_nan:bool, default=TrueIf True, it sets the value to
NAfor all the regions missing from the data but present inbrain_ontology.
See also
AnimalBrain.merge_hemispheres
BrainData.merge_hemispheres
AnimalBrain.sort_by_ontology
BrainData.sort_by_ontology
AnimalBrain.select_from_list
AnimalBrain.select_from_ontology
name
instance-attribute
The name of the group.
n
property
The size of the group.
metric
property
The metric used to compute the brains' data.
is_split
property
Whether the data of the current AnimalGroup makes a distinction between right and left hemisphere.
markers
property
The name of the markers for which the current AnimalGroup has data.
regions
property
The list of region acronyms for which the current AnimalGroup has data.
animals
property
The brains making up the current group.
mean
property
The mean between each brain of the group, for each region.
reduce
reduce(op, **kwargs)
is_comparable
is_comparable(other)
Tests whether two AnimalGroup are comparable for an analysis,
i.e. they have the same markers, the same metric and both either operate on brains
hemisphere-aware or not.
Parameters:
-
other:SelfThe other group to compare with the current one.
Returns:
-
bool–True if the current group and
otherare comparable. False otherwise.
select
select(regions, fill_nan=False, inplace=False)
Filters the data from a given list of regions.
Parameters:
-
regions:Sequence[str]The acronyms of the regions to select from the data.
-
fill_nanIf True, the regions missing from the current data are filled with
NA. Otherwise, if the data from some regions are missing, they are ignored. -
inplaceIf True, it applies the filtering to the current instance.
Returns:
-
Self–A group with data filtered accordingly to the given
regions. Ifinplace=Trueit returns the same instance.
See also
__getitem__
__getitem__(animal_name)
Parameters:
-
animal_name:strThe name of an animal part of the group
Returns:
-
AnimalBrain–The corresponding
AnimalBrainin the current group.
Raises:
apply
apply(f, hemisphere_distinction=True, brain_ontology=None, fill_nan=False)
Applies a function to each animal of the group and creates a new AnimalGroup.
Especially useful when applying some sort of metric to the brain data.
Parameters:
-
f:Callable[[AnimalBrain], AnimalBrain]A function that maps an
AnimalBraininto anotherAnimalBrain. -
brain_ontology:AllenBrainOntology, default=NoneThe ontology to which the brains' data was registered against.
If specified, it sorts the data in depth-first search order with respect to brain_ontology's hierarchy. -
fill_nan:bool, default=FalseIf True, it sets the value to
NAfor all the regions missing from the data but present inbrain_ontology.
Returns:
-
Self–A group with the data of each animal changed accordingly to
f.
get_units
get_units(marker=None)
sort_by_ontology
sort_by_ontology(brain_ontology, fill_nan=True, inplace=True)
Sorts the data in depth-first search order with respect to brain_ontology's hierarchy.
Parameters:
-
brain_ontology:AllenBrainOntologyThe ontology to which the current data was registered against.
-
fill_nanIf True, it sets the value to
NAfor all the regions inbrain_ontologymissing in the currentAnimalBrain. -
inplaceIf True, it applies the sorting to the current instance.
Returns:
-
None–A brain with data sorted accordingly to
brain_ontology. Ifinplace=Trueit returns the same instance.
merge_hemispheres
merge_hemispheres(inplace=False)
Creates a new AnimalGroup from the current instance with no hemisphere distinction.
Parameters:
-
inplaceIf True, it applies the sorting to the current instance.
Returns:
-
Self–A new
AnimalGroupwith no hemisphere distinction. Ifinplace=Trueit modifies and returns the same instance.
to_pandas
to_pandas(marker=None, units=False, missing_as_nan=False)
Constructs a DataFrame with data from the current group.
Parameters:
-
marker:str, default=NoneIf specified, it includes data only from the given marker.
-
units:bool, default=FalseWhether to include the units of measurement in the
DataFrameindex. -
missing_as_nan:bool, default=False
Returns:
-
pd.DataFrame–A \(m×n\)
DataFrame.
Ifmarkeris specified, \(m=\#regions\) and \(n=\#brains\).
Otherwise, \(m=\#regions⋅\#brains\) and \(n=\#markers+1\), as it contains the size of the regions as well. In the latter case, the index of theDataFramehas two levels: the acronyms of the regions and the name of the animal in the group.If a region is missing in some animals, the corresponding row is
NA-filled.
to_csv
to_csv(output_path, sep=',', overwrite=False)
Write the current AnimalGroup to a comma-separated values (CSV) file in output_path.
Parameters:
-
output_path:Path | strAny valid string path is acceptable. It also accepts any os.PathLike.
-
sep:str, default=','Character to treat as the delimiter.
-
overwrite:bool, default=FalseIf True, it overwrite any conflicting file in
output_path.
Returns:
-
str–The file path to the saved CSV file.
Raises:
-
FileExistsError–If
overwrite=Falseand there is a conflicting file inoutput_path.
See also
from_pandas
staticmethod
from_pandas(df, group_name)
from_csv
staticmethod
from_csv(filepath, name, sep=',')
Reads a comma-separated values (CSV) file into AnimalGroup.
Parameters:
-
filepath:Path | strAny valid string path is acceptable. It also accepts any os.PathLike.
-
name:strName of the group associated to the data.
-
sep:str, default=','Character or regex pattern to treat as the delimiter.
Returns:
-
Self–An instance of
AnimalGroupthat corresponds to the data in the CSV file
See also
to_prism
staticmethod
to_prism(marker, brain_ontology, group1, group2, *groups)
Prepares the marker data from multiple groups in a table structure that is convenient to analyse with statistical applications such as Prism by GraphPad, JASP or OriginPro.
Parameters:
-
markerThe marker used to compare all groups.
-
brain_ontology:AllenBrainOntologyThe ontology to which the groups' data was registered against.
-
group1:SelfThe first group to include in the export.
-
group2:SelfThe second group to include in the export.
-
*groups:Self, default=()Any other number of groups to include in the export.
Returns:
Raises:
-
ValueError–If the given groups are not comparable.
SlicedGroup
SlicedGroup(name, animals, brain_ontology)
Creates an experimental cohort from a set of SlicedBrain.
It is meant to help keeping organised raw data coming multiple sections per-animal.
Parameters:
-
name:strThe name of the cohort.
-
animals:Iterable[SlicedBrain]The animals part of the group.
-
brain_ontology:AllenBrainOntologyThe ontology to which the brains' data was registered against.
name
property
The name of the sliced group.
animals
property
The brains making up the current sliced group.
n
property
The size of the sliced group.
from_qupath
staticmethod
from_qupath(name, brain_names, qupath_dir, brain_ontology, ch2marker, exclude_parents, results_subdir='results', results_suffix='_regions.tsv', exclusions_subdir='regions_to_exclude', exclusions_suffix='_regions_to_exclude.txt')
Creates an experimental cohort from the section files exported with QuPath.
Parameters:
-
name:strThe name of the cohort.
-
brain_names:Iterable[str]The names of the animals part of the group.
-
qupath_dir:Path | strThe path to where all the reports of the brains' sections were saved from QuPath.
-
brain_ontology:AllenBrainOntologyAn ontology against whose version the brains were aligned.
-
ch2marker:dict[str, str]A dictionary mapping QuPath channel names to markers.
-
exclude_parents:boolexclude_parent_regionsfromBrainSlice.exclude_regions. -
results_subdir:str, default='results'The name of the subfolder in
qupath_dir/brain_namethat contains all cell counts files of each brain section.
It can beNoneif no subfolder is used. -
results_suffix:str, default='_regions.tsv'The suffix used to identify cell counts files saved in
results_subdir. It includes the file extension. -
exclusions_subdir:str, default='regions_to_exclude'The name of the subfolder in
qupath_dir/brain_namethat contains all regions to exclude from further analysis of each brain section.
It can beNoneif no subfolder is used. -
exclusions_suffix:str, default='_regions_to_exclude.txt'The suffix used to identify exclusion files saved in
results_subdir. It includes the file extension.
Returns:
-
Self–A group made of sliced brain data.
See also
get_animals
get_animals()
to_group
to_group(metric, min_slices, densities, hemisphere_distinction, validate)
Aggrecates the data from all sections of each SlicedBrain
into AnimalBrain and organises them into the corresponding
AnimalGroup.
Parameters:
-
metric:SliceMetricsThe metric used to reduce sections data from the same region into a single value.
-
min_slices:intThe minimum number of sections for a reduction to be valid. If a region has not enough sections, it will disappear from the dataset.
-
densities:boolIf True, it computes the reduction on the section density (i.e., marker/area) instead of doing it on the raw cell counts.
-
hemisphere_distinction:boolIf False, it merges, for each region, the data from left/right hemispheres into a single value.
-
validate:boolIf True, it validates each region in each brain, checking that they are present in the brain region ontology against which the brains were alligned.
Returns:
-
AnimalGroup–A group with the values from sections of the same animals aggregated.
See also
Experiment
Experiment(name, group1, group2, *groups)
Creates an experiment from the data of two or more AnimalGroups.
Parameters:
-
name:strThe name of the experiment.
-
group1:AnimalGroupThe first group of the experiment.
-
group2:AnimalGroupThe second group of the experiment.
-
*groups:AnimalGroup, default=()Any other group of the experiment.
name
property
The name of the experiment.
groups
property
The groups making up the current experiment.
__getattr__
__getattr__(name)
Get a specific group in the current experiment by accessing it with an attribute named like the name of the group.
Parameters:
-
name:strThe name of the group
Returns:
-
AnimalGroup–The group in the experiment having the same name as
name.
Raises:
-
AttributeError–If no group with
namewas found in the current experiment.
apply
apply(f, hemisphere_distinction=True, brain_ontology=None, fill_nan=False)
Applies a function to each animal of the groups of the experiment and creates a new Experiment.
Especially useful when applying some sort of metric to the brain data.
Parameters:
-
f:Callable[[AnimalBrain], AnimalBrain]A function that maps an
AnimalBraininto anotherAnimalBrain. -
brain_ontology:AllenBrainOntology, default=NoneThe ontology to which the brains' data was registered against.
If specified, it sorts the data in depth-first search order with respect to brain_ontology's hierarchy. -
fill_nan:bool, default=FalseIf True, it sets the value to
NAfor all the regions missing from the data but present inbrain_ontology.
Returns:
-
Self–An experiment with the data of each animal changed accordingly to
f.
SlicedExperiment
SlicedExperiment(name, group1, group2, *groups)
Creates an experiment from the data of two or more SlicedGroups.
Parameters:
-
name:strThe name of the sliced experiment.
-
group1:SlicedGroupThe first group of the sliced experiment.
-
group2:SlicedGroupThe second group of the sliced experiment.
-
*groups:Iterable[SlicedGroup], default=()Any other group of the sliced experiment.
name
property
The name of the sliced experiment.
groups
property
The groups making up the current sliced experiment.
__getattr__
__getattr__(name)
Get a specific group in the current sliced experiment by accessing it with an attribute named like the name of the group.
Parameters:
-
name:strThe name of the group
Returns:
-
Any–The group in the sliced experiment having the same name as
name.
Raises:
-
AttributeError–If no group with
namewas found in the current sliced experiment.
to_experiment
to_experiment(metric, min_slices, densities, hemisphere_distinction, validate)
Aggrecates the data from all sections of each SlicedBrain
into SlicedGroup and organises them into the corresponding
Experiment.
Parameters:
-
metric:SliceMetricsThe metric used to reduce sections data from the same region into a single value.
-
min_slices:intThe minimum number of sections for a reduction to be valid. If a region has not enough sections, it will disappear from the dataset.
-
densities:boolIf True, it computes the reduction on the section density (i.e., marker/area) instead of doing it on the raw cell counts.
-
hemisphere_distinction:boolIf False, it merges, for each region, the data from left/right hemispheres into a single value.
-
validate:boolIf True, it validates each region in each brain, checking that they are present in the brain region ontology against which the brains were alligned.
Returns:
-
Experiment–An experiment with the values from sections of the same animals aggregated.
See also
__contains__
__contains__(animal_name)
__getitem__
__getitem__(animal_name)
Parameters:
-
animal_name:strThe name of an animal part of the experiment.
Returns:
-
SlicedBrain–The corresponding
AnimalBrainin the current experiment.
Raises: