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

# 1D spectrum simulation¶

## 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.

## Proposed approach:¶

We will use the following classes:

## 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.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"
)

center = pointing.directional_offset_by(
position_angle=0 * u.deg, separation=offset
)
[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 link
-------- --------- ---------- -------------- --------- --- --- ------ ----
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]:
# In this simulation, we use the CTA-1DC irfs shipped with gammapy.
"\$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

[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   +/-    0.00
amplitude               :   2.50e-12   +/- 0.0e+00 1 / (cm2 s TeV)
reference    (frozen)   :      1.000       TeV

You can see that background 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                            : OIP9yFtn

Total counts                    : 289
Total background counts         : 24.60
Total excess counts             : 264.40

Predicted counts                : 305.65
Predicted background counts     : 24.28
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)) : 4.10

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   +/-    0.00
amplitude               :   2.50e-12   +/- 0.0e+00 1 / (cm2 s TeV)
reference    (frozen)   :      1.000       TeV

Total counts_off                : 123
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.31 s, sys: 11.9 ms, total: 1.33 s
Wall time: 1.32 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
str7int64float64float64float64float64float64float64float64float64float64float64float64float64float64int64int64str5float64int64float64float64float64
stacked31718.399999618530273298.600006103515627.08240213552948868.1666675131354168.16666751313541nan252718176.017719697408.03600.03600.0000000000020.088055555555555550.0051111110051472980.0829444461398654699wstat738.7245834271496929.045.0000009329422850.20000000298023224
obs-127522.0253.023.7678536548728564.1666666666666964.16666666666669nan252718170.9728768217719697919.5992773600.03600.00.07638888888888890.0061111111111111110.0702777777777777799wstat575.7795127847381109.045.00.2
obs-229320.6272.425.1711055540465566.066.0nan252718170.9728768217719697919.5992773600.03600.00.081388888888888890.0057222222222222220.0756666666666666699wstat645.49938240753031039.045.00.2
obs-328022.4257.623.98295173740537665.3333333333333465.33333333333334nan252718170.9728768217719697919.5992773600.03600.00.077777777777777780.0062222222222222220.0715555555555555799wstat585.92415469858721129.045.00.2
obs-433720.6316.427.68270994518474773.3333333333333473.33333333333334nan252718170.9728768217719697919.5992773600.03600.00.093611111111111120.0057222222222222220.0878888888888888899wstat787.3147239494481039.045.00.2
obs-528324.400000000000002258.623.72715478234789567.5000000000000167.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.078611111111111120.0067777777777777780.0718333333333333599wstat574.85257377274991229.044.999999999999990.2
obs-633022.400000000000006307.626.88918447572786673.6666666666666773.66666666666667nan252718170.9728768217719697919.5992773600.03600.00.091666666666666660.0062222222222222240.0854444444444444599wstat734.24147552859371129.044.9999999999999860.2
obs-728325.8257.223.4308797479585368.6666666666666768.66666666666667nan252718170.9728768217719697919.5992773600.03600.00.078611111111111120.0071666666666666670.0714444444444444499wstat552.36987794480441299.045.00.2
obs-830823.400000000000002284.625.4204927332833370.8333333333333470.83333333333334nan252718170.9728768217719697919.5992773600.03600.00.085555555555555550.0065000000000000010.0790555555555555699wstat652.26215725676331179.044.999999999999990.2
.....................................................................
obs-9028619.000000000000004267.025.13122188704343863.5000000000000163.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.079444444444444440.0052777777777777790.0741666666666666799wstat635.8304116110406959.044.999999999999990.2
obs-9128525.200000000000003259.823.6775459193106968.5000000000000168.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.079166666666666660.0070000000000000010.0721666666666666799wstat573.35647429633811269.044.999999999999990.2
obs-9231323.6289.425.66493542019417671.8333333333333671.83333333333336nan252718170.9728768217719697919.5992773600.03600.00.086944444444444450.0065555555555555560.0803888888888888899wstat669.44961428251961189.045.00.2
obs-9330218.8283.226.12386752260549766.0000000000000166.00000000000001nan252718170.9728768217719697919.5992773600.03600.00.083888888888888890.0052222222222222230.0786666666666666699wstat700.5066738339824949.045.00.2
obs-9432221.8300.226.57402975747320271.8333333333333471.83333333333334nan252718170.9728768217719697919.5992773600.03600.00.089444444444444440.0060555555555555550.0833888888888888999wstat715.25704980371471099.045.00.2
obs-9530524.400000000000006280.625.03073126049315271.1666666666666771.16666666666667nan252718170.9728768217719697919.5992773600.03600.00.084722222222222230.0067777777777777790.0779444444444444699wstat643.28468794047931229.044.999999999999990.2
obs-9630123.6277.424.96984596942142869.8333333333333469.83333333333334nan252718170.9728768217719697919.5992773600.03600.00.083611111111111110.0065555555555555560.0770555555555555499wstat626.73968424286241189.045.00.2
obs-9729018.8271.225.41798219445482664.0000000000000164.00000000000001nan252718170.9728768217719697919.5992773600.03600.00.080555555555555560.0052222222222222230.0753333333333333499wstat650.9762484493856949.045.00.2
obs-9830120.400000000000002280.625.68783296467500767.1666666666666767.16666666666667nan252718170.9728768217719697919.5992773600.03600.00.083611111111111110.0056666666666666670.0779444444444444699wstat664.56200994049521029.044.999999999999990.2
obs-9932320.8302.226.8570784237687171.1666666666666971.16666666666669nan252718170.9728768217719697919.5992773600.03600.00.089722222222222220.0057777777777777780.0839444444444444599wstat733.15765987680171049.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");

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 23.7 s, sys: 39.1 ms, total: 23.8 s
Wall time: 23.7 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

## 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?

[ ]: