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 …

In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
In [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.8.dev7377
numpy: 1.14.3
astropy 3.0.4
regions 0.3
sherpa 4.10.0
In [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, ObservationList
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

In [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.

In [5]:
datastore = DataStore.from_dir("$GAMMAPY_EXTRA/datasets/hess-dl3-dr1/")
obs_ids = [23523, 23526, 23559, 23592]
obs_list = datastore.obs_list(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.

In [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.

In [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()
Out[7]:
(<Figure size 432x288 with 1 Axes>,
 <matplotlib.axes._subplots.WCSAxesSubplot at 0x11e366cf8>,
 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.

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

background_estimator.run()
In [9]:
# print(background_estimator.result[0])
In [10]:
plt.figure(figsize=(8, 8))
background_estimator.plot()
/Users/deil/software/anaconda3/envs/gammapy-dev/lib/python3.6/site-packages/matplotlib/patches.py:83: UserWarning: Setting the 'color' property will overridethe edgecolor or facecolor properties.
  warnings.warn("Setting the 'color' property will override"
Out[10]:
(<Figure size 576x576 with 1 Axes>,
 <matplotlib.axes._subplots.WCSAxesSubplot at 0x11e545dd8>,
 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.

In [11]:
stats = []
for obs, bkg in zip(obs_list, background_estimator.result):
    stats.append(ObservationStats.from_obs(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: 7.67 1 / min
Bkg rate: 0.72 1 / min
Sigma: 21.86

Out[11]:
<matplotlib.axes._subplots.AxesSubplot at 0x10db4bcf8>
../_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.

In [12]:
e_reco = EnergyBounds.equal_log_spacing(0.1, 40, 40, unit="TeV")
e_true = EnergyBounds.equal_log_spacing(0.05, 100., 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.

In [13]:
ANALYSIS_DIR = "crab_analysis"

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

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

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

extraction.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.

In [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.observations, model=model)
joint_fit.run()
joint_result = joint_fit.result
In [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
        --------- --------- --------- --------------- --------- ---
            index 2.663e+00 7.100e-02                       nan nan
        amplitude 2.912e-11 1.782e-12 1 / (cm2 s TeV)       nan nan
        reference 1.000e+00 0.000e+00             TeV 0.000e+00 nan

Covariance:

           name           index               amplitude        reference
        --------- --------------------- ---------------------- ---------
            index  0.005041573853657579  7.188783815490174e-14       0.0
        amplitude 7.188783815490174e-14 3.1763363858771278e-24       0.0
        reference                   0.0                    0.0       0.0

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

../_images/notebooks_spectrum_analysis_29_1.png

Compute Flux Points

To round up out 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.

In [17]:
# Define energy binning
ebounds = [0.3, 1.1, 3, 10.1, 30] * u.TeV

stacked_obs = extraction.observations.stack()

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          26 underflow                0.01 0.31622776601683794
               1          27          36    normal 0.31622776601683794  1.1364636663857242
               2          37          44    normal  1.1364636663857242  3.1622776601683795
               3          45          53    normal  3.1622776601683795                10.0
               4          54          62    normal                10.0  31.622776601683793
               5          63          71  overflow  31.622776601683793               100.0

In [18]:
fpe = FluxPointEstimator(
    obs=stacked_obs, groups=seg.groups, model=joint_result[0].model
)
fpe.compute_points()
In [19]:
fpe.flux_points.plot()
fpe.flux_points.table
Out[19]:
Table length=4
e_refe_mine_maxdndednde_errdnde_ulis_ulsqrt_tsdnde_errpdnde_errn
TeVTeVTeV1 / (cm2 s TeV)1 / (cm2 s TeV)1 / (cm2 s TeV)1 / (cm2 s TeV)1 / (cm2 s TeV)
float64float64float64float64float64float64boolfloat64float64float64
0.59948425031894080.316227766016837941.13646366638572421.054476699836662e-109.392175822057887e-121.2525213429586618e-10False21.622634967152nannan
1.89573565240637531.13646366638572423.16227766016837955.732192992792004e-124.0298890247534667e-136.580954709029681e-12False27.277621430506628nannan
5.6234132519034913.162277660168379510.02.8691252353468466e-133.8010940407519644e-143.6879525227911325e-13False14.155667791859022nannan
17.7827941003892310.031.6227766016837938.186483435360409e-153.320772857328413e-151.6435757111984426e-14False4.271049983846689nannan
../_images/notebooks_spectrum_analysis_33_1.png

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

In [20]:
spectrum_result = SpectrumResult(
    points=fpe.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)),
    point_kwargs=dict(color="red"),
)

ax0.set_xlim(0.4, 50)
Out[20]:
(0.4, 50)
../_images/notebooks_spectrum_analysis_35_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.

In [21]:
stacked_obs = extraction.observations.stack()

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

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

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

Parameters:

           name     value     error         unit         min    max
        --------- --------- --------- --------------- --------- ---
            index 2.667e+00 7.147e-02                       nan nan
        amplitude 2.909e-11 1.784e-12 1 / (cm2 s TeV)       nan nan
        reference 1.000e+00 0.000e+00             TeV 0.000e+00 nan

Covariance:

           name           index               amplitude        reference
        --------- --------------------- ---------------------- ---------
            index  0.005108148703814004  7.240547394918019e-14       0.0
        amplitude 7.240547394918019e-14 3.1834371746354916e-24       0.0
        reference                   0.0                    0.0       0.0

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

In [23]:
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.66     0.071        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)

In [24]:
# Start exercises here

What next?

In this tutorial we learned how to extract counts spectra from an event list and generate the corresponding IRFs. Then we fitted a model to the observations and also computed flux points.

Here’s some suggestions where to go next:

  • if you want think this is way too complicated and just want to run a quick analysis check out this notebook
  • if you interested in available fit statistics checkout gammapy.stats