FairShip
Loading...
Searching...
No Matches
EventHistogram.cxx
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
3// Collaboration
4
5#include "EventHistogram.h"
6
7#include <algorithm>
8#include <cmath>
9#include <stdexcept>
10#include <string>
11
12#include "FairLogger.h"
13#include "TArrayD.h"
14#include "TAxis.h"
15#include "TParameter.h"
16
17namespace {
18
19std::vector<Double_t> AxisEdges(const TAxis* axis) {
20 std::vector<Double_t> edges;
21 for (Int_t i = 1; i <= axis->GetNbins(); ++i) {
22 edges.push_back(axis->GetBinLowEdge(i));
23 }
24 edges.push_back(axis->GetBinUpEdge(axis->GetNbins()));
25 return edges;
26}
27
28std::string Suffixed(const char* name, const char* suffix) {
29 return std::string(name) + suffix;
30}
31
32template <class T>
33std::unique_ptr<T> DetachedClone(const T* h) {
34 std::unique_ptr<T> clone(static_cast<T*>(h->Clone()));
35 clone->SetDirectory(nullptr);
36 return clone;
37}
38
39ULong64_t SplitMix64(ULong64_t x) {
40 x += 0x9E3779B97F4A7C15ULL;
41 x = (x ^ (x >> 30U)) * 0xBF58476D1CE4E5B9ULL;
42 x = (x ^ (x >> 27U)) * 0x94D049BB133111EBULL;
43 return x ^ (x >> 31U);
44}
45
46} // namespace
47
48EventHistogram::EventHistogram(const char* name, const char* title, Int_t nbins,
49 Double_t xlow, Double_t xup, Bool_t covariance,
50 Int_t nReplicas)
51 : fSum(new TH1D(name, title, nbins, xlow, xup)) {
52 Init(covariance, nReplicas);
53}
54
55EventHistogram::EventHistogram(const char* name, const char* title, Int_t nbins,
56 const Double_t* edges, Bool_t covariance,
57 Int_t nReplicas)
58 : fSum(new TH1D(name, title, nbins, edges)) {
59 Init(covariance, nReplicas);
60}
61
63
64void EventHistogram::Init(Bool_t covariance, Int_t nReplicas) {
65 fSum->SetDirectory(nullptr);
66 fSum->Sumw2();
67 const std::string name = fSum->GetName();
68 fNaive.reset(dynamic_cast<TH1D*>(
69 fSum->Clone(Suffixed(name.c_str(), "_naive").c_str())));
70 fNaive->SetDirectory(nullptr);
71 const Int_t nbins = fSum->GetNbinsX();
72 const std::vector<Double_t> edges = AxisEdges(fSum->GetXaxis());
73 if (covariance) {
74 fCov = std::make_unique<TH2D>(Suffixed(name.c_str(), "_cov").c_str(),
75 "sum over events of t_a t_b", nbins,
76 edges.data(), nbins, edges.data());
77 fCov->SetDirectory(nullptr);
78 }
79 if (nReplicas > 0) {
80 fBoot = std::make_unique<TH2D>(Suffixed(name.c_str(), "_boot").c_str(),
81 "bootstrap replicas;;replica", nbins,
82 edges.data(), nReplicas, 0., nReplicas);
83 fBoot->SetDirectory(nullptr);
84 }
86}
87
89 fCurrent.assign(fSum->GetNbinsX() + 2, 0.);
90 fIsTouched.assign(fSum->GetNbinsX() + 2, false);
91}
92
93void EventHistogram::Fill(Double_t x, Double_t w) {
94 const Int_t bin = fSum->GetXaxis()->FindFixBin(x);
95 if (!fIsTouched[bin]) {
96 fIsTouched[bin] = true;
97 fTouched.push_back(bin);
98 }
99 fCurrent[bin] += w;
100 fNaive->AddBinContent(bin, w);
101 (*fNaive->GetSumw2())[bin] += w * w;
102}
103
104void EventHistogram::EndEvent(ULong64_t eventKey) {
105 TArrayD& sumw2 = *fSum->GetSumw2();
106 const Int_t nbins = fSum->GetNbinsX();
107 for (const Int_t b : fTouched) {
108 const Double_t t = fCurrent[b];
109 // AddBinContent leaves the sum of squared weights alone, so the per-event
110 // square is added by hand: this is what makes the stored error per event.
111 fSum->AddBinContent(b, t);
112 sumw2[b] += t * t;
113 }
114 // Covariance and bootstrap cover the in-range bins, moved to the front.
115 const auto begin = fTouched.begin();
116 const auto end =
117 std::partition(fTouched.begin(), fTouched.end(),
118 [nbins](Int_t b) { return b >= 1 && b <= nbins; });
119 if (fCov) {
120 for (auto a = begin; a != end; ++a) {
121 for (auto b = begin; b != end; ++b) {
122 fCov->AddBinContent(fCov->GetBin(*a, *b), fCurrent[*a] * fCurrent[*b]);
123 }
124 }
125 }
126 if (fBoot && begin != end) {
127 for (Int_t r = 0; r < fBoot->GetNbinsY(); ++r) {
128 const Int_t k = ReplicaWeight(eventKey, r);
129 if (k == 0) continue;
130 for (auto b = begin; b != end; ++b) {
131 fBoot->AddBinContent(fBoot->GetBin(*b, r + 1), k * fCurrent[*b]);
132 }
133 }
134 }
135 for (const Int_t b : fTouched) {
136 fCurrent[b] = 0.;
137 fIsTouched[b] = false;
138 }
139 fTouched.clear();
140 ++fNEvents;
141}
142
143void EventHistogram::AddEmptyEvents(Long64_t n) { fNEvents += n; }
144
146 CheckClosed("Add");
147 other.CheckClosed("Add");
148 const char* problem = nullptr;
149 if (AxisEdges(other.fSum->GetXaxis()) != AxisEdges(fSum->GetXaxis())) {
150 problem = "binning";
151 } else if (!fCov != !other.fCov) {
152 problem = "covariance";
153 } else if (!fBoot != !other.fBoot ||
154 (fBoot && fBoot->GetNbinsY() != other.fBoot->GetNbinsY())) {
155 problem = "number of bootstrap replicas";
156 }
157 if (problem) {
158 throw std::invalid_argument(std::string("EventHistogram::Add: ") + problem +
159 " of " + other.fSum->GetName() +
160 " differs from " + fSum->GetName());
161 }
162 fSum->Add(other.fSum.get());
163 fNaive->Add(other.fNaive.get());
164 if (fCov) fCov->Add(other.fCov.get());
165 if (fBoot) fBoot->Add(other.fBoot.get());
166 fNEvents += other.fNEvents;
167}
168
169void EventHistogram::CheckClosed(const char* where) const {
170 if (HasOpenEvent()) {
171 throw std::logic_error(std::string("EventHistogram::") + where + " on " +
172 fSum->GetName() +
173 " with an open event; call EndEvent() first");
174 }
175}
176
177TH1D* EventHistogram::MakePerEvent(const char* name, const char* suffix) const {
178 const std::string newName =
179 name ? std::string(name) : Suffixed(fSum->GetName(), suffix);
180 auto* h = dynamic_cast<TH1D*>(fSum->Clone(newName.c_str()));
181 h->SetDirectory(nullptr);
182 h->Reset();
183 return h;
184}
185
186TH1D* EventHistogram::MakeResult(const char* name) const {
187 CheckClosed("MakeResult");
188 TH1D* h = MakePerEvent(name, "_result");
189 if (fNEvents <= 0) return h;
190 const Double_t n = fNEvents;
191 const TArrayD& sumw2 = *fSum->GetSumw2();
192 for (Int_t b = 0; b <= fSum->GetNbinsX() + 1; ++b) {
193 const Double_t mean = fSum->GetBinContent(b) / n;
194 const Double_t var =
195 n > 1 ? (sumw2[b] / n - mean * mean) / (n - 1) : sumw2[b] / (n * n);
196 h->SetBinContent(b, mean);
197 h->SetBinError(b, std::sqrt(std::max(var, 0.)));
198 }
199 h->SetEntries(fNEvents);
200 return h;
201}
202
203TH1D* EventHistogram::MakeNaive(const char* name) const {
204 CheckClosed("MakeNaive");
205 TH1D* h = MakePerEvent(name, "_naive_result");
206 if (fNEvents <= 0) return h;
207 const Double_t n = fNEvents;
208 const TArrayD& sumw2 = *fNaive->GetSumw2();
209 for (Int_t b = 0; b <= fSum->GetNbinsX() + 1; ++b) {
210 h->SetBinContent(b, fNaive->GetBinContent(b) / n);
211 h->SetBinError(b, std::sqrt(sumw2[b]) / n);
212 }
213 return h;
214}
215
216TH1D* EventHistogram::MakeNeff(const char* name) const {
217 CheckClosed("MakeNeff");
218 TH1D* h = MakePerEvent(name, "_neff");
219 const TArrayD& sumw2 = *fSum->GetSumw2();
220 for (Int_t b = 0; b <= fSum->GetNbinsX() + 1; ++b) {
221 const Double_t s = fSum->GetBinContent(b);
222 h->SetBinContent(b, sumw2[b] > 0 ? s * s / sumw2[b] : 0.);
223 }
224 return h;
225}
226
227TMatrixDSym EventHistogram::GetCovariance() const {
228 CheckClosed("GetCovariance");
229 const Int_t nbins = fSum->GetNbinsX();
230 TMatrixDSym cov(nbins);
231 if (!fCov) {
232 throw std::logic_error(std::string("EventHistogram ") + fSum->GetName() +
233 " was created without covariance");
234 }
235 const Double_t n = fNEvents;
236 if (n < 2) return cov;
237 for (Int_t a = 1; a <= nbins; ++a) {
238 for (Int_t b = 1; b <= nbins; ++b) {
239 const Double_t ma = fSum->GetBinContent(a) / n;
240 const Double_t mb = fSum->GetBinContent(b) / n;
241 cov(a - 1, b - 1) = (fCov->GetBinContent(a, b) / n - ma * mb) / (n - 1);
242 }
243 }
244 return cov;
245}
246
247std::vector<Double_t> EventHistogram::GetBootstrapErrors() const {
248 CheckClosed("GetBootstrapErrors");
249 const Int_t nbins = fSum->GetNbinsX();
250 std::vector<Double_t> errors(nbins, 0.);
251 if (!fBoot || fBoot->GetNbinsY() < 2) {
252 throw std::logic_error(std::string("EventHistogram ") + fSum->GetName() +
253 " has fewer than two bootstrap replicas");
254 }
255 if (fNEvents <= 0) return errors;
256 const Int_t nrep = fBoot->GetNbinsY();
257 for (Int_t b = 1; b <= nbins; ++b) {
258 Double_t sum = 0., sum2 = 0.;
259 for (Int_t r = 1; r <= nrep; ++r) {
260 const Double_t v = fBoot->GetBinContent(b, r) / fNEvents;
261 sum += v;
262 sum2 += v * v;
263 }
264 const Double_t mean = sum / nrep;
265 errors[b - 1] =
266 std::sqrt(std::max((sum2 - nrep * mean * mean) / (nrep - 1), 0.));
267 }
268 return errors;
269}
270
271void EventHistogram::Write(TDirectory* dir) const {
272 CheckClosed("Write");
273 // Every object carries the number of events it holds. hadd adds them up, so
274 // Read() can tell when files with different contents were merged.
275 for (TH1* h :
276 {static_cast<TH1*>(fSum.get()), static_cast<TH1*>(fNaive.get()),
277 static_cast<TH1*>(fCov.get()), static_cast<TH1*>(fBoot.get())}) {
278 if (h) h->SetEntries(fNEvents);
279 }
280 dir->WriteTObject(fSum.get(), fSum->GetName(), "Overwrite");
281 dir->WriteTObject(fNaive.get(), fNaive->GetName(), "Overwrite");
282 if (fCov) dir->WriteTObject(fCov.get(), fCov->GetName(), "Overwrite");
283 if (fBoot) dir->WriteTObject(fBoot.get(), fBoot->GetName(), "Overwrite");
284 const std::string key = Suffixed(fSum->GetName(), "_nevents");
285 TParameter<Long64_t> nevents(key.c_str(), fNEvents, '+');
286 dir->WriteTObject(&nevents, key.c_str(), "Overwrite");
287}
288
289std::unique_ptr<EventHistogram> EventHistogram::Read(TDirectory* dir,
290 const char* name) {
291 auto* sum = dir->Get<TH1D>(name);
292 auto* naive = dir->Get<TH1D>(Suffixed(name, "_naive").c_str());
293 auto* nevents =
294 dir->Get<TParameter<Long64_t>>(Suffixed(name, "_nevents").c_str());
295 if (!sum || !naive || !nevents) {
296 LOG(error) << "EventHistogram::Read: " << name << " not found in "
297 << dir->GetName();
298 return nullptr;
299 }
300 auto* cov = dir->Get<TH2D>(Suffixed(name, "_cov").c_str());
301 auto* boot = dir->Get<TH2D>(Suffixed(name, "_boot").c_str());
302 for (const TH1* obj :
303 {static_cast<const TH1*>(sum), static_cast<const TH1*>(naive),
304 static_cast<const TH1*>(cov), static_cast<const TH1*>(boot)}) {
305 if (obj && obj->GetEntries() != nevents->GetVal()) {
306 LOG(error) << "EventHistogram::Read: " << obj->GetName() << " holds "
307 << obj->GetEntries() << " events, " << nevents->GetName()
308 << " " << nevents->GetVal()
309 << "; were files with different settings merged?";
310 return nullptr;
311 }
312 }
313 std::unique_ptr<EventHistogram> h(new EventHistogram());
314 h->fSum = DetachedClone(sum);
315 h->fNaive = DetachedClone(naive);
316 if (cov) h->fCov = DetachedClone(cov);
317 if (boot) h->fBoot = DetachedClone(boot);
318 h->fNEvents = nevents->GetVal();
319 h->InitEventBuffers();
320 return h;
321}
322
323Int_t EventHistogram::ReplicaWeight(ULong64_t key, Int_t replica) {
324 const ULong64_t x = SplitMix64(
325 key ^ (static_cast<ULong64_t>(replica + 1) * 0xD1B54A32D192ED03ULL));
326 const Double_t u = static_cast<Double_t>(x >> 11U) * 0x1.0p-53;
327 // Inversion of the Poisson(1) distribution function.
328 static const Double_t p0 = std::exp(-1.);
329 Double_t p = p0;
330 Double_t cdf = p;
331 Int_t k = 0;
332 while (u > cdf && k < 20) {
333 ++k;
334 p /= k;
335 cdf += p;
336 }
337 return k;
338}
std::vector< bool > fIsTouched
per bin: listed in fTouched
TH1D * MakeNeff(const char *name=nullptr) const
EventHistogram()=default
void Fill(Double_t x, Double_t w=1.)
Add one branch of the current event.
std::unique_ptr< TH2D > fCov
optional: sum t_a t_b
TH1D * MakePerEvent(const char *name, const char *suffix) const
void Init(Bool_t covariance, Int_t nReplicas)
static std::unique_ptr< EventHistogram > Read(TDirectory *dir, const char *name)
static Int_t ReplicaWeight(ULong64_t key, Int_t replica)
TH1D * MakeResult(const char *name=nullptr) const
Contents per generated event with event-level errors.
std::unique_ptr< TH1D > fSum
contents sum t, sumw2 sum t^2
void AddEmptyEvents(Long64_t n)
Generated events that left no entry still count in the normalisation.
std::unique_ptr< TH2D > fBoot
optional: (bin, replica) sum r t
EventHistogram(const char *name, const char *title, Int_t nbins, Double_t xlow, Double_t xup, Bool_t covariance=kFALSE, Int_t nReplicas=0)
void EndEvent(ULong64_t eventKey=0)
void Add(const EventHistogram &other)
std::vector< Double_t > fCurrent
t_b of the open event, incl. flows
TH1D * MakeNaive(const char *name=nullptr) const
Same contents with sqrt(sum w^2)/N errors, for comparison only.
std::unique_ptr< TH1D > fNaive
contents sum w, sumw2 sum w^2
Bool_t HasOpenEvent() const
void CheckClosed(const char *where) const
TMatrixDSym GetCovariance() const
std::vector< Double_t > GetBootstrapErrors() const
std::vector< Int_t > fTouched
bins filled in the open event
void Write(TDirectory *dir=gDirectory) const
int i
Definition ShipAna.py:108