FairShip
Loading...
Searching...
No Matches
shipStrawTracking.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
3
4"""Script to run and test tracking in the straw tubes"""
5
6from argparse import ArgumentParser
7from typing import Any
8
9import geometry_config
10import global_variables
11import numpy
12import ROOT
13
14# For modules
15import shipDet_conf
16import shipunit as u
17from mc_truth import find_signal_track
18
19# For ShipGeo
20from ShipGeoConfig import load_from_root_file
21
22# For track pattern recognition
23
24
25def get_n_hits(hits) -> int:
26 return len(hits)
27
28
29def cmp(a, b: int):
30 return (a > b) - (a < b)
31
32
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 # This quality-plot step analyses the already-reconstructed Tracklets/
49 # FitTracks branches, so the method argument does not influence the result.
50 # Warn rather than silently ignore a non-default selection.
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 # Check geo file
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 # Prepare ShipGeo dictionary
69 if not fgeo.FindKey("ShipGeo"):
70 if dy:
71 ShipGeo = geometry_config.create_config(Yheight=dy)
72 else:
74 else:
75 ShipGeo = load_from_root_file(fgeo, "ShipGeo")
76
77 # Globals
78 global_variables.ShipGeo = ShipGeo
79
80
81
82 run = ROOT.FairRunSim()
83 run.SetName("TGeant4") # Transport engine
84 # Create dummy output file for FairRunSim; the quality-plot histograms are
85 # written to the separate output file (hists.root by default).
86 import tempfile
87
88 sink = ROOT.FairRootFileSink(tempfile.mktemp(suffix=".root"))
89 run.SetSink(sink)
90 ROOT.SetOwnership(sink, False) # C++ FairRun takes ownership
91 run.SetUserConfig("g4Config_basic.C") # geant4 transport not used, only needed for the mag field
92 run.GetRuntimeDb()
93
94 shipDet_conf.configure(run, ShipGeo)
95 run.Init()
96
97 # run = ROOT.FairRunSim()
98 # modules = shipDet_conf.configure(run,ShipGeo)
99
100
101
102 import geomGeant4
103
104 if hasattr(ShipGeo.Bfield, "fieldMap"):
105 fieldMaker = geomGeant4.addVMCFields(ShipGeo, "", True, withVirtualMC=False)
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 # Check input file. This is a read-only QA step: it reads the existing
120 # branches and writes quality plots to the separate output file, so open the
121 # input read-only rather than "update" (which rewrote a duplicate key cycle
122 # of the unmodified tree into the user's file on every invocation).
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 # Init book of hists for the quality measurements.
138 # Mixed counter/list values, so type as dict[str, Any].
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 # Start event loop
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: # this is a not full track (tracklet)
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 # List to numpy arrays
248 hits = {key: numpy.array(values) for key, values in hits.items()}
249
250 # Decoding
251 decode = global_variables.modules["strawtubes"].StrawDecode(hits["DetID"])
252 # StrawDecode returns a tuple of (statnb, vnb, lnb, snb).
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 # Metrics
259 metrics["n_hits"] += [get_n_hits(hits["TrackID"])]
260
261 # Tracks passed
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 # For reconstructed tracks
359 if is_reconstructed == 0:
360 continue
361
362 metrics["reco_frac_tot"] += [frac_tot]
363
364 # Momentum
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 # Direction
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 # Fitted track
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 # *int(charge)
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 # A track without a fitted state is expected; skip it. Momentum
516 # divisions (ZeroDivisionError), histogram lookups/fills
517 # (KeyError) and extrapolation errors are real bugs and must not
518 # be masked here, so only the genfit fitted-state failure is caught.
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
534
536
537
539 # etrapolate to a plane perpendicular to beam direction (z)
540 rc, pos, mom = False, None, None
541 parallelToZ = ROOT.TVector3(0.0, 0.0, 1.0)
542 fst = fT.getFitStatus()
543 if fst.isFitConverged():
544 # test for fit status for each point
545 if fT.getPoint(0).getFitterInfo() and fT.getPoint(1).getFitterInfo():
546 fstate0, fstate1 = fT.getFittedState(0), fT.getFittedState(1)
547 fPos0, fPos1 = fstate0.getPos(), fstate1.getPos()
548 if abs(z - fPos0.z()) < abs(z - fPos1.z()):
549 fstate = fstate0
550 else:
551 fstate = fstate1
552 zs = z
553 NewPosition = ROOT.TVector3(0.0, 0.0, zs)
554 # muon hypothesis (+-13), keeping the sign of the fitted PDG code
555 # (the PDG-code sign is opposite to the muon's charge sign)
556 rep = ROOT.genfit.RKTrackRep(13 * cmp(fstate.getPDG(), 0))
557 state = ROOT.genfit.StateOnPlane(rep)
558 pos, mom = fstate.getPos(), fstate.getMom()
559 rep.setPosMom(state, pos, mom)
560 detPlane = ROOT.genfit.DetPlane(NewPosition, parallelToZ)
561 detPlanePtr = ROOT.genfit.SharedPlanePtr(detPlane)
562 try:
563 rep.extrapolateToPlane(state, detPlanePtr)
564 pos, mom = state.getPos(), state.getMom()
565 rc = True
566 except Exception:
567 print("error with extrapolation")
568 if not rc:
569 # use linear extrapolation
570 px, py, pz = mom.X(), mom.Y(), mom.Z()
571 lam = (z - pos.Z()) / pz
572 pos = ROOT.TVector3(pos.X() + lam * px, pos.Y() + lam * py, z)
573 return rc, pos, mom
574
575
576
577
578
579def fracMCsame(trackids):
580 """
581 Estimates max fraction of true hit labels for a recognized track.
582 trackids : array_like
583 hit indexes of a recognized track
584 Returns
585 -------
586 frac : float
587 Max fraction of true hit labels.
588 tmax : int
589 True hit label with max fraction in a recognized track.
590 """
591
592 track = {}
593 nh = len(trackids)
594
595 for tid in trackids:
596 if tid in track:
597 track[tid] += 1
598 else:
599 track[tid] = 1
600
601 # now get track with largest number of hits
602 if track != {}:
603 tmax = max(track, key=lambda k: track[k])
604 else:
605 track = {-999: 0}
606 tmax = -999
607
608 frac = 0.0
609 if nh > 0:
610 frac = float(track[tmax]) / float(nh)
611
612 return frac, tmax
613
614
615
616
617
618def getReconstructibleTracks(iEvent: int, sTree, sGeo, ShipGeo):
619 """
620 Estimates reconstructible tracks of an event.
621 Parameters
622 ----------
623 iEvent : int
624 Event id.
625 sTree : ROOT.TTree or ROOT.TChain
626 Events in raw format.
627 sGeo : object
628 Contains SHiP detector geometry.
629 ShipGeo : object
630 Contains SHiP detector geometry.
631 Returns
632 -------
633 MCTrackIDs : array-like
634 List of reconstructible track ids.
635 """
636
637 # z extent of the tracker: station z is the centre of its 4 views (2 layers
638 # each), so the first straw layer sits 1.5 view spacings + 0.5 layer
639 # spacings away, plus one straw radius to the straw edge
640 TStationz = ShipGeo.TrackStation1.z
641 Zpos = (
642 TStationz - 3.0 / 2.0 * ShipGeo.strawtubes_geo.delta_z_view - 1.0 / 2.0 * ShipGeo.strawtubes_geo.delta_z_layer
643 )
644 TStation1StartZ = Zpos - ShipGeo.strawtubes_geo.outer_straw_diameter / 2.0
645
646 TStationz = ShipGeo.TrackStation4.z
647 Zpos = (
648 TStationz + 3.0 / 2.0 * ShipGeo.strawtubes_geo.delta_z_view + 1.0 / 2.0 * ShipGeo.strawtubes_geo.delta_z_layer
649 )
650 TStation4EndZ = Zpos + ShipGeo.strawtubes_geo.outer_straw_diameter / 2.0
651
652 ROOT.TDatabasePDG.Instance()
653
654 # returns a list of reconstructible tracks for this event
655 # call this routine once for each event before smearing
656 MCTrackIDs = []
657 sTree.GetEvent(iEvent)
658 nMCTracks = len(sTree.MCTrack)
659
660 # 1. MCTrackIDs: list of tracks decaying after the last tstation and originating before the first
661 for i in reversed(range(nMCTracks)):
662 atrack = sTree.MCTrack[i]
663 # track endpoint after tstations?
664 if atrack.GetStartZ() > TStation4EndZ:
665 motherId = atrack.GetMotherId()
666 if motherId > -1:
667 mothertrack = sTree.MCTrack[motherId]
668 mothertrackZ = mothertrack.GetStartZ()
669 # this mother track is a HNL decay
670 # track starts inside the decay volume? (before 1 st tstation)
671 if mothertrackZ < TStation1StartZ and motherId not in MCTrackIDs:
672 MCTrackIDs.append(motherId)
673
674 if len(MCTrackIDs) == 0:
675 return MCTrackIDs
676
677 # 2. hitsinTimeDet: list of tracks with hits in TimeDet
678 # nVetoHits = len(sTree.vetoPoint)
679 # hitsinTimeDet=[]
680 # for i in range(nVetoHits):
681 # avetohit = sTree.vetoPoint[i]
682 # #hit in TimeDet?
683 # if sGeo.FindNode(avetohit.GetX(), avetohit.GetY(), avetohit.GetZ()).GetName() == 'TimeDet_1':
684 # if avetohit.GetTrackID() not in hitsinTimeDet:
685 # hitsinTimeDet.append(avetohit.GetTrackID())
686
687 # 3. Remove tracks from MCTrackIDs that are not in hitsinTimeDet
688 # itemstoremove = []
689 # for item in MCTrackIDs:
690 # if item not in hitsinTimeDet:
691 # itemstoremove.append(item)
692 # for item in itemstoremove:
693 # MCTrackIDs.remove(item)
694
695 # if len(MCTrackIDs)==0:
696 # return MCTrackIDs
697
698 # 4. Find straws that have multiple hits
699 nHits = len(sTree.strawtubesPoint)
700 hitstraws = {}
701 duplicatestrawhit = set()
702
703 for i in range(nHits):
704 ahit = sTree.strawtubesPoint[i]
705 strawname = str(ahit.GetDetectorID())
706
707 if strawname in hitstraws:
708 # straw was already hit
709 if ahit.GetX() > hitstraws[strawname][1]:
710 # this hit has higher x, discard it
711 duplicatestrawhit.add(i)
712 else:
713 # del hitstraws[strawname]
714 duplicatestrawhit.add(hitstraws[strawname][0])
715 hitstraws[strawname] = [i, ahit.GetX()]
716 else:
717 hitstraws[strawname] = [i, ahit.GetX()]
718
719 # 5. Split hits up by station and outside stations
720 hits1 = {}
721 hits2 = {}
722 hits3 = {}
723 hits4 = {}
724 trackoutsidestations = set()
725
726 margin = 5.0 * u.cm
727 x_bound = ShipGeo.strawtubes_geo.width - margin
728 y_bound = ShipGeo.strawtubes_geo.height - margin
729
730 for i in range(nHits):
731 if i in duplicatestrawhit:
732 continue
733
734 ahit = sTree.strawtubesPoint[i]
735
736 # is hit inside acceptance (width/height minus margin)?
737 if abs(ahit.GetX()) >= x_bound or abs(ahit.GetY()) >= y_bound:
738 trackoutsidestations.add(ahit.GetTrackID())
739
740 if ahit.GetTrackID() not in MCTrackIDs:
741 # hit on not reconstructible track
742 continue
743
744 # group hits per tracking station, key = trackid
745 if str(ahit.GetDetectorID())[:1] == "1":
746 if ahit.GetTrackID() in hits1:
747 hits1[ahit.GetTrackID()] = [hits1[ahit.GetTrackID()][0], i]
748 else:
749 hits1[ahit.GetTrackID()] = [i]
750
751 if str(ahit.GetDetectorID())[:1] == "2":
752 if ahit.GetTrackID() in hits2:
753 hits2[ahit.GetTrackID()] = [hits2[ahit.GetTrackID()][0], i]
754 else:
755 hits2[ahit.GetTrackID()] = [i]
756
757 if str(ahit.GetDetectorID())[:1] == "3":
758 if ahit.GetTrackID() in hits3:
759 hits3[ahit.GetTrackID()] = [hits3[ahit.GetTrackID()][0], i]
760 else:
761 hits3[ahit.GetTrackID()] = [i]
762
763 if str(ahit.GetDetectorID())[:1] == "4":
764 if ahit.GetTrackID() in hits4:
765 hits4[ahit.GetTrackID()] = [hits4[ahit.GetTrackID()][0], i]
766 else:
767 hits4[ahit.GetTrackID()] = [i]
768
769 # 6. Make list of tracks with hits in in station 1,2,3 & 4
770 tracks_with_hits_in_all_stations = []
771
772 for key in hits1:
773 if (key in hits2 and key in hits3) and key in hits4:
774 if key not in tracks_with_hits_in_all_stations and key not in trackoutsidestations:
775 tracks_with_hits_in_all_stations.append(key)
776
777 for key in hits2:
778 if (key in hits1 and key in hits3) and key in hits4:
779 if key not in tracks_with_hits_in_all_stations and key not in trackoutsidestations:
780 tracks_with_hits_in_all_stations.append(key)
781
782 for key in hits3:
783 if (key in hits2 and key in hits1) and key in hits4:
784 if key not in tracks_with_hits_in_all_stations and key not in trackoutsidestations:
785 tracks_with_hits_in_all_stations.append(key)
786
787 for key in hits4:
788 if (key in hits2 and key in hits3) and key in hits1:
789 if key not in tracks_with_hits_in_all_stations and key not in trackoutsidestations:
790 tracks_with_hits_in_all_stations.append(key)
791
792 # 7. Remove tracks from MCTrackIDs with hits outside acceptance or doesn't have hits in all stations
793 itemstoremove = []
794
795 for item in MCTrackIDs:
796 if item not in tracks_with_hits_in_all_stations:
797 itemstoremove.append(item)
798
799 for item in itemstoremove:
800 MCTrackIDs.remove(item)
801
802 if len(MCTrackIDs) == 0:
803 return MCTrackIDs
804
805 # 8. Keep only the daughters of the signal particle. Everything else that
806 # reaches the tracker is a Geant secondary (delta ray, bremsstrahlung).
807 signalId = find_signal_track(sTree.MCTrack)
808
809 if signalId is None:
810 print(f"Warning: no signal track found in event {iEvent}, skipping the signal-daughter filter.")
811 else:
812 itemstoremove = [item for item in MCTrackIDs if sTree.MCTrack[item].GetMotherId() != signalId]
813
814 for item in itemstoremove:
815 MCTrackIDs.remove(item)
816
817 return MCTrackIDs
818
819
820def getPtruthFirst(sTree, mcPartKey):
821 Ptruth, Ptruthx, Ptruthy, Ptruthz = -1.0, -1.0, -1.0, -1.0
822 for ahit in sTree.strawtubesPoint:
823 if ahit.GetTrackID() == mcPartKey:
824 Ptruthx, Ptruthy, Ptruthz = ahit.GetPx(), ahit.GetPy(), ahit.GetPz()
825 Ptruth = ROOT.TMath.Sqrt(Ptruthx**2 + Ptruthy**2 + Ptruthz**2)
826 break
827 return Ptruth, Ptruthx, Ptruthy, Ptruthz
828
829
830
832
833import math
834
835import rootUtils as ut
836
837
838
839
840
841
842
843def save_hists(h, path) -> None:
844 """
845 Save book of plots.
846 Parameters
847 ----------
848 h : dict
849 Dictionary of plots.
850 path : string
851 Path where the plots will be saved.
852 """
853 ut.writeHists(h, path)
854
855
857 """
858 Creates empty plots.
859 Returns
860 -------
861 h : dict
862 Dictionary of plots.
863 """
864
865 h = {} # dictionary of histograms
866
867 ut.bookHist(h, "TracksPassed", "Tracks passing the pattern recognition", 8, -0.5, 7.5)
868 h["TracksPassed"].GetXaxis().SetBinLabel(1, "Reconstructible tracks")
869 h["TracksPassed"].GetXaxis().SetBinLabel(2, "Y view station 1&2")
870 h["TracksPassed"].GetXaxis().SetBinLabel(3, "Stereo station 1&2")
871 h["TracksPassed"].GetXaxis().SetBinLabel(4, "station 1&2")
872 h["TracksPassed"].GetXaxis().SetBinLabel(5, "Y view station 3&4")
873 h["TracksPassed"].GetXaxis().SetBinLabel(6, "Stereo station 3&4")
874 h["TracksPassed"].GetXaxis().SetBinLabel(7, "station 3&4")
875 h["TracksPassed"].GetXaxis().SetBinLabel(8, "Combined stations 1&2/3&4")
876
877 ut.bookHist(h, "TracksPassedU", "Tracks passing the pattern recognition. No clones.", 8, -0.5, 7.5)
878 h["TracksPassedU"].GetXaxis().SetBinLabel(1, "Reconstructible tracks")
879 h["TracksPassedU"].GetXaxis().SetBinLabel(2, "Y view station 1&2")
880 h["TracksPassedU"].GetXaxis().SetBinLabel(3, "Stereo station 1&2")
881 h["TracksPassedU"].GetXaxis().SetBinLabel(4, "station 1&2")
882 h["TracksPassedU"].GetXaxis().SetBinLabel(5, "Y view station 3&4")
883 h["TracksPassedU"].GetXaxis().SetBinLabel(6, "Stereo station 3&4")
884 h["TracksPassedU"].GetXaxis().SetBinLabel(7, "station 3&4")
885 h["TracksPassedU"].GetXaxis().SetBinLabel(8, "Combined stations 1&2/3&4")
886
887 ut.bookProf(h, "TracksPassed_p", "Tracks passing the pattern recognition from momentum", 30, 0, 150)
888 h["TracksPassed_p"].GetXaxis().SetTitle("Momentum")
889 h["TracksPassed_p"].GetYaxis().SetTitle("N")
890
891 ut.bookHist(h, "ptrue-p/ptrue", "(p - p-true)/p", 200, -0.25, 0.25)
892 ut.bookHist(h, "pttrue-pt/pttrue", "(pt - pt-true)/pt", 200, -0.25, 0.25)
893 ut.bookHist(h, "pxtrue-px/pxtrue", "(px - px-true)/px", 200, -0.25, 0.25)
894 ut.bookHist(h, "pytrue-py/pytrue", "(py - py-true)/py", 200, -0.25, 0.25)
895 ut.bookHist(h, "pztrue-pz/pztrue", "(pz - pz-true)/pz", 200, -0.25, 0.25)
896
897 ut.bookHist(h, "n_hits_reco", "Number of recognized hits per track, total", 64, 0.0, 64.01)
898 ut.bookHist(h, "n_hits_reco_12", "Number of recognized hits per track, station 1&2", 32, 0.0, 32.01)
899 ut.bookHist(h, "n_hits_reco_y12", "Number of recognized hits per track, Y view station 1&2", 32, 0.0, 32.01)
900 ut.bookHist(
901 h, "n_hits_reco_stereo12", "Number of recognized hits per track, Stereo view station 1&2", 32, 0.0, 32.01
902 )
903 ut.bookHist(h, "n_hits_reco_34", "Number of recognized hits per track, station 3&4", 32, 0.0, 32.01)
904 ut.bookHist(h, "n_hits_reco_y34", "Number of recognized hits per track, Y view station 3&4", 32, 0.0, 32.01)
905 ut.bookHist(
906 h, "n_hits_reco_stereo34", "Number of recognized hits per track, Stereo view station 3&4", 32, 0.0, 32.01
907 )
908
909 # Momentum dependences
910 ut.bookProf(h, "n_hits_total", "Number of recognized hits per track, total", 30, 0, 150)
911 h["n_hits_total"].GetXaxis().SetTitle("Momentum")
912 h["n_hits_total"].GetYaxis().SetTitle("N")
913
914 ut.bookProf(h, "n_hits_y12", "Number of recognized hits per track, Y view station 1&2", 30, 0, 150)
915 h["n_hits_y12"].GetXaxis().SetTitle("Momentum")
916 h["n_hits_y12"].GetYaxis().SetTitle("N")
917
918 ut.bookProf(h, "n_hits_stereo12", "Number of recognized hits per track, Stereo view station 1&2", 30, 0, 150)
919 h["n_hits_stereo12"].GetXaxis().SetTitle("Momentum")
920 h["n_hits_stereo12"].GetYaxis().SetTitle("N")
921
922 ut.bookProf(h, "n_hits_12", "Number of recognized hits per track, station 1&2", 30, 0, 150)
923 h["n_hits_12"].GetXaxis().SetTitle("Momentum")
924 h["n_hits_12"].GetYaxis().SetTitle("N")
925
926 ut.bookProf(h, "n_hits_y34", "Number of recognized hits per track, Y view station 3&4", 30, 0, 150)
927 h["n_hits_y34"].GetXaxis().SetTitle("Momentum")
928 h["n_hits_y34"].GetYaxis().SetTitle("N")
929
930 ut.bookProf(h, "n_hits_stereo34", "Number of recognized hits per track, Stereo view station 3&4", 30, 0, 150)
931 h["n_hits_stereo34"].GetXaxis().SetTitle("Momentum")
932 h["n_hits_stereo34"].GetYaxis().SetTitle("N")
933
934 ut.bookProf(h, "n_hits_34", "Number of recognized hits per track, station 3&4", 30, 0, 150)
935 h["n_hits_34"].GetXaxis().SetTitle("Momentum")
936 h["n_hits_34"].GetYaxis().SetTitle("N")
937
938 ut.bookProf(h, "perr", "(p - p-true)/p", 30, 0, 150)
939 h["perr"].GetXaxis().SetTitle("Momentum")
940 h["perr"].GetYaxis().SetTitle("(p - p-true)/p")
941
942 ut.bookProf(h, "perr_direction", "(p - p-true)/p from track direction in YZ plane", 20, 0, 10.01)
943 h["perr_direction"].GetXaxis().SetTitle("Degree")
944 h["perr_direction"].GetYaxis().SetTitle("(p - p-true)/p")
945
946 ut.bookProf(h, "frac_total", "Fraction of hits the same as MC hits, total", 30, 0, 150)
947 h["frac_total"].GetXaxis().SetTitle("Momentum")
948 h["frac_total"].GetYaxis().SetTitle("Fraction")
949
950 ut.bookProf(h, "frac_y12", "Fraction of hits the same as MC hits, Y view station 1&2", 30, 0, 150)
951 h["frac_y12"].GetXaxis().SetTitle("Momentum")
952 h["frac_y12"].GetYaxis().SetTitle("Fraction")
953
954 ut.bookProf(h, "frac_stereo12", "Fraction of hits the same as MC hits, Stereo view station 1&2", 30, 0, 150)
955 h["frac_stereo12"].GetXaxis().SetTitle("Momentum")
956 h["frac_stereo12"].GetYaxis().SetTitle("Fraction")
957
958 ut.bookProf(h, "frac_12", "Fraction of hits the same as MC hits, station 1&2", 30, 0, 150)
959 h["frac_12"].GetXaxis().SetTitle("Momentum")
960 h["frac_12"].GetYaxis().SetTitle("Fraction")
961
962 ut.bookProf(h, "frac_y34", "Fraction of hits the same as MC hits, Y view station 3&4", 30, 0, 150)
963 h["frac_y34"].GetXaxis().SetTitle("Momentum")
964 h["frac_y34"].GetYaxis().SetTitle("Fraction")
965
966 ut.bookProf(h, "frac_stereo34", "Fraction of hits the same as MC hits, Stereo view station 3&4", 30, 0, 150)
967 h["frac_stereo34"].GetXaxis().SetTitle("Momentum")
968 h["frac_stereo34"].GetYaxis().SetTitle("Fraction")
969
970 ut.bookProf(h, "frac_34", "Fraction of hits the same as MC hits, station 3&4", 30, 0, 150)
971 h["frac_34"].GetXaxis().SetTitle("Momentum")
972 h["frac_34"].GetYaxis().SetTitle("Fraction")
973
974 ut.bookHist(h, "frac_y12_dist", "Fraction of hits the same as MC hits, Y view station 1&2", 50, 0.5, 1.001)
975 ut.bookHist(
976 h, "frac_stereo12_dist", "Fraction of hits the same as MC hits, Stereo view station 1&2", 50, 0.5, 1.001
977 )
978 ut.bookHist(h, "frac_12_dist", "Fraction of hits the same as MC hits, station 1&2", 50, 0.5, 1.001)
979 ut.bookHist(h, "frac_y34_dist", "Fraction of hits the same as MC hits, Y view station 3&4", 50, 0.5, 1.001)
980 ut.bookHist(
981 h, "frac_stereo34_dist", "Fraction of hits the same as MC hits, Stereo view station 3&4", 50, 0.5, 1.001
982 )
983 ut.bookHist(h, "frac_34_dist", "Fraction of hits the same as MC hits, station 3&4", 50, 0.5, 1.001)
984 ut.bookHist(h, "frac_total_dist", "Fraction of hits the same as MC hits, total", 50, 0.5, 1.001)
985
986 ut.bookHist(
987 h, "Reco_tracks", "Number of recognized tracks, clones and ghosts for reconstructible tracks.", 5, -0.5, 4.5
988 )
989 h["Reco_tracks"].GetXaxis().SetBinLabel(1, "N total")
990 h["Reco_tracks"].GetXaxis().SetBinLabel(2, "N recognized tracks")
991 h["Reco_tracks"].GetXaxis().SetBinLabel(3, "N clones")
992 h["Reco_tracks"].GetXaxis().SetBinLabel(4, "N ghosts")
993 h["Reco_tracks"].GetXaxis().SetBinLabel(5, "N others")
994
995 # Fitted values
996 ut.bookHist(h, "chi2fittedtracks", "Chi^2 per NDOF for fitted tracks", 210, -0.05, 20.05)
997 ut.bookHist(h, "pvalfittedtracks", "pval for fitted tracks", 110, -0.05, 1.05)
998 ut.bookHist(h, "momentumfittedtracks", "momentum for fitted tracks", 251, -0.05, 250.05)
999 ut.bookHist(h, "xdirectionfittedtracks", "x-direction for fitted tracks", 91, -0.5, 90.5)
1000 ut.bookHist(h, "ydirectionfittedtracks", "y-direction for fitted tracks", 91, -0.5, 90.5)
1001 ut.bookHist(h, "zdirectionfittedtracks", "z-direction for fitted tracks", 91, -0.5, 90.5)
1002 ut.bookHist(h, "massfittedtracks", "mass fitted tracks", 210, -0.005, 0.205)
1003 ut.bookHist(h, "pvspfitted", "p-patrec vs p-fitted", 401, -200.5, 200.5, 401, -200.5, 200.5)
1004
1005 ut.bookHist(h, "abs(x - x-true)", "Hits abs(x - x-true)", 260, -0.05, 5.05)
1006 ut.bookHist(h, "abs(y - y-true)", "Hits abs(y - y-true)", 260, -0.05, 5.05)
1007
1008 ut.bookHist(h, "rmse_x", "Hits x fit rmse", 260, -0.05, 5.05)
1009 ut.bookHist(h, "rmse_y", "Hits y fit rmse", 260, -0.05, 5.05)
1010
1011 return h
1012
1013
1014
1016
1017
1018if __name__ == "__main__":
1019 parser = ArgumentParser(description=__doc__)
1020 parser.add_argument("-f", "--input", help="Input file", required=True)
1021 parser.add_argument("-g", "--geo", help="Geometry file", required=True)
1022 parser.add_argument("-o", "--output", help="Output file", default="hists.root")
1023 parser.add_argument(
1024 "-m",
1025 "--method",
1026 help="Track pattern recognition method",
1027 choices=["Baseline", "FH", "AR", "R"],
1028 default="Baseline",
1029 )
1030 options = parser.parse_args()
1031
1032 metrics = run_track_pattern_recognition(options.input, options.geo, options.output, options.method)
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)
None save_hists(h, path)
Helping functions #####################################################.
getReconstructibleTracks(int iEvent, sTree, sGeo, ShipGeo)
run_track_pattern_recognition(input_file, geo_file, output_file, method, dy=None)
getPtruthFirst(sTree, mcPartKey)