예제 #1
0
    random.seed()

    #========== particle properties ===================

    ecm_nominal = 500.0
    genstat = 1
    pdg = [13, -13]
    charge = [-1, 1]
    #pdg = 211
    mass = 0.105658

    #=================================================

    # write a RunHeader
    run = IMPL.LCRunHeaderImpl()
    run.setRunNumber(29999)  # Samae as processID
    run.parameters().setValue("Generator", "e+e- --> mu+mu- by SM. No ISR/BS")
    # run.parameters().setValue("PDG", pdg )
    # run.parameters().setValue("Charge", charge )
    # run.parameters().setValue("Mass", mass )
    wrt.writeRunHeader(run)
    #================================================

    for j in range(0, nevt):

        col = IMPL.LCCollectionVec(EVENT.LCIO.MCPARTICLE)
        evt = IMPL.LCEventImpl()

        evt.setEventNumber(j)
예제 #2
0
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()
예제 #3
0
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
예제 #4
0
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()
예제 #5
0
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()
예제 #6
0
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()
예제 #8
0
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()