Exemplo n.º 1
0
def EventLoop(SmearedHits):
    #loop over events
    for n in range(nEvents):
        fittedtrackids = []
        SmearedHits.Delete()
        fGenFitArray_PR.Delete()
        fitTrack2MC_PR.clear()
        fPartArray_PR.Delete()

        rc = sTree.GetEvent(n)

        if shipPatRec.monitor == True:
            shipPatRec.ReconstructibleMCTracks = shipPatRec.getReconstructibleTracks(
                n, sTree, sGeo)
            if len(shipPatRec.ReconstructibleMCTracks
                   ) != shipPatRec.reconstructiblerequired:
                if shipPatRec.debug == 1:
                    print("Number of reconstructible tracks =",
                          len(shipPatRec.ReconstructibleMCTracks),
                          "but number of reconstructible required=",
                          shipPatRec.reconstructiblerequired,
                          ". Rejecting event.")
                continue

            if shipPatRec.debug == 1:
                print("Reconstructible track ids",
                      shipPatRec.ReconstructibleMCTracks)

        #n = current event number, False=wire endpoints, True=MC truth

        SmearedHits = shipPatRec.SmearHits(n, sTree, modules, SmearedHits,
                                           shipPatRec.ReconstructibleMCTracks)

        fittedtrackids = shipPatRec.execute(n, SmearedHits, sTree,
                                            shipPatRec.ReconstructibleMCTracks)
        if fittedtrackids:
            tracknbr = 0
            for ids in fittedtrackids:
                nTrack = fGenFitArray_PR.GetEntries()
                fGenFitArray_PR[nTrack] = shipPatRec.theTracks[tracknbr]
                fitTrack2MC_PR.push_back(ids)
                tracknbr += 1

        Particles_PR.Fill()
        fitTracks_PR.Fill()
        mcLink_PR.Fill()
        SHbranch.Fill()

    if shipPatRec.debug == 1:
        print(shipPatRec.falsenegative,
              "matched tracks with wrong negative charge from deflection.")
        print(shipPatRec.falsepositive,
              "matched tracks with wrong positive charge from deflection.")
        print(shipPatRec.morethan500, "events with more than 500 hits.")
        print(shipPatRec.morethan100tracks,
              "events with more than 100 tracks.")

    return
Exemplo n.º 2
0
def EventLoop(SmearedHits):
 #loop over events
 for n in range(nEvents):
  fittedtrackids=[]
  SmearedHits.Delete()
  fGenFitArray_PR.Delete()
  fitTrack2MC_PR.clear()
  fPartArray_PR.Delete()
  
  rc = sTree.GetEvent(n)    
  
  if shipPatRec.monitor==True: 
     shipPatRec.ReconstructibleMCTracks=shipPatRec.getReconstructibleTracks(n,sTree,sGeo)
     if len(shipPatRec.ReconstructibleMCTracks)!=shipPatRec.reconstructiblerequired : 
        if shipPatRec.debug==1: print "Number of reconstructible tracks =",len(shipPatRec.ReconstructibleMCTracks),"but number of reconstructible required=",shipPatRec.reconstructiblerequired,". Rejecting event."
        continue

     if shipPatRec.debug==1: print "Reconstructible track ids",shipPatRec.ReconstructibleMCTracks
     
     
  #n = current event number, False=wire endpoints, True=MC truth
    
  SmearedHits  = shipPatRec.SmearHits(n,sTree,modules,SmearedHits,shipPatRec.ReconstructibleMCTracks)  

  fittedtrackids=shipPatRec.execute(n,SmearedHits,sTree,shipPatRec.ReconstructibleMCTracks)
  if fittedtrackids:
     tracknbr=0
     for ids in fittedtrackids:
	nTrack   = fGenFitArray_PR.GetEntries()
        fGenFitArray_PR[nTrack] = shipPatRec.theTracks[tracknbr]
        fitTrack2MC_PR.push_back(ids) 
	tracknbr+=1  
  
  Particles_PR.Fill()
  fitTracks_PR.Fill()
  mcLink_PR.Fill()    
  SHbranch.Fill()  
    
    
 if shipPatRec.debug==1: 
   print shipPatRec.falsenegative,"matched tracks with wrong negative charge from deflection."
   print shipPatRec.falsepositive,"matched tracks with wrong positive charge from deflection."
   print shipPatRec.morethan500,"events with more than 500 hits."  
   print shipPatRec.morethan100tracks,"events with more than 100 tracks." 
  
 return   
Exemplo n.º 3
0
 def execute(self,n):
  if n > self.nEvents-1: return None 
  rc    = self.sTree.GetEvent(n) 
  if n%1000==0: print "==> event ",n
  nShits = self.sTree.strawtubesPoint.GetEntriesFast() 
  hitPosLists    = {}
  stationCrossed = {}
  fittedtrackids=[]
  self.SmearedHits.Delete()
  self.fPartArray.Delete()
  self.fGenFitArray.Delete()
  self.fitTrack2MC.clear()
#   
  for i in range(nShits):
    ahit = self.sTree.strawtubesPoint.At(i)
    sm   = self.hit2wire(ahit,withNoStrawSmearing)
    m = array('d',[i,sm['xtop'],sm['ytop'],sm['z'],sm['xbot'],sm['ybot'],sm['z'],sm['dist'],ahit.GetDetectorID()])
    measurement = ROOT.TVectorD(9,m)
# copy to branch
    nHits = self.SmearedHits.GetEntries()
    if self.SmearedHits.GetSize() == nHits: self.SmearedHits.Expand(nHits+1000)
    self.SmearedHits[nHits] = measurement
    station = int(ahit.GetDetectorID()/10000000)
    if station > 4 : continue
    # do not use hits in Veto station for track reco   
    trID = ahit.GetTrackID()
    if not hitPosLists.has_key(trID):   
      hitPosLists[trID]     = ROOT.std.vector('TVectorD')()
      stationCrossed[trID]  = {}
    m = array('d',[sm['xtop'],sm['ytop'],sm['z'],sm['xbot'],sm['ybot'],sm['z'],sm['dist']])
    hitPosLists[trID].push_back(ROOT.TVectorD(7,m))
    if not stationCrossed[trID].has_key(station): stationCrossed[trID][station]=0
    stationCrossed[trID][station]+=1   
  nTrack = -1
  if realPR:
     fittedtrackids=shipPatRec.execute(n,self.SmearedHits,self.sTree,shipPatRec.ReconstructibleMCTracks)
     if fittedtrackids:
       tracknbr=0
       for ids in fittedtrackids:
	 nTrack   = SHiP.fGenFitArray.GetEntries()
         theTrack = shipPatRec.theTracks[tracknbr]
         if not debug: theTrack.prune("CFL")  #  http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280 
         self.fGenFitArray[nTrack] = theTrack
         self.fitTrack2MC.push_back(ids) 
	 tracknbr+=1
  else: # do fake pattern reco	 
   for atrack in hitPosLists:
    if atrack < 0: continue # these are hits not assigned to MC track because low E cut
    pdg    = self.sTree.MCTrack[atrack].GetPdgCode()
    if not PDG.GetParticle(pdg): continue # unknown particle
    meas = hitPosLists[atrack]
    nM = meas.size()
    if nM < 25 : continue                          # not enough hits to make a good trackfit 
    if len(stationCrossed[atrack]) < 3 : continue  # not enough stations crossed to make a good trackfit 
    if debug: 
       mctrack = self.sTree.MCTrack[atrack]
    charge = PDG.GetParticle(pdg).Charge()/(3.)
    posM = ROOT.TVector3(0, 0, 0)
    momM = ROOT.TVector3(0,0,3.*u.GeV)
# approximate covariance
    covM = ROOT.TMatrixDSym(6)
    resolution = ShipGeo.straw.resol
    for  i in range(3):   covM[i][i] = resolution*resolution
    covM[0][0]=resolution*resolution*100.
    for  i in range(3,6): covM[i][i] = ROOT.TMath.pow(resolution / nM / ROOT.TMath.sqrt(3), 2)
# trackrep
    rep = ROOT.genfit.RKTrackRep(pdg)
# smeared start state
    stateSmeared = ROOT.genfit.MeasuredStateOnPlane(rep)
    rep.setPosMomCov(stateSmeared, posM, momM, covM)
# create track
    seedState = ROOT.TVectorD(6)
    seedCov   = ROOT.TMatrixDSym(6)
    rep.get6DStateCov(stateSmeared, seedState, seedCov)
    theTrack = ROOT.genfit.Track(rep, seedState, seedCov)
    hitCov = ROOT.TMatrixDSym(7)
    hitCov[6][6] = resolution*resolution
    for m in meas:
      tp = ROOT.genfit.TrackPoint(theTrack) # note how the point is told which track it belongs to 
      measurement = ROOT.genfit.WireMeasurement(m,hitCov,1,6,tp) # the measurement is told which trackpoint it belongs to
      # print measurement.getMaxDistance()
      measurement.setMaxDistance(0.5*u.cm)
      # measurement.setLeftRightResolution(-1)
      tp.addRawMeasurement(measurement) # package measurement in the TrackPoint                                          
      theTrack.insertPoint(tp)  # add point to Track
   # print "debug meas",atrack,nM,stationCrossed[atrack],self.sTree.MCTrack[atrack],pdg
#check
    if not theTrack.checkConsistency():
     print 'Problem with track before fit, not consistent',atrack,theTrack
     continue
# do the fit
    try:  fitter.processTrack(theTrack) # processTrackWithRep(theTrack,rep,True)
    except: 
       print "genfit failed to fit track"
       continue
#check
    if not theTrack.checkConsistency():
     print 'Problem with track after fit, not consistent',atrack,theTrack
     continue
    fitStatus   = theTrack.getFitStatus()
    nmeas = fitStatus.getNdf()   
    chi2        = fitStatus.getChi2()/nmeas   
    h['chi2'].Fill(chi2)
# make track persistent
    nTrack   = SHiP.fGenFitArray.GetEntries()
    if not debug: theTrack.prune("CFL")  #  http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280 
    self.fGenFitArray[nTrack] = theTrack
    self.fitTrack2MC.push_back(atrack)
    if debug: 
     print 'save track',theTrack,chi2,nM,fitStatus.isFitConverged()
  return nTrack+1
Exemplo n.º 4
0
    def findTracks(self):
        hitPosLists = {}
        stationCrossed = {}
        fittedtrackids = []
        self.fGenFitArray.Delete()
        self.fitTrack2MC.clear()
        #
        if withT0:
            self.SmearedHits = self.withT0Estimate()
            # old procedure, not including estimation of t0
        else:
            self.SmearedHits = self.smearHits(withNoStrawSmearing)

        nTrack = -1
        trackCandidates = []
        if realPR:
            fittedtrackids = shipPatRec.execute(
                self.SmearedHits, self.sTree,
                shipPatRec.ReconstructibleMCTracks)
            if fittedtrackids:
                tracknbr = 0
                for ids in fittedtrackids:
                    trackCandidates.append(
                        [shipPatRec.theTracks[tracknbr], ids])
                    tracknbr += 1
        else:  # do fake pattern reco
            for sm in self.SmearedHits:
                detID = self.digiStraw[sm['digiHit']].GetDetectorID()
                station = int(detID / 10000000)
                trID = self.sTree.strawtubesPoint[sm['digiHit']].GetTrackID()
                if not hitPosLists.has_key(trID):
                    hitPosLists[trID] = ROOT.std.vector('TVectorD')()
                    stationCrossed[trID] = {}
                m = array('d', [
                    sm['xtop'], sm['ytop'], sm['z'], sm['xbot'], sm['ybot'],
                    sm['z'], sm['dist']
                ])
                hitPosLists[trID].push_back(ROOT.TVectorD(7, m))
                if not stationCrossed[trID].has_key(station):
                    stationCrossed[trID][station] = 0
                stationCrossed[trID][station] += 1
            for atrack in hitPosLists:
                if atrack < 0:
                    continue  # these are hits not assigned to MC track because low E cut
                pdg = self.sTree.MCTrack[atrack].GetPdgCode()
                if not self.PDG.GetParticle(pdg): continue  # unknown particle
                meas = hitPosLists[atrack]
                nM = meas.size()
                if nM < 25: continue  # not enough hits to make a good trackfit
                if len(stationCrossed[atrack]) < 3:
                    continue  # not enough stations crossed to make a good trackfit
                if debug:
                    mctrack = self.sTree.MCTrack[atrack]
                charge = self.PDG.GetParticle(pdg).Charge() / (3.)
                posM = ROOT.TVector3(0, 0, 0)
                momM = ROOT.TVector3(0, 0, 3. * u.GeV)
                # approximate covariance
                covM = ROOT.TMatrixDSym(6)
                resolution = self.sigma_spatial
                if withT0:
                    resolution = resolution * 1.4  # worse resolution due to t0 estimate
                for i in range(3):
                    covM[i][i] = resolution * resolution
                covM[0][0] = resolution * resolution * 100.
                for i in range(3, 6):
                    covM[i][i] = ROOT.TMath.Power(
                        resolution / nM / ROOT.TMath.Sqrt(3), 2)
                # trackrep
                rep = ROOT.genfit.RKTrackRep(pdg)
                # smeared start state
                stateSmeared = ROOT.genfit.MeasuredStateOnPlane(rep)
                rep.setPosMomCov(stateSmeared, posM, momM, covM)
                # create track
                seedState = ROOT.TVectorD(6)
                seedCov = ROOT.TMatrixDSym(6)
                rep.get6DStateCov(stateSmeared, seedState, seedCov)
                theTrack = ROOT.genfit.Track(rep, seedState, seedCov)
                hitCov = ROOT.TMatrixDSym(7)
                hitCov[6][6] = resolution * resolution
                for m in meas:
                    tp = ROOT.genfit.TrackPoint(
                        theTrack
                    )  # note how the point is told which track it belongs to
                    measurement = ROOT.genfit.WireMeasurement(
                        m, hitCov, 1, 6, tp
                    )  # the measurement is told which trackpoint it belongs to
                    # print measurement.getMaxDistance()
                    measurement.setMaxDistance(0.5 * u.cm)
                    # measurement.setLeftRightResolution(-1)
                    tp.addRawMeasurement(
                        measurement)  # package measurement in the TrackPoint
                    theTrack.insertPoint(tp)  # add point to Track
            # print "debug meas",atrack,nM,stationCrossed[atrack],self.sTree.MCTrack[atrack],pdg
                trackCandidates.append([theTrack, atrack])
        for entry in trackCandidates:
            #check
            atrack = entry[1]
            theTrack = entry[0]
            if not theTrack.checkConsistency():
                print 'Problem with track before fit, not consistent', atrack, theTrack
                continue
# do the fit
            try:
                self.fitter.processTrack(
                    theTrack)  # processTrackWithRep(theTrack,rep,True)
            except:
                if debug: print "genfit failed to fit track"
                error = "genfit failed to fit track"
                ut.reportError(error)
                continue


#check
            if not theTrack.checkConsistency():
                if debug:
                    print 'Problem with track after fit, not consistent', atrack, theTrack
                error = "Problem with track after fit, not consistent"
                ut.reportError(error)
                continue
            fitStatus = theTrack.getFitStatus()
            nmeas = fitStatus.getNdf()
            chi2 = fitStatus.getChi2() / nmeas
            h['chi2'].Fill(chi2)
            # make track persistent
            nTrack = self.fGenFitArray.GetEntries()
            if not debug:
                theTrack.prune(
                    "CFL"
                )  #  http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280
            self.fGenFitArray[nTrack] = theTrack
            self.fitTrack2MC.push_back(atrack)
            if debug:
                print 'save track', theTrack, chi2, nmeas, fitStatus.isFitConverged(
                )
        self.fitTracks.Fill()
        self.mcLink.Fill()
        return nTrack + 1
Exemplo n.º 5
0
 def findTracks(self):
  hitPosLists    = {}
  stationCrossed = {}
  fittedtrackids=[]
  self.fGenFitArray.Delete()
  self.fitTrack2MC.clear()
#   
  if withT0:  self.SmearedHits = self.withT0Estimate()
  # old procedure, not including estimation of t0 
  else:       self.SmearedHits = self.smearHits(withNoStrawSmearing)

  nTrack = -1
  trackCandidates = []
  if realPR:
     fittedtrackids=shipPatRec.execute(self.SmearedHits,self.sTree,shipPatRec.ReconstructibleMCTracks)
     if fittedtrackids:
       tracknbr=0
       for ids in fittedtrackids:
         trackCandidates.append( [shipPatRec.theTracks[tracknbr],ids] )
	 tracknbr+=1
  else: # do fake pattern reco	 
   for sm in self.SmearedHits:
    detID = self.digiStraw[sm['digiHit']].GetDetectorID()
    station = int(detID/10000000)
    trID = self.sTree.strawtubesPoint[sm['digiHit']].GetTrackID()
    if not hitPosLists.has_key(trID):   
      hitPosLists[trID]     = ROOT.std.vector('TVectorD')()
      stationCrossed[trID]  = {}
    m = array('d',[sm['xtop'],sm['ytop'],sm['z'],sm['xbot'],sm['ybot'],sm['z'],sm['dist']])
    hitPosLists[trID].push_back(ROOT.TVectorD(7,m))
    if not stationCrossed[trID].has_key(station): stationCrossed[trID][station]=0
    stationCrossed[trID][station]+=1   
   for atrack in hitPosLists:
    if atrack < 0: continue # these are hits not assigned to MC track because low E cut
    pdg    = self.sTree.MCTrack[atrack].GetPdgCode()
    if not self.PDG.GetParticle(pdg): continue # unknown particle
    meas = hitPosLists[atrack]
    nM = meas.size()
    if nM < 25 : continue                          # not enough hits to make a good trackfit 
    if len(stationCrossed[atrack]) < 3 : continue  # not enough stations crossed to make a good trackfit 
    if debug: 
       mctrack = self.sTree.MCTrack[atrack]
    charge = self.PDG.GetParticle(pdg).Charge()/(3.)
    posM = ROOT.TVector3(0, 0, 0)
    momM = ROOT.TVector3(0,0,3.*u.GeV)
# approximate covariance
    covM = ROOT.TMatrixDSym(6)
    resolution = self.sigma_spatial
    if withT0: resolution = resolution*1.4 # worse resolution due to t0 estimate
    for  i in range(3):   covM[i][i] = resolution*resolution
    covM[0][0]=resolution*resolution*100.
    for  i in range(3,6): covM[i][i] = ROOT.TMath.Power(resolution / nM / ROOT.TMath.Sqrt(3), 2)
# trackrep
    rep = ROOT.genfit.RKTrackRep(pdg)
# smeared start state
    stateSmeared = ROOT.genfit.MeasuredStateOnPlane(rep)
    rep.setPosMomCov(stateSmeared, posM, momM, covM)
# create track
    seedState = ROOT.TVectorD(6)
    seedCov   = ROOT.TMatrixDSym(6)
    rep.get6DStateCov(stateSmeared, seedState, seedCov)
    theTrack = ROOT.genfit.Track(rep, seedState, seedCov)
    hitCov = ROOT.TMatrixDSym(7)
    hitCov[6][6] = resolution*resolution
    for m in meas:
      tp = ROOT.genfit.TrackPoint(theTrack) # note how the point is told which track it belongs to 
      measurement = ROOT.genfit.WireMeasurement(m,hitCov,1,6,tp) # the measurement is told which trackpoint it belongs to
      # print measurement.getMaxDistance()
      measurement.setMaxDistance(0.5*u.cm)
      # measurement.setLeftRightResolution(-1)
      tp.addRawMeasurement(measurement) # package measurement in the TrackPoint                                          
      theTrack.insertPoint(tp)  # add point to Track
   # print "debug meas",atrack,nM,stationCrossed[atrack],self.sTree.MCTrack[atrack],pdg
    trackCandidates.append([theTrack,atrack])
  for entry in trackCandidates:
#check
    atrack = entry[1]
    theTrack = entry[0]
    if not theTrack.checkConsistency():
     print 'Problem with track before fit, not consistent',atrack,theTrack
     continue
# do the fit
    try:  self.fitter.processTrack(theTrack) # processTrackWithRep(theTrack,rep,True)
    except: 
       print "genfit failed to fit track"
       continue
#check
    if not theTrack.checkConsistency():
     print 'Problem with track after fit, not consistent',atrack,theTrack
     continue
    fitStatus   = theTrack.getFitStatus()
    nmeas = fitStatus.getNdf()   
    chi2        = fitStatus.getChi2()/nmeas   
    h['chi2'].Fill(chi2)
# make track persistent
    nTrack   = self.fGenFitArray.GetEntries()
    if not debug: theTrack.prune("CFL")  #  http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280 
    self.fGenFitArray[nTrack] = theTrack
    self.fitTrack2MC.push_back(atrack)
    if debug: 
     print 'save track',theTrack,chi2,nM,fitStatus.isFitConverged()
  self.fitTracks.Fill()
  self.mcLink.Fill()
  return nTrack+1
Exemplo n.º 6
0
    def findTracks(self, n):
        if n > self.nEvents - 1: return None
        rc = self.sTree.GetEvent(n)
        if n % 1000 == 0: print "==> event ", n
        nShits = self.sTree.strawtubesPoint.GetEntriesFast()
        hitPosLists = {}
        stationCrossed = {}
        fittedtrackids = []
        self.SmearedHits.Delete()
        self.fGenFitArray.Delete()
        self.fitTrack2MC.clear()
        #
        for i in range(nShits):
            ahit = self.sTree.strawtubesPoint.At(i)
            sm = self.hit2wire(ahit, withNoStrawSmearing)
            m = array('d', [
                i, sm['xtop'], sm['ytop'], sm['z'], sm['xbot'], sm['ybot'],
                sm['z'], sm['dist'],
                ahit.GetDetectorID()
            ])
            measurement = ROOT.TVectorD(9, m)
            # copy to branch
            nHits = self.SmearedHits.GetEntries()
            if self.SmearedHits.GetSize() == nHits:
                self.SmearedHits.Expand(nHits + 1000)
            self.SmearedHits[nHits] = measurement
            station = int(ahit.GetDetectorID() / 10000000)
            if station > 4: continue
            # do not use hits in Veto station for track reco
            trID = ahit.GetTrackID()
            if not hitPosLists.has_key(trID):
                hitPosLists[trID] = ROOT.std.vector('TVectorD')()
                stationCrossed[trID] = {}
            m = array('d', [
                sm['xtop'], sm['ytop'], sm['z'], sm['xbot'], sm['ybot'],
                sm['z'], sm['dist']
            ])
            hitPosLists[trID].push_back(ROOT.TVectorD(7, m))
            if not stationCrossed[trID].has_key(station):
                stationCrossed[trID][station] = 0
            stationCrossed[trID][station] += 1
        nTrack = -1
        if realPR:
            fittedtrackids = shipPatRec.execute(
                n, self.SmearedHits, self.sTree,
                shipPatRec.ReconstructibleMCTracks)
            if fittedtrackids:
                tracknbr = 0
                for ids in fittedtrackids:
                    nTrack = SHiP.fGenFitArray.GetEntries()
                    theTrack = shipPatRec.theTracks[tracknbr]
                    if not debug:
                        theTrack.prune(
                            "CFL"
                        )  #  http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280
                    self.fGenFitArray[nTrack] = theTrack
                    self.fitTrack2MC.push_back(ids)
                    tracknbr += 1
        else:  # do fake pattern reco
            for atrack in hitPosLists:
                if atrack < 0:
                    continue  # these are hits not assigned to MC track because low E cut
                pdg = self.sTree.MCTrack[atrack].GetPdgCode()
                if not PDG.GetParticle(pdg): continue  # unknown particle
                meas = hitPosLists[atrack]
                nM = meas.size()
                if nM < 25: continue  # not enough hits to make a good trackfit
                if len(stationCrossed[atrack]) < 3:
                    continue  # not enough stations crossed to make a good trackfit
                if debug:
                    mctrack = self.sTree.MCTrack[atrack]
                charge = PDG.GetParticle(pdg).Charge() / (3.)
                posM = ROOT.TVector3(0, 0, 0)
                momM = ROOT.TVector3(0, 0, 3. * u.GeV)
                # approximate covariance
                covM = ROOT.TMatrixDSym(6)
                resolution = ShipGeo.straw.resol
                for i in range(3):
                    covM[i][i] = resolution * resolution
                covM[0][0] = resolution * resolution * 100.
                for i in range(3, 6):
                    covM[i][i] = ROOT.TMath.Power(
                        resolution / nM / ROOT.TMath.Sqrt(3), 2)
                # trackrep
                rep = ROOT.genfit.RKTrackRep(pdg)
                # smeared start state
                stateSmeared = ROOT.genfit.MeasuredStateOnPlane(rep)
                rep.setPosMomCov(stateSmeared, posM, momM, covM)
                # create track
                seedState = ROOT.TVectorD(6)
                seedCov = ROOT.TMatrixDSym(6)
                rep.get6DStateCov(stateSmeared, seedState, seedCov)
                theTrack = ROOT.genfit.Track(rep, seedState, seedCov)
                hitCov = ROOT.TMatrixDSym(7)
                hitCov[6][6] = resolution * resolution
                for m in meas:
                    tp = ROOT.genfit.TrackPoint(
                        theTrack
                    )  # note how the point is told which track it belongs to
                    measurement = ROOT.genfit.WireMeasurement(
                        m, hitCov, 1, 6, tp
                    )  # the measurement is told which trackpoint it belongs to
                    # print measurement.getMaxDistance()
                    measurement.setMaxDistance(0.5 * u.cm)
                    # measurement.setLeftRightResolution(-1)
                    tp.addRawMeasurement(
                        measurement)  # package measurement in the TrackPoint
                    theTrack.insertPoint(tp)  # add point to Track
            # print "debug meas",atrack,nM,stationCrossed[atrack],self.sTree.MCTrack[atrack],pdg
#check
                if not theTrack.checkConsistency():
                    print 'Problem with track before fit, not consistent', atrack, theTrack
                    continue
# do the fit
                try:
                    fitter.processTrack(
                        theTrack)  # processTrackWithRep(theTrack,rep,True)
                except:
                    print "genfit failed to fit track"
                    continue
#check
                if not theTrack.checkConsistency():
                    print 'Problem with track after fit, not consistent', atrack, theTrack
                    continue
                fitStatus = theTrack.getFitStatus()
                nmeas = fitStatus.getNdf()
                chi2 = fitStatus.getChi2() / nmeas
                h['chi2'].Fill(chi2)
                # make track persistent
                nTrack = SHiP.fGenFitArray.GetEntries()
                if not debug:
                    theTrack.prune(
                        "CFL"
                    )  #  http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280
                self.fGenFitArray[nTrack] = theTrack
                self.fitTrack2MC.push_back(atrack)
                if debug:
                    print 'save track', theTrack, chi2, nM, fitStatus.isFitConverged(
                    )
        self.fitTracks.Fill()
        self.mcLink.Fill()
        self.SHbranch.Fill()
        return nTrack + 1
Exemplo n.º 7
0
 def findTracks(self):
  hitPosLists    = {}
  hitPosLists_noT4    = {}
  stationCrossed = {}
  stationCrossed_noT4 = {}
  fittedtrackids=[]
  self.fGenFitArray.Delete()
  self.fitTrack2MC.clear()
#   
  if withT0:  self.SmearedHits = self.withT0Estimate()
  # old procedure, not including estimation of t0 
  else:       self.SmearedHits = self.smearHits(withNoStrawSmearing)

  nTrack = -1
  trackCandidates = []
  trackCandidates_noT4 = []
  if realPR:
     fittedtrackids=shipPatRec.execute(self.SmearedHits,self.sTree,shipPatRec.ReconstructibleMCTracks)
     if fittedtrackids:
       tracknbr=0
       for ids in fittedtrackids:
         trackCandidates.append( [shipPatRec.theTracks[tracknbr],ids] )
	 tracknbr+=1
  else: # do fake pattern reco	 
   for sm in self.SmearedHits:
    detID = self.digiMufluxSpectrometer[sm['digiHit']].GetDetectorID()
    station = int(detID/10000000)

    trID = self.sTree.MufluxSpectrometerPoint[sm['digiHit']].GetTrackID()
    if not hitPosLists.has_key(trID):   
      hitPosLists[trID]     = ROOT.std.vector('TVectorD')()
      stationCrossed[trID]  = {}
    m = array('d',[sm['xtop'],sm['ytop'],sm['z'],sm['xbot'],sm['ybot'],sm['z'],sm['dist']])
    hitPosLists[trID].push_back(ROOT.TVectorD(7,m))
    if (int(detID/1000000)!=40): 
       if not hitPosLists_noT4.has_key(trID):   
          hitPosLists_noT4[trID]     = ROOT.std.vector('TVectorD')()
          stationCrossed_noT4[trID]  = {}	  
       m_noT4 = array('d',[sm['xtop'],sm['ytop'],sm['z'],sm['xbot'],sm['ybot'],sm['z'],sm['dist']])             
       hitPosLists_noT4[trID].push_back(ROOT.TVectorD(7,m_noT4))
       if not stationCrossed_noT4[trID].has_key(station): stationCrossed_noT4[trID][station]=0
       stationCrossed_noT4[trID][station]+=1         
    # comment next 3 lines for hits in t1-3
    #print "debug detid ",detID," m ",m
    if not stationCrossed[trID].has_key(station): stationCrossed[trID][station]=0
    stationCrossed[trID][station]+=1    
       
     
    #uncomment next 4 lines for hits in t1-3    
    #if station<4 : 
    #   hitPosLists[trID].push_back(ROOT.TVectorD(7,m))    
    #   if not stationCrossed[trID].has_key(station): stationCrossed[trID][station]=0
    #   stationCrossed[trID][station]+=1   
       
   for atrack in hitPosLists:
    if atrack < 0: continue # these are hits not assigned to MC track because low E cut
    pdg    = self.sTree.MCTrack[atrack].GetPdgCode()
    #if not self.PDG.GetParticle(pdg): continue # unknown particle
    if not abs(pdg)==13: continue # only keep muons
    meas = hitPosLists[atrack]
    nM = meas.size()

    #if nM < 12 : continue                          # not enough hits to make a good trackfit 
    #comment for hits in t1-3
    if len(stationCrossed[atrack]) < 4 : continue  # not enough stations crossed to make a good trackfit 
    
    #uncomment for hits in t1-3
    #if len(stationCrossed[atrack]) < 3 : continue  # not enough stations crossed to make a good trackfit 
    if debug: 
       mctrack = self.sTree.MCTrack[atrack]
    charge = self.PDG.GetParticle(pdg).Charge()/(3.)
    posM = ROOT.TVector3(0, 0, 0)
    momM = ROOT.TVector3(0,0,3.*u.GeV)
# approximate covariance
    covM = ROOT.TMatrixDSym(6)
    resolution = self.sigma_spatial
    if withT0: resolution = resolution*1.4 # worse resolution due to t0 estimate
    for  i in range(3):   covM[i][i] = resolution*resolution
    covM[0][0]=resolution*resolution*100.
    for  i in range(3,6): covM[i][i] = ROOT.TMath.Power(resolution / nM / ROOT.TMath.Sqrt(3), 2)
# trackrep
    rep = ROOT.genfit.RKTrackRep(pdg)
# smeared start state
    stateSmeared = ROOT.genfit.MeasuredStateOnPlane(rep)
    rep.setPosMomCov(stateSmeared, posM, momM, covM)
# create track
    seedState = ROOT.TVectorD(6)
    seedCov   = ROOT.TMatrixDSym(6)
    rep.get6DStateCov(stateSmeared, seedState, seedCov)
    theTrack = ROOT.genfit.Track(rep, seedState, seedCov)
    hitCov = ROOT.TMatrixDSym(7)
    hitCov[6][6] = resolution*resolution
    for m in meas:
      tp = ROOT.genfit.TrackPoint(theTrack) # note how the point is told which track it belongs to 
      measurement = ROOT.genfit.WireMeasurement(m,hitCov,1,6,tp) # the measurement is told which trackpoint it belongs to
      # print measurement.getMaxDistance()
      #measurement.setMaxDistance(0.5*u.cm)
      measurement.setMaxDistance(1.85*u.cm)
      # measurement.setLeftRightResolution(-1)
      tp.addRawMeasurement(measurement) # package measurement in the TrackPoint                                          
      theTrack.insertPoint(tp)  # add point to Track
   # print "debug meas",atrack,nM,stationCrossed[atrack],self.sTree.MCTrack[atrack],pdg
    trackCandidates.append([theTrack,atrack])
    
   #if 1==0:
  for atrack in hitPosLists_noT4:
    if atrack < 0: continue # these are hits not assigned to MC track because low E cut
    pdg    = self.sTree.MCTrack[atrack].GetPdgCode()
    #if not self.PDG.GetParticle(pdg): continue # unknown particle
    if not abs(pdg)==13: continue # only keep muons
    meas = hitPosLists_noT4[atrack]
    nM = meas.size()

    #if nM < 6 : continue                          # not enough hits to make a good trackfit 
    #comment for hits in t1-3

    #if len(stationCrossed_noT4[atrack]) < 4 : continue  # not enough stations crossed to make a good trackfit 
    
    #uncomment for hits in t1-3
    if len(stationCrossed[atrack]) < 3 : continue  # not enough stations crossed to make a good trackfit 
    if debug: 
       mctrack = self.sTree.MCTrack[atrack]
    charge = self.PDG.GetParticle(pdg).Charge()/(3.)
    posM = ROOT.TVector3(0, 0, 0)
    momM = ROOT.TVector3(0,0,3.*u.GeV)
# approximate covariance
    covM = ROOT.TMatrixDSym(6)
    resolution = self.sigma_spatial
    if withT0: resolution = resolution*1.4 # worse resolution due to t0 estimate
    for  i in range(3):   covM[i][i] = resolution*resolution
    covM[0][0]=resolution*resolution*100.
    for  i in range(3,6): covM[i][i] = ROOT.TMath.Power(resolution / nM / ROOT.TMath.Sqrt(3), 2)
# trackrep
    rep = ROOT.genfit.RKTrackRep(pdg)
# smeared start state
    stateSmeared = ROOT.genfit.MeasuredStateOnPlane(rep)
    rep.setPosMomCov(stateSmeared, posM, momM, covM)
# create track
    seedState = ROOT.TVectorD(6)
    seedCov   = ROOT.TMatrixDSym(6)
    rep.get6DStateCov(stateSmeared, seedState, seedCov)
    theTrack = ROOT.genfit.Track(rep, seedState, seedCov)
    hitCov = ROOT.TMatrixDSym(7)
    hitCov[6][6] = resolution*resolution
    for m in meas:
      tp = ROOT.genfit.TrackPoint(theTrack) # note how the point is told which track it belongs to 
      measurement = ROOT.genfit.WireMeasurement(m,hitCov,1,6,tp) # the measurement is told which trackpoint it belongs to
      # print measurement.getMaxDistance()
      #measurement.setMaxDistance(0.5*u.cm)
      measurement.setMaxDistance(1.85*u.cm)
      # measurement.setLeftRightResolution(-1)
      tp.addRawMeasurement(measurement) # package measurement in the TrackPoint                                          
      theTrack.insertPoint(tp)  # add point to Track
      #print "debug meas",atrack,nM,stationCrossed[atrack],self.sTree.MCTrack[atrack],pdg
    trackCandidates_noT4.append([theTrack,atrack])
  #print len(trackCandidates)," trackCandidates ",len(trackCandidates_noT4)," trackCandidates_noT4)"
  
  for entry in trackCandidates:
#check
    #print "fitting with stereo"
    atrack = entry[1]
    theTrack = entry[0]
    if not theTrack.checkConsistency():
     print 'Problem with track before fit, not consistent',atrack,theTrack
     continue
# do the fit
    try:  self.fitter.processTrack(theTrack) # processTrackWithRep(theTrack,rep,True)
    except: 
       print "genfit failed to fit track"
       continue
#check
    if not theTrack.checkConsistency():
     #print 'Problem with track after fit, not consistent',atrack,theTrack
     continue
    fitStatus   = theTrack.getFitStatus()
    nmeas = fitStatus.getNdf()   
    chi2        = fitStatus.getChi2()/nmeas  
    pvalue = fitStatus.getPVal()
    #if pvalue < 0.05:
    #  print "P value too low. Rejecting track."
    #  continue
    h['nmeas'].Fill(nmeas)    
    h['chi2'].Fill(chi2)
    h['p-value'].Fill(pvalue)
    try:

      fittedState = theTrack.getFittedState()
      fittedMom = fittedState.getMomMag()
      h['p-fittedtracks'].Fill(fittedMom)
      h['1/p-fittedtracks'].Fill(1./fittedMom)
      Px,Py,Pz = fittedState.getMom().x(),fittedState.getMom().y(),fittedState.getMom().z()
      P = fittedMom
      Ptruth,Ptruthx,Ptruthy,Ptruthz = self.getPtruthFirst(atrack)
      Pgun,Pgunx,Pguny,Pgunz = self.getPtruthAtOrigin(atrack)
      if Pz !=0: 
        pxpzfitted = Px/Pz
        pypzfitted = Py/Pz	
	if Ptruthz !=0:
          pxpztrue = Ptruthx/Ptruthz
          pypztrue = Ptruthy/Ptruthz	  
	  h['Px/Pzfitted'].Fill(pxpzfitted)
          h['Py/Pzfitted'].Fill(pypzfitted)
	  h['Px/Pztrue'].Fill(pxpztrue)
          h['Py/Pztrue'].Fill(pypztrue)		
          h['Px/Pzfitted-Px/Pztruth'].Fill(Ptruth,pxpzfitted-pxpztrue)
          h['Py/Pzfitted-Py/Pztruth'].Fill(Ptruth,pypzfitted-pypztrue)	  
      h['ptruth'].Fill(Ptruth)  
      delPOverP = (P/Ptruth)-1
      invdelPOverP = (Ptruth/P)-1
      if 1==0:
       if invdelPOverP < -0.8:
         print "invdelPOverP = ",invdelPOverP
         print "Ptruth =",Ptruth," Pfitted =",P
	 for n in range(hitPosLists[atrack].size()):	 
	    print "hit=",n," x(top) ",hitPosLists[atrack][n][0]," y(top) ",hitPosLists[atrack][n][1]," z ",hitPosLists[atrack][n][2]," x(bot) ",hitPosLists[atrack][n][3]," y(bot) ", hitPosLists[atrack][n][4], " dist ", hitPosLists[atrack][n][6]            
            nMufluxHits = self.sTree.MufluxSpectrometerPoint.GetEntriesFast()    
            for i in range(nMufluxHits):
              MufluxHit = self.sTree.MufluxSpectrometerPoint[i]
	      if ((hitPosLists[atrack][n][0]+1.8 > MufluxHit.GetX()) or(hitPosLists[atrack][n][3]+1.8 > MufluxHit.GetX())) and ((hitPosLists[atrack][n][0]-1.8<MufluxHit.GetX()) or (hitPosLists[atrack][n][3]-1.8<MufluxHit.GetX())) and (hitPosLists[atrack][n][2]+1.>MufluxHit.GetZ()) and (hitPosLists[atrack][n][2]-1.<MufluxHit.GetZ()):
	        print "hit x=",MufluxHit.GetX()," y=",MufluxHit.GetY()," z=",MufluxHit.GetZ()
     
     
      h['delPOverP'].Fill(Ptruth,delPOverP)  
      h['invdelPOverP'].Fill(Ptruth,invdelPOverP)  
      h['deltaPOverP'].Fill(Ptruth,delPOverP)   
      h['Pfitted-Pgun'].Fill(Pgun,P)  
      #print "end fitting with stereo"
        
    except: 
       print "problem with fittedstate"
       continue    

   #if 1==0:
  for entry in trackCandidates_noT4:
#check
    #print "fitting without stereo hits"
    atrack = entry[1]
    theTrack = entry[0]
    if not theTrack.checkConsistency():
     print 'Problem with track before fit, not consistent',atrack,theTrack
     continue
# do the fit
    try:  self.fitter.processTrack(theTrack) # processTrackWithRep(theTrack,rep,True)
    except: 
       print "genfit failed to fit track"
       continue
#check
    if not theTrack.checkConsistency():
     print 'Problem with track after fit, not consistent',atrack,theTrack
     continue
    fitStatus   = theTrack.getFitStatus()
    nmeas = fitStatus.getNdf()   
    chi2        = fitStatus.getChi2()/nmeas  
    pvalue = fitStatus.getPVal()
    #if pvalue < 0.05:
    #  print "P value too low. Rejecting track."
    #  continue
    h['nmeas-noT4'].Fill(nmeas)    
    h['chi2-noT4'].Fill(chi2)
    h['p-value-noT4'].Fill(pvalue)
    try:

      fittedState = theTrack.getFittedState()
      fittedMom = fittedState.getMomMag()
      h['p-fittedtracks-noT4'].Fill(fittedMom)
      h['1/p-fittedtracks-noT4'].Fill(1./fittedMom)
      Px,Py,Pz = fittedState.getMom().x(),fittedState.getMom().y(),fittedState.getMom().z()
      P = fittedMom
      Ptruth,Ptruthx,Ptruthy,Ptruthz = self.getPtruthFirst(atrack)
      Pgun,Pgunx,Pguny,Pgunz = self.getPtruthAtOrigin(atrack)     
      if Pz !=0: 
        pxpzfitted = Px/Pz
        pypzfitted = Py/Pz	
	if Ptruthz !=0:
          pxpztrue = Ptruthx/Ptruthz
          pypztrue = Ptruthy/Ptruthz	  
          h['Px/Pzfitted-Px/Pztruth-noT4'].Fill(Ptruth,pxpzfitted-pxpztrue)
          h['Py/Pzfitted-Py/Pztruth-noT4'].Fill(Ptruth,pypzfitted-pypztrue)	       
	  h['Px/Pzfitted-noT4'].Fill(pxpzfitted)
          h['Py/Pzfitted-noT4'].Fill(pypzfitted)
	  h['Px/Pztrue-noT4'].Fill(pxpztrue)
          h['Py/Pztrue-noT4'].Fill(pypztrue)      
      
      h['ptruth-noT4'].Fill(Ptruth) 
      delPOverP = (P/Ptruth)-1
      invdelPOverP = (Ptruth/P)-1
      h['delPOverP-noT4'].Fill(Ptruth,delPOverP) 
      h['invdelPOverP-noT4'].Fill(Ptruth,invdelPOverP)    
      h['deltaPOverP-noT4'].Fill(Ptruth,delPOverP)    
      h['Pfitted-Pgun-noT4'].Fill(Pgun,P)  
      #print "end fitting without stereo hits"        
    except: 
       print "noT4 track: problem with fittedstate"
       continue           
      
# make track persistent
    nTrack   = self.fGenFitArray.GetEntries()
    if not debug: theTrack.prune("CFL")  #  http://sourceforge.net/p/genfit/code/HEAD/tree/trunk/core/include/Track.h#l280 
    self.fGenFitArray[nTrack] = theTrack
    self.fitTrack2MC.push_back(atrack)
    if debug: 
        print 'save track',theTrack,chi2,nM,fitStatus.isFitConverged()
  self.fitTracks.Fill()
  self.mcLink.Fill()
  return nTrack+1