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

Spectrum simulation for CTA

A quick example how to use the functions and classes in gammapy.spectrum in order to simulate and fit spectra.

We will simulate observations for CTA first using a power law model without any background. Then we will add a power law shaped background component.

We will use the following classes:


Same procedure as in every script …

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord, Angle
from regions import CircleSkyRegion
from gammapy.spectrum import (
from gammapy.modeling import Fit, Parameter
from gammapy.modeling.models import (
from gammapy.irf import load_cta_irfs
from import Observation
from gammapy.maps import MapAxis

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.

# 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", interp="log"

on_region_radius = Angle("0.11 deg")
on_region = CircleSkyRegion(center=pointing, radius=on_region_radius)
# Define spectral model - a simple Power Law in this case
model_simu = PowerLawSpectralModel(
    amplitude=2.5e-12 * u.Unit("cm-2 s-1 TeV-1"),
    reference=1 * u.TeV,
# we set the sky model used in the dataset
model = SkyModel(spectral_model=model_simu)

   name     value   error      unit      min max frozen
--------- --------- ----- -------------- --- --- ------
    index 3.000e+00   nan                nan nan  False
amplitude 2.500e-12   nan cm-2 s-1 TeV-1 nan nan  False
reference 1.000e+00   nan            TeV nan nan   True
# Load the IRFs
# In this simulation, we use the CTA-1DC irfs shipped with gammapy.
irfs = load_cta_irfs(
obs = Observation.create(pointing=pointing, livetime=livetime, irfs=irfs)
Info for OBS_ID = 0
- Pointing pos: RA 266.40 deg / Dec -28.94 deg
- Livetime duration: 3600.0 s

WARNING: AstropyDeprecationWarning: The truth value of a Quantity is ambiguous. In the future this will raise a ValueError. [astropy.units.quantity]
# 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 =, obs)
# Set the model on the dataset, and fake
dataset.model = model

    Name                            : 0

    Total counts                    : 16
    Total predicted counts          : nan
    Total background counts         : 22.35

    Effective area min              : 8.16e+04 m2
    Effective area max              : 5.08e+06 m2

    Livetime                        : 3.60e+03 s

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

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

    Number of parameters            : 0
    Number of free parameters       : 0

You can see that backgound counts are now simulated

OnOff analysis

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

dataset_onoff = SpectrumDatasetOnOff(

    Name                            :

    Total counts                    : 331
    Total predicted counts          : 296.82
    Total off counts                : 122.00

    Total background counts         : 24.40

    Effective area min              : 8.16e+04 m2
    Effective area max              : 5.08e+06 m2

    Livetime                        : 1.00e+00 h

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

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

    Number of parameters            : 3
    Number of free parameters       : 2

    Model type                      : SkyModels
    Acceptance mean:                : 1.0

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


n_obs = 100
datasets = []

for idx in range(n_obs):
    dataset_onoff.fake(random_state=idx, background_model=dataset.background) = f"obs_{idx}"
CPU times: user 213 ms, sys: 3.67 ms, total: 217 ms
Wall time: 220 ms

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

n_on = [ for dataset in datasets]
n_off = [ for dataset in datasets]
excess = [ for dataset in datasets]

fix, axes = plt.subplots(1, 3, figsize=(12, 4))

Now, we fit each simulated spectrum individually

results = []
for dataset in datasets:
    dataset.models = model.copy()
    fit = Fit([dataset])
    result = fit.optimize()
            "index": result.parameters["index"].value,
            "amplitude": result.parameters["amplitude"].value,
CPU times: user 4.43 s, sys: 33.6 ms, total: 4.46 s
Wall time: 4.53 s

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

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.008268371884822 += 0.08582628065923613


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

What next?

In this tutorial we simulated and analysed the spectrum of source using CTA prod 2 IRFs.

If you’d like to go further, please see the other tutorial notebooks.

[ ]: