40 def __init__(self, finput, fout, fgeo, validation: bool =
False) ->
None:
42 self.
trackFitter = getattr(global_variables,
"trackFitter",
"acts")
53 self.
recoTree = ROOT.TTree(
"ship_reco_sim",
"Digitization and Reconstruction")
56 if self.
sTree.GetBranch(
"GeoTracks"):
57 self.
sTree.SetBranchStatus(
"GeoTracks", 0)
91 if "strawtubes" in global_variables.modules:
94 if self.
sTree.GetBranch(
"MTCDetPoint"):
96 if self.
sTree.GetBranch(
"SiliconTargetPoint"):
98 "SiliconTarget", self.
sTree,
"SiliconTarget", outtree=self.
recoTree
100 if self.
sTree.GetBranch(
"vetoPoint"):
104 if self.
sTree.GetBranch(
"TimeDetPoint"):
106 if self.
sTree.GetBranch(
"UpstreamTaggerPoint"):
109 "UpstreamTagger", self.
sTree, mcBranchName=
"digiUBT2MC", outtree=self.
recoTree
111 except UBTGeometryMismatch
as error:
112 logger.warning(
"%s: %s; the UBT is not digitized.", fgeo.GetName(), error)
113 if self.
sTree.GetBranch(
"CaloScoringPlanePoint"):
117 elif getattr(global_variables,
"caloScoringPlanePIDFile",
None):
119 "--caloScoringPlanePID was given, but the input has no CaloScoringPlanePoint branch "
120 "(simulated before the scoring plane existed?); it is ignored and no scoring-plane hits are made."
124 if hasattr(self,
"strawtubes"):
125 self.
v_drift = global_variables.modules[
"strawtubes"].StrawVdrift()
126 self.
sigma_spatial = global_variables.modules[
"strawtubes"].StrawSigmaSpatial()
133 ROOT.gRandom.SetSeed(13)
134 self.
PDG = ROOT.TDatabasePDG.Instance()
136 self.
sTree.GetEvent(0)
140 self.
actsTracker = make_tracker(ROOT.gGeoManager, global_variables.fieldMaker.getGlobalField())
143 self.
geoMat = ROOT.genfit.TGeoMaterialInterface()
145 self.
bfield = ROOT.genfit.FairShipFields()
146 self.
bfield.setField(global_variables.fieldMaker.getGlobalField())
147 self.
fM = ROOT.genfit.FieldManager.getInstance()
149 ROOT.SetOwnership(self.
bfield,
False)
150 ROOT.genfit.MaterialEffects.getInstance().init(self.
geoMat)
151 ROOT.SetOwnership(self.
geoMat,
False)
157 self.
fitter.setMaxIterations(50)
158 if global_variables.debug:
159 self.
fitter.setDebugLvl(1)
197 """Fit tracks and vertices with ACTS and persist them.
199 Fills the RecoTracks/RecoVertices/Particles branches, the MC link
200 and Tracklets, and the SBT veto links.
209 tracks, vertices, track_hit_indices = self.
actsTracks()
211 for track, hit_indices
in zip(tracks, track_hit_indices, strict=
True):
216 global_variables.h[
"nmeas"].Fill(nmeas)
217 global_variables.h[
"chi2"].Fill(track.chi2() / nmeas)
224 indices_vector = ROOT.std.vector(
"unsigned int")()
225 for index
in hit_indices:
235 if len(vtx.trackIds()) != 2:
236 logger.debug(
"Skipping vertex with %d tracks (expected 2)", len(vtx.trackIds()))
238 t1, t2 = vtx.trackIds()
240 P = ROOT.TLorentzVector()
241 covP = np.zeros((4, 4))
243 p = np.array([vtx.trackPx()[i], vtx.trackPy()[i], vtx.trackPz()[i]])
244 energy = math.hypot(np.linalg.norm(p), MUON_MASS)
245 P += ROOT.TLorentzVector(float(p[0]), float(p[1]), float(p[2]), energy)
246 cov = np.zeros((3, 3))
247 cov[np.triu_indices(3)] = list(vtx.GetTrackMomentumCovariance(i))
248 cov = cov + np.triu(cov, 1).T
250 jacobian = np.vstack([np.eye(3), p / energy])
251 covP += jacobian @ cov @ jacobian.T
252 vertex_position_4d = ROOT.TLorentzVector(vtx.x(), vtx.y(), vtx.z(), 0.0)
253 particle = ROOT.ShipParticle(9900015, 0, -1, -1, t1, t2, P, vertex_position_4d)
257 particle.SetCovP(list(covP[np.triu_indices(4)]))
258 particle.SetCovV(list(vtx.GetCovarianceElements()))
259 particle.SetDoca(vtx.doca())
262 if hasattr(self,
"digiSBT"):
268 for hitID, distMin
in veto_results:
282 if n_good_tracks > 0:
284 validation_tools.record_event_stat(self.
validation_stats,
"event_fitted_tracks", n_tracks)
285 validation_tools.record_event_stat(self.
validation_stats,
"event_good_tracks", n_good_tracks)
286 if hasattr(self,
"digiSBT"):
288 validation_tools.record_event_stat(
293 """Collect this event's straw hits and fit track candidates with ACTS.
295 Returns (fitted tracks, vertices, per-track hit indices into
298 if global_variables.patRec
in (
"Truth",
"Segments"):
302 if global_variables.withT0:
315 digiHit = int(sm[
"digiHit"])
317 point = self.
sTree.strawtubesPoint[digiHit]
320 detector_id=digi.GetDetectorID(),
321 station=digi.GetStationNumber(),
322 view=digi.GetViewNumber(),
323 layer=digi.GetLayerNumber(),
324 track_id=point.GetTrackID(),
330 digi_to_straw[digiHit] = k
332 if global_variables.patRec ==
"Truth":
334 elif candidates
is not None:
337 for cand
in candidates:
338 cand[
"indices"] = [digi_to_straw[i]
for i
in cand[
"indices"]
if i
in digi_to_straw]
345 fit_vertex=global_variables.vertexing,
389 """Digitize, run pattern recognition and build fitter-agnostic track candidates.
391 Each candidate holds the seed state, hit measurements and indices;
392 fitting is done separately (e.g. by fitTracksGenfit).
395 hit_detector_ids = {}
396 stationCrossed: dict[int, dict[int, int]] = {}
397 listOfIndices: dict[int, list[int]] = {}
398 trackParams: dict[int, dict] = {}
401 if global_variables.withT0:
413 logger.debug(
"PatRec returned %d track candidates", len(track_hits))
416 if len(track_hits) > 0:
418 validation_tools.record_event_stat(self.
validation_stats,
"event_track_candidates", len(track_hits))
420 for i_track
in track_hits:
421 atrack = track_hits[i_track]
422 atrack_y12 = atrack[
"y12"]
423 atrack_stereo12 = atrack[
"stereo12"]
424 atrack_y34 = atrack[
"y34"]
425 atrack_stereo34 = atrack[
"stereo34"]
426 atrack_smeared_hits = list(atrack_y12) + list(atrack_stereo12) + list(atrack_y34) + list(atrack_stereo34)
428 trackParams[i_track] = {
429 "k_y12": atrack.get(
"k_y12"),
430 "b_y12": atrack.get(
"b_y12"),
431 "k_y34": atrack.get(
"k_y34"),
432 "b_y34": atrack.get(
"b_y34"),
434 for sm
in atrack_smeared_hits:
436 station = self.
strawtubes.det[sm[
"digiHit"]].GetStationNumber()
439 if trID
not in hitPosLists:
440 hitPosLists[trID] = ROOT.std.vector(
"TVectorD")()
441 listOfIndices[trID] = []
442 stationCrossed[trID] = {}
443 hit_detector_ids[trID] = ROOT.std.vector(
"int")()
444 hit_detector_ids[trID].push_back(detID)
445 m = array(
"d", [sm[
"xtop"], sm[
"ytop"], sm[
"z"], sm[
"xbot"], sm[
"ybot"], sm[
"z"], sm[
"dist"]])
446 hitPosLists[trID].push_back(ROOT.TVectorD(7, m))
447 listOfIndices[trID].append(sm[
"digiHit"])
448 if station
not in stationCrossed[trID]:
449 stationCrossed[trID][station] = 0
450 stationCrossed[trID][station] += 1
453 n_too_few_stations = 0
454 track_candidates = []
456 for atrack
in hitPosLists:
462 params = trackParams.get(atrack, {})
463 k_y12 = params.get(
"k_y12")
464 k_y34 = params.get(
"k_y34")
465 if k_y12
is not None and k_y34
is not None:
468 pdg = 13
if k_y34 > k_y12
else -13
473 charge = -1
if pdg > 0
else 1
474 meas = hitPosLists[atrack]
475 detIDs = hit_detector_ids[atrack]
477 n_stations_crossed = len(stationCrossed[atrack])
483 self.
validation_stats[
"candidate_stations_sum_sq"] += n_stations_crossed * n_stations_crossed
485 if nM < MIN_HITS_PER_TRACK:
488 if n_stations_crossed < MIN_STATIONS_CROSSED:
489 n_too_few_stations += 1
491 if global_variables.debug:
492 self.
sTree.MCTrack[atrack]
497 track_candidates.append(
505 "indices": listOfIndices[atrack],
510 "findTracks: %d candidates, %d too few hits, %d too few stations, %d candidates kept for fitting",
514 len(track_candidates),
518 self.
validation_stats[
"track_candidates_rejected_stations"] += n_too_few_stations
520 return track_candidates
523 """Fit track candidates with GenFit and persist the fitted tracks."""
529 for cand
in candidates:
532 detIDs = cand[
"detIDs"]
534 posM, momM = cand[
"pos"], cand[
"mom"]
538 best_chi2ndf = float(
"inf")
539 for try_pdg
in [pdg, -pdg]:
543 covM = ROOT.TMatrixDSym(6)
545 if global_variables.withT0:
548 covM[i][i] = resolution * resolution
551 covM[0][0] = resolution * resolution * 100.0
552 for i
in range(3, 6):
553 covM[i][i] = ROOT.TMath.Power(resolution / nM / ROOT.TMath.Sqrt(3), 2)
554 rep = ROOT.genfit.RKTrackRep(try_pdg)
555 stateSmeared = ROOT.genfit.MeasuredStateOnPlane(rep)
556 rep.setPosMomCov(stateSmeared, posM, momM, covM)
557 seedState = ROOT.TVectorD(6)
558 seedCov = ROOT.TMatrixDSym(6)
559 rep.get6DStateCov(stateSmeared, seedState, seedCov)
560 theTrack = ROOT.genfit.Track(rep, seedState, seedCov)
561 ROOT.SetOwnership(rep,
False)
562 hitCov = ROOT.TMatrixDSym(7)
563 hitCov[6][6] = resolution * resolution
565 for m, detID
in zip(meas, detIDs, strict=
True):
566 tp = ROOT.genfit.TrackPoint(theTrack)
567 measurement = ROOT.genfit.WireMeasurement(m, hitCov, detID, hitID, tp)
568 measurement.setMaxDistance(
569 global_variables.ShipGeo.strawtubes_geo.outer_straw_diameter / 2.0
570 - global_variables.ShipGeo.strawtubes_geo.wall_thickness
572 tp.addRawMeasurement(measurement)
573 ROOT.SetOwnership(measurement,
False)
574 theTrack.insertPoint(tp)
575 ROOT.SetOwnership(tp,
False)
579 theTrack.checkConsistency()
580 except ROOT.genfit.Exception:
585 self.
fitter.processTrack(theTrack)
586 except Exception
as e:
587 logger.debug(
"Failed to processTrack for hypothesis %d: %s", try_pdg, e)
592 theTrack.checkConsistency()
593 except ROOT.genfit.Exception:
594 logger.debug(
"Track inconsistent after fit for hypothesis %d", try_pdg)
599 fittedState = theTrack.getFittedState()
600 fittedState.getMomMag()
601 except Exception
as e:
602 logger.debug(
"Failed to getFittedState/getMomMag for hypothesis %d: %s", try_pdg, e)
606 fitStatus = theTrack.getFitStatus()
607 if not fitStatus.isFitConverged():
611 nmeas = fitStatus.getNdf()
614 chi2ndf = fitStatus.getChi2() / nmeas
615 if chi2ndf < best_chi2ndf:
616 best_chi2ndf = chi2ndf
617 best_track = theTrack
618 if best_track
is not None:
619 fittedTracks.append((best_track, cand))
621 for theTrack, cand
in fittedTracks:
623 fitStatus = theTrack.getFitStatus()
624 nmeas = fitStatus.getNdf()
625 global_variables.h[
"nmeas"].Fill(nmeas)
626 chi2 = fitStatus.getChi2() / nmeas
634 global_variables.h[
"chi2"].Fill(chi2)
637 trackCopy = ROOT.genfit.Track(theTrack)
638 ROOT.SetOwnership(trackCopy,
False)
640 if global_variables.debug:
641 print(
"save track", theTrack, chi2, nmeas, fitStatus.isFitConverged())
644 for index
in cand[
"indices"]:
645 ahit = self.
sTree.strawtubesPoint[index]
646 track_ids += [ahit.GetTrackID()]
650 indices = ROOT.std.vector(
"unsigned int")()
651 for index
in cand[
"indices"]:
652 indices.push_back(index)
653 aTracklet = ROOT.Tracklet(1, indices)
656 logger.debug(
"fitTracksGenfit: %d fitted tracks saved", len(self.
fGenFitArray))
659 if global_variables.debug:
660 print(
"save tracklets:")
662 print(x.getType(), len(x.getList()))
666 """Compute seed position and momentum for the track fitter.
668 When PatRec track parameters (k_y, b_y) are available, use them
669 to place the seed at the first hit's Z with the correct Y position
670 and momentum direction. Prefers station 1-2 parameters, falls back
671 to station 3-4, then to a geometry-free default at the first hit.
673 params = trackParams.get(atrack)
677 if params.get(
"k_y12")
is not None and params.get(
"b_y12")
is not None:
678 k_y = params[
"k_y12"]
679 b_y = params[
"b_y12"]
680 elif params.get(
"k_y34")
is not None and params.get(
"b_y34")
is not None:
681 k_y = params[
"k_y34"]
682 b_y = params[
"b_y34"]
686 y_seed = k_y * z_seed + b_y
687 posM = ROOT.TVector3(0, y_seed, z_seed)
688 p_total = 3.0 * u.GeV
689 pz = p_total / ROOT.TMath.Sqrt(1.0 + k_y * k_y)
691 momM = ROOT.TVector3(0, py, pz)
693 "seed from PatRec: z=%.1f y=%.1f k_y=%.4f p=(0, %.2f, %.2f)",
701 posM = ROOT.TVector3(0, 0, z_seed)
702 momM = ROOT.TVector3(0, 0, 3.0 * u.GeV)
742 xx = track.getFittedState()
743 rep = ROOT.genfit.RKTrackRep(xx.getPDG())
744 state = ROOT.genfit.StateOnPlane(rep)
745 rep.setPosMom(state, xx.getPos(), xx.getMom())
746 for i, vetoHit
in enumerate(self.
digiSBT.det):
749 rep.extrapolateToPoint(state, vetoHitPos,
False)
751 error =
"shipDigiReco::findVetoHitOnTrack extrapolation did not worked"
752 ut.reportError(error)
753 if global_variables.debug:
756 dist = (rep.getPos(state) - vetoHitPos).Mag()
760 return ROOT.vetoHitOnTrack(hitID, distMin)