示例#1
0
def getScalesWithCut(dir,
                     fileNames,
                     cut='OSTight',
                     massWindow=True,
                     type='DY'):
    yieldsHist = {}
    xs = {}
    scales = {}
    iFiles = []
    iTrees = []
    for cat in fileNames.keys():
        iFiles.append(r.TFile("%s/%s" % (dir, fileNames[cat])))
        iTrees.append(iFiles[len(iFiles) - 1].Get('eventTree'))
        yieldsHist[cat] = r.TH1F(cat, "", 6, 4, 10)
        nEntries = iTrees[len(iTrees) - 1].GetEntries()
        iTrees[len(iTrees) - 1].GetEntry(0)
        xs[cat] = iTrees[len(iTrees) - 1].xs

        for i in range(nEntries):
            iTrees[len(iTrees) - 1].GetEntry(i)
            signSelection, isoSelection, bTagSelection = makeWholeTools2.findCategory(
                tree=iTrees[len(iTrees) - 1],
                iso=1.0,
                option='iso',
                isData=False,
                relaxedRegionOption=makeWholeSample_cfg.Relax,
                isEmbed=False,
                usePassJetTrigger=makeWholeSample_cfg.usePassJetTrigger,
                nBtag='')
            if signSelection == None or isoSelection == None:
                continue
            if iTrees[len(iTrees) - 1].HLT_Any == 0:
                continue
            if type == 'DY' and iTrees[len(iTrees) - 1].ZTT == 0:
                continue
            if type == 'ZLL' and iTrees[len(iTrees) - 1].ZLL == 0:
                continue
            if massWindow and not makeWholeTools2.passCut(
                    iTrees[len(iTrees) - 1], 'iso'):
                continue
            if cut != signSelection + isoSelection:
                continue
            yieldsHist[cat].Fill(
                iTrees[len(iTrees) - 1].LHEProduct,
                iTrees[len(iTrees) - 1].xs /
                (iTrees[len(iTrees) - 1].initEvents + 0.0))

    for i in range(2, 6, 1):
        scales['%ijet' %
               (i - 1)] = (yieldsHist['inclusive'].GetBinContent(i + 1) + 0.0
                           ) / (yieldsHist['%ijet' %
                                           (i - 1)].GetBinContent(i + 1) + 0.0)

    return scales, xs
def getScalesWithCut(dir, fileNames, cut='OSTight', massWindow=True, type = 'DY'):
    yieldsHist = {}
    xs = {}
    scales = {}
    iFiles = []
    iTrees = []
    for cat in fileNames.keys():
        iFiles.append(r.TFile("%s/%s" %(dir, fileNames[cat])))
        iTrees.append(iFiles[len(iFiles)-1].Get('eventTree'))
        yieldsHist[cat] = r.TH1F(cat, "", 6, 4, 10)
        nEntries = iTrees[len(iTrees)-1].GetEntries()
        iTrees[len(iTrees)-1].GetEntry(0)
        xs[cat] = iTrees[len(iTrees)-1].xs

        for i in range(nEntries):
            iTrees[len(iTrees)-1].GetEntry(i)
            signSelection, isoSelection, bTagSelection = makeWholeTools2.findCategory(tree = iTrees[len(iTrees)-1], 
                                                                                      iso = 1.0, 
                                                                                      option = 'iso',
                                                                                      isData = False,
                                                                                      relaxedRegionOption = makeWholeSample_cfg.Relax,
                                                                                      isEmbed = False,
                                                                                      usePassJetTrigger = makeWholeSample_cfg.usePassJetTrigger,
                                                                                      nBtag = '')
            if signSelection == None or isoSelection == None:
                continue
            if iTrees[len(iTrees)-1].HLT_Any == 0:
                continue
            if type == 'DY' and iTrees[len(iTrees)-1].ZTT == 0:
                continue
            if type == 'ZLL' and iTrees[len(iTrees)-1].ZLL == 0:
                continue
            if  massWindow and not makeWholeTools2.passCut(iTrees[len(iTrees)-1], 'iso'):
                continue
            if cut != signSelection+isoSelection:
                continue
            yieldsHist[cat].Fill(iTrees[len(iTrees)-1].LHEProduct, iTrees[len(iTrees)-1].xs/(iTrees[len(iTrees)-1].initEvents+0.0))

    for i in range(2,6,1):
        scales['%ijet' %(i-1)] = (yieldsHist['inclusive'].GetBinContent(i+1)+0.0)/(yieldsHist['%ijet' %(i-1)].GetBinContent(i+1)+0.0)

    return scales, xs
