braian
AllenBrainOntology
AllenBrainOntology(path_to_allen_json, blacklisted_acronyms=[], 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:
-
path_to_allen_json
:str
The path to an Allen structural graph json
-
blacklisted_acronyms
:Iterable
, default=[]
Acronyms of branches from the onthology to exclude completely from the analysis
-
version
:str | None
, default=None
Must 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 | str
A 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
r
exists 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
:Iterable
Regions to blacklist
-
key
:str
, default='acronym'
The key in Allen's structural graph used to identify the
regions
to blacklist -
has_reference
:bool
, default=True
If
regions
exist in the used version of the CCF or not
Raises:
-
ValueError
–If it can't find at least one of the
regions
in 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
:int
The 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
:int
The 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
:Iterable
The 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
regions
in 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
:str
Must be "summary structure", "major divisions", "leaves", "depth
" or "structural level "
Returns:
Raises:
-
ValueError
–If
selection_method
is 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'
Must be eithe "breadth" or "depth". The order in which the returned acronyms will be: breadth-first or depth-first
Returns:
Raises:
-
ValueError
–If given
mode
is not supported -
ValueError
–If it can't find at least one of the
ids
in the ontology
acronym_to_ids
acronym_to_ids(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'
Must be eithe "breadth" or "depth". The order in which the returned acronyms will be: breadth-first or depth-first
Returns:
Raises:
-
ValueError
–If given
mode
is not supported -
ValueError
–If it can't find at least one of the
ids
in 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 | int
A 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
:Iterable
The 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
:str
The 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
mode
is not supported -
ValueError
–If it can't find
acronym
in 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
:str
Acronym 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
acronym
in the ontology.
get_layer1
get_layer1()
get_region_colors
get_region_colors()
BrainSlice
BrainSlice(data, animal, name, is_split, area_units='µm2', brain_ontology=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 in area_units
, and the others corresponding to the markers used to
measure brain activity.
Parameters:
-
data
:pd.DataFrame
The data extracted from a brain slice.
-
animal
:str
The name of the animal from which the slice was cut.
-
name
:str
The name of hte brain slice.
-
is_split
:bool
Whether the data was extracted distinguishing between the two hemispheres or not.
-
area_units
:str
, default='µm2'
The units of measurements used by
"area"
column indata
. Accepted values are:"µm2"
,"um2"
ormm2
. -
brain_ontology
:AllenBrainOntology | None
, default=None
If specified, it checks the brain regions in
data
against the given ontology and it sorts the rows in depth-first order in ontology's hierarchy.
Raises:
-
InvalidRegionsHemisphereError
–If
is_split=True
but some rows' indices don't start with"Left: "
or with"Right: "
. -
ValueError
–If the specified
area_units
is 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.
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_file, ch2marker, *args, **kwargs)
Creates a BrainSlice
from a file exported with
qupath-extension-braian
.
Additional arguments are passed to BrainSlice
's constructor.
Parameters:
-
csv_file
:str | Path
The 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. -
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.
-
*args
Other arguments are passed to
BrainSlice
constructor. -
**kwargs
Other keyword arguments are passed to
BrainSlice
constructor.
Returns:
-
Self
–
Raises:
-
EmptyResultsError
–If the given
csv_file
is empty -
InvalidResultsError
–If the given
csv_file
is 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
csv_file
is 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 | str
The path to file exported with
AtlasManager.saveExcludedRegions()
.
Returns:
Raises:
-
ExcludedRegionsNotFoundError
–If the
file_path
was 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
:AllenBrainOntology
an ontology against whose version the brain section was aligned.
-
exclude_parent_regions
:bool
Whether the cell counts of the parent regions are excluded or subtracted.
Raises:
-
InvalidExcludedRegionsHemisphereError
–if
BrainSlice.is_split
but a region inexcluded_regions
is not considering left/right hemisphere distinction. -
UnkownBrainRegionsError
–if a region in
excluded_regions
is not recognised frombrain_ontology
. -
ExcludedAllRegionsError
–if there is no cell count left after the exclusion is done.
merge_hemispheres
staticmethod
merge_hemispheres(slice)
For each brain region, sums the data of left and right hemispheres into one single datum
Parameters:
-
slice
:Self
A brain section to merge
Returns:
-
Self
–A new
BrainSlice
with no hemisphere distinction. Ifslice
is 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
:str
The name of the animal.
-
slices
:Iterable[BrainSlice]
The list of
BrainSlice
that makes up a sample of a brain. -
markers
:Iterable[str]
The list of markers in used in all
BrainSlice
s.
Raises:
-
EmptyBrainError
–If
slices
is 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
:str
The name of the animal.
-
animal_dir
:str | Path
The path to where all the reports of the brain sections were saved from QuPath. Both per-region results and exclusions.
-
brain_ontology
:AllenBrainOntology
An 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=False
exclude_parent_regions
fromBrainSlice.exclude_regions
. -
results_subdir
:str
, default='results'
The name of the subfolder in
animal_dir
that contains all cell counts files of each brain section.
It can beNone
if 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_dir
that contains all regions to exclude from further analysis of each brain section.
It can beNone
if 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=False
If True, the result is a
DataFrame
of slices marker densities. Otherwise, the result will contain the cell counts.
Returns:
-
pd.DataFrame
–A
DataFrame
of 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=None
If specified, it sorts and check the regions accordingly to the given atlas ontology.
Returns:
-
BrainData
–A
BrainData
with the number of slices per region.
merge_hemispheres
staticmethod
merge_hemispheres(sliced_brain)
Creates a new SlicedBrain
from all merged BrainSlice
in sliced_brain
.
Parameters:
-
sliced_brain
:Self
A sliced brain to merge.
Returns:
-
Self
–A new
SlicedBrain
with no hemisphere distinction. Ifsliced_brain
is 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.Series
A pandas Series associating brain region acronyms (i.e. the index) to brain data (i.e. the values).
-
name
:str
A name identifying
data
. -
metric
:str
The metric used to extract
data
. If they no metric was previosuly used, useRAW_TYPE
. -
units
:str
The units of measurment of the values in
data
. -
brain_ontology
:AllenBrainOntology | None
, default=None
The ontology against which the extracted data was aligned. It is used to check that all
data
is attributable to a region in the ontology and to sort it accordingly.
If left empty, no check or sorting is performed. -
fill_nan
If ontology is not
None
, it fills withNA
the value of the regions inontology
and 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
:Self
The first data to reduce.
-
*others
:Self
, default=()
Any number of additional brain data to reduce.
-
op
:Callable[[pd.DataFrame], pd.Series]
, default=pd.DataFrame.mean
A function that maps a
DataFrame
into aSeries
. It must include anaxis
parameter. -
name
The name of the resulting BrainData.
If not specified, it builds a name joining all given data names. -
op_name
The name of the reduction function. If not specified, it uses
op
name. -
same_units
Whether it should enforce the same units of measurement for all
BrainData
. -
**kwargs
Other keyword arguments are passed to
op
.
Returns:
-
Self
–A new
BrainData
result 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
BrainData
to average. -
**kwargs
Other 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
BrainData
to search the minimum from. -
**kwargs
Other 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
BrainData
to search the maximum from. -
**kwargs
Other 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
:AllenBrainOntology
The ontology to which the current data was registered against.
-
fill_nan
If True, it sets the value to
NaN
for all the regions inbrain_ontology
missing in the currentAnimalBrain
. -
inplace
If True, it applies the sorting to the current instance.
Returns:
-
Self
–Brain data sorted accordingly to
brain_ontology
. Ifinplace=True
it returns the same instance.
root
root(hemisphere=None)
Retrieves the value associated to the whole brain.
Parameters:
-
hemisphere
:str
, default=None
Anything between "left", "L", "right" and "R".
If the currentBrainData
is 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
hemisphere
was not specified but the currentBrainData
is 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
:str
Acronyms of the brain regions to remove.
-
*regions
:str
Acronyms of the brain regions to remove.
-
inplace
:bool
, default=False
If True, it removes the region(s) from the current instance.
-
fill_nan
:bool
, default=False
If True, instead of removing the region(s), it sets their value to
NA
Returns:
-
Self
–Brain data with
regions
removed. Ifinplace=True
it 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
:AllenBrainOntology
The ontology to which the current data was registered against.
-
fill
:Number | Collection[Number]
, default=pd.NA
If 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=False
If False, it fails if
brain_regions
contains region acronyms for which a value is already assigned. -
inplace
:bool
, default=False
If True, it sets the regions for the current instance.
Returns:
-
Self
–Brain data with
brain_regions
added. Ifinplace=True
it returns the same instance.
Raises:
-
ValueError
–if
fill
is a collection of different length thanbrain_regions
. -
UnkownBrainRegionsError
–if any of
brain_regions
is 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_nan
If 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
If True, it applies the filtering to the current instance.
Returns:
-
Self
–A brain data filtered accordingly to the given
brain_regions
. Ifinplace=True
it 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
:AllenBrainOntology
The ontology to which the current data was registered against.
-
*args
Other arguments are passed to
select_from_list
. -
**kwargs
Other 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
:BrainData
A
BrainData
with the size of the subject's brain regions. -
raw
:bool
, default=False
Whether the data can be considered raw (e.g., contains simple cell positive counts) or not.
markers
instance-attribute
The name of the markers for which the current AnimalBrain
has data.
markers_data
instance-attribute
The whole-brain data for each marker.
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.
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
:SlicedBrain
A sectioned brain.
-
metric
:SliceMetrics | str
, default=SliceMetrics.SUM
The metric used to reduce sections data from the same region into a single value.
-
min_slices
:int
, default=0
The 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=True
if False and
sliced_brain
is split between left/right hemispheres, it first merges, for each section, the hemispheric data. -
densities
:bool
, default=False
If 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_brain
has not enough sections or whenmin_slices
filters out all brain regions.
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
:AllenBrainOntology
The ontology to which the current data was registered against.
-
fill_nan
:bool
, default=False
If True, it sets the value to
NA
for all the regions inbrain_ontology
missing in the currentAnimalBrain
. -
inplace
:bool
, default=False
If True, it applies the sorting to the current instance.
Returns:
-
Self
–A brain with data sorted accordingly to
brain_ontology
. Ifinplace=True
it 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=False
If 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=False
If True, it applies the filtering to the current instance.
Returns:
-
Self
–A brain with data filtered accordingly to the given
regions
. Ifinplace=True
it 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
:AllenBrainOntology
The ontology to which the current data was registered against.
-
fill_nan
:bool
, default=False
If 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=False
If True, it applies the filtering to the current instance.
Returns:
-
Self
–A brain with data filtered accordingly to the given ontology selection. If
inplace=True
it 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.
Parameters:
-
inplace
If True, it applies the sorting to the current instance.
Returns:
-
Self
–A new
AnimalBrain
with no hemisphere distinction. If it is already merged, it return the same instance with no changes.
See also
to_pandas
to_pandas(units=False)
Converts the current AnimalBrain
to a DataFrame. T
Parameters:
-
units
:bool
, default=False
Whether the columns should include the units of measurement or not.
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 | str
Any valid string path is acceptable. It also accepts any os.PathLike.
-
sep
:str
, default=','
Character to treat as the delimiter.
-
overwrite
:bool
, default=False
If True, it overwrite any conflicting file in
output_path
.
Returns:
-
str
–The file path to the saved CSV file.
Raises:
-
FileExistsError
–If
overwrite=False
and 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 | str
Any valid string path is acceptable. It also accepts any os.PathLike.
-
name
:str
Name of the animal associated to the data.
-
sep
:str
, default=','
Character or regex pattern to treat as the delimiter.
Returns:
-
Self
–An instance of
AnimalBrain
that 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
:str
The name of the cohort.
-
animals
:Sequence[AnimalBrain]
The animals part of the group.
-
hemisphere_distinction
:bool
, default=True
If False, it merges, for each region, the data from left/right hemispheres into a single value.
-
brain_ontology
:AllenBrainOntology
, default=None
The 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=True
If True, it sets the value to
NA
for 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
:Self
The other group to compare with the current one.
Returns:
-
bool
–True if the current group and
other
are 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_nan
If 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
If True, it applies the filtering to the current instance.
Returns:
-
Self
–A group with data filtered accordingly to the given
regions
. Ifinplace=True
it returns the same instance.
See also
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
AnimalBrain
into anotherAnimalBrain
. -
brain_ontology
:AllenBrainOntology
, default=None
The 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=False
If True, it sets the value to
NA
for 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
:AllenBrainOntology
The ontology to which the current data was registered against.
-
fill_nan
If True, it sets the value to
NA
for all the regions inbrain_ontology
missing in the currentAnimalBrain
. -
inplace
If True, it applies the sorting to the current instance.
Returns:
-
None
–A brain with data sorted accordingly to
brain_ontology
. Ifinplace=True
it returns the same instance.
merge_hemispheres
merge_hemispheres(inplace=False)
Creates a new AnimalGroup
from the current instance with no hemisphere distinction.
Parameters:
-
inplace
If True, it applies the sorting to the current instance.
Returns:
-
Self
–A new
AnimalGroup
with no hemisphere distinction. Ifinplace=True
it modifies and returns the same instance.
to_pandas
to_pandas(marker=None, units=False)
Constructs a DataFrame
with data from the current group.
Parameters:
-
marker
:str
, default=None
If specified, it includes data only from the given marker.
-
units
:bool
, default=False
Whether to include the units of measurement in the
DataFrame
index.
Returns:
-
pd.DataFrame
–A \(m×n\)
DataFrame
.
Ifmarker
is 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 theDataFrame
has 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 | str
Any valid string path is acceptable. It also accepts any os.PathLike.
-
sep
:str
, default=','
Character to treat as the delimiter.
-
overwrite
:bool
, default=False
If True, it overwrite any conflicting file in
output_path
.
Returns:
-
str
–The file path to the saved CSV file.
Raises:
-
FileExistsError
–If
overwrite=False
and 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 | str
Any valid string path is acceptable. It also accepts any os.PathLike.
-
name
:str
Name of the group associated to the data.
-
sep
:str
, default=','
Character or regex pattern to treat as the delimiter.
Returns:
-
Self
–An instance of
AnimalGroup
that 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:
-
marker
The marker used to compare all groups.
-
brain_ontology
:AllenBrainOntology
The ontology to which the groups' data was registered against.
-
group1
:Self
The first group to include in the export.
-
group2
:Self
The 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
:str
The name of the cohort.
-
animals
:Iterable[SlicedBrain]
The animals part of the group.
-
brain_ontology
:AllenBrainOntology
The 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
:str
The name of the cohort.
-
brain_names
:Iterable[str]
The names of the animals part of the group.
-
qupath_dir
:Path | str
The path to where all the reports of the brains' sections were saved from QuPath.
-
brain_ontology
:AllenBrainOntology
An ontology against whose version the brains were aligned.
-
ch2marker
:dict[str, str]
A dictionary mapping QuPath channel names to markers.
-
exclude_parents
:bool
exclude_parent_regions
fromBrainSlice.exclude_regions
. -
results_subdir
:str
, default='results'
The name of the subfolder in
qupath_dir/brain_name
that contains all cell counts files of each brain section.
It can beNone
if 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_name
that contains all regions to exclude from further analysis of each brain section.
It can beNone
if 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
:SliceMetrics
The metric used to reduce sections data from the same region into a single value.
-
min_slices
:int
The minimum number of sections for a reduction to be valid. If a region has not enough sections, it will disappear from the dataset.
-
densities
:bool
If True, it computes the reduction on the section density (i.e., marker/area) instead of doing it on the raw cell counts.
-
hemisphere_distinction
:bool
If False, it merges, for each region, the data from left/right hemispheres into a single value.
-
validate
:bool
If 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
:str
The name of the experiment.
-
group1
:AnimalGroup
The first group of the experiment.
-
group2
:AnimalGroup
The 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.
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
AnimalBrain
into anotherAnimalBrain
. -
brain_ontology
:AllenBrainOntology
, default=None
The 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=False
If True, it sets the value to
NA
for 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
:str
The name of the sliced experiment.
-
group1
:SlicedGroup
The first group of the sliced experiment.
-
group2
:SlicedGroup
The 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.
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
:SliceMetrics
The metric used to reduce sections data from the same region into a single value.
-
min_slices
:int
The minimum number of sections for a reduction to be valid. If a region has not enough sections, it will disappear from the dataset.
-
densities
:bool
If True, it computes the reduction on the section density (i.e., marker/area) instead of doing it on the raw cell counts.
-
hemisphere_distinction
:bool
If False, it merges, for each region, the data from left/right hemispheres into a single value.
-
validate
:bool
If 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.