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

Spectral analysis with Gammapy


This notebook explains in detail how to use the classes in gammapy.spectrum and related ones.

Based on a datasets of 4 Crab observations with H.E.S.S. (simulated events for now) we will perform a full region based spectral analysis, i.e. extracting source and background counts from certain regions, and fitting them using the forward-folding approach. We will use the following classes

Data handling:

To extract the 1-dim spectral information:

To perform the joint fit:

To compute flux points (a.k.a. “SED” = “spectral energy distribution”)

Feedback welcome!


As usual, we’ll start with some setup …

%matplotlib inline
import matplotlib.pyplot as plt
# Check package versions
import gammapy
import numpy as np
import astropy
import regions

print("gammapy:", gammapy.__version__)
print("numpy:", np.__version__)
print("astropy", astropy.__version__)
print("regions", regions.__version__)
gammapy: 0.14
numpy: 1.17.2
astropy 3.2.1
regions 0.4
import astropy.units as u
from astropy.coordinates import SkyCoord, Angle
from regions import CircleSkyRegion
from gammapy.maps import Map
from gammapy.modeling import Fit, Datasets
from import ObservationStats, ObservationSummary, DataStore
from gammapy.modeling.models import (
from gammapy.spectrum import (

Load Data

First, we select and load some H.E.S.S. observations of the Crab nebula (simulated events for now).

We will access the events, effective area, energy dispersion, livetime and PSF for containement correction.

datastore = DataStore.from_dir("$GAMMAPY_DATA/hess-dl3-dr1/")
obs_ids = [23523, 23526, 23559, 23592]
observations = datastore.get_observations(obs_ids)

Define Target Region

The next step is to define a signal extraction region, also known as on region. In the simplest case this is just a CircleSkyRegion, but here we will use the Target class in gammapy that is useful for book-keeping if you run several analysis in a script.

target_position = SkyCoord(ra=83.63, dec=22.01, unit="deg", frame="icrs")
on_region_radius = Angle("0.11 deg")
on_region = CircleSkyRegion(center=target_position, radius=on_region_radius)

Create exclusion mask

We will use the reflected regions method to place off regions to estimate the background level in the on region. To make sure the off regions don’t contain gamma-ray emission, we create an exclusion mask.

Using we find that there’s only one known gamma-ray source near the Crab nebula: the AGN called RGB J0521+212 at GLON = 183.604 deg and GLAT = -8.708 deg.

exclusion_region = CircleSkyRegion(
    center=SkyCoord(183.604, -8.708, unit="deg", frame="galactic"),
    radius=0.5 * u.deg,

skydir = target_position.galactic
exclusion_mask = Map.create(
    npix=(150, 150), binsz=0.05, skydir=skydir, proj="TAN", coordsys="GAL"

mask = exclusion_mask.geom.region_mask([exclusion_region], inside=False) = mask

Estimate background

Next we will manually perform a background estimate by placing reflected regions around the pointing position and looking at the source statistics. This will result in a gammapy.spectrum.BackgroundEstimate that serves as input for other classes in gammapy.

background_estimator = ReflectedRegionsBackgroundEstimator(
plt.figure(figsize=(8, 8))
<Figure size 576x576 with 0 Axes>

Source statistic

Next we’re going to look at the overall source statistics in our signal region. For more info about what debug plots you can create check out the ObservationSummary class.

stats = []
for obs, bkg in zip(observations, background_estimator.result):
    stats.append(ObservationStats.from_observation(obs, bkg))


obs_summary = ObservationSummary(stats)
fig = plt.figure(figsize=(10, 6))
ax1 = fig.add_subplot(121)

ax2 = fig.add_subplot(122)
*** Observation summary report ***
Observation Id: 23526
Livetime: 0.437 h
On events: 201
Off events: 228
Alpha: 0.083
Bkg events in On region: 19.00
Excess: 182.00
Excess / Background: 9.58
Gamma rate: 6.94 1 / min
Bkg rate: 0.72 1 / min
Sigma: 21.79


Extract spectrum

Now, we’re going to extract a spectrum using the SpectrumExtraction class. We provide the reconstructed energy binning we want to use. It is expected to be a Quantity with unit energy, i.e. an array with an energy unit. We also provide the true energy binning to use.

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

Instantiate a SpectrumExtraction object that will do the extraction. The containment_correction parameter is there to allow for PSF leakage correction if one is working with full enclosure IRFs. We also compute a threshold energy and store the result in OGIP compliant files (pha, rmf, arf). This last step might be omitted though.

extraction = SpectrumExtraction(
CPU times: user 1.34 s, sys: 17.6 ms, total: 1.36 s
Wall time: 1.36 s

Now we can (optionally) compute the energy thresholds for the analysis, acoording to different methods. Here we choose the energy where the effective area drops below 10% of the maximum:

# Add a condition on correct energy range in case it is not set by default
extraction.compute_energy_threshold(method_lo="area_max", area_percent_lo=10.0)
/Users/adonath/github/adonath/gammapy/gammapy/utils/ Warning: Interpolated values reached float32 precision limit
  "Interpolated values reached float32 precision limit", Warning

Let’s take a look at the datasets, we just extracted:

# Requires IPython widgets
# extraction.spectrum_observations.peek()


Finally you can write the extrated datasets to disk using the OGIP format (PHA, ARF, RMF, BKG, see here for details):

# ANALYSIS_DIR = "crab_analysis"
# extraction.write(outdir=ANALYSIS_DIR, overwrite=True)

If you want to read back the datasets from disk you can use:

# datasets = []
# for obs_id in obs_ids:
#     filename = ANALYSIS_DIR + "/ogip_data/pha_obs{}.fits".format(obs_id)
#     datasets.append(SpectrumDatasetOnOff.from_ogip_files(filename))

Fit spectrum

Now we’ll fit a global model to the spectrum. First we do a joint likelihood fit to all observations. If you want to stack the observations see below. We will also produce a debug plot in order to show how the global fit matches one of the individual observations.

model = PowerLawSpectralModel(
    index=2, amplitude=2e-11 * u.Unit("cm-2 s-1 TeV-1"), reference=1 * u.TeV

datasets_joint = extraction.spectrum_observations

for dataset in datasets_joint:
    dataset.model = model

fit_joint = Fit(datasets_joint)
result_joint =

# we make a copy here to compare it later
model_best_joint = model.copy()
model_best_joint.parameters.covariance = result_joint.parameters.covariance

        backend    : minuit
        method     : minuit
        success    : True
        message    : Optimization terminated successfully.
        nfev       : 47
        total stat : 113.85

plt.figure(figsize=(8, 6))
ax_spectrum, ax_residual = datasets_joint[0].plot_fit()
ax_spectrum.set_ylim(0, 25)
(0, 25)

Compute Flux Points

To round up our analysis we can compute flux points by fitting the norm of the global model in energy bands. We’ll use a fixed energy binning for now:

e_min, e_max = 0.7, 30
e_edges = np.logspace(np.log10(e_min), np.log10(e_max), 11) * u.TeV

Now we create an instance of the FluxPointsEstimator, by passing the dataset and the energy binning:

fpe = FluxPointsEstimator(datasets=datasets_joint, e_edges=e_edges)
flux_points =

Here is a the table of the resulting flux points:

Table length=10
e_refe_mine_maxref_dnderef_fluxref_efluxref_e2dndenormloglikenorm_errcounts [4]norm_errpnorm_errnnorm_ulsqrt_tstsnorm_scan [11]dloglike_scan [11]dndednde_uldnde_errdnde_errpdnde_errn
TeVTeVTeV1 / (cm2 s TeV)1 / (cm2 s)TeV / (cm2 s)TeV / (cm2 s)1 / (cm2 s TeV)1 / (cm2 s TeV)1 / (cm2 s TeV)1 / (cm2 s TeV)1 / (cm2 s TeV)
0.8590.7371.0024.210e-111.123e-119.564e-123.108e-110.87513.9200.1180 .. 00.1230.1131.13013.866192.2630.200 .. 5.00082.45006199452813 .. 359.518216992184763.683e-114.759e-114.959e-125.164e-124.758e-12
1.2611.0021.5881.530e-119.108e-121.126e-112.435e-110.94412.7660.08831 .. 360.0910.0851.13120.509420.6060.200 .. 5.000168.4105202093644 .. 644.96956374346341.444e-111.731e-111.347e-121.396e-121.300e-12
1.8521.5882.1605.561e-123.198e-125.871e-121.908e-111.1769.8880.14727 .. 120.1530.1411.49315.288233.7300.200 .. 5.000114.5510226385427 .. 250.195242430466046.539e-128.303e-128.164e-138.497e-137.840e-13
2.5182.1602.9362.475e-121.935e-124.829e-121.569e-111.2409.2080.17510 .. 110.1840.1671.62313.944194.4370.200 .. 5.00095.99339781990182 .. 177.99017210114623.068e-124.017e-124.338e-134.548e-134.136e-13
3.6972.9364.6568.993e-131.569e-125.687e-121.230e-110.94614.8940.15917 .. 110.1680.1511.29910.705114.5950.200 .. 5.00060.74745714205392 .. 211.276860788658728.508e-131.168e-121.433e-131.511e-131.357e-13
5.4294.6566.3303.269e-135.510e-132.964e-129.633e-121.1568.7580.2719 .. 50.2910.2511.7818.14166.2720.200 .. 5.00038.67728017805366 .. 78.63802027297813.780e-135.823e-138.851e-149.527e-148.203e-14
7.9716.33010.0371.188e-134.468e-133.491e-127.547e-121.07412.4200.2835 .. 40.3080.2601.7366.85546.9910.200 .. 5.00033.38530405289388 .. 76.720794107118681.276e-132.062e-133.365e-143.654e-143.092e-14
11.70310.03713.6474.317e-141.569e-131.820e-125.913e-120.94510.5010.4500 .. 10.5130.3922.1023.36911.3490.200 .. 5.00015.707789721282893 .. 36.257102124552144.079e-149.076e-141.943e-142.214e-141.693e-14
17.18313.64721.6361.569e-141.272e-132.143e-124.633e-120.3297.2300.2981 .. 00.3790.3291.2560.9400.8840.200 .. 5.0007.444575932216505 .. 40.42920707182635.157e-151.971e-144.682e-155.950e-155.157e-15
25.22921.63629.4195.702e-154.467e-141.117e-123.630e-120.0000.5240.0010 .. 00.2990.0001.1960.0020.0000.200 .. 5.0001.1929670228175648 .. 17.251475130606751.018e-206.818e-158.331e-181.704e-151.018e-20

Now we plot the flux points and their likelihood profiles. For the plotting of upper limits we choose a threshold of TS < 4.

plt.figure(figsize=(8, 5))
flux_points.table["is_ul"] = flux_points.table["ts"] < 4
ax = flux_points.plot(
    energy_power=2, flux_unit="erg-1 cm-2 s-1", color="darkorange"
<matplotlib.axes._subplots.AxesSubplot at 0x11854c908>

The final plot with the best fit model, flux points and residuals can be quickly made like this:

flux_points_dataset = FluxPointsDataset(
    data=flux_points, model=model_best_joint
plt.figure(figsize=(8, 6))

Stack observations

And alternative approach to fitting the spectrum is stacking all observations first and the fitting a model. For this we first stack the individual datasets:

dataset_stacked = Datasets(datasets_joint).stack_reduce()

Again we set the model on the dataset we would like to fit (in this case it’s only a singel one) and pass it to the Fit object:

dataset_stacked.model = model
stacked_fit = Fit([dataset_stacked])
result_stacked =

# make a copy to compare later
model_best_stacked = model.copy()
model_best_stacked.parameters.covariance = result_stacked.parameters.covariance

        backend    : minuit
        method     : minuit
        success    : True
        message    : Optimization terminated successfully.
        nfev       : 35
        total stat : 29.38

Table length=3
amplitude2.822e-111.894e-12cm-2 s-1 TeV-1nannanFalse
Table length=3
amplitude2.825e-111.895e-12cm-2 s-1 TeV-1nannanFalse

Finally, we compare the results of our stacked analysis to a previously published Crab Nebula Spectrum for reference. This is available in gammapy.spectrum.

plot_kwargs = {
    "energy_range": [0.1, 30] * u.TeV,
    "energy_power": 2,
    "flux_unit": "erg-1 cm-2 s-1",

# plot stacked model
model_best_stacked.plot(**plot_kwargs, label="Stacked analysis result")

# plot joint model
model_best_joint.plot(**plot_kwargs, label="Joint analysis result", ls="--")

create_crab_spectral_model().plot(**plot_kwargs, label="Crab reference")
<matplotlib.legend.Legend at 0x11b6ccb00>


Now you have learned the basics of a spectral analysis with Gammapy. To practice you can continue with the following exercises:

  • Fit a different spectral model to the data. You could try e.g. an ExpCutoffPowerLawSpectralModel or LogParabolaSpectralModel model.
  • Compute flux points for the stacked dataset.
  • Create a FluxPointsDataset with the flux points you have computed for the stacked dataset and fit the flux points again with obe of the spectral models. How does the result compare to the best fit model, that was directly fitted to the counts data?
[ ]: