コード例 #1
0
def writeHeader(outfile_name, edmfile, onlyWeights=True):
    with open(outfile_name, "w") as outfile:
        outfile.write("# ---> From file %s" % edmfile)

        source = "externalLHEProducer"
        #source = "source"
        runs = Runs(edmfile)
        run = runs.__iter__().next()
        runInfoHandle = Handle("LHERunInfoProduct")
        run.getByLabel(source, runInfoHandle)
        runInfo = runInfoHandle.product()
        foundrwgt = False
        IPython.embed()
        for i, h in enumerate(runInfo.headers_begin()):
            print i, h, runInfo.headers_size()
            if i == runInfo.headers_size() or i > 20:
                break
            # For some of the 7_1_X samples, the header is added for each LHE file, read only the first copy
            if "initrwgt" in str(h.tag()):
                if foundrwgt:
                    break
                foundrwgt = True
            if not foundrwgt and onlyWeights:
                continue
            for line in h.lines():
                outfile.write(line)
コード例 #2
0
def getWeightIDs(edm_file_name) :
    if "/store/" in edm_file_name :
        edm_file_name = "/".join(["root://cmsxrootd.fnal.gov/",
            edm_file_name])
    elif not os.path.isfile(edm_file_name) :
        raise FileNotFoundException("File %s was not found." % edm_file_name)
    runs = Runs(edm_file_name)
    runInfoHandle = Handle("LHERunInfoProduct")
    lheLabel = WeightTools.getLHEInfoTag(runs, runInfoHandle)
    run = runs.__iter__().next()
    run.getByLabel(lheLabel, runInfoHandle)
    lheStuff = runInfoHandle.product()
    lines = []
    for i, h in enumerate(lheStuff.headers_begin()) :
        if i == lheStuff.headers_size() :
            break
        hlines = []
        isWeights = False
        for line in h.lines() :
            hlines.append(line)
            if 'weightgroup' in line :
                isWeights = True
        if isWeights :
            lines.extend(hlines)
            break
    return ''.join(lines).rstrip("<")
コード例 #3
0
ファイル: EDMWeightInfo.py プロジェクト: yw5mj/cmgtools-lite
def getWeightIDs(edm_file_name):
    if "/store/" in edm_file_name:
        #edm_file_name = "/".join(["root://cmsxrootd.fnal.gov/",
        edm_file_name = "/".join(
            ["root://cms-xrd-global.cern.ch/", edm_file_name])
    elif not os.path.isfile(edm_file_name):
        raise FileNotFoundException("File %s was not found." % edm_file_name)
    runs = Runs(edm_file_name)
    runInfoHandle = Handle("LHERunInfoProduct")
    lheLabel = WeightTools.getLHEInfoTag(runs, runInfoHandle)
    run = runs.__iter__().next()
    run.getByLabel(lheLabel, runInfoHandle)
    lheStuff = runInfoHandle.product()

    # id number of PDF used
    pdfidx = lheStuff.heprup().PDFSUP.first
    print '%% Id number of PDF used: ' + str(pdfidx)

    lines = []
    for i, h in enumerate(lheStuff.headers_begin()):
        if i == lheStuff.headers_size():
            break
        hlines = []
        isWeights = False
        for line in h.lines():
            hlines.append(line)
            if 'weightgroup' in line:
                isWeights = True
        if isWeights:
            lines.extend(hlines)
    #        break
    return ''.join(lines).rstrip("<")
コード例 #4
0
def readHeader(edm_file_name, tag):
    if "/store/" in edm_file_name[:7]:
        edm_file_name = "/".join(
            ["root://cms-xrd-global.cern.ch/", edm_file_name])
    elif not os.path.isfile(edm_file_name):
        raise FileNotFoundException("File %s was not found." % edm_file_name)

    full_header = not tag

    runs = Runs(edm_file_name)
    runInfoHandle = Handle("LHERunInfoProduct")
    lheLabel = getLHEInfoTag(runs, runInfoHandle)
    run = runs.__iter__().next()
    run.getByLabel(lheLabel, runInfoHandle)
    lheStuff = runInfoHandle.product()
    lines = []
    for i, h in enumerate(lheStuff.headers_begin()):
        if i == lheStuff.headers_size():
            break
        hlines = []
        toStore = False
        for line in h.lines():
            hlines.append(line)
            if tag in line or full_header:
                toStore = True
        if toStore:
            lines.extend(hlines)
            if not full_header:
                break
    return ''.join(lines).rstrip("<")
コード例 #5
0
ファイル: DumpLumiCount.py プロジェクト: yimuchen/UserUtils
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument( 'inputfiles', metavar='N', type=str, nargs='+',
                    help='List of input files to use')
    args = parser.parse_args()

    numofevts = 0
    numoflumis = 0
    numofruns  = 0

    # Using wc style output format
    print "{:>8s} {:>8s} {:>8s}   {}".format("Events","Lumis", "Runs", "Files")
    fmtstr = "{:>8d} {:>8d} {:>8d}   {}"

    for inputfile in args.inputfiles:
        ev = Events( inputfile )
        lm = Lumis( inputfile )
        rn = Runs( inputfile )
        numofevts = numofevts + ev.size()
        numoflumis = numoflumis + lm._lumi.size()
        numofruns  = numofruns + rn._run.size()
        print fmtstr.format(
            ev.size(),
            lm._lumi.size(),
            rn._run.size(),
            inputfile
             )

    print fmtstr.format( numofevts,
        numoflumis,
        numofruns,
        "total({} files)".format(len(args.inputfiles))
    )
コード例 #6
0
ファイル: MCWeighter.py プロジェクト: pallabidas/cmg-cmssw
    def __init__(self, cfg_ana, cfg_comp, looperName):
        super(MCWeighter, self).__init__(cfg_ana, cfg_comp, looperName)
        self.mcweight = 1.
        if hasattr(cfg_ana, 'countSign'):
            self.countSign = cfg_ana.countSign
        else:
            self.countSign = False

        self.runs = Runs(cfg_comp.files)
コード例 #7
0
def getHeader(filename, weightsonly=True):
    LHEProduct, LHEProductLabel = Handle(
        "LHERunInfoProduct"), "externalLHEProducer"
    runs = Runs(filename)
    for ir, run in enumerate(runs):
        run.getByLabel(LHEProductLabel, LHEProduct)
        var = LHEProduct.product()
        test = var.headers_begin()

        header = []
        while (test != var.headers_end()):
            for line in range(test.lines().size()):
                header.append(test.lines().at(line)[0:-1].strip())
            test = test + 1
    if weightsonly == True:
        return getonlyweights(header)
    else:
        return header
コード例 #8
0
    def beginLoop(self, setup):
        '''
        Compute the weight just once at the beginning of the loop.
        Warning: this works correctly only the file(s) is(are) 
        completely processed.
        '''
        super(MCWeighter, self).beginLoop(setup)

        # runsHandle = Handle('std::vector<double>')
        # runsLabel = ('genEvtWeightsCounter', 'genWeight', 'H2TAUTAU')

        # Make it compatible with SkimAnalyzerCount
        self.counters.addCounter('SkimReport')
        self.count = self.counters.counter('SkimReport')
        if self.cfg_comp.isMC:
            self.count.register('Sum Weights')
            self.count.register('Sum Unity Weights')
        else:
            return

        self.runs = Runs(self.cfg_comp.files)
        print 'Files', self.cfg_comp.files

        runsHandle = Handle('double')
        runsLabel = ('genEvtWeightsCounter', '', 'H2TAUTAU')

        runsHandleU = Handle('double')
        runsLabelU = ('genEvtWeightsCounter', 'sumUnityGenWeights', 'H2TAUTAU')

        mcw = []
        mcuw = []
        for run in self.runs:
            run.getByLabel(runsLabel, runsHandle)
            mcw += [runsHandle.product()[0]]
            run.getByLabel(runsLabelU, runsHandleU)
            mcuw += [runsHandleU.product()[0]]

        # self.mcweight = numpy.mean(mcw)

        self.count.inc('Sum Weights', numpy.sum(mcw))
        self.count.inc('Sum Unity Weights', numpy.sum(mcuw))
コード例 #9
0
for key in samples.keys():
    print '#################################'
    print ' LHE Info for dataset: '
    print '    '+key
    print '#################################'
#    print EDMWeightInfo.getWeightIDs(samples[key])

    edm_file_name = samples[key]

    if "/store/" in edm_file_name :
        #edm_file_name = "/".join(["root://cmsxrootd.fnal.gov/",
        edm_file_name = "/".join(["root://cms-xrd-global.cern.ch/",
            edm_file_name])
    elif not os.path.isfile(edm_file_name) :
        raise FileNotFoundException("File %s was not found." % edm_file_name)
    runs = Runs(edm_file_name)
    runInfoHandle = Handle("LHERunInfoProduct")
    run = runs.__iter__().next()
    run.getByLabel('externalLHEProducer', runInfoHandle)
    lheStuff = runInfoHandle.product()

    # id number of PDF used
    pdfidx = lheStuff.heprup().PDFSUP.first
    pdfname = LHAID[str(pdfidx)] if pdfidx!=-1 else ' undefined, please check the LHE header.'

    print '## Id number of PDF used: '+str(pdfidx)
    print '## PDF set name: '+pdfname
    print '####'

    lines = []
    for i, h in enumerate(lheStuff.headers_begin()) :
コード例 #10
0
    #or list = [weight_id, mu_R, mu_F] for scale-variation


filename = "/pnfs/desy.de/cms/tier2/store/user/hmildner/ttHTobb_M125_13TeV_powheg_pythia8/Boostedv2MiniAOD/151017_154254/0000/BoostedTTH_MiniAOD_13.root"
#filename = "/pnfs/desy.de/cms/tier2//store/user/hmildner/ttHToNonbb_M125_13TeV_powheg_pythia8/Boostedv2MiniAOD/151017_154312/0000/BoostedTTH_MiniAOD_1.root"
#filename = "/pnfs/desy.de/cms/tier2/store/mc/RunIISpring15MiniAODv2/ttHToNonbb_M125_13TeV_powheg_pythia8/MINIAODSIM/74X_mcRun2_asymptotic_v2-v1/10000/02FE2DB6-D06D-E511-8BC7-0025905C431C.root"
#filename = "/pnfs/desy.de/cms/tier2/store/user/hmildner/TT_TuneCUETP8M1_13TeV-powheg-pythia8/Boostedv2MiniAOD/151017_154450/0000/BoostedTTH_MiniAOD_101.root"
#filename = "/pnfs/desy.de/cms/tier2//store/user/hmildner/TT_TuneCUETP8M1_13TeV-powheg-pythia8/Boostedv2MiniAOD/151017_154450/0000/BoostedTTH_MiniAOD_204.root"

outputname = "scales_BoostedTTH_MiniAOD_13_2.root"
#outputname = "scales_BoostedTTH_MiniAOD_1.root"
#outputname = "scales_BoostedTTH_MiniAOD_101.root"
#outputname = "scales_BoostedTTbar_MiniAOD_204.root"

events = Events(filename)
runs = Runs(filename)

#Getting weight number for PDF:
weightnum = True

if (weightnum):
    for ir, run in enumerate(runs):
        if ir > 10: break
        run.getByLabel(LHEProductLabel, LHEProduct)

        ##############################

        #read header and print the part about the weights
        var = LHEProduct.product()

        test = var.headers_begin()
コード例 #11
0
import ROOT
import sys
from DataFormats.FWLite import Events, Runs, Handle

runs = Runs([
    "root://cms-xrd-global.cern.ch//store/mc/RunIISummer16MiniAODv2/WGToLNuG_01J_5f_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/40000/10BFD217-3702-E811-A0B4-0CC47A009E24.root"
])

handleLHERunInfoProduct = Handle("LHERunInfoProduct")
labelLHERunInfoProduct = ("externalLHEProducer")

found_run_card = False

for run in runs:

    run.getByLabel(labelLHERunInfoProduct, handleLHERunInfoProduct)

    header = handleLHERunInfoProduct.product().headers_begin()

    while header != handleLHERunInfoProduct.product().headers_end():

        if not ((not found_run_card and header.tag() == "MGRunCard")
                or header.tag() == "initrwgt"):
            header = header + 1
            continue

        if header.tag() == "MGRunCard":
            found_run_card = True

        print "len(header.lines()) = " + str(len(header.lines()))
コード例 #12
0
from DataFormats.FWLite import Handle, Runs
import ROOT
import sys

lheruninfo=Handle('LHERunInfoProduct')
runs=Runs(sys.argv[1])
for r in runs:
    r.getByLabel('externalLHEProducer',lheruninfo)
    #r.getByLabel('source',lheruninfo)
    it=lheruninfo.product().headers_begin()
    while it!=lheruninfo.product().headers_end():
        lines=it.lines()
        allowPrint=False
        wgtCtr=0
        for i in xrange(0,lines.size()):
            linestr=lines.at(i)
            if '<weightgroup' in linestr : allowPrint=True
            if '</weightgroup' in linestr : allowPrint=False
            if not allowPrint : continue
            if 'weightgroup' in linestr :
                print '*'*50
                print linestr
                print '*'*50
            else:
                if not 'weight' in linestr : continue
                print wgtCtr,linestr
                wgtCtr+=1
        it.next()
コード例 #13
0
import ROOT
import sys
from DataFormats.FWLite import Events, Handle, Runs

from math import hypot, pi

events = Events (['./nomadspin.root'])
runs = Runs (['./nomadspin.root'])

file_out = open('fail.txt','w')

geninfo,geninfoLabel = Handle("GenEventInfoProduct"), "generator"
lheinfo,lheinfoLabel = Handle("LHEEventProduct"), "externalLHEProducer"
lheruninfo,lheruninfoLabel = Handle("LHERunInfoProduct"), "externalLHEProducer"
handlePruned  = Handle ("std::vector<reco::GenParticle>")
labelPruned = ("prunedGenParticles")

# loop over events
count= 0
countweighted = 0

count = count+1
runs.getByLabel(lheruninfoLabel,lheruninfo)
lherun = lheruninfo.product()
iiter = lherun.headers_begin()
print len(iiter.lines())
for ii in range(0,lherun.headers_size()-1):
    if ii<57: continue
#    if 'initrwgt' not in iiter.tag(): continue
    print 'tag:', iiter.tag()
    for iline in range(0,iiter.lines().size()):
コード例 #14
0
class LHEWeightAnalyzer(Analyzer):
    """Read the WeightsInfo objects of the LHE branch and store them
       in event.LHE_weights list.

       If the WeightsInfo.id is a string, replace it with an integer.

       So far the only allowed string format is "mg_reweight_X",
       which gets stored as str(10000+int(X))

       If w.id is an unknown string or anything but a string or int,
       a RuntimeError is raised.
    """
    def __init__(self, cfg_ana, cfg_comp, looperName):
        super(LHEWeightAnalyzer, self).__init__(cfg_ana, cfg_comp, looperName)
        self.index = []

    def declareHandles(self):
        super(LHEWeightAnalyzer, self).declareHandles()
        self.mchandles['LHEweights'] = AutoHandle('externalLHEProducer',
                                                  'LHEEventProduct',
                                                  mayFail=True,
                                                  fallbackLabel='source',
                                                  lazy=False)

    def beginLoop(self, setup):
        super(LHEWeightAnalyzer, self).beginLoop(setup)

        self.run = Runs(self.cfg_comp.files[0])
        runsHandle = Handle('LHERunInfoProduct')
        self.run.getByLabel('externalLHEProducer', runsHandle)

        self.scale = TH1F('scale', 'scale', 10, 0, 10)
        self.pdf = TH1F('pdf', 'pdf', 101, 0, 101)
        self.alpha_s = TH1F('alpha_s', 'alpha_s', 2, 0, 2)

        iterator = runsHandle.product().headers_begin()

        # scan iterator so that it includes weight information
        for it in range(100):
            flag = False
            for itt in iterator.base().lines():
                print itt
                if itt.find('weight id') != -1: flag = True

            if flag:
                break
            else:
                iterator.next()
        else:
            print 'Could not find any weight information !!'

        self.index = []
        self.pdfindex = []
        self.alphaindex = []

        idx = 0

        for a in iterator.base().lines():
            if a.find('weight id') == -1: continue
            print a

            # For Higgs signal
            #            if (a.find('muR')!=-1 and a.find('muF')!=-1 and a.find('muR=2 muF=0.5')==-1 and a.find('muR=0.5 muF=2')==-1):
            # For LO Z->tautau
            if (a.find('mur') != -1 and a.find('muf') != -1
                    and a.find('mur=2 muf=0.5') == -1
                    and a.find('mur=0.5 muf=2') == -1):

                self.index.append(idx)

# For Higgs signal
#            if a.find('PDF')!=-1:
#                flag = False
#                for weight_id in range(260000, 260101):
#                    if a.find(str(weight_id))!=-1: flag = True
#
#                if flag:
#                    self.pdfindex.append(idx)
#
#            if a.find('PDF')!=-1 and a.find('265000')!=-1 or a.find('266000')!=-1:
#                self.alphaindex.append(idx)

# For LO Z->tautau
            if a.find('Member') != -1:
                flag = False
                for weight_id in range(10, 111):
                    if a.find('id=\"' + str(weight_id) + '\"') != -1:
                        flag = True

                if flag:
                    self.pdfindex.append(idx)


#            if a.find('pdf')!=-1 and a.find('292301')!=-1 or a.find('292302')!=-1:

            idx += 1

        self.alphaindex.append(0)
        self.alphaindex.append(1)

        print 'scale variation index: ', self.index, 'len', len(self.index)
        print 'pdf variation index: ', self.pdfindex, 'len', len(self.pdfindex)
        print 'alpha variation index: ', self.alphaindex, 'len', len(
            self.alphaindex)

    def process(self, event):
        self.readCollections(event.input)

        #        import pdb; pdb.set_trace()
        # if not MC, nothing to do
        if not self.cfg_comp.isMC:
            return True

        # Add LHE weight info

        event.LHE_originalWeight = 1.0

        if self.mchandles['LHEweights'].isValid() == False:
            print 'LHE information not available !'
            return True

        event.LHE_originalWeight = self.mchandles['LHEweights'].product(
        ).originalXWGTUP()
        event.scale_variation = []
        event.pdf_variation = []
        event.alpha_variation = []

        for ii, windex in enumerate(self.index):

            LHE_weight = self.mchandles['LHEweights'].product().weights(
            )[windex].wgt
            event.scale_variation.append(LHE_weight / event.LHE_originalWeight)

            self.scale.Fill(ii, LHE_weight / event.LHE_originalWeight)

        for ii, windex in enumerate(self.pdfindex):

            LHE_weight = self.mchandles['LHEweights'].product().weights(
            )[windex].wgt
            event.pdf_variation.append(LHE_weight / event.LHE_originalWeight)

            self.pdf.Fill(ii, LHE_weight / event.LHE_originalWeight)

        for ii, windex in enumerate(self.alphaindex):

            LHE_weight = self.mchandles['LHEweights'].product().weights(
            )[windex].wgt
            event.alpha_variation.append(LHE_weight / event.LHE_originalWeight)

            self.alpha_s.Fill(ii, LHE_weight / event.LHE_originalWeight)

        return True

    def write(self, setup):
        #        import pdb; pdb.set_trace()
        super(LHEWeightAnalyzer, self).write(setup)

        self.rootfile = TFile('/'.join([self.dirName, 'weight.root']),
                              'recreate')

        self.alpha_s.Write()
        self.pdf.Write()
        self.scale.Write()
        self.rootfile.Write()
        self.rootfile.Close()
コード例 #15
0
from DataFormats.FWLite import Handle, Runs
import ROOT

lheruninfo=Handle('LHERunInfoProduct')

runs=Runs('root://eoscms//eos/cms/store/group/phys_top/gkrintir/TopHI/HINPbPbAutumn18DR_skims/WJetsToLNu_TuneCP5_HydjetDrumMB_5p02TeV-amcatnloFXFX-pythia8/B02D2CBB-AFBB-B741-B810-6D00B71B2AAD.root')
#runs=Runs('root://cms-xrd-global.cern.ch//store/himc/HINPbPbAutumn18DR/TT_TuneCP5_HydjetDrumMB_5p02TeV-powheg-pythia8/AODSIM/mva98_103X_upgrade2018_realistic_HI_v11-v1/270000/EF779097-4F67-024E-A13E-5EE36B3E5101.root')
for r in runs:
    r.getByLabel('externalLHEProducer',lheruninfo)
    it=lheruninfo.product().headers_begin()
    while it!=lheruninfo.product().headers_end():
        lines=it.lines()
        allowPrint=False
        wgtCtr=0
        for i in xrange(0,lines.size()):
            linestr=lines.at(i)
            if '<weightgroup' in linestr : allowPrint=True
            if '</weightgroup' in linestr : allowPrint=False
            if not allowPrint : continue
            if 'weightgroup' in linestr :
                print '*'*50
                print linestr
                print '*'*50
            else:
                if not 'weight' in linestr : continue
                print wgtCtr,linestr
                wgtCtr+=1
        it.next()
コード例 #16
0
#files.append('root://xrootd.unl.edu//store/mc/RunIISpring16MiniAODv2/RSGluonToTT_M-1000_TuneCUETP8M1_13TeV-pythia8/MINIAODSIM/PUSpring16RAWAODSIM_reHLT_80X_mcRun2_asymptotic_v14-v1/20000/02E562CD-9038-E611-A654-B083FED13803.root')
#files.append('root://xrootd.unl.edu//store/mc/RunIISpring16MiniAODv2/TTJets_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/PUSpring16RAWAODSIM_reHLT_80X_mcRun2_asymptotic_v14-v1/00000/001AFDCE-C33B-E611-B032-0025905D1C54.root')
#files.append('root://cmsxrootd.fnal.gov///store/user/jdolen/B2G2016/ZprimeToTT_M-3000_W-30_TuneCUETP8M1_13TeV-madgraphMLM_RunIISpring16MiniAODv2-PUSpring16RAWAODSIM_reHLT_MINIAOD.root')
#files.append('root://xrootd.unl.edu//store/mc/RunIISpring15DR74/ZprimeToTT_M-3000_W-900_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/AODSIM/Asympt25ns_MCRUN2_74_V9-v1/50000/02C3658C-8B08-E511-9624-AC853D9DACE3.root')
Nruns = 0
#for ifile in filesraw : #{ Loop over text file and find root files linked
#if len( ifile ) > 2 :
#s = ifile.rstrip()
#files.append( s )
#print 'Added ' + s
#} End loop over txt file

# loop over files
for ifile in files:  #{ Loop over root files
    print 'Processing file ' + ifile
    runs = Runs(ifile)
    if options.maxruns > 0 and Nruns > options.maxruns:
        break

    # Make sure the handles we want are in the files so we can
    # avoid leaking memory
    readFilters = True

    #NrunsInFile = runs.size()
    #if NrunsInFile <= 0 :
    #continue
    # loop over runs in this file
    for run in runs:  #{ Loop over runs in root files

        #Event weight errors
        #gotLHE = event.getByLabel( l_lhe, h_lhe )
コード例 #17
0
ファイル: inspect_edObject.py プロジェクト: bainbrid/.bin
pick = False
if args.pick:
   pick = tuple([int(i) for i in args.pick.split(':')])

import ROOT
import pprint
from DataFormats.FWLite import Events, Handle, Runs
from pdb import set_trace
ROOT.gROOT.SetBatch()

fname = args.file
if fname.startswith('/store/'):
   fname = 'root://cmsxrootd-site.fnal.gov/%s' % fname

events = Runs(fname) if args.inrun else Events(fname)
iterator = events.__iter__()
handle = Handle(args.handle)
keep_going = True
loop = 0

while keep_going:
   evt = iterator.next()
   loop += 1
   get_result = evt.getByLabel(args.label, handle)
   obj = handle.product()
   if pick:
      evtid = (evt.eventAuxiliary().run(), evt.eventAuxiliary().luminosityBlock(), evt.eventAuxiliary().event())
      if evtid == pick:
         keep_going = False
   else:
コード例 #18
0
                                          composite_dataset_definitions)

fout = open("configurationOptionsXSecs.py", "w")
content = "############################################################# \n"
content += "# Cross sections below obatined with crossSectionExtractor.py \n"

for dataset in split_datasets:
    datasetName = dataset_names[dataset]
    fileList = os.popen('das_client.py --query="file dataset=' + datasetName +
                        '" --limit 0').read().split('\n')
    xrootdPath = 'root://cmsxrootd.fnal.gov/' + str(fileList[0])
    f = TFile.Open(xrootdPath)  # Check that file is valid
    if not f:
        print "ERROR:  Could not open file: ", xrootdPath
        continue
    runs = Runs(xrootdPath)
    handle = Handle('GenRunInfoProduct')
    label = ("generator", '', 'SIM')
    for run in runs:
        run.getByLabel(label, handle)
        runGenInfo = handle.product()
        print "crossSection of      " + str(dataset) + " is: " + str(
            runGenInfo.crossSection())
        print "internal xsec of     " + str(dataset) + " is: " + str(
            runGenInfo.internalXSec().value())
        print "external LO xsec of  " + str(dataset) + " is: " + str(
            runGenInfo.externalXSecLO().value())
        print "external NLO xsec of " + str(dataset) + " is: " + str(
            runGenInfo.externalXSecNLO().value())
        print "filterEfficiency of  " + str(dataset) + " is: " + str(
            runGenInfo.filterEfficiency())
コード例 #19
0
        totalPatOutput += patFilterInfoH.product().numEventsPassed()
        
        fe = simFilterInfoH.product().filterEfficiency()
        sc = patFilterInfoH.product().numEventsTried()/(1.*simFilterInfoH.product().numEventsPassed())
        
        w = fe/(sc*simFilterInfoH.product().numEventsTried())
        weights.append(w)
        print w
    print 'Mean',sum(weights)/(1.*len(weights))
    
    genFilterEfficiency = totalSimInput/(1.*totalSimOutput)
    scalingFraction = totalPatInput/(1.*totalSimOutput)    
    print totalSimInput,totalSimOutput,totalPatInput,totalPatOutput,genFilterEfficiency,scalingFraction

    options.parseArguments()
    runs = Runs(options)
    
    genInfoH = Handle('GenRunInfoProduct')
    cross_sections = []
    for run in runs:
        run.getByLabel('generator',genInfoH)
        cross_sections.append(genInfoH.product().crossSection())
    genCrossSection = sum(cross_sections)/(1.*len(cross_sections))
    print genCrossSection
    
    intLumi = 2005.2
    #eventWeight = intLumi*(genCrossSection*genFilterEfficiency)/(scalingFraction*totalSimInput)
    eventWeight = (genFilterEfficiency)/(scalingFraction*totalSimInput)
    print 'Event Weight',eventWeight

    # use Varparsing object
コード例 #20
0
ファイル: printLHEInfo.py プロジェクト: yw5mj/cmgtools-lite
for key in samples.keys():
    print '#################################'
    print ' LHE Info for dataset: '
    print '    ' + key
    print '#################################'
    #    print EDMWeightInfo.getWeightIDs(samples[key])

    edm_file_name = samples[key]

    if "/store/" in edm_file_name:
        #edm_file_name = "/".join(["root://cmsxrootd.fnal.gov/",
        edm_file_name = "/".join(
            ["root://cms-xrd-global.cern.ch/", edm_file_name])
    elif not os.path.isfile(edm_file_name):
        raise FileNotFoundException("File %s was not found." % edm_file_name)
    runs = Runs(edm_file_name)
    runInfoHandle = Handle("LHERunInfoProduct")
    run = runs.__iter__().next()
    run.getByLabel('externalLHEProducer', runInfoHandle)
    lheStuff = runInfoHandle.product()

    # id number of PDF used
    pdfidx = lheStuff.heprup().PDFSUP.first
    pdfname = LHAID[
        str(pdfidx
            )] if pdfidx != -1 else ' undefined, please check the LHE header.'

    print '## Id number of PDF used: ' + str(pdfidx)
    print '## PDF set name: ' + pdfname
    print '####'
コード例 #21
0
    def beginLoop(self, setup):
        super(LHEWeightAnalyzer, self).beginLoop(setup)

        self.run = Runs(self.cfg_comp.files[0])
        runsHandle = Handle('LHERunInfoProduct')
        self.run.getByLabel('externalLHEProducer', runsHandle)

        self.scale = TH1F('scale', 'scale', 10, 0, 10)
        self.pdf = TH1F('pdf', 'pdf', 101, 0, 101)
        self.alpha_s = TH1F('alpha_s', 'alpha_s', 2, 0, 2)

        iterator = runsHandle.product().headers_begin()

        # scan iterator so that it includes weight information
        for it in range(100):
            flag = False
            for itt in iterator.base().lines():
                print itt
                if itt.find('weight id') != -1: flag = True

            if flag:
                break
            else:
                iterator.next()
        else:
            print 'Could not find any weight information !!'

        self.index = []
        self.pdfindex = []
        self.alphaindex = []

        idx = 0

        for a in iterator.base().lines():
            if a.find('weight id') == -1: continue
            print a

            # For Higgs signal
            #            if (a.find('muR')!=-1 and a.find('muF')!=-1 and a.find('muR=2 muF=0.5')==-1 and a.find('muR=0.5 muF=2')==-1):
            # For LO Z->tautau
            if (a.find('mur') != -1 and a.find('muf') != -1
                    and a.find('mur=2 muf=0.5') == -1
                    and a.find('mur=0.5 muf=2') == -1):

                self.index.append(idx)

# For Higgs signal
#            if a.find('PDF')!=-1:
#                flag = False
#                for weight_id in range(260000, 260101):
#                    if a.find(str(weight_id))!=-1: flag = True
#
#                if flag:
#                    self.pdfindex.append(idx)
#
#            if a.find('PDF')!=-1 and a.find('265000')!=-1 or a.find('266000')!=-1:
#                self.alphaindex.append(idx)

# For LO Z->tautau
            if a.find('Member') != -1:
                flag = False
                for weight_id in range(10, 111):
                    if a.find('id=\"' + str(weight_id) + '\"') != -1:
                        flag = True

                if flag:
                    self.pdfindex.append(idx)


#            if a.find('pdf')!=-1 and a.find('292301')!=-1 or a.find('292302')!=-1:

            idx += 1

        self.alphaindex.append(0)
        self.alphaindex.append(1)

        print 'scale variation index: ', self.index, 'len', len(self.index)
        print 'pdf variation index: ', self.pdfindex, 'len', len(self.pdfindex)
        print 'alpha variation index: ', self.alphaindex, 'len', len(
            self.alphaindex)