"""BrainGlobe model for integration in MagellanMapper"""fromrequests.exceptionsimportChunkedEncodingError,ConnectionErrorimportshutilfromtypingimportCallable,Dict,Optionaltry:frombrainglobe_atlasapiimportbg_atlas,descriptors,list_atlasesexceptImportError:# BrainGlobe Atlas API package was renamed in v2frombg_atlasapiimportbg_atlas,descriptors,list_atlasesfrommagmap.settingsimportconfig_logger=config.logger.getChild(__name__)
[docs]classBrainGlobeMM:"""Model for BrainGlobe-MagellanMapper interactions. Attributes: atlases_avail: Dictionary of the names of available atlases from BrainGlobe to their latest version string. atlases_local: Dictionary of the names of locally downloaded BrainGlobe atlases to their version string. """def__init__(self):self.atlases_avail:Dict[str,str]={}self.atlases_local:Dict[str,str]={}
[docs]defget_avail_atlases(self)->Dict[str,str]:"""Fetch the available atlases from BrainGlobe. Returns: Dictionary of the names of available atlases from BrainGlobe to their latest version string. """try:self.atlases_avail=list_atlases.get_all_atlases_lastversions()exceptConnectionError:_logger.warn("Unable to get BrainGlobe available atlases")returnself.atlases_avail
[docs]defget_local_atlases(self)->Dict[str,str]:"""Get local, downloaded BrainGlobe atlases. Returns: Dictionary of the names of locally downloaded BrainGlobe atlases to their version string. """self.atlases_local={a:list_atlases.get_local_atlas_version(a)forainlist_atlases.get_downloaded_atlases()}returnself.atlases_local
[docs]defget_atlas(self,name:str,download:bool=True,fn_update:Callable[[int,int],None]=None)->Optional[bg_atlas.BrainGlobeAtlas]:"""Get a BrainGlobe atlas. Args: name: Name of atlas to retrieve. download: True to download the atlas if not available locally; False to return None if the atlas is not present. fn_update: Handler for progress updates during atlas download. Returns: The BrainGlobe atlas instance. None if the atlas could not be found or downloaded. """ifnotdownloadandnamenotinself.atlases_local:returnNonetry:try:# get atlas with progress handler using bg-atlasapi > v1.0.2atlas=bg_atlas.BrainGlobeAtlas(name,fn_update=fn_update)exceptTypeError:# fall back to showing a busy progress indicatorfn_update(0,0)atlas=bg_atlas.BrainGlobeAtlas(name)exceptChunkedEncodingErrorase:# download error_logger.error("Error downloading atlas: %s",e)returnNone# add an attribute to store the path to the structures fileatlas.structures_path=atlas.root_dir/descriptors.STRUCTURES_FILENAMEreturnatlas
[docs]defremove_local_atlas(self,name:str):"""Remove local copy of downloaded BrainGlobe atlas. Args: name: Name of atlas to remove """atlas=self.get_atlas(name,False)ifnotatlas:_logger.warn("'%s' atlas not found",name)returntry:ifatlas.root_dir.is_dir():shutil.rmtree(atlas.root_dir)_logger.debug("Removed '%s' atlas from '%s'",name,atlas.root_dir)exceptFileExistsErrorase:_logger.warn(e)