def idleLoop(): """Watches user input, next, quit or picking""" text = "event " + str(g.event.getEventNumber()) + " " + str( g.event.getRunNumber()) text = text + " - hit enter to draw next - [q] to quit - double click on objects for picking" # input loop (keyboard or mouse) print text while True: i, o, e = select.select([sys.stdin], [], [], 0.5) if (i): c = sys.stdin.readline().strip() else: c = -1 if (c == 'q' or c == ''): break if (c != -1): print text pid = g.ced.ced_selected_id_noblock() if pid != -1: print ' picked object with Id: ', pid if (pid in g.objects): print UTIL.toString(g.objects[pid]) return c
def readEvent(self): runNumber = self._lcioReader.getNumberOfRuns() try: self._event = self._lcioReader.next() except: return None evtNum = self._event.getEventNumber() pfoTargetCandidates = [] hits = self._event.getCollection('SDHcalCollection') nHits = hits.getNumberOfElements() cellIdEncoding = hits.getParameters().getStringVal( EVENT.LCIO.CellIDEncoding ) idDecoder = UTIL.BitField64( cellIdEncoding ) print 'Event : ', evtNum, ', # of SDHCAL hits: ', nHits hitsLayer = [] for iHit in range(0, nHits): hit = hits.getElementAt( iHit ) cellID = long( hit.getCellID0() & 0xffffffff ) | ( long( hit.getCellID1() ) << 32 ) idDecoder.setValue( cellID ) layer = int( idDecoder['K'].value() ) hitsLayer.append( layer ) #print 'hit layer: %d' % (layer) return self._event, hitsLayer
def readEvent(): for event in reader: allHitPos = [] hcalHits = event.getCollection('HCALOther') evtNum = event.getEventNumber() nHit = hcalHits.getNumberOfElements() cellIdEncoding = hcalHits.getParameters().getStringVal( EVENT.LCIO.CellIDEncoding) idDecoder = UTIL.BitField64(cellIdEncoding) for iHit in range(0, nHit): caloHit = hcalHits.getElementAt(iHit) pos = caloHit.getPositionVec() cellID = long(caloHit.getCellID0() & 0xffffffff) | (long(caloHit.getCellID1()) << 32) idDecoder.setValue(cellID) layer = idDecoder['layer'].value() allHitPos.append([pos[0], pos[1], pos[2]]) evt = drawPoint(allHitPos, evtNum) text = raw_input('press any key to exit: ') if text == '': evt.DisableListElements() else: print 'exit' break
def get_pos(event): # start position of each particle # get a hit collection BCAL = event.getCollection("BeamCalHits") # get the cell ID encoding string from the collection parameters cellIdEncoding = BCAL.getParameters().getStringVal( EVENT.LCIO.CellIDEncoding) # define a cell ID decoder for the collection idDecoder = UTIL.BitField64(cellIdEncoding) for calhit in BCAL: # combine the two 32 bit cell IDs of the hit into one 64 bit integer cellID = long(calhit.getCellID0() & 0xffffffff) | (long(calhit.getCellID1()) << 32) # set up the ID decoder for this cell ID idDecoder.setValue(cellID) # access the field information using a valid field from the cell ID encoding string print 'x:', idDecoder['x'].value() print 'y:', idDecoder['y'].value() # can put 'barrel' , 'layer' instead of 'x' and 'y' to get those values a = TNtuple("a", "cell", "layer")
def layerNos(nmbEvents,inFile): layerNosH=[0]*nmbEvents layerNos=[0]*nmbEvents for i in range(nmbEvents): layerNos[i]=[] layerNosH[i]=[] #create a reader readerL = LcioReader(inFile ) eventNo=-1 # loop over the events for event in readerL: eventNo+=1 if eventNo%100==0: print "recording layers of event "+str(eventNo) # get a hit collection hcalHits = event.getCollection( 'HCalBarrelHits' ) ecalHits = event.getCollection( 'ECalBarrelHits' ) # get the cell ID encoding string from the collection parameters cellIdEncoding = ecalHits.getParameters().getStringVal( EVENT.LCIO.CellIDEncoding ) cellIdEncodingH = hcalHits.getParameters().getStringVal( EVENT.LCIO.CellIDEncoding ) # define a cell ID decoder for the collection idDecoder = UTIL.BitField64( cellIdEncoding ) idDecoderH = UTIL.BitField64( cellIdEncodingH ) # loop over all hits in the collection for caloHit in ecalHits: # combine the two 32 bit cell IDs of the hit into one 64 bit integer cellID = long( caloHit.getCellID0() & 0xffffffff ) | ( long( caloHit.getCellID1() ) << 32 ) # set up the ID decoder for this cell ID idDecoder.setValue( cellID ) # access the field information using a valid field from the cell ID encoding string layerNos[eventNo].append(idDecoder['layer'].value()) for caloHitH in hcalHits: cellIDH=long(caloHitH.getCellID0() & 0xffffffff)|(long(caloHitH.getCellID1())<<32) idDecoderH.setValue(cellIDH) layerNosH[eventNo].append(idDecoderH['layer'].value()) return layerNosH, layerNos
def idleLoop(): """Watches user input, next, quit or picking""" text = "event " + str(g.event.getEventNumber()) + " " + str(g.event.getRunNumber()) text = text + " - hit enter to draw next - [q] to quit - double click on objects for picking" # input loop (keyboard or mouse) print text while True: i, o, e = select.select( [sys.stdin], [], [], 0.5 ) if(i): c = sys.stdin.readline().strip() else: c = -1 if( c == 'q' or c == '' ): break ; if( c != -1 ): print text pid = g.ced.ced_selected_id_noblock(); if pid != -1: print ' picked object with Id: ' , pid if( pid in g.objects ): print UTIL.toString( g.objects[ pid ] ) return c
def get_b_and_c_likenesses(event): collection = event.getCollection("RefinedJets") pidh = UTIL.PIDHandler(collection) algo = pidh.getAlgorithmID("lcfiplus") ibtag = pidh.getParameterIndex(algo, "BTag") ictag = pidh.getParameterIndex(algo, "CTag") likenesses = [] for jet in collection: #should be two of themath... pid = pidh.getParticleID(jet, algo) likenesses.append({ "BTag": pid.getParameters()[ibtag], "CTag": pid.getParameters()[ictag] }) return likenesses
def __open__(self, fileName): if self.isOpen: self.__close__() self.reader = UTIL.LCStdHepRdr(fileName) self.isOpen = True
eventNo = -1 # loop over the events for event in readerL: eventNo += 1 if eventNo % 100 == 0: print "recording layers of event " + str(eventNo) # print eventNo # get a hit collection ecalHits = event.getCollection('ECalBarrelHits') # get the cell ID encoding string from the collection parameters cellIdEncoding = ecalHits.getParameters().getStringVal( EVENT.LCIO.CellIDEncoding) # print cellIdEncoding # define a cell ID decoder for the collection idDecoder = UTIL.BitField64(cellIdEncoding) # loop over all hits in the collection for caloHit in ecalHits: # combine the two 32 bit cell IDs of the hit into one 64 bit integer cellID = long(caloHit.getCellID0() & 0xffffffff) | (long(caloHit.getCellID1()) << 32) # set up the ID decoder for this cell ID idDecoder.setValue(cellID) # access the field information using a valid field from the cell ID encoding string # print 'layer:', idDecoder['layer'].value() layerNos[eventNo].append(idDecoder['layer'].value()) ############################################################################### # create a reader and open an LCIO file reader = IOIMPL.LCFactory.getInstance().createLCReader()
def getEnergies(path_to_file, outfile, openingAngleCut): idDecoder = UTIL.BitField64( "system:5,side:2,module:8,stave:4,layer:9,submodule:4,x:32:-16,y:-16") idDecoderHCAL = UTIL.BitField64( "system:5,side:2,module:8,stave:4,layer:9,submodule:4,x:32:-16,y:-16") fil = ROOT.TFile.Open(str(path_to_file), "read") iEvt = 0 # We make an empty list of events event_list = [] for event in fil.EVENT: openingAngle = -1 # default if there is no pi0 -> /gamma/gamma if (len(event.MCParticles) >= 3 and event.MCParticles[0].pdgID == 111 and event.MCParticles[1].pdgID == 22 and event.MCParticles[2].pdgID == 22): gamma1px = event.MCParticles[1].psx gamma1py = event.MCParticles[1].psy gamma1pz = event.MCParticles[1].psz gamma2px = event.MCParticles[2].psx gamma2py = event.MCParticles[2].psy gamma2pz = event.MCParticles[2].psz cos_theta = (gamma1px * gamma2px + gamma1py * gamma2py + gamma1pz * gamma2pz) / math.sqrt( (gamma1px * gamma1px + gamma1py * gamma1py + gamma1pz * gamma1pz) * (gamma2px * gamma2px + gamma2py * gamma2py + gamma2pz * gamma2pz)) openingAngle = math.acos(cos_theta) if (~openingAngleCut or (openingAngle < 0.01 and openingAngle != -1) ): # either require opening angle cut of 0.01 or allow everything # We make an empty list of hits (within this event) hit_list = [] hit_listHCAL = [] iEvt = iEvt + 1 # Read HCAL for i in range(len(event.HCalBarrelCollection)): idDecoderHCAL.setValue(event.HCalBarrelCollection[i].cellID) z = idDecoderHCAL['layer'].value() x = idDecoderHCAL['x'].value() y = idDecoderHCAL['y'].value() E = event.HCalBarrelCollection[i].energyDeposit pos = event.HCalBarrelCollection[i].position hit_listHCAL.append( (int(x), int(y), int(z), E, pos.X(), pos.Y(), pos.Z())) # Read ECAL for i in range(len(event.ECalBarrelCollection)): #print event.ECalBarrelCollection.getParameters() idDecoder.setValue(event.ECalBarrelCollection[i].cellID) z = idDecoder['layer'].value() x = idDecoder['x'].value() y = idDecoder['y'].value() E = event.ECalBarrelCollection[i].energyDeposit pos = event.ECalBarrelCollection[i].position if (z < 25): hit_list.append( (int(x), int(y), int(z), E, pos.X(), pos.Y(), pos.Z())) # Read energy gunpx = event.MCParticles[0].psx gunpy = event.MCParticles[0].psy gunpz = event.MCParticles[0].psz m = event.MCParticles[0].mass gunE = ROOT.TMath.Sqrt(m * m + gunpx * gunpx + gunpy * gunpy + gunpz * gunpz) pdgID = event.MCParticles[0].pdgID photon_conversion_num = 0 for i in range(len(event.MCParticles)): if (event.MCParticles[i].pdgID == -11): positron_px = event.MCParticles[i].psx positron_py = event.MCParticles[i].psy positron_pz = event.MCParticles[i].psz positron_m = event.MCParticles[i].mass positron_E = ROOT.TMath.Sqrt(positron_m * positron_m + positron_px * positron_px + positron_py * positron_py + positron_pz * positron_pz) for j in range(len(event.MCParticles)): if (event.MCParticles[j].pdgID == 11 and event.MCParticles[j].vsx == event.MCParticles[i].vsx and event.MCParticles[j].vsy == event.MCParticles[i].vsy and event.MCParticles[j].vsz == event.MCParticles[i].vsz): electron_px = event.MCParticles[j].psx electron_py = event.MCParticles[j].psy electron_pz = event.MCParticles[j].psz electron_m = event.MCParticles[j].mass electron_E = ROOT.TMath.Sqrt( electron_m * electron_m + electron_px * electron_px + electron_py * electron_py + electron_pz * electron_pz) #if((positron_E + electron_E) > (ROOT.TMath.Sqrt(electron_m*electron_m+10)+ROOT.TMath.Sqrt(positron_m*positron_m +10))): if ((positron_E + electron_E) > 1000): photon_conversion_num += 1 event_list.append({ 'pdgID': pdgID, 'E': gunE, 'px': gunpx, 'py': gunpy, 'pz': gunpz, 'conversion': photon_conversion_num, 'ECAL': hit_list, 'HCAL': hit_listHCAL, 'openingAngle': openingAngle }) print(len(hit_list), len(hit_listHCAL)) # Append this event to the event list text_file = open(outfile, "w") for evt in event_list: text_file.write(str(evt) + "\n") text_file.close()
def processEvent(self, event): ''' Method called by the event loop for each event ''' self.numTrk = 0 self.numTracks = 0 del self.mcps[:] # Get generator particle information McP = event.getCollection("MCParticle") for p in McP: if abs(p.getCharge()) < 0.5: continue # get information fo charge particle mcpCosTheta = p.getMomentum()[2] / sqrt( p.getMomentum()[0] * p.getMomentum()[0] + p.getMomentum()[1] * p.getMomentum()[1] + p.getMomentum()[2] * p.getMomentum()[2]) mcpMom = sqrt(p.getMomentum()[0] * p.getMomentum()[0] + p.getMomentum()[1] * p.getMomentum()[1] + p.getMomentum()[2] * p.getMomentum()[2]) mcpPt = sqrt(p.getMomentum()[0] * p.getMomentum()[0] + p.getMomentum()[1] * p.getMomentum()[1]) mcpVtx = sqrt(p.getVertex()[0] * p.getVertex()[0] + p.getVertex()[1] * p.getVertex()[1] + p.getVertex()[2] * p.getVertex()[2]) mcpEnd = sqrt(p.getEndpoint()[0] * p.getEndpoint()[0] + p.getEndpoint()[1] * p.getEndpoint()[1] + p.getEndpoint()[2] * p.getEndpoint()[2]) mcpEndRho = sqrt(p.getEndpoint()[0] * p.getEndpoint()[0] + p.getEndpoint()[1] * p.getEndpoint()[1]) # Particle should not be decayed in Tracker. #if p.isDecayedInTracker() == True : #False: #True : # continue #if mcpPt < 0.100 : #0.1GeV = 100MeV # continue # Particle should not go into beam pipe if abs(mcpCosTheta) > 0.99: continue # Particle is not from overlay if p.isOverlay() == True: continue if p.getGeneratorStatus() == 1 and mcpVtx < 100.0: self.mcps.append(p) self.isGoodMCP = True # Get Track information isTrkFound = False isDupTrk = False # Get the MCTruthMarlinTrkTracksLink collection from the event mcpToTrk = event.getCollection("MCTruthMarlinTrkTracksLink") navMcptTrk = UTIL.LCRelationNavigator(mcpToTrk) TrkToMcp = event.getCollection("MarlinTrkTracksMCTruthLink") navTrktMcp = UTIL.LCRelationNavigator(TrkToMcp) for mu in self.mcps: mcpCosTheta = mu.getMomentum()[2] / sqrt( mu.getMomentum()[0] * mu.getMomentum()[0] + mu.getMomentum()[1] * mu.getMomentum()[1] + mu.getMomentum()[2] * mu.getMomentum()[2]) mcpMom = sqrt(mu.getMomentum()[0] * mu.getMomentum()[0] + mu.getMomentum()[1] * mu.getMomentum()[1] + mu.getMomentum()[2] * mu.getMomentum()[2]) mcpPt = sqrt(mu.getMomentum()[0] * mu.getMomentum()[0] + mu.getMomentum()[1] * mu.getMomentum()[1]) mcpVtx = sqrt(mu.getVertex()[0] * mu.getVertex()[0] + mu.getVertex()[1] * mu.getVertex()[1] + mu.getVertex()[2] * mu.getVertex()[2]) # tracks include this mcp trks = navMcptTrk.getRelatedToObjects(mu) # percent of track hits made of this mcp testFromWgt = navTrktMcp.getRelatedFromWeights(mu) # percent of mcp hits contribute to a track #testFromWgt4 = navMcptTrk.getRelatedToWeights( mu ) SimTrkVTX = event.getCollection("VXDCollection") Nvtx = 0 for vtx in SimTrkVTX: if vtx.getMCParticle() == mu: Nvtx = Nvtx + 1 if Nvtx > 3: break SimTrkSIT = event.getCollection("SITCollection") Nsit = 0 for sit in SimTrkSIT: if sit.getMCParticle() == mu: Nsit = Nsit + 1 if Nsit > 3: break #if mcpCosTheta < 0.9 and ( Nvtx + Nsit ) < 4 : # continue SimTrkFTD = event.getCollection("FTDCollection") Nftd = 0 for ftd in SimTrkFTD: if ftd.getMCParticle() == mu: Nftd = Nftd + 1 if Nftd > 3: break #if mcpCosTheta >= 0.9 and ( Nftd + Nsit ) < 4 : # continue if (Nvtx + Nsit + Nftd) < 4: continue iTrk = 0 iDupTrk = 0 for tr in trks: if testFromWgt[iTrk] > 0.75: isTrkFound = True iDupTrk = iDupTrk + 1 iTrk = iTrk + 1 self.efficiency1D[self.hPrefix + '_effTrkCosTheta'].Fill( isTrkFound, mcpCosTheta) self.efficiency1D[self.hPrefix + '_effTrkPt'].Fill( isTrkFound, log10(mcpPt)) self.efficiency1D[self.hPrefix + '_effTrkMom'].Fill( isTrkFound, log10(mcpMom)) self.efficiency1D[self.hPrefix + '_effTrkVtx'].Fill( isTrkFound, mcpVtx) self.efficiency1D[self.hPrefix + '_effTrkEnd'].Fill( isTrkFound, log10(mcpEnd)) self.efficiency2D[self.hPrefix + '_effTrk2DCosThetaPt'].Fill( isTrkFound, mcpCosTheta, mcpPt) self.efficiency2D[self.hPrefix + '_effTrk2DCosThetaP'].Fill( isTrkFound, mcpCosTheta, mcpMom) self.histograms2D[self.hPrefix + '_DenominatorCosThetaPt'].Fill( mcpCosTheta, mcpPt) self.histograms2D[self.hPrefix + '_DenominatorCosThetaP'].Fill( mcpCosTheta, mcpMom) if iDupTrk > 1: isDupTrk = True iDupTrk = 0 self.efficiency1D[self.hPrefix + '_dupTrkCosTheta'].Fill( isDupTrk, mcpCosTheta) self.efficiency1D[self.hPrefix + '_dupTrkPt'].Fill( isDupTrk, log10(mcpPt)) self.efficiency1D[self.hPrefix + '_dupTrkMom'].Fill( isDupTrk, log10(mcpMom)) self.efficiency1D[self.hPrefix + '_dupTrkVtx'].Fill( isDupTrk, mcpVtx) self.efficiency1D[self.hPrefix + '_dupTrkEnd'].Fill( isDupTrk, log10(mcpEnd)) isTrkFound = False isDupTrk = False MTrks = event.getCollection("MarlinTrkTracks") recoPt = 0.0 recCosth = 0.0 isFakeTrk = True for tr in MTrks: d0mcp = tr.getD0() #phmcp = tr.getPhi0() ommcp = tr.getOmega() #z0mcp = tr.getZ0() tLmcp = tr.getTanLambda() recoPt = abs(((3.0 / 10000.0) * 3.5) / ommcp) recCosth = tLmcp / sqrt(1.0 + tLmcp * tLmcp) MCPsTrk = navTrktMcp.getRelatedToObjects(tr) testToWgt = navTrktMcp.getRelatedToWeights(tr) for iTs in testToWgt: if iTs >= 0.75: # group of hits >= 75% from one MCP, consided as real reco track for this MCP, isFakeTrk = False # is not fake reco track. self.efficiency1D[self.hPrefix + '_fakeTrkCosTheta1'].Fill( isFakeTrk, recCosth) self.efficiency1D[self.hPrefix + '_fakeTrkPt'].Fill( isFakeTrk, log10(recoPt)) if isFakeTrk == True: # check the fake track: Number of MCP self.histograms1D[self.hPrefix + '_fakeTrkNmcp1'].Fill( MCPsTrk.size()) if MCPsTrk.size() == 2: Daus0 = MCPsTrk[0].getDaughters() for da0 in Daus0: if da0 == MCPsTrk[1]: isFakeTrk = False #print("Pa0: ",MCPsTrk[0].getPDG()," Da1: ", MCPsTrk[1].getPDG()) Daus1 = MCPsTrk[1].getDaughters() for da1 in Daus1: if da1 == MCPsTrk[0]: isFakeTrk = False #print("Pa1: ",MCPsTrk[1].getPDG()," Da0: ", MCPsTrk[0].getPDG()) if isFakeTrk == True: # check the fake track: Number of MCP self.histograms1D[self.hPrefix + '_fakeTrkNmcp2'].Fill( MCPsTrk.size()) self.efficiency1D[self.hPrefix + '_fakeTrkCosTheta2'].Fill( isFakeTrk, recCosth) isFakeTrk = True
def readEvent(): for event in reader: allHitPos = [] hcalHits = event.getCollection('HCALOther') evtNum = event.getEventNumber() nHit = hcalHits.getNumberOfElements() cellIdEncoding = hcalHits.getParameters().getStringVal( EVENT.LCIO.CellIDEncoding ) idDecoder = UTIL.BitField64( cellIdEncoding ) for iHit in range(0, nHit): caloHit = hcalHits.getElementAt( iHit ) pos = caloHit.getPositionVec() cellID = long( caloHit.getCellID0() & 0xffffffff ) | ( long( caloHit.getCellID1() ) << 32 ) idDecoder.setValue( cellID ) layer = idDecoder['layer'].value() allHitPos.append( [pos[0], pos[1], pos[2]] ) quantile = 0.025 Xdata = StandardScaler().fit_transform(allHitPos) bandwidth = cluster.estimate_bandwidth(Xdata, quantile=quantile) ms = cluster.MeanShift(bandwidth=bandwidth, bin_seeding=True) ms.fit(Xdata) y_pred = ms.labels_.astype(np.int) hitClusters = list(y_pred) clustersSelected = [] iClu = 0 minClusterSize = 0 maxClusterSize = 10000 while True: hitsNum = hitClusters.count(iClu) if hitsNum == 0: break allHits = len(hitClusters) idx = [i for i in range(allHits) if hitClusters[i] == iClu] printOut = False if printOut: print '----> Cluster ', iClu, ': hits number: ', hitsNum, ' =================== ' print idx, '\n' ########################################### # select clusters to show by hit number ########################################### if hitsNum > minClusterSize and hitsNum < maxClusterSize: hitCluster = [allHitPos[i] for i in idx] clustersSelected.append( hitCluster ) iClu = iClu + 1 ########################################### evt = drawClusters(clustersSelected, evtNum) #evt = drawPoints(allHitPos, evtNum) text = raw_input('press any key to exit: ') if text == '': evt.DisableListElements() #print 'next event' else: print 'exit' break
def generateEvents( outputFileName, nEvents ): random = TRandom3( 12345 ) # define a particle source sourcePosition = TVector3( 0., 0., 0. ) sourceSpreadXY = 10. pdgid = 13 charge = -1. mass = 0.105658 momentum = TVector3( 0.3, 0.1, 10. ) runNumber = 321 # define a detector with positions for the tracker planes detectorName = 'ToyTracker' trackerPlanePositions = [] hitResolution = 0.01 planeNormal = TVector3( 0., 0., 1. ) for planeZ in [ 100., 250., 480., 510., 640. ]: trackerPlanePositions.append( TVector3( 0., 0., planeZ ) ) # create a writer and open the output file writer = IOIMPL.LCFactory.getInstance().createLCWriter() writer.open( outputFileName, EVENT.LCIO.WRITE_NEW ) # create a run header and add it to the file (optional) run = IMPL.LCRunHeaderImpl() run.setRunNumber( runNumber ) run.setDetectorName( detectorName ) run.setDescription( 'This is a test run' ) writer.writeRunHeader( run ) for iEvent in xrange( nEvents ): # create an event and set its parameters event = IMPL.LCEventImpl() event.setEventNumber( iEvent ) event.setDetectorName( detectorName ) event.setRunNumber( runNumber ) event.setTimeStamp( int( time() * 1000000000. ) ) # create the mc particle collection mcParticles = IMPL.LCCollectionVec( EVENT.LCIO.MCPARTICLE ) # calculate the origin of the particle x = random.Gaus( sourcePosition.x(), sourceSpreadXY ) y = random.Gaus( sourcePosition.y(), sourceSpreadXY ) z = sourcePosition.z() origin = TVector3( x, y, z ) # create a particle mcParticle = IMPL.MCParticleImpl() mcParticle.setPDG( pdgid ) mcParticle.setMass( mass ) mcParticle.setMomentumVec( momentum ) mcParticle.setGeneratorStatus( 1 ) mcParticle.setVertexVec( origin ) mcParticle.setTime( 0. ) mcParticles.addElement( mcParticle ) # create a tracker hit collection trackerHits = IMPL.LCCollectionVec( EVENT.LCIO.SIMTRACKERHIT ) trackerHits.setFlag( UTIL.set_bit( trackerHits.getFlag(), EVENT.LCIO.THBIT_MOMENTUM ) ) # create an IDEncoder to store hit IDs # defines the tags and the number of bits for the different bit fields encodingString = 'system:3,layer:6' idEncoder = UTIL.CellIDEncoder( IMPL.SimTrackerHitImpl )( encodingString, trackerHits ) # add a hit for each layer for planePosition in trackerPlanePositions: # calculate the intersection with the plane distance = ( planePosition - origin ).Dot( planeNormal ) / momentum.Dot( planeNormal ) intersect = TVector3( momentum ) intersect.SetMag( distance ) # smear the hit position with the resolution hitX = random.Gaus( intersect.x(), hitResolution ) hitY = random.Gaus( intersect.x(), hitResolution ) hitPosition = TVector3( hitX, hitY, intersect.z() ) # build the tracker hit trackerHit = IMPL.SimTrackerHitImpl() trackerHit.setPositionVec( hitPosition ) trackerHit.setMomentumVec( momentum ) trackerHit.setMCParticle( mcParticle ) trackerHit.setTime( distance / TMath.C() ) trackerHit.setEDep( 0.1 ) # set the cell ID idEncoder.reset() idEncoder['layer'] = trackerPlanePositions.index( planePosition ) idEncoder['system'] = 1 idEncoder.setCellID( trackerHit ) trackerHits.addElement( trackerHit ) event.addCollection( mcParticles, EVENT.LCIO.MCPARTICLE ) event.addCollection( trackerHits, 'SimTrackerHits' ) writer.writeEvent( event ) writer.flush() writer.close()
def convert_to_calorimeterevent(inputFileName, outputFileName, Row2X_lut_left, Row2X_lut_right, Column2Y_lut_left, Column2Y_lut_right, Z_lut, lane_lut, IsLeft): #check flag setting, as position won't be written if LCIO::CHBIT_LONG not set... flag = IMPL.LCFlagImpl() flag.setBit(EVENT.LCIO.CHBIT_LONG) #Create a reader to parse the input file reader = LcioReader(inputFileName) #create a writer to write to the output file writer = IOIMPL.LCFactory.getInstance().createLCWriter() writer.open(outputFileName, EVENT.LCIO.WRITE_NEW) #create indexes for progress tracking... index = 0. q = int(0) #get the root tree... file = TFile(inputFileName, "read") tree = file.Get("Frames") #loop over all entries in the tree for i in range(0, tree.GetEntries()): #if index>=10: # break index += 1. tree.GetEntry(i) Lane = tree.lane #vector Row = tree.row #vector Column = tree.column #vector Event = tree.eventNumber File = tree.fileNumber Run = tree.runNumber # ++ Lane, Row and Column should be the same length. Let's just check that they are: if (len(Lane) != len(Row)) or (len(Lane) != len(Column)): print "ERROR +++++++++++++++++++++++++++++++++++++ Row vector length", len( Row), ", Column vector length", len( Column), "and Lane vector length", len( Lane), "aren't equal!" #create a new event newEvent = IMPL.LCEventImpl() newEvent.setEventNumber(Event) newEvent.setRunNumber(Run) #Create a new collection to add to the new events, now made from CalorimeterHits. CaloHits = IMPL.LCCollectionVec(EVENT.LCIO.CALORIMETERHIT) #add flag to CaloHits so we can store positions... CaloHits.setFlag(flag.getFlag()) #Create an encoder for the new events... encodingString = str("lane:7,row:11,column:11") idEncoder = UTIL.CellIDEncoder(IMPL.CalorimeterHitImpl)(encodingString, CaloHits) #Loop over all entries in the tree... for j in range(0, len(Lane)): #get the chipID from the lane... chipID = inverse_lane_lut[Lane[j]] #get x, y and z. if (IsLeft[chipID]): x = Row2X_lut_left[Row[j]] y = Column2Y_lut_left[Column[j]] else: x = Row2X_lut_right[Row[j]] y = Column2Y_lut_right[Column[j]] z = Z_lut[chipID] #Make new calorimeter hit: newHit = IMPL.CalorimeterHitImpl() #add the lane, column, row to the new collection... idEncoder.reset() idEncoder['lane'] = Lane[j] idEncoder['row'] = Row[j] idEncoder['column'] = Column[j] idEncoder.setCellID(newHit) #add x, y, z to the new collection... Position = TVector3(x, y, z) newHit.setPositionVec(Position) #add hits to collection CaloHits.addElement(newHit) #end of hit loop #add collection to event newEvent.addCollection(CaloHits, 'ECalBarrelCollection') #write the event to the output file writer.writeEvent(newEvent) #print percentage of progress (but not too often!) p = int((float(index) / float(tree.GetEntries() * 100))) progress = str(p) + '%' if (p != q): print "Progress:", progress q = int(p) #end of event loop #close the writer writer.flush() writer.close()
def convertRun(inputFileName, outputFileName, runNumber, nplanes=7): # define detector name detectorName = 'FEI4Tel' # create a writer and open the output file writer = IOIMPL.LCFactory.getInstance().createLCWriter() writer.open(outputFileName, EVENT.LCIO.WRITE_NEW) # create a run header and add it to the file run = IMPL.LCRunHeaderImpl() run.setRunNumber(runNumber) run.setDetectorName(detectorName) run.parameters().setValue('GeoID', 0) run.parameters().setValues('MaxX', std.vector(int)(nplanes, 335)) run.parameters().setValues('MaxY', std.vector(int)(nplanes, 79)) run.parameters().setValues('MinX', std.vector(int)(nplanes, 0)) run.parameters().setValues('MinY', std.vector(int)(nplanes, 0)) run.parameters().setValue('NoOfDetector', nplanes) run.parameters().setValues('AppliedProcessor', std.vector('string')(1, '')) run.parameters().setValue('DAQHWName', 'EUDRB') run.parameters().setValue('DAQSWName', 'EUDAQ') run.parameters().setValue('DataType', 'Data') run.parameters().setValue('DateTime', '24.12.2000 23:59:59.000000000') run.parameters().setValue('EUDRBDet', 'MIMOSA26') run.parameters().setValue('EUDRBMode', 'ZS2') writer.writeRunHeader(run) aDataSet = JudithData(inputFileName, nplanes) MAXEVENTS = aDataSet.GetNEvents() #MAXEVENTS = 500 NEVENTS = 0 # event loop for eventnr in range(MAXEVENTS): if (eventnr % 1000 == 0): print 'Events processed: %i ...' % eventnr # create an event and set its parameters event = IMPL.LCEventImpl() event.setEventNumber(eventnr) event.setDetectorName(detectorName) event.setRunNumber(runNumber) event.setTimeStamp(int(time() * 1000000000.)) event.parameters().setValue('EventType', 2) # parse input file telescopeData = aDataSet.GetEvent(eventnr) #aDataSet.PrintEvent(eventnr) # if first event, create additional setup collection(s) if eventnr == 0: eudrbSetup = IMPL.LCCollectionVec(EVENT.LCIO.LCGENERICOBJECT) # collection parameters eudrbSetup.parameters().setValue( 'DataDescription', 'type:i,mode:i,spare1:i,spare2:i,spare3:i') eudrbSetup.parameters().setValue('TypeName', 'Setup Description') # create on setup object per Telescope plane for sensorID in range(nplanes): setupObj = IMPL.LCGenericObjectImpl(5, 0, 0) setupObj.setIntVal(0, 102) setupObj.setIntVal(1, 101) eudrbSetup.addElement(setupObj) event.addCollection(eudrbSetup, 'eudrbSetup') # ID encoder info encodingString = 'sensorID:5,sparsePixelType:5' # Telescope data collection trackerDataColl = IMPL.LCCollectionVec(EVENT.LCIO.TRACKERDATA) idEncoder_Telescope = UTIL.CellIDEncoder(IMPL.TrackerDataImpl)( encodingString, trackerDataColl) # fill telescope collection for sensorID in range(nplanes): planeData = IMPL.TrackerDataImpl() idEncoder_Telescope.reset() idEncoder_Telescope['sensorID'] = int( sensorID) # cannot fit 300 in 5 bits!! FIXME plane_tmp = int(sensorID) idEncoder_Telescope['sparsePixelType'] = 2 idEncoder_Telescope.setCellID(planeData) # loop over hits chargeVec = std.vector(float)() for hit in telescopeData[sensorID]: for j, val in enumerate(hit): chargeVec.push_back(val) planeData.setChargeValues(chargeVec) trackerDataColl.addElement(planeData) event.addCollection(trackerDataColl, 'zsdata_FEI4') writer.writeEvent(event) writer.flush() writer.close()
def convertRun( inputTarFile, outputFileName ): # read file names from given path #fileNames = sorted( glob.glob( inputPath+'/mpx*.txt' ) ) #nEvents = len( fileNames ) inputFiles = [] tar = tarfile.open( inputTarFile, 'r:gz' ) for member in tar.getmembers(): if not member.isfile(): continue inputFiles.append( tar.extractfile(member) ) # get run number from first file (same for the rest) assuming filename is this form: mpx-YYMMDD-HHmmSS-RUN_FRAME.txt runNumber = int( inputFiles[0].name.split('-')[-1].split('_')[0] ) runNumber = int( inputTarFile.split('n')[-1].split('.')[0] ) # define detector name detectorName = 'EUTelescope' # create a writer and open the output file writer = IOIMPL.LCFactory.getInstance().createLCWriter() writer.open( outputFileName, EVENT.LCIO.WRITE_NEW ) print "Runnumber: " + str(runNumber) # create a run header and add it to the file run = IMPL.LCRunHeaderImpl() run.setRunNumber( runNumber ) run.setDetectorName( detectorName ) run.parameters().setValue ( 'GeoID' , 0 ) run.parameters().setValues ( 'MaxX' , std.vector(int)(6,1151) ) run.parameters().setValues ( 'MaxY' , std.vector(int)(6,575) ) run.parameters().setValues ( 'MinX' , std.vector(int)(6,0) ) run.parameters().setValues ( 'MinY' , std.vector(int)(6,0) ) run.parameters().setValue ( 'NoOfDetector' , 6 ) run.parameters().setValues ( 'AppliedProcessor' , std.vector('string')(1,'') ) run.parameters().setValue ( 'DAQHWName' , 'EUDRB' ) run.parameters().setValue ( 'DAQSWName' , 'EUDAQ' ) run.parameters().setValue ( 'DataType' , 'SimData' ) run.parameters().setValue ( 'DateTime' , '24.12.2000 23:59:59.000000000' ) run.parameters().setValue ( 'EUDRBDet' , 'MIMOSA26' ) run.parameters().setValue ( 'EUDRBMode' , 'ZS2' ) writer.writeRunHeader( run ) MAXEVENTS = 1000000 NEVENTS = 0 # event loop for eventFile in inputFiles: if NEVENTS == MAXEVENTS: break NEVENTS += 1 # get event number from file name ( i.e. frame ID ) assuming file name format above iEvent = int( eventFile.name.split('_')[-1].split('.')[0] ) if ( NEVENTS%1000 == 0 ): print 'Events processed: %i ...' % NEVENTS # create an event and set its parameters event = IMPL.LCEventImpl() event.setEventNumber( iEvent ) event.setDetectorName( detectorName ) event.setRunNumber( runNumber ) event.setTimeStamp( int( time() * 1000000000. ) ) event.parameters().setValue( 'EventType', 2 ) # parse input file telescopeData, DUTData = parseFrameFile( eventFile ) # is there DUT data? containsDUT = False if len( DUTData ) > 0: containsDUT = True # if first event, create additional setup collection(s) if iEvent == 0: eudrbSetup = IMPL.LCCollectionVec( EVENT.LCIO.LCGENERICOBJECT ) # collection parameters eudrbSetup.parameters().setValue( 'DataDescription', 'type:i,mode:i,spare1:i,spare2:i,spare3:i' ) eudrbSetup.parameters().setValue( 'TypeName', 'Setup Description' ) # create on setup object per Telescope plane for sensorID in sorted( telescopeData.iterkeys() ): setupObj = IMPL.LCGenericObjectImpl(5,0,0) setupObj.setIntVal( 0, 102 ) setupObj.setIntVal( 1, 101 ) eudrbSetup.addElement( setupObj ) event.addCollection ( eudrbSetup, 'eudrbSetup' ) # check if there is a DUT if containsDUT: DUTSetup = IMPL.LCCollectionVec( EVENT.LCIO.LCGENERICOBJECT ) event.addCollection ( DUTSetup, 'DUTSetup' ) # ID encoder info encodingString = 'sensorID:7,sparsePixelType:5' # Telescope data collection trackerDataColl = IMPL.LCCollectionVec( EVENT.LCIO.TRACKERDATA ) idEncoder_Telescope = UTIL.CellIDEncoder( IMPL.TrackerDataImpl )( encodingString, trackerDataColl ) # check if there is a DUT if containsDUT: # DUT data collection DUTDataColl = IMPL.LCCollectionVec( EVENT.LCIO.TRACKERDATA ) idEncoder_DUT = UTIL.CellIDEncoder( IMPL.TrackerDataImpl )( encodingString, DUTDataColl ) REFDataColl = IMPL.LCCollectionVec( EVENT.LCIO.TRACKERDATA ) idEncoder_REF = UTIL.CellIDEncoder( IMPL.TrackerDataImpl )( encodingString, REFDataColl ) for i,sensorID in enumerate( sorted( DUTData.iterkeys() ) ): planeData = IMPL.TrackerDataImpl() idEncoder_DUT.reset() #idEncoder_DUT['sensorID'] = int( sensorID ) - 500 + 6 # cannot fit 500 in 5 bits!! FIXME idEncoder_DUT['sensorID'] = i+6 # cannot fit 500 in 5 bits!! FIXME idEncoder_DUT['sparsePixelType'] = 2 idEncoder_DUT.setCellID( planeData ) chargeVec = std.vector(float)() for val in DUTData[sensorID]: chargeVec.push_back( val ) if val < 0: print 'Negative number in Event %i' % iEvent planeData.setChargeValues( chargeVec ) if int(sensorID) == 900 : DUTDataColl.addElement( planeData ) event.addCollection( DUTDataColl, 'CMSPixelDUT' ) elif int(sensorID) == 901 : REFDataColl.addElement( planeData ) event.addCollection( REFDataColl, 'CMSPixelREF' ) else: print "Shit. Who am I? sensorID: " + str(int(sensorID)) # fill telescope collection for sensorID in sorted( telescopeData.iterkeys() ): planeData = IMPL.TrackerDataImpl() idEncoder_Telescope.reset() idEncoder_Telescope['sensorID'] = int( sensorID ) - 300 # cannot fit 300 in 5 bits!! FIXME idEncoder_Telescope['sparsePixelType'] = 2 idEncoder_Telescope.setCellID( planeData ) # loop over hits chargeVec = std.vector(float)() for val in telescopeData[sensorID]: chargeVec.push_back( val ) planeData.setChargeValues( chargeVec ) trackerDataColl.addElement( planeData ) event.addCollection( trackerDataColl, 'zsdata_m26' ) writer.writeEvent( event ) writer.flush() writer.close()
def convert_to_calorimeterevent(inputFileName, outputFileName, Row2X_lut_left, Row2X_lut_right, Column2Y_lut_left, Column2Y_lut_right, Z_lut, lane_lut, IsLeft): #check flag setting, as position won't be written if LCIO::CHBIT_LONG not set... flag = IMPL.LCFlagImpl() flag.setBit(EVENT.LCIO.CHBIT_LONG) #Create a reader to parse the input file reader = LcioReader(inputFileName) #create a writer to write to the output file writer = IOIMPL.LCFactory.getInstance().createLCWriter() writer.open(outputFileName, EVENT.LCIO.WRITE_NEW) #create indexes for progress tracking... index = 0. q = int(0) for oldEvent in reader: #if index>=10: # break index += 1. #create a new event and copy its parameters newEvent = IMPL.LCEventImpl() newEvent.setEventNumber(oldEvent.getEventNumber()) newEvent.setRunNumber(oldEvent.getRunNumber()) #Create a new collection to add to the new events, now made from CalorimeterHits. CaloHits = IMPL.LCCollectionVec(EVENT.LCIO.CALORIMETERHIT) #add flag to CaloHits so we can store positions... CaloHits.setFlag(flag.getFlag()) #Create both an encoder for the new events, and a decoder for the old ones... encodingString = str("lane:7,row:11,column:11") idEncoder = UTIL.CellIDEncoder(IMPL.CalorimeterHitImpl)(encodingString, CaloHits) idDecoder = UTIL.CellIDDecoder( IMPL.RawCalorimeterHitImpl)(encodingString) #get the raw calorimeter hits... RawCaloHits = oldEvent.getCollection('RawCalorimeterHits') #Loop over the RawCalorimeterHits for oldHit in RawCaloHits: #get the row, column and lane from the raw calorimter hits lane = idDecoder(oldHit)["lane"].value() row = idDecoder(oldHit)["row"].value() column = idDecoder(oldHit)["column"].value() #get the chipID from the lane... chipID = inverse_lane_lut[lane] #get x, y and z. if (IsLeft[chipID]): x = Row2X_lut_left[row] y = Column2Y_lut_left[column] else: x = Row2X_lut_right[row] y = Column2Y_lut_right[column] z = Z_lut[chipID] #Make new calorimeter hit: newHit = IMPL.CalorimeterHitImpl() #add the lane, column, row to the new collection... idEncoder.reset() idEncoder['lane'] = lane idEncoder['row'] = row idEncoder['column'] = column idEncoder.setCellID(newHit) #add x, y, z to the new collection... Position = TVector3(x, y, z) newHit.setPositionVec(Position) #add hits to collection CaloHits.addElement(newHit) #end of hit loop #add collection to event newEvent.addCollection(CaloHits, 'ECalBarrelCollection') #write the event to the output file writer.writeEvent(newEvent) #print percentage of progress (but not too often!) p = int((float(index) / float(reader.getNumberOfEvents())) * 100) progress = str(p) + '%' if (p != q): print "Progress:", progress q = int(p) #end of event loop #close the writer writer.flush() writer.close()
def getinfo(inputfilename, outputfilename): #Set up the LCIO output file writer = IOIMPL.LCFactory.getInstance().createLCWriter() writer.open(outputfilename, EVENT.LCIO.WRITE_NEW) #Get the file and the tree in the file: file = TFile(inputfilename, "read") tree = file.Get("Frames") #iterator for progress bar... q = int(0) #loop over all entries in the tree... for i in range(0, tree.GetEntries()): tree.GetEntry(i) Lane = tree.lane #vector Row = tree.row #vector Column = tree.column #vector Event = tree.eventNumber File = tree.fileNumber Run = tree.runNumber # ++ Lane, Row and Column should be the same length. Let's just check that they are: if (len(Lane) != len(Row)) or (len(Lane) != len(Column)): print "ERROR +++++++++++++++++++++++++++++++++++++ Row vector length", len( Row), ", Column vector length", len( Column), "and Lane vector length", len( Lane), "aren't equal!" # ++ create an event LCEvent = IMPL.LCEventImpl() LCEvent.setEventNumber(Event) LCEvent.setRunNumber(Run) # ++ create a raw calorimeter hit collection RawCaloHits = IMPL.LCCollectionVec(EVENT.LCIO.RAWCALORIMETERHIT) # ++ create an IDEncoder to store hit IDs # ++ defines the tags and the number of bits for the different bit fields encodingString = str("lane:7,row:11,column:11") idEncoder = UTIL.CellIDEncoder(IMPL.RawCalorimeterHitImpl)( encodingString, RawCaloHits) for j in range(0, len(Lane)): # ++ build the raw calorimeter hit Hit = IMPL.RawCalorimeterHitImpl() # ++ set the cell ID idEncoder.reset() idEncoder['lane'] = Lane[j] idEncoder['row'] = Row[j] idEncoder['column'] = Column[j] idEncoder.setCellID(Hit) # ++ add the hit to the collection RawCaloHits.addElement(Hit) # ++ end of hit loop # ++ add the collection to the event LCEvent.addCollection(RawCaloHits, 'RawCalorimeterHits') # ++ write the event to the output file writer.writeEvent(LCEvent) # ++ print percentage of progress (but not too often!) p = int((float(i) / float(tree.GetEntries())) * 100) progress = str(p) + '%' if (p != q): print "Progress:", progress q = int(p) # ++ end of event loop # ++ close the writer writer.flush() writer.close()