FairShip
Loading...
Searching...
No Matches
event_histogram.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
3
4"""Histograms with event-level uncertainties for samples with split branches.
5
6All branches of an event (split kaon/pion clones, their decay products and
7secondaries) share the history of the primary interaction, so they are not
8independent entries and sqrt(sum w^2) underestimates the error, by a large
9factor when many clones of one decay land in the same bin. The independent unit
10is the event: sum the weights of an event per bin first,
11
12 t_eb = sum_{i in e, x_i in b} w_i,
13
14and treat the per-event sums as the observations. With N generated events,
15including the ones that left no entry,
16
17 mu_b = sum_e t_eb / N, sigma_b^2 = (sum_e t_eb^2 / N - mu_b^2) / (N - 1).
18
19This is the numpy counterpart of the C++ class EventHistogram (libShipData).
20Both write the same ROOT objects, which hadd merges correctly, and give the same
21bootstrap replicas for the same event keys::
22
23 h = EventHistogram("p_mu", np.geomspace(5, 400, 21), covariance=True)
24 for event in tree:
25 h.fill(momenta, weights)
26 h.end_event(make_event_key(run, event_id))
27 h.add_empty_events(n_generated - h.n_events)
28 h.values(), h.errors(), h.n_eff()
29"""
30
31import json
32import math
33
34import numpy as np
35
36_MASK64 = (1 << 64) - 1
37
38
39def make_event_key(run: int, event: int) -> int:
40 """Key of an event for the bootstrap replicas, as EventHistogram::MakeEventKey."""
41 return ((run << 32) ^ event) & _MASK64
42
43
45 """Poisson(1) distribution function, accumulated as in the C++ code.
46
47 k = 0..19, so searchsorted caps the weight at 20 like the C++ inversion.
48 """
49 p = math.exp(-1.0)
50 cdf = [p]
51 for k in range(1, 20):
52 p /= k
53 cdf.append(cdf[-1] + p)
54 return np.array(cdf)
55
56
58
59
60def replica_weights(key: int, n_replicas: int) -> np.ndarray:
61 """Poisson(1) weights of one event for replicas 0..n-1 (EventHistogram::ReplicaWeight)."""
62 r = np.arange(1, n_replicas + 1, dtype=np.uint64)
63 with np.errstate(over="ignore"):
64 x = np.uint64(key & _MASK64) ^ (r * np.uint64(0xD1B54A32D192ED03))
65 x = x + np.uint64(0x9E3779B97F4A7C15)
66 x = (x ^ (x >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
67 x = (x ^ (x >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
68 x = x ^ (x >> np.uint64(31))
69 u = (x >> np.uint64(11)).astype(np.float64) * 2.0**-53
70 return np.searchsorted(_CDF, u, side="left")
71
72
73def _buffer(array, n):
74 array.reshape((n,))
75 return np.frombuffer(array, dtype=np.float64, count=n)
76
77
78def _cells(h):
79 """Writable view of the bin contents of a ROOT histogram, flows included."""
80 return _buffer(h.GetArray(), h.GetNcells())
81
82
83def _sumw2(h):
84 return _buffer(h.GetSumw2().GetArray(), h.GetNcells())
85
86
87def _inner2(h):
88 """In-range contents of a TH2D as a writable [x bin, y bin] view."""
89 ny, nx = h.GetNbinsY(), h.GetNbinsX()
90 return _cells(h).reshape(ny + 2, nx + 2)[1:-1, 1:-1].T
91
92
94 """Accumulate per-event bin sums; see the module docstring.
95
96 Arrays returned by the accessors cover the in-range bins. Under- and
97 overflow are kept internally (index 0 and nbins + 1) as in ROOT.
98 """
99
100 def __init__(self, name, edges, title="", covariance=False, n_replicas=0):
101 self.name = name
102 self.title = title
103 self.edges = np.asarray(edges, dtype=float)
104 nb = self.nbins
105 self.n_events = 0
106 self.sum_t = np.zeros(nb + 2)
107 self.sum_t2 = np.zeros(nb + 2)
108 self.sum_w = np.zeros(nb + 2)
109 self.sum_w2 = np.zeros(nb + 2)
110 self.sum_tt = np.zeros((nb, nb)) if covariance else None
111 self.boot = np.zeros((nb, n_replicas)) if n_replicas else None
112 self._current = np.zeros(nb + 2)
113 self._open = False
114
115 @property
116 def nbins(self):
117 return len(self.edges) - 1
118
119 def _bins(self, x):
120 # ROOT convention: bin i covers [low_i, high_i), the upper edge is overflow.
121 return np.searchsorted(self.edges, x, side="right")
122
123 def fill(self, x, w=1.0):
124 """Add branches (scalars or arrays) of the current event."""
125 x = np.asarray(x, dtype=float)
126 if x.size == 0:
127 return
128 w = np.broadcast_to(np.asarray(w, dtype=float), x.shape).ravel()
129 bins = self._bins(x.ravel())
130 t = np.bincount(bins, w, minlength=len(self._current))
131 self._current += t
132 self.sum_w += t
133 self.sum_w2 += np.bincount(bins, w * w, minlength=len(self._current))
134 self._open = True
135
136 def end_event(self, key=0):
137 """Close the current event. Use make_event_key(run, event) as key so the
138 bootstrap replicas agree across files, jobs and the C++ class."""
139 # Only the bins this event touched, as in the C++ class.
140 idx = np.flatnonzero(self._current)
141 t = self._current[idx]
142 self.sum_t[idx] += t
143 self.sum_t2[idx] += t * t
144 inner = (idx >= 1) & (idx <= self.nbins)
145 ii, ti = idx[inner] - 1, t[inner]
146 if self.sum_tt is not None:
147 self.sum_tt[np.ix_(ii, ii)] += np.outer(ti, ti)
148 if self.boot is not None and ii.size:
149 self.boot[ii] += ti[:, None] * replica_weights(key, self.boot.shape[1])[None, :]
150 self._current[idx] = 0.0
151 self._open = False
152 self.n_events += 1
153
154 def fill_event(self, x, w=1.0, key=0):
155 self.fill(x, w)
156 self.end_event(key)
157
158 def add_empty_events(self, n):
159 """Generated events that left no entry still count in the normalisation."""
160 self.n_events += int(n)
161
162 def __iadd__(self, other):
163 self._check_closed("merge")
164 other._check_closed("merge")
165 if not np.array_equal(self.edges, other.edges):
166 raise ValueError("EventHistogram: binning differs, cannot merge")
167 if (self.sum_tt is None) != (other.sum_tt is None):
168 raise ValueError("EventHistogram: only one has a covariance, cannot merge")
169 if (self.boot is None) != (other.boot is None) or (
170 self.boot is not None and self.boot.shape != other.boot.shape
171 ):
172 raise ValueError("EventHistogram: bootstrap replicas differ, cannot merge")
173 for attr in ("sum_t", "sum_t2", "sum_w", "sum_w2", "sum_tt", "boot"):
174 mine = getattr(self, attr)
175 if mine is not None:
176 mine += getattr(other, attr)
177 self.n_events += other.n_events
178 return self
179
180 def _check_closed(self, where):
181 if self._open:
182 raise RuntimeError(f"EventHistogram.{where}: call end_event() first")
183
184 # --- results, per generated event, in-range bins ---------------------------
185
186 def _per_event(self, sums):
187 """In-range sums divided by the number of events, zero without events."""
188 if self.n_events <= 0:
189 return np.zeros(self.nbins)
190 return sums[1:-1] / self.n_events
191
192 def values(self):
193 self._check_closed("values")
194 return self._per_event(self.sum_t)
195
196 def errors(self):
197 """Event-level standard errors."""
198 self._check_closed("errors")
199 n = self.n_events
200 m2 = self._per_event(self.sum_t2)
201 if n < 2:
202 # No spread to estimate from: sqrt(sum t^2) / N, zero without events.
203 return np.sqrt(m2)
204 m = self._per_event(self.sum_t)
205 return np.sqrt(np.maximum(m2 - m * m, 0.0) / (n - 1))
206
207 def naive_errors(self):
208 """sqrt(sum w^2)/N, which treats branches as independent. For comparison only."""
209 self._check_closed("naive_errors")
210 return self._per_event(np.sqrt(self.sum_w2))
211
212 def n_eff(self):
213 """Independent events per bin, (sum t)^2 / sum t^2. Below about 20 the error
214 estimate itself is unreliable: merge bins or check with the bootstrap."""
215 self._check_closed("n_eff")
216 s, s2 = self.sum_t[1:-1], self.sum_t2[1:-1]
217 with np.errstate(invalid="ignore", divide="ignore"):
218 return np.where(s2 > 0, s * s / s2, 0.0)
219
220 def covariance(self):
221 self._check_closed("covariance")
222 if self.sum_tt is None:
223 raise ValueError("EventHistogram: created without covariance=True")
224 n = self.n_events
225 if n < 2:
226 return np.zeros((self.nbins, self.nbins))
227 m = self.sum_t[1:-1] / n
228 return (self.sum_tt / n - np.outer(m, m)) / (n - 1)
229
231 self._check_closed("bootstrap_errors")
232 if self.boot is None or self.boot.shape[1] < 2:
233 raise ValueError("EventHistogram: needs at least two bootstrap replicas")
234 if self.n_events <= 0:
235 return np.zeros(self.nbins)
236 return (self.boot / self.n_events).std(axis=1, ddof=1)
237
238 # --- ROOT I/O, same objects as EventHistogram::Write/Read -----------------
239
240 def to_root(self, directory):
241 """Write hadd-mergeable objects, identical to the C++ EventHistogram::Write."""
242 import ROOT
243
244 self._check_closed("to_root")
245 edges = np.ascontiguousarray(self.edges)
246 nb = self.nbins
247
248 def hist1(name, sums, sums2):
249 h = ROOT.TH1D(name, self.title, nb, edges)
250 h.SetDirectory(ROOT.nullptr)
251 h.Sumw2()
252 _cells(h)[:] = sums
253 _sumw2(h)[:] = sums2
254 h.SetEntries(self.n_events)
255 return h
256
257 def hist2(name, title, values, *yaxis):
258 h = ROOT.TH2D(name, title, nb, edges, *yaxis)
259 h.SetDirectory(ROOT.nullptr)
260 _inner2(h)[:] = values
261 h.SetEntries(self.n_events)
262 return h
263
264 objects: list = [
265 hist1(self.name, self.sum_t, self.sum_t2),
266 hist1(self.name + "_naive", self.sum_w, self.sum_w2),
267 ]
268 if self.sum_tt is not None:
269 objects.append(hist2(self.name + "_cov", "sum over events of t_a t_b", self.sum_tt, nb, edges))
270 if self.boot is not None:
271 nrep = self.boot.shape[1]
272 objects.append(hist2(self.name + "_boot", "bootstrap replicas;;replica", self.boot, nrep, 0.0, float(nrep)))
273 objects.append(ROOT.TParameter("Long64_t")(self.name + "_nevents", self.n_events, "+"))
274 for obj in objects:
275 directory.WriteTObject(obj, obj.GetName(), "Overwrite")
276
277 @classmethod
278 def from_root(cls, directory, name):
279 """Restore an accumulator written by to_root() or the C++ class (also after hadd)."""
280 h = directory.Get(name)
281 naive = directory.Get(name + "_naive")
282 nevents = directory.Get(name + "_nevents")
283 if not h or not naive or not nevents:
284 raise KeyError(f"EventHistogram {name} not found in {directory.GetName()}")
285 axis = h.GetXaxis()
286 nb = axis.GetNbins()
287 edges = [axis.GetBinLowEdge(i) for i in range(1, nb + 2)]
288 cov = directory.Get(name + "_cov")
289 boot = directory.Get(name + "_boot")
290 n_events = nevents.GetVal()
291 for obj in (h, naive, cov, boot):
292 if obj and obj.GetEntries() != n_events:
293 raise ValueError(
294 f"EventHistogram {name}: {obj.GetName()} holds {obj.GetEntries()} events,"
295 f" {nevents.GetName()} {n_events}; were files with different settings merged?"
296 )
297 self = cls(name, edges, title=h.GetTitle(), covariance=bool(cov), n_replicas=boot.GetNbinsY() if boot else 0)
298 self.sum_t[:], self.sum_t2[:] = _cells(h), _sumw2(h)
299 self.sum_w[:], self.sum_w2[:] = _cells(naive), _sumw2(naive)
300 if self.sum_tt is not None:
301 self.sum_tt[:] = _inner2(cov)
302 if self.boot is not None:
303 self.boot[:] = _inner2(boot)
304 self.n_events = int(n_events)
305 return self
306
307
308def generated_events(tfile) -> int:
309 """Number of generated events of a FairShip output file, from its FileSummary.
310
311 FairShip only writes events with activity, so the number of entries of the
312 tree is not the normalisation.
313 """
314 summary = tfile.Get("FileSummary")
315 if not summary:
316 raise KeyError(f"{tfile.GetName()} has no FileSummary")
317 fsr = json.loads(str(summary))
318 for key in ("nev", "nEvents"):
319 if key in fsr:
320 return int(fsr[key])
321 raise KeyError(f"FileSummary of {tfile.GetName()} has no event count ('nev' or 'nEvents')")
__init__(self, name, edges, title="", covariance=False, n_replicas=0)
fill_event(self, x, w=1.0, key=0)
from_root(cls, directory, name)
int generated_events(tfile)
int make_event_key(int run, int event)
np.ndarray replica_weights(int key, int n_replicas)