Skip to content

Commit 831d6aa

Browse files
committed
GenericTracking: add initial TOF matching efficiency diagnostics
Add a frozen-input study using reconstructed GTRK states, source-0 TOF transport hits quantized to pixels, 20 ps timing and TGeo material. Separate hit availability, correct associations, purity, candidate gates and assignment losses. Keep truth out of matching decisions and document sampled-track competition and the missing digitization/merging model. Add a single-timeframe coverage analysis with pT plots and preserve initial controlled-study counts in the documentation.
1 parent 1c16ab0 commit 831d6aa

4 files changed

Lines changed: 560 additions & 1 deletion

File tree

‎Detectors/GenericTracking/tof/CMakeLists.txt‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,11 @@ o2_add_test(tof-matching SOURCES test/testTOFMatching.cxx COMPONENT_NAME generic
2424
if(testTarget)
2525
target_include_directories(${testTarget} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../tracking/test)
2626
endif()
27+
28+
# Frozen tracking inputs and transported TOF hits, for an initial diagnostic.
29+
# GTrkStudy is declared later by GenericTracking's parent CMakeLists.
30+
o2_add_executable(tof-hit-study
31+
SOURCES study/tofHitStudy.cxx
32+
COMPONENT_NAME gtrk
33+
PUBLIC_LINK_LIBRARIES O2::GTrkTOF O2::GTrkStudy O2::ITSMFTSimulation
34+
Boost::program_options ROOT::RIO ROOT::Tree)

‎Detectors/GenericTracking/tof/README.md‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ Outer spatial matching starts from the outward fit; inner matching starts from
4242
the inward fit. Flight-time derivatives with respect to the inward state give
4343
the shared track error. This correlation is included in the inner/outer timing
4444
gate and in the combined time, rather than counting it twice as independent
45-
noise. No TOF spatial measurement is added to the tracker fit.
45+
noise. Active-area acceptance is checked by the spatial prediction. The
46+
independent trajectory used to integrate flight time may cross the same plane
47+
outside the chip; it does not apply a second active-area veto. No TOF spatial
48+
measurement is added to the tracker fit.
4649

4750
## Inputs and running
4851

@@ -122,3 +125,64 @@ Pile-up MC studies of matching efficiency, purity and time pulls, cut tuning,
122125
material-step convergence on real tracks, and indexing performance remain
123126
necessary before production use. Synthetic and geometry tests do not establish
124127
those results.
128+
129+
## Initial efficiency studies
130+
131+
`study/tofCoverage.py` joins a single timeframe's tracking QA with a source's
132+
TF3 transport hits by source/event/track identity. It reports hit availability
133+
among good, non-clone, valid refits, with generated pT/eta cuts and a separate
134+
physical-primary selection. It rejects multi-timeframe QA files and duplicate
135+
identities. This is a denominator/reach check, not matching efficiency.
136+
Supply the chip partition from the production's TOF geometry; do not infer it
137+
from a different layout. It writes a per-track CSV, a JSON summary and pT plots.
138+
The Python requirements are numpy, uproot and matplotlib (no awkward needed).
139+
140+
`o2-gtrk-tof-hit-study` reruns GTRK on a frozen tracking-input dump and samples
141+
unique good physical-primary tracks using a fixed seed. It converts all
142+
source-0 TOF transport hits into single-pixel measurements, adds 20 ps Gaussian
143+
timing, and runs the actual three-pass matcher with TGeo material queries. The
144+
tracker retains its original LUT and configuration. All source-0 hit clutter
145+
is present; reconstructed-track competition is limited to the sampled tracks.
146+
It does not model detection efficiency, multi-pixel response or cluster merging,
147+
and therefore is not a digitized-cluster efficiency measurement.
148+
149+
```sh
150+
o2-gtrk-tof-hit-study --input TRK_tf1.input \
151+
--geometry o2sim_geometry-aligned.root --tracking-material tracker_matlut.root \
152+
--tof-hits sgn_HitsTF3.root --context collisioncontext.root \
153+
--max-tracks 100 --min-pt 0.5 --max-abs-eta 1 --output study/probe
154+
```
155+
156+
Keep `.ini` and `.truth` beside the frozen input. Set `ALICE3_MAGFIELD_MACRO`
157+
to the production's field, and `--first-orbit` to the timeframe anchor.
158+
Source events reused in several collision occurrences are explicitly rejected.
159+
The default 100 ns hit-time preselection is an additional study selection;
160+
correct hits excluded by it are counted and cause a nonzero study status.
161+
The default kinematic selection is intended for an initial barrel probe.
162+
163+
The denominator for each layer is sampled reconstructed tracks with at least
164+
one usable measurement of their own MC particle in that layer. Correct matches,
165+
wrong matches and purity are separate. The guided-inner denominator is tracks
166+
with a correct outer association and an available inner measurement. The CSV
167+
keeps each truth identity and the per-track decisions. Correct-hit propagation,
168+
mean position inside active bounds, covariance transport, spatial chi2 and
169+
coarse-time compatibility are also tested after matching, independently of
170+
cluster ownership, to distinguish transport/gate losses from assignment losses.
171+
These diagnostic gates use the forward crossing for the selected primary sample.
172+
173+
Before quoting production efficiency, repeat with digitized TF3 clusters and
174+
labels, all reconstructed competitors, representative pile-up and held-out
175+
samples, and validate time pulls at the explicitly defined track reference.
176+
177+
An initial local pp-TF check used 100 fixed-seed sampled primary refits out of
178+
11,138 eligible reconstructed particles, generated pT >= 0.5 GeV/c and |eta| < 1,
179+
with 243,605 usable synthetic measurements from 264,401 transported hits.
180+
On identical inputs, removing the second chip-bounds veto from the independent
181+
flight-time projection changed correct outer associations from 63/89 to 78/89:
182+
15 recovered identities, none lost. Correct inner associations stayed 90/97,
183+
with one wrong inner association and no wrong outer association observed.
184+
The guided-inner result was 73/77; the remaining-track pass found 17/20.
185+
Outer losses after this fix were six spatial means outside active bounds,
186+
four spatial-chi2 rejections and one flight/coarse-time rejection. These are
187+
small-sample diagnostic results under the approximations above, not production
188+
efficiencies or tuned defaults.
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
#!/usr/bin/env python3
2+
# Copyright 2019-2026 CERN and copyright holders of ALICE O2.
3+
# See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
4+
# SPDX-License-Identifier: GPL-3.0-only
5+
"""Truth-hit availability among reconstructed tracks, before testing a matcher.
6+
7+
One QA timeframe and its source's TF3 transport hits. This measures availability,
8+
not matching efficiency or digitization efficiency. Source/event/track identity
9+
is mandatory: a hit in another event does not make a track eligible.
10+
"""
11+
import argparse
12+
import csv
13+
import json
14+
from pathlib import Path
15+
import subprocess
16+
17+
import numpy as np
18+
import uproot
19+
20+
21+
def interval(numerator, denominator):
22+
if denominator == 0:
23+
return {"fraction": None, "low": None, "high": None}
24+
value = numerator / denominator
25+
# Wilson interval with z=1 (approximately 68% coverage).
26+
centre = (value + 0.5 / denominator) / (1.0 + 1.0 / denominator)
27+
half = np.sqrt(value * (1.0 - value) / denominator + 0.25 / denominator**2) / (1.0 + 1.0 / denominator)
28+
return {"fraction": value, "low": float(centre - half), "high": float(centre + half)}
29+
30+
31+
def main():
32+
parser = argparse.ArgumentParser(description=__doc__)
33+
parser.add_argument("--qa", type=Path, required=True)
34+
parser.add_argument("--tof-hits", type=Path, required=True)
35+
parser.add_argument("--first-outer-chip", type=int, required=True, help="from this simulation's TOF GeometryTGeo")
36+
parser.add_argument("--total-chips", type=int, required=True)
37+
parser.add_argument("--source", type=int, default=0, help="MC source corresponding to --tof-hits")
38+
parser.add_argument("--min-pt", type=float, default=0.1)
39+
parser.add_argument("--max-abs-eta", type=float, default=1.0)
40+
parser.add_argument("--include-secondaries", action="store_true")
41+
parser.add_argument("--output", type=Path, required=True, help="output filename prefix")
42+
args = parser.parse_args()
43+
if not 0 < args.first_outer_chip < args.total_chips or not 0 <= args.source < 256:
44+
parser.error("invalid chip partition or source")
45+
with uproot.open(args.qa) as qa:
46+
if qa["run"].num_entries != 1:
47+
parser.error("provide exactly one QA timeframe: MC identities repeat between timeframes")
48+
tracks = qa["tracks"].arrays(library="np")
49+
with uproot.open(args.tof_hits) as tof:
50+
tree = tof["o2sim"]
51+
track_ids = tree["TF3Hit.mTrackID"].array(library="np")
52+
chips = tree["TF3Hit.mDetectorID"].array(library="np")
53+
inner, outer = set(), set()
54+
hit_rows = 0
55+
for event, (ids, sensors) in enumerate(zip(track_ids, chips)):
56+
if len(ids) != len(sensors):
57+
raise ValueError("inconsistent hit columns")
58+
if np.any(sensors < 0) or np.any(sensors >= args.total_chips):
59+
raise ValueError("hit sensor outside the declared barrel geometry")
60+
for track_id, chip in zip(ids, sensors):
61+
if track_id < 0:
62+
continue
63+
identity = int(track_id) | (event << 31) | (args.source << 50)
64+
(inner if chip < args.first_outer_chip else outer).add(identity)
65+
hit_rows += 1
66+
ids = tracks["mcParticle"]
67+
selected = (~tracks["fake"].astype(bool) & ~tracks["clone"].astype(bool) & tracks["fitValid"].astype(bool) &
68+
(tracks["ptGen"] >= args.min_pt) & (np.abs(tracks["etaGen"]) < args.max_abs_eta) &
69+
(((ids >> np.uint64(50)) & np.uint64(255)) == args.source))
70+
if not args.include_secondaries:
71+
selected &= tracks["origin"] == 0 # TrackingQA::ParticleOrigin::kPhysicalPrimary
72+
identities = ids[selected]
73+
if len(np.unique(identities)) != len(identities):
74+
raise ValueError("duplicate identities remain after excluding clones")
75+
selected_pt = tracks["ptGen"][selected]
76+
selected_eta = tracks["etaGen"][selected]
77+
has_inner = np.array([int(identity) in inner for identity in identities], dtype=bool)
78+
has_outer = np.array([int(identity) in outer for identity in identities], dtype=bool)
79+
counts = {"selected_tracks": len(identities), "inner": int(has_inner.sum()), "outer": int(has_outer.sum()),
80+
"both": int((has_inner & has_outer).sum()), "inner_only": int((has_inner & ~has_outer).sum()),
81+
"outer_only": int((~has_inner & has_outer).sum()), "neither": int((~has_inner & ~has_outer).sum())}
82+
pt_edges = np.array([0.1, 0.2, 0.3, 0.5, 0.7, 1.0, 2.0, 5.0, 10.0, np.inf])
83+
bins = []
84+
for low, high in zip(pt_edges[:-1], pt_edges[1:]):
85+
mask = (selected_pt >= low) & (selected_pt < high)
86+
den = int(mask.sum())
87+
row = {"pt_low": float(low), "pt_high": None if np.isinf(high) else float(high), "denominator": den}
88+
for name, available in [("inner", has_inner), ("outer", has_outer), ("both", has_inner & has_outer)]:
89+
num = int((mask & available).sum())
90+
row[name] = {"numerator": num, **interval(num, den)}
91+
bins.append(row)
92+
report = {"kind": "TOF transport-hit availability, NOT matching efficiency",
93+
"inputs": {"qa": str(args.qa.resolve()), "tof_hits": str(args.tof_hits.resolve())},
94+
"source_revision": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(),
95+
"selection": {"min_generated_pt_GeV": args.min_pt, "max_abs_generated_eta": args.max_abs_eta,
96+
"physical_primaries_only": not args.include_secondaries,
97+
"tracking": "good, non-clone, valid refit", "source": args.source},
98+
"geometry": {"first_outer_chip": args.first_outer_chip, "total_barrel_chips": args.total_chips},
99+
"events": len(track_ids), "hit_rows": hit_rows, "input_reconstructed_tracks": len(ids),
100+
"counts": counts, "pt_bins": bins}
101+
args.output.parent.mkdir(parents=True, exist_ok=True)
102+
Path(str(args.output) + ".json").write_text(json.dumps(report, indent=2) + "\n")
103+
with Path(str(args.output) + ".csv").open("w", newline="") as stream:
104+
writer = csv.writer(stream)
105+
writer.writerow(["mc_particle", "pt_gen_GeV", "eta_gen", "inner_hit", "outer_hit"])
106+
writer.writerows(zip(identities, selected_pt, selected_eta, has_inner, has_outer))
107+
import matplotlib
108+
matplotlib.use("Agg")
109+
import matplotlib.pyplot as plt
110+
fig, ax = plt.subplots(figsize=(7, 4.5))
111+
for name, label in [("inner", "Inner TOF"), ("outer", "Outer TOF"), ("both", "Both")]:
112+
finite = [b for b in bins if b["pt_high"] is not None and b["denominator"]]
113+
x = [np.sqrt(b["pt_low"] * b["pt_high"]) for b in finite]
114+
y = [b[name]["fraction"] for b in finite]
115+
error = [[b[name]["fraction"] - b[name]["low"] for b in finite], [b[name]["high"] - b[name]["fraction"] for b in finite]]
116+
ax.errorbar(x, y, yerr=error, marker="o", capsize=2, label=label)
117+
ax.set(xscale="log", ylim=(0, 1.05), xlabel="Generated pT [GeV/c]", ylabel="Fraction with a TOF transport hit",
118+
title="TOF hit availability among reconstructed tracks")
119+
ax.text(0.02, 0.03, f"Good unique refits; |eta(gen)| < {args.max_abs_eta}; transport hits\nNot a matching-efficiency measurement", transform=ax.transAxes, fontsize=9)
120+
ax.grid(alpha=0.25)
121+
ax.legend()
122+
fig.tight_layout()
123+
fig.savefig(str(args.output) + ".png", dpi=160)
124+
fig.savefig(str(args.output) + ".pdf")
125+
print(json.dumps(counts, indent=2))
126+
127+
128+
if __name__ == "__main__":
129+
main()

0 commit comments

Comments
 (0)