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
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