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