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

CTA data analysis with Gammapy

Introduction

This notebook shows an example how to make a sky image and spectrum for simulated CTA data with Gammapy.

The dataset we will use is three observation runs on the Galactic center. This is a tiny (and thus quick to process and play with and learn) subset of the simulated CTA dataset that was produced for the first data challenge in August 2017.

Setup

As usual, we’ll start with some setup …

[1]:
%matplotlib inline
import matplotlib.pyplot as plt
[2]:
!gammapy info --no-envvar --no-system

Gammapy package:

        version                : 0.17
        path                   : /Users/terrier/Code/gammapy-dev/gammapy-docs/build/v0.17/gammapy/gammapy


Other packages:

        numpy                  : 1.18.1
        scipy                  : 1.4.1
        astropy                : 4.0
        regions                : 0.4
        click                  : 7.1.1
        yaml                   : 5.1.2
        IPython                : 7.13.0
        jupyterlab             : 2.0.1
        matplotlib             : 3.1.2
        pandas                 : 0.25.3
        healpy                 : 1.13.0
        iminuit                : 1.3.8
        sherpa                 : 4.12.0
        naima                  : 0.9.1
        emcee                  : 2.2.1
        corner                 : 2.0.1
        parfive                : 1.0.0

[3]:
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord
from astropy.convolution import Gaussian2DKernel
from regions import CircleSkyRegion
from gammapy.modeling import Fit
from gammapy.data import DataStore
from gammapy.datasets import (
    Datasets,
    FluxPointsDataset,
    SpectrumDataset,
    MapDataset,
)
from gammapy.modeling.models import (
    PowerLawSpectralModel,
    SkyModel,
    GaussianSpatialModel,
)
from gammapy.maps import MapAxis, WcsNDMap, WcsGeom
from gammapy.makers import (
    MapDatasetMaker,
    SafeMaskMaker,
    SpectrumDatasetMaker,
    ReflectedRegionsBackgroundMaker,
)
from gammapy.estimators import TSMapEstimator, FluxPointsEstimator
from gammapy.estimators.utils import find_peaks
from gammapy.visualization import plot_spectrum_datasets_off_regions
[4]:
# Configure the logger, so that the spectral analysis
# isn't so chatty about what it's doing.
import logging

logging.basicConfig()
log = logging.getLogger("gammapy.spectrum")
log.setLevel(logging.ERROR)

Select observations

A Gammapy analysis usually starts by creating a gammapy.data.DataStore and selecting observations.

This is shown in detail in the other notebook, here we just pick three observations near the galactic center.

[5]:
data_store = DataStore.from_dir("$GAMMAPY_DATA/cta-1dc/index/gps")
[6]:
# Just as a reminder: this is how to select observations
# from astropy.coordinates import SkyCoord
# table = data_store.obs_table
# pos_obs = SkyCoord(table['GLON_PNT'], table['GLAT_PNT'], frame='galactic', unit='deg')
# pos_target = SkyCoord(0, 0, frame='galactic', unit='deg')
# offset = pos_target.separation(pos_obs).deg
# mask = (1 < offset) & (offset < 2)
# table = table[mask]
# table.show_in_browser(jsviewer=True)
[7]:
obs_id = [110380, 111140, 111159]
observations = data_store.get_observations(obs_id)
[8]:
obs_cols = ["OBS_ID", "GLON_PNT", "GLAT_PNT", "LIVETIME"]
data_store.obs_table.select_obs_id(obs_id)[obs_cols]
[8]:
ObservationTable length=3
OBS_IDGLON_PNTGLAT_PNTLIVETIME
degdegs
int64float64float64float64
110380359.9999912037958-1.2999959379053661764.0
111140358.49998338300741.30000202119542841764.0
1111591.50000565682677411.2999404683352941764.0

Make sky images

Define map geometry

Select the target position and define an ON region for the spectral analysis

