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

Spectral analysis with Gammapy

Introduction

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!

Setup

As usual, we’ll start with some setup …

[1]:
%matplotlib inline
import matplotlib.pyplot as plt
[2]:
# 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.10
numpy: 1.16.0
astropy 3.1.1
regions 0.3
sherpa 4.10.2
[3]:
import astropy.units as u
from astropy.coordinates import SkyCoord, Angle
from astropy.table import vstack as vstack_table
from regions import CircleSkyRegion
from gammapy.data import DataStore, Observations
from gammapy.data import ObservationStats, ObservationSummary
from gammapy.background.reflected import ReflectedRegionsBackgroundEstimator
from gammapy.utils.energy import EnergyBounds
from gammapy.spectrum import (
    SpectrumExtraction,
    SpectrumObservation,
    SpectrumFit,
    SpectrumResult,
)
from gammapy.spectrum.models import (
    PowerLaw,
    ExponentialCutoffPowerLaw,
    LogParabola,
)
from gammapy.spectrum import (
    FluxPoints,
    SpectrumEnergyGroupMaker,
    FluxPointEstimator,
)
from gammapy.maps import Map

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 https://docs.python.org/2/howto/logging.html#logging-basic-tutorial

[4]:
# Setup the logger
import logging

logging.basicConfig()
logging.getLogger("gammapy.spectrum").setLevel("WARNING")

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.

[5]:
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.

[6]:
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 http://gamma-sky.net/ 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.

[7]:
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)
exclusion_mask.data = mask
exclusion_mask.plot()
[7]:
(<Figure size 432x288 with 1 Axes>,
 <matplotlib.axes._subplots.WCSAxesSubplot at 0x1198546d8>,
 None)
../_images/notebooks_spectrum_analysis_14_1.png

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.

[8]:
background_estimator = ReflectedRegionsBackgroundEstimator(
    observations=observations,
    on_region=on_region,
    exclusion_mask=exclusion_mask,
)

background_estimator.run()
[9]:
# print(background_estimator.result[0])
[10]:
plt.figure(figsize=(8, 8))
background_estimator.plot(add_legend=True)
/Users/jer/anaconda/envs/gammapy-dev/lib/python3.7/site-packages/matplotlib/patches.py:75: UserWarning: Setting the 'color' property will overridethe edgecolor or facecolor properties.
  warnings.warn("Setting the 'color' property will override"
[10]:
(<Figure size 576x576 with 1 Axes>,
 <matplotlib.axes._subplots.WCSAxesSubplot at 0x1194fda20>,
 None)
../_images/notebooks_spectrum_analysis_18_2.png

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.

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

print(stats[1])

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

obs_summary.plot_excess_vs_livetime(ax=ax1)
ax2 = fig.add_subplot(122)
obs_summary.plot_significance_vs_livetime(ax=ax2)
*** 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

[11]:
<matplotlib.axes._subplots.AxesSubplot at 0x11c5c0ef0>
../_images/notebooks_spectrum_analysis_20_2.png

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.

[12]:
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.

[13]:
ANALYSIS_DIR = "crab_analysis"

extraction = SpectrumExtraction(
    observations=observations,
    bkg_estimate=background_estimator.result,
    containment_correction=False,
)
extraction.run()

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

print(extraction.spectrum_observations[0])
# Write output in the form of OGIP files: PHA, ARF, RMF, BKG
# extraction.run(observations=observations, 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.

[14]:
# filename = ANALYSIS_DIR + '/ogip_data/pha_obs23523.fits'
# obs = SpectrumObservation.read(filename)

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

extraction.spectrum_observations[0].peek()
../_images/notebooks_spectrum_analysis_26_0.png

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.

[15]:
model = PowerLaw(
    index=2, amplitude=2e-11 * u.Unit("cm-2 s-1 TeV-1"), reference=1 * u.TeV
)

joint_fit = SpectrumFit(obs_list=extraction.spectrum_observations, model=model)
joint_fit.run()
joint_result = joint_fit.result
[16]:
ax0, ax1 = joint_result[0].plot(figsize=(8, 8))
ax0.set_ylim(0, 20)
print(joint_result[0])

Fit result info
---------------
Model: PowerLaw

Parameters:

           name     value     error        unit      min max frozen
        --------- --------- --------- -------------- --- --- ------
            index 2.663e+00 7.100e-02                nan nan  False
        amplitude 2.912e-11 1.782e-12 cm-2 s-1 TeV-1 nan nan  False
        reference 1.000e+00 0.000e+00            TeV nan nan   True

Covariance:

           name     index   amplitude reference
        --------- --------- --------- ---------
            index 5.042e-03 7.189e-14 0.000e+00
        amplitude 7.189e-14 3.176e-24 0.000e+00
        reference 0.000e+00 0.000e+00 0.000e+00

Statistic: 42.226 (wstat)
Fit Range: [  0.87992254 100.        ] TeV

../_images/notebooks_spectrum_analysis_29_1.png

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.

[17]:
# Define energy binning
stacked_obs = extraction.spectrum_observations.stack()

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


seg = SpectrumEnergyGroupMaker(obs=stacked_obs)
seg.compute_groups_fixed(ebounds=ebounds)

print(seg.groups)
SpectrumEnergyGroups:
energy_group_idx bin_idx_min bin_idx_max  bin_type     energy_min         energy_max
                                                          TeV                TeV
---------------- ----------- ----------- --------- ------------------ ------------------
               0           0          32 underflow               0.01 0.6812920690579611
               1          33          34    normal 0.6812920690579611 0.8799225435691069
               2          35          36    normal 0.8799225435691069 1.1364636663857242
               3          37          38    normal 1.1364636663857242  1.467799267622069
               4          39          40    normal  1.467799267622069 1.8957356524063753
               5          41          43    normal 1.8957356524063753  2.782559402207123
               6          44          45    normal  2.782559402207123  3.593813663804626
               7          46          47    normal  3.593813663804626 4.6415888336127775
               8          48          49    normal 4.6415888336127775  5.994842503189409
               9          50          51    normal  5.994842503189409  7.742636826811269
              10          52          53    normal  7.742636826811269               10.0
              11          54          55    normal               10.0 12.915496650148826
              12          56          57    normal 12.915496650148826 16.681005372000573
              13          58          59    normal 16.681005372000573  21.54434690031882
              14          60          62    normal  21.54434690031882 31.622776601683793
              15          63          71  overflow 31.622776601683793              100.0

[18]:
fpe = FluxPointEstimator(
    obs=stacked_obs, groups=seg.groups, model=joint_result[0].model
)
flux_points = fpe.run()
[19]:
flux_points.table_formatted
[19]:
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)
float64float64float64float64float64float64float64float64float64float64float64float64float64float64float64float64float64float64float64float64float64float64
0.7740.6810.8805.755e-111.149e-118.838e-123.450e-110.9362.0420.1470.1540.1401.26012.360152.7690.200 .. 5.00056.82736077344509 .. 227.660830865326665.390e-117.252e-118.466e-128.877e-128.063e-12
1.0000.8801.1362.912e-117.506e-127.458e-122.912e-110.9230.3190.1000.1030.0961.13617.742314.7750.200 .. 5.000114.08743116543133 .. 487.950845101761442.687e-113.308e-112.905e-123.004e-122.808e-12
1.2921.1361.4681.473e-114.904e-126.294e-122.457e-110.8970.0270.1160.1200.1111.14714.971224.1240.200 .. 5.00078.24025777805605 .. 358.718082989308471.322e-111.690e-111.704e-121.773e-121.636e-12
1.6681.4681.8967.452e-123.204e-125.312e-122.074e-111.1601.3970.1510.1570.1451.48714.582212.6320.200 .. 5.00096.25330907994987 .. 228.794779506126648.646e-121.108e-111.125e-121.171e-121.080e-12
2.2971.8962.7833.180e-122.850e-126.454e-121.677e-111.1460.1620.1440.1500.1381.45715.219231.6310.200 .. 5.000101.33520129148684 .. 249.879783331533563.644e-124.632e-124.575e-134.757e-134.398e-13
3.1622.7833.5941.357e-121.106e-123.475e-121.357e-111.2131.3380.2180.2310.2061.70010.563111.5820.200 .. 5.00052.63650430715782 .. 110.877597159866711.645e-122.306e-122.962e-133.131e-132.798e-13
4.0843.5944.6426.863e-137.226e-132.933e-121.145e-110.7740.1690.2080.2250.1921.2596.45141.6210.200 .. 5.00014.68576252786226 .. 107.494615854146745.310e-138.642e-131.428e-131.545e-131.316e-13
5.2754.6425.9953.472e-134.721e-132.475e-129.662e-121.0461.3030.2830.3080.2591.7116.76445.7510.200 .. 5.00021.000351801111176 .. 65.136039521872183.632e-135.940e-139.814e-141.071e-138.981e-14
6.8135.9957.7431.757e-133.085e-132.089e-128.153e-121.3720.5370.3820.4170.3492.2788.03164.4970.200 .. 5.00025.594608964059326 .. 36.241240731949762.411e-134.001e-136.709e-147.319e-146.125e-14
8.7997.74310.0008.887e-142.016e-131.762e-126.881e-120.9291.8800.3900.4450.3411.9224.21517.7680.200 .. 5.0009.045165002963646 .. 34.667941351558578.259e-141.708e-133.466e-143.951e-143.029e-14
11.36510.00012.9154.496e-141.317e-131.487e-125.807e-121.0010.0260.4870.5620.4172.2843.94415.5520.200 .. 5.0005.956190625912367 .. 21.3622360878516774.503e-141.027e-132.188e-142.525e-141.876e-14
14.67812.91516.6812.274e-148.606e-141.255e-124.900e-120.2581.1830.3270.4420.2311.3981.1931.4220.200 .. 5.0001.218046461095414 .. 24.869917457151975.860e-153.180e-147.430e-151.006e-145.257e-15
18.95716.68121.5441.151e-145.623e-141.059e-124.135e-120.8630.0490.6810.8550.5292.9382.3035.3020.200 .. 5.0001.962892508344067 .. 10.5243314949586579.928e-153.380e-147.833e-159.843e-156.092e-15
26.10221.54431.6234.910e-155.002e-141.287e-123.345e-120.0000.5910.0000.2640.0001.0590.0000.0000.200 .. 5.0001.3479592650749823 .. 19.5074164930217157.631e-305.198e-151.993e-221.298e-157.631e-30

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

[20]:
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"
)
flux_points.to_sed_type("e2dnde").plot_likelihood(ax=ax)
[20]:
<matplotlib.axes._subplots.AxesSubplot at 0x11daa9f98>
../_images/notebooks_spectrum_analysis_35_1.png

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

[21]:
spectrum_result = SpectrumResult(
    points=flux_points, model=joint_result[0].model
)
ax0, ax1 = spectrum_result.plot(
    energy_range=joint_fit.result[0].fit_range,
    energy_power=2,
    flux_unit="erg-1 cm-2 s-1",
    fig_kwargs=dict(figsize=(8, 8)),
)

ax0.set_xlim(0.4, 50)
[21]:
(0.4, 50)
../_images/notebooks_spectrum_analysis_37_1.png

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.

[22]:
stacked_obs = extraction.spectrum_observations.stack()

stacked_fit = SpectrumFit(obs_list=stacked_obs, model=model)
stacked_fit.run()
[22]:
FitResult

    backend    : minuit
    method     : minuit
    success    : True
    nfev       : 31
    total stat : 30.31
    message    : Optimization terminated successfully.
[23]:
stacked_result = stacked_fit.result
print(stacked_result[0])

Fit result info
---------------
Model: PowerLaw

Parameters:

           name     value     error        unit      min max frozen
        --------- --------- --------- -------------- --- --- ------
            index 2.667e+00 7.147e-02                nan nan  False
        amplitude 2.909e-11 1.784e-12 cm-2 s-1 TeV-1 nan nan  False
        reference 1.000e+00 0.000e+00            TeV nan nan   True

Covariance:

           name     index   amplitude reference
        --------- --------- --------- ---------
            index 5.108e-03 7.241e-14 0.000e+00
        amplitude 7.241e-14 3.183e-24 0.000e+00
        reference 0.000e+00 0.000e+00 0.000e+00

Statistic: 30.311 (wstat)
Fit Range: [  0.68129207 100.        ] TeV

[24]:
stacked_table = stacked_result[0].to_table(format=".3g")
stacked_table["method"] = "stacked"
joint_table = joint_result[0].to_table(format=".3g")
joint_table["method"] = "joint"
total_table = vstack_table([stacked_table, joint_table])
print(
    total_table["method", "index", "index_err", "amplitude", "amplitude_err"]
)
 method index index_err    amplitude     amplitude_err
                        1 / (cm2 s TeV) 1 / (cm2 s TeV)
------- ----- --------- --------------- ---------------
stacked  2.67    0.0715        2.91e-11        1.78e-12
  joint  2.67    0.0715        2.91e-11        1.78e-12

Exercises

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)

[25]:
# Start exercises here