Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-11-25 09:09:17

0001 #!/usr/bin/env python3
0002 """Truth-matched K0S -> pi+ pi- performance of a secondary vertex collection.
0003 
0004 A K0S counts as reconstructable if both of its pions are the best (highest-weight) MC match of
0005 some reconstructed track, and as found if a two-track secondary vertex contains exactly those two
0006 tracks. The output figure has three panels:
0007   1. vertex-finding efficiency (found / reconstructable) vs. true decay radius
0008   2. invariant mass of all two-track vertices with chi2/ndf < 3 and r > 2 mm (no truth used)
0009   3. invariant mass of the truth-matched (found) K0S vertices
0010 """
0011 
0012 import argparse
0013 
0014 import awkward as ak
0015 import matplotlib.pyplot as plt
0016 import numpy as np
0017 import uproot
0018 
0019 K0S_MASS = 0.4976  # GeV
0020 RADIUS_BINS = np.array([0, 2, 5, 10, 20, 50, 100, 200, 500])  # mm
0021 MASS_BINS = np.linspace(0.2, 1.0, 41)  # GeV
0022 
0023 
0024 def best_mc_match(rec, sim, weight):
0025     """Map each reconstructed track index to its highest-weight MC particle index."""
0026     best = {}
0027     for r, s, w in zip(rec, sim, weight):
0028         if r not in best or w > best[r][1]:
0029             best[r] = (s, w)
0030     return {r: s for r, (s, w) in best.items()}
0031 
0032 
0033 def process_file(path, vertices_collection, result):
0034     V = vertices_collection
0035     R = "ReconstructedChargedParticles"
0036     A = "ReconstructedChargedParticleAssociations"
0037     P = "MCParticles"
0038     branches = {
0039         "pdg": f"{P}/{P}.PDG",
0040         "end_x": f"{P}/{P}.endpoint.x",
0041         "end_y": f"{P}/{P}.endpoint.y",
0042         "dau_begin": f"{P}/{P}.daughters_begin",
0043         "dau_end": f"{P}/{P}.daughters_end",
0044         "dau_index": f"_{P}_daughters/_{P}_daughters.index",
0045         "px": f"{R}/{R}.momentum.x",
0046         "py": f"{R}/{R}.momentum.y",
0047         "pz": f"{R}/{R}.momentum.z",
0048         "energy": f"{R}/{R}.energy",
0049         "assoc_rec": f"_{A}_rec/_{A}_rec.index",
0050         "assoc_sim": f"_{A}_sim/_{A}_sim.index",
0051         "assoc_weight": f"{A}/{A}.weight",
0052         "vtx_x": f"{V}/{V}.position.x",
0053         "vtx_y": f"{V}/{V}.position.y",
0054         "vtx_chi2": f"{V}/{V}.chi2",
0055         "vtx_ndf": f"{V}/{V}.ndf",
0056         "vtx_begin": f"{V}/{V}.associatedParticles_begin",
0057         "vtx_end": f"{V}/{V}.associatedParticles_end",
0058         "vtx_index": f"_{V}_associatedParticles/_{V}_associatedParticles.index",
0059     }
0060     tree = uproot.open(path)["events"]
0061     arrays = tree.arrays(list(branches.values()), library="ak")
0062     events = {name: ak.to_list(arrays[branch]) for name, branch in branches.items()}
0063 
0064     for ev in range(len(events["pdg"])):
0065         e = {name: values[ev] for name, values in events.items()}
0066         rec_to_mc = best_mc_match(e["assoc_rec"], e["assoc_sim"], e["assoc_weight"])
0067         matched_mc = set(rec_to_mc.values())
0068 
0069         # Truth K0S -> pi+ pi-, keyed by the (unordered) pair of pion MC indices
0070         k0s = {}
0071         for i, pdg in enumerate(e["pdg"]):
0072             if pdg != 310:
0073                 continue
0074             daughters = e["dau_index"][e["dau_begin"][i]:e["dau_end"][i]]
0075             if len(daughters) == 2 and all(abs(e["pdg"][j]) == 211 for j in daughters):
0076                 r_true = np.hypot(e["end_x"][i], e["end_y"][i])
0077                 if all(j in matched_mc for j in daughters):
0078                     k0s[frozenset(daughters)] = r_true
0079                     result["reconstructable_r"].append(r_true)
0080 
0081         px, py, pz, energy = e["px"], e["py"], e["pz"], e["energy"]
0082         found = set()
0083         for v in range(len(e["vtx_x"])):
0084             tracks = e["vtx_index"][e["vtx_begin"][v]:e["vtx_end"][v]]
0085             if len(tracks) != 2:
0086                 continue
0087             # Vertices reference ReconstructedParticles, which MatchClusters fills with a copy of
0088             # ReconstructedChargedParticles first, in the same order, so the indices coincide
0089             t1, t2 = tracks
0090             if max(t1, t2) >= len(energy):
0091                 continue
0092             mass2 = ((energy[t1] + energy[t2]) ** 2 - (px[t1] + px[t2]) ** 2
0093                      - (py[t1] + py[t2]) ** 2 - (pz[t1] + pz[t2]) ** 2)
0094             mass = np.sqrt(max(mass2, 0))
0095             r_vtx = np.hypot(e["vtx_x"][v], e["vtx_y"][v])
0096             chi2_ndf = e["vtx_chi2"][v] / (e["vtx_ndf"][v] + 1e-10)  # as in invariant_mass.py
0097             if chi2_ndf < 3 and r_vtx > 2:
0098                 result["displaced_mass"].append(mass)
0099 
0100             pair = frozenset((rec_to_mc.get(t1), rec_to_mc.get(t2)))
0101             if pair in k0s and pair not in found:
0102                 found.add(pair)
0103                 result["found_r"].append(k0s[pair])
0104                 result["found_mass"].append(mass)
0105 
0106 
0107 def main():
0108     parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
0109     parser.add_argument("--input", "-i", nargs="+", required=True, help="Input edm4eic ROOT file(s)")
0110     parser.add_argument("--output", "-o", required=True, help="Output plot filename")
0111     parser.add_argument("--vertices-collection", default="SecondaryVerticesAMVF",
0112                         help="Name of the vertices collection (default: SecondaryVerticesAMVF)")
0113     args = parser.parse_args()
0114 
0115     result = {"reconstructable_r": [], "found_r": [], "found_mass": [], "displaced_mass": []}
0116     for path in args.input:
0117         print(f"Loading {path}...")
0118         process_file(path, args.vertices_collection, result)
0119     result = {name: np.array(values) for name, values in result.items()}
0120 
0121     n_reco, _ = np.histogram(result["reconstructable_r"], RADIUS_BINS)
0122     n_found, _ = np.histogram(result["found_r"], RADIUS_BINS)
0123     print(f"\n=== K0S -> pi+ pi- found in {args.vertices_collection} ===")
0124     print(f"{'true r [mm]':>14} {'found':>6} / {'reco':<6} efficiency")
0125     for lo, hi, k, n in zip(RADIUS_BINS[:-1], RADIUS_BINS[1:], n_found, n_reco):
0126         eff = f"{k / n:.0%}" if n else "-"
0127         print(f"{f'[{lo}, {hi})':>14} {k:>6} / {n:<6} {eff}")
0128     print(f"{'total':>14} {len(result['found_r']):>6} / {len(result['reconstructable_r']):<6}")
0129 
0130     fig, axs = plt.subplots(1, 3, figsize=(18, 5))
0131 
0132     has = n_reco > 0
0133     eff = np.divide(n_found, n_reco, out=np.zeros(len(n_reco)), where=has)
0134     err = np.sqrt(np.divide(eff * (1 - eff), n_reco, out=np.zeros(len(n_reco)), where=has))
0135     centers = 0.5 * (RADIUS_BINS[1:] + RADIUS_BINS[:-1])
0136     axs[0].errorbar(centers[has], eff[has], yerr=err[has], xerr=0.5 * np.diff(RADIUS_BINS)[has], fmt="o")
0137     axs[0].set(xscale="symlog", xlim=(0, RADIUS_BINS[-1]), ylim=(0, 1.05),
0138                xlabel="True K⁰_S decay radius [mm]", ylabel="Vertex-finding efficiency",
0139                title=f"K⁰_S (both pions reconstructed) found in {args.vertices_collection}")
0140 
0141     axs[1].hist(result["displaced_mass"], bins=MASS_BINS, histtype="step", linewidth=2)
0142     axs[1].set(xlabel="Invariant mass [GeV]", ylabel="Vertices",
0143                title=f"{args.vertices_collection}: χ²/ndf < 3, r > 2 mm")
0144 
0145     axs[2].hist(result["found_mass"], bins=MASS_BINS, histtype="step", linewidth=2)
0146     axs[2].set(xlabel="Invariant mass [GeV]", ylabel="Vertices", title="Truth-matched K⁰_S vertices")
0147 
0148     for ax in axs[1:]:
0149         ax.axvline(K0S_MASS, color="red", linestyle="--", label="K⁰_S")
0150         ax.legend()
0151 
0152     plt.tight_layout()
0153     plt.savefig(args.output, dpi=150, bbox_inches="tight")
0154     print(f"Plot saved to {args.output}")
0155 
0156 
0157 if __name__ == "__main__":
0158     main()