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

Spectral analysis#


  • Understanding how spectral extraction is performed in Cherenkov astronomy, in particular regarding OFF background measurements.

  • Understanding the basics data reduction and modeling/fitting process with the gammapy library API as shown in the first gammapy analysis with the gammapy library API tutorial


While 3D analyses allow in principle to consider complex field of views containing overlapping gamma-ray sources, in many cases we might have an observation with a single, strong, point-like source in the field of view. A spectral analysis, in that case, might consider all the events inside a source (or ON) region and bin them in energy only, obtaining 1D datasets.

In classical Cherenkov astronomy, the background estimation technique associated with this method measures the number of events in OFF regions taken in regions of the field-of-view devoid of gamma-ray emitters, where the background rate is assumed to be equal to the one in the ON region.

This allows to use a specific fit statistics for ON-OFF measurements, the wstat (see gammapy.stats.wstat), where no background model is assumed. Background is treated as a set of nuisance parameters. This removes some systematic effects connected to the choice or the quality of the background model. But this comes at the expense of larger statistical uncertainties on the fitted model parameters.

Objective: perform a full region based spectral analysis of 4 Crab observations of H.E.S.S. data release 1 and fit the resulting datasets.


Here, as usual, we use the to retrieve a list of selected observations ( Then, we define the ON region containing the source and the geometry of the gammapy.datasets.SpectrumDataset object we want to produce. We then create the corresponding dataset Maker.

We have to define the Maker object that will extract the OFF counts from reflected regions in the field-of-view. To ensure we use data in an energy range where the quality of the IRFs is good enough we also create a safe range Maker.

We can then proceed with data reduction with a loop over all selected observations to produce datasets in the relevant geometry.

We can then explore the resulting datasets and look at the cumulative signal and significance of our source. We finally proceed with model fitting.

In practice, we have to: - Create a poiting to the relevant data - Apply an observation selection to produce a list of observations, a object. - Define a geometry of the spectrum we want to produce: - Create a ~regions.CircleSkyRegion for the ON extraction region - Create a gammapy.maps.MapAxis for the energy binnings: one for the reconstructed (i.e. measured) energy, the other for the true energy (i.e. the one used by IRFs and models) - Create the necessary makers : - the spectrum dataset maker : gammapy.makers.SpectrumDatasetMaker - the OFF background maker, here a gammapy.makers.ReflectedRegionsBackgroundMaker - and the safe range maker : gammapy.makers.SafeMaskMaker - Perform the data reduction loop. And for every observation: - Apply the makers sequentially to produce a gammapy.datasets.SpectrumDatasetOnOff - Append it to list of datasets - Define the gammapy.modeling.models.SkyModel to apply to the dataset. - Create a gammapy.modeling.Fit object and run it to fit the model parameters - Apply a gammapy.estimators.FluxPointsEstimator to compute flux points for the spectral part of the fit.


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.20.1
numpy: 1.22.3
astropy 5.0.4
regions 0.6
from pathlib import Path
import astropy.units as u
from astropy.coordinates import SkyCoord, Angle
from regions import CircleSkyRegion
from gammapy.maps import MapAxis, RegionGeom, WcsGeom
from gammapy.modeling import Fit
from import DataStore
from gammapy.datasets import (
from gammapy.modeling.models import (
from gammapy.makers import (
from gammapy.estimators import FluxPointsEstimator
from gammapy.visualization import plot_spectrum_datasets_off_regions

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.

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
geom = WcsGeom.create(
    npix=(150, 150), binsz=0.05, skydir=skydir, proj="TAN", frame="icrs"

exclusion_mask = ~geom.region_mask([exclusion_region])

Run data reduction chain#

We begin with the configuration of the maker classes:

energy_axis = MapAxis.from_energy_bounds(
    0.1, 40, nbin=10, per_decade=True, unit="TeV", name="energy"
energy_axis_true = MapAxis.from_energy_bounds(
    0.05, 100, nbin=20, per_decade=True, unit="TeV", name="energy_true"

geom = RegionGeom.create(region=on_region, axes=[energy_axis])
dataset_empty = SpectrumDataset.create(
    geom=geom, energy_axis_true=energy_axis_true
dataset_maker = SpectrumDatasetMaker(
    containment_correction=True, selection=["counts", "exposure", "edisp"]
bkg_maker = ReflectedRegionsBackgroundMaker(exclusion_mask=exclusion_mask)
safe_mask_masker = SafeMaskMaker(methods=["aeff-max"], aeff_percent=10)
datasets = Datasets()

for obs_id, observation in zip(obs_ids, observations):
    dataset =
        dataset_empty.copy(name=str(obs_id)), observation
    dataset_on_off =, observation)
    dataset_on_off =, observation)
CPU times: user 6.68 s, sys: 202 ms, total: 6.88 s
Wall time: 7.38 s

Plot off regions#

plt.figure(figsize=(8, 8))
ax = exclusion_mask.plot()
on_region.to_pixel(ax.wcs).plot(ax=ax, edgecolor="k")
plot_spectrum_datasets_off_regions(ax=ax, datasets=datasets)
<WCSAxesSubplot:xlabel='Right Ascension', ylabel='Declination'>

Source statistic#

Next we’re going to look at the overall source statistics in our signal region.

info_table = datasets.info_table(cumulative=True)
Table length=4
m2 sm2 sss1 / s1 / s1 / s
    info_table["livetime"].to("h"), info_table["excess"], marker="o", ls="none"
plt.xlabel("Livetime [h]")
plt.xlabel("Livetime [h]")

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

path = Path("spectrum_analysis")
for dataset in datasets:
        filename=path / f"obs_{}.fits.gz", overwrite=True

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

datasets = Datasets()

for obs_id in obs_ids:
    filename = path / f"obs_{obs_id}.fits.gz"

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.

spectral_model = ExpCutoffPowerLawSpectralModel(
    amplitude=1e-12 * u.Unit("cm-2 s-1 TeV-1"),
    lambda_=0.1 * u.Unit("TeV-1"),
    reference=1 * u.TeV,
model = SkyModel(spectral_model=spectral_model, name="crab")

datasets.models = [model]

fit_joint = Fit()
result_joint =

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

Fit quality and model residuals#

We can access the results dictionary to see if the fit converged:


        backend    : minuit
        method     : migrad
        success    : True
        message    : Optimization terminated successfully.
        nfev       : 244
        total stat : 86.12


        backend    : minuit
        method     : hesse
        success    : True
        message    : Hesse terminated successfully.

and check the best-fit parameters

Table length=5
crabspectralamplitude4.7913e-11cm-2 s-1 TeV-13.600e-12nannanFalseTrue

A simple way to inspect the model residuals is using the function ~SpectrumDataset.plot_fit()

ax_spectrum, ax_residuals = datasets[0].plot_fit()
ax_spectrum.set_ylim(0.1, 40)

For more ways of assessing fit quality, please refer to the dedicated modeling and fitting tutorial.

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
energy_edges = np.geomspace(e_min, e_max, 11) * u.TeV

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

fpe = FluxPointsEstimator(
    energy_edges=energy_edges, source="crab", selection_optional="all"
flux_points =

Here is a the table of the resulting flux points:

flux_points.to_table(sed_type="dnde", formatted=True)
Table length=10
e_refe_mine_maxdndednde_errdnde_errpdnde_errndnde_ultssqrt_tsnpred [4]npred_excess [4]statis_ulcounts [4]successnorm_scan [11]stat_scan [11]
TeVTeVTeV1 / (cm2 s TeV)1 / (cm2 s TeV)1 / (cm2 s TeV)1 / (cm2 s TeV)1 / (cm2 s TeV)
0.8230.7370.9206.950e-117.224e-127.462e-127.000e-128.496e-11318.30817.84131.36646258047154 .. 23.88972920716321728.875505 .. 21.7202638.252False30.0 .. 25.0True0.200 .. 5.000140.739 .. 451.124
1.1480.9201.4342.884e-112.581e-122.654e-122.510e-123.430e-11449.77021.20840.721594294634784 .. 29.62744928687194738.467556 .. 27.44928212.649False43.0 .. 35.0True0.200 .. 5.000182.603 .. 693.653
1.7901.4342.2351.104e-111.132e-121.168e-121.096e-121.345e-11350.10918.71131.973739526878333 .. 21.12462051291238729.863094 .. 19.9055826.105False37.0 .. 21.0True0.200 .. 5.000150.799 .. 424.855
2.7902.2353.4833.462e-124.450e-134.631e-134.273e-134.426e-12219.11414.80220.86827471761865 .. 13.38555309646616819.729824 .. 12.43493812.915False13.0 .. 17.0True0.200 .. 5.000102.546 .. 293.446
3.8923.4834.3488.756e-132.576e-132.800e-132.362e-131.482e-1236.2356.0204.959042980000916 .. 2.7024813304763824.168653 .. 2.53700954.035False8.0 .. 2.0True0.200 .. 5.00013.594 .. 125.092
5.4294.3486.7785.335e-131.079e-131.149e-131.011e-137.776e-1386.9269.3238.52067876691984 .. 5.1731515929736398.258547 .. 4.978128411.815False12.0 .. 6.0True0.200 .. 5.00047.101 .. 132.109
8.4626.77810.5641.623e-134.547e-144.941e-144.186e-142.695e-1338.1086.1735.121380116204808 .. 3.10554850724478954.620307 .. 2.7313458.980False5.0 .. 5.0True0.200 .. 5.00028.474 .. 55.783
11.80310.56413.1895.214e-143.008e-143.529e-142.546e-141.339e-137.9112.8131.2131436603915728 .. 0.73238595665644071.1362206 .. 0.67833197.934False0.0 .. 0.0True0.200 .. 5.00012.285 .. 18.679
16.46513.18920.5561.177e-147.816e-159.399e-156.393e-153.395e-145.2692.2950.9432263496672387 .. 0.69875750777488540.84752977 .. 0.509568336.611False1.0 .. 0.0True0.200 .. 5.0009.622 .. 17.557
25.66320.55632.040nannan1.094e-15nan4.378e-15-0.012-0.0000.07895530597715192 .. 0.109373779883999840.002032229 .. 0.00126567180.633True0.0 .. 0.0False0.200 .. 5.0000.866 .. 6.774

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))
ax = flux_points.plot(sed_type="e2dnde", color="darkorange")
flux_points.plot_ts_profiles(ax=ax, sed_type="e2dnde");

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, models=model_best_joint

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).stack_reduce()

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

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

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

        backend    : minuit
        method     : migrad
        success    : True
        message    : Optimization terminated successfully.
        nfev       : 54
        total stat : 8.16


        backend    : minuit
        method     : hesse
        success    : True
        message    : Hesse terminated successfully.

Table length=5
spectralamplitude4.7913e-11cm-2 s-1 TeV-13.600e-12nannanFalseTrue
Table length=5
spectralamplitude4.7800e-11cm-2 s-1 TeV-13.566e-12nannanFalseTrue

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

plot_kwargs = {
    "energy_bounds": [0.1, 30] * u.TeV,
    "sed_type": "e2dnde",
    "yunits": u.Unit("erg cm-2 s-1"),

# plot stacked model
    **plot_kwargs, label="Stacked analysis result"
    facecolor="blue", alpha=0.3, **plot_kwargs

# plot joint model
    **plot_kwargs, label="Joint analysis result", ls="--"
    facecolor="orange", alpha=0.3, **plot_kwargs

    **plot_kwargs, label="Crab reference"
<matplotlib.legend.Legend at 0x146fe3af0>


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

What next?#

The methods shown in this tutorial is valid for point-like or midly extended sources where we can assume that the IRF taken at the region center is valid over the whole region. If one wants to extract the 1D spectrum of a large source and properly average the response over the extraction region, one has to use a different approach explained in the extended source spectral analysis tutorial.