FairShip
Loading...
Searching...
No Matches
test_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
4import numpy as np
5import pytest
6from event_histogram import EventHistogram, make_event_key, replica_weights
7
8EDGES = np.linspace(0.0, 10.0, 11)
9
10
11def correlated_sample(seed, n_events, p_active=0.3, n_clones=20):
12 """Events with n_clones branches of weight 1/n_clones around a common x."""
13 rng = np.random.default_rng(seed)
14 events: list[tuple[np.ndarray, np.ndarray] | None] = []
15 for _ in range(n_events):
16 if rng.random() < p_active:
17 x0 = rng.uniform(0.0, 10.0)
18 events.append((x0 + rng.normal(0.0, 0.3, n_clones), np.full(n_clones, 1.0 / n_clones)))
19 else:
20 events.append(None)
21 return events
22
23
24def fill(h, events, run=1):
25 for i, ev in enumerate(events):
26 if ev is None:
27 h.add_empty_events(1)
28 else:
29 h.fill_event(*ev, key=make_event_key(run, i))
30
31
32def fill_cpp(h, events, run=1):
33 for i, ev in enumerate(events):
34 if ev is None:
35 h.AddEmptyEvents(1)
36 continue
37 for x, w in zip(*ev):
38 h.Fill(x, w)
39 h.EndEvent(make_event_key(run, i))
40
41
43 events = correlated_sample(1, 3000)
44 h = EventHistogram("x", EDGES)
45 fill(h, events)
46 t = np.zeros((len(events), len(EDGES) - 1))
47 for i, ev in enumerate(events):
48 if ev is not None:
49 t[i] = np.histogram(ev[0], EDGES, weights=ev[1])[0]
50 n = len(events)
51 assert h.n_events == n
52 assert h.values() == pytest.approx(t.sum(0) / n)
53 assert h.errors() == pytest.approx(t.std(0, ddof=1) / np.sqrt(n))
54
55
57 h = EventHistogram("x", EDGES)
58 fill(h, correlated_sample(2, 3000))
59 assert np.all(h.errors() / h.naive_errors() > 2.0)
60 assert np.all(h.n_eff() < 3000)
61
62
64 a, b = correlated_sample(3, 1000), correlated_sample(4, 1500)
65 ha = EventHistogram("x", EDGES, covariance=True, n_replicas=50)
66 hb = EventHistogram("x", EDGES, covariance=True, n_replicas=50)
67 hab = EventHistogram("x", EDGES, covariance=True, n_replicas=50)
68 fill(ha, a, run=1)
69 fill(hb, b, run=2)
70 fill(hab, a, run=1)
71 fill(hab, b, run=2)
72 ha += hb
73 assert ha.n_events == hab.n_events
74 assert ha.errors() == pytest.approx(hab.errors())
75 assert ha.covariance() == pytest.approx(hab.covariance())
76 assert ha.bootstrap_errors() == pytest.approx(hab.bootstrap_errors())
77
78
79def state(h):
80 """Copy of the accumulators of h, which has a covariance and replicas."""
81 assert h.sum_tt is not None and h.boot is not None
82 return h.sum_t.copy(), h.sum_tt.copy(), h.boot.copy(), h.n_events
83
84
85@pytest.mark.parametrize(
86 "kwargs",
87 [{"covariance": False, "n_replicas": 50}, {"covariance": True, "n_replicas": 20}, {"covariance": True}],
88)
90 ha = EventHistogram("x", EDGES, covariance=True, n_replicas=50)
91 fill(ha, correlated_sample(5, 200))
92 before = state(ha)
93 hb = EventHistogram("x", EDGES, **kwargs)
94 fill(hb, correlated_sample(6, 200))
95 with pytest.raises(ValueError):
96 ha += hb
97 for x, y in zip(before, state(ha)):
98 assert np.array_equal(x, y)
99
100
102 ha, hb = EventHistogram("x", EDGES), EventHistogram("x", EDGES)
103 hb.fill(1.0)
104 with pytest.raises(RuntimeError):
105 ha += hb
106
107
109 h = EventHistogram("x", EDGES, covariance=True, n_replicas=10)
110 nb = len(EDGES) - 1
111 for result in (h.values(), h.errors(), h.naive_errors(), h.bootstrap_errors()):
112 assert np.array_equal(result, np.zeros(nb))
113 assert np.array_equal(h.covariance(), np.zeros((nb, nb)))
114
115
117 h = EventHistogram("x", EDGES, covariance=True)
118 fill(h, correlated_sample(5, 2000))
119 assert np.diag(h.covariance()) == pytest.approx(h.errors() ** 2)
120
121
123 h = EventHistogram("x", EDGES, n_replicas=400)
124 fill(h, correlated_sample(6, 4000))
125 assert h.bootstrap_errors() == pytest.approx(h.errors(), rel=0.25)
126
127
129 w = np.concatenate([replica_weights(k, 50) for k in range(4000)])
130 assert w.mean() == pytest.approx(1.0, abs=0.02)
131 assert w.var() == pytest.approx(1.0, abs=0.04)
132 assert np.array_equal(replica_weights(42, 10), replica_weights(42, 10))
133
134
136 h = EventHistogram("x", EDGES)
137 h.fill([1.0], [1.0])
138 with pytest.raises(RuntimeError):
139 h.values()
140
141
143 h = EventHistogram("x", EDGES)
144 h.fill_event([-1.0, 5.0, 10.0, 11.0], [1.0, 1.0, 1.0, 1.0])
145 assert h.values().sum() == pytest.approx(1.0)
146 assert h.sum_t[0] == pytest.approx(1.0)
147 assert h.sum_t[-1] == pytest.approx(2.0)
148
149
150@pytest.fixture(scope="module")
151def root_with_shipdata(root_with_shipdata):
152 if not hasattr(root_with_shipdata, "EventHistogram"):
153 pytest.skip("libShipData with EventHistogram not available")
154 return root_with_shipdata
155
156
157def test_root_round_trip_and_cpp_agree(root_with_shipdata, tmp_path):
158 ROOT = root_with_shipdata
159 events = correlated_sample(7, 2000)
160 h = EventHistogram("x", EDGES, covariance=True, n_replicas=20)
161 fill(h, events)
162 cpp = ROOT.EventHistogram("x", "", len(EDGES) - 1, 0.0, 10.0, True, 20)
163 fill_cpp(cpp, events)
164 result = cpp.MakeResult()
165 assert [result.GetBinContent(b) for b in range(1, 11)] == pytest.approx(h.values())
166 assert [result.GetBinError(b) for b in range(1, 11)] == pytest.approx(h.errors())
167 assert list(cpp.GetBootstrapErrors()) == pytest.approx(h.bootstrap_errors())
168 for key in (0, 1, make_event_key(7, 123456)):
169 assert [cpp.ReplicaWeight(key, r) for r in range(30)] == list(replica_weights(key, 30))
170
171 # Python writes, C++ reads; C++ writes, Python reads.
172 path = str(tmp_path / "eh.root")
173 f = ROOT.TFile(path, "RECREATE")
174 h.to_root(f)
175 f.Close()
176 f = ROOT.TFile(path)
177 back = ROOT.EventHistogram.Read(f, "x")
178 assert back.GetNEvents() == h.n_events
179 res = back.MakeResult()
180 assert [res.GetBinError(b) for b in range(1, 11)] == pytest.approx(h.errors())
181 f.Close()
182 path2 = str(tmp_path / "eh_cpp.root")
183 f = ROOT.TFile(path2, "RECREATE")
184 cpp.Write(f)
185 f.Close()
186 f = ROOT.TFile(path2)
187 again = EventHistogram.from_root(f, "x")
188 assert again.errors() == pytest.approx(h.errors())
189 assert again.covariance() == pytest.approx(h.covariance())
190 f.Close()
191
192 # Both refuse an incompatible merge and an open event.
193 other = ROOT.EventHistogram("x", "", len(EDGES) - 1, 0.0, 10.0, False, 20)
194 with pytest.raises(Exception, match="covariance"):
195 cpp.Add(other)
196 other.Fill(1.0)
197 with pytest.raises(Exception, match="open event"):
198 other.MakeResult()
199
200
201def test_hadd_of_different_settings_is_refused(root_with_shipdata, tmp_path):
202 ROOT = root_with_shipdata
203 paths = []
204 for i, covariance in enumerate((True, False)):
205 h = EventHistogram("x", EDGES, covariance=covariance)
206 fill(h, correlated_sample(8 + i, 200), run=i)
207 paths.append(str(tmp_path / f"part{i}.root"))
208 f = ROOT.TFile(paths[-1], "RECREATE")
209 h.to_root(f)
210 f.Close()
211 merged = str(tmp_path / "merged.root")
212 merger = ROOT.TFileMerger(False)
213 merger.OutputFile(merged, "RECREATE")
214 for path in paths:
215 merger.AddFile(path)
216 assert merger.Merge()
217 f = ROOT.TFile(merged)
218 with pytest.raises(ValueError, match="different settings"):
219 EventHistogram.from_root(f, "x")
220 assert not ROOT.EventHistogram.Read(f, "x")
221 f.Close()
correlated_sample(seed, n_events, p_active=0.3, n_clones=20)
test_root_round_trip_and_cpp_agree(root_with_shipdata, tmp_path)
fill_cpp(h, events, run=1)
test_hadd_of_different_settings_is_refused(root_with_shipdata, tmp_path)
root_with_shipdata(root_with_shipdata)