Пример #1
0
 def prepare_input(self, input_dir, connectivity_dir, structure_map_dir,
                   **kwargs):
     mcc = MouseConnectivityCache(
         manifest_file=f'{connectivity_dir}/mouse_connectivity_manifest.json'
     )
     mcc.get_structure_tree()
     experiments = os.listdir(structure_map_dir)
     try:
         os.makedirs(input_dir)
         for e in experiments:
             os.makedirs(f'{input_dir}/{e}')
     except FileExistsError:
         pass
Пример #2
0
class StructureTree(ipytree.Tree):
    def __init__(self, ids, multiple_selection):
        self.ids = ids
        self.mcc = MouseConnectivityCache(
            manifest_file=
            f'../mouse_connectivity/mouse_connectivity_manifest.json',
            resolution=25)
        self.structure_tree = self.mcc.get_structure_tree()
        node = self.fill_node('grey')
        while len(node.nodes) < 2:
            node = node.nodes[0]
        super().__init__(nodes=[node], multiple_selection=multiple_selection)

    def fill_node(self, start_node):
        start_struct = self.structure_tree.get_structures_by_acronym(
            [start_node])[0]
        children = [
            self.fill_node(c['acronym']) for c in self.structure_tree.children(
                [self.structure_tree.get_id_acronym_map()[start_node]])[0]
        ]
        children = [c for c in children if c is not None]

        if not children and start_struct['acronym'] not in self.ids:
            return None

        node = StructureTreeNode(start_struct['acronym'],
                                 start_struct['acronym'], children)
        if start_struct['acronym'] not in self.ids:
            node.disabled = True

        return node
Пример #3
0
 def __init__(self, experiment_id, directory, structdata_dir, connectivity_dir, logger):
     self.logger = logger
     self.structdata_dir = structdata_dir
     self.directory = directory
     self.experiment_id = experiment_id
     mcc = MouseConnectivityCache(manifest_file=f'{connectivity_dir}/mouse_connectivity_manifest.json')
     tree = mcc.get_structure_tree()
     self.structures = [f'Field CA{i}' for i in range(1, 4)]
     self.pyramidal_layers = {s: self.get_pyramidal_layer(tree, s) for s in self.structures}
Пример #4
0
 def get_anatomical_info(self):
     
     manifest_path = './connectivity/mouse_connectivity_manifest.json'
     mcc = MouseConnectivityCache(resolution=self.resolution, manifest_file=manifest_path)
     tree = mcc.get_structure_tree()
     annotation, _ = mcc.get_annotation_volume()
         
     self.areas_in_blob = list(set([tree.get_structures_by_id([i])[0]['acronym'] for i in annotation[np.where(self.mask>0)] if i>0]))
     
     self.cuboid_center_areas = [tree.get_structures_by_id([i])[0]['acronym'] for i in annotation[tuple(self.cuboid_points.T)] if i>0]
def main():
    # Find the path to an existing ontology document that was installed through the Brain Explorer interface
    path = r'C:\Users\jenniferwh\AppData\Local\Allen Institute\Brain Explorer 2\Atlases\Allen Mouse Brain Common Coordinate Framework'
    dat = pd.read_csv(os.path.join(path, 'ontology_v2.csv'))

    mcc = MouseConnectivityCache(
        manifest_file='/connectivity/mouse_connectivity_manifest.json')
    st = mcc.get_structure_tree()
    ia_map = st.get_id_acronym_map()

    jsonfile = r'/Users/jenniferwh/Dropbox (Allen Institute)/Diamond_collaboration/data_files/consensus_structures.json'
    with open(jsonfile, 'r') as file:
        consensus_structures = json.load(file)
    age = str(args.age) + 'monthTG'
    print(age)

    tau_structures = consensus_structures[age]
    tau_structure_ids = [ia_map[structure] for structure in tau_structures]
    '''
    for structure in thal_structure_ids:
        if structure not in ss:
            children = st.descendant_ids([structure])[0]
            child_ss = [structure_id for structure_id in children if structure_id in ss]
            ss += [structure]
            thal_structure_ids+=child_ss
    '''
    colormap = cm.Reds
    all_structures = dat['abbreviation'].unique()
    all_structures = [
        structure for structure in all_structures
        if structure in ia_map.keys()
    ]
    all_structures.remove('root')
    all_structure_ids = [ia_map[structure] for structure in all_structures]
    structure_vals = dict()
    for structure in all_structure_ids:
        if structure in tau_structure_ids:
            structure_vals[structure] = 0.9
        else:
            structure_vals[structure] = 0
    rgb_vals = structure_vals.copy()
    for key in all_structure_ids:
        rgb_vals[key] = tuple(
            [255 * i for i in colormap(structure_vals[key])[:3]])
        dat.loc[dat['database_id'] == key, 'red'] = int(rgb_vals[key][0])
        dat.loc[dat['database_id'] == key, 'green'] = int(rgb_vals[key][1])
        dat.loc[dat['database_id'] == key, 'blue'] = int(rgb_vals[key][2])
    rgb_vals[0] = (0, 0, 0)
    dat.loc[dat['abbreviation'] == 'root', 'parent'] = 0.
    dat['parent'] = [int(value) for value in dat['parent']]

    dat.to_csv(os.path.join(path, 'ontology_v2.csv'), index=False)
Пример #6
0
class ABA:
    """
        This class augments the functionality of
        BrainGlobeAtlas with methods specific to the Allen
        Mouse Brain atlas and necessary to populate scenes in 
        brainrender. These include stuff like fetching streamlines
        and neuronal morphology data. 
    """

    atlas_name = "ABA"
    resolution = 25

    excluded_regions = ["fiber tracts"]

    # Used for streamlines
    base_url = "https://neuroinformatics.nl/HBP/allen-connectivity-viewer/json/streamlines_NNN.json.gz"

    def __init__(self):
        # get mouse connectivity cache and structure tree
        self.mcc = MouseConnectivityCache(manifest_file=os.path.join(
            self.mouse_connectivity_cache, "manifest.json"))
        self.structure_tree = self.mcc.get_structure_tree()

        # get ontologies API and brain structures sets
        self.oapi = OntologiesApi()

        # get reference space
        self.space = ReferenceSpaceApi()
        self.spacecache = ReferenceSpaceCache(
            manifest=os.path.join(
                self.annotated_volume_fld, "manifest.json"
            ),  # downloaded files are stored relative to here
            resolution=int(self.resolution[0]),
            reference_space_key=
            "annotation/ccf_2017",  # use the latest version of the CCF
        )
        self.annotated_volume, _ = self.spacecache.get_annotation_volume()

        # mouse connectivity API [used for tractography]
        self.mca = MouseConnectivityApi()

        # Get tree search api
        self.tree_search = TreeSearchApi()

    # ------------------------- Scene population methods ------------------------- #
    def get_neurons(
        self,
        neurons,
        color=None,
        display_axon=True,
        display_dendrites=True,
        alpha=1,
        neurite_radius=None,
        soma_radius=None,
        use_cache=True,
    ):
        """
        Gets rendered morphological data of neurons reconstructions downloaded from the
        Mouse Light project at Janelia (or other sources). 
        Accepts neurons argument as:
            - file(s) with morphological data
            - vedo mesh actor(s) of entire neurons reconstructions
            - dictionary or list of dictionary with actors for different neuron parts

        :param neurons: str, list, dict. File(s) with neurons data or list of rendered neurons.
        :param display_axon, display_dendrites: if set to False the corresponding neurite is not rendered
        :param color: default None. Can be:
                - None: each neuron is given a random color
                - color: rbg, hex etc. If a single color is passed all neurons will have that color
                - cmap: str with name of a colormap: neurons are colored based on their sequential order and cmap
                - dict: a dictionary specifying a color for soma, dendrites and axon actors, will be the same for all neurons
                - list: a list of length = number of neurons with either a single color for each neuron
                        or a dictionary of colors for each neuron
        :param alpha: float in range 0,1. Neurons transparency
        :param neurite_radius: float > 0 , radius of tube actor representing neurites
        :param use_cache: bool, if True a cache is used to avoid having to crate a neuron's mesh anew, otherwise a new mesh is created
        """

        if not isinstance(neurons, (list, tuple)):
            neurons = [neurons]

        # ---------------------------------- Render ---------------------------------- #
        _neurons_actors = []
        for neuron in neurons:
            neuron_actors = {"soma": None, "dendrites": None, "axon": None}

            # Deal with neuron as filepath
            if isinstance(neuron, str):
                if os.path.isfile(neuron):
                    if neuron.endswith(".swc"):
                        neuron_actors, _ = get_neuron_actors_with_morphapi(
                            swcfile=neuron,
                            neurite_radius=neurite_radius,
                            soma_radius=soma_radius,
                            use_cache=use_cache,
                        )
                    else:
                        raise NotImplementedError(
                            "Currently we can only parse morphological reconstructions from swc files"
                        )
                else:
                    raise ValueError(
                        f"Passed neruon {neuron} is not a valid input. Maybe the file doesn't exist?"
                    )

            # Deal with neuron as single actor
            elif isinstance(neuron, Mesh):
                # A single actor was passed, maybe it's the entire neuron
                neuron_actors["soma"] = neuron  # store it as soma
                pass

            # Deal with neuron as dictionary of actor
            elif isinstance(neuron, dict):
                neuron_actors["soma"] = neuron.pop("soma", None)
                neuron_actors["axon"] = neuron.pop("axon", None)

                # Get dendrites actors
                if ("apical_dendrites" in neuron.keys()
                        or "basal_dendrites" in neuron.keys()):
                    if "apical_dendrites" not in neuron.keys():
                        neuron_actors["dendrites"] = neuron["basal_dendrites"]
                    elif "basal_dendrites" not in neuron.keys():
                        neuron_actors["dendrites"] = neuron["apical_dendrites"]
                    else:
                        neuron_actors["dendrites"] = merge(
                            neuron["apical_dendrites"],
                            neuron["basal_dendrites"],
                        )
                else:
                    neuron_actors["dendrites"] = neuron.pop("dendrites", None)

            # Deal with neuron as instance of Neuron from morphapi
            elif isinstance(neuron, Neuron):
                neuron_actors, _ = get_neuron_actors_with_morphapi(
                    neuron=neuron,
                    neurite_radius=neurite_radius,
                    use_cache=use_cache,
                )
            # Deal with other inputs
            else:
                raise ValueError(
                    f"Passed neuron {neuron} is not a valid input")

            # Check that we don't have anything weird in neuron_actors
            for key, act in neuron_actors.items():
                if act is not None:
                    if not isinstance(act, Mesh):
                        raise ValueError(
                            f"Neuron actor {key} is {type(act)} but should be a vedo Mesh. Not: {act}"
                        )

            if not display_axon:
                neuron_actors["axon"] = None
            if not display_dendrites:
                neuron_actors["dendrites"] = None
            _neurons_actors.append(neuron_actors)

        # Color actors
        colors = parse_neurons_colors(neurons, color)
        for n, neuron in enumerate(_neurons_actors):
            if neuron["axon"] is not None:
                neuron["axon"].c(colors["axon"][n])
                neuron["axon"].name = "neuron-axon"
            if neuron["soma"] is not None:
                neuron["soma"].c(colors["soma"][n])
                neuron["soma"].name = "neuron-soma"
            if neuron["dendrites"] is not None:
                neuron["dendrites"].c(colors["dendrites"][n])
                neuron["dendrites"].name = "neuron-dendrites"

        # Return
        return return_list_smart(_neurons_actors), None

    def get_tractography(
        self,
        tractography,
        color=None,
        color_by="manual",
        others_alpha=1,
        verbose=True,
        VIP_regions=[],
        VIP_color=None,
        others_color="white",
        include_all_inj_regions=False,
        display_injection_volume=True,
    ):
        """
        Renders tractography data and adds it to the scene. A subset of tractography data can receive special treatment using the  with VIP regions argument:
        if the injection site for the tractography data is in a VIP regions, this is colored differently.

        :param tractography: list of dictionaries with tractography data
        :param color: color of rendered tractography data

        :param color_by: str, specifies which criteria to use to color the tractography (Default value = "manual")
                        options:
                            -  manual, define color of each tract
                            - target_region, color by the injected region

        :param others_alpha: float (Default value = 1)
        :param verbose: bool (Default value = True)
        :param VIP_regions: list of brain regions with VIP treatement (Default value = [])
        :param VIP_color: str, color to use for VIP data (Default value = None)
        :param others_color: str, color for not VIP data (Default value = "white")
        :param include_all_inj_regions: bool (Default value = False)
        :param display_injection_volume: float, if True a spehere is added to display the injection coordinates and volume (Default value = True)
        """

        # check argument
        if not isinstance(tractography, list):
            if isinstance(tractography, dict):
                tractography = [tractography]
            else:
                raise ValueError(
                    "the 'tractography' variable passed must be a list of dictionaries"
                )
        else:
            if not isinstance(tractography[0], dict):
                raise ValueError(
                    "the 'tractography' variable passed must be a list of dictionaries"
                )

        if not isinstance(VIP_regions, list):
            raise ValueError("VIP_regions should be a list of acronyms")

        COLORS = parse_tractography_colors(
            tractography,
            include_all_inj_regions,
            color=color,
            color_by=color_by,
            VIP_regions=VIP_regions,
            VIP_color=VIP_color,
            others_color=others_color,
        )
        COLORS = [
            c if c is not None else self._get_from_structure(
                t["structure-abbrev"], "rgb_triplet")
            for c, t in zip(COLORS, tractography)
        ]

        # add actors to represent tractography data
        actors, structures_acronyms = [], []
        if brainrender.VERBOSE and verbose:
            print("Structures found to be projecting to target: ")

        # Loop over injection experiments
        for i, (t, color) in enumerate(zip(tractography, COLORS)):
            # Use allen metadata
            if include_all_inj_regions:
                inj_structures = [
                    x["abbreviation"] for x in t["injection-structures"]
                ]
            else:
                inj_structures = [
                    self.get_structure_ancestors(t["structure-abbrev"])[-1]
                ]

            if (brainrender.VERBOSE and verbose and not is_any_item_in_list(
                    inj_structures, structures_acronyms)):
                print("     -- ({})".format(t["structure-abbrev"]))
                structures_acronyms.append(t["structure-abbrev"])

            # get tractography points and represent as list
            if color_by == "target_region" and not is_any_item_in_list(
                    inj_structures, VIP_regions):
                alpha = others_alpha
            else:
                alpha = brainrender.TRACTO_ALPHA

            if alpha == 0:
                continue  # skip transparent ones

            # represent injection site as sphere
            if display_injection_volume:
                actors.append(
                    shapes.Sphere(
                        pos=t["injection-coordinates"],
                        c=color,
                        r=brainrender.INJECTION_VOLUME_SIZE *
                        t["injection-volume"],
                        alpha=brainrender.TRACTO_ALPHA,
                    ))
                actors[-1].name = (str(t["injection-coordinates"]) +
                                   "_injection")

            points = [p["coord"] for p in t["path"]]
            actors.append(
                shapes.Tube(
                    points,
                    r=brainrender.TRACTO_RADIUS,
                    c=color,
                    alpha=alpha,
                    res=brainrender.TRACTO_RES,
                ))
            actors[-1].name = str(t["injection-coordinates"]) + "_tractography"

        return actors

    def get_streamlines(self, sl_file, color=None, *args, **kwargs):
        """
        Render streamline data downloaded from https://neuroinformatics.nl/HBP/allen-connectivity-viewer/streamline-downloader.html

        :param sl_file: path to JSON file with streamliens data [or list of files]
        :param color: either a single color or a list of colors to color each streamline individually
        :param *args:
        :param **kwargs:

        """
        if not isinstance(sl_file, (list, tuple)):
            sl_file = [sl_file]

        # get a list of colors of length len(sl_file)
        if color is not None:
            if isinstance(color, (list, tuple)):
                if isinstance(color[0], (float, int)):  # it's an rgb color
                    color = [color for i in sl_file]
                elif len(color) != len(sl_file):
                    raise ValueError(
                        "Wrong number of colors, should be one per streamline or 1"
                    )
            else:
                color = [color for i in sl_file]
        else:
            color = ["salmon" for i in sl_file]

        actors = []
        if isinstance(sl_file[0],
                      (str, pd.DataFrame)):  # we have a list of files to add
            for slf, col in track(
                    zip(sl_file, color),
                    total=len(sl_file),
                    description="parsing streamlines",
            ):
                if isinstance(slf, str):
                    streamlines = parse_streamline(color=col,
                                                   filepath=slf,
                                                   *args,
                                                   **kwargs)
                else:
                    streamlines = parse_streamline(color=col,
                                                   data=slf,
                                                   *args,
                                                   **kwargs)
                actors.extend(streamlines)
        else:
            raise ValueError(
                "unrecognized argument sl_file: {}".format(sl_file))

        return actors

    # ----------------------------------- Utils ---------------------------------- #
    def get_projection_tracts_to_target(self, p0=None, **kwargs):
        """
        Gets tractography data for all experiments whose projections reach the brain region or location of iterest.
        
        :param p0: list of 3 floats with AP-DV-ML coordinates of point to be used as seed (Default value = None)
        :param **kwargs: 
        """

        # check args
        if p0 is None:
            raise ValueError("Please pass coordinates")
        elif isinstance(p0, np.ndarray):
            p0 = list(p0)
        elif not isinstance(p0, (list, tuple)):
            raise ValueError("Invalid argument passed (p0): {}".format(p0))

        p0 = [np.int(p) for p in p0]
        tract = self.mca.experiment_spatial_search(seed_point=p0, **kwargs)

        if isinstance(tract, str):
            raise ValueError(
                "Something went wrong with query, query error message:\n{}".
                format(tract))
        else:
            return tract

    def download_streamlines_for_region(self, region, *args, **kwargs):
        """
            Using the Allen Mouse Connectivity data and corresponding API, this function finds expeirments whose injections
            were targeted to the region of interest and downloads the corresponding streamlines data. By default, experiements
            are selected for only WT mice and onl when the region was the primary injection target. Look at "ABA.experiments_source_search"
            to see how to change this behaviour.

            :param region: str with region to use for research
            :param *args: arguments for ABA.experiments_source_search
            :param **kwargs: arguments for ABA.experiments_source_search

        """
        # Get experiments whose injections were targeted to the region
        region_experiments = experiments_source_search(self.mca, region, *args,
                                                       **kwargs)
        try:
            return download_streamlines(
                region_experiments.id.values,
                streamlines_folder=self.streamlines_cache,
            )
        except:
            print(f"Could not download streamlines for region {region}")
            return [], []  # <- there were no experiments in the target region

    def download_streamlines_to_region(self,
                                       p0,
                                       *args,
                                       mouse_line="wt",
                                       **kwargs):
        """
            Using the Allen Mouse Connectivity data and corresponding API, this function finds injection experiments
            which resulted in fluorescence being found in the target point, then downloads the streamlines data.

            :param p0: list of floats with AP-DV-ML coordinates
            :param mouse_line: str with name of the mouse line to use(Default value = "wt")
            :param *args: 
            :param **kwargs: 

        """
        experiments = pd.DataFrame(self.get_projection_tracts_to_target(p0=p0))
        if mouse_line == "wt":
            experiments = experiments.loc[experiments["transgenic-line"] == ""]
        else:
            if not isinstance(mouse_line, list):
                experiments = experiments.loc[experiments["transgenic-line"] ==
                                              mouse_line]
            else:
                raise NotImplementedError(
                    "ops, you've found a bug!. For now you can only pass one mouse line at the time, sorry."
                )
        return download_streamlines(experiments.id.values,
                                    streamlines_folder=self.streamlines_cache)
def test_notebook(fn_temp_dir):

    # coding: utf-8

    # ## Mouse Connectivity
    # 
    # This notebook demonstrates how to access and manipulate data in the Allen Mouse Brain Connectivity Atlas. The `MouseConnectivityCache` AllenSDK class provides methods for downloading metadata about experiments, including their viral injection site and the mouse's transgenic line. You can request information either as a Pandas DataFrame or a simple list of dictionaries.
    # 
    # An important feature of the `MouseConnectivityCache` is how it stores and retrieves data for you. By default, it will create (or read) a manifest file that keeps track of where various connectivity atlas data are stored. If you request something that has not already been downloaded, it will download it and store it in a well known location.
    # 
    # Download this notebook in .ipynb format <a href='mouse_connectivity.ipynb'>here</a>.

    # In[1]:

    from allensdk.core.mouse_connectivity_cache import MouseConnectivityCache

    # The manifest file is a simple JSON file that keeps track of all of
    # the data that has already been downloaded onto the hard drives.
    # If you supply a relative path, it is assumed to be relative to your
    # current working directory.
    mcc = MouseConnectivityCache(manifest_file='connectivity/mouse_connectivity_manifest.json')

    # open up a list of all of the experiments
    all_experiments = mcc.get_experiments(dataframe=True)
    print("%d total experiments" % len(all_experiments))

    # take a look at what we know about an experiment with a primary motor injection
    all_experiments.loc[122642490]


    # `MouseConnectivityCache` has a method for retrieving the adult mouse structure tree as an `StructureTree` class instance. This is a wrapper around a list of dictionaries, where each dictionary describes a structure. It is principally useful for looking up structures by their properties.

    # In[2]:

    # pandas for nice tables
    import pandas as pd

    # grab the StructureTree instance
    structure_tree = mcc.get_structure_tree()

    # get info on some structures
    structures = structure_tree.get_structures_by_name(['Primary visual area', 'Hypothalamus'])
    pd.DataFrame(structures)


    # As a convenience, structures are grouped in to named collections called "structure sets". These sets can be used to quickly gather a useful subset of structures from the tree. The criteria used to define structure sets are eclectic; a structure set might list:
    # 
    # * structures that were used in a particular project.
    # * structures that coarsely partition the brain.
    # * structures that bear functional similarity.
    # 
    # or something else entirely. To view all of the available structure sets along with their descriptions, follow this [link](http://api.brain-map.org/api/v2/data/StructureSet/query.json). To see only structure sets relevant to the adult mouse brain, use the StructureTree:

    # In[3]:

    from allensdk.api.queries.ontologies_api import OntologiesApi

    oapi = OntologiesApi()

    # get the ids of all the structure sets in the tree
    structure_set_ids = structure_tree.get_structure_sets()

    # query the API for information on those structure sets
    pd.DataFrame(oapi.get_structure_sets(structure_set_ids))


    # On the connectivity atlas web site, you'll see that we show most of our data at a fairly coarse structure level. We did this by creating a structure set of ~300 structures, which we call the "summary structures". We can use the structure tree to get all of the structures in this set:

    # In[4]:

    # From the above table, "Mouse Connectivity - Summary" has id 167587189
    summary_structures = structure_tree.get_structures_by_set_id([167587189])
    pd.DataFrame(summary_structures)


    # This is how you can filter experiments by transgenic line:

    # In[5]:

    # fetch the experiments that have injections in the isocortex of cre-positive mice
    isocortex = structure_tree.get_structures_by_name(['Isocortex'])[0]
    cre_cortical_experiments = mcc.get_experiments(cre=True, 
                                                    injection_structure_ids=[isocortex['id']])

    print("%d cre cortical experiments" % len(cre_cortical_experiments))

    # same as before, but restrict the cre line
    rbp4_cortical_experiments = mcc.get_experiments(cre=[ 'Rbp4-Cre_KL100' ], 
                                                    injection_structure_ids=[isocortex['id']])


    print("%d Rbp4 cortical experiments" % len(rbp4_cortical_experiments))


    # ## Structure Signal Unionization
    # 
    # The ProjectionStructureUnionizes API data tells you how much signal there was in a given structure and experiment. It contains the density of projecting signal, volume of projecting signal, and other information. `MouseConnectivityCache` provides methods for querying and storing this data.

    # In[6]:

    # find wild-type injections into primary visual area
    visp = structure_tree.get_structures_by_acronym(['VISp'])[0]
    visp_experiments = mcc.get_experiments(cre=False, 
                                           injection_structure_ids=[visp['id']])

    print("%d VISp experiments" % len(visp_experiments))

    structure_unionizes = mcc.get_structure_unionizes([ e['id'] for e in visp_experiments ], 
                                                      is_injection=False,
                                                      structure_ids=[isocortex['id']],
                                                      include_descendants=True)

    print("%d VISp non-injection, cortical structure unionizes" % len(structure_unionizes))


    # In[7]:

    structure_unionizes.head()


    # This is a rather large table, even for a relatively small number of experiments.  You can filter it down to a smaller list of structures like this.

    # In[8]:

    dense_unionizes = structure_unionizes[ structure_unionizes.projection_density > .5 ]
    large_unionizes = dense_unionizes[ dense_unionizes.volume > .5 ]
    large_structures = pd.DataFrame(structure_tree.nodes(large_unionizes.structure_id))

    print("%d large, dense, cortical, non-injection unionizes, %d structures" % ( len(large_unionizes), len(large_structures) ))

    print(large_structures.name)

    large_unionizes


    # ## Generating a Projection Matrix
    # The `MouseConnectivityCache` class provides a helper method for converting ProjectionStructureUnionize records for a set of experiments and structures into a matrix.  This code snippet demonstrates how to make a matrix of projection density values in auditory sub-structures for cre-negative VISp experiments. 

    # In[9]:

    import numpy as np
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')

    visp_experiment_ids = [ e['id'] for e in visp_experiments ]
    ctx_children = structure_tree.child_ids( [isocortex['id']] )[0]

    pm = mcc.get_projection_matrix(experiment_ids = visp_experiment_ids, 
                                   projection_structure_ids = ctx_children,
                                   hemisphere_ids= [2], # right hemisphere, ipsilateral
                                   parameter = 'projection_density')

    row_labels = pm['rows'] # these are just experiment ids
    column_labels = [ c['label'] for c in pm['columns'] ] 
    matrix = pm['matrix']

    fig, ax = plt.subplots(figsize=(15,15))
    heatmap = ax.pcolor(matrix, cmap=plt.cm.afmhot)

    # put the major ticks at the middle of each cell
    ax.set_xticks(np.arange(matrix.shape[1])+0.5, minor=False)
    ax.set_yticks(np.arange(matrix.shape[0])+0.5, minor=False)

    ax.set_xlim([0, matrix.shape[1]])
    ax.set_ylim([0, matrix.shape[0]])          

    # want a more natural, table-like display
    ax.invert_yaxis()
    ax.xaxis.tick_top()

    ax.set_xticklabels(column_labels, minor=False)
    ax.set_yticklabels(row_labels, minor=False)

    # ## Manipulating Grid Data
    # 
    # The `MouseConnectivityCache` class also helps you download and open every experiment's projection grid data volume. By default it will download 25um volumes, but you could also download data at other resolutions if you prefer (10um, 50um, 100um).
    # 
    # This demonstrates how you can load the projection density for a particular experiment. It also shows how to download the template volume to which all grid data is registered. Voxels in that template have been structurally annotated by neuroanatomists and the resulting labels stored in a separate annotation volume image.

    # In[10]:

    # we'll take this experiment - an injection into the primary somatosensory - as an example
    experiment_id = 181599674


    # In[11]:

    # projection density: number of projecting pixels / voxel volume
    pd, pd_info = mcc.get_projection_density(experiment_id)

    # injection density: number of projecting pixels in injection site / voxel volume
    ind, ind_info = mcc.get_injection_density(experiment_id)

    # injection fraction: number of pixels in injection site / voxel volume
    inf, inf_info = mcc.get_injection_fraction(experiment_id)

    # data mask:
    # binary mask indicating which voxels contain valid data
    dm, dm_info = mcc.get_data_mask(experiment_id)

    template, template_info = mcc.get_template_volume()
    annot, annot_info = mcc.get_annotation_volume()

    # in addition to the annotation volume, you can get binary masks for individual structures
    # in this case, we'll get one for the isocortex
    cortex_mask, cm_info = mcc.get_structure_mask(315)

    print(pd_info)
    print(pd.shape, template.shape, annot.shape)


    # Once you have these loaded, you can use matplotlib see what they look like.

    # In[12]:

    # compute the maximum intensity projection (along the anterior-posterior axis) of the projection data
    pd_mip = pd.max(axis=0)
    ind_mip = ind.max(axis=0)
    inf_mip = inf.max(axis=0)

    # show that slice of all volumes side-by-side
    f, pr_axes = plt.subplots(1, 3, figsize=(15, 6))

    pr_axes[0].imshow(pd_mip, cmap='hot', aspect='equal')
    pr_axes[0].set_title("projection density MaxIP")

    pr_axes[1].imshow(ind_mip, cmap='hot', aspect='equal')
    pr_axes[1].set_title("injection density MaxIP")

    pr_axes[2].imshow(inf_mip, cmap='hot', aspect='equal')
    pr_axes[2].set_title("injection fraction MaxIP")


    # In[13]:

    # Look at a slice from the average template and annotation volumes

    # pick a slice to show
    slice_idx = 264

    f, ccf_axes = plt.subplots(1, 3, figsize=(15, 6))

    ccf_axes[0].imshow(template[slice_idx,:,:], cmap='gray', aspect='equal', vmin=template.min(), vmax=template.max())
    ccf_axes[0].set_title("registration template")

    ccf_axes[1].imshow(annot[slice_idx,:,:], cmap='gray', aspect='equal', vmin=0, vmax=2000)
    ccf_axes[1].set_title("annotation volume")

    ccf_axes[2].imshow(cortex_mask[slice_idx,:,:], cmap='gray', aspect='equal', vmin=0, vmax=1)
    ccf_axes[2].set_title("isocortex mask")


    # On occasion the TissueCyte microscope fails to acquire a tile. In this case the data from that tile should not be used for analysis. The data mask associated with each experiment can be used to determine which portions of the grid data came from correctly acquired tiles.
    # 
    # In this experiment, a missed tile can be seen in the data mask as a dark warped square. The values in the mask exist within [0, 1], describing the fraction of each voxel that was correctly acquired

    # In[14]:

    f, data_mask_axis = plt.subplots(figsize=(5, 6))

    data_mask_axis.imshow(dm[81, :, :], cmap='hot', aspect='equal', vmin=0, vmax=1)
    data_mask_axis.set_title('data mask')
