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. Note, that there is also spectrum_pipe.ipynb which explains how to do the analysis using a high-level interface. This notebook is aimed at advanced users who want to script taylor-made analysis pipelines and implement new methods.

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:

For the global fit (using Sherpa and WSTAT in the background):

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
import sherpa

print("gammapy:", gammapy.__version__)
print("numpy:", np.__version__)
print("astropy", astropy.__version__)
print("regions", regions.__version__)
print("sherpa", sherpa.__version__)
gammapy: 0.12.dev8700
numpy: 1.16.2
astropy 3.1.2
regions 0.3
sherpa 4.11.0
import astropy.units as u
from astropy.coordinates import SkyCoord, Angle
from astropy.table import vstack as vstack_table
from regions import CircleSkyRegion
from import DataStore
from import ObservationStats, ObservationSummary
from gammapy.background.reflected import ReflectedRegionsBackgroundEstimator
from import EnergyBounds
from gammapy.spectrum import SpectrumExtraction
from gammapy.spectrum.models import PowerLaw
from gammapy.spectrum import FluxPointEstimator, FluxPointsDataset
from gammapy.maps import Map
from gammapy.utils.fitting import Fit

Configure logger

Most high level classes in gammapy have the possibility to turn on logging or debug output. We well configure the logger in the following. For more info see

# Setup the logger
import logging


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.background.BackgroundEstimate that serves as input for other classes in gammapy.

