# Licensed under a 3-clause BSD style license - see LICENSE.rstimporthtmlfromcollections.abcimportMutableMappingfromastropy.ioimportfitsfromgammapy.mapsimportMapfromgammapy.utils.scriptsimportmake_path__all__=["Maps"]
[docs]classMaps(MutableMapping):"""A Dictionary containing Map objects sharing the same geometry. This class simplifies handling and I/O of maps collections. For maps with different geometries, use a regular dict. """def__init__(self,**kwargs):self._geom=Noneself._data={}forkey,valueinkwargs.items():self.__setitem__(key,value)@propertydefgeom(self):"""Map geometry as a `~gammapy.maps.Geom` object."""returnself._geomdef__setitem__(self,key,value):ifvalueisnotNoneandnotisinstance(value,Map):raiseValueError(f"MapDict can only contain Map objects, got {type(value)} instead.")# TODO: which loosers criterion to apply? broadcastability?else:self._geom=value.geomself._data[key]=valuedef__getitem__(self,key):returnself._data[key]def__len__(self):"""Returns the length of MapDict."""returnlen(self._data)def__delitem__(self,key):delself._data[key]def__iter__(self):returniter(self._data)def__repr__(self):returnf"{type(self).__name__}({self._data})"def__str__(self):str_=f"{self.__class__.__name__}\n"str_+="-"*len(self.__class__.__name__)+"\n"str_+="\n"str_+=self._geom.__repr__()str_+="\n"forname,valueinself.items():str_+=f"{name}\n"str_+=f"\t unit\t : {value.unit}\n"str_+=f"\t dtype\t : {value.data.dtype}\n"str_+="\n"returnstr_def_repr_html_(self):try:returnself.to_html()exceptAttributeError:returnf"<pre>{html.escape(str(self))}</pre>"
[docs]defto_hdulist(self,hdu_bands="BANDS"):"""Convert map dictionary to list of HDUs. Parameters ---------- hdu_bands : str, optional Name of the HDU with the BANDS table. If set to None, each map will have its own hdu_band. Default is 'BANDS'. Returns ------- hdulist : `~astropy.io.fits.HDUList` Map dataset list of HDUs. """exclude_primary=slice(1,None)hdu_primary=fits.PrimaryHDU()hdulist=fits.HDUList([hdu_primary])forkey,minself.items():hdulist+=m.to_hdulist(hdu=key,hdu_bands=hdu_bands)[exclude_primary]returnhdulist
[docs]@classmethoddeffrom_hdulist(cls,hdulist,hdu_bands="BANDS"):"""Create map dictionary from a HDU list. Because FITS keywords are case-insensitive, all key names will return as lower-case. Parameters ---------- hdulist : `~astropy.io.fits.HDUList` List of HDUs. hdu_bands : str, optional Name of the HDU with the BANDS table. If set to None, each map should have its own hdu_band. Default is 'BANDS'. Returns ------- maps : `~gammapy.maps.Maps` Maps object. """maps=cls()forhduinhdulist:ifhdu.is_imageandhdu.dataisnotNone:map_name=hdu.name.lower()maps[map_name]=Map.from_hdulist(hdulist,hdu=map_name,hdu_bands=hdu_bands)returnmaps
[docs]@classmethoddefread(cls,filename,checksum=False):"""Read map dictionary from file. Because FITS keywords are case-insensitive, all key names will return as lower-case. Parameters ---------- filename : str Filename to read from. Returns ------- maps : `~gammapy.maps.Maps` Maps object. """withfits.open(str(make_path(filename)),memmap=False,checksum=checksum)ashdulist:returncls.from_hdulist(hdulist)
[docs]defwrite(self,filename,overwrite=False,checksum=False):"""Write map dictionary to file. Parameters ---------- filename : str Filename to write to. overwrite : bool, optional Overwrite existing file. Default is False. checksum : bool, optional When True adds both DATASUM and CHECKSUM cards to the headers written to the file. Default is False. """filename=make_path(filename)hdulist=self.to_hdulist()hdulist.writeto(filename,overwrite=overwrite,checksum=checksum)
[docs]@classmethoddeffrom_geom(cls,geom,names,kwargs_list=None):"""Create map dictionary from a geometry. Parameters ---------- geom : `~gammapy.maps.Geom` The input geometry that will be used by all maps. names : list of str The list of all map names. kwargs_list : list of dict the list of arguments to be passed to `~gammapy.maps.Map.from_geom()`. Returns ------- maps : `~gammapy.maps.Maps` Maps object. """mapdict={}ifkwargs_listisNone:kwargs_list=[{}]*len(names)forname,kwargsinzip(names,kwargs_list):mapdict[name]=Map.from_geom(geom,**kwargs)returncls(**mapdict)