示例#1
0
def getReader(
    datafile="rv02-00-01.sv02-00-01.mILD_l5_o1_v02.E500-TDR_ws.I106519.Pe2e2h.eL.pR.n001.d_dstm_10263_0.slcio",
    datadir="/hsm/ilc/grid/storm/prod/ilc/mc-opt-3/ild/dst-merged/500-TDR_ws/higgs_ffh/ILD_l5_o1_v02/v02-00-01/"
):
    '''
    Returns LcioReader of input file.   Prepared for interactive use.
  
    :params string datafile : input filename. The default is
    :params string datadir  : directory of input file. The default is
    '''
    inputpath = datadir + datafile
    return LcioReader.LcioReader(datadir + datafile)
示例#2
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
示例#3
0
#  For development, do 
#     python -i develop.py 
#  then, interactive session starts after executing this script


import os, pprint
from pyLCIO import EVENT, UTIL
from pyLCIO.io import LcioReader, StdHepReader
import ROOT
ROOT.gROOT.SetBatch()


# basepath = os.environ["HOME"] + "/Tutorial/data"
# infile = basepath + "/E250-TDR_ws.Pe2e2h.Gwhizard-1_95.eL.pR.I106479.001.stdhep"
infile = "sdelphes.E250-TDR_ws.Pe2e2h.eL.pR.I106479.0.slcio"

# reader = StdHepReader.StdHepReader()  # Create reader
reader = LcioReader.LcioReader()  # Create reader
reader.addFile(infile)

reader.skip(5)                        # Skip 5 records
event = reader.next()                 # Get event collection fron next event
params = event.getParameters()        # Get event paraneter
mcps = event.getCollection("MCParticles")  # Get MCParticle collection 
mcp = mcps.at(0)                          # Get element 0 of MCParticle collection

pfos = event.getCollection("PFOs")  # Get PFOs collection 
pfo = pfos.at(0)  # Get PFO

示例#4
0
    options = {
        "l5": {
            "color": 2,
            "legend": "l5_o1"
        },
        "s5": {
            "color": 3,
            "legend": "s5_o1"
        },
        "dbd": {
            "color": 4,
            "legend": "dbd"
        }
    }
    plotdata = []

    for key, infiles in files.iteritems():
        print key
        rootfile = "anal-" + key + ".root"
        if do_anal:
            reader = LcioReader.LcioReader()
            for infile in infiles:
                print "Reading " + infile
                reader.addFile(infile)

            makeNtuple(reader, rootFile=rootfile, maxRead=maxread)

        plotdata.append({"rootfile": rootfile, "option": options[key]})

    makePlots(plotdata)
示例#5
0
def printData(data, maxdump=1):
    ''' 
    Function: Read maxdump of records defined in data and print it contents.
  
    Input arguments: 
        data : Dictionay object describing data
                  data = {"alias": "alias of data file", "files": ["file1","file2",...] } 
        maxdump : Number of events to dump.
    
    '''

    dataname = data["alias"]
    print("==== Dump events from " + data["files"][0])

    reader = LcioReader.LcioReader()
    # reader = StdHepReader.StdHepReader()
    for infile in data["files"]:
        print("Adding " + infile)
        reader.addFile(infile)

    print("There are " + str(reader.getNumberOfEvents()) + " in this file.")

    for idx, event in enumerate(reader):
        if maxdump > 0 and idx >= maxdump:
            break

        print("\n=== Reading:" + str(idx + 1) + "-th record. ==============")
        print("### Event header ", )
        print("    Run number=%d  Event number=%d " %
              (event.getRunNumber(), event.getEventNumber()))
        print("### Event parameters ")
        #  Dump event parameters
        strvec = ROOT.vector("string")()
        params = event.getParameters()
        #### List Float parameter values
        for key in params.getFloatKeys(strvec):
            print("    Float parameters " + str(key) + " = " +
                  str(params.getFloatVal(key)))
    #### List Int parameter values
        strvec.clear()
        for key in params.getIntKeys(strvec):
            print("    Int parameters " + str(key) + " = " +
                  str(params.getIntVal(key)))
    #### List String parameter values
        strvec.clear()
        for key in params.getStringKeys(strvec):
            print("    String parameters " + str(key) + " = " +
                  str(params.getStringVal(key)))

    #  print collections in the event
        print("### Collections in this event")
        cols = event.getCollectionNames()
        for col in cols:
            print("  " + col)

        mcps = event.getCollection("MCParticle")
        print("Number of MCParticle elements =" + str(len(mcps)))

        # Loop over all elements of MCParticle collection
        # for ip in range(0, mcps.getNumberOfElements()):
        #    mcp = mcps.at(ip)
        for ip, mcp in enumerate(mcps):
            pv = mcp.getLorentzVec()
            pdgid = mcp.getPDG()
            charge = mcp.getCharge()
            status = mcp.getGeneratorStatus()
            parents = mcp.getParents()
            daughters = mcp.getDaughters()
            nb_daughters = len(daughters)

            # print data
            print("#ip=%d: id=%d pdgid=%d status=%d charge=%d #daughters=%d " %
                  (ip, mcp.id(), pdgid, status, charge, nb_daughters),
                  end="")
            if len(parents) > 0:
                print(" parents=", end="")
                for parent in parents:
                    print("%d " % parent.id(), end="")
            if nb_daughters > 0:
                print(" daughters:(id,pdg)=", end="")
                for dau in daughters:
                    print("(%d,%d)" % (dau.id(), dau.getPDG()), end="")
            print("")
            print(" (E,px,py,pz)=(%g,%g,%g,%g)" %
                  (pv.E(), pv.Px(), pv.Py(), pv.Pz()))

    del reader  # Remove reader
示例#6
0
def makeNtuple(data, maxread=1000, genmeta_json=""):
    '''
    Function: Read maxread of events from data and create a root file of ntuple.  
   
    Inputs:
       data : Dictionay object describing data
              data = {"alias": "alias of data file", "files": ["file1","file2",...]}
       maxread : Number of events to be read from files.
       genmeta_json : A generator meta information in json format.
              If not given, read from os.environ["HOME"]+"/Tutorial/data/genmetaByID.json"
              The standard one is at https://ild.ngt.ndu.ac.jp/CDS/files/genmetaByID.json

    Output: 
       Returns dictionary consists as follows.
       ret = {"cm_energy":Center of mass energy, extracted from the first file name , 
              "cross_section":cross section of this process, 
              "nread":Number of events read from an input stream
              "intlumi":Integrated luminosity of analized events. 
              "rootfile":root_file_name }
       

    '''

    # =======================================================================
    # Preparing to read and analize files
    # =======================================================================
    ##  Create a root file.
    dataname = data["alias"]
    rootfile = dataname + ".root"
    rfile = ROOT.TFile(rootfile, "RECREATE")
    ntev = ROOT.TNtuple("nt", dataname + " analysis",
                        "emum:emup:mmumu:mmiss:mrest")
    print("==== Creating root file " + str(rootfile))

    ##  Get enrgy and process id from filename
    filemeta = decodeFileName(os.path.basename(data["files"][0]))
    ecm = float(filemeta["E"].split("-")[0])  # Get Energy from file name

    ## Get cross_section from input data or genmeta file.
    if "cross_section" in data:
        cross_section = float(data["cross_section"])
        print("Cross section of input file is %f " % (cross_section))
    else:
        ##  Getcross section from a genmeta json file.
        procid = filemeta["I"]
        genmeta_json = os.environ["HOME"] + "/Tutorial/data/genmetaByID.json"
        if not os.path.exists(genmeta_json):
            print("ERROR : " + genmeta_json + " does not exist.")
            exit(0)
        genmeta = json.load(open(genmeta_json))
        cross_section = float(genmeta[str(procid)]["cross_section_in_fb"])
        print("Cross section of procid %s is %f " % (procid, cross_section))

    # ========================================================================
    # Create reader
    # ========================================================================
    reader = LcioReader.LcioReader()
    #######  reader = StdHepReader.StdHepReader()  # Memory leak ?  Not work to read too many files.
    for infile in data["files"]:
        print("Adding " + infile)
        reader.addFile(infile)

    nbevents = reader.getNumberOfEvents() if maxread == 0 else maxread
    print("There are " + str(nbevents) + " events in this file.")

    # =======================================================================
    # Read events in the file, and fill Ntuple
    # =======================================================================
    nread = 0
    for idx, event in enumerate(reader):
        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, ecm)

        mcp = event.getCollection("MCParticle")

        # Loop over all particle in MCParticle collection.
        # and find mu+ and mu- of the highest energy
        for mcp in event.getCollection("MCParticle"):
            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()  # Mass recoil to mu+, mu-
        restmas = (psum - pmum - pmup).M()  # Mass other than mu+, mu-

        # Fiil variables in Ntuple
        ntev.Fill(float(pmum.E()), float(pmup.E()), float(mumumas),
                  float(missmas), float(restmas))

        if nread >= nbevents:
            print("### Completed last event. Nread is " + str(nread))
            break

    print("### Read " + str(nread) + " events")
    intlumi = float(nread) / cross_section if float(
        cross_section) > 0.0 else 0.0
    rfile.Write()
    rfile.Close()  # Close root file

    ret = {
        "cm_energy": ecm,
        "cross_section": cross_section,
        "nread": nread,
        "intlumi": intlumi,
        "rootfile": rootfile
    }
    del reader

    return ret
示例#7
0
from pyLCIO.io import LcioReader

infile = "/".join([
    "/hsm/ilc/grid/storm/prod/ilc/mc-opt-3/ild/dst-merged/500-TDR_ws/higgs_ffh/ILD_l5_o1_v02/v02-00-01",
    "rv02-00-01.sv02-00-01.mILD_l5_o1_v02.E500-TDR_ws.I106523.Pnnh.eL.pR.n005.d_dstm_10763_18.slcio"
])

reader = LcioReader.LcioReader(infile)
event = reader.next()

reco_mc_links = event.getCollection("RecoMCTruthLink")

lnk = reco_mc_links.getElementAt(0)  # Get First element

# help(lnk)  # Get help of link object
# lfrom = lnk.getFrom()
# lweight = lnk.getWeight()
# help(lweight)
# lto = lnk.getTo()
# help(lto)   # Get help of to object

for lnk in reco_mc_links:
    mcp = lnk.getTo()
    weight = lnk.getWeight()
    print "Linked to MCParticle, PDG=" + str(
        mcp.getPDG()) + "  weight=" + str(weight)
示例#8
0
ROOT.gROOT.SetBatch()
import pprint

#======================================================#
if __name__ == '__main__':

    # reader = getReader()
    datadir = "/hsm/ilc/grid/storm/prod/ilc/mc-opt-3/ild/dst-merged/1-calib/single/ILD_l5_o1_v02_nobg/v02-00-01/"
    # infile = "rv02-00-01.sv02-00-01.mILD_l5_o1_v02_nobg.E1-calib.I110131.Ps_22_p010_t5-14.e0.p0.n001.d_dstm_10752_0.slcio"
    infile = "rv02-00-01.sv02-00-01.mILD_l5_o1_v02_nobg.E1-calib.I110141.Ps_22_p010.e0.p0.n001.d_dstm_10752_0.slcio"
    fullpath = datadir + infile
    if not os.path.exists(fullpath):
        print "Error: input file, " + fullpath + " does not exist."
        exit(-1)

    reader = LcioReader.LcioReader(fullpath)
    maxevt = reader.getNumberOfEvents()
    print "There are " + str(maxevt) + " events in the file."

    tf = ROOT.TFile("ntuple.root", "recreate")
    nt = ROOT.TNtuple("nt", "sample ntuple", "nevt:chg:ptype:e:px:py:pz")

    maxread = 1000
    nevt = 0

    for idx, event in enumerate(reader):
        ''' print collections in the event '''

        if nevt >= maxread:
            break
        nevt += 1
示例#9
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()