background_estimator = ReflectedRegionsBackgroundEstimator(
# print(background_estimator.result[0])
plt.figure(figsize=(8, 8))
/Users/deil/software/anaconda3/envs/gammapy-dev/lib/python3.7/site-packages/matplotlib/ UserWarning: Setting the 'color' property will overridethe edgecolor or facecolor properties.
  warnings.warn("Setting the 'color' property will override"

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: 225
Alpha: 0.083
Bkg events in On region: 18.75
Excess: 182.25
Excess / Background: 9.72
Gamma rate: 6.95 1 / min
Bkg rate: 0.72 1 / min
Sigma: 21.86


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 use a utility function to create it. We also provide the true energy binning to use.

e_reco = EnergyBounds.equal_log_spacing(0.1, 40, 40, unit="TeV")
e_true = EnergyBounds.equal_log_spacing(0.05, 100.0, 200, unit="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.

ANALYSIS_DIR = "crab_analysis"

extraction = SpectrumExtraction(

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

# Write output in the form of OGIP files: PHA, ARF, RMF, BKG
#, bkg_estimate=background_estimator.result, outdir=ANALYSIS_DIR)
*** Observation summary report ***
Observation Id: 23523
Livetime: 0.439 h
On events: 125
Off events: 98
Alpha: 0.083
Bkg events in On region: 8.17
Excess: 116.83
Excess / Background: 14.31
Gamma rate: 4.43 1 / min
Bkg rate: 0.01 1 / min
Sigma: 18.74
energy range: 0.88 TeV - 100.00 TeV

Look at observations

Now we will look at the files we just created. We will use the SpectrumObservation object that are still in memory from the extraction step. Note, however, that you could also read them from disk if you have written them in the step above. The ANALYSIS_DIR folder contains 4 FITS files for each observation. These files are described in detail here. In short, they correspond to the on vector, the off vector, the effectie area, and the energy dispersion.

# filename = ANALYSIS_DIR + '/ogip_data/pha_obs23523.fits'
# obs =

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


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 = PowerLaw(
    index=2, amplitude=2e-11 * u.Unit("cm-2 s-1 TeV-1"), reference=1 * u.TeV

datasets_joint = [
    obs.to_spectrum_dataset() for obs in 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()

        backend    : minuit
        method     : minuit
        success    : True
        nfev       : 56
        total stat : 133.89
        message    : Optimization terminated successfully.

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

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.

# Define energy binning
stacked_obs = extraction.spectrum_observations.stack()

e_min, e_max = stacked_obs.lo_threshold.to_value("TeV"), 30
e_edges = np.logspace(np.log10(e_min), np.log10(e_max), 15) * u.TeV
dataset_stacked = stacked_obs.to_spectrum_dataset()

fpe = FluxPointEstimator(
    datasets=[dataset_stacked], e_edges=e_edges, model=model
flux_points =
Table length=14
e_refe_mine_maxref_dnderef_fluxref_efluxref_e2dndenormloglikenorm_errnorm_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.7740.6810.8805.754e-111.148e-118.836e-123.449e-110.9372.0430.1470.1540.1401.26012.360152.7680.200 .. 5.00056.841232833160404 .. 227.564294091517675.390e-117.252e-118.466e-128.878e-128.063e-12
1.0000.8801.1362.911e-117.505e-127.458e-122.911e-110.9230.3130.1000.1030.0961.13617.748314.9760.200 .. 5.000114.10827174432183 .. 487.86359879216832.687e-113.308e-112.905e-123.004e-122.808e-12
1.2921.1361.4681.473e-114.905e-126.295e-122.457e-110.8970.0280.1160.1200.1111.14814.987224.5970.200 .. 5.00078.37352113843957 .. 358.7153848081451.322e-111.691e-111.704e-121.773e-121.636e-12
1.6681.4681.8967.454e-123.205e-125.313e-122.074e-111.1601.3980.1510.1570.1451.48714.582212.6310.200 .. 5.00096.2381260591199 .. 228.886316422156948.646e-121.108e-111.125e-121.171e-121.080e-12
2.2971.8962.7833.181e-122.852e-126.457e-121.678e-111.1460.1620.1440.1500.1381.45615.219231.6310.200 .. 5.000101.3026355684641 .. 250.069994364036123.644e-124.632e-124.576e-134.757e-134.398e-13
3.1622.7833.5941.358e-121.107e-123.478e-121.358e-111.2121.3380.2180.2310.2061.69910.563111.5820.200 .. 5.00052.61300378013567 .. 111.009085725775651.646e-122.306e-122.962e-133.132e-132.798e-13
4.0843.5944.6426.870e-137.232e-132.935e-121.146e-110.7730.1690.2080.2250.1921.2586.45141.6210.200 .. 5.00014.673263320318824 .. 107.631448081897335.310e-138.643e-131.428e-131.545e-131.316e-13
5.2754.6425.9953.476e-134.726e-132.477e-129.672e-121.0451.3030.2820.3080.2581.7096.76445.7500.200 .. 5.00020.98476725592962 .. 65.24707414612053.632e-135.940e-139.815e-141.070e-138.984e-14
6.8135.9957.7431.759e-133.089e-132.091e-128.164e-121.3730.5270.3810.4160.3482.2788.06965.1080.200 .. 5.00025.85228109133402 .. 36.2802137410048642.415e-134.006e-136.709e-147.319e-146.125e-14
8.7997.74310.0008.900e-142.019e-131.765e-126.891e-120.9281.8790.3890.4440.3401.9194.21517.7690.200 .. 5.0009.03652347499479 .. 34.741052915736438.258e-141.708e-133.466e-143.952e-143.028e-14
11.36510.00012.9154.503e-141.319e-131.490e-125.816e-121.0050.0220.4860.5610.4162.2854.07516.6040.200 .. 5.0006.108419580643113 .. 21.3779366677982244.526e-141.029e-132.188e-142.525e-141.875e-14
14.67812.91516.6812.279e-148.621e-141.257e-124.909e-120.2571.1830.3260.4410.2311.3961.1931.4220.200 .. 5.0001.2176598223010413 .. 24.9194860829918885.860e-153.180e-147.431e-151.006e-145.257e-15
18.95716.68121.5441.153e-145.634e-141.061e-124.143e-120.8730.0410.6800.8540.5292.9442.3605.5710.200 .. 5.0002.0491770958158293 .. 10.5092059270922041.006e-143.394e-147.839e-159.842e-156.102e-15
26.10221.54431.6234.920e-155.013e-141.290e-123.352e-120.0000.5910.0000.2640.0001.0570.0000.0000.200 .. 5.0001.3495624013823302 .. 19.5474949007054347.648e-305.200e-151.995e-221.298e-157.648e-30

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 0x12202f320>

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

model.parameters.covariance = result_joint.parameters.covariance
flux_points_dataset = FluxPointsDataset(data=flux_points, model=model)
plt.figure(figsize=(8, 6))

Stack observations

And alternative approach to fitting the spectrum is stacking all observations first and the fitting a model to the stacked observation. This works as follows. A comparison to the joint likelihood fit is also printed.

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

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

        backend    : minuit
        method     : minuit
        success    : True
        nfev       : 31
        total stat : 30.35
        message    : Optimization terminated successfully.

Table length=3
amplitude2.911e-11nancm-2 s-1 TeV-1nannanFalse
Table length=3
amplitude2.909e-111.782e-12cm-2 s-1 TeV-1nannanFalse


Some things we might do:

  • Fit a different spectral model (ECPL or CPL or …)

  • Use different method or parameters to compute the flux points

  • Do a chi^2 fit to the flux points and compare

TODO: give pointers how to do this (and maybe write a notebook with solutions)

# Start exercises here
[ ]: