def test_hpxmap_read_healpy(tmp_path): import healpy as hp path = tmp_path / "tmp.fits" npix = 12 * 1024 * 1024 m = [np.arange(npix), np.arange(npix) - 1, np.arange(npix) - 2] hp.write_map(filename=path, m=m, nest=False, overwrite=True) with fits.open(path, memmap=False) as hdulist: hdu_out = find_bintable_hdu(hdulist) header = hdu_out.header assert header["PIXTYPE"] == "HEALPIX" assert header["ORDERING"] == "RING" assert header["EXTNAME"] == "xtension" assert header["NSIDE"] == 1024 format = HpxConv.identify_hpx_format(header) assert format == "healpy" #default case: should take the first column "TEMPERATURE" m1 = Map.read(path) assert m1.data.shape[0] == npix diff = np.sum(m[0] - m1.data) assert_allclose(diff, 0.0) #specifying the colname by default for healpy it is "Q_POLARISATION" m2 = Map.read(path, colname="Q_POLARISATION") assert m2.data.shape[0] == npix diff = np.sum(m[1] - m2.data) assert_allclose(diff, 0.0)
def test_hpxmap_read_write(tmp_path, nside, nested, coordsys, region, axes, sparse): path = tmp_path / "tmp.fits" m = create_map(nside, nested, coordsys, region, axes, sparse) fill_poisson(m, mu=0.5, random_state=0) m.write(path, sparse=sparse, overwrite=True) m2 = HpxNDMap.read(path) m3 = HpxSparseMap.read(path) m4 = Map.read(path, map_type="hpx") if sparse: msk = np.isfinite(m2.data[...]) else: msk = np.ones_like(m2.data[...], dtype=bool) assert_allclose(m.data[...][msk], m2.data[...][msk]) assert_allclose(m.data[...][msk], m3.data[...][msk]) assert_allclose(m.data[...][msk], m4.data[...][msk]) m.write(path, sparse=True, overwrite=True) m2 = HpxNDMap.read(path) m3 = HpxMap.read(path, map_type="hpx") m4 = Map.read(path, map_type="hpx") assert_allclose(m.data[...][msk], m2.data[...][msk]) assert_allclose(m.data[...][msk], m3.data[...][msk]) assert_allclose(m.data[...][msk], m4.data[...][msk]) # Specify alternate HDU name for IMAGE and BANDS table m.write(path, hdu="IMAGE", hdu_bands="TEST", overwrite=True) m2 = HpxNDMap.read(path) m3 = Map.read(path) m4 = Map.read(path, map_type="hpx")
def test_hpxmap_read_write(tmp_path, nside, nested, frame, region, axes): path = tmp_path / "tmp.fits" m = create_map(nside, nested, frame, region, axes) m.write(path, sparse=True, overwrite=True) m2 = HpxNDMap.read(path) m4 = Map.read(path, map_type="hpx") msk = np.ones_like(m2.data[...], dtype=bool) assert_allclose(m.data[...][msk], m2.data[...][msk]) assert_allclose(m.data[...][msk], m4.data[...][msk]) m.write(path, overwrite=True) m2 = HpxNDMap.read(path) m3 = HpxMap.read(path, map_type="hpx") m4 = Map.read(path, map_type="hpx") assert_allclose(m.data[...][msk], m2.data[...][msk]) assert_allclose(m.data[...][msk], m3.data[...][msk]) assert_allclose(m.data[...][msk], m4.data[...][msk]) # Specify alternate HDU name for IMAGE and BANDS table m.write(path, sparse=True, hdu="IMAGE", hdu_bands="TEST", overwrite=True) m2 = HpxNDMap.read(path) m3 = Map.read(path) m4 = Map.read(path, map_type="hpx")
def data_prep(): counts = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts-cube.fits.gz") background = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-background-cube.fits.gz") exposure = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-exposure-cube.fits.gz") # unit is not properly stored on the file. We add it manually exposure = Map.from_geom(exposure.geom, data=exposure.data, unit="cm2s") psfmap = PSFMap.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-psf-cube.fits.gz", format="gtpsf") edisp = EDispKernelMap.from_diagonal_response( energy_axis=counts.geom.axes["energy"], energy_axis_true=exposure.geom.axes["energy_true"], ) dataset = MapDataset( counts=counts, background=background, exposure=exposure, psf=psfmap, name="fermi-3fhl-gc", edisp=edisp, ) return dataset
def test_compute_lima_on_off_image(): """ Test Li & Ma image with snippet from the H.E.S.S. survey data. """ filename = "$GAMMAPY_DATA/tests/unbundled/hess/survey/hess_survey_snippet.fits.gz" n_on = Map.read(filename, hdu="ON") n_off = Map.read(filename, hdu="OFF") a_on = Map.read(filename, hdu="ONEXPOSURE") a_off = Map.read(filename, hdu="OFFEXPOSURE") significance = Map.read(filename, hdu="SIGNIFICANCE") kernel = Tophat2DKernel(5) results = compute_lima_on_off_image(n_on, n_off, a_on, a_off, kernel) # Reproduce safe significance threshold from HESS software results["significance"].data[results["n_on"].data < 5] = 0 # crop the image at the boundaries, because the reference image # is cut out from a large map, there is no way to reproduce the # result with regular boundary handling actual = results["significance"].crop(kernel.shape).data desired = significance.crop(kernel.shape).data # Set boundary to NaN in reference image assert_allclose(actual, desired, atol=1e-5)
def fermi_dataset(): size = Angle("3 deg", "3.5 deg") counts = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts-cube.fits.gz") counts = counts.cutout(counts.geom.center_skydir, size) background = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-background-cube.fits.gz") background = background.cutout(background.geom.center_skydir, size) background = BackgroundModel(background, datasets_names=["fermi-3fhl-gc"]) exposure = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-exposure-cube.fits.gz") exposure = exposure.cutout(exposure.geom.center_skydir, size) exposure.unit = "cm2 s" psf = EnergyDependentTablePSF.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-psf-cube.fits.gz") psfmap = PSFMap.from_energy_dependent_table_psf(psf) edisp = EDispKernelMap.from_diagonal_response( energy_axis=counts.geom.axes["energy"], energy_axis_true=exposure.geom.axes["energy_true"], ) return MapDataset( counts=counts, models=[background], exposure=exposure, psf=psfmap, name="fermi-3fhl-gc", edisp=edisp, )
def test_wcs_nd_map_data_transpose_issue(tmp_path): # Regression test for https://github.com/gammapy/gammapy/issues/1346 # Our test case: a little map with WCS shape (3, 2), i.e. numpy array shape (2, 3) data = np.array([[0, 1, 2], [np.nan, np.inf, -np.inf]]) geom = WcsGeom.create(npix=(3, 2)) # Data should be unmodified after init m = WcsNDMap(data=data, geom=geom) assert_equal(m.data, data) # Data should be unmodified if initialised like this m = WcsNDMap(geom=geom) # and then filled via an in-place Numpy array operation m.data += data assert_equal(m.data, data) # Data should be unmodified after write / read to normal image format m.write(tmp_path / "normal.fits.gz") m2 = Map.read(tmp_path / "normal.fits.gz") assert_equal(m2.data, data) # Data should be unmodified after write / read to sparse image format m.write(tmp_path / "sparse.fits.gz") m2 = Map.read(tmp_path / "sparse.fits.gz") assert_equal(m2.data, data)
def test_hpxmap_read_write_fgst(tmpdir): filename = str(tmpdir / "map.fits") axis = MapAxis.from_bounds(100.0, 1000.0, 4, name="energy", unit="MeV") # Test Counts Cube m = create_map(8, False, "GAL", None, [axis], False) m.write(filename, conv="fgst-ccube", overwrite=True) with fits.open(filename) as h: assert "SKYMAP" in h assert "EBOUNDS" in h assert h["SKYMAP"].header["HPX_CONV"] == "FGST-CCUBE" assert h["SKYMAP"].header["TTYPE1"] == "CHANNEL1" m2 = Map.read(filename) # Test Model Cube m.write(filename, conv="fgst-template", overwrite=True) with fits.open(filename) as h: assert "SKYMAP" in h assert "ENERGIES" in h assert h["SKYMAP"].header["HPX_CONV"] == "FGST-TEMPLATE" assert h["SKYMAP"].header["TTYPE1"] == "ENERGY1" m2 = Map.read(filename)
def test_wcsndmap_read_write_fgst(tmpdir): filename = str(tmpdir / "map.fits") axis = MapAxis.from_bounds(100.0, 1000.0, 4, name="energy", unit="MeV") geom = WcsGeom.create(npix=10, binsz=1.0, proj="AIT", coordsys="GAL", axes=[axis]) # Test Counts Cube m = WcsNDMap(geom) m.write(filename, conv="fgst-ccube", overwrite=True) with fits.open(filename) as h: assert "EBOUNDS" in h m2 = Map.read(filename) assert m2.geom.conv == "fgst-ccube" # Test Model Cube m.write(filename, conv="fgst-template", overwrite=True) with fits.open(filename) as h: assert "ENERGIES" in h m2 = Map.read(filename) assert m2.geom.conv == "fgst-template"
def input_dataset(): filename = "$GAMMAPY_DATA/tests/unbundled/poisson_stats_image/input_all.fits.gz" energy = MapAxis.from_energy_bounds("0.1 TeV", "1 TeV", 1) energy_true = MapAxis.from_energy_bounds("0.1 TeV", "1 TeV", 1, name="energy_true") counts2D = Map.read(filename, hdu="counts") counts = counts2D.to_cube([energy]) exposure2D = Map.read(filename, hdu="exposure") exposure2D.unit = "cm2s" exposure = exposure2D.to_cube([energy_true]) background2D = Map.read(filename, hdu="background") background = background2D.to_cube([energy]) # add mask mask2D_data = np.ones_like(background2D.data).astype("bool") mask2D_data[0:40, :] = False mask2D = Map.from_geom(geom=counts2D.geom, data=mask2D_data) mask = mask2D.to_cube([energy]) name = "test-dataset" return MapDataset( counts=counts, exposure=exposure, background=background, mask_safe=mask, name=name, )
def fermi_dataset(): size = Angle("3 deg", "3.5 deg") counts = Map.read("$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts-cube.fits.gz") counts = counts.cutout(counts.geom.center_skydir, size) background = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-background-cube.fits.gz" ) background = background.cutout(background.geom.center_skydir, size) background = BackgroundModel(background, datasets_names=["fermi-3fhl-gc"]) exposure = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-exposure-cube.fits.gz" ) exposure = exposure.cutout(exposure.geom.center_skydir, size) exposure.unit = "cm2s" mask_safe = counts.copy(data=np.ones_like(counts.data).astype("bool")) psf = EnergyDependentTablePSF.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-psf-cube.fits.gz" ) psfmap = PSFMap.from_energy_dependent_table_psf(psf) dataset = MapDataset( counts=counts, models=[background], exposure=exposure, mask_safe=mask_safe, psf=psfmap, name="fermi-3fhl-gc", ) dataset = dataset.to_image() return dataset
def test_compute_lima_on_off_image(): """ Test Li & Ma image with snippet from the H.E.S.S. survey data. """ filename = "$GAMMAPY_DATA/tests/unbundled/hess/survey/hess_survey_snippet.fits.gz" n_on = Map.read(filename, hdu="ON") n_off = Map.read(filename, hdu="OFF") a_on = Map.read(filename, hdu="ONEXPOSURE") a_off = Map.read(filename, hdu="OFFEXPOSURE") significance = Map.read(filename, hdu="SIGNIFICANCE") kernel = Tophat2DKernel(5) results = LiMaMapEstimator.compute_lima_on_off_image( n_on, n_off, a_on, a_off, kernel) # Reproduce safe significance threshold from HESS software results["significance"].data[results["n_on"].data < 5] = 0 # crop the image at the boundaries, because the reference image # is cut out from a large map, there is no way to reproduce the # result with regular boundary handling actual = results["significance"].crop(kernel.shape).data desired = significance.crop(kernel.shape).data # Set boundary to NaN in reference image # The absolute tolerance is low because the method used here is slightly different from the one used in HGPS # n_off is convolved as well to ensure the method applies to true ON-OFF datasets assert_allclose(actual, desired, atol=0.2)
def fermi_dataset(): size = Angle("3 deg", "3.5 deg") counts = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts-cube.fits.gz") counts = counts.cutout(counts.geom.center_skydir, size) background = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-background-cube.fits.gz") background = background.cutout(background.geom.center_skydir, size) exposure = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-exposure-cube.fits.gz") exposure = exposure.cutout(exposure.geom.center_skydir, size) psfmap = PSFMap.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-psf-cube.fits.gz", format="gtpsf") edisp = EDispKernelMap.from_diagonal_response( energy_axis=counts.geom.axes["energy"], energy_axis_true=exposure.geom.axes["energy_true"], ) return MapDataset( counts=counts, background=background, exposure=exposure, psf=psfmap, name="fermi-3fhl-gc", edisp=edisp, )
def input_maps(): filename = "$GAMMAPY_DATA/tests/unbundled/poisson_stats_image/input_all.fits.gz" return { "counts": Map.read(filename, hdu="counts"), "exposure": Map.read(filename, hdu="exposure"), "background": Map.read(filename, hdu="background"), }
def get_dataset(): counts = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts-cube.fits.gz") background = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-background-cube.fits.gz") exposure = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-exposure-cube.fits.gz") # for some reason the WCS defintions are not aligned... exposure.geom._wcs = counts.geom.wcs psf = PSFMap.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-psf-cube.fits.gz", format="gtpsf") # reduce size of the PSF psf = psf.slice_by_idx(slices={"rad": slice(0, 130)}) edisp = EDispKernelMap.from_diagonal_response( energy_axis=counts.geom.axes["energy"], energy_axis_true=exposure.geom.axes["energy_true"], geom=psf.psf_map.geom) mask_safe = counts.geom.boundary_mask(width="0.2 deg") return MapDataset(counts=counts, background=background, exposure=exposure, psf=psf, name="fermi-3fhl-gc", edisp=edisp, mask_safe=mask_safe)
def test_hpxmap_read_write_fgst(tmp_path): path = tmp_path / "tmp.fits" axis = MapAxis.from_bounds(100.0, 1000.0, 4, name="energy", unit="MeV") # Test Counts Cube m = create_map(8, False, "GAL", None, [axis], False) m.write(path, conv="fgst-ccube", overwrite=True) with fits.open(path, memmap=False) as hdulist: assert "SKYMAP" in hdulist assert "EBOUNDS" in hdulist assert hdulist["SKYMAP"].header["HPX_CONV"] == "FGST-CCUBE" assert hdulist["SKYMAP"].header["TTYPE1"] == "CHANNEL1" m2 = Map.read(path) # Test Model Cube m.write(path, conv="fgst-template", overwrite=True) with fits.open(path, memmap=False) as hdulist: assert "SKYMAP" in hdulist assert "ENERGIES" in hdulist assert hdulist["SKYMAP"].header["HPX_CONV"] == "FGST-TEMPLATE" assert hdulist["SKYMAP"].header["TTYPE1"] == "ENERGY1" m2 = Map.read(path)
def input_dataset_simple(): axis = MapAxis.from_energy_bounds("1 TeV", "10 TeV", nbin=1) filename = "$GAMMAPY_DATA/tests/unbundled/poisson_stats_image/input_all.fits.gz" bkg_map = Map.read(filename, hdu="background") counts = Map.read(filename, hdu="counts") counts = counts.to_cube(axes=[axis]) bkg_map = bkg_map.to_cube(axes=[axis]) return MapDataset(counts=counts, background=bkg_map, name="test")
def test_to_image(geom): counts = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts-cube.fits.gz") background = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-background-cube.fits.gz") background = BackgroundModel(background, datasets_names=["fermi"]) exposure = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-exposure-cube.fits.gz") exposure = exposure.sum_over_axes(keepdims=True) dataset = MapDataset(counts=counts, models=[background], exposure=exposure, name="fermi") dataset_im = dataset.to_image() assert dataset_im.mask_safe is None assert dataset_im.counts.data.sum() == dataset.counts.data.sum() assert_allclose(dataset_im.background_model.map.data.sum(), 28548.625, rtol=1e-5) ebounds = np.logspace(-1.0, 1.0, 3) axis = MapAxis.from_edges(ebounds, name="energy", unit=u.TeV, interp="log") geom = WcsGeom.create(skydir=(0, 0), binsz=0.5, width=(1, 1), frame="icrs", axes=[axis]) dataset = MapDataset.create(geom) # Check map_safe handling data = np.array([[[False, True], [True, True]], [[False, False], [True, True]]]) dataset.mask_safe = WcsNDMap.from_geom(geom=geom, data=data) dataset_im = dataset.to_image() assert dataset_im.mask_safe.data.dtype == bool desired = np.array([[False, True], [True, True]]) assert (dataset_im.mask_safe.data == desired).all() # Check that missing entries in the dataset do not break dataset_copy = dataset.copy() dataset_copy.exposure = None dataset_copy._background_model = None dataset_im = dataset_copy.to_image() assert dataset_im.exposure is None assert dataset_im.background_model == None dataset_copy = dataset.copy() dataset_copy.counts = None dataset_im = dataset_copy.to_image() assert dataset_im.counts is None
def test_io(self, tmpdir): filename = str(tmpdir / "test-cwt.fits") self.cwt_data.write(filename=filename, overwrite=True) approx = Map.read(filename, hdu="APPROX") assert_allclose(approx.data[100, 100], self.cwt_data._approx[100, 100]) assert_allclose(approx.data[36, 63], self.cwt_data._approx[36, 63]) transform_2d = Map.read(filename, hdu="TRANSFORM_2D") assert_allclose(transform_2d.data[100, 100], self.cwt_data.transform_2d.data[100, 100]) assert_allclose(transform_2d.data[36, 63], self.cwt_data.transform_2d.data[36, 63])
def test_compute_lima_image(): """ Test Li & Ma image against TS image for Tophat kernel """ filename = "$GAMMAPY_DATA/tests/unbundled/poisson_stats_image/input_all.fits.gz" counts = Map.read(filename, hdu="counts") background = Map.read(filename, hdu="background") kernel = Tophat2DKernel(5) result_lima = compute_lima_image(counts, background, kernel) assert_allclose(result_lima["significance"].data[100, 100], 30.814916, atol=1e-3) assert_allclose(result_lima["significance"].data[1, 1], 0.164, atol=1e-3)
def get_fermi_3fhl_gc_dataset(): counts = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts-cube.fits.gz") background = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-background-cube.fits.gz") background = BackgroundModel(background, datasets_names=["fermi-3fhl-gc"]) exposure = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-exposure-cube.fits.gz") return MapDataset(counts=counts, models=[background], exposure=exposure, name="fermi-3fhl-gc")
def test_bin_image_main(tmpdir): """Run ``gammapy-bin-image`` and compare result to ``ctskymap``. """ event_file = "$GAMMAPY_DATA/tests/irf/hess/pa/hess_events_023523.fits.gz" reference_file = "$GAMMAPY_DATA/tests/irf/hess/pa/ctskymap.fits.gz" out_file = str(tmpdir / "gammapy_ctskymap.fits.gz") args = ["image", "bin", event_file, reference_file, out_file] run_cli(cli, args) actual = Map.read(out_file) expected = Map.read(reference_file) assert_allclose(actual.data, expected.data) assert_wcs_allclose(actual.geom.wcs, expected.geom.wcs)
def load(self): """Load HDU as appropriate class. TODO: this should probably go via an extensible registry. """ from gammapy.irf import IRF_REGISTRY hdu_class = self.hdu_class filename = self.path() hdu = self.hdu_name if hdu_class == "events": from gammapy.data import EventList return EventList.read(filename, hdu=hdu) elif hdu_class == "gti": from gammapy.data import GTI return GTI.read(filename, hdu=hdu) elif hdu_class == "map": from gammapy.maps import Map return Map.read(filename, hdu=hdu, format=self.format) else: cls = IRF_REGISTRY.get_cls(hdu_class) return cls.read(filename, hdu=hdu)
def test_wcsndmap_read_exposure(): exposure = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-exposure-cube.fits.gz" ) energy_axis = exposure.geom.axes["energy_true"] assert energy_axis.node_type == "center" assert exposure.unit == "cm2 s"
def from_dict(cls, data): if "filename" in data: bkg_map = Map.read(data["filename"]) elif "map" in data: bkg_map = data["map"] else: # TODO: for now create a fake map for serialization, # uptdated in MapDataset.from_dict() axis = MapAxis.from_edges(np.logspace(-1, 1, 2), unit=u.TeV, name="energy") geom = WcsGeom.create(skydir=(0, 0), npix=(1, 1), frame="galactic", axes=[axis]) bkg_map = Map.from_geom(geom) parameters = Parameters.from_dict(data["parameters"]) return cls.from_parameters( parameters=parameters, map=bkg_map, name=data["name"], datasets_names=data.get("datasets_names"), filename=data.get("filename"), )
def read(cls, filename, name=None, **kwargs): """Read map from FITS file. The default unit used if none is found in the file is ``cm-2 s-1 MeV-1 sr-1``. Parameters ---------- filename : str FITS image filename. name : str Name of the output model The default used if none is filename. """ m = Map.read(filename, **kwargs) if m.unit == "": m.unit = "cm-2 s-1 MeV-1 sr-1" if name is None: name = Path(filename).stem if m.geom.axes[0].name == "energy": m.geom.axes[0].name = "energy_true" return cls(m, name=name, filename=filename)
def get_fermi_3fhl_gc_dataset(): counts = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts-cube.fits.gz") background = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-background-cube.fits.gz") bkg_model = FoVBackgroundModel(dataset_name="fermi-3fhl-gc") exposure = Map.read( "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-exposure-cube.fits.gz") return MapDataset( counts=counts, background=background, models=[bkg_model], exposure=exposure, name="fermi-3fhl-gc", )
def test_compute_lima_image(): """ Test Li & Ma image against TS image for Tophat kernel """ filename = "$GAMMAPY_DATA/tests/unbundled/poisson_stats_image/input_all.fits.gz" counts = Map.read(filename, hdu="counts") counts = image_to_cube(counts, "1 GeV", "100 GeV") background = Map.read(filename, hdu="background") background = image_to_cube(background, "1 GeV", "100 GeV") dataset = MapDataset(counts=counts, background=background) estimator = ExcessMapEstimator("0.1 deg") result_lima = estimator.run(dataset) assert_allclose(result_lima["sqrt_ts"].data[:, 100, 100], 30.814916, atol=1e-3) assert_allclose(result_lima["sqrt_ts"].data[:, 1, 1], 0.164, atol=1e-3)
def _create_background_maker(self): """Create the Background maker.""" log.info("Creating the background Maker.") datasets_settings = self.config.datasets bkg_maker_config = {} if datasets_settings.background.exclusion: path = make_path(datasets_settings.background.exclusion) exclusion_mask = Map.read(path) exclusion_mask.data = exclusion_mask.data.astype(bool) bkg_maker_config["exclusion_mask"] = exclusion_mask bkg_maker_config.update(datasets_settings.background.parameters) bkg_method = datasets_settings.background.method bkg_maker = None if bkg_method == "fov_background": log.debug(f"Creating FoVBackgroundMaker with arguments {bkg_maker_config}") bkg_maker = FoVBackgroundMaker(**bkg_maker_config) elif bkg_method == "ring": bkg_maker = RingBackgroundMaker(**bkg_maker_config) log.debug(f"Creating RingBackgroundMaker with arguments {bkg_maker_config}") if datasets_settings.geom.axes.energy.nbins > 1: raise ValueError( "You need to define a single-bin energy geometry for your dataset." ) elif bkg_method == "reflected": bkg_maker = ReflectedRegionsBackgroundMaker(**bkg_maker_config) log.debug( f"Creating ReflectedRegionsBackgroundMaker with arguments {bkg_maker_config}" ) else: log.warning("No background maker set. Check configuration.") return bkg_maker
def from_dict(cls, data): from gammapy.modeling.models import SPECTRAL_MODEL_REGISTRY spectral_data = data.get("spectral") if spectral_data is not None: model_class = SPECTRAL_MODEL_REGISTRY.get_cls( spectral_data["type"]) spectral_model = model_class.from_dict(spectral_data) else: spectral_model = None if "filename" in data: bkg_map = Map.read(data["filename"]) elif "map" in data: bkg_map = data["map"] else: # TODO: for now create a fake map for serialization, # uptdated in MapDataset.from_dict() axis = MapAxis.from_edges(np.logspace(-1, 1, 2), unit=u.TeV, name="energy") geom = WcsGeom.create(skydir=(0, 0), npix=(1, 1), frame="galactic", axes=[axis]) bkg_map = Map.from_geom(geom) return cls( map=bkg_map, spectral_model=spectral_model, name=data["name"], datasets_names=data.get("datasets_names"), filename=data.get("filename"), )
def main(): import sys import argparse # Argument defintion usage = "usage: %(prog)s [options]" description = "Plot a WCS-based image" parser = argparse.ArgumentParser(usage,description=__abstract__) parser.add_argument("-i", "--input",type=argparse.FileType('r'),required=True, help="Input file") parser.add_argument("-e", "--extension", type=str, default=None, help="FITS HDU with map") parser.add_argument("--ebin",type=str,default=None, help="Energy bin, integer or 'ALL'") parser.add_argument("--zscale",type=str, default='log', help="Scaling for color scale") parser.add_argument("--zmin",type=float, default=None, help="Minimum z-axis value") parser.add_argument("--zmax",type=float, default=None, help="Maximum z-axis value") parser.add_argument("-o", "--output",type=argparse.FileType('w'), help="Output file. Leave blank for interactive.") # Parse the command line args = parser.parse_args(sys.argv[1:]) # Get the map themap = Map.read(args.input.name) outdata = [] if args.ebin == "ALL": for i,data in enumerate(counts): ip = ImagePlotter(themap) fig = plt.figure(i) im,ax = ip.plot(zscale=args.zscale, vmin=args.zmin, vmax=args.zmax) outdata.append(fig) elif args.ebin is None: ip = ImagePlotter(themap.sum_over_axes()) im,ax = ip.plot(zscale=args.zscale, vmin=args.zmin, vmax=args.zmax) outdata.append((im,ax)) else: try: ibin = int(args.ebin) ip = ImagePlotter(themap) im,ax = ip.plot(zscale=args.zscale, vmin=args.zmin, vmax=args.zmax) outdata.append((im,ax)) except: raise ValueError("--ebin argument must be an integer or 'ALL'") if args.output is None: plt.show() else: if len(outdata) == 1: plt.savefig(args.output.name) else: base,ext = os.path.splitext(args.output.name) for i, fig in enumerate(outdata): fig.savefig("%s_%02i%s"%(base,i,ext))
def main(): import sys import argparse # Argument defintion usage = "usage: %(prog)s [options]" description = "Collect all the new source" parser = argparse.ArgumentParser(usage, description=__abstract__) parser.add_argument("-i", "--input", type=argparse.FileType('r'), required=True, help="Input file") parser.add_argument("-e", "--extension", type=str, default="SKYMAP", help="FITS HDU with HEALPix map") parser.add_argument("--ebin", type=str, default=None, help="Energy bin, integer or 'ALL'") parser.add_argument("--zscale", type=str, default='log', help="Scaling for color scale") parser.add_argument("--zmin", type=float, default=None, help="Minimum z-axis value") parser.add_argument("--zmax", type=float, default=None, help="Maximum z-axis value") parser.add_argument("--cbar", action='store_true', default=False, help="draw color bar") parser.add_argument("-o", "--output", type=argparse.FileType('w'), help="Output file. Leave blank for interactive.") # Parse the command line args = parser.parse_args(sys.argv[1:]) hpxmap = Map.read(args.input.name, hdu=args.extension) outdata = [] if args.zscale == 'sqrt': the_norm = PowerNorm(gamma=0.5) elif args.zscale == 'log': the_norm= LogNorm() elif args.zscale == 'lin': the_norm = Normalize() else: the_norm = Normalize() fig, ax, im = hpxmap.plot(norm=the_norm, vmin=args.zmin, vmax=args.zmax) outdata.append(fig) if args.cbar: cbar = plt.colorbar(im, orientation='horizontal',shrink=0.7,pad=0.15, fraction=0.05) """ if args.ebin == "ALL": wcsproj = hpxmap.geom.make_wcs( naxis=2, proj='MOL', energies=None, oversample=2) mapping = HpxToWcsMapping(hpxmap.hpx, wcsproj) for i, data in enumerate(hpxmap.counts): ip = ImagePlotter(data=data, proj=hpxmap.hpx, mapping=mapping) fig = plt.figure(i) im, ax = ip.plot(zscale=args.zscale, vmin=args.zmin, vmax=args.zmax) outdata.append(fig) elif args.ebin is None: ip = ImagePlotter(data=hpxmap.counts, proj=hpxmap.hpx) im, ax = ip.plot(zscale=args.zscale, vmin=args.zmin, vmax=args.zmax) outdata.append((im, ax)) else: try: ibin = int(args.ebin) ip = ImagePlotter(data=hpxmap.counts[ibin], proj=hpxmap.hpx) im, ax = ip.plot(zscale=args.zscale, vmin=args.zmin, vmax=args.zmax) outdata.append((im, ax)) except: raise ValueError("--ebin argument must be an integer or 'ALL'") """ if args.output is None: plt.show() else: if len(outdata) == 1: plt.savefig(args.output.name) else: base, ext = os.path.splitext(args.output.name) for i, fig in enumerate(outdata): fig.savefig("%s_%02i%s" % (base, i, ext))
"""Make 3FHL example files.""" from astropy.coordinates import SkyCoord, Angle from gammapy.maps import Map m = Map.read('gll_iem_v06.fits') m2 = m.cutout( SkyCoord(0, 0, unit='deg', frame='galactic'), (Angle('6 deg'), Angle('11 deg')), ) print(m2.geom) m2.write('gll_iem_v06_cutout.fits', overwrite=True)
"""Plot significance image with HESS and MILAGRO colormap. """ import numpy as np import matplotlib.pyplot as plt from astropy.visualization.mpl_normalize import ImageNormalize from astropy.visualization import LinearStretch from gammapy.image import colormap_hess, colormap_milagro from gammapy.maps import Map filename = "$GAMMAPY_DATA/tests/unbundled/poisson_stats_image/expected_ts_0.000.fits.gz" image = Map.read(filename, hdu="SQRT_TS") # Plot with the HESS and Milagro colormap vmin, vmax, vtransition = -5, 15, 5 fig = plt.figure(figsize=(15.5, 6)) normalize = ImageNormalize(vmin=vmin, vmax=vmax, stretch=LinearStretch()) transition = normalize(vtransition) ax = fig.add_subplot(121, projection=image.geom.wcs) cmap = colormap_hess(transition=transition) image.plot(ax=ax, cmap=cmap, norm=normalize, add_cbar=True) plt.title("HESS-style colormap") ax = fig.add_subplot(122, projection=image.geom.wcs) cmap = colormap_milagro(transition=transition) image.plot(ax=ax, cmap=cmap, norm=normalize, add_cbar=True) plt.title("MILAGRO-style colormap") plt.tight_layout() plt.show()