def __init__(self, *args, scene_kwargs={}, **kwargs): """ Initialise API interaction and fetch metadata of neurons in the Allen Database. """ if not connected_to_internet(): raise ConnectionError( "You will need to be connected to the internet to use the AllenMorphology class" ) Paths.__init__(self, *args, **kwargs) self.scene = Scene(add_root=False, display_inset=False, **scene_kwargs) # Create a Cache for the Cell Types Cache API self.ctc = CellTypesCache( manifest_file=os.path.join(self.morphology_allen, 'manifest.json')) # Get a list of cell metadata for neurons with reconstructions, download if necessary self.neurons = pd.DataFrame( self.ctc.get_cells(species=[CellTypesApi.MOUSE], require_reconstruction=True)) self.n_neurons = len(self.neurons) if not self.n_neurons: raise ValueError( "Something went wrong and couldn't get neurons metadata from Allen" ) self.downloaded_neurons = self.get_downloaded_neurons()
def query_mouselight(query): """ Sends a GET request, not currently used for anything. :param query: """ if not connected_to_internet(): raise ConnectionError("You need an internet connection for API queries, sorry.") base_url = "http://ml-neuronbrowser.janelia.org/" full_query = base_url + query # send the query, package the return argument as a json tree response = requests.get(full_query) if response.ok: json_tree = response.json() if json_tree['success']: return json_tree else: exception_string = 'did not complete api query successfully' else: exception_string = 'API failure. Allen says: {}'.format( response.reason) # raise an exception if the API request failed raise ValueError(exception_string)
def __init__( self, base_dir=None, add_root=True, use_cache=True, scene_kwargs={}, **kwargs, ): """ Initialise the class instance to get a few useful paths and variables. :param base_dir: str, path to base directory in which all of brainrender data are stored. Pass only if you want to use a different one from what's default. :param add_root: bool, if True the root mesh is added to the rendered scene :param use_cache: if true data are loaded from a cache to speed things up. Useful to set it to false to help debugging. :param scene_kwargs: dict, params passed to the instance of Scene associated with this class """ Paths.__init__(self, base_dir=base_dir, **kwargs) # Get MCM cache cache_path = (Path(self.mouse_connectivity_volumetric) / "voxel_model_manifest.json") if not cache_path.exists(): if not connected_to_internet(): raise ValueError( "The first time you use this class it will need to download some data, but it seems that you're not connected to the internet." ) print( "Downloading volumetric data. This will take several minutes but it only needs to be done once." ) self.cache = VoxelModelCache(manifest_file=str(cache_path)) self.voxel_array = None self.target_coords, self.source_coords = None, None # Get projection cache paths self.data_cache = self.mouse_connectivity_volumetric_cache self.data_cache_projections = os.path.join(self.data_cache, "projections") self.data_cache_targets = os.path.join(self.data_cache, "targets") self.data_cache_sources = os.path.join(self.data_cache, "sources") for fold in [ self.data_cache_projections, self.data_cache_targets, self.data_cache_sources, ]: if not os.path.isdir(fold): os.mkdir(fold) # Get structures tree self.structure_tree = self.cache.get_structure_tree() # Get scene self.scene = Scene(add_root=add_root, **scene_kwargs) # Other vars self.use_cache = use_cache
def request(url): """ Sends a request to a url :param url: """ if not connected_to_internet(): raise ConnectionError("You need to have an internet connection to send requests.") response = requests.get(url) if response.ok: return response else: exception_string = 'URL request failed: {}'.format(response.reason) raise ValueError(exception_string)
def post_mouselight(url, query=None, clean=False, attempts=3): """ sends a POST request to a user URL. Query can be either a string (in which case clean should be False) or a dictionary. :param url: :param query: string or dictionary with query (Default value = None) :param clean: if not clean, the query is assumed to be in JSON format (Default value = False) :param attempts: number of attempts (Default value = 3) """ if not connected_to_internet(): raise ConnectionError("You need an internet connection for API queries, sorry.") request = None if query is not None: for i in range(attempts): try: if not clean: time.sleep(0.01) # avoid getting an error from server request = requests.post(url, json={'query': query}) else: time.sleep(0.01) # avoid getting an error from server request = requests.post(url, json=query) except Exception as e: exception = e request = None print('MouseLight API query failed. Attempt {} of {}'.format(i+1, attempts)) if request is not None: break if request is None: raise ConnectionError("\n\nMouseLight API query failed with error message:\n{}.\ \nPerhaps the server is down, visit 'http://ml-neuronbrowser.janelia.org' to find out.".format(exception)) else: raise NotImplementedError if request.status_code == 200: jreq = request.json() if 'data' in list(jreq.keys()): return jreq['data'] else: return jreq else: raise Exception("Query failed to run by returning code of {}. {} -- \n\n{}".format(request.status_code, query, request.text))
def __init__(self): SvgApi.__init__( self ) # https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/api/queries/svg_api.py ImageDownloadApi.__init__( self ) # https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/api/queries/image_download_api.py self.annsetsapi = AnnotatedSectionDataSetsApi( ) # https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/api/queries/annotated_section_data_sets_api.py self.oapi = OntologiesApi( ) # https://github.com/AllenInstitute/AllenSDK/blob/master/allensdk/api/queries/ontologies_api.py # Get metadata about atlases self.atlases = pd.DataFrame(self.oapi.get_atlases_table()) self.atlases_names = sorted(list(self.atlases['name'].values)) self.mouse_coronal_atlas_id = int(self.atlases.loc[ self.atlases['name'] == "Mouse, P56, Coronal"].id.values[0]) self.mouse_sagittal_atlas_id = int(self.atlases.loc[ self.atlases['name'] == "Mouse, P56, Sagittal"].id.values[0]) self.mouse_3D_atlas_id = int(self.atlases.loc[ self.atlases['name'] == "Mouse, Adult, 3D Coronal"].id.values[0]) # Get metadata about products if connected_to_internet(): self.products = pd.DataFrame( send_query( "http://api.brain-map.org/api/v2/data/query.json?criteria=model::Product" )) self.mouse_brain_reference_product_id = 12 self.mouse_brain_ish_data_product_id = 1 self.products_names = sorted(list(self.products["name"].values)) self.mouse_products_names = sorted( list(self.products.loc[self.products.species == "Mouse"] ["name"].values)) else: raise ConnectionError( "It seems that you are not connected to the internet, you won't be able to download stuff." )