{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# H.E.S.S. with Gammapy\n", "\n", "This tutorial explains how to analyse [H.E.S.S.](https://www.mpi-hd.mpg.de/hfm/HESS) data with Gammapy.\n", "\n", "We will analyse four observation runs of the Crab nebula, which are part of the [H.E.S.S. first public test data release](https://www.mpi-hd.mpg.de/hfm/HESS/pages/dl3-dr1/). In this tutorial we will make an image and a spectrum. The [light_curve.ipynb](light_curve.ipynb) notbook contains an example how to make a light curve.\n", "\n", "To do a 3D analysis, one needs to do a 3D background estimate. In [background_model.ipynb](background_model.ipynb) we have started to make a background model, and in this notebook we have a first look at a 3D analysis. But the results aren't OK yet, the background model needs to be improved. In this analysis, we also don't use the energy dispersion IRF yet, and we only analyse the data in the 1 TeV to 10 TeV range. The H.E.S.S. data was only released very recently, and 3D analysis in Gammapy is new. This tutorial will be improved soon.\n", "\n", "This tutorial also shows how to do a classical image analysis using the ring bakground. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from scipy.stats import norm\n", "import astropy.units as u\n", "from astropy.coordinates import SkyCoord\n", "from astropy.convolution import Tophat2DKernel\n", "from regions import CircleSkyRegion\n", "from gammapy.data import DataStore\n", "from gammapy.maps import Map, MapAxis, WcsGeom, WcsNDMap\n", "from gammapy.cube import MapMaker, MapDataset, PSFKernel, MapMakerRing\n", "from gammapy.cube.models import SkyModel, BackgroundModel\n", "from gammapy.spectrum.models import PowerLaw, ExponentialCutoffPowerLaw\n", "from gammapy.image.models import SkyGaussian, SkyPointSource\n", "from gammapy.detect import compute_lima_on_off_image \n", "from gammapy.scripts import SpectrumAnalysisIACT\n", "from gammapy.utils.fitting import Fit\n", "from gammapy.background import RingBackgroundEstimator" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data access\n", "\n", "To access the data, we use the `DataStore`, and we use the ``obs_table`` to select the Crab runs." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_store = DataStore.from_file(\n", " \"$GAMMAPY_DATA/hess-dl3-dr1/hess-dl3-dr3-with-background.fits.gz\"\n", ")\n", "mask = data_store.obs_table[\"TARGET_NAME\"] == \"Crab\"\n", "obs_table = data_store.obs_table[mask]\n", "observations = data_store.get_observations(obs_table[\"OBS_ID\"])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# pos_crab = SkyCoord.from_name('Crab')\n", "pos_crab = SkyCoord(83.633, 22.014, unit=\"deg\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Maps\n", "\n", "Let's make some 3D cubes, as well as 2D images.\n", "\n", "For the energy, we make 5 bins from 1 TeV to 10 TeV." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "energy_axis = MapAxis.from_edges(\n", " np.logspace(0, 1.0, 5), unit=\"TeV\", name=\"energy\", interp=\"log\"\n", ")\n", "geom = WcsGeom.create(\n", " skydir=(83.633, 22.014),\n", " binsz=0.02,\n", " width=(5, 5),\n", " coordsys=\"CEL\",\n", " proj=\"TAN\",\n", " axes=[energy_axis],\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%time\n", "maker = MapMaker(geom, offset_max=\"2.5 deg\")\n", "maps = maker.run(observations)\n", "images = maker.run_images()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "maps.keys()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "images[\"counts\"].smooth(3).plot(stretch=\"sqrt\", vmax=2);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## PSF\n", "\n", "Compute the mean PSF for these observations at the Crab position." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from gammapy.irf import make_mean_psf\n", "\n", "table_psf = make_mean_psf(observations, pos_crab)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "psf_kernel = PSFKernel.from_table_psf(table_psf, geom, max_radius=\"0.3 deg\")\n", "psf_kernel_array = psf_kernel.psf_kernel_map.sum_over_axes().data\n", "# psf_kernel.psf_kernel_map.slice_by_idx({'energy': 0}).plot()\n", "# plt.imshow(psf_kernel_array)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Map fit\n", "\n", "Let's fit this source assuming a Gaussian spatial shape and a power-law spectral shape, and a background with a flexible normalisation" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "spatial_model = SkyPointSource(\n", " lon_0=\"83.6 deg\", lat_0=\"22.0 deg\", frame=\"icrs\"\n", ")\n", "spectral_model = PowerLaw(\n", " index=2.6, amplitude=\"5e-11 cm-2 s-1 TeV-1\", reference=\"1 TeV\"\n", ")\n", "model = SkyModel(spatial_model=spatial_model, spectral_model=spectral_model)\n", "background_model = BackgroundModel(maps[\"background\"], norm=1.0)\n", "background_model.parameters[\"tilt\"].frozen = False" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%time\n", "dataset = MapDataset(\n", " model=model,\n", " counts=maps[\"counts\"],\n", " exposure=maps[\"exposure\"],\n", " background_model=background_model,\n", " psf=psf_kernel,\n", ")\n", "fit = Fit(dataset)\n", "result = fit.run()\n", "print(result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Best fit parameters:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "result.parameters.to_table()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Parameters covariance:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "result.parameters.covariance_to_table()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Residual image\n", "\n", "We compute a residual image as `residual = counts - model`. Note that this is counts per pixel and our pixel size is 0.02 deg. Smoothing is counts-preserving. The residual image shows that currently both the source and the background modeling isn't very good. The background model is underestimated (so residual is positive), and the source model is overestimated." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "npred = dataset.npred()\n", "residual = Map.from_geom(maps[\"counts\"].geom)\n", "residual.data = maps[\"counts\"].data - npred.data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "residual.sum_over_axes().smooth(\"0.1 deg\").plot(\n", " cmap=\"coolwarm\", vmin=-0.2, vmax=0.2, add_cbar=True\n", ");" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Spectrum\n", "\n", "We could try to improve the background modeling and spatial model of the source. But let's instead turn to one of the classic IACT analysis techniques: use a circular on region and reflected regions for background estimation, and derive a spectrum for the source without having to assume a spatial model, or without needing a 3D background model." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%time\n", "on_region = CircleSkyRegion(pos_crab, 0.11 * u.deg)\n", "exclusion_mask = images[\"counts\"].copy()\n", "exclusion_mask.data = np.ones_like(exclusion_mask.data, dtype=bool)\n", "\n", "model = PowerLaw(\n", " index=2.6, amplitude=\"5e-11 cm-2 s-1 TeV-1\", reference=\"1 TeV\"\n", ")\n", "\n", "config = {\n", " \"outdir\": \".\",\n", " \"background\": {\"on_region\": on_region, \"exclusion_mask\": exclusion_mask},\n", " \"extraction\": {\"containment_correction\": True},\n", " \"fit\": {\"model\": model, \"fit_range\": [1, 10] * u.TeV},\n", " \"fp_binning\": np.logspace(0, 1, 7) * u.TeV,\n", "}\n", "analysis = SpectrumAnalysisIACT(observations=observations, config=config)\n", "analysis.run()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(analysis.fit.result[0])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Classical Ring Background Analysis\n", "\n", "In this section, we do a classical ring background analysis on the MSH 15-52 region. Let us first select these runs in the datastore" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_store = DataStore.from_file(\n", " \"$GAMMAPY_DATA/hess-dl3-dr1/hess-dl3-dr3-with-background.fits.gz\"\n", ")\n", "data_sel = data_store.obs_table[\"TARGET_NAME\"] == \"MSH 15-52\"\n", "obs_table = data_store.obs_table[data_sel]\n", "observations = data_store.get_observations(obs_table[\"OBS_ID\"])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# pos_msh1552 = SkyCoord.from_name('MSH15-52')\n", "pos_msh1552 = SkyCoord(228.32, -59.08, unit=\"deg\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We first have to define the geometry on which we make our 2D map." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "energy_axis = MapAxis.from_edges(\n", " np.logspace(0, 5.0, 5), unit=\"TeV\", name=\"energy\", interp=\"log\"\n", ")\n", "geom = WcsGeom.create(\n", " skydir=pos_msh1552,\n", " binsz=0.02,\n", " width=(5, 5),\n", " coordsys=\"CEL\",\n", " proj=\"TAN\",\n", " axes=[energy_axis],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Choose an exclusion mask.\n", "We choose an exclusion mask on the position of MSH 1552. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "regions = CircleSkyRegion(center=pos_msh1552, radius=0.3 * u.deg)\n", "mask = Map.from_geom(geom)\n", "mask.data = mask.geom.region_mask([regions], inside=False)\n", "mask.get_image_by_idx([0]).plot();" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we instantiate the ring background" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ring_bkg = RingBackgroundEstimator(r_in=\"0.5 deg\", width=\"0.3 deg\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To facilitate classical image analysis, we have a special class called `MapMakerRing`. Here, we do the analysis over the integrated energy range. To do an analysis for each image slice of the map (eg: to investigate the significance of the source detection with energy, just call `run` instead of `run_images`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%time\n", "im = MapMakerRing(\n", " geom=geom,\n", " offset_max=2.0 * u.deg,\n", " exclusion_mask=mask,\n", " background_estimator=ring_bkg,\n", ")\n", "images = im.run_images(observations)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will use `compute_lima_on_off_image` in `gammapy.detect` to compute significance and excess maps. A common debug plot during Ring Analysis is to make histograms of the `off` count rates, so we will plot that as well.\n", "\n", "For this we will first create a Tophat2DKernel convolution kernel for the significance maps. To convert from angles to pixel scales, we use `geom.pixel_scales`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scale = geom.pixel_scales[0].to(\"deg\")\n", "# Using a convolution radius of 0.05 degrees\n", "theta = 0.05 * u.deg / scale\n", "tophat = Tophat2DKernel(theta)\n", "tophat.normalize(\"peak\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lima_maps = compute_lima_on_off_image(\n", " images[\"on\"],\n", " images[\"off\"],\n", " images[\"exposure_on\"],\n", " images[\"exposure_off\"],\n", " tophat,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "significance_map = lima_maps[\"significance\"]\n", "excess_map = lima_maps[\"excess\"]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(10, 10))\n", "ax1 = plt.subplot(221, projection=significance_map.geom.wcs)\n", "ax2 = plt.subplot(222, projection=excess_map.geom.wcs)\n", "\n", "ax1.set_title(\"Significance map\")\n", "significance_map.plot(ax=ax1, add_cbar=True)\n", "\n", "ax2.set_title(\"Excess map\")\n", "excess_map.plot(ax=ax2, add_cbar=True);" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# create a 2D mask for the images\n", "image_mask = mask.slice_by_idx({\"energy\": 0})\n", "significance_map_off = significance_map * image_mask" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "significance_all = significance_map.data[np.isfinite(significance_map.data)]\n", "significance_off = significance_map_off.data[np.isfinite(significance_map_off.data)]\n", "\n", "plt.hist(\n", " significance_all,\n", " density=True,\n", " alpha=0.5,\n", " color=\"red\",\n", " label=\"all bins\",\n", " bins=21,\n", ")\n", "\n", "plt.hist(\n", " significance_off,\n", " density=True,\n", " alpha=0.5,\n", " color=\"blue\",\n", " label=\"off bins\",\n", " bins=21,\n", ")\n", "\n", "# Now, fit the off distribution with a Gaussian\n", "mu, std = norm.fit(significance_off)\n", "x = np.linspace(-8, 8, 50)\n", "p = norm.pdf(x, mu, std)\n", "plt.plot(x, p, lw=2, color=\"black\")\n", "plt.legend()\n", "plt.xlabel(\"Significance\")\n", "plt.yscale(\"log\")\n", "plt.ylim(1e-5, 1)\n", "xmin, xmax = np.min(significance_all), np.max(significance_all)\n", "plt.xlim(xmin, xmax)\n", "\n", "print(\"Fit results: mu = {:.2f}, std = {:.2f}\".format(mu, std))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The significance and excess maps clearly indicate a bright source at the position of MSH 1552. This is also evident from the significance distribution. The off distribution should ideally be a Gaussian with `mu=0`, `sigma=1`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Excess from entire map: {:.1f}\".format(np.nansum(lima_maps[\"excess\"].data)))\n", "print(\n", " \"Excess from off regions: {:.1f}\".format(np.nansum((lima_maps[\"excess\"] * image_mask).data))\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Again: please note that this tutorial notebook was put together quickly, the results obtained here are very preliminary. We will work on Gammapy and the analysis of data from the H.E.S.S. test release and update this tutorial soon." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercises\n", "\n", "- Try analysing another source, e.g. RX J1713.7−3946\n", "- Try another model, e.g. a Gaussian spatial shape or exponential cutoff power-law spectrum." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.0" } }, "nbformat": 4, "nbformat_minor": 2 }