{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Binned light curve simulation and fitting\n", "\n", "## Prerequisites:\n", "\n", "- To understand how a single binned simulation works, please refer to [spectrum_simulation](spectrum_simulation.ipynb) [simulate_3d](simulate_3d.ipynb) for 1D and 3D simulations respectively.\n", "- For details of light curve extraction using gammapy, refer to the two tutorials [light_curve](light_curve.ipynb) and [light_curve_flare](light_curve_flare.ipynb) \n", "\n", "## Context\n", "\n", "Frequently, studies of variable sources (eg: decaying GRB light curves, AGN flares, etc) require time variable simulations. For most use cases, generating an event list is an overkill, and it suffices to use binned simulations using a temporal model.\n", "\n", "**Objective: Simulate and fit a time decaying light curve of a source with CTA using the CTA 1DC response**\n", "\n", "## Proposed approach:\n", "\n", "We will simulate 10 spectral datasets within given time intervals (Good Time Intervals) following a given spectral (a power law) and temporal profile (an exponential decay, with a decay time of 6 hr ). These are then analysed using the light curve estimator to obtain flux points. Then, we re-fit the simulated datasets to reconstruct back the injected profiles.\n", "\n", "In summary, necessary steps are:\n", "\n", "- Choose observation parameters including a list of `gammapy.data.GTI`\n", "- Define temporal and spectral models from :ref:model-gallery as per science case\n", "- Perform the simulation (in 1D or 3D)\n", "- Extract the light curve from the reduced dataset as shown in [light curve notebook](light_curve.ipynb)\n", "- Optionaly, we show here how to fit the simulated datasets using a source model \n", "\n", "\n", "## Setup \n", "\n", "As usual, we'll start with some general imports..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setup" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import astropy.units as u\n", "from astropy.coordinates import SkyCoord, Angle\n", "from astropy.time import Time\n", "from regions import CircleSkyRegion\n", "\n", "import logging\n", "\n", "log = logging.getLogger(__name__)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And some gammapy specific imports" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from gammapy.data import Observation\n", "from gammapy.irf import load_cta_irfs\n", "from gammapy.datasets import SpectrumDataset, Datasets\n", "from gammapy.modeling.models import (\n", " PowerLawSpectralModel,\n", " ExpDecayTemporalModel,\n", " SkyModel,\n", ")\n", "from gammapy.maps import MapAxis\n", "from gammapy.estimators import LightCurveEstimator\n", "from gammapy.makers import SpectrumDatasetMaker\n", "from gammapy.modeling import Fit" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Simulating a light curve\n", "\n", "We will simulate 10 datasets using an `PowerLawSpectralModel` and a `ExpDecayTemporalModel`. The important thing to note here is how to attach a different `GTI` to each dataset." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Loading IRFs\n", "irfs = load_cta_irfs(\n", " \"$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits\"\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Reconstructed and true energy axis\n", "center = SkyCoord(0.0, 0.0, unit=\"deg\", frame=\"galactic\")\n", "energy_axis = MapAxis.from_edges(\n", " np.logspace(-0.5, 1.0, 10), unit=\"TeV\", name=\"energy\", interp=\"log\"\n", ")\n", "energy_axis_true = MapAxis.from_edges(\n", " np.logspace(-1.2, 2.0, 31), unit=\"TeV\", name=\"energy_true\", interp=\"log\"\n", ")\n", "\n", "on_region_radius = Angle(\"0.11 deg\")\n", "on_region = CircleSkyRegion(center=center, radius=on_region_radius)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Pointing position\n", "pointing = SkyCoord(0.5, 0.5, unit=\"deg\", frame=\"galactic\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that observations are usually conducted in Wobble mode, in which the source is not in the center of the camera. This allows to have a symmetrical sky position from which background can be estimated." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define the source model: A combination of spectral and temporal model\n", "\n", "gti_t0 = Time(\"2020-03-01\")\n", "spectral_model = PowerLawSpectralModel(\n", " index=3, amplitude=\"1e-11 cm-2 s-1 TeV-1\", reference=\"1 TeV\"\n", ")\n", "temporal_model = ExpDecayTemporalModel(t0=\"6 h\", t_ref=gti_t0.mjd * u.d)\n", "\n", "model_simu = SkyModel(\n", " spectral_model=spectral_model,\n", " temporal_model=temporal_model,\n", " name=\"model-simu\",\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Look at the model\n", "model_simu.parameters.to_table()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, define the start and observation livetime wrt to the reference time, `gti_t0`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "n_obs = 10\n", "tstart = [1, 2, 3, 5, 8, 10, 20, 22, 23, 24] * u.h\n", "lvtm = [55, 25, 26, 40, 40, 50, 40, 52, 43, 47] * u.min" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now perform the simulations" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "datasets = Datasets()\n", "\n", "empty = SpectrumDataset.create(\n", " e_reco=energy_axis, e_true=energy_axis_true, region=on_region, name=\"empty\"\n", ")\n", "\n", "maker = SpectrumDatasetMaker(selection=[\"exposure\", \"background\", \"edisp\"])\n", "\n", "for idx in range(n_obs):\n", " obs = Observation.create(\n", " pointing=pointing,\n", " livetime=lvtm[idx],\n", " tstart=tstart[idx],\n", " irfs=irfs,\n", " reference_time=gti_t0,\n", " obs_id=idx,\n", " )\n", " empty_i = empty.copy(name=f\"dataset-{idx}\")\n", " dataset = maker.run(empty_i, obs)\n", " dataset.models = model_simu\n", " dataset.fake()\n", " datasets.append(dataset)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The reduced datasets have been successfully simulated. Let's take a quick look into our datasets." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "datasets.info_table()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Extract the lightcurve\n", "\n", "This section uses standard light curve estimation tools for a 1D extraction. Only a spectral model needs to be defined in this case. Since the estimator returns the integrated flux separately for each time bin, the temporal model need not be accounted for at this stage." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define the model:\n", "spectral_model = PowerLawSpectralModel(\n", " index=3, amplitude=\"1e-11 cm-2 s-1 TeV-1\", reference=\"1 TeV\"\n", ")\n", "model_fit = SkyModel(spectral_model=spectral_model, name=\"model-fit\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Attach model to each dataset\n", "for dataset in datasets:\n", " dataset.models = model_fit" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%time\n", "lc_maker_1d = LightCurveEstimator(\n", " energy_edges=[energy_axis.edges[0], energy_axis.edges[-1]],\n", " source=\"model-fit\",\n", ")\n", "lc_1d = lc_maker_1d.run(datasets)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lc_1d.table[\"is_ul\"] = lc_1d.table[\"ts\"] < 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ax = lc_1d.plot(marker=\"o\", label=\"3D\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We have the reconstructed lightcurve at this point. Further standard analyis might involve modeling the temporal profiles with an analytical or theoretical model. You may do this using your favourite fitting package, one possible option being `curve_fit` inside `scipy.optimize`.\n", "\n", "In the next section, we show how to simulatenously fit the all datasets using a given temporal model. This does a joint fitting across the different datasets, while simultaneously miniminsing across the temporal model parameters as well. We will fit the amplitude, spectral index and the decay time scale. Note that `t_ref` should be fixed by default for the `ExpDecayTemporalModel`. \n", "\n", "For modelling and fitting more complex flares, you should attach the relevant model to each group of `datasets`. The paramters of a model in a given group of dataset will be tied. For more details on joint fitting in gammapy, see [here](modeling.ipynb)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fit the datasets" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define the model:\n", "spectral_model1 = PowerLawSpectralModel(\n", " index=2.0, amplitude=\"1e-12 cm-2 s-1 TeV-1\", reference=\"1 TeV\"\n", ")\n", "temporal_model1 = ExpDecayTemporalModel(t0=\"10 h\", t_ref=gti_t0.mjd * u.d)\n", "\n", "model = SkyModel(\n", " spectral_model=spectral_model1,\n", " temporal_model=temporal_model1,\n", " name=\"model-test\",\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model.parameters.to_table()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "datasets.models = model" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%time\n", "# Do a joint fit\n", "fit = Fit(datasets)\n", "result = fit.run()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "result.parameters.to_table()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We see that the fitted parameters match well with the simulated ones!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercises\n", "\n", "1. Re-do the analysis with `MapDataset` instead of `SpectralDataset`\n", "2. Model the flare of PKS 2155-304 which you obtained using the [light curve flare tutorial](light_curve_flare.ipynb). Use a combination of a Gaussian and Exponential flare profiles, and fit using `scipy.optimize.curve_fit`\n", "3. Do a joint fitting of the datasets." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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 }