[9]:
axis = MapAxis.from_edges(
    np.logspace(-1.0, 1.0, 10), unit="TeV", name="energy", interp="log"
)
geom = WcsGeom.create(
    skydir=(0, 0), npix=(500, 400), binsz=0.02, frame="galactic", axes=[axis]
)
geom
[9]:
WcsGeom

        axes       : ['lon', 'lat', 'energy']
        shape      : (500, 400, 9)
        ndim       : 3
        frame      : galactic
        projection : CAR
        center     : 0.0 deg, 0.0 deg
        width      : 10.0 deg x 8.0 deg

Compute images

Exclusion mask currently unused. Remove here or move to later in the tutorial?

[10]:
target_position = SkyCoord(0, 0, unit="deg", frame="galactic")
on_radius = 0.2 * u.deg
on_region = CircleSkyRegion(center=target_position, radius=on_radius)
[11]:
exclusion_mask = geom.to_image().region_mask([on_region], inside=False)
exclusion_mask = WcsNDMap(geom.to_image(), exclusion_mask)
exclusion_mask.plot();
../_images/notebooks_cta_data_analysis_16_0.png
[12]:
%%time
stacked = MapDataset.create(geom=geom)
maker = MapDatasetMaker(selection=["counts", "background", "exposure", "psf"])
maker_safe_mask = SafeMaskMaker(methods=["offset-max"], offset_max=2.5 * u.deg)

for obs in observations:
    cutout = stacked.cutout(obs.pointing_radec, width="5 deg")
    dataset = maker.run(cutout, obs)
    dataset = maker_safe_mask.run(dataset, obs)
    stacked.stack(dataset)
CPU times: user 3.81 s, sys: 770 ms, total: 4.58 s
Wall time: 4.62 s
[13]:
# The maps are cubes, with an energy axis.
# Let's also make some images:
dataset_image = stacked.to_image()

images = {
    "counts": dataset_image.counts.get_image_by_idx((0,)),
    "exposure": dataset_image.exposure.get_image_by_idx((0,)),
    "background": dataset_image.background_model.map.get_image_by_idx((0,)),
}

images["excess"] = images["counts"] - images["background"]
/Users/terrier/Code/gammapy-dev/gammapy-docs/build/v0.17/gammapy/gammapy/irf/psf_map.py:317: RuntimeWarning: invalid value encountered in true_divide
  psf_data = exp_weighed.data * self.psf_map.data / exposure.data

Show images

Let’s have a quick look at the images we computed …

[14]:
images["counts"].smooth(2).plot(vmax=5);
../_images/notebooks_cta_data_analysis_20_0.png
[15]:
images["background"].plot(vmax=5);
../_images/notebooks_cta_data_analysis_21_0.png
[16]:
images["excess"].smooth(3).plot(vmax=2);
../_images/notebooks_cta_data_analysis_22_0.png

Source Detection

Use the class gammapy.estimators.TSMapEstimator and ~gammapy.estimators.utils.find_peaks to detect sources on the images. We search for 0.1 deg sigma gaussian sources in the dataset.

[17]:
spatial_model = GaussianSpatialModel(sigma="0.1 deg")
spectral_model = PowerLawSpectralModel(index=2)
model = SkyModel(spatial_model=spatial_model, spectral_model=spectral_model)
[18]:
%%time
ts_image_estimator = TSMapEstimator(model)
images_ts = ts_image_estimator.run(dataset_image)
print(images_ts.keys())
/Users/terrier/Code/anaconda3/envs/gammapy-dev/lib/python3.7/site-packages/astropy/units/quantity.py:481: RuntimeWarning: invalid value encountered in true_divide
  result = super().__array_ufunc__(function, method, *arrays, **kwargs)
dict_keys(['ts', 'sqrt_ts', 'flux', 'flux_err', 'flux_ul', 'niter'])
CPU times: user 13.8 s, sys: 239 ms, total: 14 s
Wall time: 14.1 s
[19]:
sources = find_peaks(images_ts["sqrt_ts"], threshold=6)
sources
[19]:
Table length=111
valuexyradec
degdeg
float32int64int64float64float64
33.708253197266.41208-29.02198
16.935207205266.80079-28.15278
12.358214198266.85440-28.34505
12.351273196266.19254-29.37365
11.921217198266.81908-28.39638
11.887277197266.12496-29.43139
11.654202193267.09247-28.19131
11.635217196266.85798-28.41709
11.304214194266.93220-28.38645
...............
6.4745174190267.47711-27.74210
6.413288203265.87510-29.55589
6.229292213265.63122-29.51878
6.1913162196267.49995-27.47454
6.1821160190267.63920-27.50174
6.1092232184266.91503-28.79800
6.0999316173266.12629-30.34723
6.0891314174266.13078-30.30268
6.0544162191267.59672-27.52584
6.0233162194267.53865-27.49507
[20]:
source_pos = SkyCoord(sources["ra"], sources["dec"])
source_pos
[20]:
<SkyCoord (ICRS): (ra, dec) in deg
    [(266.41208417, -29.02197675), (266.80078569, -28.15277706),
     (266.85440284, -28.34505079), (266.19254245, -29.37364637),
     (266.81908408, -28.39637563), (266.12496388, -29.43138591),
     (267.09246923, -28.19130928), (266.85798491, -28.4170929 ),
     (266.93219577, -28.38645429), (266.23290288, -29.27792918),
     (266.12135787, -30.08650777), (267.26396225, -27.74559804),
     (267.06616784, -27.80367473), (267.01576857, -27.80014032),
     (267.16320789, -27.73865467), (266.82209403, -28.58503656),
     (267.06246648, -27.73163821), (267.10117415, -27.75228685),
     (266.62593456, -28.71452286), (266.98070633, -27.85150651),
     (267.12449328, -27.71802333), (266.62670235, -28.59790578),
     (266.74419779, -28.54357072), (266.87285832, -28.58864192),
     (267.32210113, -27.65986372), (267.28338443, -27.63927661),
     (267.10490183, -27.82432239), (266.00310432, -29.41311646),
     (266.66218198, -28.54663069), (266.22434599, -30.09422107),
     (266.67328602, -28.64615429), (266.33502094, -30.12934913),
     (266.39423345, -30.16062377), (264.84660971, -30.98188072),
     (267.39973122, -27.9342429 ), (264.80200543, -31.00507574),
     (266.03355692, -30.13373938), (267.59381222, -27.92028868),
     (266.53703151, -28.57341134), (267.63268801, -27.94078887),
     (266.11510554, -29.94238924), (267.39587708, -27.97883418),
     (267.34536679, -27.85880105), (267.47743433, -27.97534066),
     (266.39525918, -30.04401282), (267.65962401, -27.8618394 ),
     (266.43470821, -30.06484815), (266.36786646, -30.00609875),
     (267.3686317 , -27.82449668), (266.57254651, -28.52215965),
     (267.06189432, -27.96487558), (266.15290431, -29.04745174),
     (267.03850204, -27.99912851), (266.8020421 , -28.69129197),
     (267.31820239, -27.93769083), (265.94722599, -30.0643032 ),
     (266.11700174, -29.0985922 ), (267.0060164 , -28.47239392),
     (267.39950306, -27.58438672), (266.412978  , -30.28765253),
     (266.9609492 , -27.95778498), (265.87904104, -30.1219187 ),
     (265.87183299, -29.78911175), (266.56238607, -28.30601177),
     (266.77305749, -29.00330806), (266.74934182, -29.03751164),
     (267.20940419, -28.01995964), (265.92018698, -29.72101051),
     (266.27054302, -29.83732583), (267.46565623, -27.87588439),
     (266.2946039 , -29.8032059 ), (267.72207311, -27.96457477),
     (267.59729445, -27.75907496), (266.24646588, -29.87144148),
     (266.9194629 , -27.6318213 ), (264.92562207, -31.02446459),
     (266.88083225, -27.61112227), (266.91586315, -27.55978161),
     (267.30652946, -28.07145782), (266.20854887, -30.46110528),
     (266.95448245, -27.58047075), (265.9443394 , -29.68695332),
     (265.9805374 , -29.63585936), (266.86365638, -28.91102891),
     (264.68879649, -30.89656898), (266.82457022, -28.89031403),
     (265.6675152 , -29.46777535), (266.42800403, -29.92074799),
     (265.78650845, -29.41428394), (264.71367031, -30.86274233),
     (266.35261127, -30.37299663), (266.32843568, -30.4071268 ),
     (266.20203068, -29.5898213 ), (266.49145813, -28.40850055),
     (267.35713418, -28.30812142), (265.62846055, -29.44671337),
     (267.38049111, -28.27381509), (266.85645141, -28.76694631),
     (265.71585208, -29.39974862), (265.73821192, -29.48233654),
     (266.7514805 , -27.91591078), (267.47711386, -27.74210442),
     (265.87510217, -29.55589101), (265.63121963, -29.51878374),
     (267.49994847, -27.47454088), (267.63920107, -27.50174146),
     (266.91502612, -28.79800119), (266.12629173, -30.34723498),
     (266.13077659, -30.30268297), (267.59672321, -27.52583885),
     (267.53864754, -27.4950681 )]>
[21]:
# Plot sources on top of significance sky image
images_ts["sqrt_ts"].plot(add_cbar=True)

plt.gca().scatter(
    source_pos.ra.deg,
    source_pos.dec.deg,
    transform=plt.gca().get_transform("icrs"),
    color="none",
    edgecolor="white",
    marker="o",
    s=200,
    lw=1.5,
);
../_images/notebooks_cta_data_analysis_28_0.png

Spatial analysis

See other notebooks for how to run a 3D cube or 2D image based analysis.

Spectrum

We’ll run a spectral analysis using the classical reflected regions background estimation method, and using the on-off (often called WSTAT) likelihood function.

[22]:
e_reco = np.logspace(-1, np.log10(40), 40) * u.TeV
e_true = np.logspace(np.log10(0.05), 2, 200) * u.TeV

dataset_empty = SpectrumDataset.create(
    e_reco=e_reco, e_true=e_true, region=on_region
)
[23]:
dataset_maker = SpectrumDatasetMaker(
    containment_correction=False, selection=["counts", "aeff", "edisp"]
)
bkg_maker = ReflectedRegionsBackgroundMaker(exclusion_mask=exclusion_mask)
safe_mask_masker = SafeMaskMaker(methods=["aeff-max"], aeff_percent=10)
[24]:
%%time
datasets = []

for observation in observations:
    dataset = dataset_maker.run(
        dataset_empty.copy(name=f"obs-{observation.obs_id}"), observation
    )
    dataset_on_off = bkg_maker.run(dataset, observation)
    dataset_on_off = safe_mask_masker.run(dataset_on_off, observation)
    datasets.append(dataset_on_off)
CPU times: user 3.94 s, sys: 258 ms, total: 4.2 s
Wall time: 4.21 s
[25]:
plt.figure(figsize=(8, 8))
_, ax, _ = images["counts"].smooth("0.03 deg").plot(vmax=8)

on_region.to_pixel(ax.wcs).plot(ax=ax, edgecolor="white")
plot_spectrum_datasets_off_regions(datasets, ax=ax)
../_images/notebooks_cta_data_analysis_34_0.png

Model fit

The next step is to fit a spectral model, using all data (i.e. a “global” fit, using all energies).

[26]:
%%time
spectral_model = PowerLawSpectralModel(
    index=2, amplitude=1e-11 * u.Unit("cm-2 s-1 TeV-1"), reference=1 * u.TeV
)
model = SkyModel(spectral_model=spectral_model, name="source-gc")
for dataset in datasets:
    dataset.models = model

fit = Fit(datasets)
result = fit.run()
print(result)
OptimizeResult

        backend    : minuit
        method     : minuit
        success    : True
        message    : Optimization terminated successfully.
        nfev       : 108
        total stat : 75.81

CPU times: user 885 ms, sys: 15 ms, total: 900 ms
Wall time: 941 ms

Spectral points

Finally, let’s compute spectral points. The method used is to first choose an energy binning, and then to do a 1-dim likelihood fit / profile to compute the flux and flux error.

[27]:
# Flux points are computed on stacked observation
stacked_dataset = Datasets(datasets).stack_reduce(name="stacked")

print(stacked_dataset)
SpectrumDatasetOnOff
--------------------

  Name                            : stacked

  Total counts                    : 441
  Total predicted counts          : 433.82
  Total off counts                : 2278.00

  Total background counts         : 91.22

  Effective area min              : 1.88e+08 cm2
  Effective area max              : 4.64e+10 cm2

  Livetime                        : 5.29e+03 s

  Acceptance mean:                : 1.0

  Number of total bins            : 39
  Number of fit bins              : 29

  Fit statistic type              : wstat
  Fit statistic value (-2 log(L)) : 208.36

  Number of parameters            : 3
  Number of free parameters       : 2

  Component 0: SkyModel

    Name                      : source-gc
    Datasets names            : None
    Spectral model type       : PowerLawSpectralModel
    Spatial  model type       : None
    Temporal model type       : None
    Parameters:
      index                   :   2.423
      amplitude               :   3.38e-12  1 / (cm2 s TeV)
      reference    (frozen)   :   1.000  TeV


[28]:
e_edges = MapAxis.from_energy_bounds("1 TeV", "30 TeV", nbin=5).edges

stacked_dataset.models = model

fpe = FluxPointsEstimator(e_edges=e_edges, source="source-gc")
flux_points = fpe.run(datasets=[stacked_dataset])
flux_points.table_formatted
[28]:
Table length=5
e_refe_mine_maxref_dnderef_fluxref_efluxref_e2dndenormstatsuccessnorm_errnorm_errpnorm_errnnorm_ulsqrt_tstsnull_valuenorm_scan [11]stat_scan [11]counts [1]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)
float64float64float64float64float64float64float64float64float64boolfloat64float64float64float64float64float64int64float64float64int64float64float64float64float64float64
1.3621.0021.8521.598e-121.381e-121.828e-122.966e-120.8823.705True0.1130.1270.1191.14610.896118.71200.200 .. 5.00057.282 .. 359.241831.410e-121.832e-121.804e-132.033e-131.901e-13
2.7191.8523.9932.993e-136.568e-131.708e-122.213e-121.1681.660True0.1360.1460.1361.46913.917193.67000.200 .. 5.00099.764 .. 277.338923.495e-134.397e-134.063e-144.359e-144.067e-14
5.4293.9937.3825.605e-141.930e-131.018e-121.652e-121.2083.418True0.3120.2260.2011.6819.52090.62900.200 .. 5.00050.176 .. 123.817436.772e-149.423e-141.747e-141.267e-141.129e-14
10.8387.38215.9131.050e-149.180e-149.512e-131.233e-120.7617.054True0.2260.2510.2101.3025.25727.63500.200 .. 5.00017.512 .. 99.475167.992e-151.367e-142.368e-152.636e-152.209e-15
21.63615.91329.4191.966e-152.698e-145.671e-139.202e-130.5642.889True0.3310.4090.2941.5112.5366.43100.200 .. 5.0004.599 .. 37.77341.108e-152.971e-156.501e-168.047e-165.781e-16

Plot

Let’s plot the spectral model and points. You could do it directly, but for convenience we bundle the model and the flux points in a FluxPointDataset:

[29]:
flux_points_dataset = FluxPointsDataset(data=flux_points, models=model)
[30]:
plt.figure(figsize=(8, 6))
flux_points_dataset.peek();
../_images/notebooks_cta_data_analysis_42_0.png

Exercises

  • Re-run the analysis above, varying some analysis parameters, e.g.

    • Select a few other observations

    • Change the energy band for the map

    • Change the spectral model for the fit

    • Change the energy binning for the spectral points

  • Change the target. Make a sky image and spectrum for your favourite source.

    • If you don’t know any, the Crab nebula is the “hello world!” analysis of gamma-ray astronomy.

[31]:
# print('hello world')
# SkyCoord.from_name('crab')

What next?

  • This notebook showed an example of a first CTA analysis with Gammapy, using simulated 1DC data.

  • Let us know if you have any question or issues!