\n",
"\n",
"**This is a fixed-text formatted version of a Jupyter notebook**\n",
"\n",
"- Try online[![Binder](https://static.mybinder.org/badge.svg)](https://mybinder.org/v2/gh/gammapy/gammapy-webpage/v0.19?urlpath=lab/tree/tutorials/analysis/time/light_curve_simulation.ipynb)\n",
"- You may download all the notebooks in the documentation as a\n",
"[tar file](../../../_downloads/notebooks-0.19.tar).\n",
"- **Source files:**\n",
"[light_curve_simulation.ipynb](../../../_static/notebooks/light_curve_simulation.ipynb) |\n",
"[light_curve_simulation.py](../../../_static/notebooks/light_curve_simulation.py)\n",
"
\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Simulating and fitting a time varying source\n",
"\n",
"## Prerequisites:\n",
"\n",
"- To understand how a single binned simulation works, please refer to [spectrum_simulation](../1D/spectrum_simulation.ipynb) [simulate_3d](../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",
"- Optionally, 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": 1,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:30.314867Z",
"iopub.status.busy": "2021-11-22T21:05:30.313354Z",
"iopub.status.idle": "2021-11-22T21:05:30.689080Z",
"shell.execute_reply": "2021-11-22T21:05:30.689280Z"
}
},
"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\n",
"from astropy.time import Time\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": 2,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:30.691851Z",
"iopub.status.busy": "2021-11-22T21:05:30.691458Z",
"iopub.status.idle": "2021-11-22T21:05:31.009334Z",
"shell.execute_reply": "2021-11-22T21:05:31.009526Z"
}
},
"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, RegionGeom\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": 3,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:31.012052Z",
"iopub.status.busy": "2021-11-22T21:05:31.011682Z",
"iopub.status.idle": "2021-11-22T21:05:31.059776Z",
"shell.execute_reply": "2021-11-22T21:05:31.059947Z"
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Invalid unit found in background table! Assuming (s-1 MeV-1 sr-1)\n"
]
}
],
"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": 4,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:31.070907Z",
"iopub.status.busy": "2021-11-22T21:05:31.070610Z",
"iopub.status.idle": "2021-11-22T21:05:31.071746Z",
"shell.execute_reply": "2021-11-22T21:05:31.071934Z"
}
},
"outputs": [],
"source": [
"# Reconstructed and true energy axis\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",
"geom = RegionGeom.create(\"galactic;circle(0, 0, 0.11)\", axes=[energy_axis])"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:31.073975Z",
"iopub.status.busy": "2021-11-22T21:05:31.073571Z",
"iopub.status.idle": "2021-11-22T21:05:31.075126Z",
"shell.execute_reply": "2021-11-22T21:05:31.075362Z"
}
},
"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": 6,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:31.079171Z",
"iopub.status.busy": "2021-11-22T21:05:31.078875Z",
"iopub.status.idle": "2021-11-22T21:05:31.086571Z",
"shell.execute_reply": "2021-11-22T21:05:31.086793Z"
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/adonath/software/mambaforge/envs/gammapy-dev/lib/python3.9/site-packages/astropy/units/quantity.py:486: RuntimeWarning: overflow encountered in exp\n",
" result = super().__array_ufunc__(function, method, *arrays, **kwargs)\n",
"/Users/adonath/software/mambaforge/envs/gammapy-dev/lib/python3.9/site-packages/astropy/units/quantity.py:486: RuntimeWarning: invalid value encountered in subtract\n",
" result = super().__array_ufunc__(function, method, *arrays, **kwargs)\n"
]
}
],
"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": 7,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:31.090804Z",
"iopub.status.busy": "2021-11-22T21:05:31.090379Z",
"iopub.status.idle": "2021-11-22T21:05:31.092402Z",
"shell.execute_reply": "2021-11-22T21:05:31.092576Z"
}
},
"outputs": [
{
"data": {
"text/html": [
"
Table length=5\n",
"
\n",
"
type
name
value
unit
error
min
max
frozen
link
\n",
"
str8
str9
float64
str14
int64
float64
float64
bool
str1
\n",
"
spectral
index
3.0000e+00
0.000e+00
nan
nan
False
\n",
"
spectral
amplitude
1.0000e-11
cm-2 s-1 TeV-1
0.000e+00
nan
nan
False
\n",
"
spectral
reference
1.0000e+00
TeV
0.000e+00
nan
nan
True
\n",
"
temporal
t0
6.0000e+00
h
0.000e+00
nan
nan
False
\n",
"
temporal
t_ref
5.8909e+04
d
0.000e+00
nan
nan
True
\n",
"
"
],
"text/plain": [
"
\n",
" type name value unit error min max frozen link\n",
" str8 str9 float64 str14 int64 float64 float64 bool str1\n",
"-------- --------- ---------- -------------- --------- ------- ------- ------ ----\n",
"spectral index 3.0000e+00 0.000e+00 nan nan False \n",
"spectral amplitude 1.0000e-11 cm-2 s-1 TeV-1 0.000e+00 nan nan False \n",
"spectral reference 1.0000e+00 TeV 0.000e+00 nan nan True \n",
"temporal t0 6.0000e+00 h 0.000e+00 nan nan False \n",
"temporal t_ref 5.8909e+04 d 0.000e+00 nan nan True "
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"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": 8,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:31.094619Z",
"iopub.status.busy": "2021-11-22T21:05:31.094331Z",
"iopub.status.idle": "2021-11-22T21:05:31.095404Z",
"shell.execute_reply": "2021-11-22T21:05:31.095630Z"
}
},
"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": 9,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:31.100461Z",
"iopub.status.busy": "2021-11-22T21:05:31.100119Z",
"iopub.status.idle": "2021-11-22T21:05:32.062086Z",
"shell.execute_reply": "2021-11-22T21:05:32.062266Z"
}
},
"outputs": [],
"source": [
"datasets = Datasets()\n",
"\n",
"empty = SpectrumDataset.create(\n",
" geom=geom, energy_axis_true=energy_axis_true, 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": 10,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:32.065323Z",
"iopub.status.busy": "2021-11-22T21:05:32.064931Z",
"iopub.status.idle": "2021-11-22T21:05:32.089276Z",
"shell.execute_reply": "2021-11-22T21:05:32.089460Z"
}
},
"outputs": [
{
"data": {
"text/html": [
"
"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"ax = lc_1d.plot(marker=\"o\", label=\"3D\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We have the reconstructed lightcurve at this point. Further standard analysis 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 simultaneously fit the all datasets using a given temporal model. This does a joint fitting across the different datasets, while simultaneously minimising 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 parameters of a model in a given group of dataset will be tied. For more details on joint fitting in gammapy, see [here](../2D/modeling_2D.ipynb)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Fit the datasets"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:33.804677Z",
"iopub.status.busy": "2021-11-22T21:05:33.804371Z",
"iopub.status.idle": "2021-11-22T21:05:33.807636Z",
"shell.execute_reply": "2021-11-22T21:05:33.807831Z"
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/adonath/software/mambaforge/envs/gammapy-dev/lib/python3.9/site-packages/astropy/units/quantity.py:486: RuntimeWarning: overflow encountered in exp\n",
" result = super().__array_ufunc__(function, method, *arrays, **kwargs)\n",
"/Users/adonath/software/mambaforge/envs/gammapy-dev/lib/python3.9/site-packages/astropy/units/quantity.py:486: RuntimeWarning: invalid value encountered in subtract\n",
" result = super().__array_ufunc__(function, method, *arrays, **kwargs)\n"
]
}
],
"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": 16,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:33.809962Z",
"iopub.status.busy": "2021-11-22T21:05:33.808764Z",
"iopub.status.idle": "2021-11-22T21:05:33.812022Z",
"shell.execute_reply": "2021-11-22T21:05:33.812251Z"
}
},
"outputs": [
{
"data": {
"text/html": [
"
Table length=5\n",
"
\n",
"
type
name
value
unit
error
min
max
frozen
link
\n",
"
str8
str9
float64
str14
int64
float64
float64
bool
str1
\n",
"
spectral
index
2.0000e+00
0.000e+00
nan
nan
False
\n",
"
spectral
amplitude
1.0000e-12
cm-2 s-1 TeV-1
0.000e+00
nan
nan
False
\n",
"
spectral
reference
1.0000e+00
TeV
0.000e+00
nan
nan
True
\n",
"
temporal
t0
1.0000e+01
h
0.000e+00
nan
nan
False
\n",
"
temporal
t_ref
5.8909e+04
d
0.000e+00
nan
nan
True
\n",
"
"
],
"text/plain": [
"
\n",
" type name value unit error min max frozen link\n",
" str8 str9 float64 str14 int64 float64 float64 bool str1\n",
"-------- --------- ---------- -------------- --------- ------- ------- ------ ----\n",
"spectral index 2.0000e+00 0.000e+00 nan nan False \n",
"spectral amplitude 1.0000e-12 cm-2 s-1 TeV-1 0.000e+00 nan nan False \n",
"spectral reference 1.0000e+00 TeV 0.000e+00 nan nan True \n",
"temporal t0 1.0000e+01 h 0.000e+00 nan nan False \n",
"temporal t_ref 5.8909e+04 d 0.000e+00 nan nan True "
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"model.parameters.to_table()"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:33.814543Z",
"iopub.status.busy": "2021-11-22T21:05:33.814268Z",
"iopub.status.idle": "2021-11-22T21:05:33.815355Z",
"shell.execute_reply": "2021-11-22T21:05:33.815570Z"
}
},
"outputs": [],
"source": [
"datasets.models = model"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:35.221573Z",
"iopub.status.busy": "2021-11-22T21:05:34.451283Z",
"iopub.status.idle": "2021-11-22T21:05:37.053423Z",
"shell.execute_reply": "2021-11-22T21:05:37.053590Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CPU times: user 3.22 s, sys: 41.5 ms, total: 3.26 s\n",
"Wall time: 3.23 s\n"
]
}
],
"source": [
"%%time\n",
"# Do a joint fit\n",
"fit = Fit()\n",
"result = fit.run(datasets=datasets)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"execution": {
"iopub.execute_input": "2021-11-22T21:05:37.056902Z",
"iopub.status.busy": "2021-11-22T21:05:37.056575Z",
"iopub.status.idle": "2021-11-22T21:05:37.057959Z",
"shell.execute_reply": "2021-11-22T21:05:37.058136Z"
}
},
"outputs": [
{
"data": {
"text/html": [
"
Table length=5\n",
"
\n",
"
type
name
value
unit
error
min
max
frozen
link
\n",
"
str8
str9
float64
str14
float64
float64
float64
bool
str1
\n",
"
spectral
index
2.9693e+00
3.133e-02
nan
nan
False
\n",
"
spectral
amplitude
1.0603e-11
cm-2 s-1 TeV-1
3.703e-13
nan
nan
False
\n",
"
spectral
reference
1.0000e+00
TeV
0.000e+00
nan
nan
True
\n",
"
temporal
t0
5.6466e+00
h
1.982e-01
nan
nan
False
\n",
"
temporal
t_ref
5.8909e+04
d
0.000e+00
nan
nan
True
\n",
"
"
],
"text/plain": [
"
\n",
" type name value unit error min max frozen link\n",
" str8 str9 float64 str14 float64 float64 float64 bool str1\n",
"-------- --------- ---------- -------------- --------- ------- ------- ------ ----\n",
"spectral index 2.9693e+00 3.133e-02 nan nan False \n",
"spectral amplitude 1.0603e-11 cm-2 s-1 TeV-1 3.703e-13 nan nan False \n",
"spectral reference 1.0000e+00 TeV 0.000e+00 nan nan True \n",
"temporal t0 5.6466e+00 h 1.982e-01 nan nan False \n",
"temporal t_ref 5.8909e+04 d 0.000e+00 nan nan True "
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"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.9.0"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
"autoclose": false,
"autocomplete": true,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1.0,
"eqLabelWithNumbers": true,
"eqNumInitial": 1.0,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
},
"nbsphinx": {
"orphan": true
}
},
"nbformat": 4,
"nbformat_minor": 4
}