Computing flux upper limits#

Explore how to compute flux upper limits for a non-detected source.

Prerequisites#

It is advisable to understand the general Gammapy modeling and fitting framework before proceeding with this notebook, e.g. Modeling and Fitting (DL4 to DL5).

Context#

In the study of VHE sources, one often encounters no significant detection even after long exposures. In that case, it may be useful to compute flux upper limits (UL) for the said target consistent with the observation.

Proposed approach#

In this section, we will use an empty observation from the H.E.S.S. DL3 DR1 to understand how to quantify non-detections. There are two distinct approaches to consider:

  • Test for the presence of emission anywhere in a map and compute an integral flux upper limit at any position (i.e. UL map).

  • Test the presence of emission from a potential source with given position and morphology and compute integral and differential UL.

We will use both frequentist and Bayesian approaches for this.

Setup#

As usual, let’s start with some general imports…

# %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import astropy.units as u
import logging

logging.getLogger("ultranest").setLevel(logging.WARNING)
logging.getLogger("ultranest").propagate = False

from gammapy.datasets import MapDataset, Datasets
from gammapy.estimators import FluxPointsEstimator, ExcessMapEstimator
from gammapy.modeling import select_nested_models
from gammapy.modeling.models import (
    PointSpatialModel,
    PowerLawSpectralModel,
    SkyModel,
    FoVBackgroundModel,
    Models,
)
from gammapy.estimators import FluxCollectionEstimator
from gammapy.modeling import Parameter, Sampler
from gammapy.modeling.models import UniformPrior
from gammapy.visualization import plot_distribution

Load observation#

For computational purposes, we have already created a MapDataset from observation id 20275 from the public H.E.S.S. data release and stored it in $GAMMAPY_DATA

dataset = MapDataset.read("$GAMMAPY_DATA/datasets/empty-dl4/empty-dl4.fits.gz")
dataset.peek()
plt.show()
Exposure (at FoV center), Containment radius (at FoV center), Energy Dispersion (at FoV center), Exposure map at 3.12 TeV, Counts map, Model npred

Create Upper Limit maps#

We will first use the ExcessMapEstimator for a quick check to see if there are any potential sources in the field. The correlation_radius should be roughly the quadratic sum of the PSF size (at low energies) and the source size you are searching for. You may also use the TSMapEstimator which uses a forward folding approach, where you can directly specify the spatial model you are probing.

estimator = ExcessMapEstimator(
    selection_optional="all",
    correlate_off=True,
    correlation_radius=0.2 * u.deg,
)

lima_maps = estimator.run(dataset)

significance_map = lima_maps["sqrt_ts"]
excess_map = lima_maps["npred_excess"]

fig, (ax1, ax2) = plt.subplots(
    figsize=(11, 4), subplot_kw={"projection": lima_maps.geom.wcs}, ncols=2
)
ax1.set_title("Significance map")
significance_map.plot(ax=ax1, add_cbar=True, cmap="coolwarm", vmin=-4, vmax=4)
ax2.set_title("Excess map")
excess_map.plot(ax=ax2, add_cbar=True, cmap="coolwarm")
plt.show()
Significance map, Excess map

The significance map looks featureless. We will plot a histogram of the significance distribution and fit it with a standard normal. Deviations from a standard normal can suggest the presence of gamma-ray sources, or can also originate from incorrect modeling of the residual hadronic background.

ax = plt.subplot()
plot_distribution(
    significance_map,
    func="norm",
    ax=ax,
    kwargs_hist={"bins": 50, "range": (-4, 4), "density": True},
)
plt.show()
non detected source

We can also see the correlated upper limits at any position in the map. However, it is important to note that this is not a source UL, as the containment correction is not applied here. Instead, it gives the flux upper limits contained within the correlation_radius at each pixel. This can be useful when making quick look plots to search for the presence of new sources within a field - for example in the case of alerts from Gravitational Wave detectors.

lima_maps.flux_ul.plot(add_cbar=True, cmap="Reds")
plt.show()
non detected source

Compute upper limits for a source#

Now, we address a more specific question. Suppose we were expecting a source at a specific position, say at the center of our map. We’ll attempt to fit a point source at the location to determine whether the signal is significant above the background.

For this, we compare two hypotheses:

  • Null hypothesis, \(H_0\) - only the background is present (i.e., no source)

  • Alternative hypothesis, \(H_1\) - the background plus a point source

The difference in test statistic (TS) between the two cases indicates the significance of the alternative hypothesis.

For this purpose, we utilise the function select_nested_models which performs these comparisons internally. As the null hypothesis, \(H_0\), corresponds to the case of no source, we set the amplitude to 0, in other words the source has no flux.

To prevent the fit from drifting to unrelated positions, we freeze the spatial parameters. Alternatively, you can constrain the parameter ranges to stay within your expected region. We also add a background model with a free normalisation to account for uncertainties in the background. You can add more complex background corrections such as letting the tilt free, or a piecewise correction, or add additional models like a diffuse gamma-ray background, etc.

{'ts': 4.610476648189433, 'fit_results': <gammapy.modeling.fit.FitResult object at 0x708b47adc620>, 'fit_results_null': <gammapy.modeling.fit.FitResult object at 0x708b4d1a1340>}

The fitted parameters under the alternative hypothesis:

print(LLR["fit_results"].parameters.to_table())
type    name      value         unit      ...    max    frozen link prior
---- --------- ----------- -------------- ... --------- ------ ---- -----
         index  1.1774e+00                ...       nan  False
     amplitude -8.5434e-13 TeV-1 s-1 cm-2 ...       nan  False
     reference  1.0000e+00            TeV ...       nan   True
         lon_0  1.8700e+02            deg ...       nan   True
         lat_0  2.6000e+00            deg ... 9.000e+01   True
          tilt  0.0000e+00                ...       nan   True
          norm  1.0046e+00                ...       nan  False
     reference  1.0000e+00            TeV ...       nan   True

The test statistic is ts ~ 4.6. Note that here we have only 1 free parameter, the amplitude, and thus, we can assume the simple conversion significance = \(\sqrt{ts} \approx 2.14 \sigma\). Therefore, the observed fluctuations are not significant above the background at the typically required level of 5-sigma. Next, we will estimate the differential upper limits of the source.

Differential upper limits#

As the source is not significantly detected, a measured flux would mostly reflect background fluctuations. Instead, we quote an upper limit (UL): the largest flux that is still compatible with the data, at a chosen confidence level. We compute it in two ways: first a frequentist UL from the profile likelihood, then a Bayesian UL from the posterior distribution. The two answer different questions, as discussed at the end of this notebook.

The upper limit is the maximum flux compatible with this particular data set, and is not an estimate of the true source flux. The upper limits also depends on:

  • The assumed spectral shape can have an impact on the retrieved flux. Here we assume a power law with index 2. The amplitude only sets a reference flux, which is rescaled, so its value does not affect the UL as long as it is positive. In particular, do not use a model with a negative amplitude, as obtained above. We will constrain the amplitude to positive values to remain in the physical realm. Note that for spectral models with a sharp high-energy decline (e.g. ExpCutoff, LogParabola, or EBL-absorbed models), the best-fit amplitude in the cutoff region may predict an extremely low reference flux, leading to unreliable flux limits. A conservative workaround is to use a power-law spectral model when computing flux limits in all energy bins. While this approach is not ideal, it avoids artificially suppressing the reference flux and generally yields more conservative upper limits.

  • The confidence level and the method. Always report both, and, for a Bayesian analysis, also report the prior.

Frequentist differential upper limits#

A frequentist UL is the output of a procedure with a guaranteed coverage: if the observation were repeated many times, the interval [0, UL] would contain the true flux in the stated fraction of the repetitions (e.g. 95%).

In Gammapy, the UL is the flux at which the fit statistic rises by n_sigma_ul**2 above its minimum (on the high-flux side). Asymptotically, this corresponds to a one-sided confidence level: n_sigma_ul=2 (the default) gives ΔTS = 4, i.e. ~97.7%, and n_sigma_ul=1.645 gives 95%. The FluxPointsEstimator computes one UL per energy bin. By default (reoptimize=False), only the normalisation is fitted in each bin; all other parameters stay fixed. Here we use n_sigma_ul=1.645 to get the 95% UL, which is standardly quoted in published results.

Note that in the case of a detection, n_sigma=2 still corresponds to ΔTS = 4 but is associated to a two-sided confidence level of 95%.

For computational reasons here, we keep the background normalisation frozen, but in a real analysis, you should keep it free and use reoptimize=True. The reoptimize configuration does not change the dof, so the above mentioned sigma to confidence interval remains unchanged.

sky_model.parameters["amplitude"].value = 1e-13
sky_model.parameters["index"].value = 2.0
sky_model.freeze(model_type="spatial")

norm_min = 0
norm_max = 100
norm = Parameter(
    name="norm",
    value=1,
    min=norm_min,
    max=norm_max,
    scan_min=0.01,
    scan_max=norm_max,
    interp="log",
)

energy_edges = dataset.geoms["geom"].axes["energy"].edges
fpe = FluxPointsEstimator(
    selection_optional="all",
    energy_edges=energy_edges,
    n_sigma_ul=1.645,
    source="source",
    norm=norm,
)

fp1 = fpe.run(dataset)

It is useful to plot the upper limits along with fit statistic as a density plot to see the TS difference in each bin.

fp1.plot(sed_type="dnde", color="black")
fp1.plot_ts_profiles(sed_type="dnde")
plt.show()
non detected source

It can also be useful to visualise the likelihood profile for diagnostic purposes, as explained in Fitting or Constraining parameter limits.

Expected upper limits (Brazil bands)#

An observed upper limit comes from a single realisation of the data. Repeated experiments of the same expected background (e.g. lightcurves) will lead to different Poisson realizations of the background and will yield different upper limit values. To see how unusual it is, we compare it with the distribution of upper limits we would expect if there were no source. We simulate many background-only datasets, compute the upper limits for each one in the same way as above, and take the median and the 68% and 95% ranges. These form the so-called Brazil bands.

Since this is computationally intensive, we will avoid executing it in this notebook, but show only the static plot.

Instead of running many simulations, a quick alternative is the Asimov approximation of Cowan et al. (2011). A single fit to the Asimov dataset (counts equal to the predicted background, with no fluctuations) gives the median expected upper limit.

def run_mc():
    # Simulate
    n_toys = 1000  # increase for smoother bands
    dnde_ul_toys = []
    for idx in range(n_toys):
        if idx % 10 == 0:
            print(f"Running for ---------- ${idx}")
        toy = dataset.copy(name=f"toy-{idx}")
        toy.models = None
        toy.fake(random_state=idx)
        toy.models = sky_model.copy(name="source")
        fp_toy = fpe.run(toy)
        dnde_ul_toys.append(fp_toy.dnde_ul.quantity.squeeze())

    unit = u.Unit("cm-2 s-1 TeV-1")
    dnde_ul_toys = u.Quantity(dnde_ul_toys).to_value(unit)
    p025, p16, p50, p84, p975 = np.nanpercentile(
        dnde_ul_toys, [2.5, 16, 50, 84, 97.5], axis=0
    )

    # Compute the Asimov UL
    asimov = dataset.copy(name="asimov")

    npred_bkg = asimov.npred_background()
    asimov.counts.data[...] = npred_bkg.data

    asimov.models = Models(
        [
            sky_model.copy(name="source"),
            FoVBackgroundModel(dataset_name=asimov.name),
        ]
    )

    fp_asimov = fpe.run(asimov)

    # Plot
    energy = fp1.energy_ref.to_value("TeV")

    ax = fp1.plot(sed_type="dnde", label="Observed UL", color="black", lw=2)
    ax.fill_between(
        energy, p025, p975, color="gold", alpha=0.5, label="Expected UL, 95%"
    )
    ax.fill_between(
        energy, p16, p84, color="limegreen", alpha=0.3, label="Expected UL, 68%"
    )
    ax.plot(energy, p50, linestyle="dotted", label="Expected UL, median", color="blue")
    ax.plot(
        energy,
        fp_asimov.dnde_ul.quantity.squeeze().to_value(unit),
        linestyle="dashdot",
        label="Asimov UL",
        color="red",
    )

    ax.loglog()
    ax.set_xlabel("Energy [TeV]")
    ax.set_ylabel(f"dnde [{unit.to_string('latex_inline')}]")
    ax.legend()
    plt.show()
../../_images/freq_UL_bands.png

If the observed upper limits lie inside the bands, it implies the data are consistent with background only fluctuations. If they fall below the yellow band, the background is overestimated. To avoid this, you should always reoptimize the parameters of the other models, specially the background model. If they still occur, such points should be treated with caution as they may exclude fluxes the observation was not sensitive to. This usually indicates background systematics that have not been accounted for.

Bayesian credible limits#

An alternative to the frequentist approach above is a Bayesian credible upper limit, the flux below which a chosen fraction of the posterior probability lies.

This requires a prior on every free parameter. To keep the example simple, we fix the spectral index and the position, so the amplitude is the only free parameter. We use a uniform prior starting at zero. Its upper bound must lie well above the upper limits.

Note

A Bayesian upper credible limit depends on the choice of prior. A prior that is uniform in amplitude is the usual choice for upper limits. A log-uniform prior would favour small fluxes and give a lower limit, which then depends on the lower bound of the prior.

FluxCollectionEstimator fits the same normalisation per energy bin as above. It can use either a Fit or a Sampler as solver. With a sampler, the upper limit is the \Phi(n_sigma_ul) quantile of the posterior of the normalisation. While reporting results, always quote the used prior.

prior = UniformPrior(min=norm_min, max=norm_max)
norm_bayes = Parameter("norm", value=1, prior=prior)

sampler = Sampler(
    backend="ultranest",
    options={
        "min_num_live_points": 300,
        "frac_remain": 0.3,
        "log_dir": None,
        "show_status": False,
        "viz_callback": False,
    },
)

fce_bayes = FluxCollectionEstimator(
    energy_edges=energy_edges,
    models=[sky_model],
    n_sigma_ul=1.645,
    norm=norm_bayes,
    solver=sampler,
)
results = fce_bayes.run(Datasets([dataset]))
fp_bayes = results["flux_points"]["source"]

fig, ax = plt.subplots()
unit = u.Unit("cm-2 s-1 TeV-1")
energy = fp_bayes.energy_ref.to_value("TeV")
fp1.plot(ax=ax, fmt="o-", label="Frequentist UL")
ax.plot(
    energy,
    fp_bayes.dnde_ul.quantity.squeeze().to_value(unit),
    "s--",
    label="Bayesian Limit (uniform prior, norm ≥ 0)",
)
ax.loglog()
ax.set_xlabel("Energy [TeV]")
ax.set_ylabel(f"dnde upper limit, 95% [{unit.to_string('latex_inline')}]")
ax.legend()
plt.show()
non detected source
logZ = -1774.022 +- 0.267
  single instance: logZ = -1774.022 +- 0.039
  bootstrapped   : logZ = -1774.017 +- 0.054
  tail           : logZ = +- 0.262
insert order U test : converged: True correlation: inf iterations

    norm                : 0     │▆▆▅▇▆▇▇▆▅▇▇▅▄▅▅▃▃▄▃▂▂▃▂▂▂▃▂▂▂▁▁▂▁▁▁▁▁▁▁│100       31 +- 23


logZ = -1464.975 +- 0.279
  single instance: logZ = -1464.975 +- 0.059
  bootstrapped   : logZ = -1464.973 +- 0.094
  tail           : logZ = +- 0.262
insert order U test : converged: True correlation: inf iterations

    norm                : 0     │▇▆▆▄▄▃▄▂▂▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ▁ ▁ ▁   ▁ │100       13 +- 13


logZ = -1065.356 +- 0.271
  single instance: logZ = -1065.356 +- 0.059
  bootstrapped   : logZ = -1065.352 +- 0.067
  tail           : logZ = +- 0.262
insert order U test : converged: True correlation: inf iterations

    norm                : 0     │▇▇▆▅▅▄▃▂▂▂▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ▁▁ ▁   ▁ │88        12 +- 11


logZ = -986.039 +- 0.273
  single instance: logZ = -986.039 +- 0.048
  bootstrapped   : logZ = -986.036 +- 0.077
  tail           : logZ = +- 0.262
insert order U test : converged: True correlation: inf iterations

    norm                : 0     │▇▆▆▆▅▄▄▃▃▃▃▂▂▂▂▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ▁▁ ▁▁ │100       18 +- 17


logZ = -625.977 +- 0.268
  single instance: logZ = -625.977 +- 0.052
  bootstrapped   : logZ = -625.983 +- 0.056
  tail           : logZ = +- 0.262
insert order U test : converged: True correlation: inf iterations

    norm                : 0     │▇▇▅▅▄▄▄▃▂▃▂▁▂▂▁▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ▁▁▁ │100       16 +- 16


logZ = -636.757 +- 0.274
  single instance: logZ = -636.757 +- 0.039
  bootstrapped   : logZ = -636.753 +- 0.080
  tail           : logZ = +- 0.262
insert order U test : converged: True correlation: inf iterations

    norm                : 0     │▇▇▆▇▆▅▅▄▄▅▃▃▃▃▃▁▃▂▂▂▂▂▁▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁│100       25 +- 22


logZ = -615.135 +- 0.276
  single instance: logZ = -615.135 +- 0.040
  bootstrapped   : logZ = -615.123 +- 0.088
  tail           : logZ = +- 0.262
insert order U test : converged: True correlation: inf iterations

    norm                : 0     │▇▇▇▆▅▆▄▅▄▃▄▃▂▂▃▃▂▁▂▁▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁│100       24 +- 21


logZ = -410.233 +- 0.268
  single instance: logZ = -410.233 +- 0.032
  bootstrapped   : logZ = -410.228 +- 0.053
  tail           : logZ = +- 0.262
insert order U test : converged: True correlation: inf iterations

    norm                : 0     │▅▆▆▇▅▆▅▅▄▅▅▅▃▃▃▄▅▃▃▂▃▂▃▂▂▂▂▁▂▂▃▂▁▂▁▂▁▁▁│100       33 +- 25


logZ = -268.491 +- 0.265
  single instance: logZ = -268.491 +- 0.031
  bootstrapped   : logZ = -268.488 +- 0.037
  tail           : logZ = +- 0.262
insert order U test : converged: True correlation: inf iterations

    norm                : 0     │▇▇▇▇▆▆▆▆▄▄▅▄▅▃▄▂▂▄▃▃▃▃▃▃▃▂▂▁▃▂▂▁▂▂▂▁▁▂▂│100       33 +- 26


logZ = -321.672 +- 0.264
  single instance: logZ = -321.672 +- 0.030
  bootstrapped   : logZ = -321.667 +- 0.029
  tail           : logZ = +- 0.262
insert order U test : converged: True correlation: inf iterations

    norm                : 0     │▇▇▆▅▅▄▅▅▅▄▃▃▄▃▄▃▃▃▃▃▂▃▁▃▂▂▂▁▂▂▂▂▁▂▂▂▁▁▂│100       34 +- 27

/home/runner/work/gammapy-docs/gammapy-docs/gammapy/.tox/build_docs/lib/python3.12/site-packages/gammapy/maps/region/ndmap.py:154: UserWarning: linestyle is redundantly defined by the 'linestyle' keyword argument and the fmt string "o-" (-> linestyle='-'). The keyword argument will take precedence.
  ax.errorbar(
/home/runner/work/gammapy-docs/gammapy-docs/gammapy/.tox/build_docs/lib/python3.12/site-packages/gammapy/maps/region/ndmap.py:154: UserWarning: marker is redundantly defined by the 'marker' keyword argument and the fmt string "o-" (-> marker='o'). The keyword argument will take precedence.
  ax.errorbar(

Comparing the two limits#

Note that the frequentist confidence limits and Bayesian credible limits answer different questions, so they do not have to give the same number.

  • Frequentist (profile likelihood) upper confidence limit. This is a statement about the procedure. If the experiment were repeated many times, the intervals it produces would contain the true flux in a fixed fraction of the repetitions (this is called coverage). In this approach, the other free parameters (“nuisance parameters”) are re-fitted to their best values.

  • Bayesian upper credible limit. This is a statement about the flux, given the data we actually observed and the prior we chose: “there is a 99.8% probability that the flux lies below this value”. It depends heavily on the choice of the prior. The nuisance parameters are integrated out. Every value contributes, weighted by its likelihood and its prior.

In the regime of many counts, with the true value far from the bounds and a flat prior, the likelihood is close to a Gaussian, therefore the two results converge. In the present case these conditions are not met, so differences are expected.

Integral upper limits#

To compute the integral upper limits between certain energies, one can simply run the estimators, eg FluxPointsEstimator with one bin in energy.

emin = energy_edges[0]
emax = energy_edges[-1]
fpe2 = FluxPointsEstimator(
    selection_optional=["ul"], energy_edges=[emin, emax], source="source"
)
fp2 = fpe2.run(dataset)
print(
    f"Integral upper limit between {emin:.1f} and {emax:.1f} is {fp2.flux_ul.quantity.ravel()[0]:.2e}"
)
Integral upper limit between 0.8 TeV and 10.0 TeV is 7.05e-14 1 / (s cm2)

Total running time of the script: (1 minutes 13.918 seconds)

Gallery generated by Sphinx-Gallery