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

Spectral analysis of extended sources



Many VHE sources in the Galaxy are extended. Studying them with a 1D spectral analysis is more complex than studying point sources. One often has to use complex (i.e. non circular) regions and more importantly, one has to take into account the fact that the instrument response is non uniform over the selectred region. A typical example is given by the supernova remnant RX J1713-3935 which is nearly 1 degree in diameter. See the following article.

Objective: Measure the spectrum of RX J1713-3945 in a 1 degree region fully enclosing it.

Proposed approach:

We have seen in the general presentation of the spectrum extraction for point sources, see the corresponding notebook, that Gammapy uses specific datasets makers to first produce reduced spectral data and then to extract OFF measurements with reflected background techniques: the gammapy.spectrum.SpectrumDatasetMaker and the gammapy.spectrum.ReflectedRegionsBackgroundMaker. The former simply computes the reduced IRF at the center of the ON region (assumed to be circular).

This is no longer valid for extended sources. To be able to compute average responses in the ON region, Gammapy relies on the creation of a cube enclosing it (i.e. a gammapy.cube.MapDataset) which can be reduced to a simple spectrum (i.e. a gammapy.spectrum.SpectrumDataset). We can then proceed with the OFF extraction as the standard point source case.

In summary, we have to:

Here, we will use the RX J1713-3945 observations from the H.E.S.S. first public test data release. The tutorial is implemented with the intermediate level API.


As usual, we’ll start with some general imports…

%matplotlib inline
import matplotlib.pyplot as plt
import astropy.units as u
from astropy.coordinates import SkyCoord, Angle
from regions import CircleSkyRegion
from gammapy.maps import Map, MapAxis, WcsGeom
from gammapy.modeling import Fit, Datasets
from import DataStore
from gammapy.modeling.models import (
from gammapy.cube import SafeMaskMaker, MapDataset, MapDatasetMaker
from gammapy.spectrum import ReflectedRegionsBackgroundMaker

Select the data

We first set the datastore and retrieve a few observations from our source.

datastore = DataStore.from_dir("$GAMMAPY_DATA/hess-dl3-dr1/")
obs_ids = [20326, 20327, 20349, 20350, 20396, 20397]
# In case you want to use all RX J1713 data in the HESS DR1
# other_ids=[20421, 20422, 20517, 20518, 20519, 20521, 20898, 20899, 20900]

observations = datastore.get_observations(obs_ids)

Prepare the datasets creation

Select the ON region

Here we take a simple 1 degree circular region because it fits well with the morphology of RX J1713-3945. More complex regions could be used e.g. ~regions.EllipseSkyRegion or ~regions.RectangleSkyRegion.

target_position = SkyCoord(347.3, -0.5, unit="deg", frame="galactic")
radius = Angle("0.5 deg")
on_region = CircleSkyRegion(target_position, radius)

Define the geometries

This part is especially important. - We have to define first energy axes. They define the axes of the resulting ~gammapy.SpectrumDatasetOnOff. In particular, we have to be careful to the true energy axis: it has to cover a larger range than the reconstructed energy one. - Then we define the geometry itself. It does not need to be very finely binned and should enclose all the ON region. To limit CPU and memory usage, one should avoid using a much larger region.

# The binning of the final spectrum is defined here.
energy_axis = MapAxis.from_energy_bounds(0.3, 40.0, 10, unit="TeV")

# Reduced IRFs are defined in true energy (i.e. not measured energy).
energy_axis_true = MapAxis.from_energy_bounds(0.05, 100, 30, unit="TeV")

# Here we use 1.5 degree which is slightly larger than needed.
geom = WcsGeom.create(
    width=(1.5, 1.5),

Create the makers

First we instantiate the target gammapy.cube.MapDataset.

stacked = MapDataset.create(
    geom=geom, energy_axis_true=energy_axis_true, name="rxj-stacked"

Now we create its associated maker. Here we need to produce, counts, exposure and edisp (energy dispersion) entries. PSF and IRF background are not needed, therefore we don’t compute them.

maker = MapDatasetMaker(selection=["counts", "exposure", "edisp"])

Now we create the OFF background maker for the spectra. If we have an exclusion region, we have to pass it here. We also define the safe range maker.

bkg_maker = ReflectedRegionsBackgroundMaker()
safe_mask_maker = SafeMaskMaker(
    methods=["aeff-default", "aeff-max"], aeff_percent=10

Perform the data reduction loop.

We can now run over selected observations. For each of them, we: - create the map dataset and stack it on our target dataset. - squeeze the map dataset to a spectral dataset in the ON region - Compute the OFF and create a gammapy.spectrum.SpectrumDatasetOnOff object - Run the safe mask maker on it - Add the gammapy.spectrum.SpectrumDatasetOnOff to the list.

spectrum_datasets = []

for obs in observations:
    # A MapDataset is filled in this geometry
    dataset =, obs)
    # To make images, the resulting dataset cutout is stacked onto the final one

    # Extract 1D spectrum
    spectrum_dataset = dataset.to_spectrum_dataset(on_region)
    # Compute OFF
    spectrum_dataset =, obs)
    # Define safe mask
    spectrum_dataset =, obs)
    # Append dataset to the list

datasets = Datasets(spectrum_datasets)
CPU times: user 2.49 s, sys: 166 ms, total: 2.66 s
Wall time: 2.75 s

Explore the results

First let’s look at the data to see if our region is correct. We plot it over the excess. To do so we convert it to a pixel region using the WCS information stored on the geom.

stacked.counts.sum_over_axes().smooth(width="0.05 deg").plot()
<matplotlib.axes._subplots.WCSAxesSubplot at 0x1c1e586e80>

We now turn to the spectral datasets. We can peek at their content:


Cumulative excess and signficance

Finally, we can look at cumulative significance and number of excesses. This is done with the info_table method of gammapy.modeling.Datasets.

info_table = datasets.info_table(cumulative=True)
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(121)
plt.xlabel("Livetime [h]")
plt.ylabel("Excess events")

ax = fig.add_subplot(122)
plt.xlabel("Livetime [h]")

Perform spectral model fitting

Here we perform a joint fit.

We first create the model, here a simple powerlaw, and assign it to every dataset in the gammapy.modeling.Datasets.

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

for dataset in datasets:
    dataset.models = model

Now we can run the fit

fit_joint = Fit(datasets)
result_joint =

        backend    : minuit
        method     : minuit
        success    : True
        message    : Optimization terminated successfully.
        nfev       : 39
        total stat : 73.21

Explore the fit results

First the fitted parameters values and their errors.

Table length=3
amplitude1.286e-111.022e-12cm-2 s-1 TeV-1nannanFalse

Then plot the fit result to compare measured and expected counts. Rather than plotting them for each individual dataset, we stack all datasets and plot the fit result on the result.

# First stack them all
reduced = datasets.stack_reduce()
# Assign the fitted model
reduced.models = model
# Plot the result
(<matplotlib.axes._subplots.AxesSubplot at 0x1c1e521c18>,
 <matplotlib.axes._subplots.AxesSubplot at 0x1c1e521ac8>)
[ ]: