SND@LHC Software
Loading...
Searching...
No Matches
shipPatRec_prev Namespace Reference

Functions

 initialize (fGeo)
 
 getReconstructibleTracks (iEvent, sTree, sGeo)
 
 SmearHits (iEvent, sTree, modules, SmearedHits, ReconstructibleMCTracks)
 
 Digitization (sTree, SmearedHits)
 
 PatRec (firsttwo, zlayer, zlayerv2, StrawRaw, StrawRawLink, ReconstructibleMCTracks)
 
 TrackFit (hitPosList, theTrack, charge, pinv)
 
 ptrack (zlayer, ptrackhits, nrwant, window)
 
 dorot (x, y, xc, yc, alpha)
 
 line2plane (fitt, fitc, uvview, zuv)
 
 fitline (indices, xhits, zhits, resolution)
 
 IP (s, t, b)
 
 fracMCsame (trackids)
 
 match_tracks (t1, t2, zmagnet, Bdl)
 
 dist2line (tan, cst, points)
 
 hit2wire (ahit, bot, top, no_amb=None)
 
 debugevent (stereo, y2, y3, ymin2, yother, z2, z3, zmin2, zother, foundtrackids)
 
 execute (SmearedHits, sTree, ReconstructibleMCTracks)
 
 finalize ()
 

Variables

int reconstructiblehorizontalidsfound12 = 0
 
int reconstructiblestereoidsfound12 = 0
 
int reconstructiblehorizontalidsfound34 = 0
 
int reconstructiblestereoidsfound34 = 0
 
int reconstructibleidsfound12 = 0
 
int reconstructibleidsfound34 = 0
 
int morethan500 = 0
 
int morethan100tracks = 0
 
int falsenegative = 0
 
int falsepositive = 0
 
int reconstructibleevents = 0
 
int cheated = 0
 
int monitor = 0
 
int printhelp = 0
 
int reconstructiblerequired = 2
 
int threeprong = 0
 
str geoFile = ''
 
str fgeo = ''
 
int totalaftermatching = 0
 
int totalafterpatrec = 0
 
list ReconstructibleMCTracks = []
 
list MatchedReconstructibleMCTracks = []
 
list fittedtrackids = []
 
list theTracks = []
 
 random = ROOT.TRandom()
 
 PDG = ROOT.TDatabasePDG.Instance()
 
 fitter = ROOT.genfit.DAF()
 
dict h = {}
 
dict rc = h['pinvvstruepinv'].SetMarkerStyle(8)
 
list particles = ["e-","e+","mu-","mu+","pi-","pi+","other"]
 
int i1 = 1
 
int i2 = 16
 
dict zlayer = {}
 
dict zlayerv2 = {}
 
dict z34layer = {}
 
dict z34layerv2 = {}
 
int TStation1StartZ = 0.
 
int TStation4EndZ = 0.
 
int VetoStationZ = 0.
 
int VetoStationEndZ = 0.
 

Function Documentation

◆ debugevent()

shipPatRec_prev.debugevent (   stereo,
  y2,
  y3,
  ymin2,
  yother,
  z2,
  z3,
  zmin2,
  zother,
  foundtrackids 
)

Definition at line 1620 of file shipPatRec_prev.py.

1620def debugevent(stereo,y2,y3,ymin2,yother,z2,z3,zmin2,zother,foundtrackids):
1621 c = ROOT.TCanvas("c","c",600, 400)
1622 if stereo==False:
1623 coord="y"
1624 else:
1625 coord="projected x"
1626 mg=ROOT.TMultiGraph(coord+"-hit coord vs z",coord+"-hit coord vs z; evtnb="+str(iEvent))
1627 y3vector=ROOT.TVector(len(y3))
1628 z3vector=ROOT.TVector(len(z3))
1629 for i in range(len(z3)):
1630 y3vector[i]=y3[i]
1631 z3vector[i]=z3[i]
1632 y2vector=ROOT.TVector(len(y2))
1633 z2vector=ROOT.TVector(len(z2))
1634 for i in range(len(z2)):
1635 y2vector[i]=y2[i]
1636 z2vector[i]=z2[i]
1637 ymin2vector=ROOT.TVector(len(ymin2))
1638 zmin2vector=ROOT.TVector(len(zmin2))
1639 for i in range(len(zmin2)):
1640 ymin2vector[i]=ymin2[i]
1641 zmin2vector[i]=zmin2[i]
1642 yothervector=ROOT.TVector(len(yother))
1643 zothervector=ROOT.TVector(len(zother))
1644 for i in range(len(zother)):
1645 yothervector[i]=yother[i]
1646 zothervector[i]=zother[i]
1647 if len(z3)>0:
1648 g3=ROOT.TGraph(z3vector,y3vector)
1649 g3.SetName("g3")
1650 g3.SetTitle("TrackID=3")
1651 g3.SetMarkerStyle(3)
1652 g3.SetDrawOption("AP")
1653 g3.SetFillStyle(0)
1654 mg.Add(g3)
1655 if len(z2)>0:
1656 g2=ROOT.TGraph(z2vector,y2vector)
1657 g2.SetName("g2")
1658 g2.SetTitle("TrackID=2")
1659 g2.SetMarkerStyle(2)
1660 g2.SetDrawOption("AP")
1661 g2.SetFillStyle(0)
1662 mg.Add(g2)
1663 if len(zmin2)>0:
1664 gmin2=ROOT.TGraph(zmin2vector,ymin2vector)
1665 gmin2.SetName("gmin2")
1666 gmin2.SetMarkerStyle(4)
1667 gmin2.SetTitle("TrackID=-2")
1668 gmin2.SetDrawOption("AP")
1669 gmin2.SetFillStyle(0)
1670 mg.Add(gmin2)
1671 if len(zother) > 0:
1672 gother=ROOT.TGraph(zothervector,yothervector)
1673 gother.SetName("gother")
1674 gother.SetMarkerStyle(5)
1675 gother.SetDrawOption("AP")
1676 gother.SetTitle("TrackID=Other")
1677 gother.SetFillStyle(0)
1678 mg.Add(gother)
1679 mg.Draw("A P")
1680 c.BuildLegend(0.6,0.3,0.99,0.5,"Recble TrackIDs="+str(ReconstructibleMCTracks)+"Found TrackIDs:"+str(foundtrackids))
1681 c.Write()
1682 return
1683

◆ Digitization()

shipPatRec_prev.Digitization (   sTree,
  SmearedHits 
)

Definition at line 660 of file shipPatRec_prev.py.

660def Digitization(sTree,SmearedHits):
661 #digitization
662 #input: Smeared TrackingHits
663 #output: StrawRaw, StrawRawLink
664
665 StrawRaw={} #raw hit dictionary: key=hit number, values=xtop,ytop,ztop,xbot,ybot,zbot,dist2Wire,strawname
666 StrawRawLink={} #raw hit dictionary: key=hit number, value=the hit object
667 j=0
668 for i in range(len(SmearedHits)):
669 xtop=SmearedHits[i]['xtop']
670 xbot=SmearedHits[i]['xbot']
671 ytop=SmearedHits[i]['ytop']
672 ybot=SmearedHits[i]['ybot']
673 ztop=SmearedHits[i]['z']
674 zbot=SmearedHits[i]['z']
675 distance=SmearedHits[i]['dist']
676 strawname=sTree.strawtubesPoint[i].GetDetectorID()
677 a=[]
678 a.append(xtop)
679 a.append(ytop)
680 a.append(ztop)
681 a.append(xbot)
682 a.append(ybot)
683 a.append(zbot)
684 a.append(float(distance))
685 a.append(str(strawname))
686 StrawRaw[j]=a
687 StrawRawLink[j]=[sTree.strawtubesPoint[i]]
688 j=j+1
689
690 if global_variables.debug:
691 print("Nbr of digitized hits", j)
692 return StrawRaw,StrawRawLink
693

◆ dist2line()

shipPatRec_prev.dist2line (   tan,
  cst,
  points 
)

Definition at line 1602 of file shipPatRec_prev.py.

1602def dist2line(tan,cst,points):
1603 #points = (x,y)
1604 #tan, cst are the tangens & constant of the fitted track
1605 dist = tan*points[0][0] + cst - points[1]
1606 return dist
1607

◆ dorot()

shipPatRec_prev.dorot (   x,
  y,
  xc,
  yc,
  alpha 
)

Definition at line 1472 of file shipPatRec_prev.py.

1472def dorot(x,y,xc,yc,alpha):
1473 #rotate x,y around xc,yc over angle alpha
1474 ca=cos(alpha)
1475 sa=sin(alpha)
1476 xout=ca*(x-xc)-sa*(y-yc)+xc
1477 yout=sa*(x-xc)+ca*(y-yc)+yc
1478 return xout,yout
1479

◆ execute()

shipPatRec_prev.execute (   SmearedHits,
  sTree,
  ReconstructibleMCTracks 
)

Definition at line 1684 of file shipPatRec_prev.py.

