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

Spectral analysis

Prerequisites

  • 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

Context

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.fit_statistics), 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.

Introduction

Here, as usual, we use the gammapy.data.DataStore to retrieve a list of selected observations (gammapy.data.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 gammapy.data.DataStore poiting to the relevant data - Apply an observation selection to produce a list of observations, a gammapy.data.Observations 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.SafeRangeMaker - 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.

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

print("gammapy:", gammapy.__version__)
print("numpy:", np.__version__)
print("astropy", astropy.__version__)
print("regions", regions.__version__)
gammapy: 0.18.3.dev1948+ge49c2233a
numpy: 1.21.1
astropy 4.3.post1
regions 0.5
[3]:
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 gammapy.data import DataStore
from gammapy.datasets import (
    Datasets,
    SpectrumDataset,
    SpectrumDatasetOnOff,
    FluxPointsDataset,
)
from gammapy.modeling.models import (
    ExpCutoffPowerLawSpectralModel,
    create_crab_spectral_model,
    SkyModel,
)
from gammapy.makers import (
    SafeMaskMaker,
    SpectrumDatasetMaker,
    ReflectedRegionsBackgroundMaker,
)
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.

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

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

[6]:
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])
exclusion_mask.plot();
../../../_images/tutorials_analysis_1D_spectral_analysis_12_0.png

Run data reduction chain

We begin with the configuration of the maker classes:

[7]:
energy_axis = MapAxis.from_energy_bounds(
    0.1, 40, nbin=15, 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
)
[8]:
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)
[9]:
%%time
datasets = Datasets()

