Exemplo n.º 1
0
def test_reflected_bkg_maker(on_region, reflected_bkg_maker, observations):
    datasets = []

    e_reco = MapAxis.from_edges(np.logspace(0, 2, 5) * u.TeV, name="energy")
    e_true = MapAxis.from_edges(np.logspace(-0.5, 2, 11) * u.TeV,
                                name="energy_true")

    dataset_empty = SpectrumDataset.create(e_reco=e_reco,
                                           e_true=e_true,
                                           region=on_region)

    maker = SpectrumDatasetMaker(selection=["counts"])

    for obs in observations:
        dataset = maker.run(dataset_empty, obs)
        dataset_on_off = reflected_bkg_maker.run(dataset, obs)
        datasets.append(dataset_on_off)

    assert_allclose(datasets[0].counts_off.data.sum(), 76)
    assert_allclose(datasets[1].counts_off.data.sum(), 60)

    regions_0 = compound_region_to_list(datasets[0].counts_off.geom.region)
    regions_1 = compound_region_to_list(datasets[1].counts_off.geom.region)
    assert_allclose(len(regions_0), 11)
    assert_allclose(len(regions_1), 11)
Exemplo n.º 2
0
    def test_to_from_ogip_files(self, tmp_path):
        dataset = self.dataset.copy(name="test")
        dataset.to_ogip_files(outdir=tmp_path)
        newdataset = SpectrumDatasetOnOff.from_ogip_files(tmp_path / "pha_obstest.fits")

        expected_regions = compound_region_to_list(self.off_counts.geom.region)
        regions = compound_region_to_list(newdataset.counts_off.geom.region)

        assert_allclose(self.on_counts.data, newdataset.counts.data)
        assert_allclose(self.off_counts.data, newdataset.counts_off.data)
        assert_allclose(self.edisp.pdf_matrix, newdataset.edisp.pdf_matrix)
        assert_time_allclose(newdataset.gti.time_start, dataset.gti.time_start)

        assert len(regions) == len(expected_regions)
        assert regions[0].center.is_equivalent_frame(expected_regions[0].center)
        assert_allclose(regions[1].angle, expected_regions[1].angle)
Exemplo n.º 3
0
    def plot_region(self, ax=None, **kwargs):
        """Plot region in the sky.

        Parameters
        ----------
        ax : `~astropy.vizualisation.WCSAxes`
            Axes to plot on. If no axes are given,
            the region is shown using the minimal
            equivalent WCS geometry.
        **kwargs : dict
            Keyword arguments forwarded to `~regions.PixelRegion.as_artist`
        """
        import matplotlib.pyplot as plt
        from matplotlib.collections import PatchCollection
        from astropy.visualization.wcsaxes import WCSAxes

        if ax is None:
            ax = plt.gca()

            if not isinstance(ax, WCSAxes):
                ax.remove()
                wcs_geom = self.to_wcs_geom()
                m = Map.from_geom(wcs_geom.to_image())
                fig, ax, cbar = m.plot(add_cbar=False)

        regions = compound_region_to_list(self.region)
        artists = [region.to_pixel(wcs=ax.wcs).as_artist() for region in regions]

        kwargs.setdefault("fc", "None")
        kwargs.setdefault("ec", "b")

        patches = PatchCollection(artists, **kwargs)
        ax.add_collection(patches)
        return ax
Exemplo n.º 4
0
    def run(self, dataset, observation):
        """Run reflected regions background maker

        Parameters
        ----------
        dataset : `SpectrumDataset`
            Spectrum dataset.
        observation : `DatastoreObservation`
            Data store observation.

        Returns
        -------
        dataset_on_off : `SpectrumDatasetOnOff`
            On off dataset.
        """
        counts_off = self.make_counts_off(dataset, observation)
        acceptance_off = len(compound_region_to_list(counts_off.region))

        return SpectrumDatasetOnOff(
            counts=dataset.counts,
            counts_off=counts_off,
            gti=dataset.gti,
            name=dataset.name,
            livetime=dataset.livetime,
            edisp=dataset.edisp,
            aeff=dataset.aeff,
            acceptance=1,
            acceptance_off=acceptance_off,
            mask_safe=dataset.mask_safe,
            mask_fit=dataset.mask_fit,
        )
Exemplo n.º 5
0
def test_reflected_bkg_maker(spectrum_dataset_maker, reflected_bkg_maker,
                             observations):
    datasets = []

    for obs in observations:
        dataset = spectrum_dataset_maker.run(obs, selection=["counts"])
        dataset_on_off = reflected_bkg_maker.run(dataset, obs)
        datasets.append(dataset_on_off)

    assert_allclose(datasets[0].counts_off.data.sum(), 76)
    assert_allclose(datasets[1].counts_off.data.sum(), 60)

    regions_0 = compound_region_to_list(datasets[0].counts_off.region)
    regions_1 = compound_region_to_list(datasets[1].counts_off.region)
    assert_allclose(len(regions_0), 11)
    assert_allclose(len(regions_1), 11)
Exemplo n.º 6
0
    def test_to_from_ogip_files(self, tmp_path):
        dataset = self.dataset.copy(name="test")
        dataset.write(tmp_path / "test.fits")
        newdataset = SpectrumDatasetOnOff.read(tmp_path / "test.fits")

        expected_regions = compound_region_to_list(self.off_counts.geom.region)
        regions = compound_region_to_list(newdataset.counts_off.geom.region)

        assert newdataset.counts.meta["RESPFILE"] == "test_rmf.fits"
        assert newdataset.counts.meta["BACKFILE"] == "test_bkg.fits"
        assert newdataset.counts.meta["ANCRFILE"] == "test_arf.fits"

        assert_allclose(self.on_counts.data, newdataset.counts.data)
        assert_allclose(self.off_counts.data, newdataset.counts_off.data)
        assert_allclose(self.edisp.edisp_map.data, newdataset.edisp.edisp_map.data)
        assert_time_allclose(newdataset.gti.time_start, dataset.gti.time_start)

        assert len(regions) == len(expected_regions)
        assert regions[0].center.is_equivalent_frame(expected_regions[0].center)
        assert_allclose(regions[1].angle, expected_regions[1].angle)
Exemplo n.º 7
0
    def _to_region_table(self):
        """Export region to a FITS region table."""
        if self.region is None:
            raise ValueError("Region definition required.")

        # TODO: make this a to_hdulist() method
        region_list = compound_region_to_list(self.region)
        pixel_region_list = []
        for reg in region_list:
            pixel_region_list.append(reg.to_pixel(self.wcs))
        table = fits_region_objects_to_table(pixel_region_list)
        table.meta.update(self.wcs.to_header())
        return table
Exemplo n.º 8
0
    def width(self):
        """Width of bounding box of the region"""
        if self.region is None:
            raise ValueError("Region definition required.")

        regions = compound_region_to_list(self.region)
        regions_pix = [_.to_pixel(self.wcs) for _ in regions]

        bbox = regions_pix[0].bounding_box

        for region_pix in regions_pix[1:]:
            bbox = bbox.union(region_pix.bounding_box)

        rectangle_pix = bbox.to_region()
        rectangle = rectangle_pix.to_sky(self.wcs)
        return u.Quantity([rectangle.width, rectangle.height])
Exemplo n.º 9
0
    def plot_region(self, ax=None, **kwargs):
        """Plot region

        Parameters
        ----------
        ax : `~astropy.vizualisation.WCSAxes`
            Axes to plot on.
        **kwargs : dict
            Keyword arguments forwarded to `~regions.PixelRegion.as_artist`
        """
        import matplotlib.pyplot as plt
        from matplotlib.collections import PatchCollection

        ax = plt.gca() or ax
        regions = compound_region_to_list(self.region)
        artists = [
            region.to_pixel(wcs=ax.wcs).as_artist() for region in regions
        ]

        patches = PatchCollection(artists, **kwargs)
        ax.add_collection(patches)
        return ax
Exemplo n.º 10
0
    def width(self):
        """Width of bounding box of the region.
        
        Returns
        -------
        width : `~astropy.units.Quantity`
            Dimensions of the region in both spatial dimensions.
            Units: ``deg``
        """
        if self.region is None:
            raise ValueError("Region definition required.")

        regions = compound_region_to_list(self.region)
        regions_pix = [_.to_pixel(self.wcs) for _ in regions]

        bbox = regions_pix[0].bounding_box

        for region_pix in regions_pix[1:]:
            bbox = bbox.union(region_pix.bounding_box)

        rectangle_pix = bbox.to_region()
        rectangle = rectangle_pix.to_sky(self.wcs)
        return u.Quantity([rectangle.width, rectangle.height])