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

1D 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, RegionGeom

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

  type      name     value         unit        error   min max frozen link
-------- --------- ---------- -------------- --------- --- --- ------ ----
spectral     index 3.0000e+00                0.000e+00 nan nan  False
spectral amplitude 2.5000e-12 cm-2 s-1 TeV-1 0.000e+00 nan nan  False
spectral reference 1.0000e+00            TeV 0.000e+00 nan nan   True
[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
geom = RegionGeom.create(region=on_region, axes=[energy_axis])

dataset_empty = SpectrumDataset.create(
    geom=geom, energy_axis_true=energy_axis_true, 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.29
  Total excess counts             : 275.71

  Predicted counts                : 303.66
  Predicted background counts     : 22.29
  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   +/-    0.00
      amplitude               :   2.50e-12   +/- 0.0e+00 1 / (cm2 s TeV)
      reference    (frozen)   :      1.000       TeV


You can see that background 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                            : zDADetr1

  Total counts                    : 298
  Total background counts         : 19.00
  Total excess counts             : 279.00

  Predicted counts                : 300.39
  Predicted background counts     : 19.02
  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              : wstat
  Fit statistic value (-2 log(L)) : 8.03

  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   +/-    0.00
      amplitude               :   2.50e-12   +/- 0.0e+00 1 / (cm2 s TeV)
      reference    (frozen)   :      1.000       TeV

    Total counts_off                : 95
  Acceptance                      : 9
  Acceptance off                  : 45

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 362 ms, sys: 11.4 ms, total: 374 ms
Wall time: 367 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
str7int64float64float64float64float64float64float64float64float64float64float64float64float64float64int64int64str5float64int64float64float64float64
stacked31718.399999618530273298.600006103515627.08240213552948868.1666675131354168.16666751313541nan252718176.017719697408.03600.03600.0000000000020.088055555555555550.0051111110051472980.0829444461398654699wstat738.7245834271496929.045.0000009329422850.20000000298023224
obs-127522.0253.023.7678536548728564.1666666666666964.16666666666669nan252718170.9728768217719697919.5992773600.03600.00.07638888888888890.0061111111111111110.0702777777777777799wstat575.7795127847381109.045.00.2
obs-229320.6272.425.1711055540465566.066.0nan252718170.9728768217719697919.5992773600.03600.00.081388888888888890.0057222222222222220.0756666666666666699wstat645.49938240753031039.045.00.2
obs-328022.4257.623.98295173740537665.3333333333333465.33333333333334nan252718170.9728768217719697919.5992773600.03600.00.077777777777777780.0062222222222222220.0715555555555555799wstat585.92415469858721129.045.00.2
obs-433720.6316.427.68270994518474773.3333333333333473.33333333333334nan252718170.9728768217719697919.5992773600.03600.00.093611111111111120.0057222222222222220.0878888888888888899wstat787.3147239494481039.045.00.2
obs-528324.400000000000002258.623.72715478234789567.5000000000000167.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.078611111111111120.0067777777777777780.0718333333333333599wstat574.85257377274991229.044.999999999999990.2
obs-633022.400000000000006307.626.88918447572786673.6666666666666773.66666666666667nan252718170.9728768217719697919.5992773600.03600.00.091666666666666660.0062222222222222240.0854444444444444599wstat734.24147552859371129.044.9999999999999860.2
obs-728325.8257.223.4308797479585368.6666666666666768.66666666666667nan252718170.9728768217719697919.5992773600.03600.00.078611111111111120.0071666666666666670.0714444444444444499wstat552.36987794480441299.045.00.2
obs-830823.400000000000002284.625.4204927332833370.8333333333333470.83333333333334nan252718170.9728768217719697919.5992773600.03600.00.085555555555555550.0065000000000000010.0790555555555555699wstat652.26215725676331179.044.999999999999990.2
obs-929920.4278.625.5708507148686366.8333333333333466.83333333333334nan252718170.9728768217719697919.5992773600.03600.00.083055555555555550.0056666666666666660.077388888888888999wstat666.90626702607861029.045.00.2
obs-1031015.2294.827.48897216135677464.3333333333333464.33333333333334nan252718170.9728768217719697919.5992773600.03600.00.086111111111111110.0042222222222222220.0818888888888888999wstat768.5404492529331769.045.00.2
obs-1128524.000000000000004261.023.93383374545468567.5000000000000167.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.079166666666666660.0066666666666666680.072599wstat583.4487532927331209.044.999999999999990.2
obs-1229921.000000000000004278.025.432526389511767.3333333333333667.33333333333336nan252718170.9728768217719697919.5992773600.03600.00.083055555555555550.00583333333333333450.0772222222222222299wstat655.27682464803571059.044.999999999999990.2
obs-1330921.6287.425.87740623501261869.5000000000000169.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.085833333333333330.0060.0798333333333333399wstat672.3557482743361089.045.00.2
obs-1432022.599999999999998297.426.28282602819256772.1666666666666772.16666666666667nan252718170.9728768217719697919.5992773600.03600.00.088888888888888890.0062777777777777770.0826111111111111199wstat697.59497454151691139.045.000000000000010.2
obs-1528322.0261.024.2540897930413765.5000000000000165.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.078611111111111120.0061111111111111110.072599wstat592.87545637398891109.045.00.2
obs-1629824.200000000000003273.824.66421820169735269.8333333333333669.83333333333336nan252718170.9728768217719697919.5992773600.03600.00.082777777777777780.0067222222222222230.0760555555555555699wstat619.25841883868051219.044.999999999999990.2
obs-1730128.200000000000003272.824.0118015192522773.6666666666666773.66666666666667nan252718170.9728768217719697919.5992773600.03600.00.083611111111111110.0078333333333333350.0757777777777777899wstat588.49763795040561419.044.999999999999990.2
.....................................................................
obs-8130119.400000000000002281.625.92234741483462266.3333333333333466.33333333333334nan252718170.9728768217719697919.5992773600.03600.00.083611111111111110.0053888888888888890.0782222222222222399wstat678.9813616402096979.044.999999999999990.2
obs-8228022.000000000000004258.024.07258704408423765.065.0nan252718170.9728768217719697919.5992773600.03600.00.077777777777777780.0061111111111111120.0716666666666666799wstat581.86100831608771109.044.999999999999990.2
obs-8330322.200000000000003280.825.39492828229910569.0000000000000169.00000000000001nan252718170.9728768217719697919.5992773600.03600.00.084166666666666670.00616666666666666750.07899wstat654.46508964703431119.044.999999999999990.2
obs-8426921.200000000000003247.823.58024714002698762.50000000000001462.500000000000014nan252718170.9728768217719697919.5992773600.03600.00.074722222222222220.005888888888888890.0688333333333333399wstat577.23628917662691069.044.999999999999990.2
obs-8529722.4274.624.99893584573557368.1666666666666768.16666666666667nan252718170.9728768217719697919.5992773600.03600.00.08250.0062222222222222220.0762777777777777899wstat631.62983611980531129.045.00.2
obs-8628617.800000000000004268.225.42340896951545362.5000000000000162.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.079444444444444440.0049444444444444460.074599wstat655.2082535886425899.044.9999999999999860.2
obs-8733319.8313.227.64685145114721772.0000000000000172.00000000000001nan252718170.9728768217719697919.5992773600.03600.00.09250.00550000000000000050.08799wstat770.1313412321031999.045.00.2
obs-8831518.200000000000003296.827.017205925109767.6666666666666967.66666666666669nan252718170.9728768217719697919.5992773600.03600.00.08750.0050555555555555560.0824444444444444599wstat734.6476098262428919.044.999999999999990.2
obs-8928722.000000000000004265.024.4945655868051566.1666666666666766.16666666666667nan252718170.9728768217719697919.5992773600.03600.00.079722222222222220.0061111111111111120.0736111111111111199wstat611.23340636850891109.044.999999999999990.2
obs-9028619.000000000000004267.025.13122188704343863.5000000000000163.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.079444444444444440.0052777777777777790.0741666666666666799wstat635.8304116110406959.044.999999999999990.2
obs-9128525.200000000000003259.823.6775459193106968.5000000000000168.50000000000001nan252718170.9728768217719697919.5992773600.03600.00.079166666666666660.0070000000000000010.0721666666666666799wstat573.35647429633811269.044.999999999999990.2
obs-9231323.6289.425.66493542019417671.8333333333333671.83333333333336nan252718170.9728768217719697919.5992773600.03600.00.086944444444444450.0065555555555555560.0803888888888888899wstat669.44961428251961189.045.00.2
obs-9330218.8283.226.12386752260549766.0000000000000166.00000000000001nan252718170.9728768217719697919.5992773600.03600.00.083888888888888890.0052222222222222230.0786666666666666699wstat700.5066738339824949.045.00.2
obs-9432221.8300.226.57402975747320271.8333333333333471.83333333333334nan252718170.9728768217719697919.5992773600.03600.00.089444444444444440.0060555555555555550.0833888888888888999wstat715.25704980371471099.045.00.2
obs-9530524.400000000000006280.625.03073126049315271.1666666666666771.16666666666667nan252718170.9728768217719697919.5992773600.03600.00.084722222222222230.0067777777777777790.0779444444444444699wstat643.28468794047931229.044.999999999999990.2
obs-9630123.6277.424.96984596942142869.8333333333333469.83333333333334nan252718170.9728768217719697919.5992773600.03600.00.083611111111111110.0065555555555555560.0770555555555555499wstat626.73968424286241189.045.00.2
obs-9729018.8271.225.41798219445482664.0000000000000164.00000000000001nan252718170.9728768217719697919.5992773600.03600.00.080555555555555560.0052222222222222230.0753333333333333499wstat650.9762484493856949.045.00.2
obs-9830120.400000000000002280.625.68783296467500767.1666666666666767.16666666666667nan252718170.9728768217719697919.5992773600.03600.00.083611111111111110.0056666666666666670.0779444444444444699wstat664.56200994049521029.044.999999999999990.2
obs-9932320.8302.226.8570784237687171.1666666666666971.16666666666669nan252718170.9728768217719697919.5992773600.03600.00.089722222222222220.0057777777777777780.0839444444444444599wstat733.15765987680171049.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_analysis_1D_spectrum_simulation_19_0.png

Now, we fit each simulated spectrum individually

[13]:
%%time
results = []

fit = Fit()

for dataset in datasets:
    dataset.models = model.copy()
    result = fit.optimize(dataset)
    results.append(
        {
            "index": result.parameters["index"].value,
            "amplitude": result.parameters["amplitude"].value,
        }
    )
CPU times: user 6.79 s, sys: 78.8 ms, total: 6.87 s
Wall time: 6.81 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.0036925550380533 += 0.08081469527527077
../../../_images/tutorials_analysis_1D_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?

[ ]: