FairShip
Loading...
Searching...
No Matches
ShipAna.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# example for accessing smeared hits and fitted tracks
5from argparse import ArgumentParser
6
7import decorators
8import ROOT
9import rootUtils as ut
10import shipRoot_conf
11import shipunit as u
12from mc_truth import find_signal_track, signal_weight
13from ShipGeoConfig import load_from_root_file
14
17PDG = ROOT.TDatabasePDG.Instance()
18
19chi2CutOff = 4.0
20fiducialCut = False
21measCutFK = 25
22measCutPR = 22
23docaCut = 2.0
24
25parser = ArgumentParser()
26
27parser.add_argument("-f", "--inputFile", dest="inputFile", help="Input file (MC simulation)", required=True)
28parser.add_argument(
29 "-r", "--recoFile", dest="recoFile", help="Reconstruction file (will be used as friend tree)", required=False
30)
31parser.add_argument(
32 "-n", "--nEvents", dest="nEvents", help="Number of events to analyze", required=False, default=999999, type=int
33)
34parser.add_argument("-g", "--geoFile", dest="geoFile", help="ROOT geofile", required=True)
35parser.add_argument("--Debug", dest="Debug", help="Switch on debugging", required=False, action="store_true")
36options = parser.parse_args()
37
38# Determine reconstruction file
39if not options.recoFile:
40 # Default: replace .root with _rec.root, or if already _rec.root use as-is
41 if options.inputFile.find("_rec.root") > 0:
42 options.recoFile = options.inputFile
43 options.inputFile = options.inputFile.replace("_rec.root", ".root")
44 else:
45 options.recoFile = options.inputFile.replace(".root", "_rec.root")
46
47# Open MC simulation file
48if not options.inputFile.find(",") < 0:
49 sTree = ROOT.TChain("cbmsim")
50 recoChain = ROOT.TChain("ship_reco_sim")
51 for x in options.inputFile.split(","):
52 sTree.AddFile(x)
53 for x in options.recoFile.split(","):
54 recoChain.AddFile(x)
55 sTree.AddFriend(recoChain)
56else:
57 f = ROOT.TFile(options.inputFile)
58 sTree = f["cbmsim"]
59 # Add reconstruction data as friend tree
60 sTree.AddFriend("ship_reco_sim", options.recoFile)
61
62from shipTrackAccess import track_info, uses_acts
63
64# reco file written with --trackFitter acts (RecoTracks) or genfit (FitTracks)?
65actsMode = uses_acts(sTree)
66
67if not options.geoFile:
68 options.geoFile = options.inputFile.replace("ship.", "geofile_full.").replace("_rec.", ".")
69fgeo = ROOT.TFile(options.geoFile)
70
71# new geofile, load Shipgeo dictionary written by run_simScript.py
72ShipGeo = load_from_root_file(fgeo, "ShipGeo")
73dy = ShipGeo.Yheight / u.m
74
75# -----Create geometry----------------------------------------------
76import shipDet_conf
77
78run = ROOT.FairRunSim()
79run.SetName("TGeant4") # Transport engine
80import tempfile
81
82sink = ROOT.FairRootFileSink(tempfile.mktemp(suffix=".root"))
83run.SetSink(sink)
84ROOT.SetOwnership(sink, False) # C++ FairRun takes ownership
85run.SetUserConfig("g4Config_basic.C") # geant4 transport not used, only needed for the mag field
86rtdb = run.GetRuntimeDb()
87# -----Create geometry----------------------------------------------
88modules = shipDet_conf.configure(run, ShipGeo)
89
90import geomGeant4
91
92if hasattr(ShipGeo.Bfield, "fieldMap"):
93 fieldMaker = geomGeant4.addVMCFields(ShipGeo, "", True, withVirtualMC=False)
94else:
95 print("no fieldmap given, geofile too old, not anymore support")
96 exit(-1)
97sGeo = fgeo["FAIRGeom"]
98geoMat = ROOT.genfit.TGeoMaterialInterface()
99ROOT.genfit.MaterialEffects.getInstance().init(geoMat)
100ROOT.SetOwnership(geoMat, False) # genfit::MaterialEffects singleton takes ownership
101bfield = ROOT.genfit.FairShipFields()
102bfield.setField(fieldMaker.getGlobalField())
103fM = ROOT.genfit.FieldManager.getInstance()
104fM.init(bfield)
105ROOT.SetOwnership(bfield, False) # genfit::FieldManager singleton takes ownership
106
107volDict = {}
108i = 0
109for x in ROOT.gGeoManager.GetListOfVolumes():
110 volDict[i] = x.GetName()
111 i += 1
112
113# prepare veto decisions
114import shipVeto
115
116veto = shipVeto.Task(sTree)
117vetoDets = {}
118h = {}
119ut.bookHist(h, "delPOverP", "delP / P", 400, 0.0, 200.0, 100, -0.5, 0.5)
120ut.bookHist(h, "pullPOverPx", "delPx / sigma", 400, 0.0, 200.0, 100, -3.0, 3.0)
121ut.bookHist(h, "pullPOverPy", "delPy / sigma", 400, 0.0, 200.0, 100, -3.0, 3.0)
122ut.bookHist(h, "pullPOverPz", "delPz / sigma", 400, 0.0, 200.0, 100, -3.0, 3.0)
123ut.bookHist(h, "delPOverP2", "delP / P chi2/nmeas<" + str(chi2CutOff), 400, 0.0, 200.0, 100, -0.5, 0.5)
124ut.bookHist(h, "delPOverPz", "delPz / Pz", 400, 0.0, 200.0, 100, -0.5, 0.5)
125ut.bookHist(h, "delPOverP2z", "delPz / Pz chi2/nmeas<" + str(chi2CutOff), 400, 0.0, 200.0, 100, -0.5, 0.5)
126ut.bookHist(h, "chi2", "chi2/nmeas after trackfit", 100, 0.0, 10.0)
127ut.bookHist(h, "prob", "prob(chi2)", 100, 0.0, 1.0)
128ut.bookHist(h, "IP", "Impact Parameter", 100, 0.0, 10.0)
129ut.bookHist(h, "Vzresol", "Vz reco - true [cm]", 100, -50.0, 50.0)
130ut.bookHist(h, "Vxresol", "Vx reco - true [cm]", 100, -10.0, 10.0)
131ut.bookHist(h, "Vyresol", "Vy reco - true [cm]", 100, -10.0, 10.0)
132ut.bookHist(h, "Vzpull", "Vz pull", 100, -5.0, 5.0)
133ut.bookHist(h, "Vxpull", "Vx pull", 100, -5.0, 5.0)
134ut.bookHist(h, "Vypull", "Vy pull", 100, -5.0, 5.0)
135ut.bookHist(h, "Doca", "Doca between two tracks", 100, 0.0, 10.0)
136for x in ["", "_pi0"]:
137 ut.bookHist(h, "IP0" + x, "Impact Parameter to target", 100, 0.0, 100.0)
138 ut.bookHist(h, "IP0/mass" + x, "Impact Parameter to target vs mass", 100, 0.0, 2.0, 100, 0.0, 100.0)
139 ut.bookHist(h, "HNL" + x, "reconstructed Mass", 500, 0.0, 2.0)
140ut.bookHist(h, "HNLw", "reconstructed Mass with weights", 500, 0.0, 2.0)
141ut.bookHist(h, "meas", "number of measurements", 40, -0.5, 39.5)
142ut.bookHist(h, "meas2", "number of measurements, fitted track", 40, -0.5, 39.5)
143ut.bookHist(h, "measVSchi2", "number of measurements vs chi2/meas", 40, -0.5, 39.5, 100, 0.0, 10.0)
144ut.bookHist(h, "distu", "distance to wire", 100, 0.0, 1.0)
145ut.bookHist(h, "distv", "distance to wire", 100, 0.0, 1.0)
146ut.bookHist(h, "disty", "distance to wire", 100, 0.0, 1.0)
147ut.bookHist(h, "meanhits", "mean number of hits / track", 50, -0.5, 49.5)
148
149ut.bookHist(h, "extrapTimeDetX", "extrapolation to TimeDet X", 100, -10.0, 10.0)
150ut.bookHist(h, "extrapTimeDetY", "extrapolation to TimeDet Y", 100, -10.0, 10.0)
151
152ut.bookHist(h, "oa", "cos opening angle", 100, 0.999, 1.0)
153# potential Veto detectors
154ut.bookHist(h, "nrtracks", "nr of tracks in signal selected", 10, -0.5, 9.5)
155ut.bookHist(h, "nrSBT", "nr of hits in SBT", 100, -0.5, 99.5)
156
157import TrackExtrapolateTool
158
159
160def VertexError(t1, t2, PosDir, CovMat, scalFac):
161 # with improved Vx x,y resolution
162 a, u = PosDir[t1]["position"], PosDir[t1]["direction"]
163 c, v = PosDir[t2]["position"], PosDir[t2]["direction"]
164 Vsq = v.Dot(v)
165 Usq = u.Dot(u)
166 UV = u.Dot(v)
167 ca = c - a
168 denom = Usq * Vsq - UV**2
169 tmp2 = Vsq * u - UV * v
170 Va = ca.Dot(tmp2) / denom
171 tmp2 = UV * u - Usq * v
172 Vb = ca.Dot(tmp2) / denom
173 X = (a + c + Va * u + Vb * v) * 0.5
174 l1 = a - X + u * Va # l2 = c - X + v*Vb
175 dist = 2.0 * ROOT.TMath.Sqrt(l1.Dot(l1))
176 T = ROOT.TMatrixD(3, 12)
177 for i in range(3):
178 for k in range(4):
179 for j in range(3):
180 KD = 0
181 if i == j:
182 KD = 1
183 if k == 0 or k == 2:
184 # cova and covc
185 temp = (u[j] * Vsq - v[j] * UV) * u[i] + (u[j] * UV - v[j] * Usq) * v[i]
186 sign = -1
187 if k == 2:
188 sign = +1
189 T[i][3 * k + j] = 0.5 * (KD + sign * temp / denom)
190 elif k == 1:
191 # covu
192 aNAZ = denom * (ca[j] * Vsq - v.Dot(ca) * v[j])
193 aZAN = (ca.Dot(u) * Vsq - ca.Dot(v) * UV) * 2 * (u[j] * Vsq - v[j] * UV)
194 bNAZ = denom * (ca[j] * UV + (u.Dot(ca) * v[j]) - 2 * ca.Dot(v) * u[j])
195 bZAN = (ca.Dot(u) * UV - ca.Dot(v) * Usq) * 2 * (u[j] * Vsq - v[j] * UV)
196 T[i][3 * k + j] = 0.5 * (
197 Va * KD + u[i] / denom**2 * (aNAZ - aZAN) + v[i] / denom**2 * (bNAZ - bZAN)
198 )
199 elif k == 3:
200 # covv
201 aNAZ = denom * (2 * ca.Dot(u) * v[j] - ca.Dot(v) * u[j] - ca[j] * UV)
202 aZAN = (ca.Dot(u) * Vsq - ca.Dot(v) * UV) * 2 * (v[j] * Usq - u[j] * UV)
203 bNAZ = denom * (ca.Dot(u) * u[j] - ca[j] * Usq)
204 bZAN = (ca.Dot(u) * UV - ca.Dot(v) * Usq) * 2 * (v[j] * Usq - u[j] * UV)
205 T[i][3 * k + j] = 0.5 * (
206 Vb * KD + u[i] / denom**2 * (aNAZ - aZAN) + v[i] / denom**2 * (bNAZ - bZAN)
207 )
208 transT = ROOT.TMatrixD(12, 3)
209 transT.Transpose(T)
210 CovTracks = ROOT.TMatrixD(12, 12)
211 tlist = [t1, t2]
212 for k in range(2):
213 for i in range(6):
214 for j in range(6):
215 xfac = 1.0
216 if i > 2:
217 xfac = scalFac[tlist[k]]
218 if j > 2:
219 xfac = xfac * scalFac[tlist[k]]
220 CovTracks[i + k * 6][j + k * 6] = CovMat[tlist[k]][i][j] * xfac
221 # if i==5 or j==5 : CovMat[tlist[k]][i][j] = 0 # ignore error on z-direction
222 tmp = ROOT.TMatrixD(3, 12)
223 tmp.Mult(T, CovTracks)
224 covX = ROOT.TMatrixD(3, 3)
225 covX.Mult(tmp, transT)
226 return X, covX, dist
227
228
229from array import array
230
231
232def dist2InnerWall(X, Y, Z):
233 dist = 0
234 # return distance to inner wall perpendicular to z-axis, if outside decayVolume return 0.
235 node = sGeo.FindNode(X, Y, Z)
236 if "decay_medium" not in node.GetName():
237 return dist
238 start = array("d", [X, Y, Z])
239 nsteps = 8
240 dalpha = 2 * ROOT.TMath.Pi() / nsteps
241 X**2 + Y**2
242 minDistance = 100 * u.m
243 for n in range(nsteps):
244 alpha = n * dalpha
245 sdir = array("d", [ROOT.TMath.Sin(alpha), ROOT.TMath.Cos(alpha), 0.0])
246 node = sGeo.InitTrack(start, sdir)
247 sGeo.FindNextBoundary()
248 distance = sGeo.GetStep()
249 if distance < minDistance:
250 minDistance = distance
251 return minDistance
252
253
254def isInFiducial(X, Y, Z) -> bool:
255 if not fiducialCut:
256 return True
257 if ShipGeo.TrackStation1.z < Z:
258 return False
259 # typical x,y Vx resolution for exclusive HNL decays 0.3cm,0.15cm (gaussian width)
260 return not dist2InnerWall(X, Y, Z) < 5 * u.cm
261
262
263#
264def ImpactParameter(point, tPos, tMom):
265 t = 0
266 if hasattr(tMom, "P"):
267 P = tMom.P()
268 else:
269 P = tMom.Mag()
270 for i in range(3):
271 t += tMom(i) / P * (point(i) - tPos(i))
272 dist = 0
273 for i in range(3):
274 dist += (point(i) - tPos(i) - t * tMom(i) / P) ** 2
275 dist = ROOT.TMath.Sqrt(dist)
276 return dist
277
278
279#
280def checkHNLorigin(sTree) -> bool:
281 flag = True
282 if not fiducialCut:
283 return flag
284 flag = False
285 # only makes sense for signal == HNL
286 hnlkey = -1
287 for n in range(len(sTree.MCTrack)):
288 mo = sTree.MCTrack[n].GetMotherId()
289 if mo < 0 or mo >= len(sTree.MCTrack):
290 continue
291 if abs(sTree.MCTrack[mo].GetPdgCode()) == 9900015:
292 hnlkey = n
293 break
294 if hnlkey < 0:
295 ut.reportError("ShipAna: checkHNLorigin, no HNL found")
296 elif hnlkey >= len(sTree.MCTrack):
297 ut.reportError("ShipAna: checkHNLorigin, HNL key out of bounds")
298 else:
299 # MCTrack after HNL should be first daughter
300 theHNLVx = sTree.MCTrack[hnlkey]
301 X, Y, Z = theHNLVx.GetStartX(), theHNLVx.GetStartY(), theHNLVx.GetStartZ()
302 if isInFiducial(X, Y, Z):
303 flag = True
304 return flag
305
306
307def checkFiducialVolume(sTree, tkey: int, dy) -> bool:
308 # extrapolate track to middle of magnet and check if in decay volume
309 inside = True
310 if not fiducialCut:
311 return True
312 if actsMode:
313 pos = ROOT.TVector3()
314 rc = sTree.RecoTracks[tkey].ExtrapolateToZ(ShipGeo.Bfield.z, pos)
315 if not rc:
316 return False
317 if not dist2InnerWall(pos[0], pos[1], pos[2]) > 0:
318 return False
319 return inside
320 fT = sTree.FitTracks[tkey]
321 rc, pos, _mom = TrackExtrapolateTool.extrapolateToPlane(fT, ShipGeo.Bfield.z)
322 if not rc:
323 return False
324 if not dist2InnerWall(pos.X(), pos.Y(), pos.Z()) > 0:
325 return False
326 return inside
327
328
329def getPtruthFirst(sTree, mcPartKey):
330 Ptruth, Ptruthx, Ptruthy, Ptruthz = -1.0, -1.0, -1.0, -1.0
331 for ahit in sTree.strawtubesPoint:
332 if ahit.GetTrackID() == mcPartKey:
333 Ptruthx, Ptruthy, Ptruthz = ahit.GetPx(), ahit.GetPy(), ahit.GetPz()
334 Ptruth = ROOT.TMath.Sqrt(Ptruthx**2 + Ptruthy**2 + Ptruthz**2)
335 break
336 return Ptruth, Ptruthx, Ptruthy, Ptruthz
337
338
339def access2SmearedHits(ev, TrackingHits, MCTracks) -> None:
340 key = 0
341 for ahit in ev.SmearedHits.GetObject():
342 print(ahit[0], ahit[1], ahit[2], ahit[3], ahit[4], ahit[5], ahit[6])
343 # follow link to true MCHit
344 mchit = TrackingHits[key]
345 mctrack = MCTracks[mchit.GetTrackID()]
346 print(mchit.GetZ(), mctrack.GetP(), mctrack.GetPdgCode())
347 key += 1
348
349
350def myVertex(t1, t2, PosDir):
351 # closest distance between two tracks
352 # d = |pq . u x v|/|u x v|
353 a = ROOT.TVector3(PosDir[t1][0](0), PosDir[t1][0](1), PosDir[t1][0](2))
354 u = ROOT.TVector3(PosDir[t1][1](0), PosDir[t1][1](1), PosDir[t1][1](2))
355 c = ROOT.TVector3(PosDir[t2][0](0), PosDir[t2][0](1), PosDir[t2][0](2))
356 v = ROOT.TVector3(PosDir[t2][1](0), PosDir[t2][1](1), PosDir[t2][1](2))
357 pq = a - c
358 uCrossv = u.Cross(v)
359 dist = pq.Dot(uCrossv) / (uCrossv.Mag() + 1e-8)
360 # u.a - u.c + s*|u|**2 - u.v*t = 0
361 # v.a - v.c + s*v.u - t*|v|**2 = 0
362 E = u.Dot(a) - u.Dot(c)
363 F = v.Dot(a) - v.Dot(c)
364 A, B = u.Mag2(), -u.Dot(v)
365 C, D = u.Dot(v), -v.Mag2()
366 t = -(C * E - A * F) / (B * C - A * D)
367 X = c.x() + v.x() * t
368 Y = c.y() + v.y() * t
369 Z = c.z() + v.z() * t
370 return X, Y, Z, abs(dist)
371
372
373def RedoVertexing(t1, t2):
374 PosDir = {}
375 for tr in [t1, t2]:
376 xx = sTree.FitTracks[tr].getFittedState()
377 PosDir[tr] = [xx.getPos(), xx.getDir()]
378 xv, yv, zv, doca = myVertex(t1, t2, PosDir)
379 # as we have learned, need iterative procedure
380 dz = 99999.0
381 reps, states, newPosDir = {}, {}, {}
382 rc = True
383 step = 0
384 while dz > 0.1:
385 zBefore = zv
386 newPos = ROOT.TVector3(xv, yv, zv)
387 # make a new rep for track 1,2
388 for tr in [t1, t2]:
389 xx = sTree.FitTracks[tr].getFittedState()
390 reps[tr] = ROOT.genfit.RKTrackRep(xx.getPDG())
391 states[tr] = ROOT.genfit.StateOnPlane(reps[tr])
392 reps[tr].setPosMom(states[tr], xx.getPos(), xx.getMom())
393 try:
394 reps[tr].extrapolateToPoint(states[tr], newPos, False)
395 except Exception:
396 print("SHiPAna: extrapolation did not work")
397 rc = False
398 break
399 newPosDir[tr] = [reps[tr].getPos(states[tr]), reps[tr].getDir(states[tr])]
400 if not rc:
401 break
402 xv, yv, zv, doca = myVertex(t1, t2, newPosDir)
403 dz = abs(zBefore - zv)
404 step += 1
405 if step > 10:
406 print("abort iteration, too many steps, pos=", xv, yv, zv, " doca=", doca, "z before and dz", zBefore, dz)
407 rc = False
408 break
409 if not rc:
410 return xv, yv, zv, doca, -1 # extrapolation failed, makes no sense to continue
411 LV = {}
412 for tr in [t1, t2]:
413 mom = reps[tr].getMom(states[tr])
414 # tracks are always fitted under the muon hypothesis (+-13)
415 pid = abs(states[tr].getPDG())
416 _pdg_particle = ut.get_particle(pid)
417 mass = _pdg_particle.Mass()
418 E = ROOT.TMath.Sqrt(mass * mass + mom.Mag2())
419 LV[tr] = ROOT.TLorentzVector()
420 LV[tr].SetPxPyPzE(mom.x(), mom.y(), mom.z(), E)
421 HNLMom = LV[t1] + LV[t2]
422 return xv, yv, zv, doca, HNLMom
423
424
425def fitSingleGauss(x: str, ba: float | None = None, be: float | None = None) -> None:
426 name = "myGauss_" + x
427 myGauss = h[x].GetListOfFunctions().FindObject(name)
428 if not myGauss:
429 if not ba:
430 ba = h[x].GetBinCenter(1)
431 if not be:
432 be = h[x].GetBinCenter(h[x].GetNbinsX())
433 bw = h[x].GetBinWidth(1)
434 mean = h[x].GetMean()
435 sigma = h[x].GetRMS()
436 norm = h[x].GetEntries() * 0.3
437 myGauss = ROOT.TF1(name, "[0]*" + str(bw) + "/([2]*sqrt(2*pi))*exp(-0.5*((x-[1])/[2])**2)+[3]", 4)
438 myGauss.SetParameter(0, norm)
439 myGauss.SetParameter(1, mean)
440 myGauss.SetParameter(2, sigma)
441 myGauss.SetParameter(3, 1.0)
442 myGauss.SetParName(0, "Signal")
443 myGauss.SetParName(1, "Mean")
444 myGauss.SetParName(2, "Sigma")
445 myGauss.SetParName(3, "bckgr")
446 if h[x].GetEntries() > 0:
447 h[x].Fit(myGauss, "", "", ba, be)
448
449
450def match2HNL(p, signal_id) -> bool:
451 matched = False
452 if signal_id is None:
453 return matched
454 hnlKey = []
455 for t in [p.GetDaughter(0), p.GetDaughter(1)]:
456 mcp = sTree.fitTrack2MC[t]
457 # Walk up the MC mother chain looking for the signal particle.
458 while mcp > -0.5:
459 if mcp >= len(sTree.MCTrack):
460 break
461 if mcp == signal_id:
462 hnlKey.append(mcp)
463 break
464 mcp = sTree.MCTrack[mcp].GetMotherId()
465 if len(hnlKey) == 2 and hnlKey[0] == hnlKey[1]:
466 matched = True
467 return matched
468
469
470def makePlots() -> None:
471 ut.bookCanvas(h, key="strawanalysis", title="Distance to wire and mean nr of hits", nx=1200, ny=600, cx=3, cy=1)
472 cv = h["strawanalysis"].cd(1)
473 h["disty"].Draw()
474 h["distu"].Draw("same")
475 h["distv"].Draw("same")
476 cv = h["strawanalysis"].cd(2)
477 h["meanhits"].Draw()
478 cv = h["strawanalysis"].cd(3)
479 h["meas2"].Draw()
480 ut.bookCanvas(h, key="fitresults", title="Fit Results", nx=1600, ny=1200, cx=2, cy=2)
481 cv = h["fitresults"].cd(1)
482 h["delPOverPz"].Draw("box")
483 cv = h["fitresults"].cd(2)
484 cv.SetLogy(1)
485 h["prob"].Draw()
486 cv = h["fitresults"].cd(3)
487 h["delPOverPz_proj"] = h["delPOverPz"].ProjectionY()
488 ROOT.gStyle.SetOptFit(11111)
489 h["delPOverPz_proj"].Draw()
490 if h["delPOverPz_proj"].GetEntries() > 0:
491 h["delPOverPz_proj"].Fit("gaus")
492 cv = h["fitresults"].cd(4)
493 h["delPOverP2z_proj"] = h["delPOverP2z"].ProjectionY()
494 h["delPOverP2z_proj"].Draw()
495 fitSingleGauss("delPOverP2z_proj")
496 h["fitresults"].Print("fitresults.gif")
497 for x in ["", "_pi0"]:
498 ut.bookCanvas(h, key="fitresults2" + x, title="Fit Results " + x, nx=1600, ny=1200, cx=2, cy=2)
499 cv = h["fitresults2" + x].cd(1)
500 if x == "":
501 h["Doca"].SetXTitle("closest distance between 2 tracks [cm]")
502 h["Doca"].SetYTitle("N/1mm")
503 h["Doca"].Draw()
504 else:
505 h["pi0Mass"].SetXTitle("#gamma #gamma invariant mass [GeV/c^{2}]")
506 h["pi0Mass"].SetYTitle("N/" + str(int(h["pi0Mass"].GetBinWidth(1) * 1000)) + "MeV")
507 h["pi0Mass"].Draw()
508 if h["pi0Mass"].GetEntries() > 0:
509 h["pi0Mass"].Fit("gaus", "S", "", 0.08, 0.19)
510 cv = h["fitresults2" + x].cd(2)
511 h["IP0" + x].SetXTitle("impact parameter to p-target [cm]")
512 h["IP0" + x].SetYTitle("N/1cm")
513 h["IP0" + x].Draw()
514 cv = h["fitresults2" + x].cd(3)
515 h["HNL" + x].SetXTitle("inv. mass [GeV/c^{2}]")
516 h["HNL" + x].SetYTitle("N/4MeV/c2")
517 h["HNL" + x].Draw()
518 fitSingleGauss("HNL" + x, 0.9, 1.1)
519 cv = h["fitresults2" + x].cd(4)
520 h["IP0/mass" + x].SetXTitle("inv. mass [GeV/c^{2}]")
521 h["IP0/mass" + x].SetYTitle("IP [cm]")
522 h["IP0/mass" + x].Draw("colz")
523 h["fitresults2" + x].Print("fitresults2" + x + ".gif")
524 ut.bookCanvas(h, key="vxpulls", title="Vertex resol and pulls", nx=1600, ny=1200, cx=3, cy=2)
525 cv = h["vxpulls"].cd(4)
526 h["Vxpull"].Draw()
527 cv = h["vxpulls"].cd(5)
528 h["Vypull"].Draw()
529 cv = h["vxpulls"].cd(6)
530 h["Vzpull"].Draw()
531 cv = h["vxpulls"].cd(1)
532 h["Vxresol"].Draw()
533 cv = h["vxpulls"].cd(2)
534 h["Vyresol"].Draw()
535 cv = h["vxpulls"].cd(3)
536 h["Vzresol"].Draw()
537 ut.bookCanvas(h, key="trpulls", title="momentum pulls", nx=1600, ny=600, cx=3, cy=1)
538 cv = h["trpulls"].cd(1)
539 h["pullPOverPx_proj"] = h["pullPOverPx"].ProjectionY()
540 h["pullPOverPx_proj"].Draw()
541 cv = h["trpulls"].cd(2)
542 h["pullPOverPy_proj"] = h["pullPOverPy"].ProjectionY()
543 h["pullPOverPy_proj"].Draw()
544 cv = h["trpulls"].cd(3)
545 h["pullPOverPz_proj"] = h["pullPOverPz"].ProjectionY()
546 h["pullPOverPz_proj"].Draw()
547 ut.bookCanvas(h, key="vetodecisions", title="Veto Detectors", nx=1600, ny=600, cx=2, cy=1)
548 cv = h["vetodecisions"].cd(1)
549 cv.SetLogy(1)
550 h["nrtracks"].Draw()
551 cv = h["vetodecisions"].cd(2)
552 cv.SetLogy(1)
553 h["nrSBT"].Draw()
554 #
555 print("finished making plots")
556
557
558# start event loop
559def myEventLoop(n: int) -> None:
560 rc = sTree.GetEntry(n)
561 # check if tracks are made from real pattern recognition
562 measCut = measCutFK
563 if sTree.GetBranch("FitTracks_PR"):
564 sTree.FitTracks = sTree.FitTracks_PR
565 measCut = measCutPR
566 if sTree.GetBranch("fitTrack2MC_PR"):
567 sTree.fitTrack2MC = sTree.fitTrack2MC_PR
568 if sTree.GetBranch("Particles_PR"):
569 sTree.Particles = sTree.Particles_PR
570 if not checkHNLorigin(sTree):
571 return
572 wg = signal_weight(sTree.MCTrack)
573 signal_id = find_signal_track(sTree.MCTrack)
574
575 # make some straw hit analysis
576 hitlist = {}
577 for ahit in sTree.strawtubesPoint:
578 detID = ahit.GetDetectorID()
579 top = ROOT.TVector3()
580 bot = ROOT.TVector3()
581 modules["strawtubes"].StrawEndPoints(detID, bot, top)
582 dw = ahit.dist2Wire()
583 if detID < 50000000:
584 if abs(top.y()) == abs(bot.y()):
585 h["disty"].Fill(dw)
586 if abs(top.y()) > abs(bot.y()):
587 h["distu"].Fill(dw)
588 if abs(top.y()) < abs(bot.y()):
589 h["distv"].Fill(dw)
590 #
591 trID = ahit.GetTrackID()
592 if not trID < 0:
593 if trID in hitlist:
594 hitlist[trID] += 1
595 else:
596 hitlist[trID] = 1
597 for tr in hitlist:
598 h["meanhits"].Fill(hitlist[tr])
599 key = -1
600 for atrack in sTree.RecoTracks if actsMode else sTree.FitTracks:
601 key += 1
602 # kill tracks outside fiducial volume
603 if not checkFiducialVolume(sTree, key, dy):
604 continue
605 info = track_info(atrack, actsMode)
606 nmeas = info.ndf
607 h["meas"].Fill(nmeas)
608 if not info.converged:
609 continue
610 h["meas2"].Fill(nmeas)
611 if nmeas < measCut:
612 continue
613 # needs different study why fit has not converged, continue with fitted tracks
614 rchi2 = info.chi2
615 prob = ROOT.TMath.Prob(rchi2, int(nmeas))
616 h["prob"].Fill(prob)
617 chi2 = rchi2 / nmeas
618 h["chi2"].Fill(chi2, wg)
619 h["measVSchi2"].Fill(info.n_points, chi2)
620 # mom and the sigma_p* are set together, but guard each so the fitted
621 # quantities are known to be present for the rest of the loop body
622 if info.mom is None or info.sigma_px is None or info.sigma_py is None or info.sigma_pz is None:
623 continue
624 P = info.mom.Mag()
625 Px, Py, Pz = info.mom.X(), info.mom.Y(), info.mom.Z()
626 if len(sTree.fitTrack2MC) - 1 < key:
627 continue
628 mcPartKey = sTree.fitTrack2MC[key]
629 if mcPartKey < 0 or mcPartKey >= len(sTree.MCTrack):
630 continue
631 mcPart = sTree.MCTrack[mcPartKey]
632 mcPart.GetP()
633 mcPart.GetPz()
634 # get p truth from first strawpoint
635 Ptruth, Ptruthx, Ptruthy, Ptruthz = getPtruthFirst(sTree, mcPartKey)
636 delPOverP = (Ptruth - P) / Ptruth
637 h["delPOverP"].Fill(Ptruth, delPOverP)
638 delPOverPz = (1.0 / Ptruthz - 1.0 / Pz) * Ptruthz
639 h["pullPOverPx"].Fill(Ptruth, (Ptruthx - Px) / info.sigma_px)
640 h["pullPOverPy"].Fill(Ptruth, (Ptruthy - Py) / info.sigma_py)
641 h["pullPOverPz"].Fill(Ptruth, (Ptruthz - Pz) / info.sigma_pz)
642 h["delPOverPz"].Fill(Ptruthz, delPOverPz)
643 if chi2 > chi2CutOff:
644 continue
645 h["delPOverP2"].Fill(Ptruth, delPOverP)
646 h["delPOverP2z"].Fill(Ptruth, delPOverPz)
647 # try measure impact parameter
648 trackDir = info.dir
649 trackPos = info.pos
650 if trackDir is None or trackPos is None:
651 continue
652 vx = ROOT.TVector3()
653 mcPart.GetStartVertex(vx)
654 t = 0
655 for i in range(3):
656 t += trackDir(i) * (vx(i) - trackPos(i))
657 dist = 0
658 for i in range(3):
659 dist += (vx(i) - trackPos(i) - t * trackDir(i)) ** 2
660 dist = ROOT.TMath.Sqrt(dist)
661 h["IP"].Fill(dist)
662 # ---
663 # per-event veto detector decisions (independent of the reconstructed candidate)
664 vetoDets["SBT"] = veto.SBT_decision()
665 vetoDets["UBT"] = veto.UBT_decision()
666 vetoDets["TRA"] = veto.Track_decision()
667 signal_selected = False
668 # loop over particles, 2-track combinations
669 for HNL in sTree.Particles:
670 t1, t2 = HNL.GetDaughter(0), HNL.GetDaughter(1)
671 # kill tracks outside fiducial volume, if enabled
672 if not checkFiducialVolume(sTree, t1, dy) or not checkFiducialVolume(sTree, t2, dy):
673 continue
674 checkMeasurements = True
675 # cut on nDOF
676 tracks = sTree.RecoTracks if actsMode else sTree.FitTracks
677 for tr in [t1, t2]:
678 nmeas = track_info(tracks[tr], actsMode).ndf
679 if nmeas < measCut:
680 checkMeasurements = False
681 if not checkMeasurements:
682 continue
683 # check mc matching
684 if not match2HNL(HNL, signal_id):
685 continue
686 HNLPos = ROOT.TLorentzVector()
687 HNL.ProductionVertex(HNLPos)
688 HNLMom = ROOT.TLorentzVector()
689 HNL.Momentum(HNLMom)
690 doca = HNL.GetDoca()
691 # redo doca calculation
692 # xv,yv,zv,doca,HNLMom = RedoVertexing(t1,t2)
693 # if HNLMom == -1: continue
694 # check if decay inside decay volume
695 if not isInFiducial(HNLPos.X(), HNLPos.Y(), HNLPos.Z()):
696 continue
697 h["Doca"].Fill(doca)
698 if doca > docaCut:
699 continue
700 tr = ROOT.TVector3(0, 0, ShipGeo.target.z0)
701
702 # look for pi0
703 """
704 for pi0 in pi0Reco.findPi0(sTree,HNLPos):
705 rc = h['pi0Mass'].Fill(pi0.M())
706 if abs(pi0.M()-0.135)>0.02: continue
707# could also be used for eta, by changing cut
708 HNLwithPi0 = HNLMom + pi0
709 dist = ImpactParameter(tr,HNLPos,HNLwithPi0)
710 mass = HNLwithPi0.M()
711 h['IP0_pi0'].Fill(dist)
712 h['IP0/mass_pi0'].Fill(mass,dist)
713 h['HNL_pi0'].Fill(mass)
714 """
715
716 dist = ImpactParameter(tr, HNLPos, HNLMom)
717 mass = HNLMom.M()
718 h["IP0"].Fill(dist)
719 h["IP0/mass"].Fill(mass, dist)
720 h["HNL"].Fill(mass)
721 h["HNLw"].Fill(mass, wg)
722 signal_selected = True
723 #
724 # HNL true
725 mcTrackIdx = sTree.fitTrack2MC[t1]
726 if mcTrackIdx < 0 or mcTrackIdx >= len(sTree.MCTrack):
727 continue
728 mctrack = sTree.MCTrack[mcTrackIdx]
729 h["Vzresol"].Fill((mctrack.GetStartZ() - HNLPos.Z()) / u.cm)
730 h["Vxresol"].Fill((mctrack.GetStartX() - HNLPos.X()) / u.cm)
731 h["Vyresol"].Fill((mctrack.GetStartY() - HNLPos.Y()) / u.cm)
732 PosDir, newPosDir, CovMat, _scalFac = {}, {}, {}, {}
733 # opening angle at vertex
734 newPos = ROOT.TVector3(HNLPos.X(), HNLPos.Y(), HNLPos.Z())
735 if actsMode:
736 # momenta smoothed at the vertex, from the vertex holding exactly
737 # these two tracks; fall back to the track momenta otherwise
738 mom1 = track_info(sTree.RecoTracks[t1], actsMode).mom
739 mom2 = track_info(sTree.RecoTracks[t2], actsMode).mom
740 for vtx in sTree.RecoVertices:
741 if sorted(vtx.trackIds()) == sorted([t1, t2]):
742 vtx_px, vtx_py, vtx_pz = vtx.trackPx(), vtx.trackPy(), vtx.trackPz()
743 if len(vtx_px) >= 2:
744 mom1 = ROOT.TVector3(vtx_px[0], vtx_py[0], vtx_pz[0])
745 mom2 = ROOT.TVector3(vtx_px[1], vtx_py[1], vtx_pz[1])
746 break
747 else:
748 st1, st2 = sTree.FitTracks[t1].getFittedState(), sTree.FitTracks[t2].getFittedState()
749 PosDir[t1] = {"position": st1.getPos(), "direction": st1.getDir(), "momentum": st1.getMom()}
750 PosDir[t2] = {"position": st2.getPos(), "direction": st2.getDir(), "momentum": st2.getMom()}
751 CovMat[t1] = st1.get6DCov()
752 CovMat[t2] = st2.get6DCov()
753 rep1, rep2 = ROOT.genfit.RKTrackRep(st1.getPDG()), ROOT.genfit.RKTrackRep(st2.getPDG())
754 state1, state2 = ROOT.genfit.StateOnPlane(rep1), ROOT.genfit.StateOnPlane(rep2)
755 rep1.setPosMom(state1, st1.getPos(), st1.getMom())
756 rep2.setPosMom(state2, st2.getPos(), st2.getMom())
757 try:
758 rep1.extrapolateToPoint(state1, newPos, False)
759 rep2.extrapolateToPoint(state2, newPos, False)
760 mom1, mom2 = rep1.getMom(state1), rep2.getMom(state2)
761 except Exception:
762 mom1, mom2 = st1.getMom(), st2.getMom()
763 newPosDir[t1] = {"position": rep1.getPos(state1), "direction": rep1.getDir(state1), "momentum": mom1}
764 newPosDir[t2] = {"position": rep2.getPos(state2), "direction": rep2.getDir(state2), "momentum": mom2}
765 if mom1 is None or mom2 is None or not (mom1.Mag() > 0 and mom2.Mag() > 0):
766 continue
767 oa = mom1.Dot(mom2) / (mom1.Mag() * mom2.Mag())
768 h["oa"].Fill(oa)
769 #
770 covX = HNL.GetCovV()
771 dist = HNL.GetDoca()
772 h["Vzpull"].Fill((mctrack.GetStartZ() - HNLPos.Z()) / ROOT.TMath.Sqrt(covX[5]))
773 h["Vxpull"].Fill((mctrack.GetStartX() - HNLPos.X()) / ROOT.TMath.Sqrt(covX[0]))
774 h["Vypull"].Fill((mctrack.GetStartY() - HNLPos.Y()) / ROOT.TMath.Sqrt(covX[3]))
775
776 # fill veto histograms once per event with at least one selected candidate
777 if signal_selected:
778 h["nrtracks"].Fill(vetoDets["TRA"][2])
779 h["nrSBT"].Fill(vetoDets["SBT"][2])
780
781 # check extrapolation to TimeDet if exists
782 if hasattr(ShipGeo, "TimeDet"):
783 if actsMode:
784 pos = ROOT.TVector3()
785 for fT in sTree.RecoTracks:
786 rc = fT.ExtrapolateToZ(ShipGeo.TimeDet.z, pos)
787 if rc:
788 for aPoint in sTree.TimeDetPoint:
789 h["extrapTimeDetX"].Fill(pos[0] - aPoint.GetX())
790 h["extrapTimeDetY"].Fill(pos[1] - aPoint.GetY())
791 else:
792 for fT in sTree.FitTracks:
793 rc, pos, _mom = TrackExtrapolateTool.extrapolateToPlane(fT, ShipGeo.TimeDet.z)
794 if rc:
795 for aPoint in sTree.TimeDetPoint:
796 h["extrapTimeDetX"].Fill(pos.X() - aPoint.GetX())
797 h["extrapTimeDetY"].Fill(pos.Y() - aPoint.GetY())
798
799
800#
801def HNLKinematics() -> None:
802 HNLorigin = {}
803 ut.bookHist(h, "HNLmomNoW", "momentum unweighted", 100, 0.0, 300.0)
804 ut.bookHist(h, "HNLmom", "momentum", 100, 0.0, 300.0)
805 ut.bookHist(h, "HNLPtNoW", "Pt unweighted", 100, 0.0, 10.0)
806 ut.bookHist(h, "HNLPt", "Pt", 100, 0.0, 10.0)
807 ut.bookHist(h, "HNLmom_recTracks", "momentum", 100, 0.0, 300.0)
808 ut.bookHist(h, "HNLmomNoW_recTracks", "momentum unweighted", 100, 0.0, 300.0)
809 for n in range(sTree.GetEntries()):
810 sTree.GetEntry(n)
811 for hnlkey in [1, 2]:
812 if hnlkey >= len(sTree.MCTrack):
813 continue
814 if abs(sTree.MCTrack[hnlkey].GetPdgCode()) == 9900015:
815 theHNL = sTree.MCTrack[hnlkey]
816 wg = theHNL.GetWeight()
817 if not wg > 0.0:
818 wg = 1.0
819 if hnlkey - 1 < 0 or hnlkey - 1 >= len(sTree.MCTrack):
820 continue
821 idMother = abs(sTree.MCTrack[hnlkey - 1].GetPdgCode())
822 if idMother not in HNLorigin:
823 HNLorigin[idMother] = 0
824 HNLorigin[idMother] += wg
825 P = theHNL.GetP()
826 Pt = theHNL.GetPt()
827 h["HNLmom"].Fill(P, wg)
828 h["HNLmomNoW"].Fill(P)
829 h["HNLPt"].Fill(Pt, wg)
830 h["HNLPtNoW"].Fill(Pt)
831 for HNL in sTree.Particles:
832 t1, t2 = HNL.GetDaughter(0), HNL.GetDaughter(1)
833 tracks = sTree.RecoTracks if actsMode else sTree.FitTracks
834 for tr in [t1, t2]:
835 info = track_info(tracks[tr], actsMode)
836 if info.mom is None:
837 continue
838 Prec = info.mom.Mag()
839 h["HNLmom_recTracks"].Fill(Prec, wg)
840 h["HNLmomNoW_recTracks"].Fill(Prec)
841 theSum = 0
842 for x in HNLorigin:
843 theSum += HNLorigin[x]
844 for x in HNLorigin:
845 print("%4i : %5.4F relative fraction: %5.4F " % (x, HNLorigin[x], HNLorigin[x] / theSum))
846
847
848#
849sTree.GetEvent(0)
850options.nEvents = min(sTree.GetEntries(), options.nEvents)
851
852# import pi0Reco
853ut.bookHist(h, "pi0Mass", "gamma gamma inv mass", 100, 0.0, 0.5)
854
855for n in range(options.nEvents):
856 myEventLoop(n)
857 if not actsMode:
858 sTree.FitTracks.clear()
859makePlots()
860# output histograms
861hfile = options.inputFile.split(",")[0]
862if "_rec" in hfile:
863 hfile = hfile.replace("_rec", "_ana")
864else:
865 hfile = hfile.replace(".root", "_ana.root")
866if "/eos" in hfile or not options.inputFile.find(",") < 0:
867 # do not write to eos, write to local directory
868 tmp = hfile.split("/")
869 hfile = tmp[len(tmp) - 1]
870ROOT.gROOT.cd()
871ut.writeHists(h, hfile)
None access2SmearedHits(ev, TrackingHits, MCTracks)
Definition ShipAna.py:339
VertexError(t1, t2, PosDir, CovMat, scalFac)
Definition ShipAna.py:160
None makePlots()
Definition ShipAna.py:470
RedoVertexing(t1, t2)
Definition ShipAna.py:373
getPtruthFirst(sTree, mcPartKey)
Definition ShipAna.py:329
bool checkHNLorigin(sTree)
Definition ShipAna.py:280
None HNLKinematics()
Definition ShipAna.py:801
dist2InnerWall(X, Y, Z)
Definition ShipAna.py:232
bool match2HNL(p, signal_id)
Definition ShipAna.py:450
bool checkFiducialVolume(sTree, int tkey, dy)
Definition ShipAna.py:307
ImpactParameter(point, tPos, tMom)
Definition ShipAna.py:264
myVertex(t1, t2, PosDir)
Definition ShipAna.py:350
None myEventLoop(int n)
Definition ShipAna.py:559
bool isInFiducial(X, Y, Z)
Definition ShipAna.py:254
None fitSingleGauss(str x, float|None ba=None, float|None be=None)
Definition ShipAna.py:425
tuple[bool, Any, Any] extrapolateToPlane(fT, z)
None apply_decorators()
Definition decorators.py:98
addVMCFields(shipGeo, str controlFile="", bool verbose=False, bool withVirtualMC=True)
configure(run, ship_geo, str|None geofile=None)
None configure(darkphoton=None)