for obs_id, observation in zip(obs_ids, observations):
    dataset = dataset_maker.run(
        dataset_empty.copy(name=str(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 4.34 s, sys: 116 ms, total: 4.46 s
Wall time: 4.45 s

Plot off regions

[10]:
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)
../../../_images/tutorials_analysis_1D_spectral_analysis_18_0.png

Source statistic

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

[11]:
info_table = datasets.info_table(cumulative=True)
[12]:
info_table
[12]:
Table length=4
namecountsbackgroundexcesssqrt_tsnprednpred_backgroundnpred_signalexposure_minexposure_maxlivetimeontimecounts_ratebackground_rateexcess_raten_binsn_fit_binsstat_typestat_sumcounts_offacceptanceacceptance_offalpha
m2 sm2 sss1 / s1 / s1 / s
str7float32float32float32float64float64float64float64float32float32float64float64float64float64float64int64int64str5float64float32float32float32float32
stacked155.011.083333143.9166720.46594906007628422.15384676329482622.153846763294826nan2892003.2841726200.01581.73675841093061687.00.097993549922756130.0070070654655434620.090986487471855644027wstat450.39841204928285133.027.0324.00.08333332
stacked331.027.416666303.5833428.90875891251434450.7692321785808350.76923217858083nan13397218.01572412900.03154.42348241806033370.00.10493201114083390.008691498203616980.09624051596050894029wstat871.8472798157485329.029.0348.00.08333332
stacked481.038.05082442.949236.6860425291860260.35833248786427460.358332487864274nan19239694.02077411600.04732.5469999313355056.00.101636602870923170.008040241205744970.093596363277289934029wstat1395.656331345136765.029.0583.03610.04952286
stacked597.046.384155550.6158441.38830992070328669.7496013376125769.74960133761257nan21017612.02635248600.06313.8116406202326742.00.094554610428852490.0073464585124812170.087208151916371274029wstat1782.05582021746731065.029.0665.852360.041268717
[13]:
plt.plot(
    info_table["livetime"].to("h"), info_table["excess"], marker="o", ls="none"
)
plt.xlabel("Livetime [h]")
plt.ylabel("Excess");
../../../_images/tutorials_analysis_1D_spectral_analysis_22_0.png
[14]:
plt.plot(
    info_table["livetime"].to("h"),
    info_table["sqrt_ts"],
    marker="o",
    ls="none",
)
plt.xlabel("Livetime [h]")
plt.ylabel("Sqrt(TS)");
../../../_images/tutorials_analysis_1D_spectral_analysis_23_0.png

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

[15]:
path = Path("spectrum_analysis")
path.mkdir(exist_ok=True)
[16]:
for dataset in datasets:
    dataset.write(
        filename=path / f"obs_{dataset.name}.fits.gz", overwrite=True
    )
WARNING: AstropyDeprecationWarning: The fits_region_objects_to_table function is deprecated and may be removed in a future version.
        Use `regions.Regions.serialize` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The fits_region_objects_to_table function is deprecated and may be removed in a future version.
        Use `regions.Regions.serialize` instead. [gammapy.maps.region]
/home/runner/work/gammapy-docs/gammapy-docs/gammapy/gammapy/irf/edisp/kernel.py:329: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  groups = np.asarray(np.split(pos, borders + 1))
WARNING: AstropyDeprecationWarning: The fits_region_objects_to_table function is deprecated and may be removed in a future version.
        Use `regions.Regions.serialize` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The fits_region_objects_to_table function is deprecated and may be removed in a future version.
        Use `regions.Regions.serialize` instead. [gammapy.maps.region]
/home/runner/work/gammapy-docs/gammapy-docs/gammapy/gammapy/irf/edisp/kernel.py:329: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  groups = np.asarray(np.split(pos, borders + 1))
WARNING: AstropyDeprecationWarning: The fits_region_objects_to_table function is deprecated and may be removed in a future version.
        Use `regions.Regions.serialize` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The fits_region_objects_to_table function is deprecated and may be removed in a future version.
        Use `regions.Regions.serialize` instead. [gammapy.maps.region]
/home/runner/work/gammapy-docs/gammapy-docs/gammapy/gammapy/irf/edisp/kernel.py:329: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  groups = np.asarray(np.split(pos, borders + 1))
WARNING: AstropyDeprecationWarning: The fits_region_objects_to_table function is deprecated and may be removed in a future version.
        Use `regions.Regions.serialize` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The fits_region_objects_to_table function is deprecated and may be removed in a future version.
        Use `regions.Regions.serialize` instead. [gammapy.maps.region]
/home/runner/work/gammapy-docs/gammapy-docs/gammapy/gammapy/irf/edisp/kernel.py:329: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  groups = np.asarray(np.split(pos, borders + 1))

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

[17]:
datasets = Datasets()

for obs_id in obs_ids:
    filename = path / f"obs_{obs_id}.fits.gz"
    datasets.append(SpectrumDatasetOnOff.read(filename))
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]
WARNING: AstropyDeprecationWarning: The FITSRegionParser class is deprecated and may be removed in a future version.
        Use `regions.Regions.parse` instead. [gammapy.maps.region]

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.

[18]:
spectral_model = ExpCutoffPowerLawSpectralModel(
    amplitude=1e-12 * u.Unit("cm-2 s-1 TeV-1"),
    index=2,
    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 = fit_joint.run(datasets=datasets)

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

[19]:
print(result_joint)
{'optimize_result': OptimizeResult

        backend    : minuit
        method     : minuit
        success    : True
        message    : Optimization terminated successfully.
        nfev       : 264
        total stat : 115.90
, 'covariance_result': CovarianceResult

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

and check the best-fit parameters

[20]:
result_joint["optimize_result"].parameters.to_table()
[20]:
Table length=5
typenamevalueuniterrorminmaxfrozen
str8str9float64str14float64float64float64bool
spectralindex2.3175e+001.394e-01nannanFalse
spectralamplitude4.7534e-11cm-2 s-1 TeV-13.395e-12nannanFalse
spectralreference1.0000e+00TeV0.000e+00nannanTrue
spectrallambda_1.0681e-01TeV-14.802e-02nannanFalse
spectralalpha1.0000e+000.000e+00nannanTrue

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

[21]:
ax_spectrum, ax_residuals = datasets[0].plot_fit()
ax_spectrum.set_ylim(0.1, 40)
/home/runner/work/gammapy-docs/gammapy-docs/gammapy/gammapy/datasets/map.py:846: RuntimeWarning: invalid value encountered in true_divide
  alpha=norm / counts_off,
[21]:
(0.1, 40)
../../../_images/tutorials_analysis_1D_spectral_analysis_37_2.png

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:

[22]:
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:

[23]:
fpe = FluxPointsEstimator(energy_edges=energy_edges, source="crab", selection_optional="all")
flux_points = fpe.run(datasets=datasets)

Here is a the table of the resulting flux points:

[24]:
flux_points.to_table(sed_type="dnde", formatted=True)
[24]:
Table length=10
e_refe_mine_maxdndednde_errdnde_errpdnde_errndnde_ultssqrt_tsstatcounts [4]norm_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)
float64float64float64float64float64float64float64float64float64float64float64float64float64float64
0.8770.7011.0995.891e-114.500e-124.606e-124.396e-126.834e-11583.77824.16117.36061.0 .. 42.00.200 .. 5.000256.670 .. 874.089
1.2761.0991.4822.181e-112.540e-122.633e-122.449e-122.726e-11264.86816.27510.86820.0 .. 25.00.200 .. 5.000108.552 .. 430.132
1.8561.4822.3231.016e-111.045e-121.079e-121.011e-121.239e-11350.12818.7128.09136.0 .. 20.00.200 .. 5.000154.811 .. 412.135
2.6992.3233.1353.808e-125.820e-136.102e-135.545e-135.086e-12157.96612.5689.49211.0 .. 12.00.200 .. 5.00074.435 .. 200.135
3.9243.1354.9131.036e-121.906e-132.014e-131.801e-131.461e-1292.7729.63222.80014.0 .. 8.00.200 .. 5.00054.981 .. 243.055
5.7074.9136.6294.979e-131.229e-131.327e-131.135e-137.837e-1362.9577.9356.7307.0 .. 4.00.200 .. 5.00032.709 .. 76.442
8.2996.62910.3901.797e-134.782e-145.174e-144.406e-142.913e-1344.4596.66814.0655.0 .. 5.00.200 .. 5.00036.405 .. 63.304
12.06810.39014.0184.520e-142.426e-142.802e-142.091e-141.093e-138.2032.86411.8030.0 .. 0.00.200 .. 5.00016.267 .. 27.391
17.55014.01821.9718.342e-155.899e-157.397e-154.743e-152.636e-142.8771.6968.0101.0 .. 0.00.200 .. 5.0009.901 .. 19.813
25.52121.97129.645-3.794e-313.123e-171.825e-153.383e-16nan-0.000nan0.5240.0 .. 0.00.200 .. 5.0000.711 .. 5.205

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

[25]:
plt.figure(figsize=(8, 5))
ax = flux_points.plot(sed_type="e2dnde", color="darkorange")
flux_points.plot_ts_profiles(ax=ax, sed_type="e2dnde");
../../../_images/tutorials_analysis_1D_spectral_analysis_46_0.png

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

[26]:
flux_points_dataset = FluxPointsDataset(
    data=flux_points, models=model_best_joint
)
[27]:
flux_points_dataset.plot_fit();
../../../_images/tutorials_analysis_1D_spectral_analysis_49_0.png

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:

[28]:
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:

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

# make a copy to compare later
model_best_stacked = model.copy()
[30]:
print(result_stacked)
{'optimize_result': OptimizeResult

        backend    : minuit
        method     : minuit
        success    : True
        message    : Optimization terminated successfully.
        nfev       : 52
        total stat : 22.32
, 'covariance_result': CovarianceResult

        backend    : minuit
        method     : hesse
        success    : True
        message    : Hesse terminated successfully.
}
[31]:
model_best_joint.parameters.to_table()
[31]:
Table length=5
typenamevalueuniterrorminmaxfrozen
str8str9float64str14float64float64float64bool
spectralindex2.3175e+001.394e-01nannanFalse
spectralamplitude4.7534e-11cm-2 s-1 TeV-13.395e-12nannanFalse
spectralreference1.0000e+00TeV0.000e+00nannanTrue
spectrallambda_1.0681e-01TeV-14.802e-02nannanFalse
spectralalpha1.0000e+000.000e+00nannanTrue
[32]:
model_best_stacked.parameters.to_table()
[32]:
Table length=5
typenamevalueuniterrorminmaxfrozen
str8str9float64str14float64float64float64bool
spectralindex2.3177e+001.414e-01nannanFalse
spectralamplitude4.7615e-11cm-2 s-1 TeV-13.452e-12nannanFalse
spectralreference1.0000e+00TeV0.000e+00nannanTrue
spectrallambda_1.0802e-01TeV-14.926e-02nannanFalse
spectralalpha1.0000e+000.000e+00nannanTrue

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.

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

# plot stacked model
model_best_stacked.spectral_model.plot(
    **plot_kwargs, label="Stacked analysis result"
)
model_best_stacked.spectral_model.plot_error(facecolor="blue", alpha=0.3, **plot_kwargs)

# plot joint model
model_best_joint.spectral_model.plot(
    **plot_kwargs, label="Joint analysis result", ls="--"
)
model_best_joint.spectral_model.plot_error(facecolor="orange", alpha=0.3, **plot_kwargs)

create_crab_spectral_model("hess_ecpl").plot(
    **plot_kwargs, label="Crab reference"
)
plt.legend()
[33]:
<matplotlib.legend.Legend at 0x7fe253a26470>
../../../_images/tutorials_analysis_1D_spectral_analysis_58_1.png

Exercises

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.