FairShip
Loading...
Searching...
No Matches
validationTools Namespace Reference

Functions

 container_size (container)
 format_mean_std (count, total, total_sq)
 safe_fraction (numerator, denominator)
 print_section (title)
 print_kv (label, value, width=28, separator=" : ")
 update_numeric_stat (stats, value)
 format_stat_summary (stats)
 make_numeric_stats ()
 make_reco_validation_stats ()
 record_event_stat (stats, key, value)
 print_reco_validation_summary (stats, has_veto_detector=False)
 _collect_generator_stats (flags, generators)
 print_simulation_output_summary (ROOT, output_filename, requested_events, flags, generators)

Function Documentation

◆ _collect_generator_stats()

validationTools._collect_generator_stats ( flags,
generators )
protected

Definition at line 206 of file validationTools.py.

206def _collect_generator_stats(flags, generators):
207 generator_stats = []
208 p8gen = generators.get("P8gen")
209 if p8gen is not None:
210 if flags["HNL"]:
211 generator_stats.append(("HNL retries", p8gen.nrOfRetries()))
212 generator_stats.append(("Geometry rejections", p8gen.nrOfGeoRejections()))
213 generator_stats.append(("HNL candidates", p8gen.GetCounter("hnl_candidates")))
214 generator_stats.append(("Accepted HNL candidates", p8gen.GetCounter("hnl_accepted_candidates")))
215 generator_stats.append(("Multi-HNL tries", p8gen.GetCounter("hnl_multi_candidate_tries")))
216 generator_stats.append(("Stored decay products", p8gen.GetCounter("hnl_stored_decay_products")))
217 elif flags["DarkPhoton"]:
218 generator_stats.append(("DP retries", p8gen.nrOfRetries()))
219 generator_stats.append(("Geometry rejections", p8gen.nrOfGeoRejections()))
220 generator_stats.append(("Total dark photons", p8gen.nrOfDP()))
221 elif flags["fixedTarget"]:
222 generator_stats.append(("Generated events", p8gen.GetCounter("generated_events")))
223 generator_stats.append(("G4-only events", p8gen.GetCounter("g4only_events")))
224 generator_stats.append(("Charm input pairs", p8gen.GetCounter("charm_input_pairs")))
225 generator_stats.append(("Stored tracks", p8gen.GetCounter("stored_tracks")))
226 generator_stats.append(("Tracked final-state particles", p8gen.GetCounter("tracked_final_state_particles")))
227 generator_stats.append(("Skipped final-state particles", p8gen.GetCounter("skipped_final_state_particles")))
228 muon_back_gen = generators.get("MuonBackgen")
229 if muon_back_gen is not None:
230 generator_stats.append(("Scanned input entries", muon_back_gen.GetCounter("scanned_entries")))
231 generator_stats.append(("Accepted input entries", muon_back_gen.GetCounter("accepted_entries")))
232 generator_stats.append(("Selected muons", muon_back_gen.GetCounter("selected_muons")))
233 generator_stats.append(("Transported tracks", muon_back_gen.GetCounter("transported_tracks")))
234 ntuple_gen = generators.get("Ntuplegen")
235 if ntuple_gen is not None:
236 generator_stats.append(("Scanned ntuple entries", ntuple_gen.GetCounter("scanned_entries")))
237 generator_stats.append(("Accepted ntuple entries", ntuple_gen.GetCounter("accepted_entries")))
238 generator_stats.append(("Rejected ntuple entries", ntuple_gen.GetCounter("rejected_entries")))
239 dis_gen = generators.get("DISgen")
240 if dis_gen is not None:
241 generator_stats.append(("Generated DIS events", dis_gen.GetCounter("generated_events")))
242 generator_stats.append(("Interaction sampling trials", dis_gen.GetCounter("interaction_sampling_trials")))
243 generator_stats.append(("Stored DIS particles", dis_gen.GetCounter("dis_particles_stored")))
244 generator_stats.append(("Stored soft particles", dis_gen.GetCounter("soft_particles_stored")))
245 generator_stats.append(("Skipped soft particles", dis_gen.GetCounter("soft_particles_skipped")))
246 genie_gen = generators.get("Geniegen")
247 if genie_gen is not None:
248 generator_stats.append(("Generated GENIE events", genie_gen.GetCounter("generated_events")))
249 generator_stats.append(("CC events", genie_gen.GetCounter("cc_events")))
250 generator_stats.append(("nu-e elastic events", genie_gen.GetCounter("nue_elastic_events")))
251 generator_stats.append(("Interaction sampling trials", genie_gen.GetCounter("interaction_sampling_trials")))
252 generator_stats.append(("Stored outgoing leptons", genie_gen.GetCounter("outgoing_leptons_stored")))
253 generator_stats.append(("Stored outgoing hadrons", genie_gen.GetCounter("outgoing_hadrons_stored")))
254 return generator_stats
255
256

◆ container_size()

validationTools.container_size ( container)

Definition at line 5 of file validationTools.py.

5def container_size(container):
6 if container is None:
7 return None
8 try:
9 return len(container)
10 except TypeError:
11 return None
12
13

◆ format_mean_std()

validationTools.format_mean_std ( count,
total,
total_sq )

Definition at line 14 of file validationTools.py.

14def format_mean_std(count, total, total_sq):
15 if count <= 0:
16 return "n/a"
17 mean = total / count
18 variance = max(0.0, total_sq / count - mean * mean)
19 std = variance**0.5
20 return f"{mean:.4g} +- {std:.4g}"
21
22

◆ format_stat_summary()

validationTools.format_stat_summary ( stats)

Definition at line 48 of file validationTools.py.

48def format_stat_summary(stats):
49 return (
50 f"{format_mean_std(stats['count'], stats['sum'], stats['sum_sq'])}"
51 f" [min={stats['min']:.4g}, max={stats['max']:.4g}]"
52 )
53
54

◆ make_numeric_stats()

validationTools.make_numeric_stats ( )

Definition at line 55 of file validationTools.py.

55def make_numeric_stats():
56 return {"count": 0, "sum": 0.0, "sum_sq": 0.0, "min": None, "max": None}
57
58

◆ make_reco_validation_stats()

validationTools.make_reco_validation_stats ( )

Definition at line 59 of file validationTools.py.

59def make_reco_validation_stats():
60 return {
61 "events_digitized": 0,
62 "events_reconstructed": 0,
63 "events_with_hits": 0,
64 "events_with_candidates": 0,
65 "events_with_fitted_tracks": 0,
66 "events_with_good_tracks": 0,
67 "smeared_hits_total": 0,
68 "track_candidates_total": 0,
69 "track_candidates_rejected_hits": 0,
70 "track_candidates_rejected_stations": 0,
71 "fit_hypotheses_tried": 0,
72 "fit_hypotheses_converged": 0,
73 "tracks_failed_consistency": 0,
74 "tracks_failed_fit": 0,
75 "tracks_failed_state_access": 0,
76 "fitted_tracks_total": 0,
77 "good_tracks_total": 0,
78 "vertexing_calls": 0,
79 "veto_links_total": 0,
80 "event_track_candidates_sum": 0.0,
81 "event_track_candidates_sum_sq": 0.0,
82 "event_fitted_tracks_sum": 0.0,
83 "event_fitted_tracks_sum_sq": 0.0,
84 "event_good_tracks_sum": 0.0,
85 "event_good_tracks_sum_sq": 0.0,
86 "event_veto_links_sum": 0.0,
87 "event_veto_links_sum_sq": 0.0,
88 "chi2_sum": 0.0,
89 "chi2_sum_sq": 0.0,
90 "chi2_count": 0,
91 "ndf_sum": 0.0,
92 "ndf_sum_sq": 0.0,
93 "ndf_count": 0,
94 "candidate_hits_sum": 0.0,
95 "candidate_hits_sum_sq": 0.0,
96 "candidate_hits_count": 0,
97 "candidate_stations_sum": 0.0,
98 "candidate_stations_sum_sq": 0.0,
99 "candidate_stations_count": 0,
100 "veto_link_distance_sum": 0.0,
101 "veto_link_distance_sum_sq": 0.0,
102 "veto_link_distance_count": 0,
103 }
104
105

◆ print_kv()

validationTools.print_kv ( label,
value,
width = 28,
separator = " : " )

Definition at line 34 of file validationTools.py.

34def print_kv(label, value, width=28, separator=" : "):
35 print(f" {label:<{width}}{separator}{value}")
36
37

◆ print_reco_validation_summary()

validationTools.print_reco_validation_summary ( stats,
has_veto_detector = False )

Definition at line 111 of file validationTools.py.

111def print_reco_validation_summary(stats, has_veto_detector=False):
112 print_section("Reco Validation")
113 for label in [
114 "events_digitized",
115 "events_reconstructed",
116 "events_with_hits",
117 "events_with_candidates",
118 "events_with_fitted_tracks",
119 "events_with_good_tracks",
120 "smeared_hits_total",
121 "track_candidates_total",
122 "track_candidates_rejected_hits",
123 "track_candidates_rejected_stations",
124 "fit_hypotheses_tried",
125 "fit_hypotheses_converged",
126 "tracks_failed_consistency",
127 "tracks_failed_fit",
128 "tracks_failed_state_access",
129 "fitted_tracks_total",
130 "good_tracks_total",
131 "vertexing_calls",
132 "veto_links_total",
133 ]:
134 print_kv(label, stats[label], width=40)
135 if stats["events_reconstructed"] > 0:
136 n_events = stats["events_reconstructed"]
137 print_kv(
138 "track_candidates_per_event",
139 format_mean_std(n_events, stats["event_track_candidates_sum"], stats["event_track_candidates_sum_sq"]),
140 width=40,
141 )
142 print_kv(
143 "fitted_tracks_per_event",
144 format_mean_std(n_events, stats["event_fitted_tracks_sum"], stats["event_fitted_tracks_sum_sq"]),
145 width=40,
146 )
147 print_kv(
148 "good_tracks_per_event",
149 format_mean_std(n_events, stats["event_good_tracks_sum"], stats["event_good_tracks_sum_sq"]),
150 width=40,
151 )
152 if has_veto_detector:
153 print_kv(
154 "veto_links_per_event",
155 format_mean_std(n_events, stats["event_veto_links_sum"], stats["event_veto_links_sum_sq"]),
156 width=40,
157 )
158 if stats["candidate_hits_count"] > 0:
159 print_kv(
160 "hits_per_candidate",
161 format_mean_std(stats["candidate_hits_count"], stats["candidate_hits_sum"], stats["candidate_hits_sum_sq"]),
162 width=40,
163 )
164 if stats["candidate_stations_count"] > 0:
165 print_kv(
166 "stations_per_candidate",
167 format_mean_std(
168 stats["candidate_stations_count"], stats["candidate_stations_sum"], stats["candidate_stations_sum_sq"]
169 ),
170 width=40,
171 )
172 if stats["veto_link_distance_count"] > 0:
173 print_kv(
174 "veto_link_distance",
175 format_mean_std(
176 stats["veto_link_distance_count"], stats["veto_link_distance_sum"], stats["veto_link_distance_sum_sq"]
177 ),
178 width=40,
179 )
180 if stats["chi2_count"] > 0:
181 print_kv(
182 "fit_chi2_over_ndf", format_mean_std(stats["chi2_count"], stats["chi2_sum"], stats["chi2_sum_sq"]), width=40
183 )
184 if stats["ndf_count"] > 0:
185 print_kv("fit_ndf", format_mean_std(stats["ndf_count"], stats["ndf_sum"], stats["ndf_sum_sq"]), width=40)
186 if stats["fit_hypotheses_tried"] > 0:
187 print_kv(
188 "fit_convergence_fraction",
189 f"{100.0 * stats['fit_hypotheses_converged'] / stats['fit_hypotheses_tried']:.2f}%",
190 width=40,
191 )
192 if stats["track_candidates_total"] > 0:
193 print_kv(
194 "candidate_to_fit_fraction",
195 f"{100.0 * stats['fitted_tracks_total'] / stats['track_candidates_total']:.2f}%",
196 width=40,
197 )
198 if stats["fitted_tracks_total"] > 0:
199 print_kv(
200 "good_track_fraction",
201 f"{100.0 * stats['good_tracks_total'] / stats['fitted_tracks_total']:.2f}%",
202 width=40,
203 )
204
205

◆ print_section()

validationTools.print_section ( title)

Definition at line 29 of file validationTools.py.

29def print_section(title):
30 print(" ")
31 print(f"[{title}]")
32
33

◆ print_simulation_output_summary()

validationTools.print_simulation_output_summary ( ROOT,
output_filename,
requested_events,
flags,
generators )

Definition at line 257 of file validationTools.py.

257def print_simulation_output_summary(ROOT, output_filename, requested_events, flags, generators):
258 generator_stats = _collect_generator_stats(flags, generators)
259 if generator_stats:
260 print_section("Generator Validation")
261 for label, value in generator_stats:
262 print_kv(label, value)
263
264 try:
265 summary_file = ROOT.TFile.Open(output_filename, "READ")
266 except OSError:
267 print("Could not reopen output file for summary:", output_filename)
268 return
269
270 with summary_file:
271 keys = list(summary_file.GetListOfKeys())
272 print_section("Tree Validation")
273 print_kv("Requested events", requested_events)
274
275 tree = summary_file.Get("cbmsim")
276 if not tree:
277 print("No cbmsim tree found in output file.")
278 return
279
280 n_entries = tree.GetEntries()
281 print_kv("Final cbmsim entries", n_entries)
282 print_kv("Kept fraction", safe_fraction(n_entries, requested_events))
283
284 branch_names = [branch.GetName() for branch in tree.GetListOfBranches()]
285 print_kv("Branches in cbmsim", len(branch_names))
286 print_kv("ROOT objects", len(keys))
287
288 if n_entries <= 0:
289 print("cbmsim tree is empty.")
290 return
291
292 scalar_stats = {}
293 branch_stats = {}
294 track_counts = {"total": 0, "primary": 0, "secondary": 0}
295 track_numeric_stats = {
296 "p": make_numeric_stats(),
297 "energy": make_numeric_stats(),
298 "start_z": make_numeric_stats(),
299 "weight": make_numeric_stats(),
300 }
301 pdg_counts: dict[int, int] = {}
302
303 for branch_name in branch_names:
304 branch_stats[branch_name] = {"total": 0, "nonzero": 0, "max": 0, "sum_sq": 0.0}
305
306 for event_index in range(n_entries):
307 tree.GetEntry(event_index)
308 for branch_name in branch_names:
309 container = getattr(tree, branch_name, None)
310 if container is None:
311 continue
312 count = container_size(container)
313 if count is None:
314 try:
315 value = float(container)
316 except (TypeError, ValueError):
317 continue
318 if branch_name not in scalar_stats:
319 scalar_stats[branch_name] = make_numeric_stats()
320 update_numeric_stat(scalar_stats[branch_name], value)
321 continue
322
323 stats = branch_stats[branch_name]
324 stats["total"] += count
325 if count > 0:
326 stats["nonzero"] += 1
327 if count > stats["max"]:
328 stats["max"] = count
329 stats["sum_sq"] += count * count
330
331 if branch_name == "MCTrack" and count > 0:
332 for track in container:
333 track_counts["total"] += 1
334 if track.GetMotherId() < 0:
335 track_counts["primary"] += 1
336 else:
337 track_counts["secondary"] += 1
338 update_numeric_stat(track_numeric_stats["p"], float(track.GetP()))
339 update_numeric_stat(track_numeric_stats["energy"], float(track.GetEnergy()))
340 update_numeric_stat(track_numeric_stats["start_z"], float(track.GetStartZ()))
341 update_numeric_stat(track_numeric_stats["weight"], float(track.GetWeight()))
342 pdg = int(track.GetPdgCode())
343 pdg_counts[pdg] = pdg_counts.get(pdg, 0) + 1
344
345 countable_branches = [
346 name for name, stats in branch_stats.items() if stats["total"] > 0 or stats["nonzero"] > 0
347 ]
348 print_kv("Countable branches", len(countable_branches))
349
350 if track_counts["total"] > 0:
351 print_section("MCTrack Validation")
352 print_kv("Total tracks", track_counts["total"])
353 print_kv("Primary tracks", track_counts["primary"])
354 print_kv("Secondary tracks", track_counts["secondary"])
355 print_kv("Tracks per event", f"{track_counts['total'] / n_entries:.4g}")
356 print_kv("Track momentum", format_stat_summary(track_numeric_stats["p"]))
357 print_kv("Track energy", format_stat_summary(track_numeric_stats["energy"]))
358 print_kv("Track start Z", format_stat_summary(track_numeric_stats["start_z"]))
359 print_kv("Track weight", format_stat_summary(track_numeric_stats["weight"]))
360 top_pdgs = sorted(pdg_counts.items(), key=lambda item: (-item[1], abs(item[0]), item[0]))[:10]
361 print_kv("Top PDG counts", ", ".join(f"{pdg}:{count}" for pdg, count in top_pdgs))
362
363 if scalar_stats:
364 print_section("Scalar Branch Validation")
365 for branch_name in sorted(scalar_stats):
366 print_kv(branch_name, format_stat_summary(scalar_stats[branch_name]))
367
368 print_section("Branch Multiplicity")
369 for branch_name in sorted(countable_branches):
370 stats = branch_stats[branch_name]
371 active = 100.0 * stats["nonzero"] / n_entries
372 print_kv(
373 branch_name,
374 f"total={stats['total']}, mean/event={format_mean_std(n_entries, stats['total'], stats['sum_sq'])},"
375 f" active={stats['nonzero']}/{n_entries} ({active:5.1f}%), max={stats['max']}",
376 width=22,
377 )

◆ record_event_stat()

validationTools.record_event_stat ( stats,
key,
value )

Definition at line 106 of file validationTools.py.

106def record_event_stat(stats, key, value):
107 stats[f"{key}_sum"] += value
108 stats[f"{key}_sum_sq"] += value * value
109
110

◆ safe_fraction()

validationTools.safe_fraction ( numerator,
denominator )

Definition at line 23 of file validationTools.py.

23def safe_fraction(numerator, denominator):
24 if denominator == 0:
25 return "n/a"
26 return f"{100.0 * numerator / denominator:.2f}%"
27
28

◆ update_numeric_stat()

validationTools.update_numeric_stat ( stats,
value )

Definition at line 38 of file validationTools.py.

38def update_numeric_stat(stats, value):
39 stats["count"] += 1
40 stats["sum"] += value
41 stats["sum_sq"] += value * value
42 if stats["min"] is None or value < stats["min"]:
43 stats["min"] = value
44 if stats["max"] is None or value > stats["max"]:
45 stats["max"] = value
46
47