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

Spectrum simulation

Prerequisites

Context

To simulate a specific observation, it is not always necessary to simulate the full photon list. For many uses cases, simulating directly a reduced binned dataset is enough: the IRFs reduced in the correct geometry are combined with a source model to predict an actual number of counts per bin. The latter is then used to simulate a reduced dataset using Poisson probability distribution.

This can be done to check the feasibility of a measurement, to test whether fitted parameters really provide a good fit to the data etc.

Here we will see how to perform a 1D spectral simulation of a CTA observation, in particular, we will generate OFF observations following the template background stored in the CTA IRFs.

Objective: simulate a number of spectral ON-OFF observations of a source with a power-law spectral model with CTA using the CTA 1DC response, fit them with the assumed spectral model and check that the distribution of fitted parameters is consistent with the input values.

Setup

[1]:
%matplotlib inline
import matplotlib.pyplot as plt
[2]:
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord, Angle
from regions import CircleSkyRegion
from gammapy.datasets import SpectrumDatasetOnOff, SpectrumDataset, Datasets
from gammapy.makers import SpectrumDatasetMaker
from gammapy.modeling import Fit
from gammapy.modeling.models import (
    PowerLawSpectralModel,
    SkyModel,
)
from gammapy.irf import load_cta_irfs
from gammapy.data import Observation
from gammapy.maps import MapAxis

Simulation of a single spectrum

To do a simulation, we need to define the observational parameters like the livetime, the offset, the assumed integration radius, the energy range to perform the simulation for and the choice of spectral model. We then use an in-memory observation which is convolved with the IRFs to get the predicted number of counts. This is Poission fluctuated using the fake() to get the simulated counts for each observation.

[3]:
# Define simulation parameters parameters
livetime = 1 * u.h

pointing = SkyCoord(0, 0, unit="deg", frame="galactic")
offset = 0.5 * u.deg

# 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"
)

on_region_radius = Angle("0.11 deg")

center = pointing.directional_offset_by(
    position_angle=0 * u.deg, separation=offset
)
on_region = CircleSkyRegion(center=center, radius=on_region_radius)
[4]:
# Define spectral model - a simple Power Law in this case
model_simu = PowerLawSpectralModel(
    index=3.0,
    amplitude=2.5e-12 * u.Unit("cm-2 s-1 TeV-1"),
    reference=1 * u.TeV,
)
print(model_simu)
# we set the sky model used in the dataset
model = SkyModel(spectral_model=model_simu, name="source")
PowerLawSpectralModel

   name     value         unit      min max frozen   error
--------- ---------- -------------- --- --- ------ ---------
    index 3.0000e+00                nan nan  False 0.000e+00
amplitude 2.5000e-12 cm-2 s-1 TeV-1 nan nan  False 0.000e+00
reference 1.0000e+00            TeV nan nan   True 0.000e+00
[5]:
# Load the IRFs
# In this simulation, we use the CTA-1DC irfs shipped with gammapy.
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)
[6]:
obs = Observation.create(pointing=pointing, livetime=livetime, irfs=irfs)
print(obs)
Observation

        obs id            : 0
        tstart            : 51544.00
        tstop             : 51544.04
        duration          : 3600.00 s
        pointing (icrs)   : 266.4 deg, -28.9 deg

        deadtime fraction : 0.0%

[7]:
# Make the SpectrumDataset
dataset_empty = SpectrumDataset.create(
    e_reco=energy_axis, e_true=energy_axis_true, region=on_region, name="obs-0"
)
maker = SpectrumDatasetMaker(selection=["exposure", "edisp", "background"])

dataset = maker.run(dataset_empty, obs)
[8]:
# Set the model on the dataset, and fake
dataset.models = model
dataset.fake(random_state=42)
print(dataset)
SpectrumDataset
---------------

  Name                            : obs-0

  Total counts                    : 298
  Total background counts         : 22.32
  Total excess counts             : 275.68

  Predicted counts                : 303.69
  Predicted background counts     : 22.32
  Predicted excess counts         : 281.37

  Exposure min                    : 2.53e+08 m2 s
  Exposure max                    : 1.77e+10 m2 s

  Number of total bins            : 9
  Number of fit bins              : 9

  Fit statistic type              : cash
  Fit statistic value (-2 log(L)) : -1811.58

  Number of models                : 1
  Number of parameters            : 3
  Number of free parameters       : 2

  Component 0: SkyModel

    Name                      : source
    Datasets names            : None
    Spectral model type       : PowerLawSpectralModel
    Spatial  model type       :
    Temporal model type       :
    Parameters:
      index                   :   3.000
      amplitude               :   2.50e-12  1 / (cm2 s TeV)
      reference    (frozen)   :   1.000  TeV


You can see that backgound counts are now simulated

On-Off analysis

To do an on off spectral analysis, which is the usual science case, the standard would be to use SpectrumDatasetOnOff, which uses the acceptance to fake off-counts

[9]:
dataset_on_off = SpectrumDatasetOnOff.from_spectrum_dataset(
    dataset=dataset, acceptance=1, acceptance_off=5
)
dataset_on_off.fake(npred_background=dataset.npred_background())
print(dataset_on_off)
SpectrumDatasetOnOff
--------------------

  Name                            : obs-0

  Total counts                    : 285
  Total off counts                : 112.00
  Total background counts         : 22.40
  Total excess counts             : 262.60

  Predicted counts                : 303.54
  Predicted background counts     : 22.17
  Predicted excess counts         : 281.37

  Exposure min                    : 2.53e+08 m2 s
  Exposure max                    : 1.77e+10 m2 s

  Acceptance mean                 : 1.000
  Acceptance off                  : 45.000

  Number of total bins            : 9
  Number of fit bins              : 9

  Fit statistic type              : wstat
  Fit statistic value (-2 log(L)) : 4.48

  Number of models                : 1
  Number of parameters            : 3
  Number of free parameters       : 2

  Component 0: SkyModel

    Name                      : source
    Datasets names            : None
    Spectral model type       : PowerLawSpectralModel
    Spatial  model type       :
    Temporal model type       :
    Parameters:
      index                   :   3.000
      amplitude               :   2.50e-12  1 / (cm2 s TeV)
      reference    (frozen)   :   1.000  TeV


You can see that off counts are now simulated as well. We now simulate several spectra using the same set of observation conditions.

[10]:
%%time

n_obs = 100
datasets = Datasets()

for idx in range(n_obs):
    dataset_on_off.fake(
        random_state=idx, npred_background=dataset.npred_background()
    )
    dataset_fake = dataset_on_off.copy(name=f"obs-{idx}")
    dataset_fake.meta_table["OBS_ID"] = [idx]
    datasets.append(dataset_fake)
CPU times: user 607 ms, sys: 13 ms, total: 620 ms
Wall time: 621 ms
[11]:
table = datasets.info_table()
table
[11]:
Table length=100
namecountsbackgroundexcesssqrt_tsnprednpred_backgroundnpred_signalexposure_minexposure_maxlivetimeontimecounts_ratebackground_rateexcess_raten_binsn_fit_binsstat_typestat_sumcounts_offacceptanceacceptance_offalpha
m2 sm2 sss1 / s1 / s1 / s
str6float64float64float64float64float64float64float64float64float64float64float64float64float64float64int64int64str5float64int64float64float64float64
obs-0317.018.400000000000002298.627.08240194504324300.023721792529318.653546302364763281.37017549016446252718170.9728751517719697919.599263600.03600.00.088055555555555550.0051111111111111110.0829444444444444599wstat9.917001109717983929.044.999999999999990.2
obs-1275.022.0253.023.76785365487285302.9527632060656421.582587715901177281.37017549016446252718170.9728751517719697919.599263600.03600.00.07638888888888890.0061111111111111110.0702777777777777799wstat8.818660828556191109.045.00.2
obs-2293.020.6272.425.17110555404655301.839734872925520.469559382761037281.37017549016446252718170.9728751517719697919.599263600.03600.00.081388888888888890.0057222222222222220.0756666666666666699wstat7.3591110029987461039.045.00.2
obs-3280.022.4257.623.982951737405376303.455713902603522.085538412438968281.37017549016446252718170.9728751517719697919.599263600.03600.00.077777777777777780.0062222222222222220.0715555555555555799wstat11.8329834891773161129.045.00.2
obs-4337.020.6316.427.682709945184747302.281284162580720.911108672416212281.37017549016446252718170.9728751517719697919.599263600.03600.00.093611111111111120.0057222222222222220.0878888888888888899wstat17.8671037271713121039.045.00.2
obs-5283.024.400000000000002258.623.727154782347895305.383813845902624.013638355738106281.37017549016446252718170.9728751517719697919.599263600.03600.00.078611111111111120.0067777777777777780.0718333333333333599wstat8.0051961804382581229.044.999999999999990.2
obs-6330.022.400000000000006307.626.889184475727866304.171682312679122.8015068225146281.37017549016446252718170.9728751517719697919.599263600.03600.00.091666666666666660.0062222222222222240.0854444444444444599wstat10.0987664444295581129.044.9999999999999860.2
obs-7283.026.000000000000004257.023.389178133235443307.0218633524487525.651687862284245281.37017549016446252718170.9728751517719697919.599263600.03600.00.078611111111111120.0072222222222222240.0713888888888888999wstat4.3108997791891191309.044.999999999999990.2
obs-8308.023.400000000000002284.625.42049273328333304.835178286128323.46500279596388281.37017549016446252718170.9728751517719697919.599263600.03600.00.085555555555555550.0065000000000000010.0790555555555555699wstat4.1429472135169961179.044.999999999999990.2
.....................................................................
obs-90286.019.000000000000004267.025.131221887043438300.2660027111190318.895827220954608281.37017549016446252718170.9728751517719697919.599263600.03600.00.079444444444444440.0052777777777777790.0741666666666666799wstat6.724388228060566959.044.999999999999990.2
obs-91285.025.200000000000003259.823.67754591931069306.219148597141124.848973106976626281.37017549016446252718170.9728751517719697919.599263600.03600.00.079166666666666660.0070000000000000010.0721666666666666799wstat14.5779408268717591269.044.999999999999990.2
obs-92313.023.6289.425.664935420194176305.05832734099223.688151850827467281.37017549016446252718170.9728751517719697919.599263600.03600.00.086944444444444450.0065555555555555560.0803888888888888899wstat6.3046465683080981189.045.00.2
obs-93302.018.8283.226.123867522605497300.1259513871509618.75577589698646281.37017549016446252718170.9728751517719697919.599263600.03600.00.083888888888888890.0052222222222222230.0786666666666666699wstat5.86503429029057949.045.00.2
obs-94322.022.0300.026.5292481657426303.6642079652339722.294032475069507281.37017549016446252718170.9728751517719697919.599263600.03600.00.089444444444444440.0061111111111111110.0833333333333333399wstat10.0058837608730521109.045.00.2
obs-95305.024.600000000000005280.424.98804632088198305.893020446573724.522844956409255281.37017549016446252718170.9728751517719697919.599263600.03600.00.084722222222222230.00683333333333333450.0778888888888888899wstat5.6277991710462881239.044.999999999999990.2
obs-96301.023.6277.424.969845969421428305.039959264549323.669783774384797281.37017549016446252718170.9728751517719697919.599263600.03600.00.083611111111111110.0065555555555555560.0770555555555555499wstat5.511772031205331189.045.00.2
obs-97290.018.8271.225.417982194454826300.093377655459318.723202165294804281.37017549016446252718170.9728751517719697919.599263600.03600.00.080555555555555560.0052222222222222230.0753333333333333499wstat5.667231272491558949.045.00.2
obs-98301.020.400000000000002280.625.687832964675007301.75614855910520.38597306894053281.37017549016446252718170.9728751517719697919.599263600.03600.00.083611111111111110.0056666666666666670.0779444444444444699wstat7.142141153018121029.044.999999999999990.2
obs-99323.020.8302.226.85707842376871302.476691765042521.106516274878086281.37017549016446252718170.9728751517719697919.599263600.03600.00.089722222222222220.0057777777777777780.0839444444444444599wstat5.0596239298516051049.045.00.2

Before moving on to the fit let’s have a look at the simulated observations.

[12]:
fix, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].hist(table["counts"])
axes[0].set_xlabel("Counts")
axes[1].hist(table["counts_off"])
axes[1].set_xlabel("Counts Off")
axes[2].hist(table["excess"])
axes[2].set_xlabel("excess");
../_images/tutorials_spectrum_simulation_19_0.png

Now, we fit each simulated spectrum individually

[13]:
%%time
results = []

for dataset in datasets:
    dataset.models = model.copy()
    fit = Fit([dataset])
    result = fit.optimize()
    results.append(
        {
            "index": result.parameters["index"].value,
            "amplitude": result.parameters["amplitude"].value,
        }
    )
CPU times: user 11.5 s, sys: 86.2 ms, total: 11.6 s
Wall time: 11.7 s

We take a look at the distribution of the fitted indices. This matches very well with the spectrum that we initially injected.

[14]:
index = np.array([_["index"] for _ in results])
plt.hist(index, bins=10, alpha=0.5)
plt.axvline(x=model_simu.parameters["index"].value, color="red")
print(f"index: {index.mean()} += {index.std()}")
index: 3.0036666673409944 += 0.08075110145690628
../_images/tutorials_spectrum_simulation_23_1.png

Exercises

  • Change the observation time to something longer or shorter. Does the observation and spectrum results change as you expected?

  • Change the spectral model, e.g. add a cutoff at 5 TeV, or put a steep-spectrum source with spectral index of 4.0

  • Simulate spectra with the spectral model we just defined. How much observation duration do you need to get back the injected parameters?

[ ]: