zfit binned#
There are two main ways of looking at “binned fits”
Either an analytic shape that could be fit unbinned but is fit to binned data because of the datasize (typical LHCb, Belle II,…)
stacking template histograms from simulation to provide the shape and fit to binned data (typical done in CMS, ATLAS, some LHCb,…)
Some templated fits with uniform binning, no analytic components and specific morphing and constraints fit into the HistFactory model, implemented in pyhf. These fits make a large portion of CMS and ATLAS analyses.
zfit can, in principle, reproduce them too. However, it’s comparably inefficient, a lot of code and slow. The main purpose is to support anything that is beyond HistFactory.
import matplotlib.pyplot as plt
import mplhep
import numpy as np
import zfit
import zfit.z.numpy as znp # numpy-like backend interface
from zfit import z # backend, special functions
zfit.settings.set_seed(43)
No module named 'nlopt'
Binned parts#
zfit introduces binned equivalents to unbinned components and transformations from one to the other. For example:
SumPDF
->BinnedSumPDF
Data
->BinnedData
UnbinnedNLL
->BinnedNLL
There are converters and new, histogram specific PDFs and methods.
From unbinned to binned#
Let’s start with an example, namely a simple, unbinned fit that we want to perform binned.
normal_np = np.random.normal(loc=2., scale=1.3, size=10000)
obs = zfit.Space("x", limits=(-10, 10))
mu = zfit.Parameter("mu", 1., -4, 6)
sigma = zfit.Parameter("sigma", 1., 0.1, 10)
model_nobin = zfit.pdf.Gauss(mu, sigma, obs)
data_nobin = zfit.Data.from_numpy(obs, normal_np)
loss_nobin = zfit.loss.UnbinnedNLL(model_nobin, data_nobin)
minimizer = zfit.minimize.Minuit()
# make binned
nbins = 50
data = data_nobin.to_binned(nbins)
model = model_nobin.to_binned(data.space)
loss = zfit.loss.BinnedNLL(model, data)
result = minimizer.minimize(loss)
print(result)
FitResult
of
<BinnedNLL model=[<zfit.models.tobinned.BinnedFromUnbinnedPDF object at 0x7efcbd7c6ad0>] data=[<zfit._data.binneddatav1.BinnedData object at 0x7efcbd7c6b50>] constraints=[]>
with
<Minuit Minuit tol=0.001>
╒═════════╤═════════════╤══════════════════╤═══════╤══════════════════════════════════╕
│ valid │ converged │ param at limit │ edm │ approx. fmin (full | internal) │
╞═════════╪═════════════╪══════════════════╪═══════╪══════════════════════════════════╡
│
True
│ True
│ False
│ 3e-05 │ -56085.38 | -55783.96 │
╘═════════╧═════════════╧══════════════════╧═══════╧══════════════════════════════════╛
Parameters
name value (rounded) at limit
------ ------------------ ----------
mu 2.00582 False
sigma 1.30038 False
result.hesse(name="hesse")
{<zfit.Parameter 'mu' floating=True value=2.006>: {'error': 0.013055034979373707,
'cl': 0.68268949},
<zfit.Parameter 'sigma' floating=True value=1.3>: {'error': 0.009267626382269405,
'cl': 0.68268949}}
result.errors(name="errors")
({<zfit.Parameter 'mu' floating=True value=2.006>: {'lower': -0.013153332037857358,
'upper': 0.012957752326530852,
'is_valid': True,
'upper_valid': True,
'lower_valid': True,
'at_lower_limit': False,
'at_upper_limit': False,
'nfcn': 26,
'original': ┌──────────┬───────────────────────┐
│ │ mu │
├──────────┼───────────┬───────────┤
│ Error │ -0.013 │ 0.013 │
│ Valid │ True │ True │
│ At Limit │ False │ False │
│ Max FCN │ False │ False │
│ New Min │ False │ False │
└──────────┴───────────┴───────────┘,
'cl': 0.68268949},
<zfit.Parameter 'sigma' floating=True value=1.3>: {'lower': -0.009231683018082047,
'upper': 0.00930353947983417,
'is_valid': True,
'upper_valid': True,
'lower_valid': True,
'at_lower_limit': False,
'at_upper_limit': False,
'nfcn': 12,
'original': ┌──────────┬───────────────────────┐
│ │ sigma │
├──────────┼───────────┬───────────┤
│ Error │ -0.009 │ 0.009 │
│ Valid │ True │ True │
│ At Limit │ False │ False │
│ Max FCN │ False │ False │
│ New Min │ False │ False │
└──────────┴───────────┴───────────┘,
'cl': 0.68268949}},
None)
print(result)
FitResult
of
<BinnedNLL model=[<zfit.models.tobinned.BinnedFromUnbinnedPDF object at 0x7efcbd7c6ad0>] data=[<zfit._data.binneddatav1.BinnedData object at 0x7efcbd7c6b50>] constraints=[]>
with
<Minuit Minuit tol=0.001>
╒═════════╤═════════════╤══════════════════╤═══════╤══════════════════════════════════╕
│ valid │ converged │ param at limit │ edm │ approx. fmin (full | internal) │
╞═════════╪═════════════╪══════════════════╪═══════╪══════════════════════════════════╡
│
True
│ True
│ False
│ 3e-05 │ -56085.38 | -55783.96 │
╘═════════╧═════════════╧══════════════════╧═══════╧══════════════════════════════════╛
Parameters
name value (rounded) hesse errors at limit
------ ------------------ ----------- ------------------- ----------
mu 2.00582 +/- 0.013 - 0.013 + 0.013 False
sigma 1.30038 +/- 0.0093 - 0.0092 + 0.0093 False
Binned parts in detail#
to_binned
creates a binned (and to_unbinned
an unbinned) version of objects. It takes a binned Space, a binning or (as above), an integer (in which case a uniform binning is created).
This creates implicitly a new, binned space.
obs_binned_auto = data.space
print(obs_binned_auto)
<zfit Space obs=('x',), axes=(0,), limits=(array([[-10.]]), array([[10.]])), binned=True>
print(f"is_binned: {obs_binned_auto.is_binned}, binned obs binning: {obs_binned_auto.binning}")
print(f"is_binned: {obs.is_binned}, unbinned obs binning:{obs.binning}")
is_binned: True, binned obs binning: (RegularBinning(50, -10, 10, underflow=False, overflow=False, name='x'),)
is_binned: False, unbinned obs binning:None
Explicit conversion#
We can explicitly convert spaces, data and models to binned parts.
Either number of bins for uniform binning or explicit binning.
obs_binned = obs.with_binning(nbins)
print(obs_binned)
# or we can create binnings
binning_regular = zfit.binned.RegularBinning(nbins, -10, 10, name='x')
binning_variable = zfit.binned.VariableBinning([-10, -6, -1, -0.1, 0.4, 3, 10], name='x')
<zfit Space obs=('x',), axes=None, limits=(array([[-10.]]), array([[10.]])), binned=True>
Since a binning contains all the information needed to create a Space, a binning can be used to define a space directly.
obs_binned_variable = zfit.Space(binning=binning_variable)
print(obs_binned_variable, obs_binned_variable.binning)
<zfit Space obs=('x',), axes=None, limits=(array([[-10.]]), array([[10.]])), binned=True>
(VariableBinning([-10, -6, -1, -0.1, 0.4, 3, 10], underflow=False, overflow=False, name='x'),)
Converting data, models#
data_nobin.to_binned(obs_binned_variable)
Weight() Σ=WeightedSum(value=10000, variance=10000)
model_nobin.to_binned(obs_binned_variable)
<zfit.models.tobinned.BinnedFromUnbinnedPDF at 0x7efcbc49d890>
Compatibility with UHI#
zfit keeps compatibility with Universal Histogram Interface (UHI) and libraries that implement it (boost-histogram, hist).
BinnedData
directly adheres to UHI (and has ato_hist
attribute)BinnedPDF
has ato_binneddata
andto_hist
attribute
Where a BinnedData
object is expected, a (named) UHI object is also possible. Same goes for the binning axes.
h = model.to_hist()
h_scaled = h * [10_000]
Binneddata#
Binned data has counts
, values
and variances
attributes, it has a binning
(aliased with axes).
data.values()
<tf.Tensor: shape=(50,), dtype=float64, numpy=
array([0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00,
0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00,
0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 1.000e+00, 1.000e+00,
3.000e+00, 8.000e+00, 1.300e+01, 3.100e+01, 9.700e+01, 1.460e+02,
3.140e+02, 4.770e+02, 6.900e+02, 9.190e+02, 1.105e+03, 1.192e+03,
1.204e+03, 1.053e+03, 9.410e+02, 6.810e+02, 4.950e+02, 2.960e+02,
1.750e+02, 8.700e+01, 5.000e+01, 1.800e+01, 3.000e+00, 0.000e+00,
0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00, 0.000e+00,
0.000e+00, 0.000e+00])>
BinnedPDF#
A binned PDF has the same methods as the unbinned counterparts, namely pdf
, integrate
(and their ext_*
parts) and sample
that can respond to binned as well as unbinned data.
Additionally, there are two more methods, namely
counts
returns the absolute counts as for a histogram. Equivalent toext_pdf
,ext_integrate
, this only works if the PDF is extended.rel_counts
relative counts, like a histogram, but the sum is normalized to 1
Note on Counts vs Density#
Counts are the integrated density, i.e. they differ by a factor bin_width
. For regular binning, this is “just” a constant factor, as it’s the same for all bins,
but for Variable binning, this changes “the shape” of the histogram.
binned_sample = model.sample(n=1_000)
Plotting made easy#
This allows plotting to become a lot easier using mplhep
, also for unbinned models.
plt.title("Counts plot")
mplhep.histplot(data, label="data")
mplhep.histplot(model.to_hist() * [data.nevents],
label="model") # scaling up since model is not extended, i.e. has no yield
plt.legend()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[18], line 2
1 plt.title("Counts plot")
----> 2 mplhep.histplot(data, label="data")
3 mplhep.histplot(model.to_hist() * [data.nevents],
4 label="model") # scaling up since model is not extended, i.e. has no yield
5 plt.legend()
File ~/checkouts/readthedocs.org/user_builds/zfit-tutorials/envs/master/lib/python3.11/site-packages/mplhep/plot.py:191, in histplot(H, bins, yerr, w2, w2method, stack, density, binwnorm, histtype, xerr, label, sort, edges, binticks, ax, flow, **kwargs)
189 flow_bins = final_bins
190 for i, h in enumerate(hists):
--> 191 value, variance = h.values().copy(), h.variances()
192 if variance is not None:
193 variance = variance.copy()
File ~/checkouts/readthedocs.org/user_builds/zfit-tutorials/envs/master/lib/python3.11/site-packages/tensorflow/python/framework/tensor.py:261, in Tensor.__getattr__(self, name)
253 if name in {"T", "astype", "ravel", "transpose", "reshape", "clip", "size",
254 "tolist", "data"}:
255 # TODO(wangpeng): Export the enable_numpy_behavior knob
256 raise AttributeError(
257 f"{type(self).__name__} object has no attribute '{name}'. " + """
258 If you are looking for numpy-related methods, please run the following:
259 tf.experimental.numpy.experimental_enable_numpy_behavior()
260 """)
--> 261 self.__getattribute__(name)
AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'copy'
plt.title("Counts plot")
mplhep.histplot(binned_sample, label="sampled data")
mplhep.histplot(model.to_hist() * [binned_sample.nevents],
label="model") # scaling up since model is not extended, i.e. has no yield
plt.legend()
# or using unbinned data points, we can do a density plot
plt.title("Density plot")
mplhep.histplot(data.to_hist(), density=True, label="data")
x = znp.linspace(-10, 10, 200)
plt.plot(x, model.pdf(x), label="model")
plt.legend()
Binned loss functions#
We used above the BinnedNLL
, but zfit offers more, namely an extended version and a BinnedChi2 (or least-square).
print(zfit.loss.__all__)
Fitting using histograms#
There are a few new PDFs that are specific to histogram-like shapes, such as morphing interpolation and shape variations.
Most simple a HistogramPDF wraps a histogram and acts as a PDF.
By default, these histograms are extended automatically (which can be overruled using the extended
argument)
histpdf = zfit.pdf.HistogramPDF(h_scaled) # fixed yield
print(np.sum(histpdf.counts()))
sig_yield = zfit.Parameter('sig_yield', 4_000, 0, 100_000)
histpdf = zfit.pdf.HistogramPDF(h, extended=sig_yield)
print(np.sum(histpdf.counts()))
Modifiers#
We may want to add modifiers, i.e. scale each bin by a value. BinwiseScaleModifier
offers this functionality.
Note however that these are just free parameters and not in any way constraint. This needs to be done manually.
histpdf.space.binning.size
sig_pdf = zfit.pdf.BinwiseScaleModifier(histpdf,
modifiers=True) # or we could give a list of parameters matching each bin
modifiers = sig_pdf.params
# modifiers = {f'modifier_{i}': zfit.Parameter(f'modifier_{i}', 1, 0, 10) for i in range(histpdf.space.binning.size[0])}
# histpdf_scaled = zfit.pdf.BinwiseScaleModifier(histpdf, modifiers=modifiers)
modifiers
sig_pdf.get_yield()
Morphing#
Let’s create a background from simulation. Let’s assume, we have a parameter in the simulation that we’re unsure about.
A common used technique is to use “morphing”: creating multiple templates and interpolating between them. Typically, they are created at +1 and -1 sigma of the nuisance parameter (however, zfit allows arbitrary values and as many as wanted)
bkg_hist = zfit.Data.from_numpy(obs=obs, array=np.random.exponential(scale=20, size=100_000) - 10).to_binned(
obs_binned)
bkg_hist_m1 = zfit.Data.from_numpy(obs=obs,
array=np.random.exponential(scale=35, size=100_000) - 10).to_binned(
obs_binned)
bkg_hist_m05 = zfit.Data.from_numpy(obs=obs,
array=np.random.exponential(scale=26, size=100_000) - 10).to_binned(
obs_binned)
bkg_hist_p1 = zfit.Data.from_numpy(obs=obs,
array=np.random.exponential(scale=17, size=100_000) - 10).to_binned(
obs_binned)
bkg_hists = {-1: bkg_hist_m1, -0.5: bkg_hist_m05, 0: bkg_hist, 1: bkg_hist_p1}
bkg_histpdfs = {k: zfit.pdf.HistogramPDF(v) for k, v in bkg_hists.items()}
mplhep.histplot(list(bkg_hists.values()), label=list(bkg_hists.keys()))
plt.legend();
alpha = zfit.Parameter("alpha", 0, -3, 3)
bkg_yield = zfit.Parameter("bkg_yield", 15_000)
bkg_pdf = zfit.pdf.SplineMorphingPDF(alpha, bkg_histpdfs, extended=bkg_yield)
with alpha.set_value(-0.6): # we can change this value to play around
mplhep.histplot(bkg_pdf.to_hist())
bkg_pdf = zfit.pdf.HistogramPDF(bkg_hist, extended=bkg_yield) # we don't use the spline for simplicity
model = zfit.pdf.BinnedSumPDF([sig_pdf, bkg_pdf])
model.to_hist()
with zfit.param.set_values([alpha] + list(modifiers.values()),
[0.] + list(np.random.normal(1.0, scale=0.14, size=len(modifiers)))):
data = bkg_pdf.sample(n=10_000).to_hist() + sig_pdf.sample(1000).to_hist()
data
modifier_constraints = zfit.constraint.GaussianConstraint(params=list(modifiers.values()), observation=np.ones(len(modifiers)),
uncertainty=np.ones(len(modifiers)))
# alpha_constraint = zfit.constraint.GaussianConstraint(alpha, 0, 1)
loss_binned = zfit.loss.ExtendedBinnedNLL(model, data, constraints=modifier_constraints)
result = minimizer.minimize(loss_binned)
print(result)
mplhep.histplot(model.to_hist(), label='model')
mplhep.histplot(data, label='data')
plt.legend()
print(sig_pdf.get_yield())
Binned to unbinned#
We can convert a histogram directly to an unbinned PDF with to_unbinned
or smooth it out by interpolating with splines.
unbinned_spline = zfit.pdf.SplinePDF(sig_pdf)
plt.plot(x, unbinned_spline.pdf(x))
mplhep.histplot(sig_pdf.to_hist(), density=True)
hepstats#
As before, we can now use hepstats to do further statistical treatment (supports binned PDFs).
More tutorials on hepstats can be found in the zfit guides or in the hepstats tutorials