This is a fixed-text formatted version of a Jupyter notebook

1D spectrum simulation

Prerequisites

Context

To simulate a specific observation, it is not always necessary to simulate the full photon list. For many uses cases, simulating directly a reduced binned dataset is enough: the IRFs reduced in the correct geometry are combined with a source model to predict an actual number of counts per bin. The latter is then used to simulate a reduced dataset using Poisson probability distribution.

This can be done to check the feasibility of a measurement, to test whether fitted parameters really provide a good fit to the data etc.

Here we will see how to perform a 1D spectral simulation of a CTA observation, in particular, we will generate OFF observations following the template background stored in the CTA IRFs.

Objective: simulate a number of spectral ON-OFF observations of a source with a power-law spectral model with CTA using the CTA 1DC response, fit them with the assumed spectral model and check that the distribution of fitted parameters is consistent with the input values.

Setup

[1]:
%matplotlib inline
import matplotlib.pyplot as plt
[2]:
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord, Angle
from regions import CircleSkyRegion
from gammapy.datasets import SpectrumDatasetOnOff, SpectrumDataset, Datasets
from gammapy.makers import SpectrumDatasetMaker
from gammapy.modeling import Fit
from gammapy.modeling.models import (
    PowerLawSpectralModel,
    SkyModel,
)
from gammapy.irf import load_cta_irfs
from gammapy.data import Observation
from gammapy.maps import MapAxis, RegionGeom

Simulation of a single spectrum

To do a simulation, we need to define the observational parameters like the livetime, the offset, the assumed integration radius, the energy range to perform the simulation for and the choice of spectral model. We then use an in-memory observation which is convolved with the IRFs to get the predicted number of counts. This is Poission fluctuated using the fake() to get the simulated counts for each observation.

[3]:
# Define simulation parameters parameters
livetime = 1 * u.h

pointing = SkyCoord(0, 0, unit="deg", frame="galactic")
offset = 0.5 * u.deg

# Reconstructed and true energy axis
energy_axis = MapAxis.from_edges(
    np.logspace(-0.5, 1.0, 10), unit="TeV", name="energy", interp="log"
)
energy_axis_true = MapAxis.from_edges(
    np.logspace(-1.2, 2.0, 31), unit="TeV", name="energy_true", interp="log"
)

on_region_radius = Angle("0.11 deg")

center = pointing.directional_offset_by(
    position_angle=0 * u.deg, separation=offset
)
on_region = CircleSkyRegion(center=center, radius=on_region_radius)
[4]:
# Define spectral model - a simple Power Law in this case
model_simu = PowerLawSpectralModel(
    index=3.0,
    amplitude=2.5e-12 * u.Unit("cm-2 s-1 TeV-1"),
    reference=1 * u.TeV,
)
print(model_simu)
# we set the sky model used in the dataset
model = SkyModel(spectral_model=model_simu, name="source")
PowerLawSpectralModel

  type      name     value         unit        error   min max frozen
-------- --------- ---------- -------------- --------- --- --- ------
spectral     index 3.0000e+00                0.000e+00 nan nan  False
spectral amplitude 2.5000e-12 cm-2 s-1 TeV-1 0.000e+00 nan nan  False
spectral reference 1.0000e+00            TeV 0.000e+00 nan nan   True
[5]:
# 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"
)
Invalid unit found in background table! Assuming (s-1 MeV-1 sr-1)
[6]:
obs = Observation.create(pointing=pointing, livetime=livetime, irfs=irfs)
print(obs)
Observation

        obs id            : 0
        tstart            : 51544.00
        tstop             : 51544.04
        duration          : 3600.00 s
        pointing (icrs)   : 266.4 deg, -28.9 deg

        deadtime fraction : 0.0%

[7]:
# Make the SpectrumDataset
geom = RegionGeom.create(region=on_region, axes=[energy_axis])

dataset_empty = SpectrumDataset.create(
    geom=geom, energy_axis_true=energy_axis_true, name="obs-0"
)
maker = SpectrumDatasetMaker(selection=["exposure", "edisp", "background"])

dataset = maker.run(dataset_empty, obs)
[8]:
# Set the model on the dataset, and fake
dataset.models = model
dataset.fake(random_state=42)
print(dataset)
SpectrumDataset
---------------

  Name                            : obs-0

  Total counts                    : 298
  Total background counts         : 22.29
  Total excess counts             : 275.71

  Predicted counts                : 303.66
  Predicted background counts     : 22.29
  Predicted excess counts         : 281.37

  Exposure min                    : 2.53e+08 m2 s
  Exposure max                    : 1.77e+10 m2 s

  Number of total bins            : 9
  Number of fit bins              : 9

  Fit statistic type              : cash
  Fit statistic value (-2 log(L)) : -1811.58

  Number of models                : 1
  Number of parameters            : 3
  Number of free parameters       : 2

  Component 0: SkyModel

    Name                      : source
    Datasets names            : None
    Spectral model type       : PowerLawSpectralModel
    Spatial  model type       :
    Temporal model type       :
    Parameters:
      index                   :   3.000
      amplitude               :   2.50e-12  1 / (cm2 s TeV)
      reference    (frozen)   :   1.000  TeV


You can see that backgound counts are now simulated

On-Off analysis

To do an on off spectral analysis, which is the usual science case, the standard would be to use SpectrumDatasetOnOff, which uses the acceptance to fake off-counts

[9]:
dataset_on_off = SpectrumDatasetOnOff.from_spectrum_dataset(
    dataset=dataset, acceptance=1, acceptance_off=5
)
dataset_on_off.fake(npred_background=dataset.npred_background())
print(dataset_on_off)
SpectrumDatasetOnOff
--------------------

  Name                            : bFMwuYf3

  Total counts                    : 285
  Total background counts         : 20.60
  Total excess counts             : 264.40

  Predicted counts                : 301.71
  Predicted background counts     : 20.34
  Predicted excess counts         : 281.37

  Exposure min                    : 2.53e+08 m2 s
  Exposure max                    : 1.77e+10 m2 s

  Number of total bins            : 9
  Number of fit bins              : 9

  Fit statistic type              : wstat
  Fit statistic value (-2 log(L)) : 9.92

  Number of models                : 1
  Number of parameters            : 3
  Number of free parameters       : 2

  Component 0: SkyModel

    Name                      : source
    Datasets names            : None
    Spectral model type       : PowerLawSpectralModel
    Spatial  model type       :
    Temporal model type       :
    Parameters:
      index                   :   3.000
      amplitude               :   2.50e-12  1 / (cm2 s TeV)
      reference    (frozen)   :   1.000  TeV

    Total counts_off                : 103
  Acceptance                      : 9
  Acceptance off                  : 45

You can see that off counts are now simulated as well. We now simulate several spectra using the same set of observation conditions.

[10]:
%%time

n_obs = 100
datasets = Datasets()

for idx in range(n_obs):
    dataset_on_off.fake(
        random_state=idx, npred_background=dataset.npred_background()
    )
    dataset_fake = dataset_on_off.copy(name=f"obs-{idx}")
    dataset_fake.meta_table["OBS_ID"] = [idx]
    datasets.append(dataset_fake)
CPU times: user 1.17 s, sys: 29.2 ms, total: 1.2 s
Wall time: 1.18 s
[11]:
table = datasets.info_table()
table
[11]:
Table length=100
namecountsbackgroundexcesssqrt_tsnprednpred_backgroundnpred_signalexposure_minexposure_maxlivetimeontimecounts_ratebackground_rateexcess_raten_binsn_fit_binsstat_typestat_sumcounts_offacceptanceacceptance_offalpha
m2 sm2 sss1 / s1 / s1 / s
str7float64float64float64float64float64float64float64float64float64float64float64float64float64float64int64int64str5float64float64float64float64float64
stacked317.018.399999618530273298.600006103515627.0824018081312668.1666675131354168.16666751313541nan252718176.017719697408.03600.03600.0000000000020.088055555555555550.0051111110051472980.0829444461398654699wstat738.724583427149692.09.045.00.20000000298023224
obs-1275.022.0253.023.7678536548728564.1666666666666964.16666666666669nan252718170.9728768217719697919.5992773600.03600.00.07638888888888890.0061111111111111110.0702777777777777799wstat575.779512784738110.09.045.00.2
obs-2293.020.6272.425.1711055540465566.066.0nan252718170.9728768217719697919.5992773600.03600.00.081388888888888890.0057222222222222220.0756666666666666699wstat645.4993824075303103.09.045.00.2
obs-3280.022.4257.623.98295173740537665.3333333333333465.33333333333334nan252718170.9728768217719697919.5992773600.03600.00.077777777777777780.0062222222222222220.0715555555555555799wstat585.9241546985872112.09.045.00.2
obs-4337.020.6316.427.68270994518474773.3333333333333473.33333333333334nan252718170.9728768217719697919.5992773600.03600.00.093611111111111120.0057222222222222220.0878888888888888899wstat787.314723949448103.09.045.00.2
obs-5283.024.400000000000002258.623.72715478234789567.5000000000000167.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.078611111111111120.0067777777777777780.0718333333333333599wstat574.8525737727499122.09.044.999999999999990.2
obs-6330.022.400000000000006307.626.88918447572786673.6666666666666773.66666666666667nan252718170.9728768217719697919.5992773600.03600.00.091666666666666660.0062222222222222240.0854444444444444599wstat734.2414755285937112.09.044.9999999999999860.2
obs-7283.025.8257.223.4308797479585368.6666666666666768.66666666666667nan252718170.9728768217719697919.5992773600.03600.00.078611111111111120.0071666666666666670.0714444444444444499wstat552.3698779448044129.09.045.00.2
obs-8308.023.400000000000002284.625.4204927332833370.8333333333333470.83333333333334nan252718170.9728768217719697919.5992773600.03600.00.085555555555555550.0065000000000000010.0790555555555555699wstat652.2621572567633117.09.044.999999999999990.2
.....................................................................
obs-90286.019.000000000000004267.025.13122188704343863.5000000000000163.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.079444444444444440.0052777777777777790.0741666666666666799wstat635.830411611040695.09.044.999999999999990.2
obs-91285.025.200000000000003259.823.6775459193106968.5000000000000168.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.079166666666666660.0070000000000000010.0721666666666666799wstat573.3564742963381126.09.044.999999999999990.2
obs-92313.023.6289.425.66493542019417671.8333333333333671.83333333333336nan252718170.9728768217719697919.5992773600.03600.00.086944444444444450.0065555555555555560.0803888888888888899wstat669.4496142825196118.09.045.00.2
obs-93302.018.8283.226.12386752260549766.0000000000000166.00000000000001nan252718170.9728768217719697919.5992773600.03600.00.083888888888888890.0052222222222222230.0786666666666666699wstat700.506673833982494.09.045.00.2
obs-94322.021.8300.226.57402975747320271.8333333333333471.83333333333334nan252718170.9728768217719697919.5992773600.03600.00.089444444444444440.0060555555555555550.0833888888888888999wstat715.2570498037147109.09.045.00.2
obs-95305.024.400000000000006280.625.03073126049315271.1666666666666771.16666666666667nan252718170.9728768217719697919.5992773600.03600.00.084722222222222230.0067777777777777790.0779444444444444699wstat643.2846879404793122.09.044.999999999999990.2
obs-96301.023.6277.424.96984596942142869.8333333333333469.83333333333334nan252718170.9728768217719697919.5992773600.03600.00.083611111111111110.0065555555555555560.0770555555555555499wstat626.7396842428624118.09.045.00.2
obs-97290.018.8271.225.41798219445482664.0000000000000164.00000000000001nan252718170.9728768217719697919.5992773600.03600.00.080555555555555560.0052222222222222230.0753333333333333499wstat650.976248449385694.09.045.00.2
obs-98301.020.400000000000002280.625.68783296467500767.1666666666666767.16666666666667nan252718170.9728768217719697919.5992773600.03600.00.083611111111111110.0056666666666666670.0779444444444444699wstat664.5620099404952102.09.044.999999999999990.2
obs-99323.020.8302.226.8570784237687171.1666666666666971.16666666666669nan252718170.9728768217719697919.5992773600.03600.00.089722222222222220.0057777777777777780.0839444444444444599wstat733.1576598768017104.09.045.00.2

Before moving on to the fit let’s have a look at the simulated observations.

[12]:
fix, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].hist(table["counts"])
axes[0].set_xlabel("Counts")
axes[1].hist(table["counts_off"])
axes[1].set_xlabel("Counts Off")
axes[2].hist(table["excess"])
axes[2].set_xlabel("excess");
../../../_images/tutorials_analysis_1D_spectrum_simulation_19_0.png

Now, we fit each simulated spectrum individually

[13]:
%%time
results = []

fit = Fit()

for dataset in datasets:
    dataset.models = model.copy()
    result = fit.optimize(dataset)
    results.append(
        {
            "index": result.parameters["index"].value,
            "amplitude": result.parameters["amplitude"].value,
        }
    )
CPU times: user 22.6 s, sys: 31.2 ms, total: 22.6 s
Wall time: 22.6 s

We take a look at the distribution of the fitted indices. This matches very well with the spectrum that we initially injected.

[14]:
index = np.array([_["index"] for _ in results])
plt.hist(index, bins=10, alpha=0.5)
plt.axvline(x=model_simu.parameters["index"].value, color="red")
print(f"index: {index.mean()} += {index.std()}")
index: 3.0036925550395615 += 0.08081469527403234
../../../_images/tutorials_analysis_1D_spectrum_simulation_23_1.png

Exercises

  • Change the observation time to something longer or shorter. Does the observation and spectrum results change as you expected?

  • Change the spectral model, e.g. add a cutoff at 5 TeV, or put a steep-spectrum source with spectral index of 4.0

  • Simulate spectra with the spectral model we just defined. How much observation duration do you need to get back the injected parameters?

[ ]: