File indexing completed on 2026-11-25 09:09:12
0001 """EEEMCal reconstructed-cluster versus truth-cluster agreement.
0002
0003 The same event analysis supports electron particle guns and DIS. Particle-gun
0004 events use MCParticles[0] and the highest-energy reconstructed cluster. DIS
0005 events select the backward status-1 electron with the most negative pz from
0006 MCScatteredElectrons and spatially match the nearest reconstructed cluster.
0007
0008 Residuals are filled only when the reference electron has exactly one
0009 associated truth cluster. Truth-cluster multiplicity and energy fragmentation
0010 are saved for every selected electron, so events with split truth clusters are
0011 not silently discarded. These residuals measure reco--truth-cluster agreement,
0012 not an independent intrinsic calorimeter resolution.
0013 """
0014
0015 import argparse
0016 import json
0017 from pathlib import Path
0018
0019 import awkward as ak
0020 import matplotlib
0021 import numpy as np
0022 import uproot
0023
0024 matplotlib.use("Agg")
0025 import matplotlib.pyplot as plt
0026
0027
0028 ENERGIES = (
0029 "100MeV", "200MeV", "500MeV", "1GeV",
0030 "2GeV", "5GeV", "10GeV", "20GeV",
0031 )
0032 RECO = "EcalEndcapNClusters"
0033 TRUTH = "EcalEndcapNTruthClusters"
0034 ASSOC = "_EcalEndcapNTruthClusterAssociations"
0035 ETA_MIN = -3.5
0036 ETA_MAX = -2.0
0037
0038
0039 def read_file_list(path):
0040 paths = [
0041 line.strip()
0042 for line in Path(path).read_text().splitlines()
0043 if line.strip() and not line.lstrip().startswith("#")
0044 ]
0045 if not paths:
0046 raise ValueError(f"No input files in {path}")
0047 return paths
0048
0049
0050 def reference_electron(event, sample_type):
0051 """Return (MCParticles index, eta, raw candidates, accepted candidates)."""
0052 if sample_type == "particle-gun":
0053 candidates = [0] if len(event["MCParticles.momentum.x"]) else []
0054 else:
0055 candidates = [
0056 int(index)
0057 for index in ak.to_list(event["MCScatteredElectrons_objIdx.index"])
0058 ]
0059
0060 size = len(event["MCParticles.momentum.x"])
0061 if any(index < 0 or index >= size for index in candidates):
0062 raise ValueError("Scattered-electron relation points outside MCParticles")
0063
0064 accepted = []
0065 for index in candidates:
0066 px, py, pz = (
0067 float(event[f"MCParticles.momentum.{axis}"][index]) for axis in "xyz"
0068 )
0069 pt = np.hypot(px, py)
0070 eta = np.arcsinh(pz / pt) if pt > 0 else np.nan
0071 if ETA_MIN < eta < ETA_MAX:
0072 accepted.append((pz, index, eta))
0073 if not accepted:
0074 return None, None, len(candidates), 0
0075
0076
0077 _, index, eta = min(accepted)
0078 return index, eta, len(candidates), len(accepted)
0079
0080
0081 def associated_truth_indices(event, particle_index):
0082 rec = ak.to_list(event[f"{ASSOC}_rec.index"])
0083 sim = ak.to_list(event[f"{ASSOC}_sim.index"])
0084 if len(rec) != len(sim):
0085 raise ValueError("Truth association rec/sim arrays differ in length")
0086 result = sorted({int(r) for r, s in zip(rec, sim) if int(s) == particle_index})
0087 if any(index < 0 or index >= len(event[f"{TRUTH}.energy"]) for index in result):
0088 raise ValueError("Truth association refers to an invalid cluster")
0089 return result
0090
0091
0092 def select_reco_cluster(event, truth_index, sample_type, match_radius_mm):
0093 energies = np.asarray(ak.to_list(event[f"{RECO}.energy"]), dtype=float)
0094 if not len(energies):
0095 return None, None
0096 if sample_type == "particle-gun":
0097 return int(np.argmax(energies)), None
0098
0099 tx = float(event[f"{TRUTH}.position.x"][truth_index])
0100 ty = float(event[f"{TRUTH}.position.y"][truth_index])
0101 rx = np.asarray(ak.to_list(event[f"{RECO}.position.x"]), dtype=float)
0102 ry = np.asarray(ak.to_list(event[f"{RECO}.position.y"]), dtype=float)
0103 distances = np.hypot(rx - tx, ry - ty)
0104 index = int(np.argmin(distances))
0105 distance = float(distances[index])
0106 return (index, distance) if distance < match_radius_mm else (None, distance)
0107
0108
0109 def analyze(paths, sample_type, match_radius_mm):
0110 """Return strict residuals, fragmentation records, and selection counts."""
0111 counts = dict(
0112 events=0,
0113 no_reference_electron=0,
0114 multiple_reference_candidates=0,
0115 multiple_accepted_candidates=0,
0116 outside_pointing=0,
0117 zero_truth=0,
0118 multiple_truth=0,
0119 no_reco=0,
0120 reco_outside_match_radius=0,
0121 nonpositive_truth_energy=0,
0122 matched=0,
0123 )
0124 residuals = []
0125 fragmentation = []
0126 fields = ["MCParticles.momentum.*", f"{RECO}.*", f"{TRUTH}.*", f"{ASSOC}*"]
0127 if sample_type == "dis":
0128 fields.append("MCScatteredElectrons_objIdx.index")
0129
0130 for events in uproot.iterate(
0131 {str(path): "events" for path in paths},
0132 filter_name=fields,
0133 step_size="100 MB",
0134 ):
0135 for event in events:
0136 counts["events"] += 1
0137 particle_index, eta, n_candidates, n_accepted = reference_electron(
0138 event, sample_type
0139 )
0140 if n_candidates > 1:
0141 counts["multiple_reference_candidates"] += 1
0142 if n_accepted > 1:
0143 counts["multiple_accepted_candidates"] += 1
0144 if not n_candidates:
0145 counts["no_reference_electron"] += 1
0146 continue
0147 if particle_index is None:
0148 counts["outside_pointing"] += 1
0149 continue
0150
0151 truth_indices = associated_truth_indices(event, particle_index)
0152 truth_energies = np.asarray(
0153 [float(event[f"{TRUTH}.energy"][index]) for index in truth_indices])
0154 summed = float(np.sum(truth_energies)) if len(truth_energies) else 0.0
0155 largest = float(np.max(truth_energies)) if len(truth_energies) else 0.0
0156 fragmentation.append(
0157 (
0158 eta,
0159 len(truth_indices),
0160 summed,
0161 largest,
0162 largest / summed if summed > 0 else np.nan,
0163 )
0164 )
0165
0166 if len(truth_indices) != 1:
0167 counts["zero_truth" if not truth_indices else "multiple_truth"] += 1
0168 continue
0169 truth_index = truth_indices[0]
0170 truth_energy = float(event[f"{TRUTH}.energy"][truth_index])
0171 if truth_energy <= 0:
0172 counts["nonpositive_truth_energy"] += 1
0173 continue
0174
0175 reco_index, match_distance = select_reco_cluster(
0176 event, truth_index, sample_type, match_radius_mm
0177 )
0178 if reco_index is None:
0179 key = "no_reco" if match_distance is None else "reco_outside_match_radius"
0180 counts[key] += 1
0181 continue
0182 dx, dy = (
0183 float(event[f"{RECO}.position.{axis}"][reco_index])
0184 - float(event[f"{TRUTH}.position.{axis}"][truth_index])
0185 for axis in "xy"
0186 )
0187 reco_energy = float(event[f"{RECO}.energy"][reco_index])
0188 residuals.append(
0189 ((reco_energy - truth_energy) / truth_energy, dx, dy, np.hypot(dx, dy))
0190 )
0191 counts["matched"] += 1
0192
0193 return (
0194 np.asarray(residuals, dtype=float).reshape((-1, 4)),
0195 np.asarray(fragmentation, dtype=float).reshape((-1, 5)),
0196 counts,
0197 )
0198
0199
0200 def central_width(values):
0201 if len(values) < 20:
0202 return None
0203 low, high = np.quantile(values, (0.16, 0.84))
0204 return float((high - low) / 2)
0205
0206
0207 def plot_residuals(rows, label, output_path):
0208 fig, axes = plt.subplots(1, 3, figsize=(12, 3.5), layout="constrained")
0209 labels = (
0210 ("(E reco - E TC) / E TC", ""),
0211 ("Reco - TC x", "mm"),
0212 ("Reco - TC y", "mm"),
0213 )
0214 for i, (axis_label, unit) in enumerate(labels):
0215 axes[i].hist(rows[:, i], bins=80, histtype="step")
0216 axes[i].set_xlabel(f"{axis_label} [{unit}]" if unit else axis_label)
0217 axes[i].set_ylabel("Electron events")
0218 fig.suptitle(f"EEEMCal {label}: reco cluster versus unique associated TC")
0219 fig.savefig(output_path, dpi=150)
0220 plt.close(fig)
0221
0222
0223 def plot_fragmentation(rows, label, output_path):
0224 fig, axes = plt.subplots(1, 3, figsize=(13, 3.5), layout="constrained")
0225 multiplicity = rows[:, 1]
0226 max_multiplicity = int(np.max(multiplicity)) if len(rows) else 0
0227 axes[0].hist(
0228 multiplicity,
0229 bins=np.arange(-0.5, max(2.5, max_multiplicity + 1.5)),
0230 histtype="step",
0231 )
0232 axes[0].set_xlabel("Associated truth clusters")
0233 axes[0].set_ylabel("Selected electrons")
0234 axes[1].hist(
0235 rows[:, 4][np.isfinite(rows[:, 4])],
0236 bins=np.linspace(0, 1, 51),
0237 histtype="step",
0238 )
0239 axes[1].set_xlabel("Largest / summed TC energy")
0240 axes[1].set_ylabel("Selected electrons")
0241 axes[2].hist2d(
0242 rows[:, 0],
0243 rows[:, 1],
0244 bins=[35, np.arange(-0.5, max(2.5, max_multiplicity + 1.5))],
0245 )
0246 axes[2].set_xlabel("Generated electron eta")
0247 axes[2].set_ylabel("Associated truth clusters")
0248 fig.suptitle(f"EEEMCal {label}: truth-cluster fragmentation")
0249 fig.savefig(output_path, dpi=150)
0250 plt.close(fig)
0251
0252
0253 def result_summary(residuals, counts):
0254 return {
0255 "counts": counts,
0256 "central_68_half_width_energy_x_y": [
0257 central_width(residuals[:, i]) for i in range(3)
0258 ],
0259 "median_distance_mm": float(np.median(residuals[:, 3])) if len(residuals) else None,
0260 }
0261
0262
0263 def run_particle_gun(args):
0264 summary = {}
0265 widths = []
0266 for energy in ENERGIES:
0267 paths = read_file_list(args.input_path_format.format(energy=energy))
0268 residuals, fragmentation, counts = analyze(
0269 paths, "particle-gun", args.match_radius_mm
0270 )
0271 np.savez_compressed(args.output_dir / f"residuals_{energy}.npz",
0272 residuals=residuals, fragmentation=fragmentation)
0273 summary[energy] = result_summary(residuals, counts)
0274 widths.append(
0275 [
0276 np.nan if value is None else value
0277 for value in summary[energy]["central_68_half_width_energy_x_y"]
0278 ]
0279 )
0280 plot_residuals(residuals, energy, args.output_dir / f"residuals_{energy}.png")
0281
0282 energy_values = np.array([0.1, 0.2, 0.5, 1, 2, 5, 10, 20])
0283 widths = np.asarray(widths)
0284 fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
0285 axes[0].plot(energy_values, 100 * widths[:, 0], "o-")
0286 axes[0].set_ylabel("Energy residual central 68% half-width [%]")
0287 for index, label in ((1, "x"), (2, "y")):
0288 axes[1].plot(energy_values, widths[:, index], "o-", label=label)
0289 axes[1].set_ylabel("Position residual central 68% half-width [mm]")
0290 axes[1].legend()
0291 for axis in axes:
0292 axis.set_xlabel("Thrown electron energy [GeV]")
0293 axis.set_xscale("log")
0294 fig.savefig(args.output_dir / "agreement_widths.png", dpi=150)
0295 plt.close(fig)
0296 return summary
0297
0298
0299 def run_dis(args):
0300 paths = read_file_list(args.input_file_list)
0301 residuals, fragmentation, counts = analyze(paths, "dis", args.match_radius_mm)
0302 np.savez_compressed(args.output_dir / "residuals.npz", residuals=residuals)
0303 np.savez_compressed(
0304 args.output_dir / "fragmentation.npz",
0305 eta=fragmentation[:, 0],
0306 multiplicity=fragmentation[:, 1],
0307 summed_energy=fragmentation[:, 2],
0308 largest_energy=fragmentation[:, 3],
0309 largest_fraction=fragmentation[:, 4],
0310 )
0311 plot_residuals(residuals, args.label, args.output_dir / "residuals.png")
0312 plot_fragmentation(fragmentation, args.label, args.output_dir / "fragmentation.png")
0313 return {"sample": result_summary(residuals, counts)}
0314
0315
0316 def main():
0317 parser = argparse.ArgumentParser(description=__doc__)
0318 parser.add_argument("--sample-type", choices=("particle-gun", "dis"), required=True)
0319 parser.add_argument("--input-path-format",
0320 help="Particle-gun list-file pattern containing {energy}")
0321 parser.add_argument("--input-file-list", help="DIS reconstructed-file list")
0322 parser.add_argument("--output-dir", type=Path, required=True)
0323 parser.add_argument("--label", default="DIS")
0324 parser.add_argument("--match-radius-mm", type=float, default=50.0)
0325 args = parser.parse_args()
0326 if args.sample_type == "particle-gun" and not args.input_path_format:
0327 parser.error("--input-path-format is required for particle-gun inputs")
0328 if args.sample_type == "dis" and not args.input_file_list:
0329 parser.error("--input-file-list is required for DIS inputs")
0330
0331 args.output_dir.mkdir(parents=True, exist_ok=True)
0332 results = (
0333 run_particle_gun(args) if args.sample_type == "particle-gun" else run_dis(args)
0334 )
0335 with (args.output_dir / "summary.json").open("w") as stream:
0336 json.dump(
0337 {
0338 "sample_type": args.sample_type,
0339 "selection": (
0340 "leading reco cluster; MCParticles[0]"
0341 if args.sample_type == "particle-gun"
0342 else "most-negative-pz accepted MCScatteredElectrons candidate; "
0343 "nearest reco cluster"
0344 ),
0345 "strict_residual_selection": "exactly one associated truth cluster",
0346 "eta_range": [ETA_MIN, ETA_MAX],
0347 "match_radius_mm": (
0348 args.match_radius_mm if args.sample_type == "dis" else None
0349 ),
0350 "interpretation": "reco-TC agreement, not intrinsic resolution",
0351 "results": results,
0352 },
0353 stream,
0354 indent=2,
0355 )
0356
0357
0358 if __name__ == "__main__":
0359 main()