FairShip
Loading...
Searching...
No Matches
run_tracking_benchmark.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"""Run a full tracking benchmark: simulation -> reconstruction -> metrics.
6
7Fires a particle gun upstream of the straw tube spectrometer (T1-T4),
8runs digitisation and reconstruction (AR pattern recognition and GenFit by
9default), then computes tracking and vertexing performance metrics.
10
11Each phase (sim, reco) runs as a subprocess because FairRoot singletons
12prevent creating multiple FairRunSim instances in the same process.
13
14Example usage:
15 python macro/run_tracking_benchmark.py -n 200 --seed 42 --tag test
16 python macro/run_tracking_benchmark.py -n 1000 --nTracks 5 --tag multi
17"""
18
19from __future__ import annotations
20
21import os
22import subprocess
23import sys
24from argparse import ArgumentParser
25
26parser = ArgumentParser(description="Tracking performance benchmark for straw tube spectrometer")
27parser.add_argument("-n", "--nEvents", type=int, default=1000, help="Number of events (default: 1000)")
28parser.add_argument("--pID", type=int, default=13, help="Particle PDG ID (default: 13, mu-)")
29parser.add_argument("--Estart", type=float, default=1.0, help="Start of energy range in GeV (default: 1)")
30parser.add_argument("--Eend", type=float, default=100.0, help="End of energy range in GeV (default: 100)")
31parser.add_argument("--Vz", type=float, default=8300.0, help="Gun z-position in cm (default: 8300, ~1m upstream of T1)")
32parser.add_argument("--Dx", type=float, default=200.0, help="Position spread in x [cm] (default: 200)")
33parser.add_argument("--Dy", type=float, default=300.0, help="Position spread in y [cm] (default: 300)")
34parser.add_argument("--nTracks", type=int, default=1, help="Tracks per event (default: 1)")
35parser.add_argument("--thetaMin", type=float, default=0, help="Minimum polar angle [deg] (default: 0)")
36parser.add_argument("--thetaMax", type=float, default=0, help="Maximum polar angle [deg] (default: 0)")
37parser.add_argument("--mixCharges", action="store_true", help="Generate equal mix of particle and antiparticle")
38parser.add_argument(
39 "--Dz", type=float, default=0.0, help="Vertex spread in z [cm]; uniform in (Vz - Dz/2, Vz + Dz/2) (default: 0)"
40)
41parser.add_argument(
42 "--commonVertex", action="store_true", help="Give all tracks of an event one vertex, for vertexing studies"
43)
44parser.add_argument(
45 "--trackFitter",
46 choices=["genfit", "acts"],
47 default="acts",
48 help="Track fitter (default: acts; genfit is deprecated)",
49)
50parser.add_argument(
51 "--patRec",
52 choices=["FH", "AR", "TemplateMatching", "Truth", "Segments"],
53 default=None,
54 help="Pattern recognition passed to ShipReco.py (default: ShipReco.py's, Segments for acts and AR for genfit)",
55)
56parser.add_argument(
57 "--allTracks",
58 action="store_true",
59 help="Count secondaries as reconstructible too (needed for samples such as HNL decays)",
60)
61parser.add_argument(
62 "--strawPurity",
63 action="store_true",
64 help="Attribute hits to every MC track crossing the straw (for busy events, where tracks share straws)",
65)
66parser.add_argument("--skipSim", action="store_true", help="Reuse an existing simulation output with this tag")
67parser.add_argument("--skipReco", action="store_true", help="Reuse an existing reconstruction output")
68parser.add_argument("--tag", default="benchmark", help="Output file tag (default: benchmark)")
69parser.add_argument("--output-json", default=None, help="JSON metrics output path")
70parser.add_argument("--seed", type=int, default=42, help="Random seed (default: 42)")
71parser.add_argument("-o", "--outputDir", default=".", help="Output directory (default: .)")
72parser.add_argument(
73 "--debug",
74 type=int,
75 default=0,
76 choices=range(0, 4),
77 help="FairLogger verbosity: 0=info, 1=debug, 2=debug1, 3=debug2",
78)
79
80options = parser.parse_args()
81
82if not os.path.exists(options.outputDir):
83 os.makedirs(options.outputDir)
84options.outputDir = os.path.abspath(options.outputDir)
85
86tag = options.tag
87sim_file = os.path.join(options.outputDir, f"sim_{tag}.root")
88geo_file = os.path.join(options.outputDir, f"geo_{tag}.root")
89reco_file = os.path.join(options.outputDir, f"sim_{tag}_rec.root")
90json_file = (
91 os.path.abspath(options.output_json)
92 if options.output_json
93 else os.path.join(options.outputDir, "tracking_metrics.json")
94)
95histo_file = os.path.join(options.outputDir, "tracking_benchmark_histos.root")
96
97fairship = os.environ.get("FAIRSHIP", "")
98
99
100def run_phase(description: str, cmd: list[str], cwd: str | None = None) -> None:
101 """Run a subprocess phase, raising on failure."""
102 print("=" * 60)
103 print(f"{description}")
104 print("=" * 60)
105 result = subprocess.run(cmd, check=False, cwd=cwd)
106 if result.returncode != 0:
107 print(f"FAILED: {description} (exit code {result.returncode})")
108 sys.exit(result.returncode)
109
110
111# ============================================================
112# Phase 1: Simulation via run_simScript.py
113# ============================================================
114sim_script = os.path.join(fairship, "macro", "run_simScript.py") if fairship else "macro/run_simScript.py"
115sim_cmd = [
116 sys.executable,
117 sim_script,
118 "-n",
119 str(options.nEvents),
120 "-s",
121 str(options.seed),
122 "--debug",
123 str(options.debug),
124 "--vacuums",
125 "--SND",
126 "--SND_design",
127 "2",
128 "--shieldName",
129 "TRY_2026",
130 "--tag",
131 tag,
132 "-o",
133 options.outputDir,
134 "PG",
135 "--pID",
136 str(options.pID),
137 "--Estart",
138 str(options.Estart),
139 "--Eend",
140 str(options.Eend),
141 "--Vz",
142 str(options.Vz),
143 "--multiplePG",
144 "--Dx",
145 str(options.Dx),
146 "--Dy",
147 str(options.Dy),
148 "--smearMode",
149 "uniform3d" if options.Dz > 0 else "uniform",
150 "--Dz",
151 str(options.Dz),
152 "--multiplicity",
153 str(options.nTracks),
154 "--thetaMin",
155 str(options.thetaMin),
156 "--thetaMax",
157 str(options.thetaMax),
158]
159if options.mixCharges:
160 sim_cmd.append("--bothCharges")
161if options.commonVertex:
162 sim_cmd.append("--commonVertex")
163
164if not options.skipSim:
165 run_phase("Phase 1: Simulation", sim_cmd)
166
167if not os.path.exists(sim_file):
168 print(f"ERROR: Simulation output {sim_file} not found")
169 sys.exit(1)
170
171# ============================================================
172# Phase 2: Reconstruction via ShipReco.py
173# ============================================================
174reco_script = os.path.join(fairship, "macro", "ShipReco.py") if fairship else "macro/ShipReco.py"
175reco_cmd = [
176 sys.executable,
177 reco_script,
178 "-f",
179 sim_file,
180 "-g",
181 geo_file,
182 "-n",
183 str(options.nEvents),
184 "--trackFitter",
185 options.trackFitter,
186]
187if options.patRec:
188 reco_cmd += ["--patRec", options.patRec]
189if options.debug > 0:
190 reco_cmd.append("--Debug")
191
192if not options.skipReco:
193 run_phase("Phase 2: Reconstruction", reco_cmd, cwd=options.outputDir)
194
195if not os.path.exists(reco_file):
196 print(f"ERROR: Reconstruction output {reco_file} not found")
197 sys.exit(1)
198
199# ============================================================
200# Phase 3: Metrics (runs in this process — no FairRunSim needed)
201# ============================================================
202print("=" * 60)
203print("Phase 3: Benchmark Metrics")
204print("=" * 60)
205
206import tracking_benchmark
207
209 sim_file, reco_file, geo_file, primary_only=not options.allTracks, straw_purity=options.strawPurity
210)
211bench.compute_metrics()
212bench.print_summary()
213bench.save_json(json_file)
214bench.save_histograms(histo_file)
215
216print("=" * 60)
217print("Tracking benchmark complete.")
218print(f" Metrics: {json_file}")
219print(f" Histograms: {histo_file}")
220print("=" * 60)
None run_phase(str description, list[str] cmd, str|None cwd=None)