5"""Scan tracking benchmark over a grid of polar angles and multiplicities.
7Calls run_tracking_benchmark.py for each (theta, nTracks) point, collects
8metrics into a combined JSON, and produces summary plots with matplotlib.
11 # 1D theta scan at single-track multiplicity
12 python macro/run_tracking_scan.py -n 200 --scan-mode theta
14 # 1D multiplicity scan at theta=0
15 python macro/run_tracking_scan.py -n 200 --scan-mode nTracks
18 python macro/run_tracking_scan.py -n 500 --scan-mode grid
20 # Custom theta values, keep intermediate files
21 python macro/run_tracking_scan.py -n 200 --thetas 0,5,15,30 --keep-files
24from __future__
import annotations
31from argparse
import ArgumentParser
32from collections
import defaultdict
34parser = ArgumentParser(description=
"Scan tracking benchmark over angle and multiplicity")
35parser.add_argument(
"-n",
"--nEvents", type=int, default=500, help=
"Events per scan point (default: 500)")
38 default=
"0,1,2,3,5,7,10,15,20,30",
39 help=
"Comma-separated fixed theta values in degrees (default: 0,1,2,3,5,7,10,15,20,30)",
43 default=
"1,2,5,10,20",
44 help=
"Comma-separated multiplicities (default: 1,2,5,10,20)",
48 choices=[
"theta",
"nTracks",
"grid"],
50 help=
"Scan mode: theta (fixed theta per point), nTracks (vary multiplicity at thetaRange), grid (full 2D)",
55 help=
"Theta range 'min,max' in degrees for nTracks scan mode (default: 0,10). "
56 "Tracks are generated uniformly in this range. Ignored in theta scan mode.",
58parser.add_argument(
"--pID", type=int, default=13, help=
"Particle PDG ID (default: 13, mu-)")
59parser.add_argument(
"--Estart", type=float, default=1.0, help=
"Start of energy range in GeV (default: 1)")
60parser.add_argument(
"--Eend", type=float, default=100.0, help=
"End of energy range in GeV (default: 100)")
61parser.add_argument(
"--seed", type=int, default=42, help=
"Base random seed (default: 42)")
62parser.add_argument(
"-o",
"--outputDir", default=
"./scan_results", help=
"Base output directory")
63parser.add_argument(
"--mixCharges", action=
"store_true", help=
"Generate equal mix of particle and antiparticle")
64parser.add_argument(
"--keep-files", action=
"store_true", help=
"Keep intermediate sim/reco ROOT files")
70 help=
"FairLogger verbosity: 0=info, 1=debug, 2=debug1, 3=debug2",
73options = parser.parse_args()
75thetas = [
float(x)
for x
in options.thetas.split(
",")]
76n_tracks_list = [
int(x)
for x
in options.nTracksList.split(
",")]
80 tr_min, tr_max = (
float(x)
for x
in options.thetaRange.split(
","))
82 tr_min, tr_max = 0.0, 10.0
88if options.scan_mode ==
"theta":
89 scan_points = [(t, t, 1, t)
for t
in thetas]
90elif options.scan_mode ==
"nTracks":
91 scan_points = [(tr_min, tr_max, n, f
"{tr_min}-{tr_max}")
for n
in n_tracks_list]
93 scan_points = [(t, t, n, t)
for t
in thetas
for n
in n_tracks_list]
95os.makedirs(options.outputDir, exist_ok=
True)
100GUN_AREA_M2 = GUN_DX * GUN_DY * 1e-4
102fairship = os.environ.get(
"FAIRSHIP",
"")
104 os.path.join(fairship,
"macro",
"run_tracking_benchmark.py")
if fairship
else "macro/run_tracking_benchmark.py"
107all_results: list[dict] = []
108n_total = len(scan_points)
110for i, (theta_min, theta_max, n_tracks, label_theta)
in enumerate(scan_points):
111 tag = f
"scan_theta{label_theta}_nTr{n_tracks}"
112 point_dir = os.path.join(options.outputDir, tag)
113 json_path = os.path.join(point_dir,
"tracking_metrics.json")
114 histo_path = os.path.join(point_dir,
"tracking_benchmark_histos.root")
116 theta_desc = f
"{theta_min}°" if theta_min == theta_max
else f
"[{theta_min},{theta_max}]°"
117 print(f
"\n{'=' * 60}")
118 print(f
"Scan point {i + 1}/{n_total}: theta={theta_desc}, nTracks={n_tracks}")
125 str(options.nEvents),
139 str(options.seed + i),
153 if options.mixCharges:
154 cmd.append(
"--mixCharges")
156 result = subprocess.run(cmd, check=
False)
157 if result.returncode != 0:
158 print(f
"WARNING: scan point theta={theta_desc}, nTracks={n_tracks} failed (exit code {result.returncode})")
162 with open(json_path)
as f:
163 metrics = json.load(f)
164 benchmark_metrics = metrics[
"tracking_benchmark"]
165 except (FileNotFoundError, json.JSONDecodeError, KeyError)
as e:
166 print(f
"WARNING: failed to read results from {json_path}: {e}")
171 "theta": label_theta,
172 "thetaMin": theta_min,
173 "thetaMax": theta_max,
175 "density_per_m2": round(n_tracks / GUN_AREA_M2, 4),
176 "metrics": benchmark_metrics,
181 if not options.keep_files:
182 for pattern
in [f
"sim_{tag}.root", f
"geo_{tag}.root", f
"params_{tag}.root", f
"sim_{tag}_rec*.root"]:
183 for fpath
in glob.glob(os.path.join(point_dir, pattern)):
185 print(f
" Cleaned up {fpath}")
190 "scan_mode": options.scan_mode,
192 "nTracksList": n_tracks_list,
193 "nEvents": options.nEvents,
195 "Estart": options.Estart,
196 "Eend": options.Eend,
197 "seed": options.seed,
199 "scan_results": all_results,
202combined_json = os.path.join(options.outputDir,
"scan_results.json")
203with open(combined_json,
"w")
as f:
204 json.dump(combined, f, indent=2)
205print(f
"\nCombined results saved to {combined_json}")
210ROOT.gROOT.SetBatch(
True)
218 "charge_id_efficiency",
221 "efficiency":
"Tracking efficiency",
222 "ghost_rate":
"Ghost rate",
223 "clone_rate":
"Clone rate",
224 "dp_over_p_sigma":
"#Deltap/p resolution (#sigma)",
225 "n_reconstructible":
"Reconstructible tracks",
226 "charge_id_efficiency":
"Charge-ID efficiency",
230by_nTracks: dict[int, list[tuple[float, dict]]] = defaultdict(list)
231by_theta: dict[str, list[tuple[int, dict]]] = defaultdict(list)
234 theta_label = r[
"theta"]
235 if isinstance(theta_label, (int, float)):
236 by_nTracks[r[
"nTracks"]].append((
float(theta_label), r[
"metrics"]))
237 by_theta[str(theta_label)].append((r[
"nTracks"], r[
"metrics"]))
239summary_root = os.path.join(options.outputDir,
"scan_summary.root")
240f_out = ROOT.TFile.Open(summary_root,
"recreate")
242for metric
in metric_names:
243 for n_tr, points
in sorted(by_nTracks.items()):
244 points.sort(key=
lambda p: p[0])
245 valid = [(x, m)
for x, m
in points
if m[metric][
"value"]
is not None]
248 gr = ROOT.TGraphErrors(len(valid))
249 gr.SetName(f
"g_{metric}_vs_theta_nTr{n_tr}")
250 gr.SetTitle(f
"{metric_titles[metric]}, nTracks={n_tr};#theta [deg];{metric_titles[metric]}")
251 for j, (theta_val, m)
in enumerate(valid):
252 gr.SetPoint(j, theta_val, m[metric][
"value"])
253 gr.SetPointError(j, 0, m[metric].get(
"uncertainty")
or 0)
256 for theta_label, points
in sorted(by_theta.items()):
257 points.sort(key=
lambda p: p[0])
258 valid = [(x, m)
for x, m
in points
if m[metric][
"value"]
is not None]
261 gr = ROOT.TGraphErrors(len(valid))
262 gr.SetName(f
"g_{metric}_vs_nTracks_theta{theta_label}")
263 gr.SetTitle(f
"{metric_titles[metric]}, #theta={theta_label}#circ;nTracks;{metric_titles[metric]}")
264 for j, (n_tr_val, m)
in enumerate(valid):
265 gr.SetPoint(j, n_tr_val, m[metric][
"value"])
266 gr.SetPointError(j, 0, m[metric].get(
"uncertainty")
or 0)
270print(f
"ROOT summary saved to {summary_root}")
274 import matplotlib.pyplot
as plt
278 metric_ylimits: dict[str, tuple[float |
None, float |
None]] = {
279 "efficiency": (
None, 1.05),
280 "ghost_rate": (0,
None),
281 "clone_rate": (0,
None),
282 "dp_over_p_sigma": (0,
None),
283 "n_reconstructible": (0,
None),
284 "charge_id_efficiency": (
None, 1.05),
288 "efficiency":
"Efficiency",
289 "ghost_rate":
"Ghost rate",
290 "clone_rate":
"Clone rate",
291 "dp_over_p_sigma":
r"$\Delta p / p$ resolution ($\sigma$)",
292 "n_reconstructible": f
"Reconstructible tracks (out of {options.nEvents})",
293 "charge_id_efficiency":
"Charge-ID efficiency",
297 """Save figure as both PDF and PNG."""
298 fig.savefig(base_path +
".pdf")
299 fig.savefig(base_path +
".png", dpi=150)
301 def _get_values(points: list, metric: str) -> tuple[list, list, list]:
302 """Extract x, y, yerr from sorted scan points, skipping None values."""
303 x, y, yerr = [], [], []
305 val = p[1][metric][
"value"]
310 yerr.append(p[1][metric].get(
"uncertainty")
or 0)
313 n_curves_theta = max(len(by_nTracks), 1)
314 n_curves_mult = max(len(by_theta), 1)
315 colours_theta = plt.cm.viridis(np.linspace(0, 0.9, n_curves_theta))
316 colours_mult = plt.cm.plasma(np.linspace(0, 0.9, n_curves_mult))
318 for metric
in metric_names:
319 ymin, ymax = metric_ylimits.get(metric, (
None,
None))
320 ylabel = metric_ylabels.get(metric, metric)
323 if len(by_nTracks) > 0
and any(len(pts) > 1
for pts
in by_nTracks.values()):
324 fig, ax = plt.subplots(figsize=(8, 5))
325 for idx, (n_tr, points)
in enumerate(sorted(by_nTracks.items())):
337 label=f
"nTracks={n_tr}",
338 color=colours_theta[idx],
340 ax.set_xlabel(
r"$\theta$ [deg]")
341 ax.set_ylabel(ylabel)
342 ax.set_title(f
"{ylabel} vs polar angle")
344 ax.set_ylim(bottom=ymin)
346 ax.set_ylim(top=ymax)
348 ax.grid(
True, alpha=0.3)
350 _save_fig(fig, os.path.join(options.outputDir, f
"scan_{metric}_vs_theta"))
354 if len(by_theta) > 0
and any(len(pts) > 1
for pts
in by_theta.values()):
355 fig, ax = plt.subplots(figsize=(8, 5))
356 for idx, (theta_label, points)
in enumerate(sorted(by_theta.items())):
362 theta_legend = rf
"$\theta$={float(theta_label):.0f}°"
364 theta_legend = rf
"$\theta \in [{theta_label}]$°"
373 color=colours_mult[idx],
375 ax.set_xlabel(
"Tracks per event")
376 ax.set_ylabel(ylabel)
377 ax.set_title(f
"{ylabel} vs multiplicity (gun area = {GUN_AREA_M2:.1f} m²)")
379 ax.set_ylim(bottom=ymin)
381 ax.set_ylim(top=ymax)
383 ax.grid(
True, alpha=0.3)
385 _save_fig(fig, os.path.join(options.outputDir, f
"scan_{metric}_vs_nTracks"))
388 print(f
"Plots saved to {options.outputDir}/scan_*.{{pdf,png}}")
391 print(
"matplotlib not available — skipping plots (ROOT summary file still produced)")
393print(f
"\nScan complete: {len(all_results)}/{n_total} points succeeded.")
None _save_fig(plt.Figure fig, str base_path)
tuple[list, list, list] _get_values(list points, str metric)