FairShip
Loading...
Searching...
No Matches
EventHistogram Class Reference

#include <EventHistogram.h>

Public Member Functions

 EventHistogram (const char *name, const char *title, Int_t nbins, Double_t xlow, Double_t xup, Bool_t covariance=kFALSE, Int_t nReplicas=0)
 EventHistogram (const char *name, const char *title, Int_t nbins, const Double_t *edges, Bool_t covariance=kFALSE, Int_t nReplicas=0)
 ~EventHistogram ()
 EventHistogram (const EventHistogram &)=delete
EventHistogram & operator= (const EventHistogram &)=delete
void Fill (Double_t x, Double_t w=1.)
 Add one branch of the current event.
void EndEvent (ULong64_t eventKey=0)
void AddEmptyEvents (Long64_t n)
 Generated events that left no entry still count in the normalisation.
void Add (const EventHistogram &other)
Long64_t GetNEvents () const
Bool_t HasOpenEvent () const
TH1D * MakeResult (const char *name=nullptr) const
 Contents per generated event with event-level errors.
TH1D * MakeNaive (const char *name=nullptr) const
 Same contents with sqrt(sum w^2)/N errors, for comparison only.
TH1D * MakeNeff (const char *name=nullptr) const
TMatrixDSym GetCovariance () const
std::vector< Double_t > GetBootstrapErrors () const
void Write (TDirectory *dir=gDirectory) const

Static Public Member Functions

static std::unique_ptr< EventHistogram > Read (TDirectory *dir, const char *name)
static ULong64_t MakeEventKey (ULong64_t run, ULong64_t event)
static Int_t ReplicaWeight (ULong64_t key, Int_t replica)

Private Member Functions

 EventHistogram ()=default
void Init (Bool_t covariance, Int_t nReplicas)
void InitEventBuffers ()
void CheckClosed (const char *where) const
TH1D * MakePerEvent (const char *name, const char *suffix) const

Private Attributes

std::unique_ptr< TH1D > fSum
 contents sum t, sumw2 sum t^2
std::unique_ptr< TH1D > fNaive
 contents sum w, sumw2 sum w^2
std::unique_ptr< TH2D > fCov
 optional: sum t_a t_b
std::unique_ptr< TH2D > fBoot
 optional: (bin, replica) sum r t
std::vector< Double_t > fCurrent
 t_b of the open event, incl. flows
std::vector< Int_t > fTouched
 bins filled in the open event
std::vector< bool > fIsTouched
 per bin: listed in fTouched
Long64_t fNEvents = 0

Detailed Description

Histogram with event-level uncertainties for weighted samples whose entries are correlated within an event, such as the split kaon/pion clones of exitHadronAbsorber.

Every branch of an event (clones, split decays, their secondaries) shares the history of the primary interaction, so the branches are not independent entries and sqrt(sum w^2) underestimates the error. The independent unit is the event: the weights of an event are summed per bin first,

t_eb = sum_{i in e, x_i in b} w_i,

and the per-event sums are treated as the observations. With N generated events (including those that left no entry), the bin content per event and its error are

mu_b = sum_e t_eb / N, sigma_b^2 = (sum_e t_eb^2 / N - mu_b^2) / (N - 1).

Usage:

EventHistogram h("p_mu", "muon momentum;p (GeV/c)", 40, 0., 400.); for each event: for each muon: h.Fill(p, w); h.EndEvent(EventHistogram::MakeEventKey(run, event)); h.AddEmptyEvents(nGenerated - nWritten); std::unique_ptr<TH1D> result(h.MakeResult());

Write() stores plain ROOT objects that hadd merges correctly: a TH1D whose contents are sum_e t_eb and whose sum of squared weights is sum_e t_eb^2, the same for sqrt(sum w^2) for comparison, optional covariance and bootstrap accumulators, and the number of events. Read() restores the accumulator from them.

Definition at line 50 of file EventHistogram.h.

Constructor & Destructor Documentation

◆ EventHistogram() [1/4]

EventHistogram::EventHistogram ( const char * name,
const char * title,
Int_t nbins,
Double_t xlow,
Double_t xup,
Bool_t covariance = kFALSE,
Int_t nReplicas = 0 )
Parameters
covariancealso accumulate sum_e t_ea t_eb for the covariance
nReplicasnumber of Poisson bootstrap replicas (0 = none)

Definition at line 48 of file EventHistogram.cxx.

51 : fSum(new TH1D(name, title, nbins, xlow, xup)) {
52 Init(covariance, nReplicas);
53}
void Init(Bool_t covariance, Int_t nReplicas)
std::unique_ptr< TH1D > fSum
contents sum t, sumw2 sum t^2

◆ EventHistogram() [2/4]

EventHistogram::EventHistogram ( const char * name,
const char * title,
Int_t nbins,
const Double_t * edges,
Bool_t covariance = kFALSE,
Int_t nReplicas = 0 )

Definition at line 55 of file EventHistogram.cxx.

58 : fSum(new TH1D(name, title, nbins, edges)) {
59 Init(covariance, nReplicas);
60}

◆ ~EventHistogram()

EventHistogram::~EventHistogram ( )
default

◆ EventHistogram() [3/4]

EventHistogram::EventHistogram ( const EventHistogram & )
delete

◆ EventHistogram() [4/4]

EventHistogram::EventHistogram ( )
privatedefault

Member Function Documentation

◆ Add()

void EventHistogram::Add ( const EventHistogram & other)

Merge an accumulator filled with independent events and equal binning. Throws std::invalid_argument if binning, covariance or number of replicas differ; the target is then unchanged.

Definition at line 145 of file EventHistogram.cxx.

145 {
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}
std::unique_ptr< TH2D > fCov
optional: sum t_a t_b
std::unique_ptr< TH2D > fBoot
optional: (bin, replica) sum r t
std::unique_ptr< TH1D > fNaive
contents sum w, sumw2 sum w^2
void CheckClosed(const char *where) const

◆ AddEmptyEvents()

void EventHistogram::AddEmptyEvents ( Long64_t n)

Generated events that left no entry still count in the normalisation.

Definition at line 143 of file EventHistogram.cxx.

143{ fNEvents += n; }

◆ CheckClosed()

void EventHistogram::CheckClosed ( const char * where) const
private

Definition at line 169 of file EventHistogram.cxx.

169 {
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}
Bool_t HasOpenEvent() const

◆ EndEvent()

void EventHistogram::EndEvent ( ULong64_t eventKey = 0)

Close the current event. The key seeds the bootstrap replica weights; use MakeEventKey(run, event) so replicas agree across files and jobs.

Definition at line 104 of file EventHistogram.cxx.

104 {
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}
std::vector< bool > fIsTouched
per bin: listed in fTouched
static Int_t ReplicaWeight(ULong64_t key, Int_t replica)
std::vector< Double_t > fCurrent
t_b of the open event, incl. flows
std::vector< Int_t > fTouched
bins filled in the open event

◆ Fill()

void EventHistogram::Fill ( Double_t x,
Double_t w = 1. )

Add one branch of the current event.

Definition at line 93 of file EventHistogram.cxx.

93 {
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}

◆ GetBootstrapErrors()

std::vector< Double_t > EventHistogram::GetBootstrapErrors ( ) const

Spread of the bootstrap replicas, per generated event (in-range bins). Throws std::logic_error with fewer than two replicas.

Definition at line 247 of file EventHistogram.cxx.

247 {
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}

◆ GetCovariance()

TMatrixDSym EventHistogram::GetCovariance ( ) const

Covariance of the per-event bin contents (in-range bins only). Throws std::logic_error if created without covariance.

Definition at line 227 of file EventHistogram.cxx.

227 {
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}

◆ GetNEvents()

Long64_t EventHistogram::GetNEvents ( ) const
inline

Definition at line 77 of file EventHistogram.h.

77{ return fNEvents; }

◆ HasOpenEvent()

Bool_t EventHistogram::HasOpenEvent ( ) const
inline

Definition at line 78 of file EventHistogram.h.

78{ return !fTouched.empty(); }

◆ Init()

