27 """Yield the muon tree, DIS z and identity in the generator's replay order.
29 The identity is (muon entry across all input files, material label, DIS
30 index within that muon and material), as NewMuDISGenerator writes it.
33 materials = [str(label)
for label
in ROOT.NewMuDISGenerator.GetMaterialNames()]
36 for name
in input_files:
37 with ROOT.TFile.Open(str(name),
"READ")
as source:
38 tree = source.Get(
"MuonDIS")
40 raise ValueError(f
"Missing MuonDIS tree in {name}")
41 entries = tree.GetEntries()
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}")
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)
90 """Append input-muon hits with z < DIS z to each simulated cbmsim event.
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.
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.
105 raise ValueError(
"start_event must be nonnegative")
106 if isinstance(input_files, (str, os.PathLike)):
107 input_files = [input_files]
109 input_files = list(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")
117 for opened
in ROOT.gROOT.GetListOfFiles():
119 isinstance(opened, ROOT.TFile)
120 and os.path.realpath(opened.GetName()) == str(output_path)
121 and opened.IsWritable()
125 counts = dict.fromkeys((branch
for _, branch
in _POINT_BRANCHES), 0)
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")
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
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}")
149 muon, vertex_z, expected = next(events)
150 except StopIteration
as error:
152 f
"No input DIS interaction corresponding to simulation entry {entry}"
154 replayed = (int(tree.muDIS_muEntry), str(tree.muDIS_material), int(tree.muDIS_disIndex))
155 if replayed != expected:
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."
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)
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}")
177 if rewritten.Write(
"cbmsim", ROOT.TObject.kOverwrite) <= 0:
178 raise OSError(
"Cannot write restored cbmsim tree")
181 ROOT.TNamed(_MARKER,
"Incoming-muon hits restored for z < DIS vertex z").Write()
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)
190 if temporary
is not None:
191 Path(temporary).unlink(missing_ok=
True)
192 print(f
"Restored incoming-muon hits in {output_file}: {counts}")
_dis_events(input_files, start_event)
post_process(output_file, input_files, start_event=0)
_copy_metadata(source, destination, skip=())