def from_hdulist( cls, hdulist, psf_hdu="PSFMAP", psf_hdubands="BANDSPSF", exposure_hdu="EXPMAP", exposure_hdubands="BANDSEXP", ): """Convert to `~astropy.io.fits.HDUList`. Parameters ---------- psf_hdu : str Name or index of the HDU with the psf_map data. psf_hdubands : str Name or index of the HDU with the psf_map BANDS table. exposure_hdu : str Name or index of the HDU with the exposure_map data. exposure_hdubands : str Name or index of the HDU with the exposure_map BANDS table. """ psf_map = Map.from_hdulist(hdulist, psf_hdu, psf_hdubands, "auto") if exposure_hdu in hdulist: exposure_map = Map.from_hdulist( hdulist, exposure_hdu, exposure_hdubands, "auto" ) else: exposure_map = None return cls(psf_map, exposure_map)
def from_hdulist(cls, hdulist, name=""): """Create map dataset from list of HDUs. Parameters ---------- hdulist : `~astropy.io.fits.HDUList` List of HDUs. Returns ------- dataset : `MapDataset` Map dataset. """ kwargs = {"name": name} if "COUNTS" in hdulist: kwargs["counts"] = Map.from_hdulist(hdulist, hdu="counts") if "EXPOSURE" in hdulist: kwargs["exposure"] = Map.from_hdulist(hdulist, hdu="exposure") if "BACKGROUND" in hdulist: background_map = Map.from_hdulist(hdulist, hdu="background") kwargs["background_model"] = BackgroundModel(background_map) if "EDISP_MATRIX" in hdulist: kwargs["edisp"] = EnergyDispersion.from_hdulist( hdulist, hdu1="EDISP_MATRIX", hdu2="EDISP_MATRIX_EBOUNDS" ) if "EDISP" in hdulist: edisp_map = Map.from_hdulist(hdulist, hdu="edisp") exposure_map = Map.from_hdulist(hdulist, hdu="edisp_exposure") kwargs["edisp"] = EDispMap(edisp_map, exposure_map) if "PSF_KERNEL" in hdulist: psf_map = Map.from_hdulist(hdulist, hdu="psf_kernel") kwargs["psf"] = PSFKernel(psf_map) if "PSF" in hdulist: psf_map = Map.from_hdulist(hdulist, hdu="psf") exposure_map = Map.from_hdulist(hdulist, hdu="psf_exposure") kwargs["psf"] = PSFMap(psf_map, exposure_map) if "MASK_SAFE" in hdulist: mask_safe = Map.from_hdulist(hdulist, hdu="mask_safe") mask_safe.data = mask_safe.data.astype(bool) kwargs["mask_safe"] = mask_safe if "MASK_FIT" in hdulist: mask_fit = Map.from_hdulist(hdulist, hdu="mask_fit") mask_fit.data = mask_fit.data.astype(bool) kwargs["mask_fit"] = mask_fit if "GTI" in hdulist: gti = GTI(Table.read(hdulist, hdu="GTI")) kwargs["gti"] = gti return cls(**kwargs)
def from_hdulist(cls, hdulist, hdu_bands=None): """Create flux map dataset from list of HDUs. Parameters ---------- hdulist : `~astropy.io.fits.HDUList` List of HDUs. hdu_bands : str Name of the HDU with the BANDS table. Default is 'BANDS' If set to None, each map should have its own hdu_band Returns ------- flux_maps : `~gammapy.estimators.FluxMaps` Flux maps object. """ try: sed_type = hdulist[0].header["SED_TYPE"] except KeyError: raise ValueError( f"Cannot determine SED type of flux map from primary header.") maps = {} for map_type in REQUIRED_MAPS[sed_type]: maps[map_type] = Map.from_hdulist(hdulist, hdu=map_type, hdu_bands=hdu_bands) for map_type in OPTIONAL_QUANTITIES[ sed_type] + OPTIONAL_QUANTITIES_COMMON: if map_type.upper() in hdulist: maps[map_type] = Map.from_hdulist(hdulist, hdu=map_type, hdu_bands=hdu_bands) filename = hdulist[0].header.get("MODEL", None) if filename: reference_model = Models.read(filename)[0] else: reference_model = None if "GTI" in hdulist: gti = GTI(Table.read(hdulist["GTI"])) else: gti = None return cls.from_dict(maps=maps, sed_type=sed_type, reference_model=reference_model, gti=gti)
def test_map_time_axis_read_write(map_type): time_axis = TimeMapAxis( edges_min=[0, 2, 4] * u.d, edges_max=[1, 3, 5] * u.d, reference_time="2000-01-01", ) energy_axis = MapAxis.from_energy_bounds("1 TeV", "10 TeV", nbin=5) m = Map.create( binsz=0.1, width=10.0, map_type=map_type, skydir=SkyCoord(0.0, 30.0, unit="deg"), axes=[energy_axis, time_axis], ) hdulist = m.to_hdulist(hdu="COUNTS") m2 = Map.from_hdulist(hdulist) time_axis_new = m2.geom.axes["time"] assert time_axis_new == time_axis assert time_axis.reference_time.scale == "utc" assert time_axis_new.reference_time.scale == "tt"
def from_hdulist(cls, hdulist, hdu_bands="BANDS"): """Create map dictionary from list of HDUs. 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 Name of the HDU with the BANDS table. Default is 'BANDS' If set to None, each map should have its own hdu_band Returns ------- maps : `~gammapy.maps.Maps` Maps object. """ maps = cls() for hdu in hdulist: if hdu.is_image and hdu.data is not None: map_name = hdu.name.lower() maps[map_name] = Map.from_hdulist(hdulist, hdu=map_name, hdu_bands=hdu_bands) return maps
def from_hdulist( cls, hdulist, hdu=None, hdu_bands=None, exposure_hdu=None, exposure_hdu_bands=None, ): """Create from `~astropy.io.fits.HDUList`. Parameters ---------- hdulist : `~astropy.fits.HDUList` HDU list. hdu : str Name or index of the HDU with the IRF map. hdu_bands : str Name or index of the HDU with the IRF map BANDS table. exposure_hdu : str Name or index of the HDU with the exposure map data. exposure_hdu_bands : str Name or index of the HDU with the exposure map BANDS table. Returns ------- irf_map : `IRFMap` IRF map. """ if hdu is None: hdu = cls._hdu_name irf_map = Map.from_hdulist(hdulist, hdu=hdu, hdu_bands=hdu_bands) if exposure_hdu is None: exposure_hdu = cls._hdu_name + "_exposure" if exposure_hdu in hdulist: exposure_map = Map.from_hdulist(hdulist, hdu=exposure_hdu, hdu_bands=exposure_hdu_bands) else: exposure_map = None return cls(irf_map, exposure_map)
def test_map_unit_read_write(map_type, unit): m = Map.create(binsz=0.1, width=10.0, map_type=map_type, unit=unit) hdu_list = m.to_hdulist(hdu="COUNTS") header = hdu_list["COUNTS"].header assert Unit(header["BUNIT"]) == Unit(unit) m2 = Map.from_hdulist(hdu_list) assert m2.unit == unit
def from_hdulist(cls, hdulist, name=""): """Create map dataset from list of HDUs. Parameters ---------- hdulist : `~astropy.io.fits.HDUList` List of HDUs. Returns ------- dataset : `MapDataset` Map dataset. """ init_kwargs = {} init_kwargs["name"] = name if "COUNTS" in hdulist: init_kwargs["counts"] = Map.from_hdulist(hdulist, hdu="counts") if "COUNTS_OFF" in hdulist: init_kwargs["counts_off"] = Map.from_hdulist(hdulist, hdu="counts_off") if "ACCEPTANCE" in hdulist: init_kwargs["acceptance"] = Map.from_hdulist(hdulist, hdu="acceptance") if "ACCEPTANCE_OFF" in hdulist: init_kwargs["acceptance_off"] = Map.from_hdulist( hdulist, hdu="acceptance_off" ) if "EXPOSURE" in hdulist: init_kwargs["exposure"] = Map.from_hdulist(hdulist, hdu="exposure") if "EDISP_MATRIX" in hdulist: init_kwargs["edisp"] = EnergyDispersion.from_hdulist( hdulist, hdu1="EDISP_MATRIX", hdu2="EDISP_MATRIX_EBOUNDS" ) if "PSF_KERNEL" in hdulist: psf_map = Map.from_hdulist(hdulist, hdu="psf_kernel") init_kwargs["psf"] = PSFKernel(psf_map) if "MASK_SAFE" in hdulist: mask_safe_map = Map.from_hdulist(hdulist, hdu="mask_safe") init_kwargs["mask_safe"] = mask_safe_map.data.astype(bool) if "MASK_FIT" in hdulist: mask_fit_map = Map.from_hdulist(hdulist, hdu="mask_fit") init_kwargs["mask_fit"] = mask_fit_map.data.astype(bool) if "GTI" in hdulist: gti = GTI(Table.read(hdulist, hdu="GTI")) init_kwargs["gti"] = gti return cls(**init_kwargs)
def test_map_meta_read_write(map_type): meta = {"user": "******"} m = Map.create( binsz=0.1, width=10.0, map_type=map_type, skydir=SkyCoord(0.0, 30.0, unit="deg"), meta=meta, ) hdulist = m.to_hdulist(hdu="COUNTS") header = hdulist["COUNTS"].header assert header["META"] == '{"user": "******"}' m2 = Map.from_hdulist(hdulist) assert m2.meta == meta
def from_hdulist(cls, hdulist): """Create map dataset from list of HDUs. Parameters ---------- hdulist : `~astropy.io.fits.HDUList` List of HDUs. Returns ------- dataset : `MapDataset` Map dataset. """ init_kwargs = {} init_kwargs["counts"] = Map.from_hdulist(hdulist, hdu="counts") init_kwargs["exposure"] = Map.from_hdulist(hdulist, hdu="exposure") background_map = Map.from_hdulist(hdulist, hdu="background") init_kwargs["background_model"] = BackgroundModel(background_map) if "EDISP_MATRIX" in hdulist: init_kwargs["edisp"] = EnergyDispersion.from_hdulist( hdulist, hdu1="EDISP_MATRIX", hdu2="EDISP_MATRIX_EBOUNDS") if "PSF_KERNEL" in hdulist: psf_map = Map.from_hdulist(hdulist, hdu="psf_kernel") init_kwargs["psf"] = PSFKernel(psf_map) if "MASK_SAFE" in hdulist: mask_safe_map = Map.from_hdulist(hdulist, hdu="mask_safe") init_kwargs["mask_safe"] = mask_safe_map.data.astype(bool) if "MASK_FIT" in hdulist: mask_fit_map = Map.from_hdulist(hdulist, hdu="mask_fit") init_kwargs["mask_fit"] = mask_fit_map.data.astype(bool) return cls(**init_kwargs)
# In rare cases e.g. when the FITS file is not valid or meta data is missing from the header it can be necessary to modify the header of a certain HDU before creating the `Map` object. In this case we can use `astropy.io.fits` directly to read the FITS file: # In[ ]: filename = (os.environ["GAMMAPY_DATA"] + "/fermi-3fhl-gc/fermi-3fhl-gc-exposure.fits.gz") hdulist = fits.open(filename) hdulist.info() # And then modify the header keyword and use `Map.from_hdulist()` to create the `Map` object after: # In[ ]: hdulist["PRIMARY"].header["BUNIT"] = "cm2 s" Map.from_hdulist(hdulist=hdulist) # ### Writing Maps # # Writing FITS files is mainoy exposure via the `Map.write()` method. Here is a first example: # In[ ]: m_cube.write("example_cube.fits", overwrite=True) # By default Gammapy does not overwrite files. In this example we set `overwrite=True` in case the cell gets executed multiple times. Now we can read back the cube from disk using `Map.read()`: # In[ ]: m_cube = Map.read("example_cube.fits") print(m_cube)
print(m_2fhl_gc) # In rare cases e.g. when the FITS file is not valid or meta data is missing from the header it can be necessary to modify the header of a certain HDU before creating the `Map` object. In this case we can use `astropy.io.fits` directly to read the FITS file: # In[ ]: filename = os.environ["GAMMAPY_DATA"] + "/fermi_survey/all.fits.gz" hdulist = fits.open(filename) hdulist.info() # And then modify the header keyword and use `Map.from_hdulist()` to create the `Map` object after: # In[ ]: hdulist["exposure"].header["BUNIT"] = "cm2 s" Map.from_hdulist(hdulist=hdulist, hdu="exposure") # ### 3.2 Writing Maps # # Writing FITS files is mainoy exposure via the `Map.write()` method. Here is a first example: # In[ ]: m_cube.write("example_cube.fits", overwrite=True) # By default Gammapy does not overwrite files. In this example we set `overwrite=True` in case the cell gets executed multiple times. Now we can read back the cube from disk using `Map.read()`: # In[ ]: m_cube = Map.read("example_cube.fits") print(m_cube)
def from_hdulist( cls, hdulist, hdu=None, hdu_bands=None, exposure_hdu=None, exposure_hdu_bands=None, format="gadf", ): """Create from `~astropy.io.fits.HDUList`. Parameters ---------- hdulist : `~astropy.fits.HDUList` HDU list. hdu : str Name or index of the HDU with the IRF map. hdu_bands : str Name or index of the HDU with the IRF map BANDS table. exposure_hdu : str Name or index of the HDU with the exposure map data. exposure_hdu_bands : str Name or index of the HDU with the exposure map BANDS table. format : {"gadf", "gtpsf"} File format Returns ------- irf_map : `IRFMap` IRF map. """ if format == "gadf": if hdu is None: hdu = IRF_MAP_HDU_SPECIFICATION[cls.tag] irf_map = Map.from_hdulist(hdulist, hdu=hdu, hdu_bands=hdu_bands, format=format) if exposure_hdu is None: exposure_hdu = IRF_MAP_HDU_SPECIFICATION[cls.tag] + "_exposure" if exposure_hdu in hdulist: exposure_map = Map.from_hdulist(hdulist, hdu=exposure_hdu, hdu_bands=exposure_hdu_bands, format=format) else: exposure_map = None elif format == "gtpsf": rad_axis = MapAxis.from_table_hdu(hdulist["THETA"], format=format) table = Table.read(hdulist["PSF"]) energy_axis_true = MapAxis.from_table(table, format=format) geom_psf = RegionGeom.create(region=None, axes=[rad_axis, energy_axis_true]) psf_map = Map.from_geom(geom=geom_psf, data=table["Psf"].data, unit="sr-1") geom_exposure = geom_psf.squash("rad") exposure_map = Map.from_geom(geom=geom_exposure, data=table["Exposure"].data, unit="cm2 s") return cls(psf_map=psf_map, exposure_map=exposure_map) else: raise ValueError(f"Format {format} not supported") return cls(irf_map, exposure_map)
def from_hdulist(cls, hdulist, hdu_bands=None): """Create flux map dataset from list of HDUs. Parameters ---------- hdulist : `~astropy.io.fits.HDUList` List of HDUs. hdu_bands : str Name of the HDU with the BANDS table. Default is 'BANDS' If set to None, each map should have its own hdu_band Returns ------- fluxmaps : `~gammapy.estimators.FluxMaps` the flux map. """ try: sed_type = hdulist[0].header["SED_TYPE"] except KeyError: raise ValueError( f"Cannot determine SED type of flux map from primary header.") result = {} for map_type in REQUIRED_MAPS[sed_type]: if map_type.upper() in hdulist: result[map_type] = Map.from_hdulist(hdulist, hdu=map_type, hdu_bands=hdu_bands) else: raise ValueError( f"Cannot find required map {map_type} for SED type {sed_type}." ) for map_type in OPTIONAL_MAPS[sed_type]: if map_type.upper() in hdulist: result[map_type] = Map.from_hdulist(hdulist, hdu=map_type, hdu_bands=hdu_bands) # Read additional image hdus for hdu in hdulist[1:]: if hdu.is_image: if hdu.name.lower() not in (REQUIRED_MAPS[sed_type] + OPTIONAL_MAPS[sed_type]): result[hdu.name.lower()] = Map.from_hdulist( hdulist, hdu=hdu.name, hdu_bands=hdu_bands) model_filename = hdulist[0].header.get("MODEL", None) reference_model = None if model_filename: try: reference_model = Models.read(model_filename)[0] except FileNotFoundError: raise FileNotFoundError( f"Cannot find {model_filename} model file. Check MODEL keyword." ) if "GTI" in hdulist: gti = GTI(Table.read(hdulist["GTI"])) else: gti = None return cls.from_dict(result, sed_type, reference_model, gti)
from astropy.io import fits import argparse if __name__ == '__main__': usage = "usage: %(prog)s -f path/to/fits/file.fits" description = "plot a fits template" parser = argparse.ArgumentParser(usage=usage, description=description) parser.add_argument('-f', '--file', required=True) args = parser.parse_args() filepath = PosixPath(args.file) try: m = Map.read(fits_file) except: fits_file = fits.open(filepath) # get meta data, gives problems with JSON encoder meta = fits_file[0].header.pop("META", None) # read in map m = Map.from_hdulist(fits_file) # plot the map fig, ax, _ = m.sum_over_axes(['energy_true']).plot(stretch="log", add_cbar=True) ax.tick_params(direction="out") ax.grid(ls=":", color="0.5", lw=0.5) plt.savefig("template_map.png")