def __read__(self): ''' Get the next event from the stream ''' event = IMPL.LCEventImpl() try: self.reader.updateNextEvent(event, EVENT.LCIO.MCPARTICLE) event.setEventNumber(self.processedEvents) self.processedEvents += 1 return event except: return
def LCStdHepRdrIterator(self): ''' Helper method to make LCStdHepRdr iterable ''' processedEvents = 0 while True: event = IMPL.LCEventImpl() try: self.updateNextEvent(event) event.setEventNumber(processedEvents) except Exception: break yield event processedEvents += 1
def doAlignment(outputFileName): # create a writer and open the output file writer = IOIMPL.LCFactory.getInstance().createLCWriter() writer.open(outputFileName, EVENT.LCIO.WRITE_NEW) # create an event and set its parameters event = IMPL.LCEventImpl() event.setEventNumber(0) event.setRunNumber(0) event.setTimeStamp(int(time() * 1000000000.)) alignmentColl = IMPL.LCCollectionVec(EVENT.LCIO.LCGENERICOBJECT) # collection parameters alignmentColl.parameters().setValue( 'DataDescription', 'sensorID, xOff, yOff, zOff, alpha, beta, gamma + 13 spare fields') alignmentColl.parameters().setValue('TypeName', 'Alignment Constant') # number of items nValues = 20 for sensorID in xrange(4, 10): alignObj = IMPL.LCGenericObjectImpl(nValues, 0, nValues) for i in xrange(nValues): alignObj.setIntVal(i, 0) alignObj.setDoubleVal(i, 0.) alignmentColl.addElement(alignObj) event.addCollection(alignmentColl, 'alignment') writer.writeEvent(event) writer.flush() writer.close()
decayLen = 1.e32 genstat = 1 pt_min = 1. pt_max = 1500. theta_min = 10. / 180. * math.pi theta_max = 170. / 180. * math.pi #================================================= for j in range(0, nevt): col = IMPL.LCCollectionVec(EVENT.LCIO.MCPARTICLE) evt = IMPL.LCEventImpl() evt.setEventNumber(j) evt.addCollection(col, "MCParticle") print(j, "-----------------------------") for ipart in range(0, npart): pt = random.uniform(pt_min, pt_max) theta = random.uniform(theta_min, theta_max) phi = random.random() * math.pi * 2. p = pt / math.sin(theta)
def merge(inputFileName, outputFileName, nEventsPerEvent): ''' Merges the events from the input file and writes them to the output file. Each output event will contain the information from the defined number of input events per event.''' # create a reader reader = LcioReader(inputFileName) print('Processing %d events from %s' % (reader.getNumberOfEvents(), inputFileName)) # create a writer writer = IOIMPL.LCFactory.getInstance().createLCWriter() writer.open(outputFileName, EVENT.LCIO.WRITE_NEW) readEvents = 0 readEventsSinceLastWrite = 0 combinedEvents = 0 combinedEvent = None # loop over the input file for event in reader: # check if we have merged sufficient events to write it to the output file if not combinedEvent or readEventsSinceLastWrite % nEventsPerEvent == 0: if combinedEvent: writer.writeEvent(combinedEvent) combinedEvents += 1 readEventsSinceLastWrite = 0 # create a new event and copy all parameters combinedEvent = IMPL.LCEventImpl() combinedEvent.setEventNumber(combinedEvents) combinedEvent.setRunNumber(event.getRunNumber()) combinedEvent.setDetectorName(event.getDetectorName()) combinedEvent.setTimeStamp(event.getTimeStamp()) copyObjectParameters(event, combinedEvent) # create new empty collections in the merged event for every collection in the input event for collectionName in event.getCollectionNames(): collection = event.getCollection(collectionName) collectionType = collection.getTypeName() # only treat supported types if collectionType in supportedTypes: combinedEvent.addCollection( IMPL.LCCollectionVec(collection.getTypeName()), collectionName) copyObjectParameters( collection, combinedEvent.getCollection(collectionName)) mergeEvents(event, combinedEvent) if readEvents % 100 == 0 and readEvents != 0: print('Processed %d events' % (readEvents)) readEvents += 1 readEventsSinceLastWrite += 1 # check if there are events not yet written if readEventsSinceLastWrite > 0: if combinedEvent: writer.writeEvent(combinedEvent) writer.flush() writer.close()
def selectEvents(inputFileName, outputFileName, maxread=1000): ''' Function: Select events from inputFileName and write to outputFileName Inputs: inputFileName : outputFileName : maxread : max number of events to read ''' # ======================================================================= MASS_MIN = 81.1876 MASS_MAX = 101.1876 # create a reader if not os.path.exists(inputFileName): print(inputFileName + " does not exist.") exit(0) reader = LcioReader.LcioReader(str(inputFileName)) print("Input file is " + inputFileName) # create a writer print("Selected events are written in " + outputFileName) if os.path.exists(outputFileName): print("Output file, " + outputFileName + ", exists. Remove it first.") exit(0) writer = IOIMPL.LCFactory.getInstance().createLCWriter() writer.open(str(outputFileName), EVENT.LCIO.WRITE_NEW) # Write run header aRunNumber = 1234 runHeader = IMPL.LCRunHeaderImpl() runHeader.setRunNumber(aRunNumber) runpara = runHeader.getParameters() # keyVec = ROOT.vector("string")() runpara.setValue("InputFileName", str(inputFileName)) runpara.setValue("Mass Maximum", float(MASS_MAX)) runpara.setValue("Mass Minimum", float(MASS_MIN)) writer.writeRunHeader(runHeader) nread = 0 nwrite = 0 ## Create a root file to monitor selection. rootfile = outputFileName.replace(".slcio", ".root") rfile = ROOT.TFile(rootfile, "RECREATE") ntev = ROOT.TNtuple("nt", "event selection", "emum:emup:mmumu:mmiss:mrest") print("==== Creating root file " + str(rootfile)) nbevents = reader.getNumberOfEvents() print("There are " + str(nbevents) + " events in this file.") # ======================================================================= # Read events in the file, and fill Ntuple # ======================================================================= nread = 0 for event in reader: if nread >= nbevents: print( "### Completed selection of input file(s) at nread=%d, nwrite=%d" % (nread, nwrite)) break if maxread > 0 and nread >= maxread: print("Reached maxread(%d) at nread=%d" % (maxread, nread)) break nread = nread + 1 if nread % 1000 == 0: print(" reading " + str(nread) + "-th event") psum = ROOT.TLorentzVector(0.0, 0.0, 0.0, 0.0) pmum = ROOT.TLorentzVector(0.0, 0.0, 0.0, 0.0) pmup = ROOT.TLorentzVector(0.0, 0.0, 0.0, 0.0) pini = ROOT.TLorentzVector(0.0, 0.0, 0.0, 250.0) # for colname in event.getCollectionNames(): # print(" colname="+colname) mcps = event.getCollection(str("MCParticle")) # Loop over all particle in MCParticle collection. # and find mu+ and mu- of the highest energy for mcp in mcps: if mcp.getGeneratorStatus() == 1: # select final state particles p = mcp.getLorentzVec() psum += p pdg = mcp.getPDG() if pdg == 13 and p.E() > pmum.E(): pmum = p if pdg == -13 and p.E() > pmup.E(): pmup = p pmumu = pmum + pmup mumumas = pmumu.M() missmas = (pini - pmumu).M() restmas = (psum - pmum - pmup).M() # Fiil variables in Ntuple ntev.Fill(float(pmum.E()), float(pmup.E()), float(mumumas), float(missmas), float(restmas)) # ################################################# # Select events # ################################################# if float(mumumas) >= MASS_MIN and float(mumumas) <= MASS_MAX: # Passed event selection. Create output collection nwrite = nwrite + 1 if nwrite < 10 or nwrite % 1000 == 1: print("Passed selection: M(mumu)=%f, nwrite/nread=%d/%d" % (float(mumumas), nwrite, nread)) writeEvent = IMPL.LCEventImpl() # Event header writeEvent.setEventNumber(event.getEventNumber()) writeEvent.setRunNumber(aRunNumber) writeEvent.setDetectorName(event.getDetectorName()) writeEvent.setTimeStamp(event.getTimeStamp()) copyObjectParameters(event, writeEvent) # Event parameters writeParams = writeEvent.getParameters() # keyVec = ROOT.vector("string")() writeParams.setValue("nwrite", nwrite) # integer writeParams.setValue("mumu_mass", float(mumumas)) # float # Collections for colname in ["MCParticle"]: col = event.getCollection(colname) colwrite = copy.deepcopy(col) writeEvent.addCollection( colwrite, colwrite.getTypeName()) # Add input correction to output # Write event writer.writeEvent(writeEvent) # close file at the end. writer.flush() writer.close print("### Read %d events. Write %d events" % (nread, nwrite)) rfile.Write() rfile.Close() return
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 generateEvents(inputFileName, outputFileName, nEvents=-1, nSplit=-1): fin = r.TFile(inputFileName) ttree = fin.events # define a detector with positions for the tracker planes detectorName = 'ToyTracker' # 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(1) run.setDetectorName(str(detectorName)) run.setDescription(str('This is a test run')) writer.writeRunHeader(run) iEvent = 0 flag = True for e in ttree: if iEvent == nEvents and nEvents > -1: print('END file ', iEvent - 1) flag = True break if nSplit > -1 and nSplit > iEvent: iEvent += 1 continue elif flag: print('START file ', iEvent) flag = False # create an event and set its parameters event = IMPL.LCEventImpl() event.setEventNumber(iEvent) event.setDetectorName(str(detectorName)) event.setRunNumber(1) event.setTimeStamp(int(time() * 1000000000.)) tracks = IMPL.LCCollectionVec(EVENT.LCIO.TRACK) recops = IMPL.LCCollectionVec(EVENT.LCIO.RECONSTRUCTEDPARTICLE) #loop over the reconstructed particles for rp in range(e.ReconstructedParticles.size()): recp = IMPL.ReconstructedParticleImpl() recp.setCharge(e.ReconstructedParticles.at(rp).charge) #print ('charge ',e.ReconstructedParticles.at(rp).charge) momentum = r.TVector3( e.ReconstructedParticles.at(rp).momentum.x, e.ReconstructedParticles.at(rp).momentum.y, e.ReconstructedParticles.at(rp).momentum.z) recp.setMomentumVec(momentum) recp.setEnergy(e.ReconstructedParticles.at(rp).energy) #print ('get recp energy ',recp.getEnergy(), ' get charge ',recp.getCharge(),' get m ',recp.getMass()) #print ('set recp energy ',e.ReconstructedParticles.at(rp).energy, ' px ',e.ReconstructedParticles.at(rp).momentum.x, ' m ',e.ReconstructedParticles.at(rp).mass,' charge ',e.ReconstructedParticles.at(rp).charge) tlv = r.TLorentzVector() tlv.SetXYZM( e.ReconstructedParticles.at(rp).momentum.x, e.ReconstructedParticles.at(rp).momentum.y, e.ReconstructedParticles.at(rp).momentum.z, e.ReconstructedParticles.at(rp).mass) #print ('tlv e ',tlv.E(),' tlv m ',tlv.M()) #recp.setEnergy(tlv.E()) #get the track associated to the reco particle if e.ReconstructedParticles.at( rp).tracks_begin < e.EFlowTrack_1.size(): track = IMPL.TrackImpl() trkind = e.ReconstructedParticles.at(rp).tracks_begin track.setD0(e.EFlowTrack_1.at(trkind).D0) track.setPhi(e.EFlowTrack_1.at(trkind).phi) track.setOmega(e.EFlowTrack_1.at(trkind).omega) track.setZ0(e.EFlowTrack_1.at(trkind).Z0) track.setTanLambda(e.EFlowTrack_1.at(trkind).tanLambda) track.subdetectorHitNumbers().resize(50) #In EDM4Hep the covariance matrix is the upper triangle. In LCIO the bottom triangle. Only diagonals terms are filled because correlations are ignored. vec = r.std.vector('float')(15) vec[0] = e.EFlowTrack_1.at(trkind).covMatrix[0] vec[2] = e.EFlowTrack_1.at(trkind).covMatrix[5] vec[5] = e.EFlowTrack_1.at(trkind).covMatrix[9] vec[9] = e.EFlowTrack_1.at(trkind).covMatrix[12] vec[14] = e.EFlowTrack_1.at(trkind).covMatrix[14] track.setCovMatrix(vec) tracks.addElement(track) recp.addTrack(track) recops.addElement(recp) event.addCollection(tracks, EVENT.LCIO.TRACK) event.addCollection(recops, EVENT.LCIO.RECONSTRUCTEDPARTICLE) writer.writeEvent(event) iEvent += 1 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()
#========== particle properties =================== configs = [[10, 30, 50], [10, 30, 100], [10, 30, 200]] genstat = 1 decayLen = 1.e32 #================================================= #================================================ for p1, p2, shifty in configs: outfile = 'PDG130211_' + str(p1) + 'GeV_' + str(p2) + 'GeV_' + str( shifty) + 'mm.slcio' # write a RunHeader run = IMPL.LCRunHeaderImpl() run.setRunNumber(0) run.parameters().setValue("Generator", "${lcgeo}_DIR/examples/lcio_particle_gun.py") wrt = IOIMPL.LCFactory.getInstance().createLCWriter() wrt.open(outfile, EVENT.LCIO.WRITE_NEW) wrt.writeRunHeader(run) print "---> created outfile: ", outfile for j in range(0, nevt): col = IMPL.LCCollectionVec(EVENT.LCIO.MCPARTICLE) evt = IMPL.LCEventImpl()
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()
def write_to_lcio(showers, energy, model_name, outfile, N): status_text = st.empty() status_text.text("Writing to LCIO files...") progress_bar = st.progress(0) ## get the dictionary f = open('cell_maps/cell-map_HCAL.pickle', 'rb') cmap = pickle.load(f) #pbar_cache = pkbar.Pbar(name='Writing to lcio files', target=N) wrt = IOIMPL.LCFactory.getInstance().createLCWriter() wrt.open(outfile, EVENT.LCIO.WRITE_NEW) random.seed() #========== MC particle properties =================== genstat = 1 charge = 1 mass = 1.40e-01 #decayLen = 1.e32 pdg = 211 # write a RunHeader run = IMPL.LCRunHeaderImpl() run.setRunNumber(0) run.parameters().setValue("Generator", model_name) run.parameters().setValue("PDG", pdg) wrt.writeRunHeader(run) for j in range(0, N): ### MC particle Collections colmc = IMPL.LCCollectionVec(EVENT.LCIO.MCPARTICLE) ## we are shooting 90 deg. HCAL px = 0.00 py = energy[j] pz = 0.00 vx = 30.00 vy = 1000.00 vz = 1000.00 epx = 50.00 epy = 3000.00 epz = 1000.00 momentum = arr.array('f', [px, py, pz]) vertex = arr.array('d', [vx, vy, vz]) endpoint = arr.array('d', [epx, epy, epz]) mcp = IMPL.MCParticleImpl() mcp.setGeneratorStatus(genstat) mcp.setMass(mass) mcp.setPDG(pdg) mcp.setMomentum(momentum) mcp.setCharge(charge) mcp.setVertex(vertex) mcp.setEndpoint(endpoint) colmc.addElement(mcp) evt = IMPL.LCEventImpl() evt.setEventNumber(j) evt.addCollection(colmc, "MCParticle") ### Calorimeter Collections col = IMPL.LCCollectionVec(EVENT.LCIO.SIMCALORIMETERHIT) flag = IMPL.LCFlagImpl(0) flag.setBit(EVENT.LCIO.CHBIT_LONG) flag.setBit(EVENT.LCIO.CHBIT_ID1) col.setFlag(flag.getFlag()) col.parameters().setValue( EVENT.LCIO.CellIDEncoding, 'system:0:5,module:5:3,stave:8:4,tower:12:5,layer:17:6,slice:23:4,x:32:-16,y:48:-16' ) evt.addCollection(col, "HcalBarrelRegCollection") for layer in range(48): ## loop over layers nx, nz = np.nonzero( showers[j][layer]) ## get non-zero energy cells for k in range(0, len(nx)): try: cell_energy = showers[j][layer][nx[k]][nz[k]] / 1000.0 tmp = cmap[(layer, nx[k], nz[k])] sch = IMPL.SimCalorimeterHitImpl() position = arr.array('f', [tmp[0], tmp[1], tmp[2]]) sch.setPosition(position) sch.setEnergy(cell_energy) sch.setCellID0(int(tmp[3])) sch.setCellID1(int(tmp[4])) col.addElement(sch) except KeyError: # Key is not present pass progress_bar.progress(int(j * 100 / N)) wrt.writeEvent(evt) progress_bar.empty() st.info('LCIO file was created: {}'.format(os.getcwd() + '/' + outfile)) status_text_rec = st.empty() status_text_rec.text("We are ready to run reconstruction via iLCsoft") wrt.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 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 run(): direc='incoherent_pair' infile=direc+'/'+'incoherent_pair.slcio' outfile = direc+'/'+'inco_pair_split.slcio' reader = LcioReader.LcioReader(infile) totalevent = reader.getNumberOfEvents() wrt = IOIMPL.LCFactory.getInstance().createLCWriter( ) wrt.open( outfile , EVENT.LCIO.WRITE_NEW ) newcol = 0 newevt = 0 for iev in range(totalevent): event = reader.next() run = IMPL.LCRunHeaderImpl() run.setRunNumber( iev ) run.parameters().setValue("Generator","CAIN") wrt.writeRunHeader( run ) try: mcps = event.getCollection('MCParticle') imcp=int(0) isubev=int(0) for mcp in mcps: if imcp%1000==0: if imcp>0: wrt.writeEvent( newevt ) isubev=isubev+1 newevt = IMPL.LCEventImpl() newevt.setEventNumber( isubev ) newcol = IMPL.LCCollectionVec( EVENT.LCIO.MCPARTICLE ) newevt.addCollection( newcol , "MCParticle" ) newcol.addElement( mcp ) imcp=imcp+1 wrt.writeEvent( newevt ) print 'written', isubev, 'subevents' print outfile +' is created' except: print 'error!' wrt.close()