示例#3
0
def makeSyncNtuples(iLocation, cut, cutBTag, treepath, usePassJetTrigger, pairOption):

    if '.root' in iLocation:
        iFile = r.TFile(iLocation)
        iTree = iFile.Get(treepath)
        nEntries = iTree.GetEntries()
        oFileName = iLocation[iLocation.rfind("/")+1:iLocation.rfind(".root")]
        oFileName += '_sync'
        oFileName += '%s_%s' %(cut, cutBTag)
        if usePassJetTrigger:
            oFileName += '_jetCut'
    else:
        iTree = r.TChain(treepath)
        nEntries = tool.addFiles(ch=iTree, dirName=iLocation, knownEventNumber=0, maxFileNumber=-1, printTotalEvents = True)
        oFileName = iLocation[iLocation.rfind("/")+1:iLocation.find("-SUB-TT")]

    iTree.SetBranchStatus("*",1)
    print iLocation


    oFile = r.TFile("/nfs_scratch/zmao/samples/sync/%s.root" %oFileName,"recreate")
    oTree = r.TTree('TauCheck', 'TauCheck')

    run  = array('i', [0])
    lumi = array('i', [0])
    evt = array('I', [0])
    nTauPairs  = array('i', [0])

    npv = array('i', [0])
    npu = array('i', [0])
    rho = array('f', [0.])

    mvis = array('f', [0.])
    m_sv = array('f', [0.])
    pt_sv = array('f', [0.])
    eta_sv = array('f', [0.])
    phi_sv = array('f', [0.])
    
    pt_1 = array('f', [0.])
    phi_1 = array('f', [0.])
    eta_1 = array('f', [0.])
    m_1 = array('f', [0.])
    q_1 = array('i', [0])
    iso_1 = array('f', [0.])
    mva_1 = array('f', [0.])
    byCombinedIsolationDeltaBetaCorrRaw3Hits_1 = array('f', [0.])
    d0_1 = array('f', [0.])
    dZ_1 = array('f', [0.])
    mt_1 = array('f', [0.])

    pt_2 = array('f', [0.])
    phi_2 = array('f', [0.])
    eta_2 = array('f', [0.])
    m_2 = array('f', [0.])
    q_2 = array('i', [0])
    iso_2 = array('f', [0.])
    mva_2 = array('f', [0.])
    byCombinedIsolationDeltaBetaCorrRaw3Hits_2 = array('f', [0.])
    d0_2 = array('f', [0.])
    dZ_2 = array('f', [0.])
    mt_2 = array('f', [0.])

    againstElectronMVA3raw_1 = array('f', [0.])
    againstElectronMVA3raw_2 = array('f', [0.])
    againstMuonLoose2_1 = array('f', [0.])
    againstMuonLoose2_2 = array('f', [0.])
    againstMuonMedium2_1 = array('f', [0.])
    againstMuonMedium2_2 = array('f', [0.])
    againstMuonTight2_1 = array('f', [0.])
    againstMuonTight2_2 = array('f', [0.])

    met = array('f', [0.])
    puweight = array('f', [0.])
    mvamet = array('f', [0.])
    mvametphi = array('f', [0.])
    mvacov00 = array('f', [0.])
    mvacov01 = array('f', [0.])
    mvacov10 = array('f', [0.])
    mvacov11 = array('f', [0.])

    pzetavis = array('f', [0.])
    pzetamiss = array('f', [0.])

    pt_tt = array('f', [0.])
    njets = array('i', [0])
    njetspt20 = array('i', [0])

    jpt_1 = array('f', [0.])
    jeta_1 = array('f', [0.])
    jphi_1 = array('f', [0.])
    jptraw_1 = array('f', [0.])
    jptunc_1 = array('f', [0.])
    jmva_1 = array('f', [0.])
    jlrm_1 = array('f', [0.])
    jctm_1 = array('f', [0.])
    jpass_1 = array('b', [0])

    jpt_2 = array('f', [0.])
    jeta_2 = array('f', [0.])
    jphi_2 = array('f', [0.])
    jptraw_2 = array('f', [0.])
    jptunc_2 = array('f', [0.])
    jmva_2 = array('f', [0.])
    jlrm_2 = array('f', [0.])
    jctm_2 = array('f', [0.])
    jpass_2 = array('b', [0])

    bpt_1 = array('f', [0.])
    beta_1 = array('f', [0.])
    bphi_1 = array('f', [0.])
    bcsv_1 = array('f', [0.])

    bpt_2 = array('f', [0.])
    beta_2 = array('f', [0.])
    bphi_2 = array('f', [0.])
    bcsv_2 = array('f', [0.])

    bpt_3 = array('f', [0.])
    beta_3 = array('f', [0.])
    bphi_3 = array('f', [0.])
    bcsv_3 = array('f', [0.])

    decayModeWeight_1 = array('f', [0.])
    decayModeWeight_2 = array('f', [0.])
    embeddedWeight = array('f', [0.])
    m_bb = array('f', [0.])
    m_ttbb = array('f', [0.])
    nbtag = array('i', [0])

    trigweight_1 = array('f', [0.])
    trigweight_2 = array('f', [0.])
    effweight = array('f', [0.])
    DYWeight = array('f', [0.])
    weight = array('f', [0.])


    oTree.Branch("run", run, "run/I")
    oTree.Branch("lumi", lumi, "lumi/I")
    oTree.Branch("evt", evt, "evt/i")
    oTree.Branch("nTauPairs", nTauPairs, "nTauPairs/I")

    oTree.Branch("npv", npv, "npv/I")
    oTree.Branch("npu", npu, "npu/I")
    oTree.Branch("rho", rho, "rho/F")

    oTree.Branch("mvis", mvis, "mvis/F")
    oTree.Branch("m_sv", m_sv, "m_sv/F")
    oTree.Branch("pt_sv", pt_sv, "pt_sv/F")
    oTree.Branch("eta_sv", eta_sv, "eta_sv/F")
    oTree.Branch("phi_sv", phi_sv, "phi_sv/F")

    oTree.Branch("pt_1", pt_1, "pt_1/F")
    oTree.Branch("phi_1", phi_1, "phi_1/F")
    oTree.Branch("eta_1", eta_1, "eta_1/F")
    oTree.Branch("m_1", m_1, "m_1/F")
    oTree.Branch("q_1", q_1, "q_1/I")
    oTree.Branch("iso_1", iso_1, "iso_1/F")
    oTree.Branch("mva_1", mva_1, "mva_1/F")
    oTree.Branch("byCombinedIsolationDeltaBetaCorrRaw3Hits_1", byCombinedIsolationDeltaBetaCorrRaw3Hits_1, "byCombinedIsolationDeltaBetaCorrRaw3Hits_1/F")
    oTree.Branch("d0_1", d0_1, "d0_1/F")
    oTree.Branch("dZ_1", dZ_1, "dZ_1/F")
    oTree.Branch("mt_1", mt_1, "mt_1/F")

    oTree.Branch("pt_2", pt_2, "pt_2/F")
    oTree.Branch("phi_2", phi_2, "phi_2/F")
    oTree.Branch("eta_2", eta_2, "eta_2/F")
    oTree.Branch("m_2", m_2, "m_2/F")
    oTree.Branch("q_2", q_2, "q_2/I")
    oTree.Branch("iso_2", iso_2, "iso_2/F")
    oTree.Branch("mva_2", mva_2, "mva_2/F")
    oTree.Branch("byCombinedIsolationDeltaBetaCorrRaw3Hits_2", byCombinedIsolationDeltaBetaCorrRaw3Hits_2, "byCombinedIsolationDeltaBetaCorrRaw3Hits_2/F")
    oTree.Branch("d0_2", d0_2, "d0_2/F")
    oTree.Branch("dZ_2", dZ_2, "dZ_2/F")
    oTree.Branch("mt_2", mt_2, "mt_2/F")

    oTree.Branch("againstElectronMVA3raw_1", againstElectronMVA3raw_1, "againstElectronMVA3raw_1/F")
    oTree.Branch("againstElectronMVA3raw_2", againstElectronMVA3raw_2, "againstElectronMVA3raw_2/F")
    oTree.Branch("againstMuonLoose2_1", againstMuonLoose2_1, "againstMuonLoose2_1/F")
    oTree.Branch("againstMuonLoose2_2", againstMuonLoose2_2, "againstMuonLoose2_2/F")
    oTree.Branch("againstMuonMedium2_1", againstMuonMedium2_1, "againstMuonMedium2_1/F")
    oTree.Branch("againstMuonMedium2_2", againstMuonMedium2_2, "againstMuonMedium2_2/F")
    oTree.Branch("againstMuonTight2_1", againstMuonTight2_1, "againstMuonTight2_1/F")
    oTree.Branch("againstMuonTight2_2", againstMuonTight2_2, "againstMuonTight2_2/F")

    oTree.Branch("met", met, "met/F")
    oTree.Branch("mvamet", mvamet, "mvamet/F")
    oTree.Branch("mvametphi", mvametphi, "mvametphi/F")
    oTree.Branch("mvacov00", mvacov00, "mvacov00/F")
    oTree.Branch("mvacov01", mvacov01, "mvacov01/F")
    oTree.Branch("mvacov10", mvacov10, "mvacov10/F")
    oTree.Branch("mvacov11", mvacov11, "mvacov11/F")

    oTree.Branch("pzetavis", pzetavis, "pzetavis/F")
    oTree.Branch("pzetamiss", pzetamiss, "pzetamiss/F")

    oTree.Branch("pt_tt", pt_tt, "pt_tt/F")
    oTree.Branch("njets", njets, "njets/I")
    oTree.Branch("njetspt20", njetspt20, "njetspt20/I")
    oTree.Branch("nbtag", nbtag, "nbtag/I")

    oTree.Branch("jpt_1", jpt_1, "jpt_1/F")
    oTree.Branch("jeta_1", jeta_1, "jeta_1/F")
    oTree.Branch("jphi_1", jphi_1, "jphi_1/F")
    oTree.Branch("jptraw_1", jptraw_1, "jptraw_1/F")
    oTree.Branch("jptunc_1", jptunc_1, "jptunc_1/F")
    oTree.Branch("jmva_1", jmva_1, "jmva_1/F")
    oTree.Branch("jctm_1", jctm_1, "jctm_1/F")
    oTree.Branch("jpass_1", jpass_1, "jpass_1/B")    

    oTree.Branch("jpt_2", jpt_2, "jpt_2/F")
    oTree.Branch("jeta_2", jeta_2, "jeta_2/F")
    oTree.Branch("jphi_2", jphi_2, "jphi_2/F")
    oTree.Branch("jptraw_2", jptraw_2, "jptraw_2/F")
    oTree.Branch("jptunc_2", jptunc_2, "jptunc_2/F")
    oTree.Branch("jmva_2", jmva_2, "jmva_2/F")
    oTree.Branch("jctm_2", jctm_2, "jctm_2/F")
    oTree.Branch("jpass_2", jpass_2, "jpass_2/B")    
    oTree.Branch("puweight", puweight, "puweight/F")    

    oTree.Branch("bpt_1", bpt_1, "bpt_1/F")
    oTree.Branch("beta_1", beta_1, "beta_1/F")
    oTree.Branch("bphi_1", bphi_1, "bphi_1/F")
    oTree.Branch("bcsv_1", bcsv_1, "bcsv_1/F")
    oTree.Branch("bpt_2", bpt_2, "bpt_2/F")
    oTree.Branch("beta_2", beta_2, "beta_2/F")
    oTree.Branch("bphi_2", bphi_2, "bphi_2/F")
    oTree.Branch("bcsv_2", bcsv_2, "bcsv_2/F")
    oTree.Branch("bpt_3", bpt_3, "bpt_3/F")
    oTree.Branch("beta_3", beta_3, "beta_3/F")
    oTree.Branch("bphi_3", bphi_3, "bphi_3/F")
    oTree.Branch("bcsv_3", bcsv_3, "bcsv_3/F")
    oTree.Branch("weight", weight, "weight/F")
    oTree.Branch("embeddedWeight", embeddedWeight, "embeddedWeight/F")
    oTree.Branch("DYWeight", DYWeight, "DYWeight/F")


    oTree.Branch("m_bb", m_bb, "m_bb/F")    
    oTree.Branch("m_ttbb", m_ttbb, "m_ttbb/F")    

    oTree.Branch("trigweight_1", trigweight_1, "trigweight_1/F")    
    oTree.Branch("trigweight_2", trigweight_2, "trigweight_2/F")    
    oTree.Branch("effweight", effweight, "effweight/F")    
    oTree.Branch("decayModeWeight_1", decayModeWeight_1, "decayModeWeight_1/F")    
    oTree.Branch("decayModeWeight_2", decayModeWeight_2, "decayModeWeight_2/F")   

    counter = 0
    lvClass = r.Math.LorentzVector(r.Math.PtEtaPhiM4D('double'))
    b1 = lvClass()
    b2 = lvClass()
    tau1 = lvClass()
    tau2 = lvClass()

    eventMask = [(1, 6647,  2656734),(1, 14273, 2853418),(1, 9775, 3906872),(1, 38627, 7722260)]

    
    for iEntry in range(nEntries):
        track = False
        iTree.GetEntry(iEntry)
        tool.printProcessStatus(iEntry, nEntries, 'Saving to file %s.root' % (oFileName))
        iBestPair = makeWholeTools2.findRightPair(iTree, pairOption)

        if (iTree.RUN,iTree.LUMI, iTree.EVENT,) in eventMask:
            print ''
            print 'Event: %i Lumi: %i run: %i' %(iTree.EVENT, iTree.LUMI, iTree.RUN)
            print 'pt1: %.2f pt2: %.2f CSVJ1: %.2f CSVJ2: %.2f b1Pt: %.2f b1Eta: %.2f b2Pt: %.2f b2Eta: %.2f' %(iTree.pt1.at(iBestPair), iTree.pt2.at(iBestPair), iTree.CSVJ1, iTree.CSVJ2, iTree.CSVJ1Pt, iTree.CSVJ1Eta, iTree.CSVJ2Pt, iTree.CSVJ2Eta)
            print 'iso1: %.2f iso2: %.2f charge: %.2f' %(iTree.iso1.at(iBestPair), iTree.iso2.at(iBestPair), iTree.charge1.at(iBestPair) + iTree.charge2.at(iBestPair))
            print 'svMass: %.2f mJJ: %.2f' %(iTree.svMass.at(iBestPair), iTree.mJJ)
            print 'mvaMet: %.2f' %(iTree.met.at(iBestPair))
            print 'met: %.2f' %(iTree.metUnc)
            print 'fMass: %.2f' %(iTree.fMassKinFit)
            print 'sampleName: %s' %iTree.sampleName

            track = True
        if iTree.HLT_Any == 0:
            continue
        if not makeWholeTools2.passCut(iTree, pairOption):
            continue
        if (iTree.nElectrons > 0 or iTree.nMuons > 0):
            continue
        signSelection, isoSelection, bTagSelection = makeWholeTools2.findCategory(tree = iTree,
                                                                                  iso = 1.0, 
                                                                                  option = pairOption, 
                                                                                  isData = True,
                                                                                  relaxedRegionOption = 'one1To4',
                                                                                  isEmbed = True, 
                                                                                  usePassJetTrigger = usePassJetTrigger)
        if signSelection == None  or isoSelection == None or bTagSelection == None:
            continue
        tmpSelect = signSelection+isoSelection
        if tmpSelect != cut:
            continue
        if not (cutBTag in bTagSelection) and (cutBTag != 'inclusive'):
            continue 
        if iTree.ZTT == 0:
            continue

        trigweight_1[0] = iTree.triggerEff1
        trigweight_2[0] = iTree.triggerEff2

        effweight[0] = trigweight_1[0] * trigweight_2[0]
        nTauPairs[0] = len(iTree.pt1)
    
        run[0] = iTree.RUN
        evt[0] = iTree.EVENT
        npv[0] = iTree.vertices
        npu[0] = int(iTree.puTruth)
        lumi[0] = iTree.LUMI
        rho[0] = iTree.Rho
        mvis[0] = (tau1+tau2).mass()
        m_sv[0] = iTree.svMass.at(iBestPair)
        pt_sv[0] = iTree.svPt.at(iBestPair)
        eta_sv[0] = iTree.svEta.at(iBestPair)
        phi_sv[0] = iTree.svPhi.at(iBestPair)

        pt_1[0] = iTree.pt1.at(iBestPair)
        eta_1[0] = iTree.eta1.at(iBestPair)
        phi_1[0] = iTree.phi1.at(iBestPair)
        m_1[0] = iTree.m1.at(iBestPair)
        q_1[0] = int(iTree.charge1.at(iBestPair))
        iso_1[0] = iTree.tau1MVAIso
        mva_1[0] = 0
        byCombinedIsolationDeltaBetaCorrRaw3Hits_1[0] = iTree.iso1.at(iBestPair)
        d0_1[0] = iTree.d0_1
        dZ_1[0] = iTree.l1dz
#         mt_1[0] = iTree.mt1

        pt_2[0] = iTree.pt2.at(iBestPair)
        eta_2[0] = iTree.eta2.at(iBestPair)
        phi_2[0] = iTree.phi2.at(iBestPair)
        m_2[0] = iTree.m2.at(iBestPair)
        q_2[0] = int(iTree.charge2.at(iBestPair))
        iso_2[0] = iTree.tau2MVAIso
        mva_2[0] = 0
        byCombinedIsolationDeltaBetaCorrRaw3Hits_2[0] = iTree.iso2.at(iBestPair)
        d0_2[0] = iTree.d0_2
        dZ_2[0] = iTree.l2dz
#         mt_2[0] = iTree.mt2

        againstElectronMVA3raw_1[0] = iTree.againstElectronMVA3raw_1
        againstElectronMVA3raw_2[0] = iTree.againstElectronMVA3raw_2
        againstMuonLoose2_1[0] = iTree.againstMuonLoose1.at(iBestPair)
        againstMuonLoose2_2[0] = iTree.againstMuonLoose2.at(iBestPair)
        againstMuonMedium2_1[0] = iTree.againstMuonMedium2_1
        againstMuonMedium2_2[0] = iTree.againstMuonMedium2_2
        againstMuonTight2_1[0] = iTree.againstMuonTight2_1
        againstMuonTight2_2[0] = iTree.againstMuonTight2_2

        met[0] = iTree.metUnc
        mvamet[0] = iTree.met.at(iBestPair)
#         mvametphi[0] = iTree.metphi.at(iBestPair)
        mvacov00[0] = iTree.mvacov00
        mvacov01[0] = iTree.mvacov01
        mvacov10[0] = iTree.mvacov10
        mvacov11[0] = iTree.mvacov11
    
        pzetavis[0] = iTree.pZV
        pzetamiss[0] = iTree.pZetaMiss

#         pt_tt[0] = iTree.fullPt

        njets[0] = int(iTree.njets)
        njetspt20[0] = int(iTree.njetspt20)
        nbtag[0] = int(iTree.NBTags)

        bcsv_1[0] = iTree.CSVJ1
        bpt_1[0] = iTree.CSVJ1Pt
        beta_1[0] = iTree.CSVJ1Eta
        bphi_1[0] = iTree.CSVJ1Phi
        bcsv_2[0] = iTree.CSVJ2
        bpt_2[0] = iTree.CSVJ2Pt
        beta_2[0] = iTree.CSVJ2Eta
        bphi_2[0] = iTree.CSVJ2Phi

        jpt_1[0] = iTree.J1Pt
        jeta_1[0] = iTree.J1Eta
        jphi_1[0] = iTree.J1Phi
        jptraw_1[0] = iTree.J1PtUncorr
        jptunc_1[0] = iTree.J1JECUnc
        jmva_1[0] = iTree.jmva_1
        jctm_1[0] = iTree.J1Ntot
        jpass_1[0] = bool(iTree.jpass_1) 

        jpt_2[0] = iTree.J2Pt
        jeta_2[0] = iTree.J2Eta
        jphi_2[0] = iTree.J2Phi
        jptraw_2[0] = iTree.J2PtUncorr
        jptunc_2[0] = iTree.J2JECUnc
        jmva_2[0] = iTree.jmva_2
        jctm_2[0] = iTree.J2Ntot
        jpass_2[0] = bool(iTree.jpass_2)
#         embeddedWeight[0] = iTree.embeddedWeight
#         weight[0] = effweight[0]*iTree.decayModeWeight*iTree.embeddedWeight
        weight[0] = effweight[0]*iTree.decayModeWeight*iTree.PUWeight
        puweight[0] = iTree.PUWeight
        m_bb[0] = iTree.mJJ
#         m_ttbb[0] = iTree.HMass

#         decayModeWeight_1[0] = iTree.decayModeWeight1
#         decayModeWeight_2[0] = iTree.decayModeWeight2
#         DYWeight[0] = iTree.xs/3504000.0

        oTree.Fill()
        if track:
            print 'saved'
        counter += 1
        tool.printProcessStatus(iEntry, nEntries, 'Saving to file ')
    
    print ''
    print '%i events saved' %counter
    oFile.cd()
    oTree.Write()
    oFile.Close()
    print 'Saved file: %s.root' %oFileName
示例#4
0
def yieldCalculator(dy_mc, tt_full_mc, dy_embed, tt_embed, massWindow, pairOption = 'iso', nBtag = '', doDraw = False):

    yieldForMediumCat = {}
    eventCounterForMediumCat = {}
    yieldForLooseCat = {}
    eventCounterForLooseCat = {}
    inclusiveYields = {}
    eventCounterForInclusive = {}

    bins = [19, 225, 700]
    dy_embed_1M = r.TH1F('dy_embed_1M', '', bins[0], bins[1], bins[2])
    dy_embed_2M = r.TH1F('dy_embed_2M', '', bins[0], bins[1], bins[2])
    tt_embed_1M = r.TH1F('tt_embed_1M', '', bins[0], bins[1], bins[2])
    tt_embed_2M = r.TH1F('tt_embed_2M', '', bins[0], bins[1], bins[2])

    fileList = [('DY_inclusive', dy_mc), ('tt_inclusive', tt_full_mc), ('DY_embed', dy_embed), ('tt_embed', tt_embed)]

    for indexFile in range(len(fileList)):
        name = fileList[indexFile][0]
        iFile =  r.TFile(fileList[indexFile][1])
        iTree = iFile.Get('eventTree')
        yieldForMediumCat[name+'_1M'] = 0.0
        yieldForMediumCat[name+'_2M'] = 0.0
        yieldForLooseCat[name+'_1L'] = 0.0
        yieldForLooseCat[name+'_2L'] = 0.0
        eventCounterForInclusive[name] = 0
        eventCounterForMediumCat[name+'_1M'] = 0
        eventCounterForMediumCat[name+'_2M'] = 0
        eventCounterForLooseCat[name+'_1L'] = 0
        eventCounterForLooseCat[name+'_2L'] = 0
        total = iTree.GetEntries()
        inclusiveYields[name] = 0.0
        counter = 0
        counter_0 = 0
        isEmbed = False
        isData = False
        if 'emb' in name:
            isEmbed = True
        if name == 'DY_embed':
            isData = True

        for i in range(0, total):
            tool.printProcessStatus(iCurrent=i+1, total=total, processName = 'Looping sample [%s]' %name, iPrevious=i)
            #Fill Histograms
            iTree.GetEntry(i)

            #get the right pair of taus based on isoMin or ptMax
            if (iTree.nElectrons > 0 or iTree.nMuons > 0):
                continue

            #get event category
            signSelection, isoSelection, bTagSelection = makeWholeTools2.findCategory(tree = iTree, 
                                                                                      iso = makeWholeSample_cfg.iso, 
                                                                                      option = pairOption,
                                                                                      isData = isData,
                                                                                      relaxedRegionOption = makeWholeSample_cfg.Relax,
                                                                                      isEmbed = isEmbed,
                                                                                      usePassJetTrigger = makeWholeSample_cfg.usePassJetTrigger,
                                                                                      nBtag = nBtag)
            if signSelection == None or isoSelection == None or bTagSelection == None:
                continue
            looseTag, mediumTag = getRightBTagCatName(bTagSelection)

            if iTree.HLT_Any == 0:
                continue
            if iTree.ZTT == 0:
                continue
            if 'tt' not in name:
                tmpEventYield = iTree.triggerEff*iTree.decayModeWeight
            else:
                tmpEventYield = iTree.triggerEff

            if  massWindow and not makeWholeTools2.passCut(iTree, pairOption):
                continue

            #calculate inclusiveYield
            if (signSelection == "OS") and (isoSelection == "Tight"):
                eventCounterForInclusive[name] += 1
                if 'data' in iTree.sampleName:
                    inclusiveYields[name] += tmpEventYield*iTree.embeddedWeight
                elif isEmbed:
                    inclusiveYields[name] += iTree.triggerEff*iTree.xs*0.983*(lumi/tt_semi_InitEvents)*iTree.embeddedWeight*iTree.PUWeight
                else:
                    if not makeWholeTools2.passJetTrigger(iTree):
                        continue
                    inclusiveYields[name] += tmpEventYield*iTree.xs*lumi*iTree.PUWeight/(iTree.initEvents+0.0)
            else:
                continue
                
            fillValue = iTree.fMassKinFit

            #calculate category yield
            if mediumTag != '0M':
                if isEmbed:
                    if 'data' in iTree.sampleName:
                        yieldForMediumCat["%s_%s" %(name, mediumTag)] += tmpEventYield*iTree.embeddedWeight
                        if mediumTag == '1M':
                            dy_embed_1M.Fill(fillValue, tmpEventYield*iTree.embeddedWeight)
                        else:
                            dy_embed_2M.Fill(fillValue, tmpEventYield*iTree.embeddedWeight)
                    else:
                        yieldForMediumCat["%s_%s" %(name, mediumTag)] += tmpEventYield*iTree.xs*0.983*(lumi/tt_semi_InitEvents)*iTree.embeddedWeight*iTree.PUWeight
                        if mediumTag == '1M':
                            tt_embed_1M.Fill(fillValue, tmpEventYield*iTree.xs*0.983*(lumi/tt_semi_InitEvents)*iTree.embeddedWeight*iTree.PUWeight)
                        else:
                            tt_embed_2M.Fill(fillValue, tmpEventYield*iTree.xs*0.983*(lumi/tt_semi_InitEvents)*iTree.embeddedWeight*iTree.PUWeight)

                else:
                    yieldForMediumCat["%s_%s" %(name, mediumTag)] += tmpEventYield*iTree.xs*lumi*iTree.PUWeight/iTree.initEvents
                eventCounterForMediumCat["%s_%s" %(name, mediumTag)] += 1


            #calculate loose cat yield for embed samples
            if isEmbed and (looseTag != '0L'):
                if 'data' in iTree.sampleName:
                    yieldForLooseCat["%s_%s" %(name, looseTag)] += tmpEventYield*iTree.embeddedWeight
                else:
                    yieldForLooseCat["%s_%s" %(name, looseTag)] += tmpEventYield*iTree.embeddedWeight*iTree.xs*0.983*lumi/tt_semi_InitEvents
                eventCounterForLooseCat["%s_%s" %(name, looseTag)] += 1

        print ''

        if isEmbed:
            print name
            print 'inclusive yield for %s: %.2f +/- %.2f' %(name, inclusiveYields[name], calcSysUncSingle(inclusiveYields[name], eventCounterForInclusive[name]))
            print '1-Medium %s yield: %.2f +/- %.2f \t events: %i' %(name, yieldForMediumCat[name+'_1M'], calcSysUncSingle(yieldForMediumCat[name+'_1M'], eventCounterForMediumCat[name+'_1M']), eventCounterForMediumCat[name+'_1M'])
            print '1-Loose %s yield: %.2f  +/- %.2f \t events: %i' %(name, yieldForLooseCat[name+'_1L'], calcSysUncSingle(yieldForLooseCat[name+'_1L'], eventCounterForLooseCat[name+'_1L']), eventCounterForLooseCat[name+'_1L'])
            print '2-Medium %s yield: %.2f +/- %.2f \t events: %i' %(name, yieldForMediumCat[name+'_2M'], calcSysUncSingle(yieldForMediumCat[name+'_2M'], eventCounterForMediumCat[name+'_2M']), eventCounterForMediumCat[name+'_2M'])
            print '2-Loose %s yield: %.2f +/- %.2f \t events: %i' %(name, yieldForLooseCat[name+'_2L'], calcSysUncSingle(yieldForLooseCat[name+'_2L'], eventCounterForLooseCat[name+'_2L']), eventCounterForLooseCat[name+'_2L'])

        else:
            print 'inclusive yield for %s: %.2f' %(name, inclusiveYields[name])

    delta_dy_inclusive = calcSysUncSingle(inclusiveYields['DY_embed'], eventCounterForInclusive['DY_embed'])
    delta_tt_inclusive = calcSysUncSingle(inclusiveYields['tt_embed'], eventCounterForInclusive['tt_embed'])
    delta_dy_1M = calcSysUncSingle(yieldForMediumCat['DY_embed_1M'], eventCounterForMediumCat['DY_embed_1M'])
    delta_tt_1M = calcSysUncSingle(yieldForMediumCat['tt_embed_1M'], eventCounterForMediumCat['tt_embed_1M'])
    delta_dy_2M = calcSysUncSingle(yieldForMediumCat['DY_embed_2M'], eventCounterForMediumCat['DY_embed_2M'])
    delta_tt_2M = calcSysUncSingle(yieldForMediumCat['tt_embed_2M'], eventCounterForMediumCat['tt_embed_2M'])

    sysUnc_1M = calcSysUnc(sf = (yieldForMediumCat['DY_embed_1M']-yieldForMediumCat['tt_embed_1M'])/(inclusiveYields['DY_embed'] - inclusiveYields['tt_embed']), 
                        numA = yieldForMediumCat['DY_embed_1M'], 
                        numB = yieldForMediumCat['tt_embed_1M'],
                        denomA = inclusiveYields['DY_embed'],
                        denomB = inclusiveYields['tt_embed'],
                        delta_numA = delta_dy_1M,
                        delta_numB = delta_tt_1M,
                        delta_denomA = delta_dy_inclusive,
                        delta_denomB = delta_tt_inclusive)

    sysUnc_2M = calcSysUnc(sf = (yieldForMediumCat['DY_embed_2M']-yieldForMediumCat['tt_embed_2M'])/(inclusiveYields['DY_embed'] - inclusiveYields['tt_embed']), 
                        numA = yieldForMediumCat['DY_embed_2M'], 
                        numB = yieldForMediumCat['tt_embed_2M'],
                        denomA = inclusiveYields['DY_embed'],
                        denomB = inclusiveYields['tt_embed'],
                        delta_numA = delta_dy_2M,
                        delta_numB = delta_tt_2M,
                        delta_denomA = delta_dy_inclusive,
                        delta_denomB = delta_tt_inclusive)

    sysUnc_xs_1M = calcSysUnc(sf = (yieldForMediumCat['DY_embed_1M']-yieldForMediumCat['tt_embed_1M'])/(inclusiveYields['DY_embed'] - inclusiveYields['tt_embed']), 
                        numA = yieldForMediumCat['DY_embed_1M'], 
                        numB = yieldForMediumCat['tt_embed_1M'],
                        denomA = inclusiveYields['DY_embed'],
                        denomB = inclusiveYields['tt_embed'],
                        delta_numA = 0,
                        delta_numB = yieldForMediumCat['tt_embed_1M']*0.1,
                        delta_denomA = 0,
                        delta_denomB = inclusiveYields['tt_embed']*0.1)

    sysUnc_xs_2M = calcSysUnc(sf = (yieldForMediumCat['DY_embed_2M']-yieldForMediumCat['tt_embed_2M'])/(inclusiveYields['DY_embed'] - inclusiveYields['tt_embed']), 
                        numA = yieldForMediumCat['DY_embed_2M'], 
                        numB = yieldForMediumCat['tt_embed_2M'],
                        denomA = inclusiveYields['DY_embed'],
                        denomB = inclusiveYields['tt_embed'],
                        delta_numA = 0,
                        delta_numB = yieldForMediumCat['tt_embed_2M']*0.1,
                        delta_denomA = 0,
                        delta_denomB = inclusiveYields['tt_embed']*0.1)

    preScaleFactor = inclusiveYields['DY_inclusive']/(inclusiveYields['DY_embed'] - inclusiveYields['tt_embed'])
    scaleFactor_1M = preScaleFactor*(yieldForMediumCat['DY_embed_1M']-yieldForMediumCat['tt_embed_1M'])
    scaleFactor_2M = preScaleFactor*(yieldForMediumCat['DY_embed_2M']-yieldForMediumCat['tt_embed_2M'])

    preScaleFactor2 = (inclusiveYields['DY_inclusive']+inclusiveYields['tt_inclusive'])/(inclusiveYields['DY_embed'])
    scaleFactor_1M2 = preScaleFactor2*(yieldForMediumCat['DY_embed_1M'])
    scaleFactor_2M2 = preScaleFactor2*(yieldForMediumCat['DY_embed_2M'])

    print ''
    print 'predicted DY in 1M: %.2fx(%.2f +/- %.2f - %.2f +/- %.2f)/(%.2f +/- %.2f - %.2f +/- %.2f) = %.2f +/- %.2f%% (statistical)' %(inclusiveYields['DY_inclusive'],
                                                                         yieldForMediumCat['DY_embed_1M'],
                                                                         calcSysUncSingle(yieldForMediumCat['DY_embed_1M'], eventCounterForMediumCat['DY_embed_1M']),
                                                                         yieldForMediumCat['tt_embed_1M'],
                                                                         calcSysUncSingle(yieldForMediumCat['tt_embed_1M'], eventCounterForMediumCat['tt_embed_1M']),
                                                                         inclusiveYields['DY_embed'],
                                                                         calcSysUncSingle(inclusiveYields['DY_embed'], eventCounterForInclusive['DY_embed']),
                                                                         inclusiveYields['tt_embed'],
                                                                         calcSysUncSingle(inclusiveYields['tt_embed'], eventCounterForInclusive['tt_embed']),
                                                                         scaleFactor_1M,
                                                                         sysUnc_1M*inclusiveYields['DY_inclusive']/scaleFactor_1M*100
                                                                        )
    print 'predicted DY in 2M: %.2fx(%.2f +/- %.2f - %.2f +/- %.2f)/(%.2f +/- %.2f - %.2f +/- %.2f) = %.2f +/- %.2f%% (statistical)' %(inclusiveYields['DY_inclusive'],
                                                                         yieldForMediumCat['DY_embed_2M'],
                                                                         calcSysUncSingle(yieldForMediumCat['DY_embed_2M'], eventCounterForMediumCat['DY_embed_2M']),
                                                                         yieldForMediumCat['tt_embed_2M'],
                                                                         calcSysUncSingle(yieldForMediumCat['tt_embed_2M'], eventCounterForMediumCat['tt_embed_2M']),
                                                                         inclusiveYields['DY_embed'],
                                                                         calcSysUncSingle(inclusiveYields['DY_embed'], eventCounterForInclusive['DY_embed']),
                                                                         inclusiveYields['tt_embed'],
                                                                         calcSysUncSingle(inclusiveYields['tt_embed'], eventCounterForInclusive['tt_embed']),
                                                                         scaleFactor_2M,
                                                                         sysUnc_2M*inclusiveYields['DY_inclusive']/scaleFactor_2M*100
                                                                        )
    print ''
    print 'predicted DY in 1M: %.2fx(%.2f - %.2f +/- %.2f)/(%.2f - %.2f +/- %.2f) = %.2f +/- %.2f%% (tt_xs)' %(inclusiveYields['DY_inclusive'],
                                                                         yieldForMediumCat['DY_embed_1M'],
                                                                         yieldForMediumCat['tt_embed_1M'],
                                                                         yieldForMediumCat['tt_embed_1M']*0.1,
                                                                         inclusiveYields['DY_embed'],
                                                                         inclusiveYields['tt_embed'],
                                                                         inclusiveYields['tt_embed']*0.1,
                                                                         scaleFactor_1M,
                                                                         sysUnc_xs_1M*inclusiveYields['DY_inclusive']/scaleFactor_1M*100
                                                                        )
    print 'predicted DY in 2M: %.2fx(%.2f - %.2f +/- %.2f)/(%.2f - %.2f +/- %.2f) = %.2f +/- %.2f%% (tt_xs)' %(inclusiveYields['DY_inclusive'],
                                                                         yieldForMediumCat['DY_embed_2M'],
                                                                         yieldForMediumCat['tt_embed_2M'],
                                                                         yieldForMediumCat['tt_embed_2M']*0.1,
                                                                         inclusiveYields['DY_embed'],
                                                                         inclusiveYields['tt_embed'],
                                                                         inclusiveYields['tt_embed']*0.1,
                                                                         scaleFactor_2M,
                                                                         sysUnc_xs_2M*inclusiveYields['DY_inclusive']/scaleFactor_2M*100
                                                                        )
    print ''
    print 'DY MC in 1M: %.2f' %yieldForMediumCat['DY_inclusive_1M']
    print 'DY MC in 2M: %.2f' %yieldForMediumCat['DY_inclusive_2M']
