FairShip
Loading...
Searching...
No Matches
run_tracking_scan.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-3.0-or-later
3# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
4
5"""Scan tracking benchmark over a grid of polar angles and multiplicities.
6
7Calls run_tracking_benchmark.py for each (theta, nTracks) point, collects
8metrics into a combined JSON, and produces summary plots with matplotlib.
9
10Example usage:
11 # 1D theta scan at single-track multiplicity
12 python macro/run_tracking_scan.py -n 200 --scan-mode theta
13
14 # 1D multiplicity scan at theta=0
15 python macro/run_tracking_scan.py -n 200 --scan-mode nTracks
16
17 # Full 2D grid
18 python macro/run_tracking_scan.py -n 500 --scan-mode grid
19
20 # Custom theta values, keep intermediate files
21 python macro/run_tracking_scan.py -n 200 --thetas 0,5,15,30 --keep-files
22"""
23
24from __future__ import annotations
25
26import glob
27import json
28import os
29import subprocess
30import sys
31from argparse import ArgumentParser
32from collections import defaultdict
33
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)")
36parser.add_argument(
37 "--thetas",
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)",
40)
41parser.add_argument(
42 "--nTracksList",
43 default="1,2,5,10,20",
44 help="Comma-separated multiplicities (default: 1,2,5,10,20)",
45)
46parser.add_argument(
47 "--scan-mode",
48 choices=["theta", "nTracks", "grid"],
49 default="grid",
50 help="Scan mode: theta (fixed theta per point), nTracks (vary multiplicity at thetaRange), grid (full 2D)",
51)
52parser.add_argument(
53 "--thetaRange",
54 default=None,
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.",
57)
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")
65parser.add_argument(
66 "--debug",
67 type=int,
68 default=0,
69 choices=range(0, 4),
70 help="FairLogger verbosity: 0=info, 1=debug, 2=debug1, 3=debug2",
71)
72
73options = parser.parse_args()
74
75thetas = [float(x) for x in options.thetas.split(",")]
76n_tracks_list = [int(x) for x in options.nTracksList.split(",")]
77
78# Parse theta range for nTracks mode
79if options.thetaRange:
80 tr_min, tr_max = (float(x) for x in options.thetaRange.split(","))
81else:
82 tr_min, tr_max = 0.0, 10.0
83
84# Build scan grid: each point is (thetaMin, thetaMax, nTracks, label_theta)
85# In theta mode: fixed theta per point (thetaMin == thetaMax)
86# In nTracks mode: uniform theta range, vary multiplicity
87# In grid mode: fixed theta per point, vary both
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]
92else: # grid
93 scan_points = [(t, t, n, t) for t in thetas for n in n_tracks_list]
94
95os.makedirs(options.outputDir, exist_ok=True)
96
97# Gun position spread [cm]; single source of truth passed to the benchmark below.
98GUN_DX = 200.0
99GUN_DY = 300.0
100GUN_AREA_M2 = GUN_DX * GUN_DY * 1e-4
101
102fairship = os.environ.get("FAIRSHIP", "")
103benchmark_script = (
104 os.path.join(fairship, "macro", "run_tracking_benchmark.py") if fairship else "macro/run_tracking_benchmark.py"
105)
106
107all_results: list[dict] = []
108n_total = len(scan_points)
109
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")
115
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}")
119 print(f"{'=' * 60}")
120
121 cmd = [
122 sys.executable,
123 benchmark_script,
124 "-n",
125 str(options.nEvents),
126 "--thetaMin",
127 str(theta_min),
128 "--thetaMax",
129 str(theta_max),
130 "--nTracks",
131 str(n_tracks),
132 "--Dx",
133 str(GUN_DX),
134 "--Dy",
135 str(GUN_DY),
136 "--tag",
137 tag,
138 "--seed",
139 str(options.seed + i),
140 "-o",
141 point_dir,
142 "--output-json",
143 json_path,
144 "--pID",
145 str(options.pID),
146 "--Estart",
147 str(options.Estart),
148 "--Eend",
149 str(options.Eend),
150 "--debug",
151 str(options.debug),
152 ]
153 if options.mixCharges:
154 cmd.append("--mixCharges")
155
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})")
159 continue
160
161 try:
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}")
167 continue
168
169 all_results.append(
170 {
171 "theta": label_theta,
172 "thetaMin": theta_min,
173 "thetaMax": theta_max,
174 "nTracks": n_tracks,
175 "density_per_m2": round(n_tracks / GUN_AREA_M2, 4),
176 "metrics": benchmark_metrics,
177 }
178 )
179
180 # Clean up intermediate ROOT files
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)):
184 os.remove(fpath)
185 print(f" Cleaned up {fpath}")
186
187# Save combined results
188combined = {
189 "scan_config": {
190 "scan_mode": options.scan_mode,
191 "thetas": thetas,
192 "nTracksList": n_tracks_list,
193 "nEvents": options.nEvents,
194 "pID": options.pID,
195 "Estart": options.Estart,
196 "Eend": options.Eend,
197 "seed": options.seed,
198 },
199 "scan_results": all_results,
200}
201
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}")
206
207# Save TGraphErrors to ROOT file
208import ROOT
209
210ROOT.gROOT.SetBatch(True)
211
212metric_names = [
213 "efficiency",
214 "ghost_rate",
215 "clone_rate",
216 "dp_over_p_sigma",
217 "n_reconstructible",
218 "charge_id_efficiency",
219]
220metric_titles = {
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",
227}
228
229# Group results — only include numeric theta values for "vs theta" graphs
230by_nTracks: dict[int, list[tuple[float, dict]]] = defaultdict(list)
231by_theta: dict[str, list[tuple[int, dict]]] = defaultdict(list)
232
233for r in all_results:
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"]))
238
239summary_root = os.path.join(options.outputDir, "scan_summary.root")
240f_out = ROOT.TFile.Open(summary_root, "recreate")
241
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]
246 if not valid:
247 continue
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)
254 gr.Write()
255
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]
259 if not valid:
260 continue
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)
267 gr.Write()
268
269f_out.Close()
270print(f"ROOT summary saved to {summary_root}")
271
272# Generate matplotlib plots
273try:
274 import matplotlib.pyplot as plt
275 import numpy as np
276
277 # Axis limits: rates are bounded to [0, max], efficiency to [min, 1.05]
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),
285 }
286
287 metric_ylabels = {
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",
294 }
295
296 def _save_fig(fig: plt.Figure, base_path: str) -> None:
297 """Save figure as both PDF and PNG."""
298 fig.savefig(base_path + ".pdf")
299 fig.savefig(base_path + ".png", dpi=150)
300
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 = [], [], []
304 for p in points:
305 val = p[1][metric]["value"]
306 if val is None:
307 continue
308 x.append(p[0])
309 y.append(val)
310 yerr.append(p[1][metric].get("uncertainty") or 0)
311 return x, y, yerr
312
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))
317
318 for metric in metric_names:
319 ymin, ymax = metric_ylimits.get(metric, (None, None))
320 ylabel = metric_ylabels.get(metric, metric)
321
322 # Plots vs theta
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())):
326 points.sort()
327 x, y, yerr = _get_values(points, metric)
328 if not x:
329 continue
330 ax.errorbar(
331 x,
332 y,
333 yerr=yerr,
334 marker="o",
335 linestyle="none",
336 capsize=3,
337 label=f"nTracks={n_tr}",
338 color=colours_theta[idx],
339 )
340 ax.set_xlabel(r"$\theta$ [deg]")
341 ax.set_ylabel(ylabel)
342 ax.set_title(f"{ylabel} vs polar angle")
343 if ymin is not None:
344 ax.set_ylim(bottom=ymin)
345 if ymax is not None:
346 ax.set_ylim(top=ymax)
347 ax.legend()
348 ax.grid(True, alpha=0.3)
349 fig.tight_layout()
350 _save_fig(fig, os.path.join(options.outputDir, f"scan_{metric}_vs_theta"))
351 plt.close(fig)
352
353 # Plots vs nTracks
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())):
357 points.sort()
358 x, y, yerr = _get_values(points, metric)
359 if not x:
360 continue
361 try:
362 theta_legend = rf"$\theta$={float(theta_label):.0f}°"
363 except ValueError:
364 theta_legend = rf"$\theta \in [{theta_label}]$°"
365 ax.errorbar(
366 x,
367 y,
368 yerr=yerr,
369 marker="s",
370 linestyle="none",
371 capsize=3,
372 label=theta_legend,
373 color=colours_mult[idx],
374 )
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²)")
378 if ymin is not None:
379 ax.set_ylim(bottom=ymin)
380 if ymax is not None:
381 ax.set_ylim(top=ymax)
382 ax.legend()
383 ax.grid(True, alpha=0.3)
384 fig.tight_layout()
385 _save_fig(fig, os.path.join(options.outputDir, f"scan_{metric}_vs_nTracks"))
386 plt.close(fig)
387
388 print(f"Plots saved to {options.outputDir}/scan_*.{{pdf,png}}")
389
390except ImportError:
391 print("matplotlib not available — skipping plots (ROOT summary file still produced)")
392
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)