void EventHistogram::Init ( Bool_t covariance,
Int_t nReplicas )
private

Definition at line 64 of file EventHistogram.cxx.

64 {
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}

◆ InitEventBuffers()

void EventHistogram::InitEventBuffers ( )
private

Definition at line 88 of file EventHistogram.cxx.

88 {
89 fCurrent.assign(fSum->GetNbinsX() + 2, 0.);
90 fIsTouched.assign(fSum->GetNbinsX() + 2, false);
91}

◆ MakeEventKey()

ULong64_t EventHistogram::MakeEventKey ( ULong64_t run,
ULong64_t event )
inlinestatic

Definition at line 101 of file EventHistogram.h.

101 {
102 return (run << 32) ^ event;
103 }

◆ MakeNaive()

TH1D * EventHistogram::MakeNaive ( const char * name = nullptr) const

Same contents with sqrt(sum w^2)/N errors, for comparison only.

Definition at line 203 of file EventHistogram.cxx.

203 {
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}
TH1D * MakePerEvent(const char *name, const char *suffix) const

◆ MakeNeff()

TH1D * EventHistogram::MakeNeff ( const char * name = nullptr) const

Effective number of independent events per bin, (sum t)^2 / sum t^2. Below about 20 the error estimate itself becomes unreliable.

Definition at line 216 of file EventHistogram.cxx.

216 {
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}

◆ MakePerEvent()

TH1D * EventHistogram::MakePerEvent ( const char * name,
const char * suffix ) const
private

Definition at line 177 of file EventHistogram.cxx.

177 {
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}

◆ MakeResult()

TH1D * EventHistogram::MakeResult ( const char * name = nullptr) const

Contents per generated event with event-level errors.

Definition at line 186 of file EventHistogram.cxx.

186 {
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}

◆ operator=()

EventHistogram & EventHistogram::operator= ( const EventHistogram & )
delete

◆ Read()

std::unique_ptr< EventHistogram > EventHistogram::Read ( TDirectory * dir,
const char * name )
static

Definition at line 289 of file EventHistogram.cxx.

290 {
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}
EventHistogram()=default

◆ ReplicaWeight()

Int_t EventHistogram::ReplicaWeight ( ULong64_t key,
Int_t replica )
static

Poisson(1) replica weight, a pure function of key and replica so that the Python implementation (event_histogram.py) gives the same replicas.

Definition at line 323 of file EventHistogram.cxx.

323 {
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}

◆ Write()

void EventHistogram::Write ( TDirectory * dir = gDirectory) const

Writing or reading results with an open event throws std::logic_error. Read() returns nullptr if the objects are missing or hold different numbers of events, e.g. after hadd of files with different settings.

Definition at line 271 of file EventHistogram.cxx.

271 {
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}

Member Data Documentation

◆ fBoot

std::unique_ptr<TH2D> EventHistogram::fBoot
private

optional: (bin, replica) sum r t

Definition at line 118 of file EventHistogram.h.

◆ fCov

std::unique_ptr<TH2D> EventHistogram::fCov
private

optional: sum t_a t_b

Definition at line 117 of file EventHistogram.h.

◆ fCurrent

std::vector<Double_t> EventHistogram::fCurrent
private

t_b of the open event, incl. flows

Definition at line 119 of file EventHistogram.h.

◆ fIsTouched

std::vector<bool> EventHistogram::fIsTouched
private

per bin: listed in fTouched

Definition at line 121 of file EventHistogram.h.

◆ fNaive

std::unique_ptr<TH1D> EventHistogram::fNaive
private

contents sum w, sumw2 sum w^2

Definition at line 116 of file EventHistogram.h.

◆ fNEvents

Long64_t EventHistogram::fNEvents = 0
private

Definition at line 122 of file EventHistogram.h.

◆ fSum

std::unique_ptr<TH1D> EventHistogram::fSum
private

contents sum t, sumw2 sum t^2

Definition at line 115 of file EventHistogram.h.

◆ fTouched

std::vector<Int_t> EventHistogram::fTouched
private

bins filled in the open event

Definition at line 120 of file EventHistogram.h.


The documentation for this class was generated from the following files: