Example #1
0
    for ev in range(nEvents):

        increment = 50
        if nEvents > increment and ev % (nEvents / increment) == 0:
            sys.stdout.write('\r' + "=" * (ev / (nEvents / increment)) + " " *
                             ((nEvents - ev) / (nEvents / increment)) + "]" +
                             str(round((ev + 1) /
                                       (float(nEvents) / 100), 2)) + "%")
            sys.stdout.flush()
            sys.stdout.write('\r')
        chain.GetEntry(eList.GetEntry(ev))

        #pileupweight = puReweighting(chain) if not s['isData'] else 1.

        weight = reduceStat * getVarValue(
            chain, "weight") * (luminosity / 1000.) if not s['isData'] else 1

        mll = getVarValue(chain, "dl_mass")
        mt2ll = getVarValue(chain, "dl_mt2ll")
        met = getVarValue(chain, "met_pt")
        nLep = getVarValue(chain, "nLepGood")
        l_Pt = getVarValue(chain, "LepGood_pt")
        l1_Pt = l_Pt[0]
        l2_Pt = l_Pt[1]

        jets = filter(
            lambda j: j['pt'] > 30 and abs(j['eta']) < 2.4 and j['id'],
            getJets(chain))

        if nLep == 2:
            if len(jets) >= 2:
Example #2
0
  print '\n', "Looping over %s" % s["name"]
  eList = getEList(chain, preselection) 
  nEvents = eList.GetN()/reduceStat
  print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselection,nEvents)
 
  for ev in range(nEvents):

    increment = 50
    if nEvents>increment and ev%(nEvents/increment)==0: 
      sys.stdout.write('\r' + "=" * (ev / (nEvents/increment)) +  " " * ((nEvents - ev)/ (nEvents/increment)) + "]" +  str(round((ev+1) / (float(nEvents)/100),2)) + "%")
      sys.stdout.flush()
      sys.stdout.write('\r')
    chain.GetEntry(eList.GetEntry(ev))
    mt2Calc.reset()
    #event weight (L= 4fb^-1)
    weight = reduceStat*getVarValue(chain, "weight")

    if s not in data: weight = weight*(luminosity/4000.)

    #MET
    met = getVarValue(chain, "met_pt")
    metPhi = getVarValue(chain, "met_phi")
    #jetpt
    leadingjetpt = getVarValue(chain, "Jet_pt",0)
    subleadingjetpt = getVarValue(chain, "Jet_pt",1)
    #Leptons 
    allLeptons = getLeptons(chain) 
    muons = filter(looseMuID, allLeptons)    
    electrons = filter(looseEleID, allLeptons)

    #SF and OF channels
Example #3
0
  print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselection,nEvents)
 
  #ROOT output file
  #TreeFile = ROOT.TFile("./trees/tree"+s["name"]+".root","recreate")
  #Tree = ROOT.TTree("VarTree","Tree of Variables")
  #Tree.Branch("MET",MET_n,"MET/D")
  #Tree.Branch("MT2ee",MT2ee_n,"MT2ee/D")
  #Tree.Branch("MT2emu",MT2emu_n,"MT2emu/D")
  #Tree.Branch("MT2mumu",MT2mumu_n,"MT2mumu/D")
  for ev in range(nEvents):
    if ev%10000==0:print "At %i/%i"%(ev,nEvents)
    chain.GetEntry(eList.GetEntry(ev))
    mt2Calc.reset()
    #event weight (L= 4fb^-1)
    if s.has_key('totalweight'): weight = getWeight(chain,s, 4000) #this method for Ward's SPRING15 samples
    else:                        weight = reduceStat*getVarValue(chain, "weight") #this method for Robert's PHYS14 samples
    #MET
    met = getVarValue(chain, "met_pt")
    metPhi = getVarValue(chain, "met_phi")
    #jetpt
    leadingjetpt = getVarValue(chain, "Jet_pt",0)
    subleadingjetpt = getVarValue(chain, "Jet_pt",1)
    #Leptons 
    allLeptons = getLeptons(chain) 
    muons = filter(looseMuID, allLeptons)    
    electrons = filter(looseEleID, allLeptons)
    #GENinfo
    #genparticles = getGenParts(chain)
    #ROOT output file
    #MET_n[0] = met
Example #4
0
  eList = getEList(chain, preselection) 
  nEvents = eList.GetN()/reduceStat
  print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselection,nEvents)

 
  for ev in range(nEvents):

    increment = 50
    if nEvents>increment and ev%(nEvents/increment)==0: 
      sys.stdout.write('\r' + "=" * (ev / (nEvents/increment)) +  " " * ((nEvents - ev)/ (nEvents/increment)) + "]" +  str(round((ev+1) / (float(nEvents)/100),2)) + "%")
      sys.stdout.flush()
      sys.stdout.write('\r')
    chain.GetEntry(eList.GetEntry(ev))
    mt2Calc.reset()
    #event weight (L= 4fb^-1)
    weight = reduceStat*getVarValue(chain, "weight")

    weight = weight*(luminosity/1000.)

    #MET
    met = getVarValue(chain, "met_pt")
    metPhi = getVarValue(chain, "met_phi")
    #jetpt
    leadingjetpt = getVarValue(chain, "Jet_pt",0)
    subleadingjetpt = getVarValue(chain, "Jet_pt",1)
    #leptons
    l0pt = getVarValue(chain, "l1_pt")
    l1pt = getVarValue(chain, "l2_pt")
    mll = getVarValue(chain,"dl_mass")
          
    #Leptons 
Example #5
0
    nEvents = eList.GetN()/reduceStat
    print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselection,nEvents)

    for ev in range(nEvents):

        increment = 50
        if nEvents>increment and ev%(nEvents/increment)==0:
            sys.stdout.write('\r' + "=" * (ev / (nEvents/increment)) +  " " * ((nEvents - ev)/ (nEvents/increment)) + "]" +  str(round((ev+1) / (float(nEvents)/100),2)) + "%")
            sys.stdout.flush()
            sys.stdout.write('\r')
        chain.GetEntry(eList.GetEntry(ev))

        #pileupweight = puReweighting(chain) if not s['isData'] else 1.

        weight = reduceStat*getVarValue(chain, "weight")*(luminosity/1000.) if not s['isData'] else 1

        mll = getVarValue(chain,"dl_mass")
        mt2ll = getVarValue(chain,"dl_mt2ll")
        met = getVarValue(chain,"met_pt")
        nLep = getVarValue(chain,"nLepGood")
        l_Pt = getVarValue(chain,"LepGood_pt")
        l1_Pt = l_Pt[0]
        l2_Pt = l_Pt[1]

        jets  = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(chain))

        if nLep==2:
            if len(jets)>=2:
                plots['2l']['dl_mass']['2mj']['histo'][s['name']].Fill(mll,weight)
                plots['2l']['dl_mt2ll']['2mj']['histo'][s['name']].Fill(mt2ll,weight)
Example #6
0
def getTaus(c, collVars=tauVars):
    return [
        getObjDict(c, 'TauGood_', collVars, i)
        for i in range(int(getVarValue(c, 'nTauGood')))
    ]
Example #7
0
def getJets(c, jetVars=jetVars, jetColl="Jet"):
    return [
        getObjDict(c, jetColl + '_', jetVars, i)
        for i in range(int(getVarValue(c, 'n' + jetColl)))
    ]
def getJets(c, jetVars=jetVars):
    return [
        getObjDict(c, 'Jet_', jetVars, i)
        for i in range(int(getVarValue(c, 'nJet')))
    ]
Example #9
0
    counterRecoGen_recoTau[mode]={}
    counterRecoGen_recoMatchedTau[mode]={}
    counterRecoGen_looseMu[mode]={}
    counterRecoGen_looseEle[mode]={}
    counterRecofake_fakeMet50[mode]={}
    counterRecofake_fakeMet100[mode]={}
    counterRecofake_fakeMet200[mode]={}
    counterRecoGen_failRelIso03[mode]={}
    badMuonCandidates[mode]=[]
    badElectronCandidates[mode]=[]
  for ev in range(nEvents):
    ntot+=1
    if ev%10000==0:print "At %i/%i"%(ev,nEvents)
    chain.GetEntry(eList.GetEntry(ev))
    mt2Calc.reset()
    weight = reduceStat*getVarValue(chain, "weight")*lumiScale if not s['isData'] else 1
    mt2ll = getVarValue(chain, "dl_mt2ll")
    met = getVarValue(chain, "met_pt")
    metPhi = getVarValue(chain, "met_phi")
    genMet = getVarValue(chain, "met_genPt")
    genMetPhi = getVarValue(chain, "met_genPhi")
    deltaMet = sqrt((met*cos(metPhi)-genMet*cos(genMetPhi))**2+(met*sin(metPhi)-genMet*sin(genMetPhi))**2)
    jets = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(chain))

    allLeptons = getLeptons(chain, collVars=leptonVars+['mcMatchId','mcMatchAny','mcMatchTau','mcPt','ip3d', 'relIso03', 'relIso04', 'jetPtRatiov1', 'jetPtRelv1', 'jetPtRelv2', 'jetPtRatiov2', 'jetBTagCSV', 'jetDR'])
    leptons = filter(lambda l: looseMuID(l) or looseEleID(l), allLeptons)

#LepGood_mcMatchId Match to source from hard scatter (pdgId of heaviest particle in chain, 25 for H, 6 for t, 23/24 for W/Z), zero if non-prompt or fake for Leptons after the preselection 
#LepGood_mcMatchAny  Match to any final state leptons: 0 if unmatched, 1 if light flavour (including prompt), 4 if charm, 5 if bottom for Leptons after the preselection
#LepGood_mcMatchTau True if the leptons comes from a tau for Leptons after the preselection
Example #10
0
def getGenPartsAll(c):
    return [getObjDict(c, "genPartAll_", genVars, i) for i in range(int(getVarValue(c, "ngenPartAll")))]
Example #11
0
def getJets(c, jetVars=jetVars, jetColl="Jet"):
    return [getObjDict(c, jetColl + "_", jetVars, i) for i in range(int(getVarValue(c, "n" + jetColl)))]
Example #12
0
def getPhotons(c, collVars=photonVars, idLevel="loose"):
    return [getObjDict(c, "gamma_", collVars, i) for i in range(int(getVarValue(c, "ngamma")))]
Example #13
0
def getTaus(c, collVars=tauVars):
    return [getObjDict(c, "TauGood_", collVars, i) for i in range(int(getVarValue(c, "nTauGood")))]
Example #14
0
def getGenParts(c):
    return [
        getObjDict(c, "GenPart_", ["eta", "pt", "phi", "charge", "pdgId", "motherId", "grandmotherId"], i)
        for i in range(int(getVarValue(c, "nGenPart")))
    ]
Example #15
0
def getLeptons(c, collVars=leptonVars):
    return [
        getObjDict(c, 'LepGood_', collVars, i)
        for i in range(int(getVarValue(c, 'nLepGood')))
    ]
def getJets(c, jetVars=jetVars):
  return [getObjDict(c, 'Jet_', jetVars, i) for i in range(int(getVarValue(c, 'nJet')))]
Example #17
0
def getElectrons(c, collVars=leptonVars):
    return [
        getObjDict(c, 'LepGood_', collVars, i)
        for i in range(int(getVarValue(c, 'nLepGood')))
        if abs(getVarValue(c, "LepGood_pdgId", i)) == 11
    ]
def getLeptons(c, collVars=leptonVars):
  return [getObjDict(c, 'LepGood_', collVars, i) for i in range(int(getVarValue(c, 'nLepGood')))]
Example #19
0
def getGenParts(c):
    return [
        getObjDict(c, 'GenPart_', [
            'eta', 'pt', 'phi', 'charge', 'pdgId', 'motherId', 'grandmotherId'
        ], i) for i in range(int(getVarValue(c, 'nGenPart')))
    ]
def getElectrons(c, collVars=leptonVars):
  return [getObjDict(c, 'LepGood_', collVars, i) for i in range(int(getVarValue(c, 'nLepGood'))) if abs(getVarValue(c,"LepGood_pdgId",i))==11]
Example #21
0
def loopAndFill(stacks, mode="loop"):
    allSamples = []
    allSampleNames = []
    allPlots = []
    usedBranches = []
    for s in stacks:
        usedBranches = list(set(usedBranches + s.usedBranches))
        for l in s.plotLists:
            for p in l:
                allPlots.append(p)
                if p.leaf:
                    if not p.leaf in usedBranches:
                        usedBranches.append(p.leaf)
                    if p.weightString and not p.weightString in usedBranches:
                        usedBranches.append(p.weightString)
                else:
                    usedBranches = list(set(usedBranches + p.usedBranches))
                if not p.sample in allSamples:
                    assert p.sample.has_key('dir') or p.sample.has_key(
                        'dirname'
                    ), "Missing key dir or dirname in sample %s" % repr(
                        p.sample)
                    allSamples.append(p.sample)
    if mode == 'loop':
        assert not any([
            p.string for p in allPlots
        ]), "Loop mode is %s but specified 'string' for: %s" % (
            mode, ", ".join([p.name for p in allPlots if p.string]))
    if mode == 'draw':
        assert all([
            p.string for p in allPlots
        ]), "Loop mode is %s but specified no 'string' for: %s" % (
            mode, ", ".join([p.name for p in allPlots if not p.string]))
    print "Found", len(allSamples), 'different samples:', ", ".join(
        s['name'] for s in allSamples)
    for s in allSamples:
        cutStringForSample = []
        plotsPerCutForSample = {}
        #    print s['name'], s.has_key('isData'), s.has_key('isData') and s['isData'], s.has_key('isData') and s['isData'] and s.has_key('dataCut')
        for p in allPlots:
            if p.sample == s:
                cut = p.cut['string'] if not (
                    s.has_key('isData') and s['isData']
                    and p.cut.has_key('dataCut')
                ) else "(" + p.cut['string'] + ")&&(" + p.cut['dataCut'] + ")"
                if not cut in cutStringForSample:
                    cutStringForSample.append(cut)
                    plotsPerCutForSample[cut] = []
                if not p in plotsPerCutForSample[cut]:
                    plotsPerCutForSample[cut].append(p)
        s['plotsPerCutForSample'] = plotsPerCutForSample
    for s in allSamples:
        sampleScaleFac = 1 if not s.has_key('scale') else s['scale']
        if sampleScaleFac != 1:
            print "Using sampleScaleFac", sampleScaleFac, "for sample", s[
                "name"]

        bins = s['bins'] if s.has_key('bins') else ['default']
        for b in bins:
            treeName = 'Events' if not s.has_key('treeName') else s['treeName']
            maxN = -1 if not (s.has_key('small') and s['small']) else 1
            c = ROOT.TChain(treeName)
            counter = 0
            dir = s['dirname'] if s.has_key('dirname') else s['dir']
            fileList = getFileList(
                dir + '/' + b, maxN=maxN,
                histname="") if s.has_key('bins') else [s['file']]
            for f in fileList:
                if not f[-5:] == '.root': continue
                #        counter+=1
                #        c.Add(f)
                if checkRootFile(f, checkForObjects=[treeName]):
                    counter += 1
                    c.Add(f)
                else:
                    print "File %s looks broken." % f
            ntot = c.GetEntries()
            print "Added ", counter, 'files from sample', s[
                'name'], 'dir', dir, 'bin', b, 'ntot', ntot

            switchOnBranches(c, usedBranches)

            if ntot == 0:
                print "Warning! Found zero events in", s[
                    'name'], 'bin', b, " -> do nothing"
                continue
            if mode.lower() == 'loop':
                for ics, cutString in enumerate(
                        s['plotsPerCutForSample'].keys()):
                    plotsToFill = s['plotsPerCutForSample'][cutString]
                    elistName = "eList_" + s['name'] + '_' + b + '_' + str(ics)
                    elist = ROOT.TEventList(elistName)
                    c.Draw(">>" + elistName, cutString)
                    #        print "elist",elist,elist.GetN(),cutString,'plots',plotsToFill
                    number_events = elist.GetN(
                    )  # if not (s.has_key('small')  and s['small']) else min(elist.GetN(), 100)
                    print "Reading: ", s[
                        "name"], b, "with", number_events, "events passing cutString", cutString, 'and will fill', len(
                            [p.name for p in plotsToFill]), 'vars.'
                    for p in plotsToFill:
                        if not (p.cut.has_key('func') and p.cut['func']):
                            p.cut['func'] = None
                        if p.TTreeFormula:
                            assert p.TTreeFormula and not (
                                p.TTreeFormula == ""
                            ), "Problem in TTreeFormula %s" % p.TTreeFormula
                            fString = 'ROOT.TTreeFormula("' + p.name + '","' + p.TTreeFormula + '",c)'
                            exec('p.ttreeFormula=' + fString)
                            print "Created TTreeFormula:", fString
                    for i in range(0, number_events):
                        if (i % 10000 == 0) and i > 0:
                            print i
                        c.GetEntry(elist.GetEntry(i))
                        for p in plotsToFill:
                            #            print p.cut['func'],  p.cut['func'](c)
                            if (not p.cut['func']) or p.cut['func'](c):
                                weight = c.GetLeaf(p.weightString).GetValue(
                                ) if p.weightString else 1.
                                reWeight = p.weightFunc(
                                    c) if p.weightFunc else 1.
                                #              print c, p.weightFunc, p.weightFunc(c), getVarValue(c, "nVert"), c.GetLeaf("nVert").GetValue(), c.nVert
                                if p.leaf:
                                    val = getVarValue(c, p.leaf, p.ind)
    #                print "Fill leaf",p.leaf, p.ind, val, weight,sampleScaleFac
                                if p.TTreeFormula:
                                    p.ttreeFormula.UpdateFormulaLeaves()
                                    val = p.ttreeFormula.EvalInstance()
                                if p.func:
                                    val = p.func(c)
    #              if val>170:print val, reWeight, weight, sampleScaleFac, p.leaf, p.ind, i, c.GetEntries(), elist.GetEntry(i),"x",c.GetLeaf('Jet_pt').GetValue(4), c.GetLeaf('met_pt').GetValue(), c.GetLeaf('lumi').GetValue(), c.GetLeaf('evt').GetValue()
                                if val < float('inf'):
                                    p.histo.Fill(
                                        val,
                                        reWeight * weight * sampleScaleFac)
    #              print p.histo.GetName(), b, val, weight*sampleScaleFac, reWeight*weight*sampleScaleFac
            elif mode.lower() == 'draw':
                for ics, cutString in enumerate(
                        s['plotsPerCutForSample'].keys()):
                    plotsToFill = s['plotsPerCutForSample'][cutString]
                    print "Reading: ", s[
                        "name"], b, "with cutString", cutString, 'and will fill', len(
                            [p.name for p in plotsToFill]), 'vars.'
                    for p in plotsToFill:
                        print c, "String", p.string, p.binning, "Cut", cutString, p.weightString, p.binningIsExplicit, sampleScaleFac
                        tmp = getPlotFromChain(
                            c,
                            p.string,
                            p.binning,
                            cutString,
                            p.weightString,
                            binningIsExplicit=p.binningIsExplicit)
                        tmp.Scale(sampleScaleFac)
                        p.histo.Add(tmp)
#      for ics, cutString in enumerate(s['plotsPerCutForSample'].keys()):
#        plotsToFill = s['plotsPerCutForSample'][cutString]
#        for p in plotsToFill:
#          print c.GetEntries(), p.name,p.histo.Integral()
#      c.GetListOfFiles().ls()
            c.Reset()
            del c

#do over-flow bins
    for p in allPlots:
        if p.overFlow and p.overFlow in ["upper", "both"]:
            nbins = p.histo.GetNbinsX()
            p.histo.SetBinContent(
                nbins,
                p.histo.GetBinContent(nbins) +
                p.histo.GetBinContent(nbins + 1))
            p.histo.SetBinError(
                nbins,
                sqrt(
                    p.histo.GetBinError(nbins)**2 +
                    p.histo.GetBinError(nbins + 1)**2))
        if p.overFlow and p.overFlow in ["lower", "both"]:
            p.histo.SetBinContent(
                1,
                p.histo.GetBinContent(0) + p.histo.GetBinContent(1))
            p.histo.SetBinError(
                1, sqrt(p.histo.GetBinError(0)**2 + p.histo.GetBinError(1)**2))
#sum stacks
    for s in stacks:
        sumStackHistos(s)
#normalize
    for p in allPlots:
        if p.normalizeTo:
            t = p.normalizeTo.histo.Integral()
            y = p.histo.Integral()
            r = p.normalizeRef.histo.Integral() if p.normalizeRef else y
            if r > 0:
                p.histo.Scale(t / r)
Example #22
0
      #start event loop
    for ev in range(nEvents):

        ##################################
        #        Processing output       #
        ##################################
        increment = 50
        if nEvents>increment and ev%(nEvents/increment)==0:
            sys.stdout.write('\r' + "=" * (ev / (nEvents/increment)) +  " " * ((nEvents - ev)/ (nEvents/increment)) + "]" +  str(round((ev+1) / (float(nEvents)/100),2)) + "%")
            sys.stdout.flush()
            sys.stdout.write('\r')
        chain.GetEntry(eList.GetEntry(ev))

        #No double counting in data samples
        if getVarValue(chain, "evt") in ListOfDataEvents:
            continue
        else:
            ListOfDataEvents.append(getVarValue(chain, "evt"))

        weight = reduceStat*getVarValue(chain, "weight")*(luminosity/1000.) if not s['isData'] else 1

        #leptons
        electrons = getGoodElectrons(chain)
        muons = getGoodMuons(chain)
        leptons = getGoodLeptons(chain,10)

        #mt2ll for 2l
        mt2ll = getVarValue(chain,"dl_mt2ll")

        #met
                *plots[pk][plot]['binning'])

    chain = s["chain"]
    #Using Event loop
    #get EList after preselection
    print "Looping over %s" % s["name"]
    eList = getEList(chain, preselection)
    nEvents = eList.GetN() / reduceStat
    print "Found %i events in %s after preselection %s, looping over %i" % (
        eList.GetN(), s["name"], preselection, nEvents)
    for ev in range(nEvents):
        if ev % 10000 == 0: print "At %i/%i" % (ev, nEvents)
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        #event weight (L= 4fb^-1)
        weight = reduceStat * getVarValue(chain, "weight")
        #MET
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        #Leptons
        allLeptons = getLeptons(chain)
        muons = filter(looseMuID, allLeptons)
        electrons = filter(looseEleID, allLeptons)

        #SF and OF channels
        leptons = {\
          'mu':   {'name': 'mumu', 'file': muons},
          'e':   {'name': 'ee', 'file': electrons},
          }
        for lep in leptons.keys():
            twoleptons = False
Example #24
0
    nEvents = eList.GetN()/reduceStat
    print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselection,nEvents)



    for ev in range(nEvents):

        increment = 50
        if nEvents>increment and ev%(nEvents/increment)==0:
            sys.stdout.write('\r' + "=" * (ev / (nEvents/increment)) +  " " * ((nEvents - ev)/ (nEvents/increment)) + "]" +  str(round((ev+1) / (float(nEvents)/100),2)) + "%")
            sys.stdout.flush()
            sys.stdout.write('\r')
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        #event weight (L= 4fb^-1)
        weight = reduceStat*getVarValue(chain, "weight")

        if s not in data: weight = weight*(luminosity/1000.)

        #MET
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        #jetpt
        leadingjetpt = getVarValue(chain, "Jet_pt",0)
        subleadingjetpt = getVarValue(chain, "Jet_pt",1)
        #leptons
        l0pt = getVarValue(chain, "l1_pt")
        l1pt = getVarValue(chain, "l2_pt")
        mll = getVarValue(chain,"dl_mass")

        #Leptons
Example #25
0
        for plot in plots[pk].keys():
            plots[pk][plot]['histo'][s["name"]] = ROOT.TH1F(plots[pk][plot]['name']+"_"+s["name"]+"_"+pk, plots[pk][plot]['name']+"_"+s["name"]+"_"+pk, *plots[pk][plot]['binning'])

    chain = s["chain"]
    #Using Event loop
    #get EList after preselection
    print "Looping over %s" % s["name"]
    eList = getEList(chain, preselection)
    nEvents = eList.GetN()/reduceStat
    print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselection,nEvents)
    for ev in range(nEvents):
        if ev%10000==0:print "At %i/%i"%(ev,nEvents)
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        #event weight (L= 4fb^-1)
        weight = reduceStat*getVarValue(chain, "weight")
        #MET
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        #jetpt
        leadingjetpt = getVarValue(chain, "Jet_pt",0)
        subleadingjetpt = getVarValue(chain, "Jet_pt",1)
        #Leptons
        allLeptons = getLeptons(chain)
        muons = filter(looseMuID, allLeptons)
        electrons = filter(looseEleID, allLeptons)
        #GENinfo
        genparticles = getGenParts(chain)

        #SF and OF channels
        leptons = {\
Example #26
0
def makeMETPerformanceHistos(setup):
  for name, v in setup["variables"].iteritems():
    v['bins']=[(v["binning"][i],v["binning"][i+1]) for i in range(len(v["binning"])-1)]
    v['uperp']={}
    v['upara']={}
    v['uparaPlusQt']={}
    v['qt']={}
    v['histo']={}
    for mname, mv in setup["metVariables"].iteritems():
      hname = '_'.join([name,mname])
      v['histo'][mname]=ROOT.TH1D('histo_'+hname, 'histo_'+hname, len(v['binning'])-1, array('d',v['binning']))
      v['upara'][mname]={}
      v['uparaPlusQt'][mname]={}
      v['uperp'][mname]={}
      v['qt'][mname]={}
      v['upara'][mname]["scale"] = ROOT.TH1D(hname+'_upara_scale', hname+'_upara_scale',len(v['binning'])-1, array('d',v['binning']))
  #    v['upara'][mname]["scale"] = ROOT.TH1D(hname+'_upara_scale', hname+'_upara_scale',len(v['binning'])-1, array('d',v['binning']))
      v['upara'][mname]["RMS"] = ROOT.TH1D(hname+'_upara_RMS', hname+'_upara_RMS',len(v['binning'])-1, array('d',v['binning']))
      v['uperp'][mname]["RMS"] = ROOT.TH1D(hname+'_uperp_RMS', hname+'_uperp_RMS',len(v['binning'])-1, array('d',v['binning']))
      v['upara'][mname]["RMScorr"] = ROOT.TH1D(hname+'_upara_RMScorr', hname+'_upara_RMScorr',len(v['binning'])-1, array('d',v['binning']))
      v['uperp'][mname]["RMScorr"] = ROOT.TH1D(hname+'_uperp_RMScorr', hname+'_uperp_RMScorr',len(v['binning'])-1, array('d',v['binning']))
      for b in v['bins']:
        hname = name+'_'.join([str(x) for x in b])
        v['uperp'][mname][b] = ROOT.TH1D(hname+'_'+mname+'_uperp', hname+'_'+mname+'_uperp', 800,-400,400) 
        v['upara'][mname][b] = ROOT.TH1D(hname+'_'+mname+'_upara', hname+'_'+mname+'_upara', 800,-600,200) 
        v['uparaPlusQt'][mname][b] = ROOT.TH1D(hname+'_'+mname+'_uparaPlusQt', hname+'_'+mname+'_uparaPlusQt', 800,-400,400) 
        v['qt'][mname][b] = ROOT.TH1D(hname+'_'+mname+'_qt', hname+'_'+mname+'_qt', 500,0,500) 

  for s in setup["samples"]:
    for b in s['bins']:
      b['chain'].Draw('>>eList', setup['preselection'])
      eList = ROOT.gDirectory.Get('eList')
      nEvents = eList.GetN() if not setup.has_key('maxEvents') or setup['maxEvents']<0 else setup['maxEvents']
      for nev in range(nEvents):
        if nev%1000==0:print "At %i / %i"%(nev, nEvents)
        b['chain'].GetEntry(eList.GetEntry(nev))
        muons = setup['leptons'](b['chain'])
        if len(muons)!=2:continue
        l0, l1 = muons
        if not setup['massWindow'](l0,l1):continue
        qx = l0['pt']*cos(l0['phi']) + l1['pt']*cos(l1['phi'])  
        qy = l0['pt']*sin(l0['phi']) + l1['pt']*sin(l1['phi']) 
  #      qphi = atan2(qy, qx)
        qt = sqrt(qx**2+qy**2)
  #      print l0, l1

        for mname, mv in setup["metVariables"].iteritems():
          mv['pt'] = mv['ptFunc'](b['chain']) 
          mv['phi'] = mv['phiFunc'](b['chain'])
          ux = -mv['pt']*cos(mv['phi']) - qx 
          uy = -mv['pt']*sin(mv['phi']) - qy
          upara = (ux*qx+uy*qy)/qt
          uperp = (ux*qy-uy*qx)/qt
          weight = getVarValue(b['chain'], 'genWeight')*b['lumiScale']
          for name, v in setup["variables"].iteritems():
            if v['func']=='qt':varValue=qt
            else:
              varValue = v['func'](b['chain'])
            v['histo'][mname].Fill(varValue, weight)         #Filling distribution of binning variable
            varBin = findBin(v, varValue)
            if varBin: 
              v['uperp'][mname][varBin].Fill(uperp, weight) 
              v['upara'][mname][varBin].Fill(upara, weight) 
              v['uparaPlusQt'][mname][varBin].Fill(upara+qt, weight) 
              v['qt'][mname][varBin].Fill(qt, weight) 
    del eList

  for name, v in setup["variables"].iteritems():
    for mname, mv in setup["metVariables"].iteritems():
      for bin in v['bins']:
        upara_mean      = v['upara'][mname][bin].GetMean()
        upara_mean_err  = v['upara'][mname][bin].GetMeanError()
        uperp_mean      = v['uperp'][mname][bin].GetMean()
        uperp_mean_err  = v['uperp'][mname][bin].GetMeanError()
        upara_RMS      = v['uparaPlusQt'][mname][bin].GetRMS()
        upara_RMS_err  = v['uparaPlusQt'][mname][bin].GetRMSError()
        uperp_RMS      = v['uperp'][mname][bin].GetRMS()
        uperp_RMS_err  = v['uperp'][mname][bin].GetRMSError()
        qt_mean       = v['qt'][mname][bin].GetMean()
        qt_mean_err   = v['qt'][mname][bin].GetMeanError()
        if (not qt_mean>0):continue
        scale         =  - upara_mean / qt_mean 
        scale_err     =  upara_mean / qt_mean * sqrt(upara_mean_err**2/upara_mean**2 + qt_mean_err**2/qt_mean**2)
        upara_RMS_scaleCorr       =  upara_RMS/scale if scale>0 else float('nan')
        upara_RMS_scaleCorr_err   =  upara_RMS/scale*sqrt(upara_RMS_err**2/upara_RMS**2 + scale_err**2/scale**2) if upara_RMS>0 and scale>0 else float('nan') 
        uperp_RMS_scaleCorr       =  uperp_RMS/scale if scale>0 else float('nan')
        uperp_RMS_scaleCorr_err   =  uperp_RMS/scale*sqrt(uperp_RMS_err**2/uperp_RMS**2 + scale_err**2/scale**2) if uperp_RMS>0 and scale>0 else float('nan')
        val = 0.5*(bin[0]+bin[1])
        nbin = v['upara'][mname]["scale"].FindBin(val)
        v['upara'][mname]["scale"].SetBinContent(nbin, scale)
        v['upara'][mname]["scale"].SetBinError(nbin, scale_err)
        v['upara'][mname]["RMS"].SetBinContent(nbin, upara_RMS)
        v['upara'][mname]["RMS"].SetBinError(nbin, upara_RMS_err)
        v['upara'][mname]["RMScorr"].SetBinContent(nbin, upara_RMS_scaleCorr)
        v['upara'][mname]["RMScorr"].SetBinError(nbin, upara_RMS_scaleCorr_err)
        v['uperp'][mname]["RMS"].SetBinContent(nbin, uperp_RMS)
        v['uperp'][mname]["RMS"].SetBinError(nbin, uperp_RMS_err)
        v['uperp'][mname]["RMScorr"].SetBinContent(nbin, uperp_RMS_scaleCorr)
        v['uperp'][mname]["RMScorr"].SetBinError(nbin, uperp_RMS_scaleCorr_err)
  return setup
Example #27
0
        counterRecoGen_recoMatchedTau[mode]={}
        counterRecoGen_looseMu[mode]={}
        counterRecoGen_looseEle[mode]={}
        counterRecofake_fakeMet50[mode]={}
        counterRecofake_fakeMet100[mode]={}
        counterRecofake_fakeMet200[mode]={}
        counterRecoGen_failRelIso03[mode]={}
        counterRecoGen_genLepOutOfAcceptance[mode]={}
        badMuonCandidates[mode]=[]
        badElectronCandidates[mode]=[]
    for ev in range(nEvents):
        ntot+=1
        if ev%10000==0:print "At %i/%i"%(ev,nEvents)
        s.chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        weight = getVarValue(s.chain, "weight")*lumiScale
        mt2ll = getVarValue(s.chain, "dl_mt2ll")
        met = getVarValue(s.chain, "met_pt")
        metPhi = getVarValue(s.chain, "met_phi")
        genMet = getVarValue(s.chain, "met_genPt")
        genMetPhi = getVarValue(s.chain, "met_genPhi")
        deltaMet = sqrt((met*cos(metPhi)-genMet*cos(genMetPhi))**2+(met*sin(metPhi)-genMet*sin(genMetPhi))**2)
        jets = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(s.chain, jetColl="JetGood"))

        allLeptons = getLeptons(s.chain, collVars=leptonVars+['mcMatchId','mcMatchAny','mcMatchTau','mcPt','ip3d', 'relIso03', 'relIso04', 'jetPtRatiov1', 'jetPtRelv1', 'jetPtRelv2', 'jetPtRatiov2', 'jetBTagCSV', 'jetDR'])
        leptons = filter(lambda l: looseMuID(l) or looseEleID(l), allLeptons)

#LepGood_mcMatchId Match to source from hard scatter (pdgId of heaviest particle in s.chain, 25 for H, 6 for t, 23/24 for W/Z), zero if non-prompt or fake for Leptons after the preselection
#LepGood_mcMatchAny  Match to any final state leptons: 0 if unmatched, 1 if light flavour (including prompt), 4 if charm, 5 if bottom for Leptons after the preselection
#LepGood_mcMatchTau True if the leptons comes from a tau for Leptons after the preselection
Example #28
0
    leptoncounterTTZ = 0
    neutrinocounterTTZ = 0
    othercounterTTZ = 0

    for ev in range(nEvents):

        increment = 50
        if nEvents>increment and ev%(nEvents/increment)==0:
            sys.stdout.write('\r' + "=" * (ev / (nEvents/increment)) +  " " * ((nEvents - ev)/ (nEvents/increment)) + "]" +  str(round((ev+1) / (float(nEvents)/100),2)) + "%")
            sys.stdout.flush()
            sys.stdout.write('\r')
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        #event weight (L= 4fb^-1)
        weight = reduceStat*getVarValue(chain, "weight")

        weight = weight*(luminosity/1000.)

        #MET
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        #jetpt
        leadingjetpt = getVarValue(chain, "Jet_pt",0)
        subleadingjetpt = getVarValue(chain, "Jet_pt",1)
        #leptons
        l0pt = getVarValue(chain, "l1_pt")
        l1pt = getVarValue(chain, "l2_pt")
        mll = getVarValue(chain,"dl_mass")

        #Leptons
Example #29
0
        eList.GetN(), s["name"], preselection, nEvents)

    for ev in range(nEvents):

        increment = 50
        if nEvents > increment and ev % (nEvents / increment) == 0:
            sys.stdout.write('\r' + "=" * (ev / (nEvents / increment)) + " " *
                             ((nEvents - ev) / (nEvents / increment)) + "]" +
                             str(round((ev + 1) /
                                       (float(nEvents) / 100), 2)) + "%")
            sys.stdout.flush()
            sys.stdout.write('\r')
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        #event weight (L= 4fb^-1)
        weight = reduceStat * getVarValue(chain, "weight")

        if s not in data: weight = weight * (luminosity / 4000.)

        #MET
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        #jetpt
        leadingjetpt = getVarValue(chain, "Jet_pt", 0)
        subleadingjetpt = getVarValue(chain, "Jet_pt", 1)
        #Leptons
        allLeptons = getLeptons(chain)
        muons = filter(looseMuID, allLeptons)
        electrons = filter(looseEleID, allLeptons)

        #SF and OF channels
    for mode in ["isMuMu", "isEE", "isEMu"]:
        counterReco[mode] = 0
        counterRecoGen[mode] = {}
        counterRecoGen_muMatched[mode] = {}
        counterRecoGen_eleMatched[mode] = {}
        counterRecoGen_allMatched[mode] = {}
        counterRecoGen_oneMuMatchedToB[mode] = {}
        counterRecoGen_oneEleMatchedToB[mode] = {}
        counterRecoGen_oneMuMatchedToTau[mode] = {}
        counterRecoGen_oneEleMatchedToTau[mode] = {}
    for ev in range(nEvents):
        ntot += 1
        if ev % 10000 == 0: print "At %i/%i" % (ev, nEvents)
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        weight = reduceStat * getVarValue(
            chain, "weight") * lumiScale if not s['isData'] else 1
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        jets = filter(
            lambda j: j['pt'] > 30 and abs(j['eta']) < 2.4 and j['id'],
            getJets(chain))

        leptons = filter(
            lambda l: looseMuID(l) or looseEleID(l),
            getLeptons(chain,
                       collVars=leptonVars +
                       ['mcMatchId', 'mcMatchAny', 'mcMatchTau', 'mcPt']))
        #LepGood_mcMatchId Match to source from hard scatter (pdgId of heaviest particle in chain, 25 for H, 6 for t, 23/24 for W/Z), zero if non-prompt or fake for Leptons after the preselection
        #LepGood_mcMatchAny  Match to any final state leptons: 0 if unmatched, 1 if light flavour (including prompt), 4 if charm, 5 if bottom for Leptons after the preselection
        #LepGood_mcMatchTau True if the leptons comes from a tau for Leptons after the preselection
Example #31
0
    for pk in plots.keys():
        plots[pk]['histo'][sample['name']] = ROOT.TH1F("plot_"+sample["name"], "plot_"+sample["name"], *(plots[pk]['binning']))
        plots[pk]['histo'][sample['name']].SetLineColor(plots[pk]['color'])
        plots[pk]['histo'][sample['name']].SetMarkerColor(plots[pk]['color'])
        plots[pk]['histo'][sample['name']].SetMarkerSize(0)

    chain = sample["chain"]
    print "Looping over %s" % sample["name"]
    eList = getEList(chain, preselection)
    nEvents = eList.GetN()/reduceStat
    print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),sample["name"],preselection,nEvents)
    for ev in range(nEvents):
        if ev%10000==0:print "At %i/%i"%(ev,nEvents)
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        weight = reduceStat*getVarValue(chain, "weight")*lumiScale
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        puppiMet = getVarValue(chain, "puppiMet_pt")
        puppiMetPhi = getVarValue(chain, "puppiMet_phi")
        genMet = getVarValue(chain, "met_genPt")
        genMetPhi = getVarValue(chain, "met_genPhi")
        leptons = getGoodLeptons(chain, leptonVars+['mcMatchId', 'mcMatchAny', 'mcPt'])
        l0GenPt, l0HasMatch, l0pt, l0eta, l0phi = leptons[0]['mcPt'],  abs(leptons[0]['mcMatchId'])==6, leptons[0]['pt'],  leptons[0]['eta'],  leptons[0]['phi']
        l1GenPt, l1HasMatch, l1pt, l1eta, l1phi = leptons[1]['mcPt'],  abs(leptons[1]['mcMatchId'])==6, leptons[1]['pt'],  leptons[1]['eta'],  leptons[1]['phi']
        mll = sqrt(2.*l0pt*l1pt*(cosh(l0eta-l1eta)-cos(l0phi-l1phi)))
        jets = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(chain, jetVars+['mcPt', 'mcMatchId', 'mcFlavour']))
    #  bjets = filter(lambda j:j['btagCSV']>0.890, jets)
    #  print len(leptons), len(bjets), mll
        mt2Calc.setMet(met,metPhi)
        mt2Calc.setLeptons(l0pt, l0eta, l0phi, l1pt, l1eta, l1phi)
Example #32
0
    for plot in plots[pk].keys():
      plots[pk][plot]['histo'][s["name"]] = ROOT.TH1F(plots[pk][plot]['name']+"_"+s["name"]+"_"+pk, plots[pk][plot]['name']+"_"+s["name"]+"_"+pk, *plots[pk][plot]['binning'])
 
  chain = s["chain"]
  #Using Event loop
  #get EList after preselection
  print "Looping over %s" % s["name"]
  eList = getEList(chain, preselection) 
  nEvents = eList.GetN()/reduceStat
  print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselection,nEvents)
  for ev in range(nEvents):
    if ev%10000==0:print "At %i/%i"%(ev,nEvents)
    chain.GetEntry(eList.GetEntry(ev))
    mt2Calc.reset()
    #event weight (L= 4fb^-1)
    weight = reduceStat*getVarValue(chain, "weight")
    #MET
    met = getVarValue(chain, "met_pt")
    metPhi = getVarValue(chain, "met_phi")
    #Leptons 
    allLeptons = getLeptons(chain) 
    muons = filter(looseMuID, allLeptons)    
    electrons = filter(looseEleID, allLeptons)

    #SF and OF channels
    leptons = {\
      'mu':   {'name': 'mumu', 'file': muons},
      'e':   {'name': 'ee', 'file': electrons},
      }
    for lep in leptons.keys():
      twoleptons = False
Example #33
0
def getOtherLeptons(c, collVars=leptonVars):
    return [
        getObjDict(c, 'LepOther_', collVars, i)
        for i in range(int(getVarValue(c, 'nLepOther')))
    ]
Example #34
0
def getGenLeps(c):
  return [getObjDict(c, 'genLep_', ['eta','pt','phi','charge', 'pdgId', 'sourceId'], i) for i in range(int(getVarValue(c, 'ngenLep')))]
Example #35
0
def getGenLeps(c):
    return [
        getObjDict(c, 'genLep_',
                   ['eta', 'pt', 'phi', 'charge', 'pdgId', 'sourceId'], i)
        for i in range(int(getVarValue(c, 'ngenLep')))
    ]
Example #36
0
def getGenPartsAll(c):
  return [getObjDict(c, 'genPartAll_', ['eta','pt','phi','charge', 'pdgId', 'motherId', 'grandmotherId'], i) for i in range(int(getVarValue(c, 'ngenPartAll')))]
Example #37
0
def getPhotons(c, collVars=photonVars, idLevel='loose'):
    return [
        getObjDict(c, 'gamma_', collVars, i)
        for i in range(int(getVarValue(c, 'ngamma')))
    ]
Example #38
0
def getJets(c):
  return [getObjDict(c, 'Jet_', ['eta','pt','phi','btagCMVA','btagCSV', 'id'], i) for i in range(int(getVarValue(c, 'nJet')))]
Example #39
0
def getGenPartsAll(c):
    return [
        getObjDict(c, 'genPartAll_', genVars, i)
        for i in range(int(getVarValue(c, 'ngenPartAll')))
    ]
Example #40
0
def getElectrons(c):
  return [getObjDict(c, 'LepGood_', ['eta','pt','phi','charge', 'dxy', 'dz', 'relIso03','tightId', 'pdgId', 'mediumMuonId', 'miniRelIso', 'sip3d', 'mvaIdPhys14', 'convVeto', 'lostHits'], i) for i in range(int(getVarValue(c, 'nLepGood'))) if abs(getVarValue(c,"LepGood_pdgId",i))==11]
Example #41
0
    for plot in plots[pk].keys():
      plots[pk][plot]['histo'][s["name"]] = ROOT.TH1F(plots[pk][plot]['name']+"_"+s["name"]+"_"+pk, plots[pk][plot]['name']+"_"+s["name"]+"_"+pk, *plots[pk][plot]['binning'])

  chain = s["chain"]
  #Using Event loop
  #get EList after preselection
  print "Looping over %s" % s["name"]
  eList = getEList(chain, preselection) 
  nEvents = eList.GetN()/reduceStat
  print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselection,nEvents)
  for ev in range(nEvents):
    if ev%10000==0:print "At %i/%i"%(ev,nEvents)
    chain.GetEntry(eList.GetEntry(ev))
    mt2Calc.reset()
    #event weight (L= 4fb^-1)
    weight = reduceStat*getVarValue(chain, "weight")
    #MET
    met = getVarValue(chain, "met_pt")
    metPhi = getVarValue(chain, "met_phi")
    #jetpt
    leadingjetpt = getVarValue(chain, "Jet_pt",0)
    subleadingjetpt = getVarValue(chain, "Jet_pt",1)
    #Leptons 
    allLeptons = getLeptons(chain) 
    muons = filter(looseMuID, allLeptons)    
    electrons = filter(looseEleID, allLeptons)
    #GENinfo
    genparticles = getGenParts(chain)

    #SF and OF channels
    leptons = {\
        eList.GetN(), s["name"], preselection, nEvents)

    for ev in range(nEvents):

        increment = 50
        if nEvents > increment and ev % (nEvents / increment) == 0:
            sys.stdout.write('\r' + "=" * (ev / (nEvents / increment)) + " " *
                             ((nEvents - ev) / (nEvents / increment)) + "]" +
                             str(round((ev + 1) /
                                       (float(nEvents) / 100), 2)) + "%")
            sys.stdout.flush()
            sys.stdout.write('\r')
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        #event weight (L= 4fb^-1)
        weight = reduceStat * getVarValue(chain, "weight")

        weight = weight * (luminosity / 1000.)

        #MET
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        #jetpt
        leadingjetpt = getVarValue(chain, "Jet_pt", 0)
        subleadingjetpt = getVarValue(chain, "Jet_pt", 1)
        #leptons
        l0pt = getVarValue(chain, "l1_pt")
        l1pt = getVarValue(chain, "l2_pt")
        mll = getVarValue(chain, "dl_mass")

        isEE = getVarValue(chain, "isEE")
def loopAndFill(stacks, mode="loop"):
  allSamples=[]
  allSampleNames=[]
  allPlots = []
  usedBranches = []
  for s in stacks:
    usedBranches = list(set(usedBranches+s.usedBranches))
    for l in s.stackLists:
      for p in l:
        allPlots.append(p)
        if p.leaf:
          if not p.leaf in usedBranches:
            usedBranches.append(p.leaf)
          if p.weightString  and not p.weightString in usedBranches:
            usedBranches.append(p.weightString)
        else:
          usedBranches = list(set(usedBranches+p.usedBranches))
        if not p.sample in allSamples:
          assert p.sample.has_key('dir') or p.sample.has_key('dirname'), "Missing key dir or dirname in sample %s"%repr(p.sample)
          allSamples.append(p.sample)
  if mode=='loop':
    assert not any ([p.string for p in allPlots]), "Loop mode is %s but specified 'string' for: %s"%(mode, ", ".join([p.name for p in allPlots if p.string]))
  if mode=='draw': 
    assert all([p.string for p in allPlots]), "Loop mode is %s but specified no 'string' for: %s"%(mode, ", ".join([p.name for p in allPlots if not p.string])) 
  print "Found",len(allSamples),'different samples:',", ".join(s['name'] for s in allSamples)
  for s in allSamples:
    cutStringForSample=[]
    plotsPerCutForSample={}
#    print s['name'], s.has_key('isData'), s.has_key('isData') and s['isData'], s.has_key('isData') and s['isData'] and s.has_key('dataCut')
    for p in allPlots:
      if p.sample==s:
        cut = p.cut['string'] if not (s.has_key('isData') and s['isData'] and p.cut.has_key('dataCut')) else "("+p.cut['string']+")&&("+p.cut['dataCut']+")"
        if not cut in cutStringForSample:
          cutStringForSample.append(cut)
          plotsPerCutForSample[cut]=[]
        if not p in plotsPerCutForSample[cut]:
          plotsPerCutForSample[cut].append(p)
    s['plotsPerCutForSample'] = plotsPerCutForSample
  for s in allSamples:
    sampleScaleFac = 1 if not s.has_key('scale') else s['scale']
    if sampleScaleFac!=1:
      print "Using sampleScaleFac", sampleScaleFac ,"for sample",s["name"]
    for b in s['bins']:
      c = ROOT.TChain('Events' if not s.has_key('treeName') else s['treeName'])
      counter=0
      dir = s['dirname'] if s.has_key('dirname') else s['dir']
      for f in getFileList(dir+'/'+b, maxN = -1 if not (s.has_key('small') and s['small']) else 1, histname=""):#, minAgeDPM, histname, xrootPrefix, maxN):
        if not f[-5:]=='.root':continue
        counter+=1
        c.Add(f)
      ntot = c.GetEntries()
      print "Added ",counter,'files from sample',s['name'],'dir',dir,'bin',b,'ntot',ntot
      switchOnBranches(c, usedBranches)
         
      if ntot==0:
        print "Warning! Found zero events in",s['name'],'bin',b," -> do nothing"
        continue
      if mode.lower()=='loop':
        for ics, cutString in enumerate(s['plotsPerCutForSample'].keys()):
          plotsToFill = s['plotsPerCutForSample'][cutString]
          elistName = "eList_"+s['name']+'_'+b+'_'+str(ics)
          elist = ROOT.TEventList(elistName)
          c.Draw(">>"+elistName,cutString)
  #        print "elist",elist,elist.GetN(),cutString,'plots',plotsToFill
          number_events = elist.GetN()# if not (s.has_key('small')  and s['small']) else min(elist.GetN(), 100)
          print "Reading: ", s["name"], b, "with",number_events,"events passing cutString", cutString, 'and will fill', len([p.name for p in plotsToFill]),'vars.'
          for p in plotsToFill:
            if not (p.cut.has_key('func') and p.cut['func']):
              p.cut['func']=None
            if p.TTreeFormula:
              assert p.TTreeFormula and not (p.TTreeFormula==""), "Problem in TTreeFormula %s" % p.TTreeFormula
              fString='ROOT.TTreeFormula("'+p.name+'","'+p.TTreeFormula+'",c)'
              exec('p.ttreeFormula='+fString)
              print "Created TTreeFormula:",fString
          for i in range(0,number_events):
            if (i%10000 == 0) and i>0 :
              print i
            c.GetEntry(elist.GetEntry(i))
            for p in plotsToFill:
  #            print p.cut['func'],  p.cut['func'](c)
              if (not p.cut['func']) or p.cut['func'](c):
                weight = c.GetLeaf(p.weightString).GetValue() if p.weightString else 1.
                reWeight = p.weightFunc(c) if p.weightFunc else 1.
  #              print c, p.weightFunc, p.weightFunc(c), getVarValue(c, "nVert"), c.GetLeaf("nVert").GetValue(), c.nVert
                if p.leaf:
                  val =  getVarValue(c, p.leaf, p.ind)
  #                print "Fill leaf",p.leaf, p.ind, val, weight,sampleScaleFac
                if p.TTreeFormula:
                  p.ttreeFormula.UpdateFormulaLeaves()
                  val = p.ttreeFormula.EvalInstance()
                if p.func:
                  val = p.func(c)
  #              if val>170:print val, reWeight, weight, sampleScaleFac, p.leaf, p.ind, i, c.GetEntries(), elist.GetEntry(i),"x",c.GetLeaf('Jet_pt').GetValue(4), c.GetLeaf('met_pt').GetValue(), c.GetLeaf('lumi').GetValue(), c.GetLeaf('evt').GetValue()
                if val<float('inf'):
                  p.histo.Fill(val, reWeight*weight*sampleScaleFac)
  #              print p.histo.GetName(), b, val, weight*sampleScaleFac, reWeight*weight*sampleScaleFac
      elif mode.lower()=='draw':
        for ics, cutString in enumerate(s['plotsPerCutForSample'].keys()):
          plotsToFill = s['plotsPerCutForSample'][cutString]
          print "Reading: ", s["name"], b, "with cutString", cutString, 'and will fill', len([p.name for p in plotsToFill]),'vars.'
          for p in plotsToFill:
#            print c, p.string, p.binning, cutString, p.weightString, p.binningIsExplicit, sampleScaleFac
            tmp = getPlotFromChain(c, p.string, p.binning, cutString, p.weightString, binningIsExplicit=p.binningIsExplicit)
            tmp.Scale(sampleScaleFac)
            p.histo.Add(tmp)
#      for ics, cutString in enumerate(s['plotsPerCutForSample'].keys()):
#        plotsToFill = s['plotsPerCutForSample'][cutString]
#        for p in plotsToFill:
#          print c.GetEntries(), p.name,p.histo.Integral()
#      c.GetListOfFiles().ls()
      c.Reset()
      del c
      
#do over-flow bins
  for p in allPlots:
    if p.overFlow and p.overFlow in [ "upper", "both"]:
      nbins = p.histo.GetNbinsX()
      p.histo.SetBinContent(nbins , p.histo.GetBinContent(nbins) + p.histo.GetBinContent(nbins + 1))
      p.histo.SetBinError(nbins , sqrt(p.histo.GetBinError(nbins)**2 + p.histo.GetBinError(nbins + 1)**2))
    if p.overFlow and p.overFlow in [ "lower", "both"]:
      p.histo.SetBinContent(1 , p.histo.GetBinContent(0) + p.histo.GetBinContent(1))
      p.histo.SetBinError(1 , sqrt(p.histo.GetBinError(0)**2 + p.histo.GetBinError(1)**2))
  for s in stacks:
    sumStackHistos(s)   
Example #44
0
        ##################################
        #        Processing output       #
        ##################################
        increment = 50
        if nEvents > increment and ev % (nEvents / increment) == 0:
            sys.stdout.write('\r' + "=" * (ev / (nEvents / increment)) + " " *
                             ((nEvents - ev) / (nEvents / increment)) + "]" +
                             str(round((ev + 1) /
                                       (float(nEvents) / 100), 2)) + "%")
            sys.stdout.flush()
            sys.stdout.write('\r')
        chain.GetEntry(eList.GetEntry(ev))

        #No double counting in data samples
        if getVarValue(chain, "evt") in ListOfDataEvents:
            continue
        else:
            ListOfDataEvents.append(getVarValue(chain, "evt"))

        weight = reduceStat * getVarValue(
            chain, "weight") * (luminosity / 1000.) if not s['isData'] else 1

        #leptons
        electrons = getGoodElectrons(chain)
        muons = getGoodMuons(chain)
        leptons = getGoodLeptons(chain, 10)

        #mt2ll for 2l
        mt2ll = getVarValue(chain, "dl_mt2ll")
Example #45
0
def cutflow(sig):
    #######################################################
    #        SELECT WHAT YOU WANT TO DO HERE              #
    #######################################################
    reduceStat = 100  #recude the statistics, i.e. 10 is ten times less samples to look at

    #######################################################
    #         Define cutflow you want to make             #
    #######################################################
    mt2llcut = 80.
    metcut = 40.
    lumi = 10000.

    baselineamount = {
        'samples': {},
        'SoverB': None,
    }

    cutflow = {\
      'metsig':{'baseline': 0.,
                'cuts': {\
                  3:{'samples':{}, 'SoverB': None},
                  4:{'samples':{}, 'SoverB': None},
                  5:{'samples':{}, 'SoverB': None},
                  6:{'samples':{}, 'SoverB': None},
                  7:{'samples':{}, 'SoverB': None},
                  8:{'samples':{}, 'SoverB': None},
                  9:{'samples':{}, 'SoverB': None},
                  10:{'samples':{}, 'SoverB': None},
                  10:{'samples':{}, 'SoverB': None},
                  },
                'event': None,
                },
      'nbjets':{'baseline': 1.,
                'cuts': {\
                  0:{'samples':{}, 'SoverB': None},
                  1:{'samples':{}, 'SoverB': None},
                  2:{'samples':{}, 'SoverB': None},
                  3:{'samples':{}, 'SoverB': None},
                  4:{'samples':{}, 'SoverB': None},
                  5:{'samples':{}, 'SoverB': None},
                  },
                'event': None,
                },
      'njets': {'baseline': 2.,
                'cuts': {\
                  1:{'samples':{}, 'SoverB': None},
                  2:{'samples':{}, 'SoverB': None},
                  3:{'samples':{}, 'SoverB': None},
                  4:{'samples':{}, 'SoverB': None},
                  5:{'samples':{}, 'SoverB': None},
                  6:{'samples':{}, 'SoverB': None},
                  7:{'samples':{}, 'SoverB': None},
                  },
                'event': None,
                },
      'ht':    {'baseline': 0.,
                'cuts': {\
                  50: {'samples':{}, 'SoverB': None},
                  100:{'samples':{}, 'SoverB': None},
                  200:{'samples':{}, 'SoverB': None},
                  300:{'samples':{}, 'SoverB': None},
                  400:{'samples':{}, 'SoverB': None},
                  500:{'samples':{}, 'SoverB': None},
                  },
                'event': None,
                },
    }

    #preselection: MET>40, njets>=2, n_bjets>=1, n_lep>=2
    #For now see here for the Sum$ syntax: https://root.cern.ch/root/html/TTree.html#TTree:Draw@2
    preselection = 'met_pt>' + str(metcut) + '&&Sum$(LepGood_pt>20)==2'

    #######################################################
    #                 load all the samples                #
    #######################################################
    backgrounds = [singleTop_50ns, DY_50ns, TTJets_50ns]
    #signals = [SMS_T2tt_2J_mStop425_mLSP325, SMS_T2tt_2J_mStop500_mLSP325, SMS_T2tt_2J_mStop650_mLSP325, SMS_T2tt_2J_mStop850_mLSP100]
    signal = [sig]

    #######################################################
    #            get the TChains for each sample          #
    #######################################################
    for s in backgrounds + signal:
        s['chain'] = getChain(s, histname="")

    #######################################################
    #            Start filling in the histograms          #
    #######################################################
    for s in backgrounds + signal:
        for cuttype in cutflow.keys():
            for cut in cutflow[cuttype]['cuts'].keys():
                cutflow[cuttype]['cuts'][cut]['samples'][s["name"]] = 0

        baselineamount['samples'][s['name']] = 0

        chain = s["chain"]
        #Using Event loop
        #get EList after preselection
        print "Looping over %s" % s["name"]
        eList = getEList(chain, preselection)
        nEvents = eList.GetN() / reduceStat
        print "Found %i events in %s after preselection %s, looping over %i" % (
            eList.GetN(), s["name"], preselection, nEvents)

        for ev in range(nEvents):
            increment = 50
            if nEvents > increment and ev % (nEvents / increment) == 0:
                sys.stdout.write(
                    '\r' + "=" * (ev / (nEvents / increment)) + " " *
                    ((nEvents - ev) / (nEvents / increment)) + "]" +
                    str(round((ev + 1) / (float(nEvents) / 100), 2)) + "%")
                sys.stdout.flush()
                sys.stdout.write('\r')
            chain.GetEntry(eList.GetEntry(ev))
            mt2Calc.reset()
            #event weight (L= 4fb^-1)
            weight = reduceStat * getVarValue(chain, "weight")

            weight = weight * (lumi / 4000.)

            #MET
            met = getVarValue(chain, "met_pt")
            metPhi = getVarValue(chain, "met_phi")
            #jetpt
            leadingjetpt = getVarValue(chain, "Jet_pt", 0)
            subleadingjetpt = getVarValue(chain, "Jet_pt", 1)
            #Leptons
            allLeptons = getLeptons(chain)
            muons = filter(looseMuID, allLeptons)
            electrons = filter(looseEleID, allLeptons)
            nlep = len(allLeptons)

            #SF and OF channels
            leptons = {\
              'mu':   {'name': 'mumu', 'file': muons},
              'e':   {'name': 'ee', 'file': electrons},
              'emu': {'name': 'emu', 'file': [electrons,muons]},
              }
            for lep in leptons.keys():
                twoleptons = False
                #Same Flavor
                if lep != 'emu':
                    if len(leptons[lep]['file']) == 2 and leptons[lep]['file'][
                            0]['pdgId'] * leptons[lep]['file'][1]['pdgId'] < 0:

                        twoleptons = True
                        l0pt, l0eta, l0phi = leptons[lep]['file'][0][
                            'pt'], leptons[lep]['file'][0]['eta'], leptons[
                                lep]['file'][0]['phi']
                        l1pt, l1eta, l1phi = leptons[lep]['file'][1][
                            'pt'], leptons[lep]['file'][1]['eta'], leptons[
                                lep]['file'][1]['phi']
                        leadingleptonpt = l0pt
                        subleadingleptonpt = l1pt
                        mll = sqrt(2. * l0pt * l1pt *
                                   (cosh(l0eta - l1eta) - cos(l0phi - l1phi)))
                        zveto = True
                #Opposite Flavor
                if lep == 'emu':
                    if len(leptons[lep]['file'][0]) == 1 and len(
                            leptons[lep]['file']
                        [1]) == 1 and leptons[lep]['file'][0][0][
                            'pdgId'] * leptons[lep]['file'][1][0]['pdgId'] < 0:

                        twoleptons = True
                        l0pt, l0eta, l0phi = leptons[lep]['file'][0][0][
                            'pt'], leptons[lep]['file'][0][0]['eta'], leptons[
                                lep]['file'][0][0]['phi']
                        l1pt, l1eta, l1phi = leptons[lep]['file'][1][0][
                            'pt'], leptons[lep]['file'][1][0]['eta'], leptons[
                                lep]['file'][1][0]['phi']
                        if l1pt > l0pt:
                            leadingleptonpt = l1pt
                            subleadingleptonpt = l0pt
                        else:
                            leadingleptonpt = l0pt
                            subleadingleptonpt = l1pt
                        mll = sqrt(2. * l0pt * l1pt *
                                   (cosh(l0eta - l1eta) - cos(l0phi - l1phi)))
                        zveto = False
                if (twoleptons and mll > 20
                        and not zveto) or (twoleptons and mll > 20 and zveto
                                           and abs(mll - 91.2) > 15):
                    mt2Calc.setMet(met, metPhi)
                    mt2Calc.setLeptons(l0pt, l0eta, l0phi, l1pt, l1eta, l1phi)
                    mt2ll = mt2Calc.mt2ll()
                    jets = filter(
                        lambda j: j['pt'] > 30 and abs(j['eta']) < 2.4 and j[
                            'id'], getJets(chain))
                    bjetspt = filter(lambda j: j['btagCSV'] > 0.89, jets)
                    nobjets = filter(lambda j: j['btagCSV'] <= 0.89, jets)
                    nmuons = len(muons)
                    nelectrons = len(electrons)
                    ht = sum([j['pt'] for j in jets])

                    if len(jets) < 1: continue
                    if mt2ll < mt2llcut: continue

                    cutflow['metsig']['event'] = met / sqrt(ht)
                    cutflow['nbjets']['event'] = len(bjetspt)
                    cutflow['njets']['event'] = len(jets)
                    cutflow['ht']['event'] = ht

                    for cuttype in cutflow.keys():
                        eventisgood = True
                        for cuttype2 in cutflow.keys():
                            if cuttype2 != cuttype:
                                if cutflow[cuttype2]['event'] < cutflow[
                                        cuttype2]['baseline']:
                                    eventisgood = False
                        if eventisgood:
                            for cut in cutflow[cuttype]['cuts']:
                                if cutflow[cuttype]['event'] >= cut:
                                    cutflow[cuttype]['cuts'][cut]['samples'][
                                        s['name']] += weight

                    baselineisgood = True
                    for cuttype in cutflow.keys():
                        if cutflow[cuttype]['event'] < cutflow[cuttype][
                                'baseline']:
                            baselineisgood = False
                    if baselineisgood:
                        baselineamount['samples'][s['name']] += weight

        del eList

    sigtot = baselineamount['samples'][signal[0]['name']]
    bkgtot = sum(baselineamount['samples'].values()) - sigtot

    if bkgtot > 0: baselineamount['SoverB'] = 100 * (sigtot / sqrt(bkgtot))
    else: baselineamount['SoverB'] = 0.

    for cuttype in cutflow.keys():
        for cut in cutflow[cuttype]['cuts']:
            sigtot = cutflow[cuttype]['cuts'][cut]['samples'][signal[0]
                                                              ['name']]
            bkgtot = sum(
                cutflow[cuttype]["cuts"][cut]['samples'].values()) - sigtot
            if bkgtot > 0:
                cutflow[cuttype]['cuts'][cut]['SoverB'] = 100 * (sigtot /
                                                                 sqrt(bkgtot))
            else:
                cutflow[cuttype]['cuts'][cut]['SoverB'] = 0.

    maketable(baselineamount, cutflow, mt2llcut, metcut, signal, lumi)
Example #46
0
#######################################################
#            Start filling in the histograms          #
#######################################################
for i, s in enumerate(
        backgrounds + signals
):  #Enumerate returns a couple (index of key in array, dictionary)
    chain = s["chain"]
    print "Looping over %s" % s["name"]
    eList = getEList(
        chain,
        preselection)  #Returns a list with events that pass the selection
    nEvents = eList.GetN() / reduceStat
    for ev in range(nEvents):
        chain.GetEntry(eList.GetEntry(ev))
        m_ll = getVarValue(chain, "dl_mass")
        ZVetoCut = abs(91.2 - m_ll) > 15
        isSF = True if (getVarValue(chain, "isEE") == 1
                        or getVarValue(chain, "isMuMu") == 1) else False
        if (not isSF):
            ZVetoCut = True
        weight = reduceStat * getVarValue(chain, "weight") * lumi
        if (ZVetoCut):
            for plot in plots.keys():
                variable = getVarValue(chain, plots[plot]['variable'])
                plots[plot]['histo'][s["name"]].Fill(variable, weight)
    print(plots[plot]['histo'][s['name']].GetEntries())

    print("I finished a background: " + s["name"])
processtime = datetime.now()
print "Time to process chains: ", processtime - start
Example #47
0
            *(plots[pk]['binning']))
        plots[pk]['histo'][sample['name']].SetLineColor(plots[pk]['color'])
        plots[pk]['histo'][sample['name']].SetMarkerColor(plots[pk]['color'])
        plots[pk]['histo'][sample['name']].SetMarkerSize(0)

    chain = sample["chain"]
    print "Looping over %s" % sample["name"]
    eList = getEList(chain, preselection)
    nEvents = eList.GetN() / reduceStat
    print "Found %i events in %s after preselection %s, looping over %i" % (
        eList.GetN(), sample["name"], preselection, nEvents)
    for ev in range(nEvents):
        if ev % 10000 == 0: print "At %i/%i" % (ev, nEvents)
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        weight = reduceStat * getVarValue(chain, "weight") * lumiScale
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        puppiMet = getVarValue(chain, "puppiMet_pt")
        puppiMetPhi = getVarValue(chain, "puppiMet_phi")
        genMet = getVarValue(chain, "met_genPt")
        genMetPhi = getVarValue(chain, "met_genPhi")
        leptons = getGoodLeptons(
            chain, leptonVars + ['mcMatchId', 'mcMatchAny', 'mcPt'])
        l0GenPt, l0HasMatch, l0pt, l0eta, l0phi = leptons[0]['mcPt'], abs(
            leptons[0]['mcMatchId']
        ) == 6, leptons[0]['pt'], leptons[0]['eta'], leptons[0]['phi']
        l1GenPt, l1HasMatch, l1pt, l1eta, l1phi = leptons[1]['mcPt'], abs(
            leptons[1]['mcMatchId']
        ) == 6, leptons[1]['pt'], leptons[1]['eta'], leptons[1]['phi']
        mll = sqrt(2. * l0pt * l1pt *
  for mode in ["isMuMu", "isEE", "isEMu"]:
    counterReco[mode]=0
    counterRecoGen[mode]={}
    counterRecoGen_muMatched[mode]={}
    counterRecoGen_eleMatched[mode]={}
    counterRecoGen_allMatched[mode]={}
    counterRecoGen_oneMuMatchedToB[mode]={}
    counterRecoGen_oneEleMatchedToB[mode]={}
    counterRecoGen_oneMuMatchedToTau[mode]={}
    counterRecoGen_oneEleMatchedToTau[mode]={}
  for ev in range(nEvents):
    ntot+=1
    if ev%10000==0:print "At %i/%i"%(ev,nEvents)
    chain.GetEntry(eList.GetEntry(ev))
    mt2Calc.reset()
    weight = reduceStat*getVarValue(chain, "weight")*lumiScale if not s['isData'] else 1
    met = getVarValue(chain, "met_pt")
    metPhi = getVarValue(chain, "met_phi")
    jets = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(chain))

    leptons = filter(lambda l: looseMuID(l) or looseEleID(l), getLeptons(chain, collVars=leptonVars+['mcMatchId','mcMatchAny','mcMatchTau','mcPt']))
#LepGood_mcMatchId Match to source from hard scatter (pdgId of heaviest particle in chain, 25 for H, 6 for t, 23/24 for W/Z), zero if non-prompt or fake for Leptons after the preselection 
#LepGood_mcMatchAny  Match to any final state leptons: 0 if unmatched, 1 if light flavour (including prompt), 4 if charm, 5 if bottom for Leptons after the preselection
#LepGood_mcMatchTau True if the leptons comes from a tau for Leptons after the preselection

#    for l in leptons:
#      if (l['mcMatchAny']==0 and (not (l['mcMatchId']==0))) or ( (not l['mcMatchAny']==0) and (l['mcMatchId']==0)):
#        print "Match?",l

#RECO
    mu      = filter(lambda l: abs(l['pdgId'])==13, leptons)
Example #49
0
for s in backgrounds+signals:
  for plot in plots:
    plots[plot]['histo'][s['name']] = ROOT.TH1F(plot + "_" + s["name"], plot + "_" + s["name"], *(plots[plot]['binning']))


#######################################################
#            Start filling in the histograms          #
#######################################################
for i,s in enumerate(backgrounds+signals): #Enumerate returns a couple (index of key in array, dictionary)
  chain = s["chain"]
  print "Looping over %s" % s["name"]
  eList = getEList(chain, preselection) #Returns a list with events that pass the selection
  nEvents = eList.GetN()/reduceStat
  for ev in range(nEvents):
    chain.GetEntry(eList.GetEntry(ev))
    m_ll = getVarValue(chain, "dl_mass")
    ZVetoCut = abs(90.2-m_ll) > 15
    isSF = True if (getVarValue(chain, "isEE") == 1 or getVarValue(chain, "isMuMu") == 1) else False
    if (not isSF):
      ZVetoCut = True
    weight = reduceStat*getVarValue(chain, "weight")*lumi             
    if (ZVetoCut):
      for plot in plots.keys():   
        variable = getVarValue(chain, plots[plot]['variable'])
        plots[plot]['histo'][s["name"]].Fill(variable, weight)
  print (plots[plot]['histo'][s['name']].GetEntries())

  print("I finished a background: " + s["name"])
processtime = datetime.now()
print "Time to process chains: ", processtime - start
Example #50
0
import itertools

small = False
from StopsDilepton.samples.cmgTuples_Spring15_50ns_postProcessed import *
from StopsDilepton.samples.cmgTuples_Spring15_25ns_postProcessed import *
from StopsDilepton.samples.cmgTuples_Data50ns_1l_postProcessed import *
from StopsDilepton.samples.cmgTuples_Data25ns_postProcessed import *
from StopsDilepton.tools.objectSelection import getLeptons, getMuons, getElectrons, getGoodMuons, getGoodElectrons, getGoodLeptons, mZ
from StopsDilepton.tools.helpers import getVarValue, getYieldFromChain, getChain
from StopsDilepton.tools.localInfo import plotDir
from simplePlotHelpers import plot, stack, loopAndFill, drawNMStacks
from StopsDilepton.tools.puReweighting import getReweightingFunction

puReweightingFunc = getReweightingFunction(era="Run2015D_205pb")
#puReweightingFunc = getReweightingFunction(era="Run2015D_205pb_doubleMu_onZ_isOS")
puReweighting = lambda c:puReweightingFunc(getVarValue(c, "nVert"))

cutBranches = ["weight", "leptonPt", "met*", "nVert",\
               'Jet_pt', "Jet_id", "Jet_eta", "Jet_phi", "Jet_btagCSV",
               "LepGood_pdgId", "LepGood_mediumMuonId", "LepGood_miniRelIso", "LepGood_sip3d", "LepGood_dxy", "LepGood_dz", "LepGood_convVeto", "LepGood_lostHits",
               "Flag_HBHENoiseFilter", "Flag_HBHENoiseIsoFilter", "Flag_HBHENoiseFilterMinZeroPatched", "Flag_goodVertices", "Flag_CSCTightHaloFilter", "Flag_eeBadScFilter",
               "HLT_mumuIso", "HLT_ee_DZ", "HLT_mue",
               "is*","dl_*","l1_*","l2_*", "nGoodMuons", "nGoodElectrons"
                ]
subdir = "png25ns_2l"
#preprefixes = ["PUDoubleMuOnZIsOS"]
preprefixes = []

def getZCut(mode):
  zstr = "abs(dl_mass - "+str(mZ)+")"
  if mode.lower()=="onz": return zstr+"<15"
Example #51
0
		nEvents = eList.GetN()/reduceStat
		print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselectionMC,nEvents)

	else:
		eList = getEList(chain, preselectionData)
		nEvents = eList.GetN()/reduceStat
		print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselectionData,nEvents)


	for ev in range(nEvents):

		if ev%10000==0:print "At %i/%i"%(ev,nEvents)
		chain.GetEntry(eList.GetEntry(ev))

		mt2Calc.reset()
		weight = reduceStat*getVarValue(chain, "weight")*lumiScale if not s['isData'] else 1

		met = getVarValue(chain, "met_pt")
		metPhi = getVarValue(chain, "met_phi")
		metEta = getVarValue(chain, "met_eta")
		mt2ll[0] = 0
		mt2bb[0] = 0
		mt2blbl[0] = 0
		MET[0] = met 
		METPhi[0] = metPhi
		xsecWeight[0] = weight
		pileupWeight[0] = getVarValue(chain,"puWeight")
		isMC[0] = 1-s['isData']
		isElecElec[0] = 0 
		isMuonMuon[0] = 0 
		isMuonElec[0] = 0 
Example #52
0
        print "Found %i events in %s after preselection %s, looping over %i" % (
            eList.GetN(), s["name"], preselectionMC, nEvents)

    else:
        eList = getEList(chain, preselectionData)
        nEvents = eList.GetN() / reduceStat
        print "Found %i events in %s after preselection %s, looping over %i" % (
            eList.GetN(), s["name"], preselectionData, nEvents)

    for ev in range(nEvents):

        if ev % 10000 == 0: print "At %i/%i" % (ev, nEvents)
        chain.GetEntry(eList.GetEntry(ev))

        mt2Calc.reset()
        weight = reduceStat * getVarValue(
            chain, "weight") * lumiScale if not s['isData'] else 1

        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        metEta = getVarValue(chain, "met_eta")
        EventNumber[0] = getVarValue(chain, "evt")
        mt2ll[0] = 0
        mt2bb[0] = 0
        mt2blbl[0] = 0
        MET[0] = met
        METPhi[0] = metPhi
        xsecWeight[0] = weight
        isMC[0] = 1 - s['isData']
        isElecElec[0] = 0
        isMuonMuon[0] = 0
        isMuonElec[0] = 0
Example #53
0
def cutflow(sig):
  #######################################################
  #        SELECT WHAT YOU WANT TO DO HERE              #
  #######################################################
  reduceStat = 100 #recude the statistics, i.e. 10 is ten times less samples to look at


  #######################################################
  #         Define cutflow you want to make             #
  #######################################################
  mt2llcut = 80.
  metcut = 40.
  lumi = 10000.

  baselineamount = { 'samples':{}, 'SoverB': None,}

  cutflow = {\
    'metsig':{'baseline': 0., 
              'cuts': {\
                3:{'samples':{}, 'SoverB': None}, 
                4:{'samples':{}, 'SoverB': None}, 
                5:{'samples':{}, 'SoverB': None}, 
                6:{'samples':{}, 'SoverB': None},
                7:{'samples':{}, 'SoverB': None},
                8:{'samples':{}, 'SoverB': None},
                9:{'samples':{}, 'SoverB': None},
                10:{'samples':{}, 'SoverB': None},
                10:{'samples':{}, 'SoverB': None},
                },
              'event': None,
              },
    'nbjets':{'baseline': 1., 
              'cuts': {\
                0:{'samples':{}, 'SoverB': None}, 
                1:{'samples':{}, 'SoverB': None}, 
                2:{'samples':{}, 'SoverB': None}, 
                3:{'samples':{}, 'SoverB': None},
                4:{'samples':{}, 'SoverB': None},
                5:{'samples':{}, 'SoverB': None},
                },
              'event': None,
              },
    'njets': {'baseline': 2., 
              'cuts': {\
                1:{'samples':{}, 'SoverB': None}, 
                2:{'samples':{}, 'SoverB': None}, 
                3:{'samples':{}, 'SoverB': None},
                4:{'samples':{}, 'SoverB': None},
                5:{'samples':{}, 'SoverB': None},
                6:{'samples':{}, 'SoverB': None},
                7:{'samples':{}, 'SoverB': None},
                },
              'event': None,
              },
    'ht':    {'baseline': 0., 
              'cuts': {\
                50: {'samples':{}, 'SoverB': None}, 
                100:{'samples':{}, 'SoverB': None}, 
                200:{'samples':{}, 'SoverB': None},
                300:{'samples':{}, 'SoverB': None},
                400:{'samples':{}, 'SoverB': None},
                500:{'samples':{}, 'SoverB': None},
                },
              'event': None,
              },
  }

  #preselection: MET>40, njets>=2, n_bjets>=1, n_lep>=2
  #For now see here for the Sum$ syntax: https://root.cern.ch/root/html/TTree.html#TTree:Draw@2
  preselection = 'met_pt>'+str(metcut)+'&&Sum$(LepGood_pt>20)==2'

  #######################################################
  #                 load all the samples                #
  #######################################################
  backgrounds = [singleTop_50ns,DY_50ns,TTJets_50ns]
  #signals = [SMS_T2tt_2J_mStop425_mLSP325, SMS_T2tt_2J_mStop500_mLSP325, SMS_T2tt_2J_mStop650_mLSP325, SMS_T2tt_2J_mStop850_mLSP100]
  signal = [sig]

  #######################################################
  #            get the TChains for each sample          #
  #######################################################
  for s in backgrounds+signal:
    s['chain'] = getChain(s,histname="")


  #######################################################
  #            Start filling in the histograms          #
  #######################################################
  for s in backgrounds+signal:
    for cuttype in cutflow.keys():
      for cut in cutflow[cuttype]['cuts'].keys():
        cutflow[cuttype]['cuts'][cut]['samples'][s["name"]] = 0

    baselineamount['samples'][s['name']] = 0

    chain = s["chain"]
    #Using Event loop
    #get EList after preselection
    print "Looping over %s" % s["name"]
    eList = getEList(chain, preselection) 
    nEvents = eList.GetN()/reduceStat
    print "Found %i events in %s after preselection %s, looping over %i" % (eList.GetN(),s["name"],preselection,nEvents)

    for ev in range(nEvents):
      increment = 50
      if nEvents>increment and ev%(nEvents/increment)==0: 
        sys.stdout.write('\r' + "=" * (ev / (nEvents/increment)) +  " " * ((nEvents - ev)/ (nEvents/increment)) + "]" +  str(round((ev+1) / (float(nEvents)/100),2)) + "%")
        sys.stdout.flush()
        sys.stdout.write('\r')
      chain.GetEntry(eList.GetEntry(ev))
      mt2Calc.reset()
      #event weight (L= 4fb^-1)
      weight = reduceStat*getVarValue(chain, "weight")

      weight = weight*(lumi/4000.)

      #MET
      met = getVarValue(chain, "met_pt")
      metPhi = getVarValue(chain, "met_phi")
      #jetpt
      leadingjetpt = getVarValue(chain, "Jet_pt",0)
      subleadingjetpt = getVarValue(chain, "Jet_pt",1)
      #Leptons 
      allLeptons = getLeptons(chain) 
      muons = filter(looseMuID, allLeptons)    
      electrons = filter(looseEleID, allLeptons)
      nlep = len(allLeptons)

      #SF and OF channels
      leptons = {\
        'mu':   {'name': 'mumu', 'file': muons},
        'e':   {'name': 'ee', 'file': electrons},
        'emu': {'name': 'emu', 'file': [electrons,muons]},
        }
      for lep in leptons.keys():
        twoleptons = False
        #Same Flavor
        if lep != 'emu':
          if len(leptons[lep]['file'])==2 and leptons[lep]['file'][0]['pdgId']*leptons[lep]['file'][1]['pdgId']<0:

            twoleptons = True
            l0pt, l0eta, l0phi = leptons[lep]['file'][0]['pt'],  leptons[lep]['file'][0]['eta'],  leptons[lep]['file'][0]['phi']
            l1pt, l1eta, l1phi = leptons[lep]['file'][1]['pt'],  leptons[lep]['file'][1]['eta'],  leptons[lep]['file'][1]['phi']
            leadingleptonpt = l0pt
            subleadingleptonpt = l1pt
            mll = sqrt(2.*l0pt*l1pt*(cosh(l0eta-l1eta)-cos(l0phi-l1phi)))
            zveto = True
        #Opposite Flavor
        if lep == 'emu':
          if len(leptons[lep]['file'][0])==1 and len(leptons[lep]['file'][1])==1 and leptons[lep]['file'][0][0]['pdgId']*leptons[lep]['file'][1][0]['pdgId']<0:

            twoleptons = True
            l0pt, l0eta, l0phi = leptons[lep]['file'][0][0]['pt'],  leptons[lep]['file'][0][0]['eta'],  leptons[lep]['file'][0][0]['phi']
            l1pt, l1eta, l1phi = leptons[lep]['file'][1][0]['pt'],  leptons[lep]['file'][1][0]['eta'],  leptons[lep]['file'][1][0]['phi']
            if l1pt > l0pt :
              leadingleptonpt = l1pt
              subleadingleptonpt = l0pt
            else:
              leadingleptonpt = l0pt
              subleadingleptonpt = l1pt
            mll = sqrt(2.*l0pt*l1pt*(cosh(l0eta-l1eta)-cos(l0phi-l1phi)))
            zveto = False
        if (twoleptons and mll>20 and not zveto) or (twoleptons and mll > 20 and zveto and abs(mll-90.2)>15):
          mt2Calc.setMet(met,metPhi)
          mt2Calc.setLeptons(l0pt, l0eta, l0phi, l1pt, l1eta, l1phi)        
          mt2ll = mt2Calc.mt2ll()
          jets = filter(lambda j:j['pt']>30 and abs(j['eta'])<2.4 and j['id'], getJets(chain))
          bjetspt = filter(lambda j:j['btagCSV']>0.89, jets)
          nobjets = filter(lambda j:j['btagCSV']<=0.89, jets)
          nmuons = len(muons)
          nelectrons = len(electrons)
          ht = sum([j['pt'] for j in jets])


          if len(jets)<1: continue
          if mt2ll<mt2llcut: continue 

          cutflow['metsig']['event'] = met/sqrt(ht)
          cutflow['nbjets']['event'] = len(bjetspt)
          cutflow['njets']['event'] = len(jets)
          cutflow['ht']['event'] = ht

          for cuttype in cutflow.keys():
            eventisgood = True
            for cuttype2 in cutflow.keys():
              if cuttype2 != cuttype:
                if cutflow[cuttype2]['event'] < cutflow[cuttype2]['baseline']:
                  eventisgood = False
            if eventisgood:
              for cut in cutflow[cuttype]['cuts']:
                if cutflow[cuttype]['event'] >= cut:
                  cutflow[cuttype]['cuts'][cut]['samples'][s['name']] += weight

          baselineisgood = True
          for cuttype in cutflow.keys():
            if cutflow[cuttype]['event'] < cutflow[cuttype]['baseline']:
              baselineisgood = False
          if baselineisgood:
            baselineamount['samples'][s['name']] += weight

    del eList

  sigtot = baselineamount['samples'][signal[0]['name']]
  bkgtot = sum(baselineamount['samples'].values()) - sigtot

  if bkgtot > 0: baselineamount['SoverB'] = 100 * (sigtot/sqrt(bkgtot))
  else:          baselineamount['SoverB'] = 0.

  for cuttype in cutflow.keys(): 
    for cut in cutflow[cuttype]['cuts']:
      sigtot = cutflow[cuttype]['cuts'][cut]['samples'][signal[0]['name']]
      bkgtot = sum(cutflow[cuttype]["cuts"][cut]['samples'].values()) - sigtot
      if bkgtot > 0: cutflow[cuttype]['cuts'][cut]['SoverB'] = 100 * (sigtot/sqrt(bkgtot))
      else:          cutflow[cuttype]['cuts'][cut]['SoverB'] = 0.

  maketable(baselineamount, cutflow, mt2llcut, metcut,signal,lumi)
Example #54
0
    #TreeFile = ROOT.TFile("./trees/tree"+s["name"]+".root","recreate")
    #Tree = ROOT.TTree("VarTree","Tree of Variables")
    #Tree.Branch("MET",MET_n,"MET/D")
    #Tree.Branch("MT2ee",MT2ee_n,"MT2ee/D")
    #Tree.Branch("MT2emu",MT2emu_n,"MT2emu/D")
    #Tree.Branch("MT2mumu",MT2mumu_n,"MT2mumu/D")
    for ev in range(nEvents):
        if ev % 10000 == 0: print "At %i/%i" % (ev, nEvents)
        chain.GetEntry(eList.GetEntry(ev))
        mt2Calc.reset()
        #event weight (L= 4fb^-1)
        if s.has_key('totalweight'):
            weight = getWeight(chain, s,
                               4000)  #this method for Ward's SPRING15 samples
        else:
            weight = reduceStat * getVarValue(
                chain, "weight")  #this method for Robert's PHYS14 samples
        #MET
        met = getVarValue(chain, "met_pt")
        metPhi = getVarValue(chain, "met_phi")
        #jetpt
        leadingjetpt = getVarValue(chain, "Jet_pt", 0)
        subleadingjetpt = getVarValue(chain, "Jet_pt", 1)
        #Leptons
        allLeptons = getLeptons(chain)
        muons = filter(looseMuID, allLeptons)
        electrons = filter(looseEleID, allLeptons)
        #GENinfo
        #genparticles = getGenParts(chain)
        #ROOT output file
        #MET_n[0] = met