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 drawEvents(fileName): # ced.ced_new_event() ced.ced_register_elements() ced.ced_client_init("localhost", 7286) rdr = LcioReader(fileName) for event in rdr: #------------------------------------------ ced.ced_new_event() drawEvent(event) ced.ced_send_event() #----------------------------------------- text = "event " + str(event.getEventNumber()) + " " + str( event.getRunNumber( )) + " - hit enter to draw next - [q] to quit ..." c = raw_input(text) if (c == 'q'): break
def addFile(self, fileName): if not self.reader: extension = fileName.split('.')[-1] if extension in ['slcio']: self.reader = LcioReader(fileName) elif extension in ['stdhep']: self.reader = StdHepReader(fileName) else: print 'Unknown extension for %s' % (extension) else: self.reader.addFile(fileName)
def init(): """Loads the required libraries and connects to glced.""" g.ced = load_library("libCED") g.marlinutil = load_library("libMarlinUtil") # g.cedviewer = load_library( "libCEDViewer" ) g.reader = LcioReader(g.fileName) g.ced.ced_register_elements() g.ced.ced_client_init(g.host, g.port) g.setColorScheme(g.colorScheme) g.objects = dict()
class EventReader: def __init__(self, fileName) : self._lcioReader = LcioReader( fileName ) self._event = None 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 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
angle = -angle return angle ############################################################################ ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Input global variables and data file ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ phi = 0 #angle of incidence - from particle gun phir = phi * math.pi / 180. #phi in radians pRange = 0.1 #Specify backscatter cut. Hits with solid angle outside phir +/- pRange are considered backscatter evtsPerEn = 500 inFile = 'reco_' + str(evtsPerEn) + 'a.GeVScan.' + str(phi) + 'phi.slcio' nmbEvents = 7 * evtsPerEn readerL = LcioReader(inFile) #create a reader ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create histograms and legends ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ energyArray = [1, 2, 5, 10, 20, 50, 100] #simulated energies in data file angleHistogram = [0] * 7 xHistogram = [0] * 7 yHistogram = [0] * 7 zHistogram = [0] * 7 backscatterEHist = [0] * 7 centerscatterEHist = [0] * 7 scatterLegend = [0] * 7 for i in range(7): angleHistogram[i] = TH1D( 'showerSpread' + str(i),
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()
# A. Steinhebel, University of Oregon # Nov. 2016 # # Input: Reconstructed .slcio file # Output: ROOT Histograms of the total energy deposited in each event, both for the entire calorimeter and individual layers # # #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ inFile = 'fileAfterRecon.slcio' # if the layer info of each hit is necessary for the analysis, set to "True". If not, set to "False" layerInfo = True #create a reader readerL = LcioReader(inFile) # create a histograms for the hit energies if layerInfo: nmbLayers = 31 layerHist = [0] * nmbLayers for i in range(nmbLayers): layerHist[i] = TH1D( 'DepositedEnergy', 'Energy per Event in Layer ' + str(i) + ';HCal Barrel Hit Energy [GeV];Entries', 10, 0, 0.1) hitEnergyHistogram = TH1D( 'TotalDepositedEnergy', 'Event Energy Deposit;HCAL Barrel Hit Energy [GeV];Entries', 100, 0., 1.) if not layerInfo:
else: print 'exit' break if __name__=='__main__': if len(sys.argv) == 4: fileName = sys.argv[1] minClusterSize = int(sys.argv[2]) maxClusterSize = int(sys.argv[3]) if minClusterSize > maxClusterSize: minClusterSize, maxClusterSize = maxClusterSize, minClusterSize if len(sys.argv) == 2: fileName = sys.argv[1] if len(sys.argv) == 1: fileName = "PDG211_50GeV_endcap_rec_0.slcio" #r = ROOT.TRandom(0) eventNumber = 1 reader = LcioReader( fileName ) print 'Loaded file: ', fileName event = None eveManager = ROOT.TEveManager.Create() readEvent()
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 __init__(self, fileName) : self._lcioReader = LcioReader( fileName ) self._event = None
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()
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Set global variables and import data files ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ phi=[0,3.75,7.5,9.3,11.25,15,18.75,22.5,30] #Each input data file contains showers at one phi location. This array defines which of those files are pulled into the code for analysis. Here, 14 files are pulled in - 7 phi locations for both 100 GeV and 10 GeV EM showers phi1=[x+0.5 for x in phi] #to offset the data points for easy visual comparison nmbEvents=500 #number of showers in each file nmbLayers=32 #number of ECal layers inFile=[0]*len(phi) readerL=[0]*len(phi) inFile1=[0]*len(phi) readerL1=[0]*len(phi) for i in range(len(phi)): inFile[i]='reco_500a.10GeV.'+str(phi[i])+'phi.slcio' readerL[i] = LcioReader(inFile[i]) inFile1[i]='reco_500a.100GeV.'+str(phi[i])+'phi.slcio' readerL1[i] = LcioReader(inFile1[i]) #All objects associated with 100 GeV runs has an additional "1" on their name, to differentiate from the 10 GeV-associated objects ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create histograms and legends to compare ECal and HCal hits as a function of phi at 100 GeV and 10 GeV #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ sumHistE=[0]*len(phi) sumHistH=[0]*len(phi) sumHistE1=[0]*len(phi) sumHistH1=[0]*len(phi) for i in range(len(phi)): sumHistE[i] = TH1D( 'totalEcal'+str(i), 'Event Energy Deposit (10 GeV photons, phi='+str(phi[i])+', theta=90);ECAL Barrel Hit Energy [GeV];Entries', 200, 0., 2. ) sumHistH[i] = TH1D( 'totalHcal'+str(i), 'Event Energy Deposit (10 GeV photons, phi='+str(phi[i])+', theta=90);HCAL Barrel Hit Energy [GeV];Entries', 20, 0., 0.1 ) sumHistE1[i] = TH1D( 'totalEcal'+str(i)+str(i), 'Event Energy Deposit (100 GeV photons, phi='+str(phi[i])+', theta=90);ECAL Barrel Hit Energy [GeV];Entries', 200, 0., 2. )