FairShip
Loading...
Searching...
No Matches
tracking_benchmark.TrackingBenchmark Class Reference

Public Member Functions

None __init__ (self, str sim_file, str reco_file, str geo_file, float purity_cut=0.70, int min_hits=25, int min_stations=3, bool primary_only=True, bool straw_purity=False)
dict[str, Any] compute_metrics (self)
None save_json (self, str output_path)
None save_histograms (self, str output_path)
None print_summary (self)
None __del__ (self)

Public Attributes

 purity_cut = purity_cut
 min_hits = min_hits
 min_stations = min_stations
 primary_only = primary_only
 straw_purity = straw_purity
 f_sim = ROOT.TFile.Open(sim_file, "read")
 sim_tree = self.f_sim["cbmsim"]
 f_reco = ROOT.TFile.Open(reco_file, "read")
 reco_tree = self.f_reco["ship_reco_sim"]
 f_geo = ROOT.TFile.Open(geo_file, "read")
 PDG = ROOT.TDatabasePDG.Instance()
dict metrics = {}

Protected Member Functions

dict[int, dict[str, Any]] _build_straw_index (self)
bool _is_reconstructible (self, int mc_track_id)
tuple[float, float, float, float] _get_ptruth_first (self, int mc_track_id)
tuple[float, float, float] _get_truth_pos_first (self, int mc_track_id)
tuple[float, float] _get_truth_slopes (self, int mc_track_id)
tuple[float, int] _fracMCsame (self, int reco_track_idx)
dict[str, Any] _rates (self, dict[str, int] stats)
dict[str, Any] _vertex_metrics (self, dict[str, Any] stats)
float _truth_charge (self, int mc_track_id)
dict[tuple, list[int]] _truth_vertices (self, set[int] reconstructible_ids)
list[tuple[int, int]] _opposite_pairs (self, list[int] mc_ids)
None _evaluate_vertices (self, set[int] reconstructible_ids, dict[str, Any] stats)

Static Protected Member Functions

dict[str, Any] _fraction (int k, int n)
dict[str, Any] _width (histogram, int n_replicas=200)
str _fmt (float|None value, float|None uncertainty, str fmt=".4f")

Protected Attributes

dict _straw_crossers = {}
dict _histos = {}
dict _straw_index = {}
dict _vertex_histos = {name: stats[name] for name in stats if name.startswith("h_")}

Detailed Description

Compute tracking benchmark metrics from simulation and reconstruction files.

Parameters
----------
sim_file : str
    Path to MC simulation ROOT file (contains cbmsim tree).
reco_file : str
    Path to reconstruction ROOT file (contains ship_reco_sim tree).
geo_file : str
    Path to geometry ROOT file.
purity_cut : float
    Minimum hit purity fraction for a reco track to be considered matched.
min_hits : int
    Minimum number of straw hits for reconstructibility.
min_stations : int
    Minimum number of tracking stations crossed for reconstructibility.
primary_only : bool
    Count only primary particles as reconstructible. Set to False for
    samples whose tracks of interest are secondaries, such as HNL
    daughters.
straw_purity : bool
    Attribute a hit to every MC track that crossed its straw, not only to
    the one whose hit was recorded (the earliest). In busy events tracks
    share straws, and a correct track would otherwise look impure.

Definition at line 61 of file tracking_benchmark.py.

Constructor & Destructor Documentation

◆ __init__()

None tracking_benchmark.TrackingBenchmark.__init__ ( self,
str sim_file,
str reco_file,
str geo_file,
float purity_cut = 0.70,
int min_hits = 25,
int min_stations = 3,
bool primary_only = True,
bool straw_purity = False )

Definition at line 88 of file tracking_benchmark.py.

98 ) -> None:
99 self.purity_cut = purity_cut
100 self.min_hits = min_hits
101 self.min_stations = min_stations
102 self.primary_only = primary_only
103 self.straw_purity = straw_purity
104 # Per event: MC tracks that crossed each straw
105 self._straw_crossers: dict[int, set[int]] = {}
106
107 self.f_sim = ROOT.TFile.Open(sim_file, "read")
108 self.sim_tree = self.f_sim["cbmsim"]
109
110 self.f_reco = ROOT.TFile.Open(reco_file, "read")
111 self.reco_tree = self.f_reco["ship_reco_sim"]
112
113 self.f_geo = ROOT.TFile.Open(geo_file, "read")
114
115 self.PDG = ROOT.TDatabasePDG.Instance()
116
117 self.metrics: dict[str, Any] = {}
118 self._histos: dict[str, Any] = {}
119 # Per-event index over strawtubesPoint, rebuilt each event.
120 self._straw_index: dict[int, dict[str, Any]] = {}
121

◆ __del__()

None tracking_benchmark.TrackingBenchmark.__del__ ( self)

Definition at line 848 of file tracking_benchmark.py.

848 def __del__(self) -> None:
849 for f in [self.f_sim, self.f_reco, self.f_geo]:
850 if f and f.IsOpen():
851 f.Close()

Member Function Documentation

◆ _build_straw_index()

dict[int, dict[str, Any]] tracking_benchmark.TrackingBenchmark._build_straw_index ( self)
protected
Build a per-event index over strawtubesPoint.

Maps MC track id -> {n_hits, stations, first}, where ``first`` holds the
(px, py, pz, x, y, z) of the first straw hit for that track. One pass
replaces the repeated full-branch scans in the reconstructibility and
truth-lookup helpers.

Definition at line 122 of file tracking_benchmark.py.