#     print 'predicted DY+tt in 1M: %.2f' %scaleFactor_1M2
#     print 'predicted DY+tt in 2M: %.2f' %scaleFactor_2M2


    if doDraw:
        position = (0.6, 0.9 - 0.06*2, 0.87, 0.9)
        l1 = tool.setMyLegend(position, [(dy_embed_1M, 'dy_embed_1M'), (tt_embed_1M, 'tt_embed_1M')])
        l2 = tool.setMyLegend(position, [(dy_embed_2M, 'dy_embed_2M'), (tt_embed_2M, 'tt_embed_2M')])

        psfile = 'DY_embed_tauUp.pdf'
        c = r.TCanvas("c","Test", 800, 600)
        dy_embed_1M.Draw()
        dy_embed_1M.SetTitle(';fMassKinFit;')
        tt_embed_1M.SetLineStyle(2)
        tt_embed_1M.SetLineColor(r.kRed)
        tt_embed_1M.Draw('same')
        l1.Draw('same')

        c.Print('%s(' %psfile)
        dy_embed_2M.Draw()
        dy_embed_2M.SetTitle(';fMassKinFit;')

        tt_embed_2M.SetLineStyle(2)
        tt_embed_2M.SetLineColor(r.kRed)
        tt_embed_2M.Draw('same')
        l2.Draw('same')

        c.Print('%s)' %psfile)


    return scaleFactor_1M, scaleFactor_2M, scaleFactor_1M2, scaleFactor_2M2, preScaleFactor
示例#5
0
def l2MYieldCalculator(sample, massWindow, pairOption = 'iso', nBtag = '', ZLL = False):

    yieldForMediumCat = {}
    yieldForLooseCat = {}
    eventCounterForMediumCat = {}
    eventCounterForLooseCat = {}

    iFile =  r.TFile(sample)
    iTree = iFile.Get('eventTree')
    yieldForMediumCat['1M'] = 0.0
    yieldForMediumCat['2M'] = 0.0
    yieldForLooseCat['1L'] = 0.0
    yieldForLooseCat['2L'] = 0.0
    eventCounterForMediumCat['1M'] = 0.0
    eventCounterForMediumCat['2M'] = 0.0
    eventCounterForLooseCat['1L'] = 0.0
    eventCounterForLooseCat['2L'] = 0.0

    total = iTree.GetEntries()

    for i in range(0, total):
        tool.printProcessStatus(iCurrent=i+1, total=total, processName = 'Looping sample [%s]' %sample, iPrevious=i)
        iTree.GetEntry(i)
            
        #get the right pair of taus based on isoMin or ptMax
        if (iTree.nElectrons > 0 or iTree.nMuons > 0):
            continue
        if not makeWholeTools2.passJetTrigger(iTree):
            continue

        if ZLL and iTree.ZLL == 0:
            continue
        #get event category
        signSelection, isoSelection, bTagSelection = makeWholeTools2.findCategory(tree = iTree, 
                                                                                  iso = makeWholeSample_cfg.iso, 
                                                                                  option = pairOption,
                                                                                  isData = False,
                                                                                  relaxedRegionOption = makeWholeSample_cfg.Relax,
                                                                                  isEmbed = False,
                                                                                  usePassJetTrigger = makeWholeSample_cfg.usePassJetTrigger,
                                                                                  nBtag = nBtag)

        if signSelection == None or isoSelection == None:
            continue
        looseTag, mediumTag = getRightBTagCatName(bTagSelection)

        if  massWindow and not makeWholeTools2.passCut(iTree, pairOption):
            continue
        #calculate category yield
        if (signSelection == "OS") and (isoSelection == "Tight") and (mediumTag != '0M'):
            yieldForMediumCat[mediumTag] += iTree.triggerEff*iTree.xs*lumi*iTree.PUWeight/iTree.initEvents
            eventCounterForMediumCat[mediumTag] += 1

        #calculate loose cat yield for embed samples
        if (signSelection == "OS") and (isoSelection == "Tight") and (looseTag != '0L'):
            yieldForLooseCat[looseTag] += iTree.triggerEff*iTree.xs*lumi*iTree.PUWeight/iTree.initEvents
            eventCounterForLooseCat[looseTag] += 1
    print ''


    scaleFactor_1M = yieldForMediumCat['1M']/yieldForLooseCat['1L']
    scaleFactor_2M = yieldForMediumCat['2M']/yieldForLooseCat['2L']

    print '[%s] (1L): %.2f  %.0f'%(sample, yieldForLooseCat['1L'], eventCounterForLooseCat['1L'])
    print '[%s] (2L): %.2f  %.0f'%(sample, yieldForLooseCat['2L'], eventCounterForLooseCat['2L'])
    print '[%s] (1M): %.2f  %.0f'%(sample, yieldForMediumCat['1M'], eventCounterForMediumCat['1M'])
    print '[%s] (2M): %.2f  %.0f'%(sample, yieldForMediumCat['2M'], eventCounterForMediumCat['2M'])

    unc_1M = calcSysUncSingle(yieldForMediumCat['1M'], eventCounterForMediumCat['1M'])
    unc_2M = calcSysUncSingle(yieldForMediumCat['2M'], eventCounterForMediumCat['2M'])

    print '1M: %.2f +/- %.1f%%' %(yieldForMediumCat['1M'], unc_1M*100/yieldForMediumCat['1M'])
    print '2M: %.2f +/- %.1f%%' %(yieldForMediumCat['2M'], unc_2M*100/yieldForMediumCat['2M'])

    return yieldForMediumCat['1M'], yieldForMediumCat['2M']
