33def run_track_pattern_recognition(input_file, geo_file, output_file, method, dy=None):
34 """
35 Runs all steps of track pattern recognition.
36 Parameters
37 ----------
38 input_file : string
39 Path to an input .root file with events.
40 geo_file : string
41 Path to a file with SHiP geometry.
42 output_file : string
43 Path to an output .root file with quality plots.
44 method : string
45 Name of a track pattern recognition method.
46 """
47
48
49
50
51 if method != "Baseline":
52 print(
53 f"Warning: pattern-recognition method '{method}' has no effect here; "
54 "this script only produces quality plots from existing reconstruction."
55 )
56
57
58
59
60 try:
61 fgeo = ROOT.TFile(geo_file)
62 except Exception:
63 print("An error with opening the ship geo file.")
64 raise
65
66 sGeo = fgeo.Get("FAIRGeom")
67
68
69 if not fgeo.FindKey("ShipGeo"):
70 if dy:
72 else:
74 else:
75 ShipGeo = load_from_root_file(fgeo, "ShipGeo")
76
77
78 global_variables.ShipGeo = ShipGeo
79
80
81
82 run = ROOT.FairRunSim()
83 run.SetName("TGeant4")
84
85
86 import tempfile
87
88 sink = ROOT.FairRootFileSink(tempfile.mktemp(suffix=".root"))
89 run.SetSink(sink)
90 ROOT.SetOwnership(sink, False)
91 run.SetUserConfig("g4Config_basic.C")
92 run.GetRuntimeDb()
93
95 run.Init()
96
97
98
99
100
101
102 import geomGeant4
103
104 if hasattr(ShipGeo.Bfield, "fieldMap"):
106 else:
107 print("no fieldmap given, geofile too old, not anymore support")
108 exit(-1)
109 sGeo = fgeo.Get("FAIRGeom")
110 geoMat = ROOT.genfit.TGeoMaterialInterface()
111 ROOT.genfit.MaterialEffects.getInstance().init(geoMat)
112 bfield = ROOT.genfit.FairShipFields()
113 bfield.setField(fieldMaker.getGlobalField())
114 fM = ROOT.genfit.FieldManager.getInstance()
115 fM.init(bfield)
116
117
118
119
120
121
122
123 try:
124 fn = ROOT.TFile(input_file, "read")
125 except Exception:
126 print("An error with opening the input data file.")
127 raise
128
129 sTree = fn.Get("cbmsim")
130
131
132
133 h = init_book_hist()
134
135
136
137
138
139 metrics: dict[str, Any] = {
140 "n_hits": [],
141 "reconstructible": 0,
142 "passed_y12": 0,
143 "passed_stereo12": 0,
144 "passed_12": 0,
145 "passed_y34": 0,
146 "passed_stereo34": 0,
147 "passed_34": 0,
148 "passed_combined": 0,
149 "reco_passed": 0,
150 "reco_passed_no_clones": 0,
151 "frac_y12": [],
152 "frac_stereo12": [],
153 "frac_12": [],
154 "frac_y34": [],
155 "frac_stereo34": [],
156 "frac_34": [],
157 "reco_frac_tot": [],
158 "reco_mc_p": [],
159 "reco_mc_theta": [],
160 "fitted_p": [],
161 "fitted_pval": [],
162 "fitted_chi": [],
163 "fitted_x": [],
164 "fitted_y": [],
165 "fitted_z": [],
166 "fitted_mass": [],
167 }
168
169
170 nEvents = sTree.GetEntries()
171
172 for iEvent in range(nEvents):
173 if iEvent % 1000 == 0:
174 print("Event ", iEvent)
175
176
177
178 sTree.GetEvent(iEvent)
179
180
181
182 reconstructible_tracks = getReconstructibleTracks(iEvent, sTree, sGeo, ShipGeo)
183
184 metrics["reconstructible"] += len(reconstructible_tracks)
185 for i_reco in reconstructible_tracks:
186 h["TracksPassed"].Fill("Reconstructible tracks", 1)
187 h["TracksPassedU"].Fill("Reconstructible tracks", 1)
188
189 in_y12 = []
190 in_stereo12 = []
191 in_12 = []
192 in_y34 = []
193 in_stereo34 = []
194 in_34 = []
195 in_combo = []
196
197 found_track_ids = []
198 n_tracks = len(reconstructible_tracks)
199 n_recognized = 0
200 n_clones = 0
201 n_ghosts = 0
202 n_others = 0
203
204 min_eff = 0.0
205
206
207
208 nTracklets = len(sTree.Tracklets)
209
210 for i_track in range(nTracklets):
211 atracklet = sTree.Tracklets[i_track]
212
213 if atracklet.getType() != 1:
214 continue
215
216 atrack = atracklet.getList()
217
218 if len(atrack) == 0:
219 continue
220
221 hits = {
222 "X": [],
223 "Y": [],
224 "Z": [],
225 "DetID": [],
226 "TrackID": [],
227 "Pz": [],
228 "Px": [],
229 "Py": [],
230 "dist2Wire": [],
231 "Pdg": [],
232 }
233
234 for ihit in atrack:
235 ahit = sTree.strawtubesPoint[ihit]
236 hits["X"] += [ahit.GetX()]
237 hits["Y"] += [ahit.GetY()]
238 hits["Z"] += [ahit.GetZ()]
239 hits["DetID"] += [ahit.GetDetectorID()]
240 hits["TrackID"] += [ahit.GetTrackID()]
241 hits["Pz"] += [ahit.GetPz()]
242 hits["Px"] += [ahit.GetPx()]
243 hits["Py"] += [ahit.GetPy()]
244 hits["dist2Wire"] += [ahit.dist2Wire()]
245 hits["Pdg"] += [ahit.PdgCode()]
246
247
248 hits = {key: numpy.array(values) for key, values in hits.items()}
249
250
251 decode = global_variables.modules["strawtubes"].StrawDecode(hits["DetID"])
252
253 is_stereo = (decode[1] == 1) + (decode[1] == 2)
254 is_y = (decode[1] == 0) + (decode[1] == 3)
255 is_before = (decode[0] == 1) + (decode[0] == 2)
256 is_after = (decode[0] == 3) + (decode[0] == 4)
257
258
259 metrics["n_hits"] += [get_n_hits(hits["TrackID"])]
260
261
262 frac_y12, tmax_y12 = fracMCsame(hits["TrackID"][is_before * is_y])
263 n_hits_y12 = get_n_hits(hits["TrackID"][is_before * is_y])
264 frac_stereo12, tmax_stereo12 = fracMCsame(hits["TrackID"][is_before * is_stereo])
265 n_hits_stereo12 = get_n_hits(hits["TrackID"][is_before * is_stereo])
266 frac_12, tmax_12 = fracMCsame(hits["TrackID"][is_before])
267 n_hits_12 = get_n_hits(hits["TrackID"][is_before])
268
269 frac_y34, tmax_y34 = fracMCsame(hits["TrackID"][is_after * is_y])
270 n_hits_y34 = get_n_hits(hits["TrackID"][is_after * is_y])
271 frac_stereo34, tmax_stereo34 = fracMCsame(hits["TrackID"][is_after * is_stereo])
272 n_hits_stereo34 = get_n_hits(hits["TrackID"][is_after * is_stereo])
273 frac_34, tmax_34 = fracMCsame(hits["TrackID"][is_after])
274 n_hits_34 = get_n_hits(hits["TrackID"][is_after])
275 frac_tot, tmax_tot = fracMCsame(hits["TrackID"])
276 n_hits_tot = get_n_hits(hits["TrackID"])
277
278 if tmax_y12 == tmax_stereo12 and tmax_y12 == tmax_y34 and tmax_y12 == tmax_stereo34:
279 if (
280 frac_y12 >= min_eff
281 and frac_stereo12 >= min_eff
282 and frac_y34 >= min_eff
283 and frac_stereo34 >= min_eff
284 ):
285 if tmax_y12 in reconstructible_tracks and tmax_y12 not in found_track_ids:
286 n_recognized += 1
287 found_track_ids.append(tmax_y12)
288 elif tmax_y12 in reconstructible_tracks and tmax_y12 in found_track_ids:
289 n_clones += 1
290 elif tmax_y12 not in reconstructible_tracks:
291 n_others += 1
292
293 else:
294 n_ghosts += 1
295 else:
296 n_ghosts += 1
297
298 is_reconstructed = 0
299
300 if tmax_y12 in reconstructible_tracks:
301 metrics["passed_y12"] += 1
302 metrics["frac_y12"] += [frac_y12]
303 h["TracksPassed"].Fill("Y view station 1&2", 1)
304 if tmax_y12 not in in_y12:
305 h["TracksPassedU"].Fill("Y view station 1&2", 1)
306 in_y12.append(tmax_y12)
307
308 if tmax_stereo12 == tmax_y12:
309 metrics["passed_stereo12"] += 1
310 metrics["frac_stereo12"] += [frac_stereo12]
311 h["TracksPassed"].Fill("Stereo station 1&2", 1)
312 if tmax_stereo12 not in in_stereo12:
313 h["TracksPassedU"].Fill("Stereo station 1&2", 1)
314 in_stereo12.append(tmax_stereo12)
315
316 if tmax_12 == tmax_y12:
317 metrics["passed_12"] += 1
318 metrics["frac_12"] += [frac_12]
319 h["TracksPassed"].Fill("station 1&2", 1)
320 if tmax_12 not in in_12:
321 h["TracksPassedU"].Fill("station 1&2", 1)
322 in_12.append(tmax_12)
323
324 if tmax_y34 in reconstructible_tracks:
325 metrics["passed_y34"] += 1
326 metrics["frac_y34"] += [frac_y34]
327 h["TracksPassed"].Fill("Y view station 3&4", 1)
328 if tmax_y34 not in in_y34:
329 h["TracksPassedU"].Fill("Y view station 3&4", 1)
330 in_y34.append(tmax_y34)
331
332 if tmax_stereo34 == tmax_y34:
333 metrics["passed_stereo34"] += 1
334 metrics["frac_stereo34"] += [frac_stereo34]
335 h["TracksPassed"].Fill("Stereo station 3&4", 1)
336 if tmax_stereo34 not in in_stereo34:
337 h["TracksPassedU"].Fill("Stereo station 3&4", 1)
338 in_stereo34.append(tmax_stereo34)
339
340 if tmax_34 == tmax_y34:
341 metrics["passed_34"] += 1
342 metrics["frac_34"] += [frac_34]
343 h["TracksPassed"].Fill("station 3&4", 1)
344 if tmax_34 not in in_34:
345 h["TracksPassedU"].Fill("station 3&4", 1)
346 in_34.append(tmax_34)
347
348 if tmax_12 == tmax_34:
349 metrics["passed_combined"] += 1
350 h["TracksPassed"].Fill("Combined stations 1&2/3&4", 1)
351 metrics["reco_passed"] += 1
352 is_reconstructed = 1
353 if tmax_34 not in in_combo:
354 h["TracksPassedU"].Fill("Combined stations 1&2/3&4", 1)
355 metrics["reco_passed_no_clones"] += 1
356 in_combo.append(tmax_34)
357
358
359 if is_reconstructed == 0:
360 continue
361
362 metrics["reco_frac_tot"] += [frac_tot]
363
364
365 p, px, py, pz = getPtruthFirst(sTree, tmax_tot)
366 pt = math.sqrt(px**2 + py**2)
367
368 Z_true = []
369 X_true = []
370 Y_true = []
371 for ahit in sTree.strawtubesPoint:
372 if ahit.GetTrackID() == tmax_tot:
373 az, ax, ay = ahit.GetZ(), ahit.GetX(), ahit.GetY()
374 Z_true.append(az)
375 X_true.append(ax)
376 Y_true.append(ay)
377
378 metrics["reco_mc_p"] += [p]
379 h["TracksPassed_p"].Fill(p, 1)
380
381
382 Z = hits["Z"][(hits["TrackID"] == tmax_tot) * is_before]
383 X = hits["X"][(hits["TrackID"] == tmax_tot) * is_before]
384 Y = hits["Y"][(hits["TrackID"] == tmax_tot) * is_before]
385 Z = Z - Z[0]
386 X = X - X[0]
387 Y = Y - Y[0]
388 R = numpy.sqrt(X**2 + Y**2 + Z**2)
389 Theta = numpy.arccos(Z[1:] / R[1:])
390 theta = numpy.mean(Theta)
391
392 metrics["reco_mc_theta"] += [theta]
393
394 h["n_hits_reco_y12"].Fill(n_hits_y12)
395 h["n_hits_reco_stereo12"].Fill(n_hits_stereo12)
396 h["n_hits_reco_12"].Fill(n_hits_12)
397 h["n_hits_reco_y34"].Fill(n_hits_y34)
398 h["n_hits_reco_stereo34"].Fill(n_hits_stereo34)
399 h["n_hits_reco_34"].Fill(n_hits_34)
400 h["n_hits_reco"].Fill(n_hits_tot)
401
402 h["n_hits_y12"].Fill(p, n_hits_y12)
403 h["n_hits_stereo12"].Fill(p, n_hits_stereo12)
404 h["n_hits_12"].Fill(p, n_hits_12)
405 h["n_hits_y34"].Fill(p, n_hits_y34)
406 h["n_hits_stereo34"].Fill(p, n_hits_stereo34)
407 h["n_hits_34"].Fill(p, n_hits_34)
408 h["n_hits_total"].Fill(p, n_hits_tot)
409
410 h["frac_y12"].Fill(p, frac_y12)
411 h["frac_stereo12"].Fill(p, frac_stereo12)
412 h["frac_12"].Fill(p, frac_12)
413 h["frac_y34"].Fill(p, frac_y34)
414 h["frac_stereo34"].Fill(p, frac_stereo34)
415 h["frac_34"].Fill(p, frac_34)
416 h["frac_total"].Fill(p, frac_tot)
417
418 h["frac_y12_dist"].Fill(frac_y12)
419 h["frac_stereo12_dist"].Fill(frac_stereo12)
420 h["frac_12_dist"].Fill(frac_12)
421 h["frac_y34_dist"].Fill(frac_y34)
422 h["frac_stereo34_dist"].Fill(frac_stereo34)
423 h["frac_34_dist"].Fill(frac_34)
424 h["frac_total_dist"].Fill(frac_tot)
425
426
427
428 thetrack = sTree.FitTracks[i_track]
429
430 fitStatus = thetrack.getFitStatus()
431
432 nmeas = fitStatus.getNdf()
433 pval = fitStatus.getPVal()
434 chi2 = fitStatus.getChi2() / nmeas
435
436 metrics["fitted_pval"] += [pval]
437 metrics["fitted_chi"] += [chi2]
438
439 h["chi2fittedtracks"].Fill(chi2)
440 h["pvalfittedtracks"].Fill(pval)
441
442 try:
443 fittedState = thetrack.getFittedState()
444 fittedMom = fittedState.getMomMag()
445 fittedMom = fittedMom
446
447 px_fit, py_fit, pz_fit = fittedState.getMom().x(), fittedState.getMom().y(), fittedState.getMom().z()
448 p_fit = fittedMom
449 pt_fit = math.sqrt(px_fit**2 + py_fit**2)
450
451 metrics["fitted_p"] += [p_fit]
452 perr = (p - p_fit) / p
453 h["ptrue-p/ptrue"].Fill(perr)
454 h["perr"].Fill(p, perr)
455 h["perr_direction"].Fill(numpy.rad2deg(theta), perr)
456
457 pterr = (pt - pt_fit) / pt
458 h["pttrue-pt/pttrue"].Fill(pterr)
459
460 pxerr = (px - px_fit) / px
461 h["pxtrue-px/pxtrue"].Fill(pxerr)
462
463 pyerr = (py - py_fit) / py
464 h["pytrue-py/pytrue"].Fill(pyerr)
465
466 pzerr = (pz - pz_fit) / pz
467 h["pztrue-pz/pztrue"].Fill(pzerr)
468
469 if math.fabs(p) > 0.0:
470 h["pvspfitted"].Fill(p, fittedMom)
471 fittedtrackDir = fittedState.getDir()
472 fittedx = math.degrees(math.acos(fittedtrackDir[0]))
473 fittedy = math.degrees(math.acos(fittedtrackDir[1]))
474 fittedz = math.degrees(math.acos(fittedtrackDir[2]))
475 fittedmass = fittedState.getMass()
476 h["momentumfittedtracks"].Fill(fittedMom)
477 h["xdirectionfittedtracks"].Fill(fittedx)
478 h["ydirectionfittedtracks"].Fill(fittedy)
479 h["zdirectionfittedtracks"].Fill(fittedz)
480 h["massfittedtracks"].Fill(fittedmass)
481
482 metrics["fitted_x"] += [fittedx]
483 metrics["fitted_y"] += [fittedy]
484 metrics["fitted_z"] += [fittedz]
485 metrics["fitted_mass"] += [fittedmass]
486
487 Z_fit = []
488 X_fit = []
489 Y_fit = []
490 X_true_matched = []
491 Y_true_matched = []
492 for az, ax_true, ay_true in zip(Z_true, X_true, Y_true):
493 _rc, pos, _mom = extrapolateToPlane(thetrack, az)
494 if pos is None:
495 continue
496 Z_fit.append(pos.Z())
497 X_fit.append(pos.X())
498 Y_fit.append(pos.Y())
499 X_true_matched.append(ax_true)
500 Y_true_matched.append(ay_true)
501
502 for i in range(len(Z_fit)):
503 xerr = abs(X_fit[i] - X_true_matched[i])
504 yerr = abs(Y_fit[i] - Y_true_matched[i])
505 h["abs(x - x-true)"].Fill(xerr)
506 h["abs(y - y-true)"].Fill(yerr)
507
508 if Z_fit:
509 rmse_x = numpy.sqrt(numpy.mean((numpy.array(X_fit) - numpy.array(X_true_matched)) ** 2))
510 rmse_y = numpy.sqrt(numpy.mean((numpy.array(Y_fit) - numpy.array(Y_true_matched)) ** 2))
511 h["rmse_x"].Fill(rmse_x)
512 h["rmse_y"].Fill(rmse_y)
513
514 except ROOT.genfit.Exception as e:
515
516
517
518
519 print(f"Problem with fitted state: {e!r}")
520
521 h["Reco_tracks"].Fill("N total", n_tracks)
522 h["Reco_tracks"].Fill("N recognized tracks", n_recognized)
523 h["Reco_tracks"].Fill("N clones", n_clones)
524 h["Reco_tracks"].Fill("N ghosts", n_ghosts)
525 h["Reco_tracks"].Fill("N others", n_others)
526
527
528
529 save_hists(h, output_file)
530
531 return metrics
532
533
addVMCFields(shipGeo, str controlFile="", bool verbose=False, bool withVirtualMC=True)
create_config(str DecayVolumeMedium="helium", float Yheight=6.0, int strawDesign=10, str shieldName="TRY_2026", int nuTargetPassive=1, bool SND=True, SND_design=None, TARGET_YAML=None)
configure(run, ship_geo, str|None geofile=None)