Пример #8
0
class ExperimentImagesDownloader(DirWatcher):
    def __init__(self, input_dir, process_dir, output_dir, structure_map_dir,
                 structs, connectivity_dir, _processor_number,
                 brightness_threshold, strains):
        super().__init__(input_dir, process_dir, output_dir,
                         f'experiment-images-downloader-{_processor_number}')
        self.brightness_threshold = brightness_threshold
        self.structs = ast.literal_eval(structs)
        self.segmentation_dir = structure_map_dir
        self.mcc = MouseConnectivityCache(
            manifest_file=f'{connectivity_dir}/mouse_connectivity_manifest.json'
        )
        struct_tree = self.mcc.get_structure_tree()
        structure_ids = [
            i for sublist in struct_tree.descendant_ids(self.structs)
            for i in sublist
        ]
        self.structure_ids = set(structure_ids)
        self.image_api = ImageDownloadApi()
        self.bbox_dilation_kernel = cv2.getStructuringElement(
            cv2.MORPH_ELLIPSE, (14, 14))
        exps = self.mcc.get_experiments(dataframe=True)
        items = []
        for s, gs in strains.items():
            strain_items = []
            for g in gs:
                strain_items += [
                    sorted(exps[(exps.strain == s)
                                & (exps.gender == g)].id.tolist())
                ]
            if strain_items:
                min_len = min([len(i) for i in strain_items])
                strain_items = [i[:min_len] for i in strain_items]
                items += [str(i) for j in zip(*strain_items) for i in j]
        self.initial_items = [i for i in items if i in self.initial_items] + [
            i for i in self.initial_items if i not in items
        ]

    def on_process_error(self, item, exception):
        retval = super().on_process_error(item, exception)
        self.logger.error(f"Error occurred during processing", exc_info=True)
        if any(
                map(lambda x: issubclass(type(exception), x), [
                    urllib.error.HTTPError, OSError, ValueError,
                    http.client.error
                ])):
            return False
        else:
            return retval

    def process_item(self, item, directory):
        experiment_id = int(item)
        retries = 0
        images = []
        while True:
            try:
                time.sleep(2**(retries // 2))
                images = self.image_api.section_image_query(experiment_id)
                break
            except simplejson.errors.JSONDecodeError as e:
                if retries > 10:
                    raise e
                else:
                    self.logger.info(f"Exception invoking image API, retrying")
                    retries += 1
                    continue

        images = {i['section_number']: i for i in images}
        segmentation = np.load(
            f'{self.segmentation_dir}/{item}/{item}-sections.npz')['arr_0']
        mask = np.isin(segmentation, list(self.structure_ids))
        locs = np.where(mask)
        sections = [
            s for s in sorted(np.unique(locs[2]).tolist()) if s in images
        ]
        bboxes = {
            section: self.extract_bounding_boxes(mask[:, :, section])
            for section in sections
        }
        valid_sections = list(filter(lambda s: bboxes[s], sections))
        self.logger.info(
            f"Experiment {experiment_id}, evaluating brightness...")
        brightness = self.calculate_brightness(directory, experiment_id,
                                               images, valid_sections, mask)

        if brightness < self.brightness_threshold:
            self.logger.info(
                f"Experiment {experiment_id}: brightness less than required minimum, removing..."
            )
            return False

        with open(f'{directory}/bboxes.pickle', 'wb') as f:
            pickle.dump(bboxes, f)

        for section in valid_sections:
            self.process_section(directory, experiment_id, images, section,
                                 bboxes[section])

    def calculate_brightness(self, directory, experiment_id, images,
                             valid_sections, mask):
        pixels = np.zeros_like(mask, dtype=np.uint8)
        for section in valid_sections:
            self.download_snapshot(experiment_id, section, images[section],
                                   directory)
            filename = f'{directory}/thumbnail-{experiment_id}-{section}.jpg'
            image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
            pixels[:, :, section] = image[:mask.shape[0], :mask.shape[1]]

        return np.median(pixels[mask != 0])

    def process_section(self, directory, experiment_id, images, section,
                        bboxes):
        self.logger.info(
            f"Experiment {experiment_id}, downloading section {section}...")
        self.download_snapshot(experiment_id, section, images[section],
                               directory)
        for bbox in bboxes:
            self.download_fullres(experiment_id, section, bbox,
                                  images[section], directory)

    def extract_bounding_boxes(self, mask, area_threshold=0):
        bboxes = self.get_bounding_boxes(mask)
        bbmask = np.zeros_like(mask, dtype=np.uint8)
        for bbox in bboxes:
            cv2.rectangle(bbmask, *bbox.corners(), color=1, thickness=-1)
        bbmask = cv2.dilate(bbmask, self.bbox_dilation_kernel)
        bboxes = [
            bbox for bbox in self.get_bounding_boxes(bbmask)
            if bbox.area() > area_threshold
        ]
        return bboxes

    @staticmethod
    def get_bounding_boxes(mask):
        contours, hierarchy = cv2.findContours(mask.astype(np.uint8),
                                               cv2.RETR_EXTERNAL,
                                               cv2.CHAIN_APPROX_SIMPLE)[-2:]
        rects = []
        for cnt in contours:
            x, y, w, h = cv2.boundingRect(cnt)
            if w > 5 and h > 5:
                rects.append(Rect(x=x, y=y, w=w, h=h))
        return rects

    def download_fullres(self, experiment_id, section, bbox, image_desc,
                         directory):
        url = f'https://connectivity.brain-map.org/cgi-bin/imageservice?path={image_desc["path"]}&' \
              f'mime=1&zoom={8}&&filter=range&filterVals=0,534,0,1006,0,4095'
        x, y, w, h = bbox.scale(64)
        url += f'&top={y}&left={x}&width={w}&height={h}'
        filename = f'{directory}/full-{experiment_id}-{section}-{x}_{y}_{w}_{h}.jpg'
        for retries in range(3):
            fname, _, downloaded = self.retrieve_url(filename, url)
            if downloaded:
                try:
                    image = Image.open(fname)
                    image.load()
                    break
                except OSError or FileNotFoundError as e:
                    os.remove(fname)
                    if retries == 2:
                        raise e
                    else:
                        self.logger.info(
                            f"Corrupted file {fname}, re-downloading {filename}"
                        )
            else:
                self.logger.info(
                    f"Cached version of {filename} used, skipping verification"
                )

        return filename

    def download_snapshot(self, experiment_id, section, image_desc, directory):
        url = f'https://connectivity.brain-map.org/cgi-bin/imageservice?path={image_desc["path"]}&' \
              f'mime=1&zoom={2}&&filter=range&filterVals=0,534,0,1006,0,4095'
        filename = f'{directory}/thumbnail-{experiment_id}-{section}.jpg'
        filename, _, _ = self.retrieve_url(filename, url)
        return filename

    def download_brightness_snapshot(self, experiment_id, section, image_desc,
                                     directory):
        url = f'https://connectivity.brain-map.org/cgi-bin/imageservice?path={image_desc["path"]}&' \
              f'mime=1&zoom={2}&&filter=range&filterVals=0,534,0,1006,0,4095'
        filename = f'{directory}/thumbnail-{experiment_id}-{section}.jpg'
        filename, _, _ = self.retrieve_url(filename, url)
        return filename

    def retrieve_url(self, filename, url, retries=10):
        if os.path.isfile(filename):
            self.logger.info(f"File {filename} already downloaded")
            return filename, None, False

        backoff = 0
        urllib.request.urlcleanup()
        while True:
            try:
                time.sleep(2**backoff)
                fname, msg = urllib.request.urlretrieve(
                    url, filename=f'{filename}.partial')
                os.replace(fname, filename)
                return filename, msg, True
            except http.client.HTTPException or OSError or urllib.error.HTTPError as e:
                backoff += 1
                retries -= 1
                if retries > 0:
                    self.logger.info(
                        f"Transient error downloading {url}, "
                        f"retrying ({retries} retries left) ...",
                        exc_info=True)
                    continue
                else:
                    self.logger.exception(
                        f"Retry count exceeded or permanent error for {url} ({filename}), exiting..."
                    )
                    raise e
import pandas as pd
from allensdk.core.mouse_connectivity_cache import MouseConnectivityCache
from tqdm import tqdm

mcc = MouseConnectivityCache(
    manifest_file='mouse_connectivity/mouse_connectivity_manifest.json',
    resolution=25)

if os.path.isfile('mouse_connectivity/tree.pickle'):
    acronyms, structs_descendants, structs_children = pickle.load(
        open('mouse_connectivity/tree.pickle', 'rb'))
else:
    acronyms = {
        v: k
        for k, v in mcc.get_structure_tree().get_id_acronym_map().items()
    }
    structs_descendants = {
        i: set(mcc.get_structure_tree().descendant_ids([i])[0])
        for i in set(mcc.get_structure_tree().descendant_ids([8])[0])
    }
    structs_children = {
        i: set([a['id'] for a in mcc.get_structure_tree().children([i])[0]])
        for i in structs_descendants.keys()
    }
    pickle.dump((acronyms, structs_descendants, structs_children),
                open('mouse_connectivity/tree.pickle', 'wb'))

conversion = {
    'volume': -3,
    'region_area_right': -2,
    def launch(self, resolution, weighting, inj_f_thresh, vol_thresh):
        resolution = int(resolution)
        weighting = int(weighting)
        inj_f_thresh = float(inj_f_thresh)/100.
        vol_thresh = float(vol_thresh)

        project = dao.get_project_by_id(self.current_project_id)
        manifest_file = self.file_handler.get_allen_mouse_cache_folder(project.name)
        manifest_file = os.path.join(manifest_file, 'mouse_connectivity_manifest.json')
        cache = MouseConnectivityCache(resolution=resolution, manifest_file=manifest_file)

        # the method creates a dictionary with information about which experiments need to be downloaded
        ist2e = dictionary_builder(cache, False)

        # the method downloads experiments necessary to build the connectivity
        projmaps = download_an_construct_matrix(cache, weighting, ist2e, False)

        # the method cleans the file projmaps in 4 steps
        projmaps = pms_cleaner(projmaps)

        # download from the AllenSDK the annotation volume, the template volume
        vol, annot_info = cache.get_annotation_volume()
        template, template_info = cache.get_template_volume()

        # rotate template in the TVB 3D reference:
        template = rotate_reference(template)

        # grab the StructureTree instance
        structure_tree = cache.get_structure_tree()

        # the method includes in the parcellation only brain regions whose volume is greater than vol_thresh
        projmaps = areas_volume_threshold(cache, projmaps, vol_thresh, resolution)
        
        # the method exclude from the experimental dataset
        # those exps where the injected fraction of pixel in the injection site is lower than than the inj_f_thr 
        projmaps = infected_threshold(cache, projmaps, inj_f_thresh)

        # the method creates file order and keyword that will be the link between the SC order and the
        # id key in the Allen database
        [order, key_ord] = create_file_order(projmaps, structure_tree)

        # the method builds the Structural Connectivity (SC) matrix
        structural_conn = construct_structural_conn(projmaps, order, key_ord)

        # the method returns the coordinate of the centres and the name of the brain areas in the selected parcellation
        [centres, names] = construct_centres(cache, order, key_ord)

        # the method returns the tract lengths between the brain areas in the selected parcellation
        tract_lengths = construct_tract_lengths(centres)

        # the method associated the parent and the grandparents to the child in the selected parcellation with
        # the biggest volume
        [unique_parents, unique_grandparents] = parents_and_grandparents_finder(cache, order, key_ord, structure_tree)

        # the method returns a volume indexed between 0 and N-1, with N=tot brain areas in the parcellation.
        # -1=background and areas that are not in the parcellation
        vol_parcel = mouse_brain_visualizer(vol, order, key_ord, unique_parents, unique_grandparents,
                                            structure_tree, projmaps)

        # results: Connectivity, Volume & RegionVolumeMapping
        # Connectivity
        result_connectivity = Connectivity(storage_path=self.storage_path)
        result_connectivity.centres = centres
        result_connectivity.region_labels = names
        result_connectivity.weights = structural_conn
        result_connectivity.tract_lengths = tract_lengths
        # Volume
        result_volume = Volume(storage_path=self.storage_path)
        result_volume.origin = [[0.0, 0.0, 0.0]]
        result_volume.voxel_size = [resolution, resolution, resolution]
        # result_volume.voxel_unit= micron
        # Region Volume Mapping
        result_rvm = RegionVolumeMapping(storage_path=self.storage_path)
        result_rvm.volume = result_volume
        result_rvm.array_data = vol_parcel
        result_rvm.connectivity = result_connectivity
        result_rvm.title = "Volume mouse brain "
        result_rvm.dimensions_labels = ["X", "Y", "Z"]
        # Volume template
        result_template = StructuralMRI(storage_path=self.storage_path)
        result_template.array_data = template
        result_template.weighting = 'T1'
        result_template.volume = result_volume
        return [result_connectivity, result_volume, result_rvm, result_template]
Пример #11
0
def main():
    # Find the path to an existing ontology document that was installed through the Brain Explorer interface
    path = r'C:\Users\jenniferwh\AppData\Local\Allen Institute\Brain Explorer 2\Atlases\Allen Mouse Brain Common Coordinate Framework'
    dat = pd.read_csv(os.path.join(path, 'ontology_v2.csv'))
    aapi = AnatomyApi()
    mcc = MouseConnectivityCache(
        manifest_file='/connectivity/mouse_connectivity_manifest.json')
    st = mcc.get_structure_tree()
    ia_map = st.get_id_acronym_map()
    ss = aapi.get_summary_structure_data('id')

    if args.Thal_phase == 1:
        thal_structures = ['Isocortex']
    if args.Thal_phase == 2:
        thal_structures = ['CA1', 'ENTl', 'ENTm']
    if args.Thal_phase == 3:
        thal_structures = [
            'ACA', 'RSP', 'LA', 'BLA', 'BMA', 'PA', 'CEA', 'MEA', 'COA', 'DG',
            'PRE', 'POST', 'TH', 'CP', 'ACB', 'HY', 'SI', 'MA', 'NDB'
        ]
    if args.Thal_phase == 4:
        thal_structures = ['PAG', 'SCs', 'SCm', 'RN', 'IO', 'SNr', 'SNc']
    if args.Thal_phase == 5:
        thal_structures = [
            'GRN', 'IRN', 'PARN', 'CBX', 'PRNr', 'PRNc', 'RAmb', 'LC', 'PB',
            'TRN', 'DTN', 'PG'
        ]
    thal_structure_ids = [ia_map[structure] for structure in thal_structures]
    '''
    for structure in thal_structure_ids:
        if structure not in ss:
            children = st.descendant_ids([structure])[0]
            child_ss = [structure_id for structure_id in children if structure_id in ss]
            ss += [structure]
            thal_structure_ids+=child_ss
    '''
    colormap = cm.Reds
    all_structures = dat['abbreviation'].unique()
    all_structures = [
        structure for structure in all_structures
        if structure in ia_map.keys()
    ]
    all_structures.remove('root')
    all_structure_ids = [ia_map[structure] for structure in all_structures]
    structure_vals = dict()
    for structure in all_structure_ids:
        if structure in thal_structure_ids:
            structure_vals[structure] = 0.9
        else:
            structure_vals[structure] = 0
    rgb_vals = structure_vals.copy()
    for key in all_structure_ids:
        rgb_vals[key] = tuple(
            [255 * i for i in colormap(structure_vals[key])[:3]])
        dat.loc[dat['database_id'] == key, 'red'] = int(rgb_vals[key][0])
        dat.loc[dat['database_id'] == key, 'green'] = int(rgb_vals[key][1])
        dat.loc[dat['database_id'] == key, 'blue'] = int(rgb_vals[key][2])
    rgb_vals[0] = (0, 0, 0)
    dat.loc[dat['abbreviation'] == 'root', 'parent'] = 0.
    dat['parent'] = [int(value) for value in dat['parent']]

    dat.to_csv(os.path.join(path, 'ontology_v2.csv'), index=False)
Пример #12
0
#===============================================================================
# example 1
#===============================================================================

from allensdk.core.mouse_connectivity_cache import MouseConnectivityCache

# tell the cache class what resolution (in microns) of data you want to download
mcc = MouseConnectivityCache(resolution=25)

# use the structure tree class to get information about the isocortex structure
structure_tree = mcc.get_structure_tree()
isocortex_id = structure_tree.get_structures_by_name(['Isocortex'])[0]['id']

# a list of dictionaries containing metadata for non-Cre experiments
experiments = mcc.get_experiments(file_name='non_cre.json',
                                  injection_structure_ids=[isocortex_id])

# download the projection density volume for one of the experiments
pd = mcc.get_projection_density(experiments[0]['id'])

#===============================================================================
# example 2
#===============================================================================

import nrrd

file_name = 'mouse_connectivity/experiment_644250774/projection_density_25.nrrd'
data_array, metadata = nrrd.read(file_name)
class BrainDetailsSelector(widgets.VBox):
    def __init__(self, input_dir):
        self.mcc = MouseConnectivityCache(
            manifest_file=
            f'../mouse_connectivity/mouse_connectivity_manifest.json',
            resolution=25)
        self.input_dir = input_dir
        self.experiments_selector = ExperimentsSelector()
        self.histograms_output = widgets.Output()
        self.section_combo = widgets.Dropdown(options=[],
                                              value=None,
                                              description='Choose section:')

        self.refresh_button = widgets.Button(
            description='Refresh experiment list')
        self.refresh_button.layout.width = 'auto'
        self.refresh_button.on_click(lambda b: self.refresh)

        self.display_button = widgets.Button(description='Go!')
        self.display_button.on_click(self.display_experiment)

        self.clear_button = widgets.Button(description='Clear plots')
        self.clear_button.on_click(
            lambda b: self.histograms_output.clear_output())

        self.experiments_selector.on_selection_change(
            lambda col, change: self.refresh())
        super().__init__(
            (widgets.HBox((self.experiments_selector, self.refresh_button)),
             widgets.HBox((self.section_combo, self.display_button,
                           self.clear_button)), self.histograms_output))

        self.refresh()
        self.on_select_experiment([])

    def refresh(self):
        self.experiments_selector.set_available_brains(
            set([int(e) for e in os.listdir(self.input_dir) if e.isdigit()]))
        experiment_ids = list(set(self.experiments_selector.get_selection()))
        self.on_select_experiment(experiment_ids)

    def on_select_experiment(self, experiment_ids):
        if len(experiment_ids) != 1:
            self.section_combo.options = []
            self.section_combo.value = None
            self.section_combo.disabled = True
        else:
            experiment_id = experiment_ids[0]
            directory = f"{self.input_dir}/{experiment_id}"
            with open(f'{directory}/bboxes.pickle', "rb") as f:
                bboxes = pickle.load(f)
            bboxes = {k: v for k, v in bboxes.items() if v}
            self.section_combo.options = ['all', 'totals'] + list(
                str(i) for i in bboxes.keys())
            self.section_combo.value = self.section_combo.options[0]
            self.section_combo.disabled = False

    def display_experiment(self, b):
        experiment_id = list(self.experiments_selector.get_selection())[0]
        section = self.section_combo.value
        if not experiment_id or not section:
            return
        directory = f"{self.input_dir}/{experiment_id}"
        full_data = pd.read_parquet(
            f"{directory}/celldata-{experiment_id}.parquet")
        full_data_mtime = os.path.getmtime(
            f"{directory}/celldata-{experiment_id}.parquet")

        with self.histograms_output:
            if section == 'all':
                SectionHistogramPlotter(experiment_id, 'totals', full_data,
                                        full_data_mtime, self.input_dir,
                                        self.mcc.get_structure_tree())
                for section in sorted(full_data.section.unique().tolist()):
                    section_data = full_data[full_data.section == int(section)]
                    SectionHistogramPlotter(experiment_id, section,
                                            section_data, full_data_mtime,
                                            self.input_dir,
                                            self.mcc.get_structure_tree())
            else:
                if section != 'totals':
                    full_data = full_data[full_data.section == int(section)]
                SectionHistogramPlotter(experiment_id, section, full_data,
                                        full_data_mtime, self.input_dir,
                                        self.mcc.get_structure_tree())
Пример #14
0
class RawDataResultsSelector(widgets.VBox):
    def __init__(self, data_dir):
        self.data_frames = DataFramesHolder(data_dir)
        self.available_brains = [
            e for e in os.listdir(data_dir) if e.isdigit()
        ]
        self.data_template = self.data_frames[self.available_brains[0]]
        self.messages = widgets.Output()
        self.mcc = MouseConnectivityCache(
            manifest_file=
            f'mouse_connectivity/mouse_connectivity_manifest.json',
            resolution=25)
        self.structure_tree = self.mcc.get_structure_tree()
        self.aggregates = get_struct_aggregates(
            set(self.get_column_options(self.data_template['structure_id'])))

        self.structure_selector = StructureTree(ids=[
            s['acronym'] for s in self.structure_tree.get_structures_by_id(
                list(self.aggregates.keys()))
        ],
                                                multiple_selection=True)
        self.parameter_selector = widgets.Dropdown(
            description="Parameter", options=['coverage', 'area', 'perimeter'])

        self.change_handler = None
        super().__init__(
            (widgets.HBox([self.structure_selector,
                           self.parameter_selector]), self.messages))

    def get_available_brains(self):
        return self.available_brains

    def reset(self):
        for v in self.filter.values():
            v.value = []

    @staticmethod
    def get_column_options(df):
        return sorted(df.unique().tolist())

    def get_selected_structs(self):
        selected_acronyms = [
            n.struct_id for n in self.structure_selector.selected_nodes
        ]
        id_sets = [
            self.aggregates[self.structure_tree.get_id_acronym_map()[s]]
            for s in selected_acronyms
        ]
        ids = set.union(*id_sets)
        return [acronyms[i] for i in ids]

    def process_data_frame(self, df, structs):
        frame = df[df.structure_id.isin(structs)]
        d = frame[self.parameter_selector.value].to_numpy()
        return d

    def get_selection(self, relevant_experiments):
        structs = [
            self.structure_tree.get_id_acronym_map()[s]
            for s in self.get_selected_structs()
        ]
        return np.concatenate([
            self.process_data_frame(self.data_frames[e], structs)
            for e in relevant_experiments
        ])

    def get_selection_label(self):
        label = '.'.join(
            [n.struct_id for n in self.structure_selector.selected_nodes])
        if label == '':
            label = '<any>'
        label = f'{label}.{self.parameter_selector.value}'

        return label

    def on_selection_change(self, handler):
        self.change_handler = handler
Пример #15
0
    def launch(self, view_model):
        resolution = view_model.resolution
        weighting = view_model.weighting
        inj_f_thresh = view_model.inj_f_thresh / 100.
        vol_thresh = view_model.vol_thresh

        project = dao.get_project_by_id(self.current_project_id)
        manifest_file = self.file_handler.get_allen_mouse_cache_folder(
            project.name)
        manifest_file = os.path.join(manifest_file,
                                     'mouse_connectivity_manifest.json')
        cache = MouseConnectivityCache(resolution=resolution,
                                       manifest_file=manifest_file)

        # the method creates a dictionary with information about which experiments need to be downloaded
        ist2e = dictionary_builder(cache, False)

        # the method downloads experiments necessary to build the connectivity
        projmaps = download_an_construct_matrix(cache, weighting, ist2e, False)

        # the method cleans the file projmaps in 4 steps
        projmaps = pms_cleaner(projmaps)

        # download from the AllenSDK the annotation volume, the template volume
        vol, annot_info = cache.get_annotation_volume()
        template, template_info = cache.get_template_volume()

        # rotate template in the TVB 3D reference:
        template = rotate_reference(template)

        # grab the StructureTree instance
        structure_tree = cache.get_structure_tree()

        # the method includes in the parcellation only brain regions whose volume is greater than vol_thresh
        projmaps = areas_volume_threshold(cache, projmaps, vol_thresh,
                                          resolution)

        # the method exclude from the experimental dataset
        # those exps where the injected fraction of pixel in the injection site is lower than than the inj_f_thr
        projmaps = infected_threshold(cache, projmaps, inj_f_thresh)

        # the method creates file order and keyword that will be the link between the SC order and the
        # id key in the Allen database
        [order, key_ord] = create_file_order(projmaps, structure_tree)

        # the method builds the Structural Connectivity (SC) matrix
        structural_conn = construct_structural_conn(projmaps, order, key_ord)

        # the method returns the coordinate of the centres and the name of the brain areas in the selected parcellation
        [centres, names] = construct_centres(cache, order, key_ord)

        # the method returns the tract lengths between the brain areas in the selected parcellation
        tract_lengths = construct_tract_lengths(centres)

        # the method associated the parent and the grandparents to the child in the selected parcellation with
        # the biggest volume
        [unique_parents, unique_grandparents
         ] = parents_and_grandparents_finder(cache, order, key_ord,
                                             structure_tree)

        # the method returns a volume indexed between 0 and N-1, with N=tot brain areas in the parcellation.
        # -1=background and areas that are not in the parcellation
        vol_parcel = mouse_brain_visualizer(vol, order, key_ord,
                                            unique_parents,
                                            unique_grandparents,
                                            structure_tree, projmaps)

        # results: Connectivity, Volume & RegionVolumeMapping
        # Connectivity
        result_connectivity = Connectivity()
        result_connectivity.centres = centres
        result_connectivity.region_labels = numpy.array(names)
        result_connectivity.weights = structural_conn
        result_connectivity.tract_lengths = tract_lengths
        result_connectivity.configure()
        # Volume
        result_volume = Volume()
        result_volume.origin = numpy.array([[0.0, 0.0, 0.0]])
        result_volume.voxel_size = numpy.array(
            [resolution, resolution, resolution])
        # result_volume.voxel_unit= micron
        # Region Volume Mapping
        result_rvm = RegionVolumeMapping()
        result_rvm.volume = result_volume
        result_rvm.array_data = vol_parcel
        result_rvm.connectivity = result_connectivity
        result_rvm.title = "Volume mouse brain "
        result_rvm.dimensions_labels = ["X", "Y", "Z"]
        # Volume template
        result_template = StructuralMRI()
        result_template.array_data = template
        result_template.weighting = 'T1'
        result_template.volume = result_volume

        connectivity_index = h5.store_complete(result_connectivity,
                                               self.storage_path)
        volume_index = h5.store_complete(result_volume, self.storage_path)
        rvm_index = h5.store_complete(result_rvm, self.storage_path)
        template_index = h5.store_complete(result_template, self.storage_path)

        return [connectivity_index, volume_index, rvm_index, template_index]
 def prepare_input(self, connectivity_dir, **kwargs):
     mcc = MouseConnectivityCache(
         manifest_file=f'{connectivity_dir}/mouse_connectivity_manifest.json'
     )
     mcc.get_structure_tree()
Пример #17
0
class ABA(Paths):
	"""
	This class handles interaction with the Allen Brain Atlas datasets and APIs to get structure trees,
	experimental metadata and results, tractography data etc. 
	"""
	
	# useful vars for analysis    
	excluded_regions = ["fiber tracts"]
	resolution = 25

	def __init__(self, projection_metric = "projection_energy", base_dir=None, **kwargs):
		""" 
		Set up file paths and Allen SDKs
		
		:param base_dir: path to directory to use for saving data (default value None)
		:param path_fiprojection_metricle: - str, metric to quantify the strength of projections from the Allen Connectome. (default value 'projection_energy')
		:param kwargs: can be used to pass path to individual data folders. See brainrender/Utils/paths_manager.py

		"""

		Paths.__init__(self, base_dir=base_dir, **kwargs)

		self.projection_metric = projection_metric

		# get mouse connectivity cache and structure tree
		self.mcc = MouseConnectivityCache(manifest_file=os.path.join(self.mouse_connectivity_cache, "manifest.json"))
		self.structure_tree = self.mcc.get_structure_tree()
		
		# get ontologies API and brain structures sets
		self.oapi = OntologiesApi()
		self.get_structures_sets()

		# get reference space
		self.space = ReferenceSpaceApi()
		self.spacecache = ReferenceSpaceCache(
			manifest=os.path.join(self.annotated_volume, "manifest.json"),  # downloaded files are stored relative to here
			resolution=self.resolution,
			reference_space_key="annotation/ccf_2017"  # use the latest version of the CCF
			)
		self.annotated_volume, _ = self.spacecache.get_annotation_volume()

		# mouse connectivity API [used for tractography]
		self.mca = MouseConnectivityApi()

		# Get tree search api
		self.tree_search = TreeSearchApi()

		# Get some metadata about experiments
		self.all_experiments = self.mcc.get_experiments(dataframe=True)
		self.strains = sorted([x for x in set(self.all_experiments.strain) if x is not None])
		self.transgenic_lines = sorted(set([x for x in set(self.all_experiments.transgenic_line) if x is not None]))

	####### GET EXPERIMENTS DATA
	def get_structures_sets(self):
		""" 
		Get the Allen's structure sets.
		"""
		summary_structures = self.structure_tree.get_structures_by_set_id([167587189])  # main summary structures
		summary_structures = [s for s in summary_structures if s["acronym"] not in self.excluded_regions]
		self.structures = pd.DataFrame(summary_structures)

		# Other structures sets
		try:
			all_sets = pd.DataFrame(self.oapi.get_structure_sets())
		except:
			print("Could not retrieve data, possibly because there is no internet connection.")
		else:
			sets = ["Summary structures of the pons", "Summary structures of the thalamus", 
						"Summary structures of the hypothalamus", "List of structures for ABA Fine Structure Search",
						"Structures representing the major divisions of the mouse brain", "Summary structures of the midbrain", "Structures whose surfaces are represented by a precomputed mesh"]
			self.other_sets = {}
			for set_name in sets:
				set_id = all_sets.loc[all_sets.description == set_name].id.values[0]
				self.other_sets[set_name] = pd.DataFrame(self.structure_tree.get_structures_by_set_id([set_id]))

			self.all_avaliable_meshes = sorted(self.other_sets["Structures whose surfaces are represented by a precomputed mesh"].acronym.values)

	def print_structures_list_to_text(self):
		""" 
		Saves the name of every brain structure for which a 3d mesh (.obj file) is available in a text file.
		"""
		s = self.other_sets["Structures whose surfaces are represented by a precomputed mesh"].sort_values('acronym')
		with open('all_regions.txt', 'w') as o:
			for acr, name in zip(s.acronym.values, s['name'].values):
				o.write("({}) -- {}\n".format(acr, name))

	def load_all_experiments(self, cre=False):
		"""
		This function downloads all the experimental data from the MouseConnectivityCache and saves the unionized results
		as pickled pandas dataframes. The process is slow, but the ammount of disk space necessary to save the data is small,
		so it's worth downloading all the experiments at once to speed up subsequent analysis.

		:param cre: Bool - data from either wild time or cre mice lines (Default value = False)

		"""
		
		if not cre: raise NotImplementedError("Only works for wild type sorry")
		# Downloads all experiments from allen brain atlas and saves the results as an easy to read pkl file
		for acronym in self.structures.acronym.values:
			print("Fetching experiments for : {}".format(acronym))

			structure = self.structure_tree.get_structures_by_acronym([acronym])[0]
			experiments = self.mcc.get_experiments(cre=cre, injection_structure_ids=[structure['id']])

			print("     found {} experiments".format(len(experiments)))

			try:
				structure_unionizes = self.mcc.get_structure_unionizes([e['id'] for e in experiments], 
															is_injection=False,
															structure_ids=self.structures.id.values,
															include_descendants=False)
			except: pass
			structure_unionizes.to_pickle(os.path.join(self.output_data, "{}.pkl".format(acronym)))
	
	def print_structures(self):
		""" 
		Prints the name of every structure in the structure tree to the console.
		"""
		acronyms, names = self.structures.acronym.values, self.structures['name'].values
		sort_idx = np.argsort(acronyms)
		acronyms, names = acronyms[sort_idx], names[sort_idx]
		[print("({}) - {}".format(a, n)) for a,n in zip(acronyms, names)]

	def experiments_source_search(self, SOI, *args, source=True,  **kwargs):
		"""
		Returns data about experiments whose injection was in the SOI, structure of interest

		:param SOI: str, structure of interest. Acronym of structure to use as seed for teh search
		:param *args: 
		:param source:  (Default value = True)
		:param **kwargs: 

		"""
		"""
			list of possible kwargs
				injection_structures : list of integers or strings
					Integer Structure.id or String Structure.acronym.
				target_domain : list of integers or strings, optional
					Integer Structure.id or String Structure.acronym.
				injection_hemisphere : string, optional
					'right' or 'left', Defaults to both hemispheres.
				target_hemisphere : string, optional
					'right' or 'left', Defaults to both hemispheres.
				transgenic_lines : list of integers or strings, optional
					Integer TransgenicLine.id or String TransgenicLine.name. Specify ID 0 to exclude all TransgenicLines.
				injection_domain : list of integers or strings, optional
					Integer Structure.id or String Structure.acronym.
				primary_structure_only : boolean, optional
				product_ids : list of integers, optional
					Integer Product.id
				start_row : integer, optional
					For paging purposes. Defaults to 0.
				num_rows : integer, optional
					For paging purposes. Defaults to 2000.

		"""
		transgenic_id = kwargs.pop('transgenic_id', 0) # id = 0 means use only wild type
		primary_structure_only = kwargs.pop('primary_structure_only', True)

		if not isinstance(SOI, list): SOI = [SOI]

		if source:
			injection_structures=SOI
			target_domain = None
		else:
			injection_structures = None
			target_domain = SOI

		return pd.DataFrame(self.mca.experiment_source_search(injection_structures=injection_structures,
											target_domain = target_domain,
											transgenic_lines=transgenic_id,
											primary_structure_only=primary_structure_only))

	def experiments_target_search(self, *args, **kwargs):
		"""

		:param *args: 
		:param **kwargs: 

		"""
		return self.experiments_source_search(*args, source=False, **kwargs)

	def fetch_experiments_data(self, experiments_id, *args, average_experiments=False, **kwargs):
		"""
		Get data and metadata for expeirments in the Allen Mouse Connectome project. 
	
		:param experiments_id: int, list, np.ndarray with ID of experiments whose data need to be fetched
		:param *args: 
		:param average_experiments:  (Default value = False)
		:param **kwargs: 

		"""
		if isinstance(experiments_id, np.ndarray):
			experiments_id = [int(x) for x in experiments_id]
		elif not isinstance(experiments_id, list): 
			experiments_id = [experiments_id]
		if [x for x in experiments_id if not isinstance(x, int)]:
			raise ValueError("Invalid experiments_id argument: {}".format(experiments_id))

		default_structures_ids = self.structures.id.values


		is_injection = kwargs.pop('is_injection', False) # Include only structures that are not injection
		structure_ids = kwargs.pop('structure_ids', default_structures_ids) # Pass IDs of structures of interest 
		hemisphere_ids= kwargs.pop('hemisphere_ids', None) # 1 left, 2 right, 3 both

		if not average_experiments:
			return pd.DataFrame(self.mca.get_structure_unionizes(experiments_id,
												is_injection = is_injection,
												structure_ids = structure_ids,
												hemisphere_ids = hemisphere_ids))
		else:
			raise NotImplementedError("Need to find a way to average across experiments")
			unionized = pd.DataFrame(self.mca.get_structure_unionizes(experiments_id,
												is_injection = is_injection,
												structure_ids = structure_ids,
												hemisphere_ids = hemisphere_ids))

		for regionid in list(set(unionized.structure_id)):
			region_avg = unionized.loc[unionized.structure_id == regionid].mean(axis=1)

	####### ANALYSIS ON EXPERIMENTAL DATA
	def analyze_efferents(self, ROI, projection_metric = None):
		"""
		Loads the experiments on ROI and looks at average statistics of efferent projections

		:param ROI: str, acronym of brain region of interest
		:param projection_metric: if None, the default projection metric is used, otherwise pass a string with metric to use (Default value = None)

		"""
		if projection_metric is None: 
			projection_metric = self.projection_metric

		experiment_data = pd.read_pickle(os.path.join(self.output_data, "{}.pkl".format(ROI)))
		experiment_data = experiment_data.loc[experiment_data.volume > self.volume_threshold]

		# Loop over all structures and get the injection density
		results = {"left":[], "right":[], "both":[], "id":[], "acronym":[], "name":[]}
		for target in self.structures.id.values:
			target_acronym = self.structures.loc[self.structures.id == target].acronym.values[0]
			target_name = self.structures.loc[self.structures.id == target].name.values[0]

			exp_target = experiment_data.loc[experiment_data.structure_id == target]

			exp_target_hemi = self.hemispheres(exp_target.loc[exp_target.hemisphere_id == 1], 
												exp_target.loc[exp_target.hemisphere_id == 2], 
												exp_target.loc[exp_target.hemisphere_id == 3])
			proj_energy = self.hemispheres(np.nanmean(exp_target_hemi.left[projection_metric].values),
											np.nanmean(exp_target_hemi.right[projection_metric].values),
											np.nanmean(exp_target_hemi.both[projection_metric].values)
			)


			for hemi in self.hemispheres_names:
				results[hemi].append(proj_energy._asdict()[hemi])
			results["id"].append(target)
			results["acronym"].append(target_acronym)
			results["name"].append(target_name)

		results = pd.DataFrame.from_dict(results).sort_values("right", na_position = "first")
		return results

	def analyze_afferents(self, ROI, projection_metric = None):
		"""[Loads the experiments on ROI and looks at average statistics of afferent projections]

		:param ROI: str, acronym of region of itnerest
		:param projection_metric: if None, the default projection metric is used, otherwise pass a string with metric to use (Default value = None)

		"""
		if projection_metric is None: 
			projection_metric = self.projection_metric
		ROI_id = self.structure_tree.get_structures_by_acronym([ROI])[0]["id"]

		# Loop over all strctures and get projection towards SOI
		results = {"left":[], "right":[], "both":[], "id":[], "acronym":[], "name":[]}

		for origin in self.structures.id.values:
			origin_acronym = self.structures.loc[self.structures.id == origin].acronym.values[0]
			origin_name = self.structures.loc[self.structures.id == origin].name.values[0]

			experiment_data = pd.read_pickle(os.path.join(self.output_data, "{}.pkl".format(origin_acronym)))
			experiment_data = experiment_data.loc[experiment_data.volume > self.volume_threshold]

			exp_target = experiment_data.loc[experiment_data.structure_id == SOI_id]
			exp_target_hemi = self.hemispheres(exp_target.loc[exp_target.hemisphere_id == 1], exp_target.loc[exp_target.hemisphere_id == 2], exp_target.loc[exp_target.hemisphere_id == 3])
			proj_energy = self.hemispheres(np.nanmean(exp_target_hemi.left[projection_metric].values),
											np.nanmean(exp_target_hemi.right[projection_metric].values),
											np.nanmean(exp_target_hemi.both[projection_metric].values)
			)
			for hemi in self.hemispheres_names:
				results[hemi].append(proj_energy._asdict()[hemi])
			results["id"].append(origin)
			results["acronym"].append(origin_acronym)
			results["name"].append(origin_name)

		results = pd.DataFrame.from_dict(results).sort_values("right", na_position = "first")
		return results

	####### GET TRACTOGRAPHY AND SPATIAL DATA
	def get_projection_tracts_to_target(self, p0=None, **kwargs):
		"""
		Gets tractography data for all experiments whose projections reach the brain region or location of iterest.
		
		:param p0: list of 3 floats with XYZ coordinates of point to be used as seed (Default value = None)
		:param **kwargs: 
		"""

		# check args
		if p0 is None:
			raise ValueError("Please pass coordinates")
		elif isinstance(p0, np.ndarray):
			p0 = list(p0)
		elif not isinstance(p0, (list, tuple)):
			raise ValueError("Invalid argument passed (p0): {}".format(p0))

		tract = self.mca.experiment_spatial_search(seed_point=p0, **kwargs)

		if isinstance(tract, str): 
			raise ValueError('Something went wrong with query, query error message:\n{}'.format(tract))
		else:
			return tract

	### OPERATIONS ON STRUCTURE TREES
	def get_structure_ancestors(self, regions, ancestors=True, descendants=False):
		"""
		Get's the ancestors of the region(s) passed as arguments

		:param regions: str, list of str with acronums of regions of interest
		:param ancestors: if True, returns the ancestors of the region  (Default value = True)
		:param descendants: if True, returns the descendants of the region (Default value = False)

		"""

		if not isinstance(regions, list):
			struct_id = self.structure_tree.get_structures_by_acronym([regions])[0]['id']
			return pd.DataFrame(self.tree_search.get_tree('Structure', struct_id, ancestors=ancestors, descendants=descendants))
		else:
			ancestors = []
			for region in regions:
				struct_id = self.structure_tree.get_structures_by_acronym([region])[0]['id']
				ancestors.append(pd.DataFrame(self.tree_search.get_tree('Structure', struct_id, ancestors=ancestors, descendants=descendants)))
			return ancestors

	def get_structure_descendants(self, regions):
		return self.get_structure_ancestors(regions, ancestors=False, descendants=True)

	def get_structure_from_coordinates(self, p0):
		"""
		Given a point in the Allen Mouse Brain reference space, returns the brain region that the point is in. 

		:param p0: list of floats with XYZ coordinates. 

		"""
		voxel = np.round(np.array(p0) / self.resolution).astype(int)
		try:
			structure_id = self.annotated_volume[voxel[0], voxel[1], voxel[2]]
		except:
			return None

		# Each voxel in the annotation volume is annotated as specifically as possible
		structure = self.structure_tree.get_structures_by_id([structure_id])[0]
		return structure
class ExperimentImagesPredictor(DirWatcher):
    def __init__(self, input_dir, process_dir, output_dir, structure_map_dir,
                 parent_structs, connectivity_dir, _processor_number,
                 cell_model, crop_size, border_size, device, threshold):
        super().__init__(input_dir, process_dir, output_dir,
                         f'experiment-images-predictor-{_processor_number}')
        self.threshold = threshold
        self.device = device
        if device == 'cuda:':
            self.device += str(_processor_number)
        self.border_size = border_size
        self.crop_size = crop_size
        self.cell_model = cell_model
        self.parent_structs = parent_structs
        self.segmentation_dir = structure_map_dir
        self.mcc = MouseConnectivityCache(
            manifest_file=f'{connectivity_dir}/mouse_connectivity_manifest.json'
        )
        struct_tree = self.mcc.get_structure_tree()
        structure_ids = [
            i for sublist in struct_tree.descendant_ids(self.parent_structs)
            for i in sublist
        ]
        self.structure_ids = set(structure_ids)
        self.bbox_dilation_kernel = cv2.getStructuringElement(
            cv2.MORPH_ELLIPSE, (14, 14))
        self.init_model()

    def init_model(self):
        cfg = get_cfg()
        cfg.merge_from_file(
            model_zoo.get_config_file(
                "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
        cfg.MODEL.DEVICE = self.device
        cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = self.threshold
        cfg.MODEL.WEIGHTS = self.cell_model
        cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1
        self.cell_model = DefaultPredictor(cfg)

    def process_item(self, item, directory):
        experiment_id = int(item)
        segmentation = np.load(
            f'{self.segmentation_dir}/{item}/{item}-sections.npz')['arr_0']
        mask = np.isin(segmentation, list(self.structure_ids))
        with open(f'{directory}/bboxes.pickle', 'rb') as f:
            bboxes = pickle.load(f)
        sections = sorted([s for s in bboxes.keys() if bboxes[s]])
        for section in sorted(sections):
            self.process_section(directory, experiment_id, section,
                                 bboxes[section], mask[:, :, section])

    def process_section(self, directory, experiment_id, section, bboxes, mask):
        self.logger.info(
            f"Experiment {experiment_id}: processing section {section}...")
        for bbox in bboxes:
            x, y, w, h = bbox.scale(64)
            cellmask_fname = f'{directory}/cellmask-{experiment_id}-{section}-{x}_{y}_{w}_{h}.png'
            if not os.path.isfile(cellmask_fname):
                image = cv2.imread(
                    f'{directory}/full-{experiment_id}-{section}-{x}_{y}_{w}_{h}.jpg',
                    cv2.IMREAD_GRAYSCALE)
                img_mask = self.predict_cells(image, mask, x, y)
                cv2.imwrite(
                    cellmask_fname,
                    np.stack([
                        np.zeros_like(img_mask), img_mask,
                        np.zeros_like(img_mask)
                    ],
                             axis=2))
            else:
                self.logger.info(
                    f"{cellmask_fname} already exists, skipping segmentation..."
                )

    def predict_cells(self, image, section_mask, x, y):
        crops = create_crops_list(self.border_size, self.crop_size, image)
        cell_mask = np.zeros_like(image)
        mask_basex, mask_basey, mask_crop_size = map(lambda v: v // 64,
                                                     [x, y, self.crop_size])
        for crop, coords in crops:
            ym, xm = coords[0] // 64 + mask_basey, coords[1] // 64 + mask_basex
            if section_mask[ym:min(ym + mask_crop_size +
                                   1, section_mask.shape[0] - 1),
                            xm:min(xm + mask_crop_size +
                                   1, section_mask.shape[1] - 1)].sum() > 0:
                outputs = self.cell_model(
                    cv2.cvtColor(
                        image[coords[0]:coords[0] + self.crop_size,
                              coords[1]:coords[1] + self.crop_size],
                        cv2.COLOR_GRAY2BGR))
                _, mask = extract_predictions(outputs["instances"].to("cpu"))
                if mask is not None:
                    cell_mask[coords[0]: coords[0] + self.crop_size, coords[1]: coords[1] + self.crop_size] = \
                        np.logical_or(cell_mask[coords[0]: coords[0] + self.crop_size,
                                      coords[1]: coords[1] + self.crop_size], mask)

        ctrs, _ = cv2.findContours(cell_mask, cv2.RETR_EXTERNAL,
                                   cv2.CHAIN_APPROX_SIMPLE)
        mask = np.zeros_like(cell_mask)
        cv2.fillPoly(mask, ctrs, color=255)
        ctrs, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
                                   cv2.CHAIN_APPROX_SIMPLE)
        mask = np.zeros_like(cell_mask)
        cv2.polylines(mask, ctrs, isClosed=True, color=255)
        return mask
Пример #19
0
# The manifest file is a simple JSON file that keeps track of all of
# the data that has already been downloaded onto the hard drives.
# If you supply a relative path, it is assumed to be relative to your
# current working directory.
mcc = MouseConnectivityCache(
    manifest_file='connectivity/mouse_connectivity_manifest.json')

# open up a list of all of the experiments
all_experiments = mcc.get_experiments(dataframe=True)
print("{} total experiments".format(len(all_experiments)))

# take a look at what we know about an experiment with a primary motor injection
print(all_experiments.loc[122642490])

# grab the StructureTree instance
structure_tree = mcc.get_structure_tree()

print(structure_tree)

from allensdk.api.queries.ontologies_api import OntologiesApi

oapi = OntologiesApi()

# get the ids of all the structure sets in the tree
structure_set_ids = structure_tree.get_structure_sets()

# query the API for information on those structure sets
#print(oapi.get_structure_sets(structure_set_ids))

#
#structures = structure_tree.get_structures_by_set_id([167587189])
Пример #20
0
class ABA(Atlas):
    """
    This class handles interaction with the Allen Brain Atlas datasets and APIs to get structure trees,
    experimental metadata and results, tractography data etc. 
    """
    ignore_regions = ['retina', 'brain', 'fiber tracts', 'grey'] # ignored when rendering

    # useful vars for analysis    
    excluded_regions = ["fiber tracts"]
    resolution = 25

    _root_bounds = [[-17, 13193], 
                   [ 134, 7564], 
                    [486, 10891]]

    _root_midpoint = [np.mean([-17, 13193]), 
                        np.mean([134, 7564]),
                        np.mean([486, 10891])]

    atlas_name = "ABA"
    mesh_format = 'obj'

    base_url = "https://neuroinformatics.nl/HBP/allen-connectivity-viewer/json/streamlines_NNN.json.gz"
    # Used for streamlines

    def __init__(self,  base_dir=None, **kwargs):
        """ 
        Set up file paths and Allen SDKs
        
        :param base_dir: path to directory to use for saving data (default value None)
        :param kwargs: can be used to pass path to individual data folders. See brainrender/Utils/paths_manager.py

        """

        Atlas.__init__(self, base_dir=base_dir, **kwargs)
        self.meshes_folder = self.mouse_meshes # where the .obj mesh for each region is saved

        # get mouse connectivity cache and structure tree
        self.mcc = MouseConnectivityCache(manifest_file=os.path.join(self.mouse_connectivity_cache, "manifest.json"))
        self.structure_tree = self.mcc.get_structure_tree()
        
        # get ontologies API and brain structures sets
        self.oapi = OntologiesApi()
        self.get_structures_sets()

        # get reference space
        self.space = ReferenceSpaceApi()
        self.spacecache = ReferenceSpaceCache(
            manifest=os.path.join(self.annotated_volume_fld, "manifest.json"),  # downloaded files are stored relative to here
            resolution=self.resolution,
            reference_space_key="annotation/ccf_2017"  # use the latest version of the CCF
            )
        self.annotated_volume, _ = self.spacecache.get_annotation_volume()

        # mouse connectivity API [used for tractography]
        self.mca = MouseConnectivityApi()

        # Get tree search api
        self.tree_search = TreeSearchApi()

        # Store all regions metadata [If there's internet connection]
        if self.other_sets is not None: 
            self.regions = self.other_sets["Structures whose surfaces are represented by a precomputed mesh"].sort_values('acronym')
            self.region_acronyms = list(self.other_sets["Structures whose surfaces are represented by a precomputed mesh"].sort_values(
                                                'acronym').acronym.values)

    # ---------------------------------------------------------------------------- #
    #                       Methods to support Scene creation                      #
    # ---------------------------------------------------------------------------- #
    """
        These methods are used by brainrender.scene to populate a scene using
        the Allen brain atlas meshes. They overwrite methods of the base atlas class
    """

    # ------------------------- Getting elements for scene ------------------------- #
    def get_brain_regions(self, brain_regions, VIP_regions=None, VIP_color=None,
                        add_labels=False,
                        colors=None, use_original_color=True, 
                        alpha=None, hemisphere=None, verbose=False, **kwargs):

        """
            Gets brain regions meshes for rendering
            Many parameters can be passed to specify how the regions should be rendered.
            To treat a subset of the rendered regions, specify which regions are VIP. 
            Use the kwargs to specify more detailes on how the regins should be rendered (e.g. wireframe look)

            :param brain_regions: str list of acronyms of brain regions
            :param VIP_regions: if a list of brain regions are passed, these are rendered differently compared to those in brain_regions (Default value = None)
            :param VIP_color: if passed, this color is used for the VIP regions (Default value = None)
            :param colors: str, color of rendered brian regions (Default value = None)
            :param use_original_color: bool, if True, the allen's default color for the region is used.  (Default value = False)
            :param alpha: float, transparency of the rendered brain regions (Default value = None)
            :param hemisphere: str (Default value = None)
            :param add_labels: bool (default False). If true a label is added to each regions' actor. The label is visible when hovering the mouse over the actor
            :param **kwargs: used to determine a bunch of thigs, including the look and location of lables from scene.add_labels
        """
        # Check that the atlas has brain regions data
        if self.region_acronyms is None:
            print(f"The atlas {self.atlas_name} has no brain regions data")
            return

        # Parse arguments
        if VIP_regions is None:
            VIP_regions = brainrender.DEFAULT_VIP_REGIONS
        if VIP_color is None:
            VIP_color = brainrender.DEFAULT_VIP_COLOR
        if alpha is None:
            _alpha = brainrender.DEFAULT_STRUCTURE_ALPHA
        else: _alpha = alpha

        # check that we have a list
        if not isinstance(brain_regions, list):
            brain_regions = [brain_regions]

        # check the colors input is correct
        if colors is not None:
            if isinstance(colors[0], (list, tuple)):
                if not len(colors) == len(brain_regions): 
                    raise ValueError("when passing colors as a list, the number of colors must match the number of brain regions")
                for col in colors:
                    if not check_colors(col): raise ValueError("Invalide colors in input: {}".format(col))
            else:
                if not check_colors(colors): raise ValueError("Invalide colors in input: {}".format(colors))
                colors = [colors for i in range(len(brain_regions))]

        # loop over all brain regions
        actors = {}
        for i, region in enumerate(brain_regions):
            self._check_valid_region_arg(region)

            if region in self.ignore_regions: continue
            if verbose: print("Rendering: ({})".format(region))

            # get the structure and check if we need to download the object file
            if region not in self.region_acronyms:
                print(f"The region {region} doesn't seem to belong to the atlas being used: {self.atlas_name}. Skipping")
                continue

            obj_file = os.path.join(self.meshes_folder, "{}.{}".format(region, self.mesh_format))
            if not self._check_obj_file(region, obj_file):
                print("Could not render {}, maybe we couldn't get the mesh?".format(region))
                continue

            # check which color to assign to the brain region
            if use_original_color:
                color = [x/255 for x in self.get_region_color(region)]
            else:
                if region in VIP_regions:
                    color = VIP_color
                else:
                    if colors is None:
                        color = brainrender.DEFAULT_STRUCTURE_COLOR
                    elif isinstance(colors, list):
                        color = colors[i]
                    else: 
                        color = colors

            if region in VIP_regions:
                alpha = 1
            else:
                alpha = _alpha

            # Load the object file as a mesh and store the actor
            if hemisphere is not None:
                if hemisphere.lower() == "left" or hemisphere.lower() == "right":
                    obj = self.get_region_unilateral(region, hemisphere=hemisphere, color=color, alpha=alpha)
                else:
                    raise ValueError(f'Invalid hemisphere argument: {hemisphere}')
            else:
                obj = load(obj_file, c=color, alpha=alpha)

            if obj is not None:
                actors_funcs.edit_actor(obj, **kwargs)

                actors[region] = obj
            else:
                print(f"Something went wrong while loading mesh data for {region}")

        return actors

    def get_neurons(self, neurons, color=None, display_axon=True, display_dendrites=True,
                alpha=1, neurite_radius=None):
        """
        Gets rendered morphological data of neurons reconstructions downloaded from the
        Mouse Light project at Janelia (or other sources). 
        Accepts neurons argument as:
            - file(s) with morphological data
            - vtkplotter mesh actor(s) of entire neurons reconstructions
            - dictionary or list of dictionary with actors for different neuron parts

        :param neurons: str, list, dict. File(s) with neurons data or list of rendered neurons.
        :param display_axon, display_dendrites: if set to False the corresponding neurite is not rendered
        :param color: default None. Can be:
                - None: each neuron is given a random color
                - color: rbg, hex etc. If a single color is passed all neurons will have that color
                - cmap: str with name of a colormap: neurons are colored based on their sequential order and cmap
                - dict: a dictionary specifying a color for soma, dendrites and axon actors, will be the same for all neurons
                - list: a list of length = number of neurons with either a single color for each neuron
                        or a dictionary of colors for each neuron
        :param alpha: float in range 0,1. Neurons transparency
        :param neurite_radius: float > 0 , radius of tube actor representing neurites
        """

        if not isinstance(neurons, (list, tuple)):
            neurons = [neurons]

        # ------------------------------ Prepare colors ------------------------------ #
        N = len(neurons)
        colors = dict(
            soma = None,
            axon = None,
            dendrites = None,
        )

        # If no color is passed, get random colors
        if color is None:
            cols = get_random_colors(N)
            colors = dict(
                soma = cols.copy(),
                axon = cols.copy(),
                dendrites = cols.copy(),)
        else:
            if isinstance(color, str):
                # Deal with a a cmap being passed
                if color in _mapscales_cmaps:
                    cols = [colorMap(n, name=color, vmin=-2, vmax=N+2) for n in np.arange(N)]
                    colors = dict(
                        soma = cols.copy(),
                        axon = cols.copy(),
                        dendrites = cols.copy(),)

                else:
                    # Deal with a single color being passed
                    cols = [getColor(color) for n in np.arange(N)]
                    colors = dict(
                        soma = cols.copy(),
                        axon = cols.copy(),
                        dendrites = cols.copy(),)
            elif isinstance(color, dict):
                # Deal with a dictionary with color for each component
                if not 'soma' in color.keys():
                    raise ValueError(f"When passing a dictionary as color argument, \
                                                soma should be one fo the keys: {color}")
                dendrites_color = color.pop('dendrites', color['soma'])
                axon_color = color.pop('axon', color['soma'])

                colors = dict(
                        soma = [color['soma'] for n in np.arange(N)],
                        axon = [axon_color for n in np.arange(N)],
                        dendrites = [dendrites_color for n in np.arange(N)],)
                        
            elif isinstance(color, (list, tuple)):
                # Check that the list content makes sense
                if len(color) != N:
                    raise ValueError(f"When passing a list of color arguments, the list length"+
                                f" ({len(color)}) should match the number of neurons ({N}).")
                if len(set([type(c) for c in color])) > 1:
                    raise ValueError(f"When passing a list of color arguments, all list elements"+
                                " should have the same type (e.g. str or dict)")

                if isinstance(color[0], dict):
                    # Deal with a list of dictionaries
                    soma_colors, dendrites_colors, axon_colors = [], [], []

                    for col in colors:
                        if not 'soma' in col.keys():
                            raise ValueError(f"When passing a dictionary as col argument, \
                                                        soma should be one fo the keys: {col}")
                        dendrites_colors.append(col.pop('dendrites', col['soma']))
                        axon_colors.append(col.pop('axon', col['soma']))
                        soma_colors.append(col['soma'])

                    colors = dict(
                        soma = soma_colors,
                        axon = axon_colors,
                        dendrites = dendrites_colors,)

                else:
                    # Deal with a list of colors
                    colors = dict(
                        soma = color.copy(),
                        axon = color.copy(),
                        dendrites = color.copy(),)
            else:
                raise ValueError(f"Color argument passed is not valid. Should be a \
                                        str, dict, list or None, not {type(color)}:{color}")

        # Check colors, if everything went well we should have N colors per entry
        for k,v in colors.items():
            if len(v) != N:
                raise ValueError(f"Something went wrong while preparing colors. Not all \
                                entries have right length. We got: {colors}")



        # ---------------------------------- Render ---------------------------------- #
        _neurons_actors = []
        for neuron in neurons:
            neuron_actors = {'soma':None, 'dendrites':None, 'axon': None}
            
            # Deal with neuron as filepath
            if isinstance(neuron, str):
                if os.path.isfile(neuron):
                    if neuron.endswith('.swc'):
                        neuron_actors, _ = get_neuron_actors_with_morphapi(swcfile=neuron, neurite_radius=neurite_radius)
                    else:
                        raise NotImplementedError('Currently we can only parse morphological reconstructions from swc files')
                else:
                    raise ValueError(f"Passed neruon {neuron} is not a valid input. Maybe the file doesn't exist?")
            
            # Deal with neuron as single actor
            elif isinstance(neuron, Actor):
                # A single actor was passed, maybe it's the entire neuron
                neuron_actors['soma'] = neuron # store it as soma anyway
                pass

            # Deal with neuron as dictionary of actor
            elif isinstance(neuron, dict):
                neuron_actors['soma'] = neuron.pop('soma', None)
                neuron_actors['axon'] = neuron.pop('axon', None)

                # Get dendrites actors
                if 'apical_dendrites' in neuron.keys() or 'basal_dendrites' in neuron.keys():
                    if 'apical_dendrites' not in neuron.keys():
                        neuron_actors['dendrites'] = neuron['basal_dendrites']
                    elif 'basal_dendrites' not in neuron.keys():
                        neuron_actors['dendrites'] = neuron['apical_dendrites']
                    else:
                        neuron_ctors['dendrites'] = merge(neuron['apical_dendrites'], neuron['basal_dendrites'])
                else:
                    neuron_actors['dendrites'] = neuron.pop('dendrites', None)
            
            # Deal with neuron as instance of Neuron from morphapi
            elif isinstance(neuron, Neuron):
                neuron_actors, _ = get_neuron_actors_with_morphapi(neuron=neuron)                
            # Deal with other inputs
            else:
                raise ValueError(f"Passed neuron {neuron} is not a valid input")

            # Check that we don't have anything weird in neuron_actors
            for key, act in neuron_actors.items():
                if act is not None:
                    if not isinstance(act, Actor):
                        raise ValueError(f"Neuron actor {key} is {act.__type__} but should be a vtkplotter Mesh. Not: {act}")

            if not display_axon:
                neuron_actors['axon'] = None
            if not display_dendrites:
                neuron_actors['dendrites'] = None
            _neurons_actors.append(neuron_actors)

        # Color actors
        for n, neuron in enumerate(_neurons_actors):
            if neuron['axon'] is not None:
                neuron['axon'].c(colors['axon'][n])
            neuron['soma'].c(colors['soma'][n])
            if neuron['dendrites'] is not None:
                neuron['dendrites'].c(colors['dendrites'][n])

        # Return
        if len(_neurons_actors) == 1:
            return _neurons_actors[0], None
        elif not _neurons_actors:
            return None, None
        else:
            return _neurons_actors, None

    def get_tractography(self, tractography, color=None,  color_by="manual", others_alpha=1, verbose=True,
                        VIP_regions=[], VIP_color=None, others_color="white", include_all_inj_regions=False,
                        extract_region_from_inj_coords=False, display_injection_volume=True):
        """
        Renders tractography data and adds it to the scene. A subset of tractography data can receive special treatment using the  with VIP regions argument:
        if the injection site for the tractography data is in a VIP regions, this is colored differently.

        :param tractography: list of dictionaries with tractography data
        :param color: color of rendered tractography data

        :param color_by: str, specifies which criteria to use to color the tractography (Default value = "manual")
        :param others_alpha: float (Default value = 1)
        :param verbose: bool (Default value = True)
        :param VIP_regions: list of brain regions with VIP treatement (Default value = [])
        :param VIP_color: str, color to use for VIP data (Default value = None)
        :param others_color: str, color for not VIP data (Default value = "white")
        :param include_all_inj_regions: bool (Default value = False)
        :param extract_region_from_inj_coords: bool (Default value = False)
        :param display_injection_volume: float, if True a spehere is added to display the injection coordinates and volume (Default value = True)
        """

        # check argument
        if not isinstance(tractography, list):
            if isinstance(tractography, dict):
                tractography = [tractography]
            else:
                raise ValueError("the 'tractography' variable passed must be a list of dictionaries")
        else:
            if not isinstance(tractography[0], dict):
                raise ValueError("the 'tractography' variable passed must be a list of dictionaries")

        if not isinstance(VIP_regions, list):
            raise ValueError("VIP_regions should be a list of acronyms")

        # check coloring mode used and prepare a list COLORS to use for coloring stuff
        if color_by == "manual":
            # check color argument
            if color is None:
                color = TRACT_DEFAULT_COLOR
                COLORS = [color for i in range(len(tractography))]
            elif isinstance(color, list):
                if not len(color) == len(tractography):
                    raise ValueError("If a list of colors is passed, it must have the same number of items as the number of tractography traces")
                else:
                    for col in color:
                        if not check_colors(col): raise ValueError("Color variable passed to tractography is invalid: {}".format(col))

                    COLORS = color
            else:
                if not check_colors(color):
                    raise ValueError("Color variable passed to tractography is invalid: {}".format(color))
                else:
                    COLORS = [color for i in range(len(tractography))]

        elif color_by == "region":
            COLORS = [self.get_region_color(t['structure-abbrev']) for t in tractography]

        elif color_by == "target_region":
            if VIP_color is not None:
                if not check_colors(VIP_color) or not check_colors(others_color):
                    raise ValueError("Invalid VIP or other color passed")
                try:
                    if include_all_inj_regions:
                        COLORS = [VIP_color if is_any_item_in_list( [x['abbreviation'] for x in t['injection-structures']], VIP_regions)\
                            else others_color for t in tractography]
                    else:
                        COLORS = [VIP_color if t['structure-abbrev'] in VIP_regions else others_color for t in tractography]
                except:
                    raise ValueError("Something went wrong while getting colors for tractography")
            else:
                COLORS = [self.get_region_color(t['structure-abbrev']) if t['structure-abbrev'] in VIP_regions else others_color for t in tractography]
        else:
            raise ValueError("Unrecognised 'color_by' argument {}".format(color_by))

        # add actors to represent tractography data
        actors, structures_acronyms = [], []
        if VERBOSE and verbose:
            print("Structures found to be projecting to target: ")

        # Loop over injection experiments
        for i, (t, color) in enumerate(zip(tractography, COLORS)):
            # Use allen metadata
            if include_all_inj_regions:
                inj_structures = [x['abbreviation'] for x in t['injection-structures']]
            else:
                inj_structures = [self.get_structure_parent(t['structure-abbrev'])['acronym']]

            if VERBOSE and verbose and not is_any_item_in_list(inj_structures, structures_acronyms):
                print("     -- ({})".format(t['structure-abbrev']))
                structures_acronyms.append(t['structure-abbrev'])

            # get tractography points and represent as list
            if color_by == "target_region" and not is_any_item_in_list(inj_structures, VIP_regions):
                alpha = others_alpha
            else:
                alpha = TRACTO_ALPHA

            if alpha == 0:
                continue # skip transparent ones

            # check if we need to manually check injection coords
            if extract_region_from_inj_coords:
                try:
                    region = self.get_structure_from_coordinates(t['injection-coordinates'], 
                                                            just_acronym=False)
                    if region is None: continue
                    inj_structures = [self.get_structure_parent(region['acronym'])['acronym']]
                except:
                    raise ValueError(self.get_structure_from_coordinates(t['injection-coordinates'], 
                                                            just_acronym=False))
                if inj_structures is None: continue
                elif isinstance(extract_region_from_inj_coords, list):
                    # check if injection coord are in one of the brain regions in list, otherwise skip
                    if not is_any_item_in_list(inj_structures, extract_region_from_inj_coords):
                        continue

            # represent injection site as sphere
            if display_injection_volume:
                actors.append(shapes.Sphere(pos=t['injection-coordinates'],
                                c=color, r=INJECTION_VOLUME_SIZE*t['injection-volume'], alpha=TRACTO_ALPHA))

            points = [p['coord'] for p in t['path']]
            actors.append(shapes.Tube(points, r=TRACTO_RADIUS, c=color, alpha=alpha, res=TRACTO_RES))

        return actors

    def get_streamlines(self, sl_file, *args, colorby=None, color_each=False,  **kwargs):
        """
        Render streamline data downloaded from https://neuroinformatics.nl/HBP/allen-connectivity-viewer/streamline-downloader.html

        :param sl_file: path to JSON file with streamliens data [or list of files]
        :param colorby: str,  criteria for how to color the streamline data (Default value = None)
        :param color_each: bool, if True, the streamlines for each injection is colored differently (Default value = False)
        :param *args:
        :param **kwargs:

        """
        color = None
        if not color_each:
            if colorby is not None:
                try:
                    color = self.structure_tree.get_structures_by_acronym([colorby])[0]['rgb_triplet']
                    if "color" in kwargs.keys():
                        del kwargs["color"]
                except:
                    raise ValueError("Could not extract color for region: {}".format(colorby))
        else:
            if colorby is not None:
                color = kwargs.pop("color", None)
                try:
                    get_n_shades_of(color, 1)
                except:
                    raise ValueError("Invalide color argument: {}".format(color))

        if not isinstance(sl_file, (list, tuple)):
            sl_file = [sl_file]

        actors = []
        if isinstance(sl_file[0], (str, pd.DataFrame)): # we have a list of files to add
            for slf in tqdm(sl_file):
                if not color_each:
                    if color is not None:
                        if isinstance(slf, str):
                            streamlines = parse_streamline(filepath=slf, *args, color=color, **kwargs)
                        else:
                            streamlines = parse_streamline(data=slf, *args, color=color, **kwargs)
                    else:
                        if isinstance(slf, str):
                            streamlines = parse_streamline(filepath=slf, *args, **kwargs)
                        else:
                            streamlines = parse_streamline(data=slf,  *args, **kwargs)
                else:
                    if color is not None:
                        col = get_n_shades_of(color, 1)[0]
                    else:
                        col = get_random_colors(n_colors=1)
                    if isinstance(slf, str):
                        streamlines = parse_streamline(filepath=slf, color=col, *args, **kwargs)
                    else:
                        streamlines = parse_streamline(data= slf, color=col, *args, **kwargs)
                actors.extend(streamlines)
        else:
            raise ValueError("unrecognized argument sl_file: {}".format(sl_file))

        return actors
     
    def get_injection_sites(self, experiments, color=None):
        """
        Creates Spherse at the location of injections with a volume proportional to the injected volume

        :param experiments: list of dictionaries with tractography data
        :param color:  (Default value = None)

        """
        # check arguments
        if not isinstance(experiments, list):
            raise ValueError("experiments must be a list")
        if not isinstance(experiments[0], dict):
            raise ValueError("experiments should be a list of dictionaries")

        #c= cgeck color
        if color is None:
            color = INJECTION_DEFAULT_COLOR

        injection_sites = []
        for exp in experiments:
            injection_sites.append(shapes.Sphere(pos=(exp["injection_x"], exp["injection_y"], exp["injection_z"]),
                    r = INJECTION_VOLUME_SIZE*exp["injection_volume"]*3,
                    c=color
                    ))

        return injection_sites

        
    # ---------------------------------------------------------------------------- #
    #                          STRUCTURE TREE INTERACTION                          #
    # ---------------------------------------------------------------------------- #

    # ------------------------- Get/Print structures sets ------------------------ #

    def get_structures_sets(self):
        """ 
        Get the Allen's structure sets.
        """
        summary_structures = self.structure_tree.get_structures_by_set_id([167587189])  # main summary structures
        summary_structures = [s for s in summary_structures if s["acronym"] not in self.excluded_regions]
        self.structures = pd.DataFrame(summary_structures)

        # Other structures sets
        try:
            all_sets = pd.DataFrame(self.oapi.get_structure_sets())
        except:
            print("Could not retrieve data, possibly because there is no internet connection. Limited functionality available.")
        else:
            sets = ["Summary structures of the pons", "Summary structures of the thalamus", 
                        "Summary structures of the hypothalamus", "List of structures for ABA Fine Structure Search",
                        "Structures representing the major divisions of the mouse brain", "Summary structures of the midbrain", "Structures whose surfaces are represented by a precomputed mesh"]
            self.other_sets = {}
            for set_name in sets:
                set_id = all_sets.loc[all_sets.description == set_name].id.values[0]
                self.other_sets[set_name] = pd.DataFrame(self.structure_tree.get_structures_by_set_id([set_id]))

            self.all_avaliable_meshes = sorted(self.other_sets["Structures whose surfaces are represented by a precomputed mesh"].acronym.values)

    def print_structures_list_to_text(self):
        """ 
        Saves the name of every brain structure for which a 3d mesh (.obj file) is available in a text file.
        """
        s = self.other_sets["Structures whose surfaces are represented by a precomputed mesh"].sort_values('acronym')
        with open('all_regions.txt', 'w') as o:
            for acr, name in zip(s.acronym.values, s['name'].values):
                o.write("({}) -- {}\n".format(acr, name))

    def print_structures(self):
        """ 
        Prints the name of every structure in the structure tree to the console.
        """
        acronyms, names = self.structures.acronym.values, self.structures['name'].values
        sort_idx = np.argsort(acronyms)
        acronyms, names = acronyms[sort_idx], names[sort_idx]
        [print("({}) - {}".format(a, n)) for a,n in zip(acronyms, names)]

    # -------------------------- Parents and descendants ------------------------- #
    def get_structure_ancestors(self, regions, ancestors=True, descendants=False):
        """
        Get's the ancestors of the region(s) passed as arguments

        :param regions: str, list of str with acronums of regions of interest
        :param ancestors: if True, returns the ancestors of the region  (Default value = True)
        :param descendants: if True, returns the descendants of the region (Default value = False)

        """

        if not isinstance(regions, list):
            struct_id = self.structure_tree.get_structures_by_acronym([regions])[0]['id']
            return pd.DataFrame(self.tree_search.get_tree('Structure', struct_id, ancestors=ancestors, descendants=descendants))
        else:
            ancestors = []
            for region in regions:
                struct_id = self.structure_tree.get_structures_by_acronym([region])[0]['id']
                ancestors.append(pd.DataFrame(self.tree_search.get_tree('Structure', struct_id, ancestors=ancestors, descendants=descendants)))
            return ancestors

    def get_structure_descendants(self, regions):
        return self.get_structure_ancestors(regions, ancestors=False, descendants=True)

    def get_structure_parent(self, acronyms):
        """
        Gets the parent of a brain region (or list of regions) from the hierarchical structure of the
        Allen Brain Atals.

        :param acronyms: list of acronyms of brain regions.

        """
        if not isinstance(acronyms, list):
            self._check_valid_region_arg(acronyms)
            s = self.structure_tree.get_structures_by_acronym([acronyms])[0]
            if s['id'] in self.structures.id.values:
                return s
            else:
                return self.get_structure_ancestors(s['acronym']).iloc[-1]
        else:
            parents = []
            for region in acronyms:
                self._check_valid_region_arg(region)
                s = self.structure_tree.get_structures_by_acronym(acronyms)[0]

                if s['id'] in self.structures.id.values:
                    parents.append(s)
                parents.append(self.get_structure_ancestors(s['acronym']).iloc[-1])
            return parents

    
    # ---------------------------------------------------------------------------- #
    #                                     UTILS                                    #
    # ---------------------------------------------------------------------------- #
    def get_hemisphere_from_point(self, point):
        if point[2] < self._root_midpoint[2]:
            return 'left'
        else:
            return 'right'

    def mirror_point_across_hemispheres(self, point):
        delta = point[2] - self._root_midpoint[2]
        point[2] = self._root_midpoint[2] - delta
        return point

    def get_region_color(self, regions):
        """
        Gets the RGB color of a brain region from the Allen Brain Atlas.

        :param regions:  list of regions acronyms.

        """
        if not isinstance(regions, list):
            return self.structure_tree.get_structures_by_acronym([regions])[0]['rgb_triplet']
        else:
            return [self.structure_tree.get_structures_by_acronym([r])[0]['rgb_triplet'] for r in regions]

    def _check_obj_file(self, region, obj_file):
        """
        If the .obj file for a brain region hasn't been downloaded already, this function downloads it and saves it.

        :param region: string, acronym of brain region
        :param obj_file: path to .obj file to save downloaded data.

        """
        # checks if the obj file has been downloaded already, if not it takes care of downloading it
        if not os.path.isfile(obj_file):
            try:
                if isinstance(region, dict):
                    region = region['acronym']
                structure = self.structure_tree.get_structures_by_acronym([region])[0]
            except Exception as e:
                raise ValueError(f'Could not find region with name {region}, got error: {e}')

            try:
                self.space.download_structure_mesh(structure_id = structure["id"],
                                                    ccf_version ="annotation/ccf_2017",
                                                    file_name=obj_file)
                return True
            except:
                print("Could not get mesh for: {}".format(obj_file))
                return False
        else: return True

    def _get_structure_mesh(self, acronym,   **kwargs):
        """
        Fetches the mesh for a brain region from the Allen Brain Atlas SDK.

        :param acronym: string, acronym of brain region
        :param **kwargs:

        """
        structure = self.structure_tree.get_structures_by_acronym([acronym])[0]
        obj_path = os.path.join(self.mouse_meshes, "{}.obj".format(acronym))

        if self._check_obj_file(structure, obj_path):
            mesh = load_mesh_from_file(obj_path, **kwargs)
            return mesh
        else:
            return None

    def get_region_unilateral(self, region, hemisphere="both", color=None, alpha=None):
        """
        Regions meshes are loaded with both hemispheres' meshes by default.
        This function splits them in two.

        :param region: str, actors of brain region
        :param hemisphere: str, which hemisphere to return ['left', 'right' or 'both'] (Default value = "both")
        :param color: color of each side's mesh. (Default value = None)
        :param alpha: transparency of each side's mesh.  (Default value = None)

        """
        if color is None: color = ROOT_COLOR
        if alpha is None: alpha = ROOT_ALPHA
        bilateralmesh = self._get_structure_mesh(region, c=color, alpha=alpha)

        if bilateralmesh is None:
            print(f'Failed to get mesh for {region}, returning None')
            return None

        com = bilateralmesh.centerOfMass()   # this will always give a point that is on the midline
        cut = bilateralmesh.cutWithPlane(origin=com, normal=(0, 0, 1))

        right = bilateralmesh.cutWithPlane( origin=com, normal=(0, 0, 1))
        
        # left is the mirror right # WIP
        com = self.get_region_CenterOfMass('root', unilateral=False)[2]
        left = actors_funcs.mirror_actor_at_point(right.clone(), com, axis='x')

        if hemisphere == "both":
            return left, right
        elif hemisphere == "left": 
            return left 
        else:
            return right


    @staticmethod
    def _check_valid_region_arg(region):
        """
        Check that the string passed is a valid brain region name.

        :param region: string, acronym of a brain region according to the Allen Brain Atlas.

        """
        if not isinstance(region, int) and not isinstance(region, str):
            raise ValueError("region must be a list, integer or string, not: {}".format(type(region)))
        else:
            return True

    def get_hemispere_from_point(self, p0):
        if p0[2] > self._root_midpoint[2]:
            return 'right'
        else:
            return 'left'

    def get_structure_from_coordinates(self, p0, just_acronym=True):
        """
        Given a point in the Allen Mouse Brain reference space, returns the brain region that the point is in. 

        :param p0: list of floats with XYZ coordinates. 

        """
        voxel = np.round(np.array(p0) / self.resolution).astype(int)
        try:
            structure_id = self.annotated_volume[voxel[0], voxel[1], voxel[2]]
        except:
            return None

        # Each voxel in the annotation volume is annotated as specifically as possible
        structure = self.structure_tree.get_structures_by_id([structure_id])[0]
        if structure is not None:
            if just_acronym:
                return structure['acronym']
        return structure
    
    def get_colors_from_coordinates(self, p0):
        """
            Given a point or a list of points returns a list of colors where 
            each item is the color of the brain region each point is in
        """
        if isinstance(p0[0], (float, int)):
            struct = self.get_structure_from_coordinates(p0, just_acronym=False)
            if struct is not None:
                return struct['rgb_triplet']
            else:
                return None
        else:
            structures = [self.get_structure_from_coordinates(p, just_acronym=False) for p in p0]
            colors = [struct['rgb_triplet'] if struct is not None else None 
                            for struct in structures]
            return colors 


    # ---------------------------------------------------------------------------- #
    #                             TRACTOGRAPHY FETCHING                            #
    # ---------------------------------------------------------------------------- #
    def get_projection_tracts_to_target(self, p0=None, **kwargs):
        """
        Gets tractography data for all experiments whose projections reach the brain region or location of iterest.
        
        :param p0: list of 3 floats with XYZ coordinates of point to be used as seed (Default value = None)
        :param **kwargs: 
        """

        # check args
        if p0 is None:
            raise ValueError("Please pass coordinates")
        elif isinstance(p0, np.ndarray):
            p0 = list(p0)
        elif not isinstance(p0, (list, tuple)):
            raise ValueError("Invalid argument passed (p0): {}".format(p0))
        
        p0 = [np.int(p) for p in p0]
        tract = self.mca.experiment_spatial_search(seed_point=p0, **kwargs)

        if isinstance(tract, str): 
            raise ValueError('Something went wrong with query, query error message:\n{}'.format(tract))
        else:
            return tract


    # ---------------------------------------------------------------------------- #
    #                             STREAMLINES FETCHING                             #
    # ---------------------------------------------------------------------------- #
    def download_streamlines_for_region(self, region, *args, **kwargs):
        """
            Using the Allen Mouse Connectivity data and corresponding API, this function finds expeirments whose injections
            were targeted to the region of interest and downloads the corresponding streamlines data. By default, experiements
            are selected for only WT mice and onl when the region was the primary injection target. Look at "ABA.experiments_source_search"
            to see how to change this behaviour.

            :param region: str with region to use for research
            :param *args: arguments for ABA.experiments_source_search
            :param **kwargs: arguments for ABA.experiments_source_search

        """
        # Get experiments whose injections were targeted to the region
        region_experiments = experiments_source_search(self.mca, region, *args, **kwargs)
        try:
            return download_streamlines(region_experiments.id.values, streamlines_folder=self.streamlines_cache)
        except:
            print(f"Could not download streamlines for region {region}")
            return [], [] # <- there were no experiments in the target region 

    def download_streamlines_to_region(self, p0, *args,  mouse_line = "wt", **kwargs):
        """
            Using the Allen Mouse Connectivity data and corresponding API, this function finds injection experiments
            which resulted in fluorescence being found in the target point, then downloads the streamlines data.

            :param p0: list of floats with XYZ coordinates
            :param mouse_line: str with name of the mouse line to use(Default value = "wt")
            :param *args: 
            :param **kwargs: 

        """
        experiments = pd.DataFrame(self.get_projection_tracts_to_target(p0=p0))
        if mouse_line == "wt":
            experiments = experiments.loc[experiments["transgenic-line"] == ""]
        else:
            if not isinstance(mouse_line, list):
                experiments = experiments.loc[experiments["transgenic-line"] == mouse_line]
            else:
                raise NotImplementedError("ops, you've found a bug!. For now you can only pass one mouse line at the time, sorry.")
        return download_streamlines(experiments.id.values, streamlines_folder=self.streamlines_cache)