示例#6
0
def run():
    fileList = []
    for i in range(len(makeWholeSample_cfg.sampleConfigs)):
        #configs name, location, selection, useMediumForYield
        fileList.append((makeWholeSample_cfg.sampleConfigs[i][0], 
                        makeWholeSample_cfg.sampleConfigs[i][1], 
                        makeWholeSample_cfg.sampleConfigs[i][2],
                        makeWholeSample_cfg.sampleConfigs[i][3]))
        if makeWholeSample_cfg.sampleConfigs[i][0] == 'DY_inclusive':
            dy_mc = makeWholeSample_cfg.sampleConfigs[i][1]
        if makeWholeSample_cfg.sampleConfigs[i][0] == 't#bar{t}':
            tt_full_mc = makeWholeSample_cfg.sampleConfigs[i][1]
        if makeWholeSample_cfg.sampleConfigs[i][0] == 'DY_embed':
            dy_embed = makeWholeSample_cfg.sampleConfigs[i][1]
        if makeWholeSample_cfg.sampleConfigs[i][0] == 'tt_embed':
            tt_embed = makeWholeSample_cfg.sampleConfigs[i][1]

    oFileName = makeWholeSample_cfg.oFileName
    oFile = r.TFile(oFileName, 'RECREATE')
    oTree = r.TTree('eventTree', '')
    iso = makeWholeSample_cfg.iso
    nSamples = len(fileList)

    mJJ = array('f', [0.])
    svMass = array('f', [0.])
    fMass = array('f', [0.])
    fMassKinFit = array('f', [0.])
    chi2KinFit = array('f', [0.])
    chi2KinFit2 = array('f', [0.])
    PUWeight = array('f', [0.])
    iso1 = array('f', [0.])
    iso2 = array('f', [0.])
    pt1 = array('f', [0.])
    pt2 = array('f', [0.])
    CSVJ1Pt = array('f', [0.])
    CSVJ2Pt = array('f', [0.])
    CSVJ2 = array('f', [0.])
    NBTags = array('i', [0])
    triggerEff = array('f', [0.])
    sampleName = bytearray(20)
    genMatchName = bytearray(3)
    xs = array('f', [0.])
    embeddedWeight = array('f', [0.])
    decayModeWeight = array('f', [0.])

    initEvents = array('f', [0.])
    Category = bytearray(5)

    xsValues = {}
    initEventsValues = {}
    eventsSaved = {}


    yieldForMediumCat = {}
    inclusiveYields = {}

    inclusiveYields = {}
    catYields = {}
    svMassRange = [20, 0, 400]
    L2T_value = 0


    oTree.Branch("mJJ", mJJ, "mJJ/F")
    oTree.Branch("fMass", fMass, "fMass/F")
    oTree.Branch("fMassKinFit", fMassKinFit, "fMassKinFit/F")
    oTree.Branch("chi2KinFit", chi2KinFit, "chi2KinFit/F")
    oTree.Branch("chi2KinFit2", chi2KinFit2, "chi2KinFit2/F")
    oTree.Branch("xs", xs, "xs/F")
    oTree.Branch("initEvents", initEvents, "initEvents/F")
    oTree.Branch("NBTags", NBTags, "NBTags/I")
    oTree.Branch("Category", Category, "Category[21]/C")

    oTree.Branch("svMass", svMass, "svMass/F")
    oTree.Branch("CSVJ2", CSVJ2, "CSVJ2/F")
    oTree.Branch("iso1", iso1, "iso1/F")
    oTree.Branch("iso2", iso2, "iso2/F")
    oTree.Branch("pt1", pt1, "pt1/F")
    oTree.Branch("pt2", pt2, "pt2/F")
    oTree.Branch("CSVJ1Pt", CSVJ1Pt, "CSVJ1Pt/F")
    oTree.Branch("CSVJ2Pt", CSVJ2Pt, "CSVJ2Pt/F")

    oTree.Branch("triggerEff", triggerEff, "triggerEff/F")
    oTree.Branch("PUWeight", PUWeight, "PUWeight/F")
    oTree.Branch("embeddedWeight", embeddedWeight, "embeddedWeight/F")
    oTree.Branch("decayModeWeight", decayModeWeight, "decayModeWeight/F")

    oTree.Branch("sampleName", sampleName, "sampleName[21]/C")
    oTree.Branch("genMatchName", genMatchName, "genMatchName[21]/C")

    for indexFile in range(nSamples):
        eventsSavedCounter_1M = 0.0
        eventsSavedCounter_2M = 0.0

        name = fileList[indexFile][0]
        option = fileList[indexFile][2]
        iFile =  r.TFile(fileList[indexFile][1])
        iTree = iFile.Get('eventTree')
        useMediumCat4Yield = fileList[indexFile][3]
        if useMediumCat4Yield:
            yieldForMediumCat[name+'_1M'] = 0.0
            yieldForMediumCat[name+'_2M'] = 0.0

        total = iTree.GetEntries()
        isData = False
        if ('data' in name) or ('DY_embed' in name):
            isData = True
        if 'emb' in name:
            isEmbed = True
            inclusiveYields[name] = 0.0
        else:
            isEmbed = False
        if 'inclusive' in name:
            isInclusive = True
            inclusiveYields[name] = 0.0
        else:
            isInclusive = False
        cat = ''
        region = 'bTag'
        if '1M' in option:
            region = '1M'
        elif '2M' in option:
            region = '2M'
        elif '1L' in option:
            region = '1L'
            cat = '1M'
        elif '2L' in option:
            region = '2L'
            cat = '2M'

        for i in range(0, total):
            tool.printProcessStatus(iCurrent=i+1, total=total, processName = 'Looping sample [%s]' %name, iPrevious=i)
            #Fill Histograms
            iTree.GetEntry(i)

            #get the right pair of taus based on isoMin or ptMax
            rightPair = makeWholeTools2.findRightPair(iTree, makeWholeSample_cfg.pairOption)

            if makeWholeSample_cfg.thirdLeptonVeto and (iTree.nElectrons > 0 or iTree.nMuons > 0):
                continue
            if iTree.HLT_Any == 0:
                continue

            #get event category
            signSelection, isoSelection, bTagSelection = makeWholeTools2.findCategory(tree = iTree, 
                                                                                      iso = makeWholeSample_cfg.iso, 
                                                                                      option = makeWholeSample_cfg.pairOption,
                                                                                      isData = isData,
                                                                                      relaxedRegionOption = makeWholeSample_cfg.Relax,
                                                                                      isEmbed = isEmbed,
                                                                                      usePassJetTrigger = makeWholeSample_cfg.usePassJetTrigger,
                                                                                      nBtag = makeWholeSample_cfg.bTagShift)

            if signSelection == None or isoSelection == None or bTagSelection == None:
                continue
            looseTag, mediumTag = getRightBTagCatName(bTagSelection)

            if isEmbed and iTree.ZTT == 0:
                continue
            if name == 'ZLL' and iTree.ZLL == 0:
                continue
            if name == 'ZTT' and iTree.ZTT == 0:
                continue
            #calculate category yield
            if useMediumCat4Yield:
                if (not makeWholeSample_cfg.massWindow) or (makeWholeSample_cfg.massWindow and makeWholeTools2.passCut(iTree, makeWholeSample_cfg.pairOption)):
                    if (signSelection == "OS") and (isoSelection == "Tight") and (mediumTag != '0M'):
                        if isEmbed:
                            if 'data' in iTree.sampleName:
                                yieldForMediumCat["%s_%s" %(name, mediumTag)] += iTree.triggerEff
                            else:
                                yieldForMediumCat["%s_%s" %(name, mediumTag)] += iTree.triggerEff*iTree.xs*0.983*lumi/tt_semi_InitEvents
                        elif name == 'ZLL':
                            yieldForMediumCat["%s_%s" %(name, mediumTag)] += iTree.triggerEff*iTree.xs*lumi*iTree.PUWeight*iTree.decayModeWeight/iTree.initEvents

                        else:
                            yieldForMediumCat["%s_%s" %(name, mediumTag)] += iTree.triggerEff*iTree.xs*lumi*iTree.PUWeight/iTree.initEvents
        

            passSelection, bRegion = passCut(option, signSelection, isoSelection, looseTag, mediumTag)

            if option[:len(option)-1] != signSelection+isoSelection:
                continue
            mJJ[0] = iTree.mJJ
            fMass[0] = iTree.fMass
            fMassKinFit[0] = iTree.fMassKinFit
            chi2KinFit[0] = iTree.chi2KinFit
            chi2KinFit2[0] = iTree.chi2KinFit2
            svMass[0] = iTree.svMass.at(rightPair)
            iso1[0] = iTree.iso1.at(rightPair)
            iso2[0] = iTree.iso2.at(rightPair)
            CSVJ2[0] = iTree.CSVJ2
            NBTags[0] = int(iTree.NBTags)
            triggerEff[0] = iTree.triggerEff
            pt1[0] = iTree.pt1.at(rightPair)
            pt2[0] = iTree.pt2.at(rightPair)
            CSVJ1Pt[0] = iTree.CSVJ1Pt
            CSVJ2Pt[0] = iTree.CSVJ2Pt
            decayModeWeight[0] = 1.0
            embeddedWeight[0] = 1.0

            if '_semi' not in iTree.sampleName:
                tmpSampleName = iTree.sampleName[0:iTree.sampleName.find('_')]
            else:
                tmpSampleName = iTree.sampleName[0:iTree.sampleName.find('_semi')+5]
            if 'data' in tmpSampleName and (not isEmbed):
                sampleName[:21] = name
                initEvents[0] = 1.0
                xs[0] = 1.0           
            elif ('data' in tmpSampleName) and isEmbed:
                sampleName[:21] = 'DY_embed'
                initEvents[0] = 1.0
                xs[0] = 1.0
                embeddedWeight[0] = iTree.embeddedWeight
                decayModeWeight[0] = iTree.decayModeWeight    
            elif not isEmbed:
                if name == 'signals':
                    decayModeWeight[0] = iTree.decayModeWeight
                initEvents[0] = iTree.initEvents
                xs[0] = iTree.xs
                sampleName[:21] = tmpSampleName
                if name == 'MCOSRelax':
                    sampleName[:21] = 'MCOSRelax'
                if 'HToTauTau' in name:
                    sampleName[:21] = name
                elif name == 'ZLL':
                    sampleName[:21] = 'ZLL'
                    decayModeWeight[0] = iTree.decayModeWeight
                elif name == 'ZTT':
                    sampleName[:21] = 'ZTT'
                    decayModeWeight[0] = iTree.decayModeWeight
            else:
                initEvents[0] = tt_semi_InitEvents
                xs[0] = iTree.xs*0.983
                sampleName[:21] = 'tt_embed'
                embeddedWeight[0] = iTree.embeddedWeight       
                decayModeWeight[0] = iTree.decayModeWeight    

            if str(sampleName) not in initEventsValues.keys():
                if 'data' not in str(sampleName):
                    initEventsValues[str(sampleName)] = iTree.initEvents
                    xsValues[str(sampleName)] = iTree.xs
                eventsSaved[str(sampleName)] = 0.0
    #         genMatchName[:3] = findMatch(iTree, isData, rightPair)
            if isData:
                PUWeight[0] = 1.0
            else:
                PUWeight[0] = iTree.PUWeight

            if mediumTag == '0M':
                Category[:21] = '0M'
                oTree.Fill()
            if passSelection:
                Category[:21] = bRegion
                oTree.Fill()
            else:
                continue

            if makeWholeSample_cfg.massWindow and (not makeWholeTools2.passCut(iTree, makeWholeSample_cfg.pairOption)):
                continue
            if isData:
                eventsSaved[str(sampleName)] += 1
                if bRegion == '1M':
                    eventsSavedCounter_1M += 1
                elif bRegion == '2M':
                    eventsSavedCounter_2M += 1
            elif not isEmbed:
                eventsSaved[str(sampleName)] += triggerEff[0]
                if bRegion == '1M':
                    eventsSavedCounter_1M += triggerEff[0]*xsValues[str(sampleName)]/initEventsValues[str(sampleName)]*PUWeight[0]*lumi
                elif bRegion == '2M':
                    eventsSavedCounter_2M += triggerEff[0]*xsValues[str(sampleName)]/initEventsValues[str(sampleName)]*PUWeight[0]*lumi

        print ' --- Events Saved: (1M) %.2f    (2M) %.2f' %(eventsSavedCounter_1M, eventsSavedCounter_2M)
        if isEmbed:
            print name
            print 'inclusive yield for %s: %.2f' %(name, inclusiveYields[name])
            print '1-Medium category yield for %s: %.2f' %(name, yieldForMediumCat[name+'_1M'])
            print '2-Medium category yield for %s: %.2f' %(name, yieldForMediumCat[name+'_2M'])

        elif isInclusive:
            print 'inclusive yield for %s: %.2f' %(name, inclusiveYields[name])



    nSamples = len(initEventsValues.keys())
    initEvents = r.TH1F('initEvents', '', nSamples, 0, nSamples)
    xsHist = r.TH1F('xs', '', nSamples, 0, nSamples)

    for iKey in initEventsValues.keys():
        if 'data' not in iKey:
            initEvents.Fill(iKey, initEventsValues[iKey])
            xsHist.Fill(iKey, xsValues[iKey])

    weights = makeWholeTools2.calculateSF(fileList = makeWholeSample_cfg.sampleConfigsTools,
                                          sigRegionOption = 'Tight', 
                                          relaxedRegionOption = makeWholeSample_cfg.Relax, 
                                          verbose = True,
                                          isoTight = 1.0, 
                                          pairOption = makeWholeSample_cfg.pairOption,
                                          massWindow = makeWholeSample_cfg.massWindow,
                                          usePassJetTrigger = makeWholeSample_cfg.usePassJetTrigger,
                                          nBtag = '')

    scaleFactor_1M, scaleFactor_2M, scaleFactor_1M2, scaleFactor_2M2, preScaleFactor = embedDYYieldCalculator.yieldCalculator(dy_mc = dy_mc, 
                                                                                                                              tt_full_mc = tt_full_mc,
                                                                                                                              dy_embed = dy_embed, 
                                                                                                                              tt_embed = tt_embed, 
                                                                                                                              massWindow = makeWholeSample_cfg.massWindow,
                                                                                                                              pairOption = makeWholeSample_cfg.pairOption)


    print weights

    #define histograms
    L_to_T_SF_0M = r.TH1F('L_to_T_SF_0M', '', 1, 0, 1)
    MC2Embed2Cat_0M = r.TH1F('MC2Embed2Cat_0M', '', 1, 0, 1)

    L_to_T_1M = r.TH1F('L_to_T_1M', '', 1, 0, 1)
    L_to_T_SF_1M = r.TH1F('L_to_T_SF_1M', '', 1, 0, 1)
    MC2Embed2Cat_1M = r.TH1F('MC2Embed2Cat_1M', '', 1, 0, 1)
    EmbedWithTTLep_1M = r.TH1F('EmbedWithTTLep_1M', '', 1, 0, 1)
    DYwithTTScale_1M = r.TH1F('DYwithTTScale_1M', '', 1, 0, 1)

    L_to_T_2M = r.TH1F('L_to_T_2M', '', 1, 0, 1)
    L_to_T_SF_2M = r.TH1F('L_to_T_SF_2M', '', 1, 0, 1)
    MC2Embed2Cat_2M = r.TH1F('MC2Embed2Cat_2M', '', 1, 0, 1)
    EmbedWithTTLep_2M = r.TH1F('EmbedWithTTLep_2M', '', 1, 0, 1)
    DYwithTTScale_2M = r.TH1F('DYwithTTScale_2M', '', 1, 0, 1)

    yieldForMediumCatHists = {}


    #save histograms
    L_to_T_1M.Fill(0.5, weights[0])
    L_to_T_2M.Fill(0.5, weights[1])
    L_to_T_SF_1M.Fill(0.5, weights[2])
    L_to_T_SF_2M.Fill(0.5, weights[3])
    L_to_T_SF_0M.Fill(0.5, weights[4])

    # preScaleFactor = inclusiveYields['DY_inclusive']/(inclusiveYields['DY_embed'] - inclusiveYields['tt_embed'])
    # scaleFactor_1M = preScaleFactor*(yieldForMediumCat['DY_embed_1M']-yieldForMediumCat['tt_embed_1M'])
    # scaleFactor_2M = preScaleFactor*(yieldForMediumCat['DY_embed_2M']-yieldForMediumCat['tt_embed_2M'])
    MC2Embed2Cat_0M.Fill(0.5, preScaleFactor)
    MC2Embed2Cat_1M.Fill(0.5, scaleFactor_1M)
    MC2Embed2Cat_2M.Fill(0.5, scaleFactor_2M)
    DYwithTTScale_1M.Fill(0.5, scaleFactor_1M2)
    DYwithTTScale_2M.Fill(0.5, scaleFactor_2M2)

    print 'Embed DY prediction (1M): %.2f' %scaleFactor_1M
    print 'Embed DY prediction (2M): %.2f' %scaleFactor_2M

    oFile.cd()

    initEvents.Write()
    xsHist.Write()
    L_to_T_1M.Write()
    L_to_T_SF_1M.Write()
    L_to_T_2M.Write()
    L_to_T_SF_2M.Write()
    L_to_T_SF_0M.Write()
    MC2Embed2Cat_0M.Write()
    MC2Embed2Cat_1M.Write()
    MC2Embed2Cat_2M.Write()
    DYwithTTScale_1M.Write()
    DYwithTTScale_2M.Write()

    for iKey in yieldForMediumCat.keys():
        yieldForMediumCatHists[iKey] = r.TH1F(iKey, '', 1, 0, 1)
        yieldForMediumCatHists[iKey].Fill(0.5, yieldForMediumCat[iKey])
        print '%s prediction: %.2f' %(iKey, yieldForMediumCat[iKey])
        yieldForMediumCatHists[iKey].Write()
    oTree.Write()
    oFile.Close()

    print 'Combined event saved at: %s' %oFileName