122 def _build_straw_index(self) -> dict[int, dict[str, Any]]:
123 """Build a per-event index over strawtubesPoint.
124
125 Maps MC track id -> {n_hits, stations, first}, where ``first`` holds the
126 (px, py, pz, x, y, z) of the first straw hit for that track. One pass
127 replaces the repeated full-branch scans in the reconstructibility and
128 truth-lookup helpers.
129 """
130 index: dict[int, dict[str, Any]] = {}
131 for hit in self.sim_tree.strawtubesPoint:
132 tid = hit.GetTrackID()
133 station = int(hit.GetDetectorID() // 1_000_000)
134 entry = index.get(tid)
135 if entry is None:
136 index[tid] = {
137 "n_hits": 1,
138 "stations": {station},
139 "first": (
140 hit.GetPx(),
141 hit.GetPy(),
142 hit.GetPz(),
143 hit.GetX(),
144 hit.GetY(),
145 hit.GetZ(),
146 ),
147 }
148 else:
149 entry["n_hits"] += 1
150 entry["stations"].add(station)
151 return index
152

◆ _evaluate_vertices()

None tracking_benchmark.TrackingBenchmark._evaluate_vertices ( self,
set[int] reconstructible_ids,
dict[str, Any] stats )
protected
Match this event's vertex candidates (Particles) to MC truth vertices.

A candidate is matched if both daughters pass the purity cut, belong
to different MC tracks, and those come from the same truth vertex.
Updates the counters and histograms in ``stats``.

Definition at line 330 of file tracking_benchmark.py.

330 def _evaluate_vertices(self, reconstructible_ids: set[int], stats: dict[str, Any]) -> None:
331 """Match this event's vertex candidates (Particles) to MC truth vertices.
332
333 A candidate is matched if both daughters pass the purity cut, belong
334 to different MC tracks, and those come from the same truth vertex.
335 Updates the counters and histograms in ``stats``.
336 """
337 truth = self._truth_vertices(reconstructible_ids)
338 vertex_of = {mc_id: key for key, ids in truth.items() for mc_id in ids}
339 stats["n_truth_vertices"] += len(truth)
340 stats["n_findable_pairs"] += sum(len(self._opposite_pairs(ids)) for ids in truth.values())
341
342 found_vertices: set[tuple] = set()
343 found_pairs: set[frozenset[int]] = set()
344 particles = getattr(self.reco_tree, "Particles", None)
345 for particle in particles if particles is not None else []:
346 stats["n_candidates"] += 1
347 stats["h_doca"].Fill(particle.GetDoca())
348 mc_ids = []
349 for i in range(2):
350 frac, mc_id = self._fracMCsame(particle.GetDaughter(i))
351 if frac >= self.purity_cut:
352 mc_ids.append(mc_id)
353 if len(mc_ids) != 2 or mc_ids[0] == mc_ids[1]:
354 continue
355 key = vertex_of.get(mc_ids[0])
356 pair = frozenset(mc_ids)
357 if key is None or vertex_of.get(mc_ids[1]) != key or pair in found_pairs:
358 continue
359 found_pairs.add(pair)
360 found_vertices.add(key)
361
362 vertex = ROOT.TLorentzVector()
363 particle.ProductionVertex(vertex)
364 stats["h_vtx_dx"].Fill(vertex.X() - key[0])
365 stats["h_vtx_dy"].Fill(vertex.Y() - key[1])
366 stats["h_vtx_dz"].Fill(vertex.Z() - key[2])
367
368 # Pair mass with the masses the reconstruction assumed, against
369 # the true pair mass
370 p_reco = particle.GetMomentum()
371 p_true = ROOT.TLorentzVector()
372 for mc_id in mc_ids:
373 mc_p = ROOT.TLorentzVector()
374 self.sim_tree.MCTrack[mc_id].Get4Momentum(mc_p)
375 p_true += mc_p
376 if p_true.M() > 0:
377 stats["h_mass_rel"].Fill((p_reco.M() - p_true.M()) / p_true.M())
378
379 stats["n_matched_candidates"] += len(found_pairs)
380 stats["n_found_vertices"] += len(found_vertices)
381

◆ _fmt()

str tracking_benchmark.TrackingBenchmark._fmt ( float | None value,
float | None uncertainty,
str fmt = ".4f" )
staticprotected
Format value +/- uncertainty, handling None.

Definition at line 796 of file tracking_benchmark.py.

796 def _fmt(value: float | None, uncertainty: float | None, fmt: str = ".4f") -> str:
797 """Format value +/- uncertainty, handling None."""
798 if value is None:
799 return "undefined (no data)"
800 if uncertainty is None:
801 return f"{value:{fmt}}"
802 return f"{value:{fmt}} +/- {uncertainty:{fmt}}"
803

◆ _fracMCsame()

tuple[float, int] tracking_benchmark.TrackingBenchmark._fracMCsame ( self,
int reco_track_idx )
protected
Get the hit purity and dominant MC track ID for a reco track.

Uses the Tracklets branch to access hit indices, then checks
which MC track contributed most hits.

Definition at line 206 of file tracking_benchmark.py.

206 def _fracMCsame(self, reco_track_idx: int) -> tuple[float, int]:
207 """Get the hit purity and dominant MC track ID for a reco track.
208
209 Uses the Tracklets branch to access hit indices, then checks
210 which MC track contributed most hits.
211 """
212 tracklet = self.reco_tree.Tracklets[reco_track_idx]
213 hit_indices = tracklet.getList()
214
215 track_counts: dict[int, int] = {}
216 n_hits = 0
217 for idx in hit_indices:
218 point = self.sim_tree.strawtubesPoint[idx]
219 owners = (
220 self._straw_crossers.get(point.GetDetectorID(), {point.GetTrackID()})
221 if self.straw_purity
222 else (point.GetTrackID(),)
223 )
224 for mc_id in owners:
225 track_counts[mc_id] = track_counts.get(mc_id, 0) + 1
226 n_hits += 1
227
228 if not track_counts:
229 return 0.0, -999
230
231 tmax = max(track_counts, key=track_counts.__getitem__)
232 frac = track_counts[tmax] / n_hits if n_hits > 0 else 0.0
233 return frac, tmax
234

◆ _fraction()

dict[str, Any] tracking_benchmark.TrackingBenchmark._fraction ( int k,
int n )
staticprotected

Definition at line 236 of file tracking_benchmark.py.

236 def _fraction(k: int, n: int) -> dict[str, Any]:
237 return {
238 "value": _round_or_none(k / n if n > 0 else None),
239 "uncertainty": _round_or_none(wilson_interval(k, n)),
240 "compare": "statistical",
241 }
242

◆ _get_ptruth_first()

tuple[float, float, float, float] tracking_benchmark.TrackingBenchmark._get_ptruth_first ( self,
int mc_track_id )
protected
Get MC truth momentum at the first straw hit.

Follows the pattern from macro/ShipAna.py:getPtruthFirst().

Definition at line 177 of file tracking_benchmark.py.

177 def _get_ptruth_first(self, mc_track_id: int) -> tuple[float, float, float, float]:
178 """Get MC truth momentum at the first straw hit.
179
180 Follows the pattern from macro/ShipAna.py:getPtruthFirst().
181 """
182 entry = self._straw_index.get(mc_track_id)
183 if entry is None:
184 return -1.0, -1.0, -1.0, -1.0
185 px, py, pz = entry["first"][:3]
186 p = math.sqrt(px**2 + py**2 + pz**2)
187 return p, px, py, pz
188

◆ _get_truth_pos_first()

tuple[float, float, float] tracking_benchmark.TrackingBenchmark._get_truth_pos_first ( self,
int mc_track_id )
protected
Get MC truth position at the first straw hit.

Definition at line 189 of file tracking_benchmark.py.

189 def _get_truth_pos_first(self, mc_track_id: int) -> tuple[float, float, float]:
190 """Get MC truth position at the first straw hit."""
191 entry = self._straw_index.get(mc_track_id)
192 if entry is None:
193 return 0.0, 0.0, 0.0
194 return entry["first"][3:6]
195

◆ _get_truth_slopes()

tuple[float, float] tracking_benchmark.TrackingBenchmark._get_truth_slopes ( self,
int mc_track_id )
protected
Get MC truth track slopes tx=px/pz, ty=py/pz at first straw hit.

Definition at line 196 of file tracking_benchmark.py.

196 def _get_truth_slopes(self, mc_track_id: int) -> tuple[float, float]:
197 """Get MC truth track slopes tx=px/pz, ty=py/pz at first straw hit."""
198 entry = self._straw_index.get(mc_track_id)
199 if entry is None:
200 return 0.0, 0.0
201 px, py, pz = entry["first"][:3]
202 if abs(pz) > 1e-10:
203 return px / pz, py / pz
204 return 0.0, 0.0
205

◆ _is_reconstructible()

bool tracking_benchmark.TrackingBenchmark._is_reconstructible ( self,
int mc_track_id )
protected
Check if an MC particle meets reconstructibility criteria.

A particle is reconstructible if it is charged (and primary, unless
primary_only is False) with hits in >= min_stations tracking stations
and >= min_hits total straw hits.

Definition at line 153 of file tracking_benchmark.py.

153 def _is_reconstructible(self, mc_track_id: int) -> bool:
154 """Check if an MC particle meets reconstructibility criteria.
155
156 A particle is reconstructible if it is charged (and primary, unless
157 primary_only is False) with hits in >= min_stations tracking stations
158 and >= min_hits total straw hits.
159 """
160 mc_track = self.sim_tree.MCTrack[mc_track_id]
161
162 # Must be primary (no mother)
163 if self.primary_only and mc_track.GetMotherId() >= 0:
164 return False
165
166 # Must be charged
167 pdg_code = mc_track.GetPdgCode()
168 if not is_known_particle(pdg_code) or get_particle(pdg_code).Charge() == 0:
169 return False
170
171 # Hit counts come from the per-event straw index (built once per event).
172 entry = self._straw_index.get(mc_track_id)
173 n_hits = entry["n_hits"] if entry else 0
174 n_stations = len(entry["stations"]) if entry else 0
175 return n_hits >= self.min_hits and n_stations >= self.min_stations
176

◆ _opposite_pairs()

list[tuple[int, int]] tracking_benchmark.TrackingBenchmark._opposite_pairs ( self,
list[int] mc_ids )
protected

Definition at line 327 of file tracking_benchmark.py.

327 def _opposite_pairs(self, mc_ids: list[int]) -> list[tuple[int, int]]:
328 return [(a, b) for a, b in combinations(mc_ids, 2) if self._truth_charge(a) * self._truth_charge(b) < 0]
329

◆ _rates()

dict[str, Any] tracking_benchmark.TrackingBenchmark._rates ( self,
dict[str, int] stats )
protected
Efficiency, clone and ghost rates and vertex efficiency of a subset of events.

Definition at line 280 of file tracking_benchmark.py.

280 def _rates(self, stats: dict[str, int]) -> dict[str, Any]:
281 """Efficiency, clone and ghost rates and vertex efficiency of a subset of events."""
282 return {
283 "n_events": {"value": stats["n_events"], "compare": "exact"},
284 "n_reconstructible": {"value": stats["n_reconstructible"], "compare": "exact"},
285 "efficiency": self._fraction(stats["n_matched_mc"], stats["n_reconstructible"]),
286 "clone_rate": self._fraction(stats["n_clone_reco"], stats["n_matched_reco"]),
287 "ghost_rate": self._fraction(stats["n_total_reco"] - stats["n_matched_reco"], stats["n_total_reco"]),
288 "vertex_efficiency": self._fraction(stats["n_found_vertices"], stats["n_truth_vertices"]),
289 }
290

◆ _truth_charge()

float tracking_benchmark.TrackingBenchmark._truth_charge ( self,
int mc_track_id )
protected

Definition at line 309 of file tracking_benchmark.py.

309 def _truth_charge(self, mc_track_id: int) -> float:
310 particle = self.PDG.GetParticle(self.sim_tree.MCTrack[mc_track_id].GetPdgCode())
311 return particle.Charge() / 3.0 if particle else 0.0
312

◆ _truth_vertices()

dict[tuple, list[int]] tracking_benchmark.TrackingBenchmark._truth_vertices ( self,
set[int] reconstructible_ids )
protected
Group reconstructible MC tracks by their production vertex.

Only vertices with at least one opposite-charge pair of
reconstructible tracks are returned, as only those can give a
two-track vertex candidate.

Definition at line 313 of file tracking_benchmark.py.

313 def _truth_vertices(self, reconstructible_ids: set[int]) -> dict[tuple, list[int]]:
314 """Group reconstructible MC tracks by their production vertex.
315
316 Only vertices with at least one opposite-charge pair of
317 reconstructible tracks are returned, as only those can give a
318 two-track vertex candidate.
319 """
320 groups: dict[tuple, list[int]] = defaultdict(list)
321 for mc_id in reconstructible_ids:
322 mc = self.sim_tree.MCTrack[mc_id]
323 key = (round(mc.GetStartX(), 3), round(mc.GetStartY(), 3), round(mc.GetStartZ(), 3))
324 groups[key].append(mc_id)
325 return {key: ids for key, ids in groups.items() if self._opposite_pairs(ids)}
326

◆ _vertex_metrics()

dict[str, Any] tracking_benchmark.TrackingBenchmark._vertex_metrics ( self,
dict[str, Any] stats )
protected

Definition at line 291 of file tracking_benchmark.py.

291 def _vertex_metrics(self, stats: dict[str, Any]) -> dict[str, Any]:
292 self._vertex_histos = {name: stats[name] for name in stats if name.startswith("h_")}
293 return {
294 "n_truth_vertices": {"value": stats["n_truth_vertices"], "compare": "exact"},
295 "n_candidates": {"value": stats["n_candidates"], "compare": "exact"},
296 # truth vertices with at least one matched two-track candidate
297 "vertex_efficiency": self._fraction(stats["n_found_vertices"], stats["n_truth_vertices"]),
298 # opposite-charge pairs of reconstructible tracks with a candidate
299 "pair_efficiency": self._fraction(stats["n_matched_candidates"], stats["n_findable_pairs"]),
300 # candidates that are not a distinct true pair: fakes and duplicates
301 "fake_rate": self._fraction(stats["n_candidates"] - stats["n_matched_candidates"], stats["n_candidates"]),
302 "vertex_dx_width": self._width(stats["h_vtx_dx"]),
303 "vertex_dy_width": self._width(stats["h_vtx_dy"]),
304 "vertex_dz_width": self._width(stats["h_vtx_dz"]),
305 "mass_rel_width": self._width(stats["h_mass_rel"]),
306 "doca": self._width(stats["h_doca"]),
307 }
308

◆ _width()

dict[str, Any] tracking_benchmark.TrackingBenchmark._width ( histogram,
int n_replicas = 200 )
staticprotected
Half-width of the central 68% of a distribution, robust to tails.

The uncertainty is the spread of the half-width over Poisson
replicas of the histogram (a bootstrap of the entries).

Definition at line 244 of file tracking_benchmark.py.

244 def _width(histogram, n_replicas: int = 200) -> dict[str, Any]:
245 """Half-width of the central 68% of a distribution, robust to tails.
246
247 The uncertainty is the spread of the half-width over Poisson
248 replicas of the histogram (a bootstrap of the entries).
249 """
250 if histogram.GetEntries() < 10:
251 return {"value": None, "compare": "statistical"}
252 probabilities = array("d", [0.16, 0.5, 0.84])
253
254 def quantiles(h):
255 q = array("d", [0.0, 0.0, 0.0])
256 h.GetQuantiles(3, q, probabilities)
257 return q
258
259 q = quantiles(histogram)
260 width = (q[2] - q[0]) / 2
261 rng = ROOT.TRandom3(12345)
262 replica = histogram.Clone(f"{histogram.GetName()}_replica")
263 replica.SetDirectory(0)
264 widths = []
265 for _ in range(n_replicas):
266 for i in range(histogram.GetNbinsX() + 2):
267 replica.SetBinContent(i, rng.Poisson(histogram.GetBinContent(i)))
268 r = quantiles(replica)
269 widths.append((r[2] - r[0]) / 2)
270 mean = sum(widths) / n_replicas
271 spread = math.sqrt(sum((w - mean) ** 2 for w in widths) / (n_replicas - 1))
272 return {
273 "value": round(width, 6),
274 "uncertainty": round(spread, 6),
275 "median": round(q[1], 6),
276 "rms": round(histogram.GetRMS(), 6),
277 "compare": "statistical",
278 }
279

◆ compute_metrics()

dict[str, Any] tracking_benchmark.TrackingBenchmark.compute_metrics ( self)
Run the full benchmark analysis over all events.

Returns
-------
dict
    Dictionary of metrics compatible with compare_metrics.py format.

Definition at line 382 of file tracking_benchmark.py.

382 def compute_metrics(self) -> dict[str, Any]:
383 """Run the full benchmark analysis over all events.
384
385 Returns
386 -------
387 dict
388 Dictionary of metrics compatible with compare_metrics.py format.
389 """
390 n_events = self.sim_tree.GetEntries()
391 n_reco_events = self.reco_tree.GetEntries()
392 if n_events != n_reco_events:
393 print(f"WARNING: sim has {n_events} events, reco has {n_reco_events}")
394 n_events = min(n_events, n_reco_events)
395
396 # Book histograms
397 h_dp_over_p = ROOT.TH1D(
398 "h_dp_over_p",
399 "Momentum resolution;(p_{reco} #minus p_{truth}) / p_{truth};Entries",
400 100,
401 -0.5,
402 0.5,
403 )
404 h_dp_vs_p = ROOT.TH2D(
405 "h_dp_vs_p",
406 "Momentum resolution vs p_{truth};p_{truth} [GeV/c];(p_{reco} #minus p_{truth}) / p_{truth}",
407 50,
408 0,
409 120,
410 100,
411 -0.5,
412 0.5,
413 )
414 h_dx = ROOT.TH1D(
415 "h_dx",
416 "x resolution at first hit;x_{reco} #minus x_{truth} [cm];Entries",
417 100,
418 -5.0,
419 5.0,
420 )
421 h_dy = ROOT.TH1D(
422 "h_dy",
423 "y resolution at first hit;y_{reco} #minus y_{truth} [cm];Entries",
424 100,
425 -5.0,
426 5.0,
427 )
428 h_dtx = ROOT.TH1D(
429 "h_dtx",
430 "Slope t_{x} resolution;t_{x,reco} #minus t_{x,truth} (t_{x} = p_{x}/p_{z});Entries",
431 100,
432 -0.01,
433 0.01,
434 )
435 h_dty = ROOT.TH1D(
436 "h_dty",
437 "Slope t_{y} resolution;t_{y,reco} #minus t_{y,truth} (t_{y} = p_{y}/p_{z});Entries",
438 100,
439 -0.01,
440 0.01,
441 )
442 h_hit_residual = ROOT.TH1D(
443 "h_hit_residual",
444 "Unbiased hit residual;drift distance residual [cm];Entries",
445 100,
446 -0.2,
447 0.2,
448 )
449 h_hit_pull = ROOT.TH1D(
450 "h_hit_pull",
451 "Unbiased hit pull;(residual) / #sigma;Entries",
452 100,
453 -5.0,
454 5.0,
455 )
456 h_chi2ndf = ROOT.TH1D("h_chi2ndf", "#chi^{2}/ndf;#chi^{2}/ndf;Entries", 100, 0, 20)
457 h_p_truth = ROOT.TH1D("h_p_truth", "p_{truth} (reconstructible);p [GeV/c];Entries", 50, 0, 120)
458 h_p_matched = ROOT.TH1D("h_p_matched", "p_{truth} (matched);p [GeV/c];Entries", 50, 0, 120)
459 h_p_correct_charge = ROOT.TH1D("h_p_correct_charge", "p_{truth} (correct charge);p [GeV/c];Entries", 50, 0, 120)
460 h_p_wrong_charge = ROOT.TH1D("h_p_wrong_charge", "p_{truth} (wrong charge);p [GeV/c];Entries", 50, 0, 120)
461
462 # Counters
463 n_reconstructible = 0
464 n_matched_mc = 0 # reconstructible MC particles with >= 1 matched reco track
465 n_total_reco = 0
466 n_matched_reco = 0 # reco tracks passing purity cut
467 n_clone_reco = 0 # extra matches beyond the first for same MC particle
468 n_correct_charge = 0
469 n_wrong_charge = 0
470
471 acts_mode = uses_acts(self.reco_tree)
472
473 # Per event multiplicity (number of reconstructible tracks)
474 by_multiplicity: dict[int, dict[str, int]] = defaultdict(lambda: defaultdict(int))
475 vertex_stats: dict[str, Any] = defaultdict(int)
476 vertex_stats["h_vtx_dx"] = ROOT.TH1D("h_vtx_dx", "Vertex x;x_{reco} #minus x_{truth} [cm];Entries", 1000, -5, 5)
477 vertex_stats["h_vtx_dy"] = ROOT.TH1D("h_vtx_dy", "Vertex y;y_{reco} #minus y_{truth} [cm];Entries", 1000, -5, 5)
478 vertex_stats["h_vtx_dz"] = ROOT.TH1D(
479 "h_vtx_dz", "Vertex z;z_{reco} #minus z_{truth} [cm];Entries", 1000, -200, 200
480 )
481 vertex_stats["h_doca"] = ROOT.TH1D("h_doca", "Vertex candidate DOCA;DOCA [cm];Entries", 200, 0, 10)
482 vertex_stats["h_mass_rel"] = ROOT.TH1D(
483 "h_mass_rel", "Pair mass;(m_{reco} #minus m_{truth}) / m_{truth};Entries", 1000, -0.5, 0.5
484 )
485
486 for i_event in range(n_events):
487 self.sim_tree.GetEvent(i_event)
488 self.reco_tree.GetEvent(i_event)
489 self._straw_index = self._build_straw_index()
490 self._straw_crossers = defaultdict(set)
491 for point in self.sim_tree.strawtubesPoint:
492 self._straw_crossers[point.GetDetectorID()].add(point.GetTrackID())
493
494 # Find reconstructible MC particles
495 reconstructible_ids: set[int] = set()
496 n_mc_tracks = len(self.sim_tree.MCTrack)
497 for mc_id in range(n_mc_tracks):
498 if self._is_reconstructible(mc_id):
499 reconstructible_ids.add(mc_id)
500 p_truth, _, _, _ = self._get_ptruth_first(mc_id)
501 if p_truth > 0:
502 h_p_truth.Fill(p_truth)
503
504 n_reconstructible += len(reconstructible_ids)
505 counts_before = (n_matched_mc, n_total_reco, n_matched_reco, n_clone_reco)
506
507 # Match reco tracks to MC
508 reco_tracks = get_tracks(self.reco_tree)
509 n_reco = reco_tracks.size()
510 n_total_reco += n_reco
511
512 # Track which MC particles have been matched in this event
513 matched_mc_this_event: set[int] = set()
514
515 for i_reco in range(n_reco):
516 track = reco_tracks[i_reco]
517 info = track_info(track, acts_mode)
518 if not info.converged:
519 continue
520
521 ndf = info.ndf
522 if ndf <= 0:
523 continue
524 chi2 = info.chi2 / ndf
525 h_chi2ndf.Fill(chi2)
526
527 # Use fitTrack2MC for the MC link (already computed by fracMCsame)
528 mc_id = self.reco_tree.fitTrack2MC[i_reco]
529
530 # Recompute purity to apply our cut
531 frac, dominant_id = self._fracMCsame(i_reco)
532 if self.straw_purity:
533 mc_id = dominant_id
534
535 if frac < self.purity_cut:
536 # Ghost track
537 continue
538
539 n_matched_reco += 1
540
541 if mc_id in reconstructible_ids:
542 if mc_id in matched_mc_this_event:
543 # Clone: don't fill resolution / charge-ID / residuals
544 n_clone_reco += 1
545 continue
546 matched_mc_this_event.add(mc_id)
547
548 # Resolution histograms (use first match only for resolution)
549 p_truth, _, _, _ = self._get_ptruth_first(mc_id)
550 x_t, y_t, _ = self._get_truth_pos_first(mc_id)
551 tx_t, ty_t = self._get_truth_slopes(mc_id)
552
553 if p_truth > 0 and info.mom is not None and info.pos is not None:
554 p_reco = info.mom.Mag()
555
556 dp_over_p = (p_reco - p_truth) / p_truth
557 h_dp_over_p.Fill(dp_over_p)
558 h_dp_vs_p.Fill(p_truth, dp_over_p)
559
560 h_dx.Fill(info.pos.X() - x_t)
561 h_dy.Fill(info.pos.Y() - y_t)
562
563 pz_reco = info.mom.Z()
564 if abs(pz_reco) > 1e-10:
565 tx_reco = info.mom.X() / pz_reco
566 ty_reco = info.mom.Y() / pz_reco
567 h_dtx.Fill(tx_reco - tx_t)
568 h_dty.Fill(ty_reco - ty_t)
569
570 h_p_matched.Fill(p_truth)
571
572 # Charge identification
573 q_reco = track.charge() if acts_mode else track.getFittedState().getCharge()
574 mc_pdg = self.sim_tree.MCTrack[mc_id].GetPdgCode()
575 mc_particle = self.PDG.GetParticle(mc_pdg)
576 if mc_particle:
577 q_truth = mc_particle.Charge() / 3.0
578 if q_reco * q_truth > 0:
579 n_correct_charge += 1
580 h_p_correct_charge.Fill(p_truth)
581 else:
582 n_wrong_charge += 1
583 h_p_wrong_charge.Fill(p_truth)
584
585 # Per-hit unbiased residuals and pulls
586 if acts_mode:
587 for res_val in track.GetResiduals():
588 h_hit_residual.Fill(res_val)
589 for pull_val in track.GetPulls():
590 if pull_val != -999.0:
591 h_hit_pull.Fill(pull_val)
592 else:
593 n_meas = track.getNumPointsWithMeasurement()
594 for i_hit in range(n_meas):
595 try:
596 tp = track.getPointWithMeasurement(i_hit)
597 fitter_info = tp.getFitterInfo()
598 # A point without fitter info gives a null pointer: falsy, but not None.
599 if not fitter_info:
600 continue
601 res = fitter_info.getResidual()
602 # Index 0: 1D residual (straw drift-distance measurement)
603 res_val = res.getState()(0)
604 res_cov = res.getCov()(0, 0)
605 h_hit_residual.Fill(res_val)
606 if res_cov > 0:
607 h_hit_pull.Fill(res_val / math.sqrt(res_cov))
608 except (ROOT.genfit.Exception, AttributeError, IndexError) as e:
609 logger.debug("Skipping hit %d: %s", i_hit, e)
610 continue
611
612 n_matched_mc += len(matched_mc_this_event)
613
614 bin_stats = by_multiplicity[len(reconstructible_ids)]
615 bin_stats["n_events"] += 1
616 bin_stats["n_reconstructible"] += len(reconstructible_ids)
617 counts_after = (n_matched_mc, n_total_reco, n_matched_reco, n_clone_reco)
618 for name, before, after in zip(
619 ("n_matched_mc", "n_total_reco", "n_matched_reco", "n_clone_reco"),
620 counts_before,
621 counts_after,
622 strict=True,
623 ):
624 bin_stats[name] += after - before
625
626 vertices_before = (vertex_stats["n_truth_vertices"], vertex_stats["n_found_vertices"])
627 self._evaluate_vertices(reconstructible_ids, vertex_stats)
628 bin_stats["n_truth_vertices"] += vertex_stats["n_truth_vertices"] - vertices_before[0]
629 bin_stats["n_found_vertices"] += vertex_stats["n_found_vertices"] - vertices_before[1]
630
631 # Compute metrics (None when denominator is zero)
632 n_ghost_reco = n_total_reco - n_matched_reco
633
634 efficiency = n_matched_mc / n_reconstructible if n_reconstructible > 0 else None
635 efficiency_unc = wilson_interval(n_matched_mc, n_reconstructible)
636
637 clone_rate = n_clone_reco / n_matched_reco if n_matched_reco > 0 else None
638 clone_rate_unc = wilson_interval(n_clone_reco, n_matched_reco)
639
640 ghost_rate = n_ghost_reco / n_total_reco if n_total_reco > 0 else None
641 ghost_rate_unc = wilson_interval(n_ghost_reco, n_total_reco)
642
643 # Fit dp/p with Gaussian
644 dp_p_sigma: float | None = None
645 dp_p_sigma_unc: float | None = None
646 if h_dp_over_p.GetEntries() > 0:
647 dp_p_sigma = h_dp_over_p.GetRMS()
648 dp_p_sigma_unc = h_dp_over_p.GetRMSError()
649 if h_dp_over_p.GetEntries() > 20:
650 fit_result = h_dp_over_p.Fit("gaus", "QS")
651 if fit_result and int(fit_result) == 0:
652 dp_p_sigma = fit_result.Parameter(2)
653 dp_p_sigma_unc = fit_result.ParError(2)
654
655 # Charge-ID efficiency
656 n_charge_total = n_correct_charge + n_wrong_charge
657 charge_id_eff = n_correct_charge / n_charge_total if n_charge_total > 0 else None
658 charge_id_eff_unc = wilson_interval(n_correct_charge, n_charge_total)
659
660 # Fit hit pull with Gaussian
661 hit_pull_underflow = int(h_hit_pull.GetBinContent(0))
662 hit_pull_overflow = int(h_hit_pull.GetBinContent(h_hit_pull.GetNbinsX() + 1))
663 if h_hit_pull.GetEntries() > 50:
664 hit_pull_mean = h_hit_pull.GetMean()
665 hit_pull_mean_unc = h_hit_pull.GetMeanError()
666 hit_pull_sigma = h_hit_pull.GetRMS()
667 hit_pull_sigma_unc = h_hit_pull.GetRMSError()
668 pull_fit = h_hit_pull.Fit("gaus", "QS")
669 if pull_fit and int(pull_fit) == 0:
670 hit_pull_mean = pull_fit.Parameter(1)
671 hit_pull_mean_unc = pull_fit.ParError(1)
672 hit_pull_sigma = pull_fit.Parameter(2)
673 hit_pull_sigma_unc = pull_fit.ParError(2)
674 else:
675 hit_pull_mean = math.nan
676 hit_pull_mean_unc = math.nan
677 hit_pull_sigma = math.nan
678 hit_pull_sigma_unc = math.nan
679
680 self.metrics = {
681 "tracking_benchmark": {
682 "n_events": {"value": int(n_events), "compare": "exact"},
683 "n_reconstructible": {"value": int(n_reconstructible), "compare": "exact"},
684 "n_total_reco": {"value": int(n_total_reco), "compare": "exact"},
685 "efficiency": {
686 "value": _round_or_none(efficiency),
687 "uncertainty": _round_or_none(efficiency_unc),
688 "compare": "statistical",
689 },
690 "clone_rate": {
691 "value": _round_or_none(clone_rate),
692 "uncertainty": _round_or_none(clone_rate_unc),
693 "compare": "statistical",
694 },
695 "ghost_rate": {
696 "value": _round_or_none(ghost_rate),
697 "uncertainty": _round_or_none(ghost_rate_unc),
698 "compare": "statistical",
699 },
700 "dp_over_p_sigma": {
701 "value": _round_or_none(dp_p_sigma),
702 "uncertainty": _round_or_none(dp_p_sigma_unc),
703 "compare": "statistical",
704 },
705 "dx_rms": {
706 "value": round(h_dx.GetRMS(), 6),
707 "uncertainty": round(h_dx.GetRMSError(), 6),
708 "compare": "statistical",
709 },
710 "dy_rms": {
711 "value": round(h_dy.GetRMS(), 6),
712 "uncertainty": round(h_dy.GetRMSError(), 6),
713 "compare": "statistical",
714 },
715 "dtx_rms": {
716 "value": round(h_dtx.GetRMS(), 6),
717 "uncertainty": round(h_dtx.GetRMSError(), 6),
718 "compare": "statistical",
719 },
720 "dty_rms": {
721 "value": round(h_dty.GetRMS(), 6),
722 "uncertainty": round(h_dty.GetRMSError(), 6),
723 "compare": "statistical",
724 },
725 "hit_residual_rms": {
726 "value": round(h_hit_residual.GetRMS(), 6),
727 "uncertainty": round(h_hit_residual.GetRMSError(), 6),
728 "compare": "statistical",
729 },
730 "hit_pull_mean": {
731 "value": round(hit_pull_mean, 6),
732 "uncertainty": round(hit_pull_mean_unc, 6),
733 "compare": "statistical",
734 },
735 "hit_pull_sigma": {
736 "value": round(hit_pull_sigma, 6),
737 "uncertainty": round(hit_pull_sigma_unc, 6),
738 "compare": "statistical",
739 },
740 "hit_pull_underflow": {
741 "value": hit_pull_underflow,
742 "compare": "exact",
743 },
744 "hit_pull_overflow": {
745 "value": hit_pull_overflow,
746 "compare": "exact",
747 },
748 "charge_id_efficiency": {
749 "value": _round_or_none(charge_id_eff),
750 "uncertainty": _round_or_none(charge_id_eff_unc),
751 "compare": "statistical",
752 },
753 "n_correct_charge": {"value": int(n_correct_charge), "compare": "exact"},
754 "n_wrong_charge": {"value": int(n_wrong_charge), "compare": "exact"},
755 },
756 "tracking_benchmark_by_multiplicity": {
757 str(multiplicity): self._rates(by_multiplicity[multiplicity])
758 for multiplicity in sorted(by_multiplicity)
759 },
760 "vertexing_benchmark": self._vertex_metrics(vertex_stats),
761 }
762
763 self._histos = {
764 "h_dp_over_p": h_dp_over_p,
765 "h_dp_vs_p": h_dp_vs_p,
766 "h_dx": h_dx,
767 "h_dy": h_dy,
768 "h_dtx": h_dtx,
769 "h_dty": h_dty,
770 "h_hit_residual": h_hit_residual,
771 "h_hit_pull": h_hit_pull,
772 "h_chi2ndf": h_chi2ndf,
773 "h_p_truth": h_p_truth,
774 "h_p_matched": h_p_matched,
775 "h_p_correct_charge": h_p_correct_charge,
776 "h_p_wrong_charge": h_p_wrong_charge,
777 }
778
779 return self.metrics
780

◆ print_summary()

None tracking_benchmark.TrackingBenchmark.print_summary ( self)
Print a human-readable summary of the benchmark results.

Definition at line 804 of file tracking_benchmark.py.

804 def print_summary(self) -> None:
805 """Print a human-readable summary of the benchmark results."""
806 if not self.metrics:
807 print("No metrics computed yet. Call compute_metrics() first.")
808 return
809 m = self.metrics["tracking_benchmark"]
810 fmt = self._fmt
811 print("\n=== Tracking Benchmark Summary ===")
812 print(f" Events: {m['n_events']['value']}")
813 print(f" Reconstructible: {m['n_reconstructible']['value']}")
814 print(f" Total reco: {m['n_total_reco']['value']}")
815 print(f" Efficiency: {fmt(m['efficiency']['value'], m['efficiency']['uncertainty'])}")
816 print(f" Clone rate: {fmt(m['clone_rate']['value'], m['clone_rate']['uncertainty'])}")
817 print(f" Ghost rate: {fmt(m['ghost_rate']['value'], m['ghost_rate']['uncertainty'])}")
818 print(f" dp/p sigma: {fmt(m['dp_over_p_sigma']['value'], m['dp_over_p_sigma']['uncertainty'], '.6f')}")
819 print(f" dx RMS: {fmt(m['dx_rms']['value'], m['dx_rms']['uncertainty'])} cm")
820 print(f" dy RMS: {fmt(m['dy_rms']['value'], m['dy_rms']['uncertainty'])} cm")
821 print(f" dtx RMS: {fmt(m['dtx_rms']['value'], m['dtx_rms']['uncertainty'], '.6f')}")
822 print(f" dty RMS: {fmt(m['dty_rms']['value'], m['dty_rms']['uncertainty'], '.6f')}")
823 print(
824 f" Hit resid RMS: {fmt(m['hit_residual_rms']['value'], m['hit_residual_rms']['uncertainty'], '.6f')} cm"
825 )
826 print(f" Hit pull mean: {fmt(m['hit_pull_mean']['value'], m['hit_pull_mean']['uncertainty'])}")
827 print(f" Hit pull sigma: {fmt(m['hit_pull_sigma']['value'], m['hit_pull_sigma']['uncertainty'])}")
828 print(
829 f" Charge-ID eff: {fmt(m['charge_id_efficiency']['value'], m['charge_id_efficiency']['uncertainty'])}"
830 )
831 print(f" Correct/wrong: {m['n_correct_charge']['value']}/{m['n_wrong_charge']['value']}")
832 v = self.metrics["vertexing_benchmark"]
833 print(f" Truth vertices: {v['n_truth_vertices']['value']} (candidates: {v['n_candidates']['value']})")
834 for name in ("vertex_efficiency", "pair_efficiency", "fake_rate"):
835 print(f" {name + ':':18}{fmt(v[name]['value'], v[name]['uncertainty'])}")
836 for name in ("vertex_dx_width", "vertex_dy_width", "vertex_dz_width", "mass_rel_width", "doca"):
837 print(f" {name + ':':18}{v[name]['value']}")
838 print(" By multiplicity (efficiency, ghost rate, vertex efficiency):")
839 for multiplicity, b in self.metrics["tracking_benchmark_by_multiplicity"].items():
840 print(
841 f" {multiplicity:>3} tracks, {b['n_events']['value']:>5} events: "
842 f"{fmt(b['efficiency']['value'], b['efficiency']['uncertainty'], '.3f')}, "
843 f"{fmt(b['ghost_rate']['value'], b['ghost_rate']['uncertainty'], '.3f')}, "
844 f"{fmt(b['vertex_efficiency']['value'], b['vertex_efficiency']['uncertainty'], '.3f')}"
845 )
846 print("==================================\n")
847

◆ save_histograms()

None tracking_benchmark.TrackingBenchmark.save_histograms ( self,
str output_path )
Save detailed histograms to a ROOT file.

Definition at line 787 of file tracking_benchmark.py.

787 def save_histograms(self, output_path: str) -> None:
788 """Save detailed histograms to a ROOT file."""
789 f_out = ROOT.TFile.Open(output_path, "recreate")
790 for name, hist in {**self._histos, **getattr(self, "_vertex_histos", {})}.items():
791 hist.Write(name)
792 f_out.Close()
793 print(f"Histograms saved to {output_path}")
794

◆ save_json()

None tracking_benchmark.TrackingBenchmark.save_json ( self,
str output_path )
Save metrics to JSON file.

Definition at line 781 of file tracking_benchmark.py.

781 def save_json(self, output_path: str) -> None:
782 """Save metrics to JSON file."""
783 with open(output_path, "w") as f:
784 json.dump(self.metrics, f, indent=2)
785 print(f"Metrics saved to {output_path}")
786

Member Data Documentation

◆ _histos

tracking_benchmark.TrackingBenchmark._histos = {}
protected

Definition at line 118 of file tracking_benchmark.py.

◆ _straw_crossers

dict tracking_benchmark.TrackingBenchmark._straw_crossers = {}
protected

Definition at line 105 of file tracking_benchmark.py.

◆ _straw_index

dict tracking_benchmark.TrackingBenchmark._straw_index = {}
protected

Definition at line 120 of file tracking_benchmark.py.

◆ _vertex_histos

dict tracking_benchmark.TrackingBenchmark._vertex_histos = {name: stats[name] for name in stats if name.startswith("h_")}
protected

Definition at line 292 of file tracking_benchmark.py.

◆ f_geo

tracking_benchmark.TrackingBenchmark.f_geo = ROOT.TFile.Open(geo_file, "read")

Definition at line 113 of file tracking_benchmark.py.

◆ f_reco

tracking_benchmark.TrackingBenchmark.f_reco = ROOT.TFile.Open(reco_file, "read")

Definition at line 110 of file tracking_benchmark.py.

◆ f_sim

tracking_benchmark.TrackingBenchmark.f_sim = ROOT.TFile.Open(sim_file, "read")

Definition at line 107 of file tracking_benchmark.py.

◆ metrics

tracking_benchmark.TrackingBenchmark.metrics = {}

Definition at line 117 of file tracking_benchmark.py.

◆ min_hits

tracking_benchmark.TrackingBenchmark.min_hits = min_hits

Definition at line 100 of file tracking_benchmark.py.

◆ min_stations

tracking_benchmark.TrackingBenchmark.min_stations = min_stations

Definition at line 101 of file tracking_benchmark.py.

◆ PDG

tracking_benchmark.TrackingBenchmark.PDG = ROOT.TDatabasePDG.Instance()

Definition at line 115 of file tracking_benchmark.py.

◆ primary_only

tracking_benchmark.TrackingBenchmark.primary_only = primary_only

Definition at line 102 of file tracking_benchmark.py.

◆ purity_cut

tracking_benchmark.TrackingBenchmark.purity_cut = purity_cut

Definition at line 99 of file tracking_benchmark.py.

◆ reco_tree

tracking_benchmark.TrackingBenchmark.reco_tree = self.f_reco["ship_reco_sim"]

Definition at line 111 of file tracking_benchmark.py.

◆ sim_tree

tracking_benchmark.TrackingBenchmark.sim_tree = self.f_sim["cbmsim"]

Definition at line 108 of file tracking_benchmark.py.

◆ straw_purity

tracking_benchmark.TrackingBenchmark.straw_purity = straw_purity

Definition at line 103 of file tracking_benchmark.py.


The documentation for this class was generated from the following file: