Exemple #1
0
def spectrum_dataset_gc():
    e_reco = np.logspace(0, 2, 5) * u.TeV
    e_true = np.logspace(-0.5, 2, 11) * u.TeV
    pos = SkyCoord(0.0, 0.0, unit="deg", frame="galactic")
    radius = Angle(0.11, "deg")
    region = CircleSkyRegion(pos, radius)
    return SpectrumDataset.create(e_reco, e_true, region=region)
Exemple #2
0
def spectrum_dataset_crab_fine():
    e_true = np.logspace(-2, 2.5, 109) * u.TeV
    e_reco = np.logspace(-2, 2, 73) * u.TeV
    pos = SkyCoord(83.63, 22.01, unit="deg", frame="icrs")
    radius = Angle(0.11, "deg")
    region = CircleSkyRegion(pos, radius)
    return SpectrumDataset.create(e_reco, e_true, region=region)
Exemple #3
0
def test_stack_no_livetime():
    e_reco = np.logspace(0, 1, 3) * u.TeV
    dataset_1 = SpectrumDataset.create(e_reco=e_reco)
    dataset_1.livetime = None
    dataset_2 = dataset_1.copy()

    with pytest.raises(ValueError):
        dataset_1.stack(dataset_2)
Exemple #4
0
    def _spectrum_extraction(self):
        """Run all steps for the spectrum extraction."""
        log.info("Reducing spectrum datasets.")
        datasets_settings = self.config.datasets
        on_lon = datasets_settings.on_region.lon
        on_lat = datasets_settings.on_region.lat
        on_center = SkyCoord(on_lon,
                             on_lat,
                             frame=datasets_settings.on_region.frame)
        on_region = CircleSkyRegion(on_center,
                                    datasets_settings.on_region.radius)

        maker_config = {}
        if datasets_settings.containment_correction:
            maker_config[
                "containment_correction"] = datasets_settings.containment_correction
        e_reco = self._make_energy_axis(
            datasets_settings.geom.axes.energy).edges

        maker_config["selection"] = ["counts", "aeff", "edisp"]
        dataset_maker = SpectrumDatasetMaker(**maker_config)
        bkg_maker_config = {}
        if datasets_settings.background.exclusion:
            exclusion_region = Map.read(datasets_settings.background.exclusion)
            bkg_maker_config["exclusion_mask"] = exclusion_region
        bkg_maker = ReflectedRegionsBackgroundMaker(**bkg_maker_config)

        safe_mask_selection = self.config.datasets.safe_mask.methods
        safe_mask_settings = self.config.datasets.safe_mask.settings
        safe_mask_maker = SafeMaskMaker(methods=safe_mask_selection,
                                        **safe_mask_settings)

        e_true = self._make_energy_axis(
            datasets_settings.geom.axes.energy_true).edges

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

        datasets = []
        for obs in self.observations:
            log.info(f"Processing observation {obs.obs_id}")
            dataset = dataset_maker.run(reference.copy(), obs)
            dataset = bkg_maker.run(dataset, obs)
            if dataset.counts_off is None:
                log.info(
                    f"No OFF region found for observation {obs.obs_id}. Discarding."
                )
                continue
            dataset = safe_mask_maker.run(dataset, obs)
            log.debug(dataset)
            datasets.append(dataset)

        self.datasets = Datasets(datasets)

        if self.config.datasets.stack:
            stacked = self.datasets.stack_reduce(name="stacked")
            self.datasets = Datasets([stacked])
    def data(self) -> SpectrumDataset:
        """Actual event data in form of a SpectrumDataset.
        """

        dataset_empty = SpectrumDataset.create(e_reco=self.energy_axis,
                                               e_true=self.energy_axis,
                                               region=self.on_region)
        maker = SpectrumDatasetMaker(containment_correction=False,
                                     selection=["background", "aeff", "edisp"])
        dataset = maker.run(dataset_empty, self.obs)
        dataset.models = self.true_model
        dataset.fake()
        return dataset
Exemple #6
0
    def test_spectrumdataset_create(self):
        e_reco = u.Quantity([0.1, 1, 10.0], "TeV")
        e_true = u.Quantity([0.05, 0.5, 5, 20.0], "TeV")
        empty_dataset = SpectrumDataset.create(e_reco, e_true)

        assert empty_dataset.counts.total_counts == 0
        assert empty_dataset.data_shape[0] == 2
        assert empty_dataset.background.total_counts == 0
        assert empty_dataset.background.energy.nbin == 2
        assert empty_dataset.aeff.data.axis("energy").nbin == 3
        assert empty_dataset.edisp.data.axis("e_reco").nbin == 2
        assert empty_dataset.livetime.value == 0
        assert len(empty_dataset.gti.table) == 0
        assert empty_dataset.energy_range[0] is None
        assert_allclose(empty_dataset.mask_safe, 0)
Exemple #7
0
    def test_npred_models(self):
        e_reco = MapAxis.from_energy_bounds("1 TeV", "10 TeV", nbin=3).edges
        dataset = SpectrumDataset.create(e_reco=e_reco)
        dataset.livetime = 1 * u.h
        dataset.aeff.data.data += 1e10 * u.Unit("cm2")

        pwl_1 = PowerLawSpectralModel(index=2)
        pwl_2 = PowerLawSpectralModel(index=2)
        model_1 = SkyModel(spectral_model=pwl_1)
        model_2 = SkyModel(spectral_model=pwl_2)

        dataset.models = Models([model_1, model_2])

        npred = dataset.npred()

        assert_allclose(npred.data.sum(), 64.8)
Exemple #8
0
def test_run(observations, phase_bkg_maker):

    maker = SpectrumDatasetMaker()

    e_reco = np.logspace(0, 2, 5) * u.TeV
    e_true = np.logspace(-0.5, 2, 11) * u.TeV

    pos = SkyCoord("08h35m20.65525s", "-45d10m35.1545s", frame="icrs")
    radius = Angle(0.2, "deg")
    region = SphericalCircleSkyRegion(pos, radius)

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

    obs = observations["111630"]
    dataset = maker.run(dataset_empty, obs)
    dataset_on_off = phase_bkg_maker.run(dataset, obs)

    assert_allclose(dataset_on_off.acceptance, 0.1)
    assert_allclose(dataset_on_off.acceptance_off, 0.3)

    assert_allclose(dataset_on_off.counts.data.sum(), 28)
    assert_allclose(dataset_on_off.counts_off.data.sum(), 57)
Exemple #9
0
def test_reflected_bkg_maker_no_off(reflected_bkg_maker, observations):
    pos = SkyCoord(83.6333313, 21.51444435, unit="deg", frame="icrs")
    radius = Angle(0.11, "deg")
    region = CircleSkyRegion(pos, radius)

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

    datasets = []

    e_reco = np.logspace(0, 2, 5) * u.TeV
    e_true = np.logspace(-0.5, 2, 11) * u.TeV
    dataset_empty = SpectrumDataset.create(e_reco=e_reco,
                                           e_true=e_true,
                                           region=region)

    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 datasets[0].counts_off is None
    assert_allclose(datasets[0].acceptance_off, 0)
Exemple #10
0
def test_reflected_bkg_maker(on_region, reflected_bkg_maker, observations):
    datasets = []

    e_reco = np.logspace(0, 2, 5) * u.TeV
    e_true = np.logspace(-0.5, 2, 11) * u.TeV

    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.region)
    regions_1 = compound_region_to_list(datasets[1].counts_off.region)
    assert_allclose(len(regions_0), 11)
    assert_allclose(len(regions_1), 11)
Exemple #11
0
# ## Spatial analysis
#
# See other notebooks for how to run a 3D cube or 2D image based analysis.

# ## Spectrum
#
# We'll run a spectral analysis using the classical reflected regions background estimation method,
# and using the on-off (often called WSTAT) likelihood function.

# In[ ]:

e_reco = np.logspace(-1, np.log10(40), 40) * u.TeV
e_true = np.logspace(np.log10(0.05), 2, 200) * u.TeV

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

# In[ ]:

dataset_maker = SpectrumDatasetMaker(containment_correction=False,
                                     selection=["counts", "aeff", "edisp"])
bkg_maker = ReflectedRegionsBackgroundMaker(exclusion_mask=exclusion_mask)
safe_mask_masker = SafeMaskMaker(methods=["aeff-max"], aeff_percent=10)

# In[ ]:

get_ipython().run_cell_magic(
    'time', '',
    'datasets = []\n\nfor observation in observations:\n    dataset = dataset_maker.run(dataset_empty, observation)\n    dataset_on_off = bkg_maker.run(dataset, observation)\n    dataset_on_off = safe_mask_masker.run(dataset_on_off, observation)\n    datasets.append(dataset_on_off)'
)
# Load the IRFs
# In this simulation, we use the CTA-1DC irfs shipped with gammapy.
irfs = load_cta_irfs(
    "$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits")

# In[ ]:

obs = Observation.create(pointing=pointing, livetime=livetime, irfs=irfs)
print(obs)

# In[ ]:

# Make the SpectrumDataset
dataset_empty = SpectrumDataset.create(e_reco=energy_axis.edges,
                                       e_true=energy_axis_true.edges,
                                       region=on_region)
maker = SpectrumDatasetMaker(selection=["aeff", "edisp", "background"])
dataset = maker.run(dataset_empty, obs)

# In[ ]:

# Set the model on the dataset, and fake
dataset.model = model
dataset.fake(random_state=42)
print(dataset)

# You can see that backgound counts are now simulated

# ### OnOff analysis
#
mask = data_store.obs_table["TARGET_NAME"] == "Crab"
obs_ids = data_store.obs_table["OBS_ID"][mask].data
observations = data_store.get_observations(obs_ids)

crab_position = SkyCoord(83.63, 22.01, unit="deg", frame="icrs")

# The ON region center is defined in the icrs frame. The angle is defined w.r.t. to its axis.
rectangle = RectangleSkyRegion(center=crab_position,
                               width=0.5 * u.deg,
                               height=0.4 * u.deg,
                               angle=0 * u.deg)

bkg_maker = ReflectedRegionsBackgroundMaker(min_distance=0.1 * u.rad)
dataset_maker = SpectrumDatasetMaker(selection=["counts"])

dataset_empty = SpectrumDataset.create(e_reco=np.logspace(-1, 2, 30) * u.TeV,
                                       region=rectangle)

datasets = []

for obs in observations:
    dataset = dataset_maker.run(dataset_empty, obs)
    dataset_on_off = bkg_maker.run(observation=obs, dataset=dataset)
    datasets.append(dataset_on_off)

m = Map.create(skydir=crab_position, width=(8, 8), proj="TAN")

_, ax, _ = m.plot(vmin=-1, vmax=0)

rectangle.to_pixel(ax.wcs).plot(ax=ax, color="black")

plot_spectrum_datasets_off_regions(datasets=datasets, ax=ax)