1684def execute(SmearedHits,sTree,ReconstructibleMCTracks):
1685 global totalaftermatching,morethan500,falsepositive,falsenegative,totalafterpatrec
1686 global reconstructibleevents,morethan100tracks,theTracks
1687
1688 fittedtrackids=[]
1689 reconstructibles12=0
1690 reconstructibles34=0
1691 theTracks=[]
1692
1693 if global_variables.debug:
1694 print("************* PatRect START **************")
1695
1696 nShits=sTree.strawtubesPoint.GetEntriesFast()
1697 nMCTracks = sTree.MCTrack.GetEntriesFast()
1698
1699 #if nMCTracks < 100:
1700 if nShits < 500:
1701
1702 StrawRaw,StrawRawLink=Digitization(sTree,SmearedHits)
1703 reconstructibleevents+=1
1704 nr12tracks,tracks12,hitids12,xtan12,xcst12,stereotan12,stereocst12,px12,py12,pz12,fraction12,trackid12=PatRec(True,zlayer,zlayerv2,StrawRaw,StrawRawLink,ReconstructibleMCTracks)
1705 tracksfound=[]
1706 if monitor==True:
1707 for item in ReconstructibleMCTracks:
1708 for value in trackid12.values():
1709 if item == value and item not in tracksfound:
1710 reconstructibles12+=1
1711 tracksfound.append(item)
1712
1713 if global_variables.debug:
1714 print(
1715 "tracksfound", tracksfound,
1716 "reconstructibles12", reconstructibles12,
1717 "ReconstructibleMCTracks", ReconstructibleMCTracks
1718 )
1719 if len(tracksfound)==0 and len(ReconstructibleMCTracks)>0:
1720 if global_variables.debug:
1721 print("No tracks found in event after stations 1&2. Rejecting event.")
1722 return
1723
1724 nr34tracks,tracks34,hitids34,xtan34,xcst34,stereotan34,stereocst34,px34,py34,pz34,fraction34,trackid34=PatRec(False,z34layer,z34layerv2,StrawRaw,StrawRawLink,ReconstructibleMCTracks)
1725
1726 tracksfound=[]
1727 if monitor==True:
1728 for item in ReconstructibleMCTracks:
1729 for value in trackid34.values():
1730 if item == value and item not in tracksfound:
1731 reconstructibles34+=1
1732 tracksfound.append(item)
1733 if len(tracksfound)==0 and len(ReconstructibleMCTracks)>0:
1734 if global_variables.debug:
1735 print("No tracks found in event after stations 3&4. Rejecting event.")
1736 return
1737 MatchedReconstructibleMCTracks=len(ReconstructibleMCTracks)*[0]
1738
1739
1740 if global_variables.debug:
1741 if (nr12tracks>0) :
1742 print(nr12tracks,"tracks12 ",tracks12)
1743 print("hitids12 ",hitids12)
1744 print("xtan ",xtan12,"xcst",xcst12)
1745 print("stereotan ",stereotan12,"stereocst ",stereocst12)
1746 print("fraction12",fraction12,"trackid12",trackid12)
1747 else :
1748 print("No tracks found in stations 1&2.")
1749
1750 if (nr34tracks>0) :
1751 print(nr34tracks,"tracks34 ",tracks34)
1752 print("hitids34 ",hitids34)
1753 print("xtan34 ",xtan34,"xcst34 ",xcst34)
1754 print("stereotan34 ",stereotan34,"stereocst34 ",stereocst34)
1755 print("px34",px34)
1756 else :
1757 print("No tracks found in stations 3&4.")
1758
1759 if monitor==False: totalafterpatrec+=1
1760
1761 zmagnet=ShipGeo.Bfield.z
1762 tracksfound=[]
1763 matches=0
1764
1765 for item in xtan12:
1766 z1=0.
1767 tgy1=xtan12[item]
1768 tgx1=stereotan12[item]
1769 y1=xcst12[item]
1770 x1=stereocst12[item]
1771 t1=[x1,y1,z1,tgx1,tgy1]
1772 for ids in hitids12[item]:
1773 #cheated
1774 if ids != 999 :
1775 #loop until we get the particle of this track
1776 particle12 = PDG.GetParticle(StrawRawLink[ids][0].PdgCode())
1777 try:
1778 charge12=particle12.Charge()/3.
1779 break
1780 except:
1781 continue
1782
1783 falsenegativethistrack=0
1784 falsepositivethistrack=0
1785 for item1 in xtan34:
1786 if monitor==True: totalafterpatrec+=1
1787 for k,v in enumerate(ReconstructibleMCTracks):
1788 if v not in tracksfound:
1789 tracksfound.append(v)
1790 rawlinkindex=0
1791 for ids in hitids34[item1]:
1792 if ids != 999 :
1793 particle34 = PDG.GetParticle(StrawRawLink[ids][0].PdgCode())
1794 try:
1795 charge34=particle34.Charge()/3.
1796 break
1797 except:
1798 continue
1799 z2=0.
1800 tgx2=stereotan34[item1]
1801 tgy2=xtan34[item1]
1802 y2=xcst34[item1]
1803 x2=stereocst34[item1]
1804 t2=[x2,y2,z2,tgx2,tgy2]
1805
1806 dx,dy,alpha,pinv=match_tracks(t1,t2,zmagnet,-0.75)
1807 p2x=px34[item1]
1808 p2y=py34[item1]
1809 p2z=pz34[item1]
1810 p2true=1./math.sqrt(p2x**2+p2y**2+p2z**2)
1811 if global_variables.debug:
1812 print(
1813 "Matching 1&2 track", item,
1814 "with 3&4 track", item1,
1815 "dx", dx, "dy", dy, "alpha", alpha, "pinv", pinv, "1/p2true", p2true
1816 )
1817 rc=h['dx-matchedtracks'].Fill(dx)
1818 rc=h['dy-matchedtracks'].Fill(dy)
1819 if ((abs(dx)<20) & (abs(dy)<2)) :
1820 #match found between track nr item in stations 12 & item1 in stations 34
1821 #get charge from deflection and check if it corresponds to the MC truth
1822 #field is horizontal (x) hence deflection in y
1823 tantheta=(tgy1-tgy2)/(1+tgy1*tgy2)
1824 if tantheta>0 :
1825 charge="-1"
1826 if charge34>0:
1827 falsenegative+=1
1828 falsenegativethistrack=1
1829 else:
1830 charge="1"
1831 if charge34<0:
1832 falsepositive+=1
1833 falsepositivethistrack=1
1834
1835 #reject track (and event) if it doesn't correspond to MC truth
1836 if monitor==True:
1837 if (falsepositivethistrack==0 & falsenegativethistrack==0):
1838 totalaftermatching+=1
1839 else:
1840 if global_variables.debug:
1841 print("Charge from track deflection doesn't match MC truth. Rejecting it.")
1842 break
1843 else:
1844 if matches==0:
1845 matches==1
1846 totalaftermatching+=1
1847
1848 if global_variables.debug:
1849 print("******* MATCH FOUND stations 12 track id",trackid12[item],"(fraction",fraction12[item]*100,"%) and stations 34 track id",trackid34[item1],"(fraction",fraction34[item1]*100,"%)")
1850 print("******* Reconstructible tracks ids",ReconstructibleMCTracks)
1851
1852 rc=h['matchedtrackefficiency'].Fill(fraction12[item],fraction34[item1])
1853 for k,v in enumerate(ReconstructibleMCTracks):
1854 if global_variables.debug:
1855 print("MatchedReconstructibleMCTracks", MatchedReconstructibleMCTracks, "k", k, "v", v)
1856 if v not in MatchedReconstructibleMCTracks:
1857 if global_variables.debug:
1858 print("ReconstructibleMCTracks", ReconstructibleMCTracks, "trackid34[item1]", trackid34[item1])
1859 if v==trackid34[item1]: MatchedReconstructibleMCTracks[k]=v
1860 p2true=p2true*int(charge)
1861 rc=h['pinvvstruepinv'].Fill(p2true,pinv)
1862 if math.fabs(pinv) > 0.0 : rc=h['ptrue-p/ptrue'].Fill((pinv-p2true)/pinv)
1863
1864 if cheated==False:
1865 hitPosList=[]
1866 for ids in range(0,len(hitids12[item])):
1867 #print "hitids12[",item,"][",ids,"]",hitids12[item][ids]
1868 if hitids12[item][ids]!=999 :
1869 m=[]
1870 if ids in range(0,32):
1871 for z in range(0,7):
1872 m.append(StrawRaw[hitids12[item][ids]][z])
1873 hitPosList.append(m)
1874 for ids in range(0,len(hitids34[item1])):
1875 if hitids34[item1][ids]!=999 :
1876 m=[]
1877 if ids in range(0,32):
1878 for z in range(0,7):
1879 m.append(StrawRaw[hitids34[item1][ids]][z])
1880 hitPosList.append(m)
1881 nM = len(hitPosList)
1882 if nM<25:
1883 if global_variables.debug:
1884 print("Only", nM, "hits on this track. Insufficient for fitting.")
1885 return
1886 #all particles are assumed to be muons
1887 if int(charge)<0:
1888 pdg=13
1889 else:
1890 pdg=-13
1891 rep = ROOT.genfit.RKTrackRep(pdg)
1892 posM = ROOT.TVector3(0, 0, 0)
1893 #would be the correct way but due to uncertainties on small angles the sqrt is often negative
1894 if math.fabs(pinv) > 0.0 : momM = ROOT.TVector3(0,0,int(charge)/pinv)
1895 else: momM = ROOT.TVector3(0,0,999)
1896 covM = ROOT.TMatrixDSym(6)
1897 resolution = ShipGeo.strawtubes.sigma_spatial
1898 for i in range(3): covM[i][i] = resolution*resolution
1899 covM[0][0]=resolution*resolution*100.
1900 for i in range(3,6): covM[i][i] = ROOT.TMath.Power(resolution / nM / ROOT.TMath.Sqrt(3), 2)
1901 # smeared start state
1902 stateSmeared = ROOT.genfit.MeasuredStateOnPlane(rep)
1903 rep.setPosMomCov(stateSmeared, posM, momM, covM)
1904 # create track
1905 seedState = ROOT.TVectorD(6)
1906 seedCov = ROOT.TMatrixDSym(6)
1907 rep.get6DStateCov(stateSmeared, seedState, seedCov)
1908 theTrack=ROOT.genfit.Track(rep, seedState, seedCov)
1909 TrackFit(hitPosList,theTrack,charge,pinv)
1910 fittedtrackids.append(trackid34[item1])
1911 else :
1912 if global_variables.debug:
1913 print(
1914 "******* MATCH NOT FOUND stations 12 track id", trackid12[item],
1915 "(fraction", fraction12[item]*100, "%) and stations 34 track id", trackid34[item1],
1916 "(fraction", fraction34[item1]*100, "%)"
1917 )
1918 if trackid12[item]==trackid34[item1] :
1919 if global_variables.debug:
1920 print("trackids the same, but not matched.")
1921
1922 else:
1923 #remove events with >500 hits
1924 morethan500+=1
1925 return
1926
1927 #else:
1928 #morethan100tracks+=1
1929 #return
1930 return fittedtrackids
1931
1932

◆ finalize()

shipPatRec_prev.finalize ( )

Definition at line 1933 of file shipPatRec_prev.py.

1933def finalize():
1934 if global_variables.debug:
1935 ut.writeHists(h,"recohists_patrec.root")

◆ fitline()

shipPatRec_prev.fitline (   indices,
  xhits,
  zhits,
  resolution 
)

Definition at line 1503 of file shipPatRec_prev.py.

1503def fitline(indices,xhits,zhits,resolution):
1504 #fit linear function (y=fitt*x+fitc) to list of hits,
1505 #"x" is the z-coordinate, "y" is the cSoordinate in tracking plane perp to z
1506 #use equal weights for the time being, and outlier removal (yet)?
1507
1508 n=0
1509 sumx=0.
1510 sumx2=0
1511 sumxy=0.
1512 sumy=0.
1513 sumweight=0.
1514 sumweightx=0.
1515 sumweighty=0.
1516 Dw=0.
1517 term=0.
1518 for ipl in range(1,len(indices)):
1519 indx= indices[ipl]
1520 if indx>-1:
1521 #n+=1
1522 #weigh points accordint to their distance to the wire
1523 weight=1/math.sqrt(xhits[ipl][3][indx]**2+resolution**2)
1524 x=zhits[ipl][0]
1525 y=xhits[ipl][0][indx]
1526 sumweight+=weight
1527 sumweightx+=weight*x
1528 sumweighty+=weight*y
1529 xmean=sumweightx/sumweight
1530 ymean=sumweighty/sumweight
1531 for ipl in range(1,len(indices)):
1532 indx= indices[ipl]
1533 if indx>-1:
1534 n+=1
1535 weight=1/math.sqrt(xhits[ipl][3][indx]**2+resolution**2)
1536 x=zhits[ipl][0]
1537 y=xhits[ipl][0][indx]
1538 Dw+=weight*(x-xmean)**2
1539 term+=weight*(x-xmean)*y
1540 sumx+=zhits[ipl][0]
1541 sumx2+=zhits[ipl][0]**2
1542 sumxy+=xhits[ipl][0][indx]*zhits[ipl][0]
1543 sumy+=xhits[ipl][0][indx]
1544 fitt=(1/Dw)*term
1545 fitc=ymean-fitt*xmean
1546 unweightedfitt=(sumxy-sumx*sumy/n)/(sumx2-sumx**2/n)
1547 unweightedfitc=(sumy-fitt*sumx)/n
1548 return fitt,fitc
1549

◆ fracMCsame()

shipPatRec_prev.fracMCsame (   trackids)

Definition at line 1558 of file shipPatRec_prev.py.

1558def fracMCsame(trackids):
1559# determine largest fraction of hits which have benn generated by the same # MC true track
1560#hits: list of pointers to true MC TrackingHits
1561#return: fraction of hits from same track, and its track-ID
1562 track={}
1563 nh=len(trackids)
1564 for tid in trackids:
1565 if tid==999:
1566 nh-=1
1567 continue
1568 if tid in track:
1569 track[tid]+=1
1570 else:
1571 track[tid]=1
1572 #now get track with largest number of hits
1573 tmax=max(track, key=track.get)
1574
1575 frac=0.
1576 if nh>0: frac=float(track[tmax])/float(nh)
1577 return frac,tmax
1578

◆ getReconstructibleTracks()

shipPatRec_prev.getReconstructibleTracks (   iEvent,
  sTree,
  sGeo 
)

Definition at line 236 of file shipPatRec_prev.py.

236def getReconstructibleTracks(iEvent,sTree,sGeo):
237
238 #returns a list of reconstructible tracks for this event
239 #call this routine once for each event before smearing
240 MCTrackIDs=[]
241 rc = sTree.GetEvent(iEvent)
242 nMCTracks = sTree.MCTrack.GetEntriesFast()
243
244 if global_variables.debug:
245 print("event nbr", iEvent, "has", nMCTracks, "tracks")
246 #1. MCTrackIDs: list of tracks decaying after the last tstation and originating before the first
247 for i in reversed(range(nMCTracks)):
248 atrack = sTree.MCTrack.At(i)
249 #for 3 prong decays check if its a nu
250 if threeprong == 1:
251 if PDG.GetParticle(atrack.GetPdgCode()):
252 if PDG.GetParticle(atrack.GetPdgCode()).GetName()[:5]=="nu_mu":
253 if (atrack.GetStartZ() < TStation1StartZ and atrack.GetStartZ() > VetoStationEndZ) and i not in MCTrackIDs:
254 MCTrackIDs.append(i)
255 else:
256 if atrack.GetStartZ() > TStation4EndZ :
257 motherId=atrack.GetMotherId()
258 if motherId > -1 :
259 mothertrack=sTree.MCTrack.At(motherId)
260 mothertrackZ=mothertrack.GetStartZ()
261 #this mother track is a HNL decay
262 #track starts inside the decay volume? (after veto, before 1 st tstation)
263 if mothertrackZ < TStation1StartZ and mothertrackZ > VetoStationEndZ:
264 if motherId not in MCTrackIDs:
265 MCTrackIDs.append(motherId)
266 else:
267 #track endpoint after tstations?
268 if atrack.GetStartZ() > TStation4EndZ :
269 motherId=atrack.GetMotherId()
270 if motherId > -1 :
271 mothertrack=sTree.MCTrack.At(motherId)
272 mothertrackZ=mothertrack.GetStartZ()
273 #this mother track is a HNL decay
274 #track starts inside the decay volume? (after veto, before 1 st tstation)
275 if mothertrackZ < TStation1StartZ and mothertrackZ > VetoStationEndZ:
276 if motherId not in MCTrackIDs:
277 MCTrackIDs.append(motherId)
278 if global_variables.debug:
279 print("Tracks with origin in decay volume", MCTrackIDs)
280 if len(MCTrackIDs)==0: return MCTrackIDs
281
282 #2. hitsinTimeDet: list of tracks with hits in TimeDet
283 nVetoHits = sTree.vetoPoint.GetEntriesFast()
284 hitsinTimeDet=[]
285 for i in range(nVetoHits):
286 avetohit = sTree.vetoPoint.At(i)
287 #hit in TimeDet?
288 if sGeo.FindNode(avetohit.GetX(),avetohit.GetY(),avetohit.GetZ()).GetName() == 'TimeDet_1':
289 if avetohit.GetTrackID() not in hitsinTimeDet:
290 hitsinTimeDet.append(avetohit.GetTrackID())
291
292 #3. Remove tracks from MCTrackIDs that are not in hitsinTimeDet
293 itemstoremove=[]
294 for item in MCTrackIDs:
295 if threeprong==1:
296 #don't remove the nu
297 if PDG.GetParticle(sTree.MCTrack.At(item).GetPdgCode()).GetName()[:5]!="nu_mu" and item not in hitsinTimeDet:
298 itemstoremove.append(item)
299 else :
300 if item not in hitsinTimeDet:
301 itemstoremove.append(item)
302 for item in itemstoremove:
303 MCTrackIDs.remove(item)
304
305 if global_variables.debug:
306 print("Tracks with hits in timedet", MCTrackIDs)
307 if len(MCTrackIDs)==0: return MCTrackIDs
308 #4. Find straws that have multiple hits
309 nHits = sTree.strawtubesPoint.GetEntriesFast()
310 hitstraws={}
311 duplicatestrawhit=[]
312 if global_variables.debug:
313 print("Nbr of Rawhits=", nHits)
314
315 for i in range(nHits):
316 ahit = sTree.strawtubesPoint[i]
317 if (str(ahit.GetDetectorID())[:1]=="5") :
318 if global_variables.debug:
319 print("Hit in straw Veto detector. Rejecting.")
320 continue
321 strawname=str(ahit.GetDetectorID())
322
323 if strawname in hitstraws:
324 #straw was already hit
325 if ahit.GetX()>hitstraws[strawname][1]:
326 #this hit has higher x, discard it
327 duplicatestrawhit.append(i)
328 else:
329 #del hitstraws[strawname]
330 duplicatestrawhit.append(hitstraws[strawname][0])
331 hitstraws[strawname]=[i,ahit.GetX()]
332 else:
333 hitstraws[strawname]=[i,ahit.GetX()]
334
335 #5. Split hits up by station and outside stations
336 hits1={}
337 hits2={}
338 hits3={}
339 hits4={}
340 trackoutsidestations=[]
341 for i in range(nHits):
342 if i in duplicatestrawhit:
343 if global_variables.debug:
344 print("Duplicate hit", i, "not reconstructible, rejecting.")
345 continue
346 ahit = sTree.strawtubesPoint[i]
347 #is hit inside acceptance? if not mark the track as bad
348 if (((ahit.GetX()/245.)**2 + (ahit.GetY()/495.)**2) >= 1.):
349 if ahit.GetTrackID() not in trackoutsidestations:
350 trackoutsidestations.append(ahit.GetTrackID())
351 if ahit.GetTrackID() not in MCTrackIDs:
352 #hit on not reconstructible track
353 if global_variables.debug:
354 print("Hit not on reconstructible track. Rejecting.")
355 continue
356 #group hits per tracking station, key = trackid
357 if str(ahit.GetDetectorID())[:1]=="1" :
358 if ahit.GetTrackID() in hits1:
359 hits1[ahit.GetTrackID()]=[hits1[ahit.GetTrackID()][0],i]
360 else:
361 hits1[ahit.GetTrackID()]=[i]
362 if str(ahit.GetDetectorID())[:1]=="2" :
363 if ahit.GetTrackID() in hits2:
364 hits2[ahit.GetTrackID()]=[hits2[ahit.GetTrackID()][0],i]
365 else:
366 hits2[ahit.GetTrackID()]=[i]
367 if str(ahit.GetDetectorID())[:1]=="3" :
368 if ahit.GetTrackID() in hits3:
369 hits3[ahit.GetTrackID()]=[hits3[ahit.GetTrackID()][0],i]
370 else:
371 hits3[ahit.GetTrackID()]=[i]
372 if str(ahit.GetDetectorID())[:1]=="4" :
373 if ahit.GetTrackID() in hits4:
374 hits4[ahit.GetTrackID()]=[hits4[ahit.GetTrackID()][0],i]
375 else:
376 hits4[ahit.GetTrackID()]=[i]
377
378 #6. Make list of tracks with hits in in station 1,2,3 & 4
379 tracks_with_hits_in_all_stations=[]
380 for key in hits1.keys():
381 if (key in hits2 and key in hits3 ) and key in hits4:
382 if key not in tracks_with_hits_in_all_stations and key not in trackoutsidestations:
383 tracks_with_hits_in_all_stations.append(key)
384 for key in hits2.keys():
385 if (key in hits1 and key in hits3 ) and key in hits4:
386 if key not in tracks_with_hits_in_all_stations and key not in trackoutsidestations:
387 tracks_with_hits_in_all_stations.append(key)
388 for key in hits3.keys():
389 if ( key in hits2 and key in hits1 ) and key in hits4:
390 if key not in tracks_with_hits_in_all_stations and key not in trackoutsidestations:
391 tracks_with_hits_in_all_stations.append(key)
392 for key in hits4.keys():
393 if (key in hits2 and key in hits3) and key in hits1:
394 if key not in tracks_with_hits_in_all_stations and key not in trackoutsidestations:
395 tracks_with_hits_in_all_stations.append(key)
396
397 #7. Remove tracks from MCTrackIDs with hits outside acceptance or doesn't have hits in all stations
398 itemstoremove=[]
399 for item in MCTrackIDs:
400 if threeprong==1:
401 #don't remove the nu
402 if PDG.GetParticle(sTree.MCTrack.At(item).GetPdgCode()).GetName()[:5]!="nu_mu" and item not in tracks_with_hits_in_all_stations:
403 itemstoremove.append(item)
404 else:
405 if item not in tracks_with_hits_in_all_stations:
406 itemstoremove.append(item)
407 for item in itemstoremove:
408 MCTrackIDs.remove(item)
409
410 if global_variables.debug:
411 print("tracks_with_hits_in_all_stations",tracks_with_hits_in_all_stations)
412 print("Tracks with hits in all stations & inside acceptance ellipse",MCTrackIDs)
413 if len(MCTrackIDs)==0: return MCTrackIDs
414 nbrechits=0
415 for i in range(nHits):
416 if i in duplicatestrawhit:
417 continue
418 nbrechits+=1
419 ahit = sTree.strawtubesPoint[i]
420 if ahit.GetTrackID()>-1 and ahit.GetTrackID() in MCTrackIDs:
421 atrack = sTree.MCTrack.At(ahit.GetTrackID())
422 for j in range(ahit.GetTrackID()+1,nMCTracks) :
423 childtrack = sTree.MCTrack.At(j)
424 if childtrack.GetMotherId() == ahit.GetTrackID():
425 trackmomentum=atrack.GetP()
426 trackweight=atrack.GetWeight()
427 rc=h['reconstructiblemomentum'].Fill(trackmomentum,trackweight)
428 motherId=atrack.GetMotherId()
429 if motherId==1 :
430 HNLmomentum=sTree.MCTrack.At(1).GetP()
431 rc=h['HNLmomentumvsweight'].Fill(trackweight,HNLmomentum)
432 if j==nMCTracks :
433 trackmomentum=atrack.GetP()
434 trackweight=atrack.GetWeight()
435 rc=h['reconstructiblemomentum'].Fill(trackmomentum,trackweight)
436 if atrack.GetMotherId()==1 :
437 HNLmomentum=sTree.MCTrack.At(1).GetP()
438 rc=h['HNLmomentumvsweight'].Fill(trackweight,HNLmomentum)
439 itemstoremove=[]
440 for item in MCTrackIDs:
441 atrack = sTree.MCTrack.At(item)
442 motherId=atrack.GetMotherId()
443 if motherId != 1:
444 itemstoremove.append(item)
445 for item in itemstoremove:
446 MCTrackIDs.remove(item)
447 if global_variables.debug:
448 print("After removing the non HNL track, MCTrackIDs", MCTrackIDs)
449 if global_variables.debug:
450 print("Tracks with HNL mother", MCTrackIDs)
451
452 #8. check if the tracks are HNL children
453 mufound=0
454 pifound=0
455 nu_mufound=0
456 itemstoremove=[]
457 if MCTrackIDs:
458 for item in MCTrackIDs:
459 try:
460 if PDG.GetParticle(sTree.MCTrack.At(item).GetPdgCode()).GetName()[:2]=="mu" : mufound+=1
461 if PDG.GetParticle(sTree.MCTrack.At(item).GetPdgCode()).GetName()[:2]=="pi" : pifound+=1
462 if PDG.GetParticle(sTree.MCTrack.At(item).GetPdgCode()).GetName()[:5]=="nu_mu":
463 nu_mufound+=1
464 itemstoremove.append(item)
465 except:
466 if global_variables.debug:
467 print("Unknown particle with pdg code:", sTree.MCTrack.At(item).GetPdgCode())
468 if reconstructiblerequired == 1 :
469 if mufound!=1 and pifound!=1:
470 if global_variables.debug:
471 print("No reconstructible pion or muon.")
472 MCTrackIDs=[]
473 if reconstructiblerequired == 2 :
474 if threeprong == 1 :
475 if mufound!=2 or nu_mufound!=1 :
476 if global_variables.debug:
477 print("No reconstructible mu-mu-nu.")
478 MCTrackIDs=[]
479 else:
480 #remove the neutrino from MCTrackIDs for the rest
481 for item in itemstoremove:
482 MCTrackIDs.remove(item)
483 else:
484 if mufound!=1 or pifound!=1 :
485 if global_variables.debug:
486 print("No reconstructible pion and muon.")
487 MCTrackIDs=[]
488 if len(MCTrackIDs)>0:
489 rc=h['nbrhits'].Fill(nHits)
490 rc=h['nbrtracks'].Fill(nMCTracks)
491 if global_variables.debug:
492 print("Tracks with required HNL decay particles", MCTrackIDs)
493 return MCTrackIDs
494

◆ hit2wire()

shipPatRec_prev.hit2wire (   ahit,
  bot,
  top,
  no_amb = None 
)

Definition at line 1608 of file shipPatRec_prev.py.

1608def hit2wire(ahit,bot,top,no_amb=None):
1609 detID = ahit.GetDetectorID()
1610 ex = ahit.GetX()
1611 ey = ahit.GetY()
1612 ez = ahit.GetZ()
1613 #distance to wire, and smear it.
1614 dw = ahit.dist2Wire()
1615 smear = dw
1616 if not no_amb: smear = ROOT.fabs(random.Gaus(dw,ShipGeo.strawtubes.sigma_spatial))
1617 smearedHit = {'mcHit':ahit,'xtop':top.x(),'ytop':top.y(),'z':top.z(),'xbot':bot.x(),'ybot':bot.y(),'z':bot.z(),'dist':smear}
1618 return smearedHit
1619

◆ initialize()

shipPatRec_prev.initialize (   fGeo)

Definition at line 127 of file shipPatRec_prev.py.

127def initialize(fGeo):
128 #creates a dictionary with z coordinates of layers
129 #and variables with station start/end coordinates
130 #to be called once at the beginning of the eventloop
131 global i1,i2,zlayer,zlayerv2,z34layer,z34layerv2,TStation1StartZ,TStation4EndZ,VetoStationZ,VetoStationEndZ
132 global fgeo
133 fgeo=fGeo
134 #z-positions of Y-view tracking
135 #4 stations, 4 views (Y,u,v,Y); each view has 2 planes and each plane has 2 layers
136
137 for i in range(i1,i2+1):
138 TStationz = ShipGeo.TrackStation1.z
139 if (i>8) :
140 TStationz = ShipGeo.TrackStation2.z
141 # Y: vnb=0 or 3
142 vnb=0.
143 if (i>4): vnb=3.
144 if (i>8): vnb=0.
145 if (i>12): vnb=3.
146 lnb = 0.
147 if (i % 2 == 0) : lnb=1.
148 pnb=0.
149 if (i==3 or i==4 or i==7 or i==8 or i==11 or i==12 or i==15 or i==16) : pnb=1.
150
151 #z positions of Y view of stations
152 Zpos = TStationz+(vnb-3./2.)*ShipGeo.strawtubes.DeltazView+(float(pnb)-1./2.)*ShipGeo.strawtubes.DeltazPlane+(float(lnb)-1./2.)*ShipGeo.strawtubes.DeltazLayer
153 zlayer[i]=[Zpos]
154
155 #z-positions for stereo views
156
157 for i in range(i1,i2+1):
158 TStationz = ShipGeo.TrackStation1.z
159 if (i>8) :
160 TStationz = ShipGeo.TrackStation2.z
161 #stereo views: vnb=1 or 2
162 vnb=1.
163 if (i>4): vnb=2.
164 if (i>8): vnb=1.
165 if (i>12): vnb=2.
166 lnb = 0.
167 if (i % 2 == 0) : lnb=1.
168 pnb=0.
169 if (i==3 or i==4 or i==7 or i==8 or i==11 or i==12 or i==15 or i==16) : pnb=1.
170
171 #z positions of u,v view of stations
172 Zpos_u = TStationz+(vnb-3./2.)*ShipGeo.strawtubes.DeltazView+(float(pnb)-1./2.)*ShipGeo.strawtubes.DeltazPlane+(float(lnb)-1./2.)*ShipGeo.strawtubes.DeltazLayer
173 zlayerv2[i]=[Zpos_u]
174
175
176 for i in range(i1,i2+1):
177 TStationz = ShipGeo.TrackStation3.z
178 if (i>8) :
179 TStationz = ShipGeo.TrackStation4.z
180 # Y: vnb=0 or 3
181 vnb=0.
182 if (i>4): vnb=3.
183 if (i>8): vnb=0.
184 if (i>12): vnb=3.
185 lnb = 0.
186 if (i % 2 == 0) : lnb=1.
187 pnb=0.
188 if (i==3 or i==4 or i==7 or i==8 or i==11 or i==12 or i==15 or i==16) : pnb=1.
189
190 #z positions of x1 view of stations
191 Zpos = TStationz+(vnb-3./2.)*ShipGeo.strawtubes.DeltazView+(float(pnb)-1./2.)*ShipGeo.strawtubes.DeltazPlane+(float(lnb)-1./2.)*ShipGeo.strawtubes.DeltazLayer
192 z34layer[i]=[Zpos]
193
194
195 for i in range(i1,i2+1):
196 #zlayerv2[i]=[i*100.+50.]
197 TStationz = ShipGeo.TrackStation3.z
198 if (i>8) :
199 TStationz = ShipGeo.TrackStation4.z
200 #stereo views: vnb=1 or 2
201 vnb=1.
202 if (i>4): vnb=2.
203 if (i>8): vnb=1.
204 if (i>12): vnb=2.
205 lnb = 0.
206 if (i % 2 == 0) : lnb=1.
207 pnb=0.
208 if (i==3 or i==4 or i==7 or i==8 or i==11 or i==12 or i==15 or i==16) : pnb=1.
209
210 #z positions of u,v view of stations
211 Zpos_u = TStationz+(vnb-3./2.)*ShipGeo.strawtubes.DeltazView+(float(pnb)-1./2.)*ShipGeo.strawtubes.DeltazPlane+(float(lnb)-1./2.)*ShipGeo.strawtubes.DeltazLayer
212 z34layerv2[i]=[Zpos_u]
213
214 VetoStationZ = ShipGeo.vetoStation.z
215 if global_variables.debug:
216 print("VetoStation midpoint z=", VetoStationZ)
217 VetoStationEndZ=VetoStationZ+(ShipGeo.strawtubes.DeltazView+ShipGeo.strawtubes.OuterStrawDiameter)/2
218 for i in range(1,5):
219 if i==1: TStationz = ShipGeo.TrackStation1.z
220 if i==2: TStationz = ShipGeo.TrackStation2.z
221 if i==3: TStationz = ShipGeo.TrackStation3.z
222 if i==4: TStationz = ShipGeo.TrackStation4.z
223 if global_variables.debug:
224 print("TrackStation",i," midpoint z=",TStationz)
225 for vnb in range(0,4):
226 for pnb in range (0,2):
227 for lnb in range (0,2):
228 Zpos = TStationz+(vnb-3./2.)*ShipGeo.strawtubes.DeltazView+(float(pnb)-1./2.)*ShipGeo.strawtubes.DeltazPlane+(float(lnb)-1./2.)*ShipGeo.strawtubes.DeltazLayer
229 print("TStation=",i,"view=",vnb,"plane=",pnb,"layer=",lnb,"z=",Zpos)
230
231 TStation1StartZ=zlayer[1][0]-ShipGeo.strawtubes.OuterStrawDiameter/2
232 TStation4EndZ=z34layer[16][0]+ShipGeo.strawtubes.OuterStrawDiameter/2
233
234 return
235

◆ IP()

shipPatRec_prev.IP (   s,
  t,
  b 
)

Definition at line 1550 of file shipPatRec_prev.py.

1550def IP(s, t, b):
1551 #some vector manipulations to get impact point of t-b to s
1552 dir=ROOT.TVector3(t-b)
1553 udir = ROOT.TVector3(dir.Unit())
1554 sep = ROOT.TVector3(t-s)
1555 ip = ROOT.TVector3(udir.Cross(sep.Cross(udir) ))
1556 return ip.Mag()
1557

◆ line2plane()

shipPatRec_prev.line2plane (   fitt,
  fitc,
  uvview,
  zuv 
)

Definition at line 1480 of file shipPatRec_prev.py.

1480def line2plane(fitt,fitc,uvview,zuv):
1481 #intersect horizontal plane, defined by tangent, constant in yz plane, with
1482 #stereo hits given in uvview,zuv with top/bottom hits of "straw"
1483 xb=uvview[0]
1484 yb=uvview[1]
1485 xt=uvview[2]
1486 yt=uvview[3]
1487 x=[]
1488 items=[]
1489 term=fitc+zuv*fitt
1490 #loop over all hits in this view
1491 for i in range(len(yb)):
1492 #f2=(term-yb[i])/(yt[i]-yb[i])
1493 #xint=xb[i]+f2*(xt[i]-xb[i])
1494 f2=(term-yb[i])/(yb[i]-yt[i])
1495 xint=xb[i]+f2*(xb[i]-xt[i])
1496 c=uvview[4][i]
1497 #do they cross inside sensitive volume defined by top/bottom of straw?
1498 if xint<max(xt[i],xb[i]) and xint>min(xb[i],xt[i]):
1499 x.append(xint)
1500 items.append(c)
1501 return x,items
1502

◆ match_tracks()

shipPatRec_prev.match_tracks (   t1,
  t2,
  zmagnet,
  Bdl 
)

Definition at line 1579 of file shipPatRec_prev.py.

1579def match_tracks(t1,t2,zmagnet,Bdl):
1580# match tracks before to after magnet
1581# t1,t2: x,y,z,tgx,tgy of two input tracks
1582# zmagnet: middle of the magnet
1583# BdL: Bdl in Tm
1584# returns:
1585# dx,dy: distance between tracks at zmagnet
1586# 1./pmom: innverse momentum*q estimated
1587
1588#linear extrapoaltion to centre of the magnet
1589 dz1=zmagnet-t1[2]
1590 x1m=t1[0]+dz1*t1[3]
1591 y1m=t1[1]+dz1*t1[4]
1592 dz2=zmagnet-t2[2]
1593 x2m=t2[0]+dz2*t2[3]
1594 y2m=t2[1]+dz2*t2[4]
1595 dx=x1m-x2m
1596 dy=y1m-y2m
1597
1598 alpha=math.atan(t1[4])-math.atan(t2[4])
1599 pinv=math.sin(alpha)/(Bdl*0.3)
1600 return dx,dy,alpha,pinv
1601

◆ PatRec()

shipPatRec_prev.PatRec (   firsttwo,
  zlayer,
  zlayerv2,
  StrawRaw,
  StrawRawLink,
  ReconstructibleMCTracks 
)

Definition at line 694 of file shipPatRec_prev.py.

694def PatRec(firsttwo,zlayer,zlayerv2,StrawRaw,StrawRawLink,ReconstructibleMCTracks):
695 global reconstructiblehorizontalidsfound12,reconstructiblestereoidsfound12,reconstructiblehorizontalidsfound34,reconstructiblestereoidsfound34
696 global reconstructibleidsfound12,reconstructibleidsfound34,rawhits,totalaftermatching
697
698 hits={}
699 rawhits={}
700 stereohits={}
701 hitids={}
702 ytan={}
703 ycst={}
704 horpx={}
705 horpy={}
706 horpz={}
707 stereomom={}
708 stereotan={}
709 stereocst={}
710 fraction={}
711 trackid={}
712 duplicates=[]
713 j=0
714 resolution=ShipGeo.strawtubes.sigma_spatial
715
716 for item in StrawRaw:
717 #y hits for horizontal straws
718 rawhits[j]=copy.deepcopy(((StrawRaw[item][1]+StrawRaw[item][4])/2,(StrawRaw[item][2]+StrawRaw[item][5])/2,StrawRaw[item][6]))
719 if firsttwo==True:
720 if global_variables.debug:
721 print(
722 "rawhits[", j, "]=", rawhits[j],
723 "trackid", StrawRawLink[item][0].GetTrackID(),
724 "strawname", StrawRawLink[item][0].GetDetectorID(),
725 "true x", StrawRawLink[item][0].GetX(),
726 "true y", StrawRawLink[item][0].GetY(),
727 "true z", StrawRawLink[item][0].GetZ()
728 )
729 j=j+1
730
731 sortedrawhits=OrderedDict(sorted(rawhits.items(),key=lambda t:t[1][1]))
732 if global_variables.debug:
733 print(" ")
734 print("horizontal view (y) hits ordered by plane: plane nr, zlayer, hits")
735
736 y2=[]
737 y3=[]
738 yother=[]
739 ymin2=[]
740 z2=[]
741 z3=[]
742 zother=[]
743 zmin2=[]
744 for i in range(i1,i2+1):
745 a=[] #the hits
746 c=[] #the keys pointing to the raw hits
747 d=[] #the distance to the wire
748 for item in sortedrawhits:
749 if (float(sortedrawhits[item][1])==float(zlayer[i][0])) :
750 #difference with previous version: make each hit a dictionary so we can later get back the mc trackid
751 if sortedrawhits[item][0] not in a:
752 a.append(float(sortedrawhits[item][0]))
753 else:
754 #This should never happen - duplicate hits are already removed at digitization
755 if global_variables.debug:
756 print(" wire hit again", sortedrawhits[item], "strawname=", StrawRawLink[item][0].GetDetectorID())
757 a.append(float(sortedrawhits[item][0]))
758 duplicates.append(float(zlayer[i][0]))
759 a.sort()
760 #find the key of the sorted hit
761 for value in a:
762 for item in sortedrawhits:
763 if ((float(sortedrawhits[item][0])==value) & (float(sortedrawhits[item][1])==float(zlayer[i][0]))) :
764 if item not in c :
765 c.append(item)
766 d.append(float(sortedrawhits[item][2]))
767 else :
768 continue
769 break
770 #indicate which hit has been used
771 b=len(a)*[0]
772 hits[i]=[a,b,c,d]
773 if global_variables.debug:
774 print(i, zlayer[i], hits[i])
775
776 # split hits up by trackid for debugging
777
778 for item in range(len(hits[i][0])):
779 if StrawRawLink[hits[i][2][item]][0].GetTrackID() == 3:
780 y3.append(float(hits[i][0][item]))
781 z3.append(float(zlayer[i][0]))
782 else:
783 if StrawRawLink[hits[i][2][item]][0].GetTrackID() == 2:
784 y2.append(float(hits[i][0][item]))
785 z2.append(float(zlayer[i][0]))
786 else:
787 if StrawRawLink[hits[i][2][item]][0].GetTrackID() == -2:
788 ymin2.append(float(hits[i][0][item]))
789 zmin2.append(float(zlayer[i][0]))
790 else:
791 yother.append(float(hits[i][0][item]))
792 zother.append(float(zlayer[i][0]))
793
794 if cheated==True :
795 if threeprong==1 : nrtrcandv1,trcandv1=ptrack(zlayer,hits,6,0.6)
796 else : nrtrcandv1,trcandv1=ptrack(zlayer,hits,7,0.5)
797 else :
798 if threeprong==1 : nrtrcandv1,trcandv1=ptrack(zlayer,hits,6,0.6)
799 else: nrtrcandv1,trcandv1=ptrack(zlayer,hits,7,0.7)
800
801 foundhorizontaltrackids=[]
802 horizontaltrackids=[]
803 removetrackids=[]
804 for t in trcandv1:
805 trackids=[]
806 if global_variables.debug:
807 print(' ')
808 print('track found in Y view:',t,' indices of hits in planes',trcandv1[t])
809 for ipl in range(len(trcandv1[t])):
810 indx= trcandv1[t][ipl]
811 if indx>-1:
812 if global_variables.debug:
813 print(
814 ' plane nr, z-position, y of hit, trackid:',
815 ipl, zlayer[ipl], hits[ipl][0][indx],
816 StrawRawLink[hits[ipl][2][indx]][0].GetTrackID()
817 )
818 trackids.append(StrawRawLink[hits[ipl][2][indx]][0].GetTrackID())
819 if global_variables.debug:
820 print(
821 " Largest fraction of hits in Y view:", fracMCsame(trackids)[0],
822 "on MC track with id",fracMCsame(trackids)[1]
823 )
824 if firsttwo==True:
825 h['fracsame12-y'].Fill(fracMCsame(trackids)[0])
826 else:
827 h['fracsame34-y'].Fill(fracMCsame(trackids)[0])
828 if monitor==1:
829 if fracMCsame(trackids)[1] in ReconstructibleMCTracks:
830 horizontaltrackids.append(fracMCsame(trackids)[1])
831 if fracMCsame(trackids)[1] not in foundhorizontaltrackids:
832 foundhorizontaltrackids.append(fracMCsame(trackids)[1])
833 else:
834 #this track is not reconstructible, remove it
835 if global_variables.debug:
836 print("Y view track with trackid", fracMCsame(trackids)[1], "is not reconstructible. Removing it.")
837 removetrackids.append(t)
838
839 if (len(foundhorizontaltrackids) == 0 or len(horizontaltrackids)==0 ):
840 if global_variables.debug:
841 print("No reconstructible Y view tracks found.")
842 if monitor==True : return 0,[],[],[],[],[],[],{},{},{},{},{}
843
844 for i in range(0,len(removetrackids)):
845 del trcandv1[removetrackids[i]]
846 nrtrcandv1=nrtrcandv1-1
847
848 #reorder trcandv1 after removing tracks
849 if len(removetrackids)>0:
850 j=0
851 for key in trcandv1:
852 j=j+1
853 if key!=j:
854 trcandv1[j]=trcandv1[key]
855 del trcandv1[key]
856
857 if monitor==1:
858 if len(ReconstructibleMCTracks)>0:
859 if firsttwo==True:
860 if len(foundhorizontaltrackids)>=len(ReconstructibleMCTracks) : reconstructiblehorizontalidsfound12+=1
861 else :
862 if global_variables.debug:
863 print("!!!!!!!!!!!!!!!! Difference between Y-view tracks found and reconstructible tracks (station 1&2). Quitting patrec.")
864 debugevent(iEvent,False,y2,y3,ymin2,yother,z2,z3,zmin2,zother,foundhorizontaltrackids)
865 return 0,[],[],[],[],[],[],{},{},{},{},{}
866 else:
867 if len(foundhorizontaltrackids)>=len(ReconstructibleMCTracks) : reconstructiblehorizontalidsfound34+=1
868 else :
869 if global_variables.debug:
870 print("!!!!!!!!!!!!!!!! Difference between Y-view tracks found and reconstructible tracks (station 3&4). Quitting patrec.")
871 debugevent(iEvent,False,y2,y3,ymin2,yother,z2,z3,zmin2,zother,foundhorizontaltrackids)
872 return 0,[],[],[],[],[],[],{},{},{},{},{}
873
874 if len(foundhorizontaltrackids) != reconstructiblerequired :
875 if global_variables.debug:
876 print(len(foundhorizontaltrackids), "Y view tracks found, but ", reconstructiblerequired, "required.")
877 return 0,[],[],[],[],[],[],{},{},{},{},{}
878 else:
879 if firsttwo==True: reconstructiblehorizontalidsfound12+=1
880 else: reconstructiblehorizontalidsfound34+=1
881
882
883 if nrtrcandv1==0 :
884 if global_variables.debug:
885 print("0 tracks found in Y view. Reconstructible:", len(ReconstructibleMCTracks))
886 if monitor==True: return 0,[],[],[],[],[],[],{},{},{},{},{}
887 else :
888 if global_variables.debug:
889 print(nrtrcandv1, "tracks found in Y view. Reconstructible:", len(ReconstructibleMCTracks))
890
891 if global_variables.debug:
892 print("***************** Start of Stereo PatRec **************************")
893
894 v2hits={}
895 v2hitsMC={}
896
897 uvview={}
898 j=0
899 rawxhits={}
900 for item in StrawRaw:
901 rawxhits[j]=copy.deepcopy((StrawRaw[item][0],StrawRaw[item][1],StrawRaw[item][3],StrawRaw[item][4],StrawRaw[item][2],StrawRaw[item][6]))
902 if firsttwo==True:
903 if global_variables.debug:
904 print(
905 "rawxhits[", j, "]=", rawxhits[j],
906 "trackid", StrawRawLink[item][0].GetTrackID(),
907 "true x", StrawRawLink[item][0].GetX(),
908 "true y",StrawRawLink[item][0].GetY()
909 )
910 j=j+1
911
912 sortedrawxhits=OrderedDict(sorted(rawxhits.items(),key=lambda t:t[1][4]))
913
914 if global_variables.debug:
915 print("stereo view hits ordered by plane:")
916 for i in range(i1,i2+1):
917 xb=[]
918 yb=[]
919 xt=[]
920 yt=[]
921 c=[]
922 d=[]
923 for item in sortedrawxhits:
924 if (float(sortedrawxhits[item][4])==float(zlayerv2[i][0])) :
925 xt.append(float(sortedrawxhits[item][0]))
926 yt.append(float(sortedrawxhits[item][1]))
927 xb.append(float(sortedrawxhits[item][2]))
928 yb.append(float(sortedrawxhits[item][3]))
929 #c is the rawxhits hit number
930 c.append(item)
931 #d is the distance to the wire
932 d.append(float(sortedrawxhits[item][5]))
933 uvview[i]=[xb,yb,xt,yt,c,d]
934
935 if global_variables.debug:
936 print(
937 ' uv hits, z,xb,yb,xt,yt,dist ',
938 i, zlayerv2[i], uvview[i][0], uvview[i][1], uvview[i][2],
939 uvview[i][3], uvview[i][4], uvview[i][5]
940 )
941
942 # now do pattern recognition in view perpendicular to first search view
943 # loop over tracks found in Y view, and intersect this "plane"
944 # with hits in other views, and project in "x", then ptrack in "x", etc..
945
946 #loop over tracks found in Y view
947 ntracks=0
948 trackkey=0
949 tracks={}
950 if global_variables.debug:
951 if (firsttwo==True) :
952 print('Loop over tracks found in Y view, stations 1&2')
953 else :
954 print('Loop over tracks found in Y view, stations 3&4')
955
956 foundstereotrackids=[]
957 foundtrackids=[]
958
959 for t in trcandv1:
960 alltrackids=[]
961 y11trackids=[]
962 y12trackids=[]
963 y21trackids=[]
964 y22trackids=[]
965 y11hitids=[]
966 y12hitids=[]
967 y21hitids=[]
968 y22hitids=[]
969 trackkey+=1
970
971 #linear "fit" to track found in this view
972
973 fitt,fitc=fitline(trcandv1[t],hits,zlayer,resolution)
974 if global_variables.debug:
975 print(' Track nr', t, 'in Y view: tangent, constant=', fitt, fitc)
976
977 tan=0.
978 cst=0.
979 px=0.
980 py=0.
981 pz=0.
982 m=0
983 if firsttwo==True: looplist=reversed(list(range(len(trcandv1[t]))))
984 else: looplist=list(range(len(trcandv1[t])))
985 for ipl in looplist:
986 indx= trcandv1[t][ipl]
987 if indx>-1:
988 if global_variables.debug:
989 print(' Plane nr, z-position, y of hit:', ipl, zlayer[ipl], hits[ipl][0][indx])
990 hitpoint=[zlayer[ipl],hits[ipl][0][indx]]
991 rc=h['disthittoYviewtrack'].Fill(dist2line(fitt,fitc,hitpoint))
992 #if px==0. : px=StrawRawLink[hits[ipl][2][indx]][0].GetPx()
993 #if py==0. : py=StrawRawLink[hits[ipl][2][indx]][0].GetPy()
994 #if pz==0. : pz=StrawRawLink[hits[ipl][2][indx]][0].GetPz()
995 px=StrawRawLink[hits[ipl][2][indx]][0].GetPx()
996 py=StrawRawLink[hits[ipl][2][indx]][0].GetPy()
997 pz=StrawRawLink[hits[ipl][2][indx]][0].GetPz()
998 ptmp=math.sqrt(px**2+py**2+pz**2)
999 if global_variables.debug:
1000 print(" p",ptmp,"px",px,"py",py,"pz",pz)
1001 if tan==0. : tan=py/pz
1002 if cst==0. : cst=StrawRawLink[hits[ipl][2][indx]][0].GetY()-tan*zlayer[ipl][0]
1003 rc=h['disthittoYviewMCtrack'].Fill(dist2line(tan,cst,hitpoint))
1004
1005 if global_variables.debug:
1006 print(' Track nr', t, 'in Y view: MC tangent, MC constant=', tan, cst)
1007
1008 for ipl in range(len(trcandv1[t])):
1009 indx= trcandv1[t][ipl]
1010 if indx>-1:
1011 diffy=hits[ipl][0][indx]-StrawRawLink[hits[ipl][2][indx]][0].GetY()
1012 h['digi-truevstruey'].Fill(diffy)
1013 if ipl<5:
1014 y11trackids.append(StrawRawLink[hits[ipl][2][indx]][0].GetTrackID())
1015 y11hitids.append([hits[ipl][2][indx]][0])
1016 if (ipl>4 and ipl<9):
1017 y12trackids.append(StrawRawLink[hits[ipl][2][indx]][0].GetTrackID())
1018 y12hitids.append([hits[ipl][2][indx]][0])
1019 if (ipl>9 and ipl<13):
1020 y21trackids.append(StrawRawLink[hits[ipl][2][indx]][0].GetTrackID())
1021 y21hitids.append([hits[ipl][2][indx]][0])
1022 if ipl>12:
1023 y22trackids.append(StrawRawLink[hits[ipl][2][indx]][0].GetTrackID())
1024 y22hitids.append([hits[ipl][2][indx]][0])
1025 else:
1026 if ipl<5:
1027 y11trackids.append(999)
1028 y11hitids.append(999)
1029 if (ipl>4 and ipl<9):
1030 y12trackids.append(999)
1031 y12hitids.append(999)
1032 if (ipl>9 and ipl<13):
1033 y21trackids.append(999)
1034 y21hitids.append(999)
1035 if ipl>12:
1036 y22trackids.append(999)
1037 y22hitids.append(999)
1038
1039 #intersect this "plane", with all hits in all other views...
1040
1041 v2y2=[]
1042 v2y3=[]
1043 v2yother=[]
1044 v2ymin2=[]
1045 v2z2=[]
1046 v2z3=[]
1047 v2zother=[]
1048 v2zmin2=[]
1049 for ipl in range(1,len(zlayerv2)+1):
1050 items=[]
1051 xclean=[]
1052 distances=[]
1053 if cheated==False:
1054 xclean,items=line2plane(fitt,fitc,uvview[ipl],zlayerv2[ipl][0])
1055
1056 else:
1057 xclean=copy.deepcopy(uvview[ipl][0])
1058 items=copy.deepcopy(uvview[ipl][4])
1059
1060 distances=copy.deepcopy(uvview[ipl][5])
1061 xcleanunsorted=[]
1062 xcleanunsorted=list(xclean)
1063
1064 xclean.sort()
1065 b=len(xclean)*[0]
1066 d=[]
1067 e=[]
1068 for item in xclean:
1069 d.append(items[xcleanunsorted.index(item)])
1070 e.append(distances[xcleanunsorted.index(item)])
1071 #fill hits info for ptrack, "b" records if hit has been used in ptrack
1072 v2hits[ipl]=[xclean,b,d,e]
1073 if global_variables.debug:
1074 print(' Plane,z, projected hits:', ipl , zlayerv2[ipl], v2hits[ipl])
1075
1076 for item in range(len(v2hits[ipl][0])):
1077 if StrawRawLink[v2hits[ipl][2][item]][0].GetTrackID() == 3:
1078 v2y3.append(float(v2hits[ipl][0][item]))
1079 v2z3.append(float(zlayerv2[ipl][0]))
1080 else:
1081 if StrawRawLink[v2hits[ipl][2][item]][0].GetTrackID() == 2:
1082 v2y2.append(float(v2hits[ipl][0][item]))
1083 v2z2.append(float(zlayerv2[ipl][0]))
1084 else:
1085 if StrawRawLink[v2hits[ipl][2][item]][0].GetTrackID() == -2:
1086 v2ymin2.append(float(v2hits[ipl][0][item]))
1087 v2zmin2.append(float(zlayerv2[ipl][0]))
1088 else:
1089 v2yother.append(float(v2hits[ipl][0][item]))
1090 v2zother.append(float(zlayerv2[ipl][0]))
1091
1092 #pattern recognition for this track, blow up y-window, maybe make dependend of stereo angle,
1093 #constant now, should be 5*error/sin(alpha) :-), i.e. variable/plane if different "alphas"
1094 #Hence, for "real" y-view, should be small.
1095 if cheated==True:
1096 nrtrcandv2,trcandv2=ptrack(zlayerv2,v2hits,7,0.7)
1097 else:
1098 nrtrcandv2,trcandv2=ptrack(zlayerv2,v2hits,6,15.)
1099 if len(trcandv2)>1:
1100 if global_variables.debug:
1101 print(" len(trcandv2) in stereo", len(trcandv2))
1102
1103 nstereotracks=0
1104 if nrtrcandv2==0 :
1105 if global_variables.debug:
1106 print(" 0 tracks found in stereo view, for Y-view track nr", t)
1107
1108
1109 #if firsttwo==True: totalstereo12=reconstructiblestereoidsfound12
1110 #else: totalstereo34==reconstructiblestereoidsfound34
1111
1112 for t1 in trcandv2:
1113 if global_variables.debug:
1114 print(' Track belonging to Y-view view track', t, 'found in stereo view:', t1, trcandv2[t1])
1115
1116 stereofitt,stereofitc=fitline(trcandv2[t1],v2hits,zlayerv2,resolution)
1117
1118 pxMC=0.
1119 pzMC=0.
1120 stereotanMCv=0.
1121 stereocstMCv=0.
1122 if firsttwo==True: looplist=reversed(list(range(len(trcandv2[t1]))))
1123 else: looplist=list(range(len(trcandv2[t1])))
1124 for ipl in looplist:
1125 indx= trcandv2[t1][ipl]
1126 if indx>-1:
1127 hitpointx=[zlayerv2[ipl],v2hits[ipl][0][indx]]
1128 rc=h['disthittostereotrack'].Fill(dist2line(stereofitt,stereofitc,hitpointx))
1129 if pxMC==0. : pxMC=StrawRawLink[v2hits[ipl][2][indx]][0].GetPx()
1130 if pzMC ==0. : pzMC=StrawRawLink[v2hits[ipl][2][indx]][0].GetPz()
1131 if stereotanMCv==0. : stereotanMCv=pxMC/pzMC
1132 if stereocstMCv==0. : stereocstMCv=StrawRawLink[v2hits[ipl][2][indx]][0].GetX()-stereotanMCv*zlayerv2[ipl][0]
1133 rc=h['disthittostereoMCtrack'].Fill(dist2line(stereotanMCv,stereocstMCv,hitpointx))
1134
1135
1136 stereotrackids=[]
1137
1138 stereo11trackids=[]
1139 stereo12trackids=[]
1140 stereo21trackids=[]
1141 stereo22trackids=[]
1142 stereo11hitids=[]
1143 stereo12hitids=[]
1144 stereo21hitids=[]
1145 stereo22hitids=[]
1146 nstereotracks+=1
1147
1148
1149 for ipl in range(len(trcandv2[t1])):
1150 indx= trcandv2[t1][ipl]
1151 if indx>-1:
1152 stereotrackids.append(StrawRawLink[v2hits[ipl][2][indx]][0].GetTrackID())
1153 if global_variables.debug:
1154 print(
1155 " plane nr, zpos, x of hit, hitid, trackid",
1156 ipl, zlayerv2[ipl], v2hits[ipl][0][indx], v2hits[ipl][2][indx],
1157 StrawRawLink[v2hits[ipl][2][indx]][0].GetTrackID()
1158 )
1159 xdiff=v2hits[ipl][0][indx]-StrawRawLink[v2hits[ipl][2][indx]][0].GetX()
1160 h['digi-truevstruex'].Fill(xdiff)
1161 if ipl<5:
1162 if indx>-1:
1163 stereo11trackids.append(StrawRawLink[v2hits[ipl][2][indx]][0].GetTrackID())
1164 stereo11hitids.append(v2hits[ipl][2][indx])
1165 else:
1166 stereo11trackids.append(999)
1167 stereo11hitids.append(999)
1168 if (ipl>4 and ipl<9):
1169 if indx>-1:
1170 stereo12trackids.append(StrawRawLink[v2hits[ipl][2][indx]][0].GetTrackID())
1171 stereo12hitids.append(v2hits[ipl][2][indx])
1172 else:
1173 stereo12trackids.append(999)
1174 stereo12hitids.append(999)
1175 if (ipl>9 and ipl<13):
1176 if indx>-1:
1177 stereo21trackids.append(StrawRawLink[v2hits[ipl][2][indx]][0].GetTrackID())
1178 stereo21hitids.append(v2hits[ipl][2][indx])
1179 else:
1180 stereo21trackids.append(999)
1181 stereo21hitids.append(999)
1182 if ipl>12:
1183 if indx>-1:
1184 stereo22trackids.append(StrawRawLink[v2hits[ipl][2][indx]][0].GetTrackID())
1185 stereo22hitids.append(v2hits[ipl][2][indx])
1186 else:
1187 stereo22trackids.append(999)
1188 stereo22hitids.append(999)
1189
1190 if firsttwo==True: h['fracsame12-stereo'].Fill(fracMCsame(stereotrackids)[0])
1191 else: h['fracsame34-stereo'].Fill(fracMCsame(stereotrackids)[0])
1192
1193 if global_variables.debug:
1194 print(" Largest fraction of hits in stereo view:",fracMCsame(stereotrackids)[0],"on MC track with id",fracMCsame(stereotrackids)[1])
1195 #check if this trackid is the same as the track from the Y-view it belongs to
1196 if monitor==True: print(" fracMCsame(stereotrackids)[1]", fracMCsame(stereotrackids)[1],"foundhorizontaltrackids[",t-1,"]",foundhorizontaltrackids[t-1])
1197
1198 if monitor==True:
1199 if fracMCsame(stereotrackids)[1] != horizontaltrackids[t-1] :
1200 if global_variables.debug:
1201 print(
1202 " Stereo track with trackid",
1203 fracMCsame(stereotrackids)[1],
1204 "does not belong to the Y-view track with id=",
1205 horizontaltrackids[t-1]
1206 )
1207 continue
1208
1209 #check if this trackid belongs to a reconstructible track
1210 if fracMCsame(stereotrackids)[1] in ReconstructibleMCTracks:
1211 if fracMCsame(stereotrackids)[1] not in foundstereotrackids:
1212 foundstereotrackids.append(fracMCsame(stereotrackids)[1])
1213 else:
1214 if global_variables.debug:
1215 print(
1216 " Stereo track with trackid",
1217 fracMCsame(stereotrackids)[1],
1218 "is not reconstructible. Removing it."
1219 )
1220 continue
1221 else:
1222 if fracMCsame(stereotrackids)[1] not in foundstereotrackids:
1223 foundstereotrackids.append(fracMCsame(stereotrackids)[1])
1224
1225 ntracks=ntracks+1
1226 alltrackids=y11trackids+stereo11trackids+stereo12trackids+y12trackids+y21trackids+stereo21trackids+stereo22trackids+y22trackids
1227 if firsttwo==True: h['fracsame12'].Fill(fracMCsame(alltrackids)[0])
1228 else: h['fracsame34'].Fill(fracMCsame(alltrackids)[0])
1229 if global_variables.debug:
1230 print(
1231 " Largest fraction of hits in horizontal and stereo view:", fracMCsame(alltrackids)[0],
1232 "on MC track with id", fracMCsame(alltrackids)[1]
1233 )
1234
1235 #calculate efficiency after joining horizontal and stereo tracks
1236 if monitor==True:
1237 if fracMCsame(alltrackids)[1] in ReconstructibleMCTracks:
1238 if fracMCsame(alltrackids)[1] not in foundtrackids:
1239 foundtrackids.append(fracMCsame(alltrackids)[1])
1240
1241 tracks[trackkey*1000+nstereotracks]=alltrackids
1242 hitids[trackkey*1000+nstereotracks]=y11hitids+stereo11hitids+stereo12hitids+y12hitids+y21hitids+stereo21hitids+stereo22hitids+y22hitids
1243 if cheated==False :
1244 ytan[trackkey*1000+nstereotracks]=fitt
1245 ycst[trackkey*1000+nstereotracks]=fitc
1246 else:
1247 ytan[trackkey*1000+nstereotracks]=tan
1248 ycst[trackkey*1000+nstereotracks]=cst
1249
1250
1251 fraction[trackkey*1000+nstereotracks]=fracMCsame(alltrackids)[0]
1252 trackid[trackkey*1000+nstereotracks]=fracMCsame(alltrackids)[1]
1253
1254
1255 horpx[trackkey*1000+nstereotracks]=px
1256 horpy[trackkey*1000+nstereotracks]=py
1257 horpz[trackkey*1000+nstereotracks]=pz
1258
1259 if cheated==False:
1260 stereotan[trackkey*1000+nstereotracks]=stereofitt
1261 stereocst[trackkey*1000+nstereotracks]=stereofitc
1262 else:
1263 stereotan[trackkey*1000+nstereotracks]=stereotanMCv
1264 stereocst[trackkey*1000+nstereotracks]=stereocstMCv
1265 else:
1266 if global_variables.debug:
1267 print("Track with trackid", fracMCsame(alltrackids)[1], "is not reconstructible. Removing it.")
1268 continue
1269 else:
1270 if fracMCsame(alltrackids)[1] not in foundtrackids:
1271 foundtrackids.append(fracMCsame(alltrackids)[1])
1272
1273 tracks[trackkey*1000+nstereotracks]=alltrackids
1274 hitids[trackkey*1000+nstereotracks]=y11hitids+stereo11hitids+stereo12hitids+y12hitids+y21hitids+stereo21hitids+stereo22hitids+y22hitids
1275 if cheated==False :
1276 ytan[trackkey*1000+nstereotracks]=fitt
1277 ycst[trackkey*1000+nstereotracks]=fitc
1278 else:
1279 ytan[trackkey*1000+nstereotracks]=tan
1280 ycst[trackkey*1000+nstereotracks]=cst
1281
1282
1283 fraction[trackkey*1000+nstereotracks]=fracMCsame(alltrackids)[0]
1284 trackid[trackkey*1000+nstereotracks]=fracMCsame(alltrackids)[1]
1285
1286
1287 horpx[trackkey*1000+nstereotracks]=px
1288 horpy[trackkey*1000+nstereotracks]=py
1289 horpz[trackkey*1000+nstereotracks]=pz
1290
1291 if cheated==False:
1292 stereotan[trackkey*1000+nstereotracks]=stereofitt
1293 stereocst[trackkey*1000+nstereotracks]=stereofitc
1294 else:
1295 stereotan[trackkey*1000+nstereotracks]=stereotanMCv
1296 stereocst[trackkey*1000+nstereotracks]=stereocstMCv
1297
1298 if monitor==True:
1299 if len(foundstereotrackids)>=len(ReconstructibleMCTracks) :
1300 if firsttwo==True: reconstructiblestereoidsfound12+=1
1301 else: reconstructiblestereoidsfound34+=1
1302 else:
1303 if global_variables.debug:
1304 debugevent(iEvent,True,v2y2,v2y3,v2ymin2,v2yother,v2z2,v2z3,v2zmin2,v2zother,foundstereotrackids)
1305 print("Nbr of reconstructible tracks after stereo",len(foundstereotrackids)," but ",len(ReconstructibleMCTracks)," reconstructible tracks in this event. Quitting.")
1306 return 0,[],[],[],[],[],[],{},{},{},{},{}
1307
1308 if len(foundtrackids)>=len(ReconstructibleMCTracks):
1309 if firsttwo==True: reconstructibleidsfound12+=1
1310 else: reconstructibleidsfound34+=1
1311 else:
1312 if global_variables.debug:
1313 debugevent(iEvent,True,v2y2,v2y3,v2ymin2,v2yother,v2z2,v2z3,v2zmin2,v2zother,foundstereotrackids)
1314 print("Nbr of reconstructed tracks ",len(foundtrackids)," but",len(ReconstructibleMCTracks)," reconstructible tracks in this event. Quitting.")
1315 return 0,[],[],[],[],[],[],{},{},{},{},{}
1316 else:
1317 if firsttwo==True: reconstructiblestereoidsfound12+=1
1318 else: reconstructiblestereoidsfound34+=1
1319 if firsttwo==True: reconstructibleidsfound12+=1
1320 else: reconstructibleidsfound34+=1
1321
1322 #now Kalman fit, collect "all hits" around fitted track, outlier removal etc..
1323 return ntracks,tracks,hitids,ytan,ycst,stereotan,stereocst,horpx,horpy,horpz,fraction,trackid
1324

