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

Simulating and fitting a time varying source

Prerequisites:

Context

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.

Objective: Simulate and fit a time decaying light curve of a source with CTA using the CTA 1DC response

Proposed approach:

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.

In summary, necessary steps are:

  • Choose observation parameters including a list of gammapy.data.GTI

  • Define temporal and spectral models from :ref:model-gallery as per science case

  • Perform the simulation (in 1D or 3D)

  • Extract the light curve from the reduced dataset as shown in light curve notebook

  • Optionally, we show here how to fit the simulated datasets using a source model

Setup

As usual, we’ll start with some general imports…

Setup

[1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord
from astropy.time import Time

import logging

log = logging.getLogger(__name__)

And some gammapy specific imports

[2]:
from gammapy.data import Observation
from gammapy.irf import load_cta_irfs
from gammapy.datasets import SpectrumDataset, Datasets
from gammapy.modeling.models import (
    PowerLawSpectralModel,
    ExpDecayTemporalModel,
    SkyModel,
)
from gammapy.maps import MapAxis, RegionGeom
from gammapy.estimators import LightCurveEstimator
from gammapy.makers import SpectrumDatasetMaker
from gammapy.modeling import Fit

Simulating a light curve

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.

[3]:
# Loading IRFs
irfs = load_cta_irfs(
    "$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits"
)
Invalid unit found in background table! Assuming (s-1 MeV-1 sr-1)
[4]:
# Reconstructed and true energy axis
energy_axis = MapAxis.from_edges(
    np.logspace(-0.5, 1.0, 10), unit="TeV", name="energy", interp="log"
)
energy_axis_true = MapAxis.from_edges(
    np.logspace(-1.2, 2.0, 31), unit="TeV", name="energy_true", interp="log"
)

geom = RegionGeom.create("galactic;circle(0, 0, 0.11)", axes=[energy_axis])
[5]:
# Pointing position
pointing = SkyCoord(0.5, 0.5, unit="deg", frame="galactic")

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.

[6]:
# Define the source model: A combination of spectral and temporal model

gti_t0 = Time("2020-03-01")
spectral_model = PowerLawSpectralModel(
    index=3, amplitude="1e-11 cm-2 s-1 TeV-1", reference="1 TeV"
)
temporal_model = ExpDecayTemporalModel(t0="6 h", t_ref=gti_t0.mjd * u.d)

model_simu = SkyModel(
    spectral_model=spectral_model,
    temporal_model=temporal_model,
    name="model-simu",
)
/Users/adonath/software/mambaforge/envs/gammapy-dev/lib/python3.9/site-packages/astropy/units/quantity.py:486: RuntimeWarning: overflow encountered in exp
  result = super().__array_ufunc__(function, method, *arrays, **kwargs)
/Users/adonath/software/mambaforge/envs/gammapy-dev/lib/python3.9/site-packages/astropy/units/quantity.py:486: RuntimeWarning: invalid value encountered in subtract
  result = super().__array_ufunc__(function, method, *arrays, **kwargs)
[7]:
# Look at the model
model_simu.parameters.to_table()
[7]:
Table length=5
typenamevalueuniterrorminmaxfrozenlink
str8str9float64str14int64float64float64boolstr1
spectralindex3.0000e+000.000e+00nannanFalse
spectralamplitude1.0000e-11cm-2 s-1 TeV-10.000e+00nannanFalse
spectralreference1.0000e+00TeV0.000e+00nannanTrue
temporalt06.0000e+00h0.000e+00nannanFalse
temporalt_ref5.8909e+04d0.000e+00nannanTrue

Now, define the start and observation livetime wrt to the reference time, gti_t0

[8]:
n_obs = 10
tstart = [1, 2, 3, 5, 8, 10, 20, 22, 23, 24] * u.h
lvtm = [55, 25, 26, 40, 40, 50, 40, 52, 43, 47] * u.min

Now perform the simulations

[9]:
datasets = Datasets()

empty = SpectrumDataset.create(
    geom=geom, energy_axis_true=energy_axis_true, name="empty"
)

maker = SpectrumDatasetMaker(selection=["exposure", "background", "edisp"])

for idx in range(n_obs):
    obs = Observation.create(
        pointing=pointing,
        livetime=lvtm[idx],
        tstart=tstart[idx],
        irfs=irfs,
        reference_time=gti_t0,
        obs_id=idx,
    )
    empty_i = empty.copy(name=f"dataset-{idx}")
    dataset = maker.run(empty_i, obs)
    dataset.models = model_simu
    dataset.fake()
    datasets.append(dataset)

The reduced datasets have been successfully simulated. Let’s take a quick look into our datasets.

[10]:
datasets.info_table()
[10]:
Table length=10
namecountsbackgroundexcesssqrt_tsnprednpred_backgroundnpred_signalexposure_minexposure_maxlivetimeontimecounts_ratebackground_rateexcess_raten_binsn_fit_binsstat_typestat_sum
m2 sm2 sss1 / s1 / s1 / s
str9int64float64float64float64float64float64float64float64float64float64float64float64float64float64int64int64str4float64
stacked83820.318769454956055817.681213378906267.8120516609811720.31876973807811720.318769454956055nan216137904.016025275392.03299.9999999999993300.00.2539393939393940.00615720286513820.247782185872395999cashnan
dataset-13359.235804207223003325.76419579277741.88639768268303332.149612809878769.235804207223003322.9138086026557698244500.935563397284216297.3122691500.01500.00.223333333333333330.00615720280481533550.21717613052851899cash-2096.519112853783
dataset-23199.605236375511922309.3947636244880640.20011982055861293.48960258449289.605236375511922283.88436620898085102174280.972985927575584949.204761560.01560.00.204487179487179480.0061572028048153350.1983299766823641699cash-1999.167487932759
dataset-333114.777286731556805316.222713268443237.75884642088334321.783859418843814.777286731556805307.006572687287157191201.4969014211654746075.699632400.02400.00.137916666666666660.00615720280481533550.1317594638618513399cash-2093.961371303704
dataset-419114.777286731556783176.2227132684432125.003242551912294200.9861857996912414.777286731556783186.20889906813449157191201.4969011811654746075.6996142399.99999999999642399.99999999999640.079583333333333450.00615720280481533550.0734261305285181299cash-950.0232173832845
dataset-515618.471608414446006137.52839158555419.764438032194874182.999442729359418.471608414446006164.52783431491338196489001.8711267714568432594.6245383000.03000.00.0520.00615720280481533550.0458427971951846799cash-679.5591099561027
dataset-63714.77728673155680522.2227132684431944.844970711706384539.9779208281207614.77728673155680525.200634096563952157191201.4969014211654746075.699632400.02400.00.0154166666666666670.00615720280481533550.0092594638618513399cash-83.5158051456156
dataset-73419.21047275102384314.7895272489761573.040144950576299642.3048288120531219.21047275102384323.094356061029266204348561.9459718515151169898.409523120.03120.00.0108974358974358970.0061572028048153350.00474023309262056399cash-70.91103544138612
dataset-83115.88558323642356415.1144167635764363.350049281905792832.2499005026512415.88558323642356416.36431726622769168980541.60916912528852031.3771022580.02580.00.0120155038759689920.0061572028048153350.00585830107115365799cash-42.09535699583043
dataset-94117.36331190957924523.6366880904207554.81477484534861332.42183519709226417.36331190957924515.058523287513015184699661.7588591613694326638.9470652820.02820.00.0145390070921985820.00615720280481533550.00838180428738324799cash-96.29813771797772

Extract the lightcurve

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.

[11]:
# Define the model:
spectral_model = PowerLawSpectralModel(
    index=3, amplitude="1e-11 cm-2 s-1 TeV-1", reference="1 TeV"
)
model_fit = SkyModel(spectral_model=spectral_model, name="model-fit")
[12]:
# Attach model to all datasets
datasets.models = model_fit
[13]:
%%time
lc_maker_1d = LightCurveEstimator(
    energy_edges=[0.3, 10] * u.TeV,
    source="model-fit",
    selection_optional=["ul"],
)
lc_1d = lc_maker_1d.run(datasets)
CPU times: user 1.45 s, sys: 18.5 ms, total: 1.47 s
Wall time: 1.47 s
[14]:
ax = lc_1d.plot(marker="o", label="3D")
../../../_images/tutorials_analysis_time_light_curve_simulation_23_0.png

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.

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.

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.

Fit the datasets

[15]:
# Define the model:
spectral_model1 = PowerLawSpectralModel(
    index=2.0, amplitude="1e-12 cm-2 s-1 TeV-1", reference="1 TeV"
)
temporal_model1 = ExpDecayTemporalModel(t0="10 h", t_ref=gti_t0.mjd * u.d)

model = SkyModel(
    spectral_model=spectral_model1,
    temporal_model=temporal_model1,
    name="model-test",
)
/Users/adonath/software/mambaforge/envs/gammapy-dev/lib/python3.9/site-packages/astropy/units/quantity.py:486: RuntimeWarning: overflow encountered in exp
  result = super().__array_ufunc__(function, method, *arrays, **kwargs)
/Users/adonath/software/mambaforge/envs/gammapy-dev/lib/python3.9/site-packages/astropy/units/quantity.py:486: RuntimeWarning: invalid value encountered in subtract
  result = super().__array_ufunc__(function, method, *arrays, **kwargs)
[16]:
model.parameters.to_table()
[16]:
Table length=5
typenamevalueuniterrorminmaxfrozenlink
str8str9float64str14int64float64float64boolstr1
spectralindex2.0000e+000.000e+00nannanFalse
spectralamplitude1.0000e-12cm-2 s-1 TeV-10.000e+00nannanFalse
spectralreference1.0000e+00TeV0.000e+00nannanTrue
temporalt01.0000e+01h0.000e+00nannanFalse
temporalt_ref5.8909e+04d0.000e+00nannanTrue
[17]:
datasets.models = model
[18]:
%%time
# Do a joint fit
fit = Fit()
result = fit.run(datasets=datasets)
CPU times: user 3.22 s, sys: 41.5 ms, total: 3.26 s
Wall time: 3.23 s
[19]:
result.parameters.to_table()
[19]:
Table length=5
typenamevalueuniterrorminmaxfrozenlink
str8str9float64str14float64float64float64boolstr1
spectralindex2.9693e+003.133e-02nannanFalse
spectralamplitude1.0603e-11cm-2 s-1 TeV-13.703e-13nannanFalse
spectralreference1.0000e+00TeV0.000e+00nannanTrue
temporalt05.6466e+00h1.982e-01nannanFalse
temporalt_ref5.8909e+04d0.000e+00nannanTrue

We see that the fitted parameters match well with the simulated ones!

Exercises

  1. Re-do the analysis with MapDataset instead of SpectralDataset

  2. Model the flare of PKS 2155-304 which you obtained using the light curve flare tutorial. Use a combination of a Gaussian and Exponential flare profiles, and fit using scipy.optimize.curve_fit

  3. Do a joint fitting of the datasets.

[ ]: