FairShip
Loading...
Searching...
No Matches
MuDISGenerator_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"""Restore incoming-muon detector points after NewMuDISGenerator simulation."""
5
6import math
7import os
8import shutil
9import tempfile
10from pathlib import Path
11
12import ROOT
13
14# Required input branch, simulation branch / point class.
15_POINT_BRANCHES = (
16 ("muon_UBTPoints", "UpstreamTaggerPoint"),
17 ("muon_SBTPoints", "vetoPoint"),
18 ("muon_SSTPoints", "strawtubesPoint"),
19 ("muon_TDPoints", "TimeDetPoint"),
20)
21_MARKER = "MuDISGenerator_postProcessing"
22# Per-event identity written by NewMuDISGenerator.RegisterOutputBranches.
23_IDENTITY_BRANCHES = ("muDIS_muEntry", "muDIS_material", "muDIS_disIndex")
24
25
26def _dis_events(input_files, start_event):
27 """Yield the muon tree, DIS z and identity in the generator's replay order.
28
29 The identity is (muon entry across all input files, material label, DIS
30 index within that muon and material), as NewMuDISGenerator writes it.
31 """
32 # Use the generator's material order from MuDISDefs.h.
33 materials = [str(label) for label in ROOT.NewMuDISGenerator.GetMaterialNames()]
34 skip = start_event
35 offset = 0 # entries in the preceding input files
36 for name in input_files:
37 with ROOT.TFile.Open(str(name), "READ") as source:
38 tree = source.Get("MuonDIS")
39 if not tree:
40 raise ValueError(f"Missing MuonDIS tree in {name}")
41 entries = tree.GetEntries()
42 if skip >= entries:
43 skip -= entries
44 offset += entries
45 continue
46 required = [branch for branch, _ in _POINT_BRANCHES]
47 for material in materials:
48 required.extend((f"muon_nDISevt_{material}", f"mudis_DISvz_{material}"))
49 for branch in required:
50 if not tree.GetBranch(branch):
51 raise ValueError(f"Missing {branch} in {name}")
52 # Avoid reading the large DIS daughter arrays.
53 tree.SetBranchStatus("*", False)
54 for branch in required:
55 tree.SetBranchStatus(branch + "*", True)
56 for entry in range(skip, entries):
57 if tree.GetEntry(entry) <= 0:
58 raise OSError(f"Cannot read MuonDIS entry {entry} in {name}")
59 for material in materials:
60 count = int(getattr(tree, f"muon_nDISevt_{material}"))
61 vertices = getattr(tree, f"mudis_DISvz_{material}")
62 if count < 0 or len(vertices) != count:
63 raise ValueError(f"Invalid DIS count/vertices in {name}, entry {entry}, material {material}")
64 for index, z in enumerate(vertices):
65 if not math.isfinite(z):
66 raise ValueError(f"Non-finite DIS vertex in {name}, entry {entry}")
67 yield tree, float(z), (offset + entry, material, index)
68 skip = 0
69 offset += entries
70
71
72def _copy_metadata(source, destination, skip=()):
73 """Preserve the latest key of every other object, including directories."""
74 names = dict.fromkeys(key.GetName() for key in source.GetListOfKeys())
75 for name in names:
76 if name in skip:
77 continue
78 obj = source.Get(name)
79 destination.cd()
80 if obj.InheritsFrom("TDirectory"):
81 _copy_metadata(obj, destination.mkdir(name, obj.GetTitle()))
82 continue
83 if obj.InheritsFrom("TTree"):
84 obj = obj.CloneTree(-1, "fast")
85 if obj.Write(name, ROOT.TObject.kSingleKey) <= 0:
86 raise OSError(f"Cannot copy output metadata {name}")
87
88
89def post_process(output_file, input_files, start_event=0):
90 """Append input-muon hits with z < DIS z to each simulated cbmsim event.
91
92 Input files and start_event (a zero-based muon entry across the files) must
93 match NewMuDISGenerator.Init. Output must still be in generator order, before
94 any event skimming. Its entry count sets how many DIS interactions to consume.
95 Each output entry's muDIS_muEntry, muDIS_material and muDIS_disIndex must
96 match the interaction read here; any mismatch raises before the output is
97 replaced, so hits are never attached to the wrong event.
98 Copied points reference MCTrack[0], the untracked incoming muon; their event
99 IDs are updated too. Other point properties and simulated hits are preserved.
100
101 Rewrite to a temporary sibling file, preserving metadata, and replace the
102 output only after success. Return the number of appended hits per detector.
103 """
104 if start_event < 0:
105 raise ValueError("start_event must be nonnegative")
106 if isinstance(input_files, (str, os.PathLike)):
107 input_files = [input_files]
108 else:
109 input_files = list(input_files)
110 if not input_files:
111 raise ValueError("At least one MuonDIS input file is required")
112 output_path = Path(output_file).resolve()
113 if any(os.path.realpath(str(name)) == str(output_path) for name in input_files):
114 raise ValueError("Simulation output must differ from the MuonDIS input")
115
116 # FairRunSim can still own an open output file at this point.
117 for opened in ROOT.gROOT.GetListOfFiles():
118 if (
119 isinstance(opened, ROOT.TFile)
120 and os.path.realpath(opened.GetName()) == str(output_path)
121 and opened.IsWritable()
122 ):
123 opened.Flush()
124
125 counts = dict.fromkeys((branch for _, branch in _POINT_BRANCHES), 0)
126 events = _dis_events(input_files, start_event)
127 temporary = None
128 try:
129 with ROOT.TFile.Open(str(output_path), "READ") as source:
130 if source.Get(_MARKER):
131 raise ValueError("Incoming-muon hits have already been restored in this output")
132 tree = source.Get("cbmsim")
133 if not tree:
134 raise ValueError("Simulation output has no cbmsim tree")
135 for branch in ("MCTrack", *(name for _, name in _POINT_BRANCHES), *_IDENTITY_BRANCHES):
136 if not tree.GetBranch(branch):
137 raise ValueError(f"Simulation output has no {branch} branch")
138 fd, temporary = tempfile.mkstemp(
139 prefix=f".{output_path.stem}.mudis-", suffix=".root", dir=output_path.parent
140 )
141 os.close(fd)
142 with ROOT.TFile.Open(temporary, "RECREATE") as destination:
143 destination.SetCompressionSettings(source.GetCompressionSettings())
144 rewritten = tree.CloneTree(0)
145 for entry in range(tree.GetEntries()):
146 if tree.GetEntry(entry) <= 0:
147 raise OSError(f"Cannot read simulation entry {entry}")
148 try:
149 muon, vertex_z, expected = next(events)
150 except StopIteration as error:
151 raise ValueError(
152 f"No input DIS interaction corresponding to simulation entry {entry}"
153 ) from error
154 replayed = (int(tree.muDIS_muEntry), str(tree.muDIS_material), int(tree.muDIS_disIndex))
155 if replayed != expected:
156 raise ValueError(
157 f"Simulation entry {entry} replayed (muon entry, material, DIS index) = {replayed}, "
158 f"but the input order gives {expected}. Check that the input files and start "
159 "entry match the simulation run and that the output was not skimmed."
160 )
161 tracks = tree.MCTrack
162 if not tracks.size() or abs(tracks[0].GetPdgCode()) != 13 or tracks[0].GetMotherId() != -1:
163 raise ValueError(f"Simulation entry {entry} has no incoming muon at MCTrack[0]")
164 for input_branch, output_branch in _POINT_BRANCHES:
165 points = getattr(tree, output_branch)
166 point_class = getattr(ROOT, output_branch)
167 for hit in getattr(muon, input_branch):
168 if hit.GetZ() < vertex_z:
169 copied = point_class(hit)
170 copied.SetTrackID(0)
171 copied.SetEventID(tracks[0].GetEventID())
172 points.push_back(copied)
173 counts[output_branch] += 1
174 if rewritten.Fill() < 0:
175 raise OSError(f"Cannot write simulation entry {entry}")
176 destination.cd()
177 if rewritten.Write("cbmsim", ROOT.TObject.kOverwrite) <= 0:
178 raise OSError("Cannot write restored cbmsim tree")
179 _copy_metadata(source, destination, skip=("cbmsim",))
180 destination.cd()
181 ROOT.TNamed(_MARKER, "Incoming-muon hits restored for z < DIS vertex z").Write()
182 destination.Flush()
183 if destination.TestBit(ROOT.TFile.kWriteError):
184 raise OSError("Error writing restored simulation output")
185 shutil.copymode(output_path, temporary)
186 os.replace(temporary, output_path)
187 temporary = None
188 finally:
189 events.close()
190 if temporary is not None:
191 Path(temporary).unlink(missing_ok=True)
192 print(f"Restored incoming-muon hits in {output_file}: {counts}")
193 return counts
post_process(output_file, input_files, start_event=0)
_copy_metadata(source, destination, skip=())