FairShip
Loading...
Searching...
No Matches
test_mudis_postprocessing.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"""Round trip of the NewMuDIS post-processing on small hand-made files.
5
6``post_process`` pairs each simulated event with the DIS interaction it was
7generated from by walking the MuonDIS input in replay order, then copies the
8incoming muon's hits upstream of the vertex into that event. These tests build
9a MuonDIS input split over two files, with uneven DIS counts per material and
10a muon without any interaction, plus a matching ``cbmsim`` output carrying the
11``muDIS_*`` identity branches that ``NewMuDISGenerator`` writes. They check
12that hits land on the right events, that a non-zero start entry is counted
13across files, and that a mismatch stops the run without touching the output.
14"""
15
16from array import array
17
18import pytest
19
20ROOT = pytest.importorskip("ROOT")
21
22# The test needs the compiled newMuonDIS dictionary (material labels) and the
23# detector point classes; fail loudly rather than skip if they are missing.
24if ROOT.gSystem.Load("libShipMuDIS") < 0:
25 raise ImportError("libShipMuDIS could not be loaded; build FairShip and run the tests in its environment")
26
27from MuDISGenerator_postProcessing import _MARKER, _POINT_BRANCHES, post_process
28
29MATERIALS = [str(label) for label in ROOT.NewMuDISGenerator.GetMaterialNames()]
30MUON_MASS = 0.10566
31
32# Two input files: muons 0 and 1 in the first, muon 2 in the second.
33# Muon 1 has no DIS interaction at all and must be skipped by the replay order.
34FIRST_FILE = [
35 {
36 "hits": {"muon_UBTPoints": [3270.0], "muon_SBTPoints": [3500.0], "muon_SSTPoints": [8500.0]},
37 "dis": {"HE": [4000.0, 4100.0]},
38 },
39 {"hits": {"muon_SBTPoints": [3300.0]}, "dis": {}},
40]
41SECOND_FILE = [
42 {"hits": {"muon_SBTPoints": [3400.0], "muon_TDPoints": [9000.0]}, "dis": {"AIR": [8000.0]}},
43]
44# (muon entry across both files, material, DIS index), in replay order.
45REPLAY_FROM_START = [(0, "HE", 0), (0, "HE", 1), (2, "AIR", 0)]
46# A simulated hit already in every output event, which must be kept.
47SIMULATED_Z = 9999.0
48
49
50def make_point(class_name, z, track_id):
51 point = getattr(ROOT, class_name)()
52 point.SetXYZ(0.0, 0.0, z)
53 point.SetTrackID(track_id)
54 return point
55
56
57def write_input(path, muons):
58 """Write a MuonDIS tree with only the branches post_process reads."""
59 output = ROOT.TFile.Open(str(path), "RECREATE")
60 tree = ROOT.TTree("MuonDIS", "post-processing test input")
61 hits = {branch: ROOT.std.vector[class_name]() for branch, class_name in _POINT_BRANCHES}
62 for branch, vector in hits.items():
63 tree.Branch(branch, vector)
64 counts = {material: array("i", [0]) for material in MATERIALS}
65 vertices = {material: ROOT.std.vector["double"]() for material in MATERIALS}
66 for material in MATERIALS:
67 tree.Branch(f"muon_nDISevt_{material}", counts[material], f"muon_nDISevt_{material}/I")
68 tree.Branch(f"mudis_DISvz_{material}", vertices[material])
69 for muon in muons:
70 for branch, class_name in _POINT_BRANCHES:
71 hits[branch].clear()
72 for z in muon["hits"].get(branch, ()):
73 hits[branch].push_back(make_point(class_name, z, track_id=1))
74 for material in MATERIALS:
75 dis_z = muon["dis"].get(material, ())
76 counts[material][0] = len(dis_z)
77 vertices[material].clear()
78 for z in dis_z:
79 vertices[material].push_back(z)
80 tree.Fill()
81 tree.Write()
82 output.Close()
83
84
85def write_output(path, identities):
86 """Write a cbmsim tree as the simulation leaves it, one entry per identity."""
87 output = ROOT.TFile.Open(str(path), "RECREATE")
88 tree = ROOT.TTree("cbmsim", "post-processing test output")
89 tracks = ROOT.std.vector["ShipMCTrack"]()
90 tree.Branch("MCTrack", tracks)
91 points = {class_name: ROOT.std.vector[class_name]() for _, class_name in _POINT_BRANCHES}
92 for class_name, vector in points.items():
93 tree.Branch(class_name, vector)
94 muon_entry = array("i", [0])
95 dis_index = array("i", [0])
96 material = ROOT.TString()
97 tree.Branch("muDIS_muEntry", muon_entry, "muDIS_muEntry/I")
98 tree.Branch("muDIS_material", material)
99 tree.Branch("muDIS_disIndex", dis_index, "muDIS_disIndex/I")
100 for event, (entry, label, index) in enumerate(identities):
101 tracks.clear()
102 # Untracked incoming muon at MCTrack[0], as NewMuDISGenerator adds it.
103 tracks.push_back(ROOT.ShipMCTrack(13, -1, 0.0, 0.0, 50.0, MUON_MASS, 0.0, 0.0, 3000.0, 0.0, 0, event, 0, 1.0))
104 for vector in points.values():
105 vector.clear()
106 points["vetoPoint"].push_back(make_point("vetoPoint", SIMULATED_Z, track_id=1))
107 muon_entry[0] = entry
108 dis_index[0] = index
109 material.Clear()
110 material.Append(label)
111 tree.Fill()
112 tree.Write()
113 output.Close()
114
115
116def read_events(path):
117 """Return, per output entry, the identity and the z and track ID of every point."""
118 events = []
119 with ROOT.TFile.Open(str(path), "READ") as source:
120 tree = source.Get("cbmsim")
121 for entry in range(tree.GetEntries()):
122 tree.GetEntry(entry)
123 event = {
124 "identity": (int(tree.muDIS_muEntry), str(tree.muDIS_material), int(tree.muDIS_disIndex)),
125 "event_id": tree.MCTrack[0].GetEventID(),
126 }
127 for _, class_name in _POINT_BRANCHES:
128 event[class_name] = [
129 (point.GetZ(), point.GetTrackID(), point.GetEventID()) for point in getattr(tree, class_name)
130 ]
131 events.append(event)
132 restored = bool(source.Get(_MARKER))
133 return events, restored
134
135
136@pytest.fixture
137def inputs(tmp_path):
138 first = tmp_path / "muondis_a.root"
139 second = tmp_path / "muondis_b.root"
140 write_input(first, FIRST_FILE)
141 write_input(second, SECOND_FILE)
142 return [str(first), str(second)]
143
144
146 assert {"HE", "AIR"} <= set(MATERIALS)
147
148
150 output = tmp_path / "sim.root"
151 write_output(output, REPLAY_FROM_START)
152
153 counts = post_process(output, inputs, start_event=0)
154
155 # Both HE events get the UBT and SBT hits of muon 0 (z < 4000, 4100), not its
156 # SST hit; the AIR event gets the SBT hit of muon 2 (z < 8000), not its TD hit.
157 assert counts == {"UpstreamTaggerPoint": 2, "vetoPoint": 3, "strawtubesPoint": 0, "TimeDetPoint": 0}
158 events, restored = read_events(output)
159 assert restored
160 assert [event["identity"] for event in events] == REPLAY_FROM_START
161 expected_veto_z = [[SIMULATED_Z, 3500.0], [SIMULATED_Z, 3500.0], [SIMULATED_Z, 3400.0]]
162 expected_ubt_z = [[3270.0], [3270.0], []]
163 for event, veto_z, ubt_z in zip(events, expected_veto_z, expected_ubt_z):
164 assert [z for z, _, _ in event["vetoPoint"]] == pytest.approx(veto_z)
165 assert [z for z, _, _ in event["UpstreamTaggerPoint"]] == pytest.approx(ubt_z)
166 assert event["strawtubesPoint"] == []
167 assert event["TimeDetPoint"] == []
168 # The simulated hit is untouched; restored hits point at MCTrack[0] of this event.
169 assert event["vetoPoint"][0][1] == 1
170 for _, track_id, event_id in event["vetoPoint"][1:] + event["UpstreamTaggerPoint"]:
171 assert track_id == 0
172 assert event_id == event["event_id"]
173
174
176 output = tmp_path / "sim.root"
177 # Starting at muon 1 skips muon 0; muon 1 has no DIS, so the first event is
178 # muon 2, the first entry of the second file and entry 2 overall.
179 write_output(output, [(2, "AIR", 0)])
180
181 counts = post_process(output, inputs, start_event=1)
182
183 assert counts["vetoPoint"] == 1
184 events, _ = read_events(output)
185 assert [z for z, _, _ in events[0]["vetoPoint"]] == pytest.approx([SIMULATED_Z, 3400.0])
186
187
188@pytest.mark.parametrize(
189 "identities",
190 [
191 [(0, "HE", 1), (0, "HE", 0), (2, "AIR", 0)], # DIS order swapped within a muon
192 [(0, "HE", 0), (0, "HE", 1), (1, "AIR", 0)], # wrong muon entry
193 [(0, "HE", 0), (0, "AIR", 1), (2, "AIR", 0)], # wrong material
194 ],
195)
196def test_mismatch_raises_and_leaves_output_unchanged(tmp_path, inputs, identities):
197 output = tmp_path / "sim.root"
198 write_output(output, identities)
199 before = output.read_bytes()
200
201 with pytest.raises(ValueError, match="replayed"):
202 post_process(output, inputs, start_event=0)
203
204 assert output.read_bytes() == before
205 assert not list(tmp_path.glob(".sim.mudis-*.root"))
206
207
209 output = tmp_path / "sim.root"
210 write_output(output, [*REPLAY_FROM_START, (2, "AIR", 1)])
211
212 with pytest.raises(ValueError, match="No input DIS interaction"):
213 post_process(output, inputs, start_event=0)
214
215 events, restored = read_events(output)
216 assert not restored
217 assert len(events) == 4
test_mismatch_raises_and_leaves_output_unchanged(tmp_path, inputs, identities)
test_more_output_events_than_interactions_raises(tmp_path, inputs)
test_restores_hits_upstream_of_each_vertex(tmp_path, inputs)
make_point(class_name, z, track_id)
test_start_entry_counts_across_input_files(tmp_path, inputs)