◆ ptrack()

shipPatRec_prev.ptrack (   zlayer,
  ptrackhits,
  nrwant,
  window 
)

Definition at line 1389 of file shipPatRec_prev.py.

1389def ptrack(zlayer,ptrackhits,nrwant,window):
1390
1391# basic pattern recognition in one view
1392# zlayer= dictionary with z-position of planes: zlayer[iplane][0]==z-position (list of length 1 :-).
1393# ptrackhits is dictionary with hits in a projection: ptrackhits[plane number][0]=list-of-hits
1394# ndrop= nr of hits that can be missing in this projection
1395# nrwant= min nr of hits on a track in this projection
1396# window: is the size of the search window
1397
1398# get first and last plane number (needs to be consecutive, and also contains empty planes
1399# should be included in the list!
1400 planes=list(zlayer.keys())
1401 planes.sort()
1402 i_1=planes[0]
1403 i_2=planes[len(planes)-1]
1404 ndrop=len(planes)-nrwant
1405 #print 'ptrack input: planes=',i_1,i_2,ndrop,window," ptrackhits ",ptrackhits
1406
1407 nrtracks=0
1408 tracks={}
1409
1410 #loop over maxnr hits, to max-ndrop
1411 for nhitw in range(i_2-i_1+1,i_2-i_1-ndrop,-1):
1412 # nhitw: wanted number of hits when looking for a track
1413 for idrop in range(ndrop):
1414 #only start if wanted nr hits <= the nr of planes
1415 nrhitmax=i_2-i_1-idrop+1
1416 if nhitw<=nrhitmax:
1417 for k in range(idrop+1):
1418 #calculate the id of the first and last plane for this try.
1419 ifirst=i_1+k
1420 ilast=i_2-(idrop-k)
1421 #now loop over hits in first/last planes, and construct line
1422 dz=zlayer[ilast][0]-zlayer[ifirst][0]
1423 #hits in first plane
1424 for ifr in range(len(ptrackhits[ifirst][0])):
1425 #for ifr in range(len(ptrackhits[ifirst][0])):
1426 #has this hit been used already for a track: skip
1427 if ptrackhits[ifirst][1][ifr]==0:
1428 xfirst= ptrackhits[ifirst][0][ifr]
1429 #hits in last plane
1430 for il in range(len(ptrackhits[ilast][0])):
1431 #has this hit been used already for a track: skip
1432 if ptrackhits[ilast][1][il]==0:
1433 xlast= ptrackhits[ilast][0][il]
1434 nrhitsfound=2
1435 tancand=(xlast-xfirst)/dz
1436 #fill temporary hit list for track-candidate with -1
1437 trcand=(i_2-i_1+2)*[-1]
1438 #loop over in between planes
1439 for inbetween in range(ifirst+1,ilast):
1440 #can wanted number of hits be satisfied?
1441 if nrhitsfound+ilast-inbetween>=nhitw:
1442 #calculate candidate hit
1443 xwinlow=xfirst+tancand*(zlayer[inbetween][0]-zlayer[ifirst][0])-window
1444 for im in range(len(ptrackhits[inbetween][0])):
1445 #has this hit been used?
1446 if ptrackhits[inbetween][1][im]==0:
1447 xin= ptrackhits[inbetween][0][im]
1448 #hit belwo window, try next one
1449 if xin>xwinlow:
1450 #if hit larger than upper edge of window: goto next plane
1451 if xin>xwinlow+2*window:
1452 break
1453 #hit found, do administation
1454 if trcand[inbetween]==-1:
1455 nrhitsfound+=1
1456 trcand[inbetween]=im
1457 #looped over in between planes, collected enough hits?
1458 if nrhitsfound==nhitw:
1459 #mark used hits
1460 trcand[ifirst]=ifr
1461 trcand[ilast]=il
1462 for i in range(ifirst,ilast+1):
1463 if trcand[i]>=0:
1464 ptrackhits[i][1][trcand[i]]=1
1465 #store the track
1466 nrtracks+=1
1467 #print "ptrack nrtracks",nrtracks
1468 tracks[nrtracks]=trcand
1469 #print "ptrack: tracks",tracks
1470 return nrtracks,tracks
1471

◆ SmearHits()

shipPatRec_prev.SmearHits (   iEvent,
  sTree,
  modules,
  SmearedHits,
  ReconstructibleMCTracks 
)

Definition at line 495 of file shipPatRec_prev.py.

495def SmearHits(iEvent,sTree,modules,SmearedHits,ReconstructibleMCTracks):
496 #smears hits (when not cheated)
497 #apply cuts for >500 hits, duplicate straw hits and acceptance
498 #call this routine once for each event, before the digitization
499
500 top=ROOT.TVector3()
501 bot=ROOT.TVector3()
502 random = ROOT.TRandom()
503 ROOT.gRandom.SetSeed(13)
504
505 rc = sTree.GetEvent(iEvent)
506 nHits = sTree.strawtubesPoint.GetEntriesFast()
507 withNoStrawSmearing=None
508 hitstraws={}
509 duplicatestrawhit=[]
510
511 for i in range(nHits):
512 ahit = sTree.strawtubesPoint[i]
513 if (str(ahit.GetDetectorID())[:1]=="5") : continue
514 strawname=str(ahit.GetDetectorID())
515 if strawname in hitstraws:
516 #straw was already hit
517 if ahit.GetX()>hitstraws[strawname][1]:
518 #this hit has higher x, discard it
519 duplicatestrawhit.append(i)
520 else:
521 #del hitstraws[strawname]
522 duplicatestrawhit.append(hitstraws[strawname][0])
523 hitstraws[strawname]=[i,ahit.GetX()]
524 else:
525 hitstraws[strawname]=[i,ahit.GetX()]
526
527 #the following code prints some histograms related to the MC hits
528 strawname=''
529 if global_variables.debug:
530 print("nbr of hits=", nHits, "in event", iEvent)
531 station1hits={}
532 station12xhits={}
533 station12yhits={}
534 station2hits={}
535 station3hits={}
536 station4hits={}
537
538 for i in range(nHits):
539 ahit = sTree.strawtubesPoint[i]
540 strawname=str(ahit.GetDetectorID())
541 #is it a duplicate hit? if so, ignore it
542 if i in duplicatestrawhit:
543 continue
544 #only look at hits in the strawtracking stations
545 if (str(ahit.GetDetectorID())[:1]=="5") : continue
546 #is hit inside acceptance?
547 if (((ahit.GetX()/245.)**2 + (ahit.GetY()/495.)**2) >= 1.): continue
548
549 modules["Strawtubes"].StrawEndPoints(ahit.GetDetectorID(),bot,top)
550 if cheated==False :
551 #this is where the smearing takes place. the hit coordinates can also be read from somewhere else.
552 sm = hit2wire(ahit,bot,top,withNoStrawSmearing)
553 m = array('d',[i,sm['xtop'],sm['ytop'],sm['z'],sm['xbot'],sm['ybot'],sm['z'],sm['dist'],ahit.GetDetectorID()])
554 else :
555 #for MC truth
556 m = array('d',[i,ahit.GetX(),ahit.GetY(),top[2],ahit.GetX(),ahit.GetY(),top[2],ahit.dist2Wire(),ahit.GetDetectorID()])
557
558 measurement = ROOT.TVectorD(9,m)
559
560 smHits = SmearedHits.GetEntries()
561 if SmearedHits.GetSize() == smHits: SmearedHits.Expand(smHits+1000)
562 SmearedHits[smHits] = measurement
563
564
565 angle=0.
566 if (str(ahit.GetDetectorID())[1:2]=="1"): angle=ShipGeo.strawtubes.ViewAngle
567 if (str(ahit.GetDetectorID())[1:2]=="2"): angle=ShipGeo.strawtubes.ViewAngle*-1.
568 if (str(ahit.GetDetectorID())[:1]=="1") :
569 if ahit.GetTrackID() in station1hits:
570 station1hits[ahit.GetTrackID()]+=1
571 rc=h['hits1xy'].Fill(ahit.GetX(),ahit.GetY())
572 else:
573 station1hits[ahit.GetTrackID()]=1
574 if (str(ahit.GetDetectorID())[:1]=="2") :
575 if ahit.GetTrackID() in station2hits:
576 station2hits[ahit.GetTrackID()]+=1
577 else:
578 station2hits[ahit.GetTrackID()]=1
579 if (str(ahit.GetDetectorID())[:1]=="3") :
580 if ahit.GetTrackID() in station3hits:
581 station3hits[ahit.GetTrackID()]+=1
582 else:
583 station3hits[ahit.GetTrackID()]=1
584 if (str(ahit.GetDetectorID())[:1]=="4") :
585 if ahit.GetTrackID() in station4hits:
586 station4hits[ahit.GetTrackID()]+=1
587 else:
588 station4hits[ahit.GetTrackID()]=1
589
590 if ((str(ahit.GetDetectorID())[:2]=="11" or str(ahit.GetDetectorID())[:2]=="12") or (str(ahit.GetDetectorID())[:2]=="21" or str(ahit.GetDetectorID())[:2]=="22")):
591 if ahit.GetTrackID() in station12xhits:
592 station12xhits[ahit.GetTrackID()]+=1
593 else:
594 station12xhits[ahit.GetTrackID()]=1
595
596 if ((str(ahit.GetDetectorID())[:2]=="10" or str(ahit.GetDetectorID())[:2]=="13") or (str(ahit.GetDetectorID())[:2]=="20" or str(ahit.GetDetectorID())[:2]=="23")):
597 if ahit.GetTrackID() in station12yhits:
598 station12yhits[ahit.GetTrackID()]+=1
599 else:
600 station12yhits[ahit.GetTrackID()]=1
601
602 total1hits=0
603 total12xhits=0
604 total12yhits=0
605 hits1pertrack=0
606 hits12xpertrack=0
607 hits12ypertrack=0
608 total2hits=0
609 hits2pertrack=0
610 total3hits=0
611 hits3pertrack=0
612 total4hits=0
613 hits4pertrack=0
614 for items in station1hits:
615 # only count the hits on reconstructible tracks
616 if monitor==True:
617 if items in ReconstructibleMCTracks: total1hits=total1hits+station1hits[items]
618 else : total1hits=total1hits+station1hits[items]
619 if len(station1hits) > 0 :
620 hits1pertrack=total1hits/len(station1hits)
621 for items in station12xhits:
622 if monitor==True:
623 if items in ReconstructibleMCTracks: total12xhits=total12xhits+station12xhits[items]
624 else: total12xhits=total12xhits+station12xhits[items]
625 if len(station12xhits) > 0 : hits12xpertrack=total12xhits/len(station12xhits)
626 for items in station12yhits:
627 if monitor==True:
628 if items in ReconstructibleMCTracks: total12yhits=total12yhits+station12yhits[items]
629 else: total12yhits=total12yhits+station12yhits[items]
630 if len(station12yhits) > 0 : hits12ypertrack=total12yhits/len(station12yhits)
631 for items in station2hits:
632 if monitor==True:
633 if items in ReconstructibleMCTracks: total2hits=total2hits+station2hits[items]
634 else: total2hits=total2hits+station2hits[items]
635 if len(station2hits) > 0 :
636 hits2pertrack=total2hits/len(station2hits)
637 for items in station3hits:
638 if monitor==True:
639 if items in ReconstructibleMCTracks: total3hits=total3hits+station3hits[items]
640 else: total3hits=total3hits+station3hits[items]
641 if len(station3hits) > 0 :
642 hits3pertrack=total3hits/len(station3hits)
643 for items in station4hits:
644 if monitor==True:
645 if items in ReconstructibleMCTracks: total4hits=total4hits+station4hits[items]
646 else: total4hits=total4hits+station4hits[items]
647 if len(station4hits) > 0 :
648 hits4pertrack=total4hits/len(station4hits)
649
650 rc=h['hits1-4'].Fill(hits1pertrack+hits2pertrack+hits3pertrack+hits4pertrack)
651 rc=h['hits1'].Fill(hits1pertrack)
652 rc=h['hits12x'].Fill(hits12xpertrack)
653 rc=h['hits12y'].Fill(hits12ypertrack)
654 rc=h['hits2'].Fill(hits2pertrack)
655 rc=h['hits3'].Fill(hits3pertrack)
656 rc=h['hits4'].Fill(hits4pertrack)
657 return SmearedHits
658
659

◆ TrackFit()

shipPatRec_prev.TrackFit (   hitPosList,
  theTrack,
  charge,
  pinv 
)

Definition at line 1325 of file shipPatRec_prev.py.

1325def TrackFit(hitPosList,theTrack,charge,pinv):
1326 global theTracks
1327 if global_variables.debug:
1328 fitter.setDebugLvl(1)
1329 resolution = ShipGeo.strawtubes.sigma_spatial
1330 hitCov = ROOT.TMatrixDSym(7)
1331 hitCov[6][6] = resolution*resolution
1332 for item in hitPosList:
1333 itemarray=array('d',[item[0],item[1],item[2],item[3],item[4],item[5],item[6]])
1334 ms=ROOT.TVectorD(7,itemarray)
1335 tp = ROOT.genfit.TrackPoint(theTrack) # note how the point is told which track it belongs to
1336 measurement = ROOT.genfit.WireMeasurement(ms,hitCov,1,6,tp) # the measurement is told which trackpoint it belongs to
1337 measurement.setMaxDistance(0.5*u.cm)
1338 tp.addRawMeasurement(measurement) # package measurement in the TrackPoint
1339 theTrack.insertPoint(tp) # add point to Track
1340 theTracks.append(theTrack)
1341 if not global_variables.debug:
1342 return # leave track fitting to shipDigiReco
1343#check
1344 if not theTrack.checkConsistency():
1345 print('Problem with track before fit, not consistent', theTrack)
1346 return
1347# do the fit
1348 try: fitter.processTrack(theTrack)
1349 except:
1350 print("genfit failed to fit track")
1351 return
1352#check
1353 if not theTrack.checkConsistency():
1354 print('Problem with track after fit, not consistent', theTrack)
1355 return
1356
1357
1358 fitStatus = theTrack.getFitStatus()
1359 theTrack.prune("CFL") # http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280
1360
1361 nmeas = fitStatus.getNdf()
1362 pval = fitStatus.getPVal()
1363
1364 #pval close to 0 indicates a bad fit
1365 chi2 = fitStatus.getChi2()/nmeas
1366
1367 rc=h['chi2fittedtracks'].Fill(chi2)
1368 rc=h['pvalfittedtracks'].Fill(pval)
1369
1370
1371 fittedState = theTrack.getFittedState()
1372 fittedMom = fittedState.getMomMag()
1373 fittedMom = fittedMom*int(charge)
1374
1375 if math.fabs(pinv) > 0.0 : rc=h['pvspfitted'].Fill(1./pinv,fittedMom)
1376 fittedtrackDir = fittedState.getDir()
1377 fittedx=math.degrees(math.acos(fittedtrackDir[0]))
1378 fittedy=math.degrees(math.acos(fittedtrackDir[1]))
1379 fittedz=math.degrees(math.acos(fittedtrackDir[2]))
1380 fittedmass = fittedState.getMass()
1381 rc=h['momentumfittedtracks'].Fill(fittedMom)
1382 rc=h['xdirectionfittedtracks'].Fill(fittedx)
1383 rc=h['ydirectionfittedtracks'].Fill(fittedy)
1384 rc=h['zdirectionfittedtracks'].Fill(fittedz)
1385 rc=h['massfittedtracks'].Fill(fittedmass)
1386
1387 return
1388

Variable Documentation

◆ cheated

int shipPatRec_prev.cheated = 0

Definition at line 36 of file shipPatRec_prev.py.

◆ falsenegative

int shipPatRec_prev.falsenegative = 0

Definition at line 32 of file shipPatRec_prev.py.

◆ falsepositive

int shipPatRec_prev.falsepositive = 0

Definition at line 33 of file shipPatRec_prev.py.

◆ fgeo

str shipPatRec_prev.fgeo = ''

Definition at line 42 of file shipPatRec_prev.py.

◆ fittedtrackids

list shipPatRec_prev.fittedtrackids = []

Definition at line 48 of file shipPatRec_prev.py.

◆ fitter

shipPatRec_prev.fitter = ROOT.genfit.DAF()

Definition at line 55 of file shipPatRec_prev.py.

◆ geoFile

str shipPatRec_prev.geoFile = ''

Definition at line 41 of file shipPatRec_prev.py.

◆ h

dict shipPatRec_prev.h = {}

Definition at line 57 of file shipPatRec_prev.py.

◆ i1

int shipPatRec_prev.i1 = 1

Definition at line 115 of file shipPatRec_prev.py.

◆ i2

int shipPatRec_prev.i2 = 16

Definition at line 116 of file shipPatRec_prev.py.

◆ MatchedReconstructibleMCTracks

list shipPatRec_prev.MatchedReconstructibleMCTracks = []

Definition at line 47 of file shipPatRec_prev.py.

◆ monitor

int shipPatRec_prev.monitor = 0

Definition at line 37 of file shipPatRec_prev.py.

◆ morethan100tracks

int shipPatRec_prev.morethan100tracks = 0

Definition at line 31 of file shipPatRec_prev.py.

◆ morethan500

int shipPatRec_prev.morethan500 = 0

Definition at line 30 of file shipPatRec_prev.py.

◆ particles

list shipPatRec_prev.particles = ["e-","e+","mu-","mu+","pi-","pi+","other"]

Definition at line 102 of file shipPatRec_prev.py.

◆ PDG

shipPatRec_prev.PDG = ROOT.TDatabasePDG.Instance()

Definition at line 54 of file shipPatRec_prev.py.

◆ printhelp

int shipPatRec_prev.printhelp = 0

Definition at line 38 of file shipPatRec_prev.py.

◆ random

shipPatRec_prev.random = ROOT.TRandom()

Definition at line 51 of file shipPatRec_prev.py.

◆ rc

dict shipPatRec_prev.rc = h['pinvvstruepinv'].SetMarkerStyle(8)

Definition at line 99 of file shipPatRec_prev.py.

◆ reconstructibleevents

int shipPatRec_prev.reconstructibleevents = 0

Definition at line 34 of file shipPatRec_prev.py.

◆ reconstructiblehorizontalidsfound12

int shipPatRec_prev.reconstructiblehorizontalidsfound12 = 0

Definition at line 24 of file shipPatRec_prev.py.

◆ reconstructiblehorizontalidsfound34

int shipPatRec_prev.reconstructiblehorizontalidsfound34 = 0

Definition at line 26 of file shipPatRec_prev.py.

◆ reconstructibleidsfound12

int shipPatRec_prev.reconstructibleidsfound12 = 0

Definition at line 28 of file shipPatRec_prev.py.

◆ reconstructibleidsfound34

int shipPatRec_prev.reconstructibleidsfound34 = 0

Definition at line 29 of file shipPatRec_prev.py.

◆ ReconstructibleMCTracks

list shipPatRec_prev.ReconstructibleMCTracks = []

Definition at line 46 of file shipPatRec_prev.py.

◆ reconstructiblerequired

int shipPatRec_prev.reconstructiblerequired = 2

Definition at line 39 of file shipPatRec_prev.py.

◆ reconstructiblestereoidsfound12

int shipPatRec_prev.reconstructiblestereoidsfound12 = 0

Definition at line 25 of file shipPatRec_prev.py.

◆ reconstructiblestereoidsfound34

int shipPatRec_prev.reconstructiblestereoidsfound34 = 0

Definition at line 27 of file shipPatRec_prev.py.

◆ theTracks

list shipPatRec_prev.theTracks = []

Definition at line 49 of file shipPatRec_prev.py.

◆ threeprong

int shipPatRec_prev.threeprong = 0

Definition at line 40 of file shipPatRec_prev.py.

◆ totalaftermatching

int shipPatRec_prev.totalaftermatching = 0

Definition at line 44 of file shipPatRec_prev.py.

◆ totalafterpatrec

int shipPatRec_prev.totalafterpatrec = 0

Definition at line 45 of file shipPatRec_prev.py.

◆ TStation1StartZ

int shipPatRec_prev.TStation1StartZ = 0.

Definition at line 121 of file shipPatRec_prev.py.

◆ TStation4EndZ

int shipPatRec_prev.TStation4EndZ = 0.

Definition at line 122 of file shipPatRec_prev.py.

◆ VetoStationEndZ

int shipPatRec_prev.VetoStationEndZ = 0.

Definition at line 124 of file shipPatRec_prev.py.

◆ VetoStationZ

int shipPatRec_prev.VetoStationZ = 0.

Definition at line 123 of file shipPatRec_prev.py.

◆ z34layer

dict shipPatRec_prev.z34layer = {}

Definition at line 119 of file shipPatRec_prev.py.

◆ z34layerv2

dict shipPatRec_prev.z34layerv2 = {}

Definition at line 120 of file shipPatRec_prev.py.

◆ zlayer

dict shipPatRec_prev.zlayer = {}

Definition at line 117 of file shipPatRec_prev.py.

◆ zlayerv2

dict shipPatRec_prev.zlayerv2 = {}

Definition at line 118 of file shipPatRec_prev.py.