{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Fitting and error estimation with MCMC\n", "\n", "## Introduction\n", "\n", "The goal of Markov Chain Monte Carlo (MCMC) algorithms is to approximate the posterior distribution of your model parameters by random sampling in a probabilistic space. For most readers this sentence was probably not very helpful so here we'll start straight with and example but you should read the more detailed mathematical approaches of the method [here](https://www.pas.rochester.edu/~sybenzvi/courses/phy403/2015s/p403_17_mcmc.pdf) and [here](https://github.com/jakevdp/BayesianAstronomy/blob/master/03-Bayesian-Modeling-With-MCMC.ipynb).\n", "\n", "### How does it work ?\n", "\n", "The idea is that we use a number of walkers that will sample the posterior distribution (i.e. sample the Likelihood profile).\n", "\n", "The goal is to produce a \"chain\", i.e. a list of $\\theta$ values, where each $\\theta$ is a vector of parameters for your model.
\n", "If you start far away from the truth value, the chain will take some time to converge until it reaches a stationary state. Once it has reached this stage, each successive elements of the chain are samples of the target posterior distribution.
\n", "This means that, once we have obtained the chain of samples, we have everything we need. We can compute the distribution of each parameter by simply approximating it with the histogram of the samples projected into the parameter space. This will provide the errors and correlations between parameters.\n", "\n", "\n", "Now let's try to put a picture on the ideas described above. With this notebook, we have simulated and carried out a MCMC analysis for a source with the following parameters:
\n", "$Index=2.0$, $Norm=5\\times10^{-12}$ cm$^{-2}$ s$^{-1}$ TeV$^{-1}$, $Lambda =(1/Ecut) = 0.02$ TeV$^{-1}$ (50 TeV) for 20 hours.\n", "\n", "The results that you can get from a MCMC analysis will look like this :\n", "\n", " \n", "\n", "On the first two top panels, we show the pseudo-random walk of one walker from an offset starting value to see it evolve to a better solution.\n", "In the bottom right panel, we show the trace of each 16 walkers for 500 runs (the chain described previsouly). For the first 100 runs, the parameter evolve towards a solution (can be viewed as a fitting step). Then they explore the local minimum for 400 runs which will be used to estimate the parameters correlations and errors.\n", "The choice of the Nburn value (when walkers have reached a stationary stage) can be done by eye but you can also look at the autocorrelation time.\n", "\n", "### Why should I use it ?\n", "\n", "When it comes to evaluate errors and investigate parameter correlation, one typically estimate the Likelihood in a gridded search (2D Likelihood profiles). Each point of the grid implies a new model fitting. If we use 10 steps for each parameters, we will need to carry out 100 fitting procedures. \n", "\n", "Now let's say that I have a model with $N$ parameters, we need to carry out that gridded analysis $N*(N-1)$ times. \n", "So for 5 free parameters you need 20 gridded search, resulting in 2000 individual fit. \n", "Clearly this strategy doesn't scale well to high-dimensional models.\n", "\n", "Just for fun: if each fit procedure takes 10s, we're talking about 5h of computing time to estimate the correlation plots. \n", "\n", "There are many MCMC packages in the python ecosystem but here we will focus on [emcee](https://emcee.readthedocs.io), a lightweight Python package. A description is provided here : [Foreman-Mackey, Hogg, Lang & Goodman (2012)](https://arxiv.org/abs/1202.3665)." ] }, { "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", "import astropy.units as u\n", "from astropy.coordinates import SkyCoord\n", "from gammapy.irf import load_cta_irfs\n", "from gammapy.maps import WcsGeom, MapAxis\n", "from gammapy.modeling.models import (\n", " ExpCutoffPowerLawSpectralModel,\n", " GaussianSpatialModel,\n", " SkyModel,\n", " Models,\n", " FoVBackgroundModel,\n", ")\n", "from gammapy.datasets import MapDataset\n", "from gammapy.makers import MapDatasetMaker\n", "from gammapy.data import Observation\n", "from gammapy.modeling.sampling import (\n", " run_mcmc,\n", " par_to_model,\n", " plot_corner,\n", " plot_trace,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import logging\n", "\n", "logging.basicConfig(level=logging.INFO)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Simulate an observation\n", "\n", "Here we will start by simulating an observation using the simulate_dataset method." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "irfs = load_cta_irfs(\n", " \"\$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits\"\n", ")\n", "\n", "observation = Observation.create(\n", " pointing=SkyCoord(0 * u.deg, 0 * u.deg, frame=\"galactic\"),\n", " livetime=20 * u.h,\n", " irfs=irfs,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define map geometry\n", "axis = MapAxis.from_edges(\n", " np.logspace(-1, 2, 15), unit=\"TeV\", name=\"energy\", interp=\"log\"\n", ")\n", "\n", "geom = WcsGeom.create(\n", " skydir=(0, 0), binsz=0.05, width=(2, 2), frame=\"galactic\", axes=[axis]\n", ")\n", "\n", "empty_dataset = MapDataset.create(geom=geom, name=\"dataset-mcmc\")\n", "maker = MapDatasetMaker(selection=[\"background\", \"edisp\", \"psf\", \"exposure\"])\n", "dataset = maker.run(empty_dataset, observation)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define sky model to simulate the data\n", "spatial_model = GaussianSpatialModel(\n", " lon_0=\"0 deg\", lat_0=\"0 deg\", sigma=\"0.2 deg\", frame=\"galactic\"\n", ")\n", "\n", "spectral_model = ExpCutoffPowerLawSpectralModel(\n", " index=2,\n", " amplitude=\"3e-12 cm-2 s-1 TeV-1\",\n", " reference=\"1 TeV\",\n", " lambda_=\"0.05 TeV-1\",\n", ")\n", "\n", "sky_model_simu = SkyModel(\n", " spatial_model=spatial_model, spectral_model=spectral_model, name=\"source\"\n", ")\n", "\n", "bkg_model = FoVBackgroundModel(dataset_name=\"dataset-mcmc\")\n", "models = Models([sky_model_simu, bkg_model])\n", "print(models)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dataset.models = models\n", "dataset.fake()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dataset.counts.sum_over_axes().plot(add_cbar=True);" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# If you want to fit the data for comparison with MCMC later\n", "\n", "# fit = Fit(dataset)\n", "# result = fit.run(optimize_opts={\"print_level\": 1})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Estimate parameter correlations with MCMC\n", "\n", "Now let's analyse the simulated data.\n", "Here we just fit it again with the same model we had before as a starting point.\n", "The data that would be needed are the following: \n", "- counts cube, psf cube, exposure cube and background model\n", "\n", "Luckily all those maps are already in the Dataset object.\n", "\n", "We will need to define a Likelihood function and define priors on parameters.
\n", "Here we will assume a uniform prior reading the min, max parameters from the sky model." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Define priors\n", "\n", "This steps is a bit manual for the moment until we find a better API to define priors.
\n", "Note the you **need** to define priors for each parameter otherwise your walkers can explore uncharted territories (e.g. negative norms)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(dataset)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define the free parameters and min, max values\n", "parameters = dataset.models.parameters\n", "\n", "parameters[\"sigma\"].frozen = True\n", "parameters[\"lon_0\"].frozen = True\n", "parameters[\"lat_0\"].frozen = True\n", "parameters[\"amplitude\"].frozen = False\n", "parameters[\"index\"].frozen = False\n", "parameters[\"lambda_\"].frozen = False\n", "\n", "\n", "parameters[\"norm\"].frozen = True\n", "parameters[\"tilt\"].frozen = True\n", "\n", "parameters[\"norm\"].min = 0.5\n", "parameters[\"norm\"].max = 2\n", "\n", "parameters[\"index\"].min = 1\n", "parameters[\"index\"].max = 5\n", "parameters[\"lambda_\"].min = 1e-3\n", "parameters[\"lambda_\"].max = 1\n", "\n", "parameters[\"amplitude\"].min = 0.01 * parameters[\"amplitude\"].value\n", "parameters[\"amplitude\"].max = 100 * parameters[\"amplitude\"].value\n", "\n", "parameters[\"sigma\"].min = 0.05\n", "parameters[\"sigma\"].max = 1\n", "\n", "# Setting amplitude init values a bit offset to see evolution\n", "# Here starting close to the real value\n", "parameters[\"index\"].value = 2.0\n", "parameters[\"amplitude\"].value = 3.2e-12\n", "parameters[\"lambda_\"].value = 0.05\n", "\n", "print(dataset.models)\n", "print(\"stat =\", dataset.stat_sum())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%time\n", "# Now let's define a function to init parameters and run the MCMC with emcee\n", "# Depending on your number of walkers, Nrun and dimensionality, this can take a while (> minutes)\n", "sampler = run_mcmc(dataset, nwalkers=6, nrun=150) # to speedup the notebook\n", "# sampler=run_mcmc(dataset,nwalkers=12,nrun=1000) # more accurate contours" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Plot the results\n", "\n", "The MCMC will return a sampler object containing the trace of all walkers.
\n", "The most important part is the chain attribute which is an array of shape:
\n", "_(nwalkers, nrun, nfreeparam)_\n", "\n", "The chain is then used to plot the trace of the walkers and estimate the burnin period (the time for the walkers to reach a stationary stage)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "plot_trace(sampler, dataset)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plot_corner(sampler, dataset, nburn=50)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Plot the model dispersion\n", "\n", "Using the samples from the chain after the burn period, we can plot the different models compared to the truth model. To do this we need to the spectral models for each parameter state in the sample." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "emin, emax = [0.1, 100] * u.TeV\n", "nburn = 50\n", "\n", "fig, ax = plt.subplots(1, 1, figsize=(12, 6))\n", "\n", "for nwalk in range(0, 6):\n", " for n in range(nburn, nburn + 100):\n", " pars = sampler.chain[nwalk, n, :]\n", "\n", " # set model parameters\n", " par_to_model(dataset, pars)\n", " spectral_model = dataset.models[\"source\"].spectral_model\n", "\n", " spectral_model.plot(\n", " energy_range=(emin, emax),\n", " ax=ax,\n", " energy_power=2,\n", " alpha=0.02,\n", " color=\"grey\",\n", " )\n", "\n", "\n", "sky_model_simu.spectral_model.plot(\n", " energy_range=(emin, emax), energy_power=2, ax=ax, color=\"red\"\n", ");" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fun Zone\n", "\n", "Now that you have the sampler chain, you have in your hands the entire history of each walkers in the N-Dimensional parameter space.
\n", "You can for example trace the steps of each walker in any parameter space." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Here we plot the trace of one walker in a given parameter space\n", "parx, pary = 0, 1\n", "\n", "plt.plot(sampler.chain[0, :, parx], sampler.chain[0, :, pary], \"ko\", ms=1)\n", "plt.plot(\n", " sampler.chain[0, :, parx],\n", " sampler.chain[0, :, pary],\n", " ls=\":\",\n", " color=\"grey\",\n", " alpha=0.5,\n", ")\n", "\n", "plt.xlabel(\"Index\")\n", "plt.ylabel(\"Amplitude\");" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## PeVatrons in CTA ?\n", "\n", "Now it's your turn to play with this MCMC notebook. For example to test the CTA performance to measure a cutoff at very high energies (100 TeV ?).\n", "\n", "After defining your Skymodel it can be as simple as this :" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# dataset = simulate_dataset(model, geom, pointing, irfs)\n", "# sampler = run_mcmc(dataset)\n", "# plot_trace(sampler, dataset)\n", "# plot_corner(sampler, dataset, nburn=200)" ] } ], "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": 4 }