Exemple #1
0
def plot_tag_mu_pt():
    overflow = True
    norm = True
    logy = True
    setTDRStyle()
    c1 = r.TCanvas()
    xbins, xlow, xhigh = 50, 0., 50.
    his = r.TH1F("plot_tag_mu_pt", "plot_tag_mu_pt", xbins, xlow, xhigh)
    for pt, eta in zip(tag_mu_pt, tag_mu_eta):
        if abs(eta) < 2.5:
            if ~overflow or pt < xhigh: his.Fill(pt, 1.)
            else: his.Fill(xhigh - 1.e-6, 1.)
    if norm:
        his.Scale(1. / his.Integral(0, his.GetXaxis().GetNbins() + 1))
        his.GetYaxis().SetTitle("Normalised counts")
        if logy: his.GetYaxis().SetRangeUser(0.001, 1.0)
        else: his.GetYaxis().SetRangeUser(0.0, 1.0)
    else:
        his.GetYaxis().SetTitle("Events / bin")
    his.SetTitle("")
    his.GetXaxis().SetTitle("p^{tag}_{T} [GeV]")
    his.DrawNormalized("hist")
    his.SetLineWidth(2)
    r.gStyle.SetOptStat(0)
    if logy: c1.SetLogy()
    c1.Update()
    c1.SaveAs("{:s}/{:s}/plot_tag_mu_pt.pdf".format(
        dir, "bkstll" if bkstll == True else "bkll"))
Exemple #2
0
def plot_object_scale():
    logz = True
    setTDRStyle()
    r.tdrStyle.SetPadRightMargin(0.15)
    particles = [
        ("lp", "l^{#pm}", r.kBlue, 20),
        ("lm", "l^{#mp}", r.kRed, 24),
        ("k", "K^{#pm}", r.kOrange, 21),
    ]
    if bkstll == True:
        particles += [("pi", "#pi^{#mp}", r.kGreen, 25)]
    for ip, (name, title, colour, style) in enumerate(particles):
        c1 = r.TCanvas()
        his = r.TH2F(name, name, 40, 0., 5., 40, 0., 2.)
        pt_reco = getattr(this, "{:s}_reco_pt".format(name))
        pt_gen = getattr(this, "{:s}_pt".format(name))
        for reco, gen, trig in zip(pt_reco, pt_gen, mu_low):
            if trig and gen > 0.:
                his.Fill(gen, reco / gen if reco > 0. else 0., 1.)
        his.Scale(1. / his.Integral(
            0,
            his.GetXaxis().GetNbins() + 1,
            0,
            his.GetYaxis().GetNbins() + 1,
        ))
        his.Draw("colz")
        his.SetTitle(";" + title +
                     " p^{gen}_{T} [GeV];p^{reco}_{T}/p^{gen}_{T}")
        his.SetMinimum(0.00001)
        his.SetMaximum(0.05)
        r.gStyle.SetOptStat(0)
        if logz: c1.SetLogz()
        c1.Update()
        c1.SaveAs("{:s}/{:s}/plot_scale_{:s}.pdf".format(
            dir, "bkstll" if bkstll == True else "bkll", name))
Exemple #3
0
def eff_vs_hadron_pt_cut():
    setTDRStyle()
    c1 = r.TCanvas()
    his = r.TEfficiency("", "", 11, -50., 1050.)
    effs = {}
    for pt_cut in range(0, 1100, 100):
        #k_pass_tmp  = ( k_pt  > pt_cut/1000. ) & ( abs(k_eta)  < eta_cut )
        #pi_pass_tmp = ( pi_pt > pt_cut/1000. ) & ( abs(pi_eta) < eta_cut )
        #all_pass_tmp = lp_pass & lm_pass & k_pass_tmp & ( pi_pass_tmp | ~bkstll )
        k_pass_tmp = (k_reco_pt > pt_cut / 1000.) & (abs(k_reco_eta) <
                                                     eta_reco_cut)
        pi_pass_tmp = (pi_reco_pt > pt_cut / 1000.) & (abs(pi_reco_eta) <
                                                       eta_reco_cut)
        all_pass_tmp = lp_reco_pass & lm_reco_pass & k_pass_tmp & (pi_pass_tmp
                                                                   | ~bkstll)
        for in_acc, trig in zip(all_pass_tmp, mu_low):
            if trig: his.Fill(1 if in_acc == True else 0, pt_cut)
    his.SetTitle(";hadron p^{gen}_{T} cut [MeV];Acceptance")
    his.Draw("")
    r.gPad.Update()
    his.GetPaintedGraph().GetYaxis().SetNdivisions(510)
    his.GetPaintedGraph().GetYaxis().SetRangeUser(0., 0.6)
    his.GetPaintedGraph().GetXaxis().SetRangeUser(-50., 1050.)
    his.SetMarkerColor(r.kRed)
    his.SetMarkerStyle(20)
    his.SetMarkerSize(1.)
    his.SetLineColor(r.kRed)
    r.gStyle.SetOptStat(0)
    c1.Update()
    c1.SaveAs("{:s}/{:s}/eff_vs_hadron_pt_cut.pdf".format(
        dir, "bkstll" if bkstll == True else "bkll"))
Exemple #4
0
def plot_lepton_hadron_corr():

    # utility
    from ROOT import TLorentzVector as P4

    def add(pt1, eta1, phi1, m1, pt2, eta2, phi2, m2):
        v1 = P4()
        v1.SetPtEtaPhiM(pt1, eta1, phi1, m1)
        v2 = P4()
        v2.SetPtEtaPhiM(pt2, eta2, phi2, m2)
        v3 = v1 + v2
        return v3.Pt(), v3.Eta(), v3.Phi(), v3.M()

    # leptons
    l_pt = []
    l_eta = []
    l_phi = []
    l_m = []
    for pt1, eta1, phi1, m1, pt2, eta2, phi2, m2 in zip(
            lp_pt, lp_eta, lp_phi, lp_m, lm_pt, lm_eta, lm_phi, lm_m):
        pt, eta, phi, m = add(pt1, eta1, phi1, m1, pt2, eta2, phi2, m2)
        l_pt.append(pt)
        l_eta.append(eta)
        l_phi.append(phi)
        l_m.append(m)

    # hadrons
    h_pt = []
    h_eta = []
    h_phi = []
    h_m = []
    if bkstll:
        for pt1, eta1, phi1, m1, pt2, eta2, phi2, m2 in zip(
                k_pt, k_eta, k_phi, k_m, pi_pt, pi_eta, pi_phi, pi_m):
            pt, eta, phi, m = add(pt1, eta1, phi1, m1, pt2, eta2, phi2, m2)
            h_pt.append(pt)
            h_eta.append(eta)
            h_phi.append(phi)
            h_m.append(m)
    else:
        h_pt = k_pt
        h_eta = k_eta
        h_phi = k_phi
        h_m = k_m

    # plot
    setTDRStyle()
    r.tdrStyle.SetPadRightMargin(0.15)
    c1 = r.TCanvas()
    his = r.TH2F("plot_lepton_hadron_corr", "plot_lepton_hadron_corr", 40, 0.,
                 10., 40, 0., 10.)
    for lpt, hpt, trig in zip(l_pt, h_pt, mu_low):
        if trig: his.Fill(lpt, hpt, 1.)
    his.SetTitle(";p^{leptons}_{T} [GeV];p^{hadrons}_{T} [GeV]")
    his.GetZaxis().SetNdivisions(505)
    his.DrawNormalized("colz")
    r.gStyle.SetOptStat(0)
    c1.Update()
    c1.SaveAs("{:s}/{:s}/plot_lepton_hadron_corr.pdf".format(
        dir, "bkstll" if bkstll == True else "bkll"))
Exemple #5
0
def plot_tag_mu_eta():
    overflow = True
    norm = True
    logy = True
    setTDRStyle()
    c1 = r.TCanvas()
    xbins, xhigh = 60, 3.
    his = r.TH1F("plot_tag_mu_eta", "plot_tag_mu_eta", xbins, -xhigh, xhigh)
    for pt, eta in zip(tag_mu_pt, tag_mu_eta):
        if pt > 7:
            if ~overflow or abs(eta) < xhigh: his.Fill(eta, 1.)
            elif eta > xhigh: his.Fill(xhigh - 1.e-6, 1.)
            elif eta < -xhigh: his.Fill(-xhigh + 1.e-6, 1.)
            else: print "error", eta
    if norm:
        his.Scale(1. / his.Integral(0, his.GetXaxis().GetNbins() + 1))
        his.GetYaxis().SetTitle("Normalised counts")
        if logy: his.GetYaxis().SetRangeUser(0.001, 1.0)
        else: his.GetYaxis().SetRangeUser(0.0, 1.0)
    else:
        his.GetYaxis().SetTitle("Events / bin")
    his.SetTitle("")
    his.GetXaxis().SetTitle("#eta^{tag}")
    his.DrawNormalized("hist")
    his.SetLineWidth(2)
    r.gStyle.SetOptStat(0)
    if logy: c1.SetLogy()
    c1.Update()
    c1.SaveAs("{:s}/{:s}/plot_tag_mu_eta.pdf".format(
        dir, "bkstll" if bkstll == True else "bkll"))
Exemple #6
0
def acc_vs_pt_cut():
    setTDRStyle()
    c1 = r.TCanvas()
    his = r.TEfficiency("", "", 51, -50., 5050.)
    for pt_cut in range(0, 5100, 100):
        lp_pass_tmp = (lp_pt > pt_cut / 1000.) & (abs(lp_eta) < eta_cut)
        lm_pass_tmp = (lm_pt > pt_cut / 1000.) & (abs(lm_eta) < eta_cut)
        k_pass_tmp = (k_pt > pt_cut / 1000.) & (abs(k_eta) < eta_cut)
        all_pass_tmp = lp_pass_tmp & lm_pass_tmp & k_pass_tmp & (pi_pass
                                                                 | ~bkstll)
        for in_acc, trig in zip(all_pass_tmp, mu_low):
            if trig: his.Fill(1 if in_acc == True else 0, pt_cut)
    his.SetTitle(";p^{gen}_{T} cut [MeV];Acceptance")
    his.Draw("")
    r.gPad.Update()
    his.GetPaintedGraph().GetYaxis().SetNdivisions(510)
    his.GetPaintedGraph().GetYaxis().SetRangeUser(0., 0.6)
    his.GetPaintedGraph().GetXaxis().SetRangeUser(-50., 5050.)
    his.SetMarkerColor(r.kRed)
    his.SetMarkerStyle(20)
    his.SetMarkerSize(1.)
    his.SetLineColor(r.kRed)
    r.gStyle.SetOptStat(0)
    c1.Update()
    c1.SaveAs("{:s}/acc_vs_pt_cut.pdf".format(dir))
    c1.SaveAs("{:s}/acc_vs_pt_cut.root".format(dir))
Exemple #7
0
 def __init__(self,mainConfig=None):        
     self.canvas = None
     self.plotPad = None
     self.ratioPad = None
     
     self.primaryPlot = None
     self.secondaryPlots = []
     
     self.ratioErrsSize = []
     self.ratioErrsHist = []
     
     self.ratioPairs = []
     self.nominators = []
     self.denominators = []
     setTDRStyle() 
     
     self.latexCMS      = None
     self.latexCMSExtra = None
     self.latexCuts     = None
     self.latexLumi     = None
     self.latexRegion   = None
     
     if mainConfig != None:
         self.regionName = mainConfig.plot.label2
         if hasattr(mainConfig, "jzbType"):
             self.jzbType = mainConfig.jzbType
         self.personalWork = mainConfig.personalWork
         self.preliminary = mainConfig.preliminary
         self.forTWIKI = mainConfig.forTWIKI
         self.plotData = mainConfig.plotData
         self.hasRatio = mainConfig.plotRatio
         self.lumiInt = mainConfig.runRange.printval
         self.labelX = mainConfig.plot.xaxis
         self.labelY = mainConfig.plot.yaxis
Exemple #8
0
 def __init__(self):
     setTDRStyle()
     self.inFiles = {}
     self.labels = {}
     self.colors = {}
     self.markers = {}
     self.outPath = None
     self.granularity = standardGranularity
     self.order = []
Exemple #9
0
 def __init__(self):
     setTDRStyle()
     self.names = {}
     self.inFiles = {}
     self.labels = {}
     self.colors = {}
     self.outPath = None
     self.hasSystematics = {}
     self.systematics = {}
     self.granularity = standardGranularity
     self.title = ""
 def __init__(self):
     setTDRStyle()
     self.names = {}
     self.inFiles = {}
     self.labels = {}
     self.colors = {}
     self.outPath = None
     self.hasSystematics = {}
     self.systematics = {}
     self.granularity = standardGranularity
     self.title = ""
Exemple #11
0
 def __init__(self):
     setTDRStyle()
     self.names = {}
     self.outPath = None
     self.granularity = standardGranularity
     self.title = ""
     self.points = []
     self.years = []
     self.doLumi = True
     self.colors = []
     self.log = False
Exemple #12
0
def eff_vs_lepton_pt_cut(only_acc=False, use_effs=False):
    setTDRStyle()
    c1 = r.TCanvas()
    his = r.TEfficiency("", "", 51, -50., 5050.)
    for pt_cut in range(0, 5100, 100):
        if only_acc == True:
            lp_pass_tmp = (ll_lead_pt > pt_cut / 1000.) & (abs(ll_lead_eta) <
                                                           eta_cut)
            lm_pass_tmp = (ll_sub_pt > pt_cut / 1000.) & (abs(ll_sub_eta) <
                                                          eta_cut)
            #lp_pass_tmp = ( lp_pt > pt_cut/1000. ) & ( abs(lp_eta) < eta_cut )
            #lm_pass_tmp = ( lm_pt > pt_cut/1000. ) & ( abs(lm_eta) < eta_cut )
            all_pass_tmp = lp_pass_tmp & lm_pass_tmp & k_pass & (pi_pass
                                                                 | ~bkstll)
        else:
            lp_pass_tmp = (ll_lead_reco_pt > pt_cut / 1000.) & (
                abs(ll_lead_reco_eta) < eta_reco_cut)
            lm_pass_tmp = (ll_sub_reco_pt > pt_cut / 1000.) & (
                abs(ll_sub_reco_eta) < eta_reco_cut)
            #lp_pass_tmp = ( lp_reco_pt > pt_cut/1000. ) & ( abs(lp_reco_eta) < eta_reco_cut )
            #lm_pass_tmp = ( lm_reco_pt > pt_cut/1000. ) & ( abs(lm_reco_eta) < eta_reco_cut )
            all_pass_tmp = lp_pass_tmp & lm_pass_tmp & k_reco_pass & (
                pi_reco_pass | ~bkstll)
        # need to weight lp_pass_tmp and lm_pass_tmp
        for in_acc, trig, eff, wei in zip(all_pass_tmp, mu_low, ll_effs,
                                          ll_weights):
            if trig:
                #weight = wei if use_effs else 1
                #his.Fill(weight if in_acc == True else 0,pt_cut)
                if use_effs:
                    his.FillWeighted(1 if in_acc == True else 0, eff, pt_cut)
                    his.FillWeighted(0, 1. - eff, pt_cut)
                else:
                    his.Fill(1 if in_acc == True else 0, pt_cut)

    his.SetTitle(";lepton p^{gen}_{T} cut [MeV];" + "{:s}".format(
        "Acceptance" if only_acc == True else "#it{A}#times#epsilon"))
    his.Draw("")
    r.gPad.Update()
    his.GetPaintedGraph().GetYaxis().SetNdivisions(510)
    his.GetPaintedGraph().GetYaxis().SetRangeUser(0., 0.6)
    his.GetPaintedGraph().GetXaxis().SetRangeUser(-50., 5050.)
    his.SetMarkerColor(r.kRed)
    his.SetMarkerStyle(20)
    his.SetMarkerSize(1.)
    his.SetLineColor(r.kRed)
    r.gStyle.SetOptStat(0)
    c1.Update()
    c1.SaveAs("{:s}/{:s}/{:s}_vs_lepton_pt_cut.pdf".format(
        dir, "bkstll" if bkstll == True else "bkll",
        "acc" if only_acc == True else "eff"))
    print "Acc. x Eff.:", his.GetEfficiency(his.FindFixBin(500.))
Exemple #13
0
def plot_hadron_corr():
    setTDRStyle()
    r.tdrStyle.SetPadRightMargin(0.15)
    c1 = r.TCanvas()
    his = r.TH2F("hadron", "hadron", 40, 0., 10., 40, 0., 10.)
    for lp, lm, trig in zip(pi_pt, k_pt, mu_low):
        if trig: his.Fill(lp, lm, 1.)
    his.SetTitle(";p^{#pi}_{T} [GeV];p^{K}_{T} [GeV]")
    his.GetZaxis().SetNdivisions(505)
    his.DrawNormalized("colz")
    r.gStyle.SetOptStat(0)
    c1.Update()
    c1.SaveAs("{:s}/{:s}/plot_hadron_corr.pdf".format(
        dir, "bkstll" if bkstll == True else "bkll"))
Exemple #14
0
def plot_tag_eta_corr():
    setTDRStyle()
    r.tdrStyle.SetPadRightMargin(0.15)
    c1 = r.TCanvas()
    his = r.TH2F("plot_tag_eta_corr", "plot_tag_eta_corr", 30, -3., 3., 50,
                 -5., 5.)
    for bd, tag, trig in zip(bd_eta, tag_mu_eta, mu_low):
        if trig: his.Fill(tag, bd, 1.)
    his.SetTitle(";#eta^{tag};#eta^{B}")
    his.GetZaxis().SetNdivisions(505)
    his.DrawNormalized("colz")
    r.gStyle.SetOptStat(0)
    c1.Update()
    c1.SaveAs("{:s}/{:s}/plot_tag_eta_corr.pdf".format(
        dir, "bkstll" if bkstll == True else "bkll"))
Exemple #15
0
def plot_tag_pt_corr():
    setTDRStyle()
    r.tdrStyle.SetPadRightMargin(0.15)
    c1 = r.TCanvas()
    his = r.TH2F("plot_tag_pt_corr", "plot_tag_pt_corr", 40, 0., 20., 40, 0.,
                 20.)
    for bd, tag, trig in zip(bd_pt, tag_mu_pt, mu_low):
        if trig: his.Fill(tag, bd, 1.)
    his.SetTitle(";p^{tag}_{T} [GeV];p^{B}_{T} [GeV]")
    his.GetZaxis().SetNdivisions(505)
    his.DrawNormalized("colz")
    r.gStyle.SetOptStat(0)
    c1.Update()
    c1.SaveAs("{:s}/{:s}/plot_tag_pt_corr.pdf".format(
        dir, "bkstll" if bkstll == True else "bkll"))
Exemple #16
0
def deltar_vs_pt():
    logz = True
    setTDRStyle()
    r.tdrStyle.SetPadRightMargin(0.15)
    particles = [
        ("lp", "l^{#pm}", r.kBlue, 20),
        ("lm", "l^{#mp}", r.kRed, 24),
        ("k", "K^{#pm}", r.kOrange, 21),
    ]
    if bkstll == True:
        particles += [("pi", "#pi^{#mp}", r.kGreen, 25)]
    for ip, (name, title, colour, style) in enumerate(particles):
        c1 = r.TCanvas()
        his = r.TH2F(name, name, 40, 0., 5., 32, 0., 3.2)
        reco_pt = getattr(this, "{:s}_reco_pt".format(name))
        reco_eta = getattr(this, "{:s}_reco_eta".format(name))
        reco_phi = getattr(this, "{:s}_reco_phi".format(name))
        gen_pt = getattr(this, "{:s}_pt".format(name))
        gen_eta = getattr(this, "{:s}_eta".format(name))
        gen_phi = getattr(this, "{:s}_phi".format(name))
        for     trig,in_acc,\
                gpt,geta,gphi,\
                rpt,reta,rphi in zip(mu_low,all_pass,
                                     gen_pt,gen_eta,gen_phi,
                                     reco_pt,reco_eta,reco_phi) :
            if trig and in_acc:
                dr = deltaR(reta, rphi, geta, gphi)
                his.Fill(gpt, dr, 1.)
        his.Scale(1. / his.Integral(
            0,
            his.GetXaxis().GetNbins() + 1,
            0,
            his.GetYaxis().GetNbins() + 1,
        ))
        his.Draw("colz")
        his.SetTitle(";p^{gen}_{T} [GeV];#DeltaR")
        his.SetMinimum(0.00001)
        his.SetMaximum(0.05)
        r.gStyle.SetOptStat(0)
        if logz: c1.SetLogz()
        c1.Update()
        c1.SaveAs("{:s}/{:s}/plot_deltar_vs_pt_{:s}.pdf".format(
            dir, "bkstll" if bkstll == True else "bkll", name))
def main():

    #OnZPickleICHEP = loadPickles("shelves/OnZBG_ICHEPLegacy_36fb.pkl")
    #RaresPickle8TeVLegacy = loadPickles("shelves/RareOnZBG_8TeVLegacy_36fb.pkl")
    RaresPickle2016 = loadPickles("shelves/RareOnZBG_Run2016_36fb.pkl")
    RaresPickle2017 = loadPickles("shelves/RareOnZBG_Run2017_42fb.pkl")
    RaresPickle2018 = loadPickles("shelves/RareOnZBG_Run2018_60fb.pkl")
    #RaresPickle = loadPickles("shelves/RareOnZBG_8TeVLegacy_36fb.pkl")

    name = "cutAndCount"
    countingShelves2016 = {"Rares": RaresPickle2016}
    countingShelves2017 = {"Rares": RaresPickle2017}
    countingShelves2018 = {"Rares": RaresPickle2018}

    countingShelves = {
        "Run2016_36fb": countingShelves2016,
        "Run2017_42fb": countingShelves2017,
        "Run2018_60fb": countingShelves2018
    }
    setTDRStyle()
    makeOverviewPlot(countingShelves, "zeroBJets")
    makeOverviewPlot(countingShelves, "oneOrMoreBJets")
def makeMassRes(inputDATA,inputMC,output,weights):
    style = setTDRStyle()
    ROOT.gStyle.SetTitleYOffset(1.45)
    ROOT.gStyle.SetTitleXOffset(1.45)
    ROOT.gStyle.SetOptFit(0)
    ROOT.gStyle.SetStatX(.9)
    ROOT.gStyle.SetStatY(.9)
    
    (data_B,mc_B,ptdaB,ptmcB) = loadHistos(inputDATA,inputMC,"BB",weights)
    (data_E,mc_E,ptdaE,ptmcE) = loadHistos(inputDATA,inputMC,"BE",weights)

    drawMassRes(data_B,mc_B,output,"BB",ptdaB,ptmcB)
    drawMassRes(data_E,mc_E,output,"BE",ptdaE,ptmcE)
def makeMassRes(inputDATA,inputMC,output,weights,weights2,trackType,funct,mcIsData,dataIsMC):
	style = setTDRStyle()
	gStyle.SetTitleYOffset(1.45)
	gStyle.SetTitleXOffset(1.45)
	gStyle.SetOptFit(0)
	gStyle.SetStatX(.9)
	gStyle.SetStatY(.9)
	
	(data_B,mc_B,ptdaB,ptmcB) = loadHistos(inputDATA,inputMC,"BB",weights,weights2,trackType,mcIsData,dataIsMC)
	(data_E,mc_E,ptdaE,ptmcE) = loadHistos(inputDATA,inputMC,"BE",weights,weights2,trackType,mcIsData,dataIsMC)
	# ~ (data_E2,mc_E2,ptdaE2,ptmcE2) = loadHistos(inputDATA,inputMC,"BE_neweta",weights,weights2,trackType,mcIsData,dataIsMC)

	drawMassRes(data_B,mc_B,output,"BB",ptdaB,ptmcB,trackType,funct,mcIsData,dataIsMC,inputDATA)
	drawMassRes(data_E,mc_E,output,"BE",ptdaE,ptmcE,trackType,funct,mcIsData,dataIsMC,inputDATA)
Exemple #20
0
def plot_object_eff(lead=False):
    setTDRStyle()
    particles = \
        [("ll_lead","l^{lead}",r.kBlue,20),("ll_sub","l^{sub}",r.kRed,24)] if lead == True else \
        [("lp","l^{#pm}",r.kBlue,20),("lm","l^{#mp}",r.kRed,24)]
    particles += [("k", "K^{#pm}", r.kOrange, 21)]
    if bkstll == True: particles += [("pi", "#pi^{#mp}", r.kGreen, 25)]
    c1 = r.TCanvas()
    legend = r.TLegend(0.3, 0.7 - 0.07 * len(particles), 0.5, 0.7)
    hists = odict()
    for ip, (name, title, colour, style) in enumerate(particles):
        hists[name] = r.TEfficiency(name, name, 40, 0., 5.)
        his = hists[name]
        gen_pt = getattr(this, "{:s}_pt".format(name))
        reco_pt = getattr(this, "{:s}_reco_pt".format(name))
        for in_acc, reco, gen, trig in zip(all_pass, reco_pt, gen_pt, mu_low):
            if trig and in_acc: his.Fill(1 if reco > 0.5 else 0, gen)
        options = ""
        if ip > 0: options += "same"
        his.Draw(options)
        r.gPad.Update()
        his.SetTitle(";p^{gen}_{T} [GeV];Efficiency")
        his.GetPaintedGraph().GetYaxis().SetNdivisions(510)
        his.GetPaintedGraph().GetYaxis().SetRangeUser(0., 1.05)
        his.GetPaintedGraph().GetXaxis().SetRangeUser(0., 5.)
        his.SetMarkerColor(colour)
        his.SetMarkerStyle(style)
        his.SetMarkerSize(1.5)
        his.SetLineColor(colour)
        legend.AddEntry(his, title, "pe")
    r.gStyle.SetOptStat(0)
    legend.SetTextSize(0.05)
    legend.Draw("same")
    c1.Update()
    c1.SaveAs("{:s}/{:s}/plot_object_eff.pdf".format(
        dir, "bkstll" if bkstll == True else "bkll"))
Exemple #21
0
def tag_pt_vs_eta(reco=False):
    setTDRStyle()
    r.tdrStyle.SetPadRightMargin(0.2)
    c1 = r.TCanvas()
    numer = r.TH2F("numer", "numer", 5, 7., 27., 5, 0., 2.5)
    denom = r.TH2F("denom", "denom", 5, 7., 27., 5, 0., 2.5)
    acceptance = all_reco_pass if reco else all_pass
    for in_acc, pt, eta in zip(acceptance, tag_mu_pt, tag_mu_eta):
        pt = pt if pt < 27 else 27. - 1.e-6
        eta = abs(eta) if abs(eta) < 2.5 else 2.5 - 1.e-6
        denom.Fill(pt, eta, 1.)
        if in_acc: numer.Fill(pt, eta, 1.)
    his = r.TH2F(numer)
    his.Divide(denom)
    title = "Acceptance times efficiency" if reco else "Acceptance"
    his.SetTitle(";p^{tag}_{T} [GeV];|#eta^{tag}|;" + title)
    his.Draw("colztext")
    his.SetMarkerSize(2.)
    r.gStyle.SetPaintTextFormat("4.2g")
    his.GetZaxis().SetRangeUser(0., 0.2 if reco else 0.7)
    r.gStyle.SetOptStat(0)
    c1.Update()
    c1.SaveAs("{:s}/{:s}/plot_tag_pt_vs_eta.pdf".format(
        dir, "bkstll" if bkstll == True else "bkll"))
def plotDataMC(datahist,mchist,usedata, label1, label2,name,filename):
	

	hCanvas = TCanvas("hCanvas", "Distribution", 800,800)
	if usedata==True:
                plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1)
                ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3)
                setTDRStyle()
                plotPad.UseCurrentStyle()
                ratioPad.UseCurrentStyle()
                plotPad.Draw("hist")
                ratioPad.Draw("hist")
                plotPad.cd()
        else:
                plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
                setTDRStyle()
                plotPad.UseCurrentStyle()
                plotPad.Draw()
                plotPad.cd()	
	colors = createMyColors()		
	
	legend = TLegend(0.55, 0.6, 0.925, 0.925)
	legend.SetFillStyle(0)
	legend.SetBorderSize(0)
	legend.SetTextFont(42)
	legendEta = TLegend(0.45, 0.75, 0.925, 0.925)
	legendEta.SetFillStyle(0)
	legendEta.SetBorderSize(0)
	legendEta.SetTextFont(42)
	legendEta.SetNColumns(2)
	latex = ROOT.TLatex()
	latex.SetTextFont(42)
	latex.SetTextAlign(31)
	latex.SetTextSize(0.04)
	latex.SetNDC(True)
	latexCMS = ROOT.TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.06)
	latexCMS.SetNDC(True)
	latexCMSExtra = ROOT.TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.045)
	latexCMSExtra.SetNDC(True)	
	legendHists = []
	legendHistData = ROOT.TH1F()
	category = ROOT.TLatex()
	category.SetNDC(True)
	category.SetTextSize(0.04)
	if usedata==True:	
		legend.AddEntry(legendHistData,label1,"pe")	
		legendEta.AddEntry(legendHistData,label1,"pe")	

	#process.label = process.label.replace("#mu^{+}#mu^{-}","e^{+^{*}}e^{-}")
	temphist = ROOT.TH1F()
	temphist.SetFillColor(3)
	legendHists.append(temphist.Clone)
	#legend.AddEntry(temphist,label2,"l")
	#legendEta.AddEntry(temphist,process.label,"f")
	
	# Modify plot pad information	
	nEvents=-1

	ROOT.gStyle.SetOptStat(0)
	
	intlumi = ROOT.TLatex()
	intlumi.SetTextAlign(12)
	intlumi.SetTextSize(0.045)
	intlumi.SetNDC(True)
	intlumi2 = ROOT.TLatex()
	intlumi2.SetTextAlign(12)
	intlumi2.SetTextSize(0.07)
	intlumi2.SetNDC(True)
	scalelabel = ROOT.TLatex()
	scalelabel.SetTextAlign(12)
	scalelabel.SetTextSize(0.03)
	scalelabel.SetNDC(True)
	metDiffLabel = ROOT.TLatex()
	metDiffLabel.SetTextAlign(12)
	metDiffLabel.SetTextSize(0.03)
	metDiffLabel.SetNDC(True)
	chi2Label = ROOT.TLatex()
	chi2Label.SetTextAlign(12)
	chi2Label.SetTextSize(0.03)
	chi2Label.SetNDC(True)
	hCanvas.SetLogy()


	# Luminosity information	
	plotPad.cd()
	plotPad.SetLogy(0)
	plotPad.SetLogy()
	if usedata==True:
		yMax = datahist.GetBinContent(datahist.GetMaximumBin())*1000
		yMin = 0.00000001
		xMax = datahist.GetXaxis().GetXmax()
		xMin = datahist.GetXaxis().GetXmin()
	else:	
		yMax = mchist.GetBinContent(datahist.GetMaximumBin())
		yMin = 0.00000001
		xMax = mchist.GetXaxis().GetXmax()
		xMin = mchist.GetXaxis().GetXmin()	
		yMax = yMax*10000
	if name.find("dimuon")!=-1:
		plotPad.DrawFrame(xMin,yMin,xMax,yMax,"; m_{#mu#mu}[GeV] ;Events/GeV")
	else:
		plotPad.DrawFrame(xMin,yMin,xMax,yMax,"; m_{ee}[GeV] ;Events/GeV")
	# Draw signal information
	
	# Draw background from stack
	mchist.SetFillColor(0)
	mchist.SetLineColor(2)
	legend.AddEntry(mchist,label2,"l")
	mchist.Draw("samehist")		

	# Draw data
	datahist.SetMinimum(0.0001)
	if usedata==True:
		datahist.SetMarkerStyle(8)
		datahist.Draw("samepehist")	

	# Draw legend
	legend.Draw()
	plotPad.SetLogx()
	latex.DrawLatex(0.95,0.96,"13 TeV")
	yLabelPos = 0.85
	cmsExtra = "Preliminary"
	if not usedata==True:
		cmsExtra = "#splitline{Preliminary}{Simulation}"
		yLabelPos = 0.82	
	latexCMS.DrawLatex(0.19,0.89,"CMS")
	category.DrawLatex(0.3,0.7,name)
	latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra))
	#~ print datahist.Integral()
	if usedata==True:
		try:
			ratioPad.cd()
			ratioPad.SetLogx()
		except AttributeError:
			print ("Plot fails. Look up in errs/failedPlots.txt")
			outFile =open("errs/failedPlots.txt","a")
			outFile.write('%s\n'%plot.filename%("_"+run.label+"_"+dilepton))
			outFile.close()
			#plot.cuts=baseCut
			return 1
		ratioGraphs =  ratios.RatioGraph(datahist,mchist, xMin=xMin, xMax=xMax,title="R_{mumu}/R_{ee}",yMin=0,yMax=2.0,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=10000000000000,labelSize=0.125,pull=False)
		ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8)
					

	ROOT.gPad.RedrawAxis()
	plotPad.RedrawAxis()
	if usedata==True:

		ratioPad.RedrawAxis()
	if not os.path.exists("plots"):
		os.makedirs("plots")	
	hCanvas.Print("plots/%s.pdf"%filename)
Exemple #23
0
def main():
    ### for data

    histos = ["BBBE"]
    #~ labels = ["dielectron_Moriond2017_BB","dielectron_Moriond2017_BE"]
    labels = ["dielectron_Moriond2017_BBBE"]

    #~ bins = [4,7]
    bins = [4]

    massPlot = getPlot("massPlotForLimit")
    #~ massPlotSmeared = getPlot("massPlotSmeared")
    massPlotUp = getPlot("massPlotUp")
    massPlotDown = getPlot("massPlotDown")
    massPlotPUUp = getPlot("massPlotPUUp")
    massPlotPUDown = getPlot("massPlotPUDown")
    #~ massPlotWeighted = getPlot("massPlotWeighted")

    for i, histo in enumerate(histos):
        label = labels[i]

        drellyan = Process(getattr(Backgrounds, "DrellYan"))
        other = Process(getattr(Backgrounds, "Other"))
        #~ drellyan = Process(getattr(Signals,"CITo2Mu_Lam34TeVConLL"))

        dyHist = deepcopy(drellyan.loadHistogramProjected(massPlot, bins[i]))
        dyHistScaleUp = deepcopy(
            drellyan.loadHistogramProjected(massPlotUp, bins[i]))
        dyHistScaleDown = deepcopy(
            drellyan.loadHistogramProjected(massPlotDown, bins[i]))
        dyHistPUUp = deepcopy(
            drellyan.loadHistogramProjected(massPlotPUUp, bins[i]))
        dyHistPUDown = deepcopy(
            drellyan.loadHistogramProjected(massPlotPUDown, bins[i]))

        dyHist.Add(deepcopy(other.loadHistogramProjected(massPlot, bins[i])))
        dyHistScaleUp.Add(
            deepcopy(other.loadHistogramProjected(massPlotUp, bins[i])))
        dyHistScaleDown.Add(
            deepcopy(other.loadHistogramProjected(massPlotDown, bins[i])))
        dyHistPUUp.Add(
            deepcopy(other.loadHistogramProjected(massPlotPUUp, bins[i])))
        dyHistPUDown.Add(
            deepcopy(other.loadHistogramProjected(massPlotPUDown, bins[i])))

        dyHist.Add(deepcopy(other.loadHistogramProjected(massPlot, 7)))
        dyHistScaleUp.Add(deepcopy(other.loadHistogramProjected(massPlotUp,
                                                                7)))
        dyHistScaleDown.Add(
            deepcopy(other.loadHistogramProjected(massPlotDown, 7)))
        dyHistPUUp.Add(deepcopy(other.loadHistogramProjected(massPlotPUUp, 7)))
        dyHistPUDown.Add(
            deepcopy(other.loadHistogramProjected(massPlotPUDown, 7)))

        dyHist.Add(deepcopy(drellyan.loadHistogramProjected(massPlot, 7)))
        dyHistScaleUp.Add(
            deepcopy(drellyan.loadHistogramProjected(massPlotUp, 7)))
        dyHistScaleDown.Add(
            deepcopy(drellyan.loadHistogramProjected(massPlotDown, 7)))
        dyHistPUUp.Add(
            deepcopy(drellyan.loadHistogramProjected(massPlotPUUp, 7)))
        dyHistPUDown.Add(
            deepcopy(drellyan.loadHistogramProjected(massPlotPUDown, 7)))

        #~ rebin = 250

        binningEle = binning(channel="electron")
        dyHist = rebin(dyHist, binningEle)
        dyHistScaleUp = rebin(dyHistScaleUp, binningEle)
        dyHistScaleDown = rebin(dyHistScaleDown, binningEle)
        dyHistPUUp = rebin(dyHistPUUp, binningEle)
        dyHistPUDown = rebin(dyHistPUDown, binningEle)

        #~ dyHist.Rebin(rebin)
        #~ dyHistPUUp.Rebin(rebin)
        #~ dyHistPUDown.Rebin(rebin)
        #~ dyHistScaleUp.Rebin(rebin)
        #~ dyHistScaleDown.Rebin(rebin)
        hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)

        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        setTDRStyle()
        plotPad.UseCurrentStyle()
        ratioPad.UseCurrentStyle()
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()

        plotPad.DrawFrame(250, 0.00001, 5000, 500000000,
                          "; dielectron mass [GeV]; Events / 250 GeV")
        plotPad.SetLogy()
        dyHist.Draw("samehist")
        dyHist.SetFillColor(kWhite)
        dyHistScaleUp.SetFillColor(kWhite)
        dyHistScaleDown.SetFillColor(kWhite)
        dyHistPUUp.SetFillColor(kWhite)
        dyHistPUDown.SetFillColor(kWhite)
        dyHistScaleUp.SetLineColor(kBlue)
        dyHistScaleDown.SetLineColor(kBlue)
        dyHistPUUp.SetLineColor(kOrange + 2)
        dyHistPUDown.SetLineColor(kOrange + 2)
        dyHistScaleDown.Draw("samehist")
        dyHistScaleUp.Draw("samehist")
        dyHistPUUp.Draw("samehist")
        dyHistPUDown.Draw("samehist")

        legend = TLegend(0.375, 0.6, 0.925, 0.925)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextFont(42)
        legend.AddEntry(dyHist, "Default", "l")
        legend.AddEntry(dyHistScaleDown, "Scale Uncertainty", "l")
        legend.AddEntry(dyHistPUUp, "PU Uncertainty", "l")
        legend.Draw()

        ratioPad.cd()
        xMin = 250
        xMax = 5000
        yMax = 1.5
        yMin = 0
        if "BE" in label:
            yMax = 1.5
            yMin = 0.5
        ratioGraphs = ratios.RatioGraph(dyHist,
                                        dyHistScaleUp,
                                        xMin=xMin,
                                        xMax=xMax,
                                        title="Default / Uncert",
                                        yMin=yMin,
                                        yMax=yMax,
                                        ndivisions=10,
                                        color=kBlue,
                                        adaptiveBinning=10000)
        ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8)
        ratioGraphs2 = ratios.RatioGraph(dyHist,
                                         dyHistScaleDown,
                                         xMin=xMin,
                                         xMax=xMax,
                                         title="Default / Uncert",
                                         yMin=0.8,
                                         yMax=1.3,
                                         ndivisions=10,
                                         color=kBlue,
                                         adaptiveBinning=10000)
        ratioGraphs2.draw(ROOT.gPad, False, False, True, chi2Pos=0.8)
        ratioGraphs3 = ratios.RatioGraph(dyHist,
                                         dyHistPUDown,
                                         xMin=xMin,
                                         xMax=xMax,
                                         title="Default / Uncert",
                                         yMin=0.8,
                                         yMax=1.3,
                                         ndivisions=10,
                                         color=kOrange + 2,
                                         adaptiveBinning=10000)
        ratioGraphs3.draw(ROOT.gPad, False, False, True, chi2Pos=0.8)
        ratioGraphs4 = ratios.RatioGraph(dyHist,
                                         dyHistPUUp,
                                         xMin=xMin,
                                         xMax=xMax,
                                         title="Default / Uncert",
                                         yMin=0.8,
                                         yMax=1.3,
                                         ndivisions=10,
                                         color=kOrange + 2,
                                         adaptiveBinning=10000)
        ratioGraphs4.draw(ROOT.gPad, False, False, True, chi2Pos=0.8)

        #~ ratio = ratioGraphs.getGraph()

        ratio = dyHist.Clone()
        ratio.Divide(dyHistScaleUp)
        ratio.GetXaxis().SetRangeUser(0, 5000)
        ratio.GetYaxis().SetRangeUser(0, 2)
        func = TF1("f1", "pol4", 250, 5000)
        #~ func.SetParameter(0,1.1)
        ratio.Fit("f1", "R")
        #~ func.Draw("sameL")

        plotF1 = TF1("plotF1", "pol4", 250, 5000)
        plotF1.SetParameter(0, f1.GetParameter(0))
        plotF1.SetParameter(1, f1.GetParameter(1))
        plotF1.SetParameter(2, f1.GetParameter(2))
        plotF1.SetParameter(3, f1.GetParameter(3))
        plotF1.SetParameter(4, f1.GetParameter(4))
        ratio2 = dyHist.Clone()
        #~ ratio2 = ratioGraphs2.getGraph()

        ratio2.GetXaxis().SetRangeUser(0, 5000)
        ratio2.GetYaxis().SetRangeUser(0, 2)
        ratio2.Divide(dyHistScaleDown)
        func2 = TF1("f2", "pol4", 250, 5000)
        #~ func2.SetParameter(0,0.9)
        ratio2.Fit("f2", "R")
        #~ func2.Draw("sameL")
        plotF2 = TF1("plotF1", "pol4", 250, 5000)
        plotF2.SetParameter(0, f2.GetParameter(0))
        plotF2.SetParameter(1, f2.GetParameter(1))
        plotF2.SetParameter(2, f2.GetParameter(2))
        plotF2.SetParameter(3, f2.GetParameter(3))
        plotF2.SetParameter(4, f2.GetParameter(4))

        #~ ratioGraphs =  ratios.RatioGraph(dyHist,dyHistScaleUp, xMin=xMin, xMax=xMax,title="Default / Uncert",yMin=yMin,yMax=yMax,ndivisions=10,color=kBlue,adaptiveBinning=10000)
        ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8)
        #~ ratioGraphs2 =  ratios.RatioGraph(dyHist,dyHistScaleDown, xMin=xMin, xMax=xMax,title="Default / Uncert",yMin=0.8,yMax=1.3,ndivisions=10,color=kBlue,adaptiveBinning=10000)
        ratioGraphs2.draw(ROOT.gPad, False, False, True, chi2Pos=0.8)
        #~ ratioGraphs3 =  ratios.RatioGraph(dyHist,dyHistPUDown, xMin=xMin, xMax=xMax,title="Default / Uncert",yMin=0.8,yMax=1.3,ndivisions=10,color=kOrange+2,adaptiveBinning=10000)
        ratioGraphs3.draw(ROOT.gPad, False, False, True, chi2Pos=0.8)
        #~ ratioGraphs4 =  ratios.RatioGraph(dyHist,dyHistPUUp, xMin=xMin, xMax=xMax,title="Default / Uncert",yMin=0.8,yMax=1.3,ndivisions=10,color=kOrange+2,adaptiveBinning=10000)
        ratioGraphs4.draw(ROOT.gPad, False, False, True, chi2Pos=0.8)

        plotF1.Draw("sameL")
        plotF2.Draw("sameL")
        hCanvas.Print("uncertainties_%s.pdf" % label)
def compareMassRes(trackType):
	
	file2016BB = open("default2016/MassResolutionVsMass_%s_BB.pkl"%trackType)
	file2016BE = open("default2016/MassResolutionVsMass_%s_BE.pkl"%trackType)
	file2017BB = open("cruijff2016/MassResolutionVsMass_%s_BB.pkl"%trackType)
	file2017BE = open("cruijff2016/MassResolutionVsMass_%s_BE.pkl"%trackType)
	fileCBB = open("crystal2016/MassResolutionVsMass_%s_BB.pkl"%trackType)
	fileCBE = open("crystal2016/MassResolutionVsMass_%s_BE.pkl"%trackType)

	results2016BB = pickle.load(file2016BB)
	results2016BE = pickle.load(file2016BE)
	results2017BB = pickle.load(file2017BB)
	results2017BE = pickle.load(file2017BE)
	resultsCBB = pickle.load(fileCBB)
	resultsCBE = pickle.load(fileCBE)

	print results2016BB
	print results2017BB

	graph2016BB = getGraph(results2016BB,"DCBBB")
	graph2016BE = getGraph(results2016BE,"DCBBE")
	graph2017BB = getGraph(results2017BB,"CruijffBB")
	graph2017BE = getGraph(results2017BE,"CruijffBE")
	graphCBB = getGraph(resultsCBB,"CBB")
	graphCBE = getGraph(resultsCBE,"CBE")
		
	
	ratioBB = 	getRatio(results2016BB,results2017BB,"ratioBB")
	ratioBE = 	getRatio(results2016BE,results2017BE,"ratioBE")
	ratioCBB = 	getRatio(results2016BB,resultsCBB,"ratioCBB")
	ratioCBE = 	getRatio(results2016BE,resultsCBE,"ratioCBE")



	canv = TCanvas("c1","c1",800,1200)

	plotPad = TPad("plotPad","plotPad",0,0.3,1,1)
	ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
	style = setTDRStyle()
	gStyle.SetOptStat(0)
	plotPad.UseCurrentStyle()
	ratioPad.UseCurrentStyle()
	plotPad.Draw()	
	ratioPad.Draw()	
	plotPad.cd()
	plotPad.cd()
	plotPad.SetGrid()
	gStyle.SetTitleXOffset(1.45)

	xMax = 0.08
	if trackType == "Inner":
		xMax = 0.2
	if trackType == "Outer":
		xMax = 0.4

	plotPad.DrawFrame(0,-0.05,6000,0.05,";M [GeV]; mass resolution")

	graph2016BB.Draw("samepe")
	graph2017BB.Draw("samepe")
	graphCBB.Draw("samepe")
	graph2017BB.SetLineColor(kRed)
	graph2017BB.SetMarkerColor(kRed)
	graphCBB.SetLineColor(kBlue)
	graphCBB.SetMarkerColor(kBlue)

	latex = TLatex()
	latex.SetTextFont(42)
	latex.SetTextAlign(31)
	latex.SetTextSize(0.04)
	latex.SetNDC(True)
	latexCMS = TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.055)
	latexCMS.SetNDC(True)
	latexCMSExtra = TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.03)
	latexCMSExtra.SetNDC(True) 

	latex.DrawLatex(0.95, 0.96, "(13 TeV)")

	cmsExtra = "#splitline{Preliminary}{}"
	latexCMS.DrawLatex(0.19,0.88,"CMS")
	if "Simulation" in cmsExtra:
		yLabelPos = 0.81	
	else:
		yLabelPos = 0.84	

	latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra))			


	leg = TLegend(0.52, 0.76, 0.95, 0.91,"%s BB"%trackType,"brNDC")
	leg.SetFillColor(10)
	leg.SetFillStyle(0)
	leg.SetLineColor(10)
	leg.SetShadowColor(0)
	leg.SetBorderSize(1)		
	leg.AddEntry(graph2016BB,"Cruijff","l")
	leg.AddEntry(graph2017BB,"Double CB","l")
	leg.AddEntry(graphCBB,"Crystal Ball","l")

	leg.Draw()

	plotPad.RedrawAxis()


	ratioPad.cd()

	ratioBB.SetLineColor(kRed)
	ratioCBB.SetLineColor(kBlue)

	ratioPad.DrawFrame(0,0.5,6000,2.5,";ratio")

	ratioBB.Draw("samepe")
	ratioCBB.Draw("samepe")


	canv.Print("massResolutionCompareFuncMean2016_%s_BB.pdf"%trackType)
	
	
	canv = TCanvas("c1","c1",800,1200)

	plotPad = TPad("plotPad","plotPad",0,0.3,1,1)
	ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
	style = setTDRStyle()
	gStyle.SetOptStat(0)
	plotPad.UseCurrentStyle()
	ratioPad.UseCurrentStyle()
	plotPad.Draw()	
	ratioPad.Draw()	
	plotPad.cd()
	plotPad.cd()
	plotPad.SetGrid()
	gStyle.SetTitleXOffset(1.45)

	xMax = 0.08
	if trackType == "Inner":
		xMax = 0.2
	if trackType == "Outer":
		xMax = 0.4

	plotPad.DrawFrame(0,-0.05,6000,0.05,";M [GeV]; mass resolution")

	graph2016BE.Draw("samepe")
	graph2017BE.Draw("samepe")
	graphCBE.Draw("samepe")
	graph2017BE.SetLineColor(kRed)
	graph2017BE.SetMarkerColor(kRed)
	graphCBE.SetLineColor(kBlue)
	graphCBE.SetMarkerColor(kBlue)

	latex = TLatex()
	latex.SetTextFont(42)
	latex.SetTextAlign(31)
	latex.SetTextSize(0.04)
	latex.SetNDC(True)
	latexCMS = TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.055)
	latexCMS.SetNDC(True)
	latexCMSExtra = TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.03)
	latexCMSExtra.SetNDC(True) 

	latex.DrawLatex(0.95, 0.96, "(13 TeV)")

	cmsExtra = "#splitline{Preliminary}{}"
	latexCMS.DrawLatex(0.19,0.88,"CMS")
	if "Simulation" in cmsExtra:
		yLabelPos = 0.81	
	else:
		yLabelPos = 0.84	

	latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra))			


	leg = TLegend(0.52, 0.76, 0.95, 0.91,"%s BE"%trackType,"brNDC")
	leg.SetFillColor(10)
	leg.SetFillStyle(0)
	leg.SetLineColor(10)
	leg.SetShadowColor(0)
	leg.SetBorderSize(1)		
	leg.AddEntry(graph2016BE,"Cruijff","l")
	leg.AddEntry(graph2017BE,"Double CB","l")
	leg.AddEntry(graphCBE,"Crystal Ball","l")

	leg.Draw()

	plotPad.RedrawAxis()


	ratioPad.cd()

	ratioBE.SetLineColor(kRed)
	ratioCBE.SetLineColor(kBlue)

	ratioPad.DrawFrame(0,0.5,6000,1.5,";;ratio")

	ratioBE.Draw("samepe")
	ratioCBE.Draw("samepe")


	canv.Print("massResolutionCompareFuncMean2016_%s_BE.pdf"%trackType)
Exemple #25
0
def main():

    parser = argparse.ArgumentParser(description='edge fitter reloaded.')

    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        dest="verbose",
                        default=False,
                        help="Verbose mode.")
    parser.add_argument("-m",
                        "--mc",
                        action="store_true",
                        dest="mc",
                        default=False,
                        help="use MC, default is to use data.")
    parser.add_argument(
        "-u",
        "--use",
        action="store_true",
        dest="useExisting",
        default=False,
        help="use existing datasets from pickle, default is false.")
    ### MT2 changes the mll shape, but the effect on the Z shape is small
    ### Used a control region definition with MT2 cut in my thesis, but
    ### the plots do not look well when using MC due to lacking statistics
    ### or a missing sample. You have to check which CR to use. The impact
    ### on the fit results is negligible. Adapt y-range accordingly

    parser.add_argument(
        "-s",
        "--selection",
        dest="selection",
        action="store",
        default="DrellYanControl",
        #parser.add_argument("-s", "--selection", dest = "selection" , action="store", default="DrellYanControlNoMT2Cut",
        help="selection which to apply.")
    parser.add_argument("-r",
                        "--runRange",
                        dest="runRanges",
                        action="append",
                        default=[],
                        help="name of run range.")
    parser.add_argument("-c",
                        "--combine",
                        dest="combine",
                        action="store_true",
                        default=False,
                        help="combined runRanges or not")
    parser.add_argument("-x",
                        "--private",
                        action="store_true",
                        dest="private",
                        default=False,
                        help="plot is private work.")
    parser.add_argument("-w",
                        "--write",
                        action="store_true",
                        dest="write",
                        default=False,
                        help="write results to central repository")

    args = parser.parse_args()

    if not args.verbose:
        ROOT.RooMsgService.instance().setGlobalKillBelow(ROOT.RooFit.WARNING)
        ROOT.RooMsgService.instance().setSilentMode(ROOT.kTRUE)

    cmsExtra = ""
    if args.private:
        cmsExtra = "Private Work"
        if args.mc:
            cmsExtra = "#splitline{Private Work}{Simulation}"
    elif args.mc:
        cmsExtra = "Simulation"
    else:
        #~ cmsExtra = "Preliminary"
        cmsExtra = "Supplementary"

    useExistingDataset = args.useExisting
    lumi = 0

    runRangeName = "_".join(args.runRanges)
    lumis = []
    for runRange in args.runRanges:
        lumis.append(getRunRange(runRange).printval)
    #lumi = "+".join(lumis)
    lumi = "137"
    from edgeConfig import edgeConfig
    theConfig = edgeConfig(region=args.selection,
                           runNames=args.runRanges,
                           useMC=args.mc)

    if args.private:
        theConfig.ownWork = True

    # init ROOT
    # uncomment this if you want a segmentation violation
    #gROOT.Reset()
    gROOT.SetStyle("Plain")
    setTDRStyle()
    ROOT.gROOT.SetStyle("tdrStyle")

    # get data
    theDataInterface = dataInterface.DataInterface(theConfig.runRanges)
    treeOFOS = None
    treeEE = None
    treeMM = None

    #print ROOT.gDirectory.GetList()

    if not useExistingDataset:
        w = ROOT.RooWorkspace("w", ROOT.kTRUE)
        inv = ROOT.RooRealVar("inv", "inv",
                              (theConfig.maxInv - theConfig.minInv) / 2,
                              theConfig.minInv, theConfig.maxInv)
        getattr(w, 'import')(inv, ROOT.RooCmdArg())
        w.factory("weight[1.,0.,10.]")
        vars = ROOT.RooArgSet(inv, w.var('weight'))
        if (theConfig.useMC):

            log.logHighlighted("Using MC instead of data.")
            datasets = theConfig.mcdatasets  # ["TTJets", "ZJets", "DibosonMadgraph", "SingleTop"]
            (treeEM, treeEE, treeMM) = tools.getTrees(theConfig, datasets)

        else:
            treeMMraw = theDataInterface.getTreeFromDataset(
                "MergedData", "MuMu", cut=theConfig.selection.cut)
            treeEMraw = theDataInterface.getTreeFromDataset(
                "MergedData", "EMu", cut=theConfig.selection.cut)
            treeEEraw = theDataInterface.getTreeFromDataset(
                "MergedData", "EE", cut=theConfig.selection.cut)

            # convert trees
            treeEM = dataInterface.DataInterface.convertDileptonTree(treeEMraw)
            treeEE = dataInterface.DataInterface.convertDileptonTree(treeEEraw)
            treeMM = dataInterface.DataInterface.convertDileptonTree(treeMMraw)

        print "EM", treeEM.GetEntries()
        print "EE", treeEE.GetEntries()
        print "MM", treeMM.GetEntries()

        histEM = createFitHistoFromTree(
            treeEM, "inv", "weight",
            int((theConfig.maxInv - theConfig.minInv) / 2), theConfig.minInv,
            theConfig.maxInv)
        histEE = createFitHistoFromTree(
            treeEE, "inv", "weight",
            int((theConfig.maxInv - theConfig.minInv) / 2), theConfig.minInv,
            theConfig.maxInv)
        histMM = createFitHistoFromTree(
            treeMM, "inv", "weight",
            int((theConfig.maxInv - theConfig.minInv) / 2), theConfig.minInv,
            theConfig.maxInv)

        dataHistEE = ROOT.RooDataHist("dataHistEE", "dataHistEE",
                                      ROOT.RooArgList(w.var('inv')), histEE)
        dataHistMM = ROOT.RooDataHist("dataHistMM", "dataHistMM",
                                      ROOT.RooArgList(w.var('inv')), histMM)

        getattr(w, 'import')(dataHistEE, ROOT.RooCmdArg())
        getattr(w, 'import')(dataHistMM, ROOT.RooCmdArg())
        if theConfig.useMC:
            w.writeToFile("workspaces/dyControl_%s_MC.root" % (runRangeName))
        else:
            w.writeToFile("workspaces/dyControl_%s_Data.root" % (runRangeName))

    else:
        if theConfig.useMC:
            f = ROOT.TFile("workspaces/dyControl_%s_MC.root" % (runRangeName))
        else:
            f = ROOT.TFile("workspaces/dyControl_%s_Data.root" %
                           (runRangeName))
        w = f.Get("w")
        #~ vars = ROOT.RooArgSet(w.var("inv"), w.var('weight'), w.var('genWeight'))
        vars = ROOT.RooArgSet(w.var("inv"), w.var('weight'))

    ### For some reason we never switched from the hard coded maximum.
    ### Might want to change this in the future
    yMaximum = 5 * 10000  ### 2016+2017+2018 data with MT2 cut
    yMinimum = 0.1  ### 2016+2017+2018 data with MT2 cut
    #yMaximum = histEE.GetMaximum()*1e10
    #yMinimum = 10

    global nBinsDY
    nBinsDY = 240

    #
    global histoytitle
    histoytitle = 'Events / %.1f GeV' % (
        (theConfig.maxInv - theConfig.minInv) / float(nBinsDY))
    #histoytitle = 'Events / 4 GeV'
    ROOT.gSystem.Load("shapes/RooDoubleCB_cxx.so")
    ROOT.gSystem.Load("libFFTW.so")
    ## 2 GeV binning for DY compared to 5 GeV in main fit

    w.var('inv').setBins(nBinsDY)
    #~ w.var('inv').setBins(140)

    # We know the z mass
    # z mass and width
    # mass resolution in electron and muon channels
    #w.factory("zmean[91.1876, 90.1876, 92.1876]")
    w.factory("zmean[91.1876]")
    #w.factory("zmean[91.1876,89,93]")

    w.factory("cbmeanMM[3.0,-5,5]")
    w.factory("cbmeanEE[3.0,-5,5]")
    w.factory("zwidthMM[2.4952]")
    w.factory("zwidthEE[2.4952]")
    w.factory("sMM[1.6.,0.,20.]")
    w.factory("BreitWigner::zShapeMM(inv,zmean,zwidthMM)")
    w.factory("sEE[1.61321382563436089e+00,0,20.]")
    w.factory("BreitWigner::zShapeEE(inv,zmean,zwidthEE)")
    w.factory("nMML[3.,0.,10]")
    w.factory("alphaMML[1.15,0,10]")
    w.factory("nMMR[1.,0,10]")
    w.factory("alphaMMR[2.5,0,10]")

    w.factory(
        "DoubleCB::cbShapeMM(inv,cbmeanMM,sMM,alphaMML,nMML,alphaMMR,nMMR)")

    w.factory("nEEL[2.903,0.,10]")
    w.factory("alphaEEL[1.1598,0,5]")
    w.factory("nEER[1.0,0,10]")
    w.factory("alphaEER[2.508,0,5]")

    w.factory(
        "DoubleCB::cbShapeEE(inv,cbmeanEE,sEE,alphaEEL,nEEL,alphaEER,nEER)")

    Abkg = ROOT.RooRealVar("Abkg", "Abkg", 1, 0.01, 10)
    getattr(w, 'import')(Abkg, ROOT.RooCmdArg())

    #~ w.var("inv").setBins(250,"cache")
    w.factory("cContinuumEE[%f,%f,%f]" % (-0.02, -0.1, 0))

    w.factory("nZEE[100000.,500.,%s]" % (2000000))
    #~ w.factory("nZEE[100000.,300.,%s]" % (2000000))

    w.factory("Exponential::offShellEE(inv,cContinuumEE)")

    convEE = ROOT.RooFFTConvPdf("peakModelEE", "zShapeEE (x) cbShapeEE",
                                w.var("inv"), w.pdf("zShapeEE"),
                                w.pdf("cbShapeEE"))
    getattr(w, 'import')(convEE, ROOT.RooCmdArg())
    w.pdf("peakModelEE").setBufferFraction(5.0)
    w.factory("zFractionEE[0.9,0,1]")
    expFractionEE = ROOT.RooFormulaVar('expFractionEE', '1-@0',
                                       ROOT.RooArgList(w.var('zFractionEE')))
    getattr(w, 'import')(expFractionEE, ROOT.RooCmdArg())
    w.factory(
        "SUM::modelEE1(zFractionEE*peakModelEE,expFractionEE*offShellEE)")
    w.factory("SUM::modelEE(nZEE*modelEE1)")

    w.factory("cContinuumMM[%f,%f,%f]" % (-0.02, -0.1, 0))
    w.factory("Exponential::offShellMM(inv,cContinuumMM)")

    w.factory("nZMM[100000.,500.,%s]" % (2000000))
    w.factory("nOffShellMM[100000.,500.,%s]" % (2000000))
    #~ w.factory("nZMM[100000.,300.,%s]" % (2000000))
    #~ w.factory("nOffShellMM[100000.,300.,%s]" % (2000000))

    convMM = ROOT.RooFFTConvPdf("peakModelMM", "zShapeMM (x) cbShapeMM",
                                w.var("inv"), w.pdf("zShapeMM"),
                                w.pdf("cbShapeMM"))
    getattr(w, 'import')(convMM, ROOT.RooCmdArg())
    w.pdf("peakModelMM").setBufferFraction(5.0)
    w.factory("zFractionMM[0.9,0,1]")
    expFractionMM = ROOT.RooFormulaVar('expFractionMM', '1-@0',
                                       ROOT.RooArgList(w.var('zFractionMM')))
    getattr(w, 'import')(expFractionMM, ROOT.RooCmdArg())
    w.factory(
        "SUM::modelMM1(zFractionMM*peakModelMM,expFractionMM*offShellMM)")
    w.factory("SUM::modelMM(nZMM*modelMM1)")

    print "3"

    fitEE = w.pdf('modelEE').fitTo(
        w.data('dataHistEE'),
        #ROOT.RooFit.Save(), ROOT.RooFit.SumW2Error(ROOT.kFALSE), ROOT.RooFit.Minos(2.0))
        ROOT.RooFit.Save(),
        ROOT.RooFit.SumW2Error(ROOT.kFALSE),
        ROOT.RooFit.Minos(ROOT.kFALSE),
        ROOT.RooFit.Extended(ROOT.kTRUE))

    parametersToSave["nParEE"] = fitEE.floatParsFinal().getSize()

    print "3.1"

    fitMM = w.pdf('modelMM').fitTo(
        w.data('dataHistMM'),
        #ROOT.RooFit.Save(), ROOT.RooFit.SumW2Error(ROOT.kFALSE), ROOT.RooFit.Minos(2.0))
        ROOT.RooFit.Save(),
        ROOT.RooFit.SumW2Error(ROOT.kFALSE),
        ROOT.RooFit.Minos(ROOT.kTRUE),
        ROOT.RooFit.Extended(ROOT.kTRUE))

    parametersToSave["nParMM"] = fitMM.floatParsFinal().getSize()

    print "3.2"
    w.var("inv").setRange("zPeak", 81, 101)
    w.var("inv").setRange("fullRange", 20, 500)
    #~ w.var("inv").setRange("fullRange",20,300)
    w.var("inv").setRange("lowMass", 20, 70)
    argSet = ROOT.RooArgSet(w.var("inv"))

    peakIntEE = w.pdf("modelEE").createIntegral(argSet,
                                                ROOT.RooFit.NormSet(argSet),
                                                ROOT.RooFit.Range("zPeak"))
    peakEE = peakIntEE.getVal()

    lowMassIntEE = w.pdf("modelEE").createIntegral(
        argSet, ROOT.RooFit.NormSet(argSet), ROOT.RooFit.Range("lowMass"))
    lowMassEE = lowMassIntEE.getVal()

    peakIntMM = w.pdf("modelMM").createIntegral(argSet,
                                                ROOT.RooFit.NormSet(argSet),
                                                ROOT.RooFit.Range("zPeak"))
    peakMM = peakIntMM.getVal()

    lowMassIntMM = w.pdf("modelMM").createIntegral(
        argSet, ROOT.RooFit.NormSet(argSet), ROOT.RooFit.Range("lowMass"))
    lowMassMM = lowMassIntMM.getVal()

    log.logHighlighted("Peak: %.3f LowMass: %.3f (ee)" % (peakEE, lowMassEE))
    log.logHighlighted("Peak: %.3f LowMass: %.3f (mm)" % (peakMM, lowMassMM))
    log.logHighlighted("R(out,in): %.3f (ee) %.3f (mm)" %
                       (lowMassEE / peakEE, lowMassMM / peakMM))

    frameEE = w.var('inv').frame(
        ROOT.RooFit.Title('Invariant mass of ee lepton pairs'))

    frameEE.GetXaxis().SetTitle('m_{ee} [GeV]')
    frameEE.GetYaxis().SetTitle("Events / 2.5 GeV")
    #ROOT.RooAbsData.plotOn(w.data('dataHistEE'), frameEE, ROOT.RooFit.Binning(120))
    ROOT.RooAbsData.plotOn(w.data('dataHistEE'), frameEE)
    w.pdf('modelEE').plotOn(frameEE)
    sizeCanvas = 800

    #~ parametersToSave["chi2EE"] = 1.1*frameEE.chiSquare(int(parametersToSave["nParEE"]))
    parametersToSave["chi2EE"] = frameEE.chiSquare(
        int(parametersToSave["nParEE"]))
    parametersToSave["chi2ProbEE"] = TMath.Prob(
        parametersToSave["chi2EE"] *
        (nBinsDY - int(parametersToSave["nParEE"])),
        nBinsDY - int(parametersToSave["nParEE"]))
    log.logHighlighted("Floating parameters EE: %f" %
                       parametersToSave["nParEE"])
    log.logHighlighted("Chi2 EE: %f" % parametersToSave["chi2EE"])
    log.logHighlighted("Chi2 probability EE: %f" %
                       parametersToSave["chi2ProbEE"])

    cEE = ROOT.TCanvas("ee distribtution", "ee distribution", sizeCanvas,
                       int(1.25 * sizeCanvas))
    cEE.cd()
    pads = formatAndDrawFrame(w,
                              theConfig,
                              frameEE,
                              title="EE",
                              pdf=w.pdf("modelEE"),
                              yMin=0,
                              yMax=0.05 * yMaximum)

    dLeg = ROOT.TH1F()
    dLeg.SetMarkerStyle(ROOT.kFullCircle)
    dLeg.SetMarkerColor(ROOT.kBlack)
    dLeg.SetLineWidth(2)

    fullModelLeg = dLeg.Clone()
    fullModelLeg.SetLineColor(ROOT.kBlue)

    expLeg = dLeg.Clone()
    expLeg.SetLineColor(ROOT.kGreen + 2)

    peakLeg = dLeg.Clone()
    peakLeg.SetLineColor(ROOT.kRed)

    nLegendEntries = 4
    leg = tools.myLegend(0.35,
                         0.89 - 0.07 * nLegendEntries,
                         0.92,
                         0.91,
                         borderSize=0)
    leg.SetTextAlign(22)
    if (theConfig.useMC):
        leg.AddEntry(dLeg, 'Simulation', "pe")
    else:
        leg.AddEntry(dLeg, 'Data', "pe")
    leg.AddEntry(fullModelLeg, 'Full Z/#gamma* model', "l")
    leg.AddEntry(expLeg, 'Exponential component', "l")
    leg.AddEntry(peakLeg, 'DSCB #otimes BW component', "l")

    leg.Draw("same")

    goodnessOfFitEE = '#chi^{2}-prob. = %.3f' % parametersToSave["chi2ProbEE"]
    annotationsTitle = [
        (0.92, 0.47, "%s" % (theConfig.selection.latex)),
        #~ (0.92, 0.52, "%s" % (theConfig.selection.latex)),
        (0.92, 0.44, "%s" % goodnessOfFitEE),
    ]
    tools.makeCMSAnnotation(0.18,
                            0.88,
                            lumi,
                            mcOnly=theConfig.useMC,
                            preliminary=theConfig.isPreliminary,
                            year=theConfig.year,
                            ownWork=theConfig.ownWork)
    tools.makeAnnotations(annotationsTitle,
                          color=tools.myColors['AnnBlue'],
                          textSize=0.04,
                          align=31)

    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "expo",
                         w.var('cContinuumEE').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "cbMean",
                         w.var('cbmeanEE').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "nL",
                         w.var('nEEL').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "nR",
                         w.var('nEER').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "alphaL",
                         w.var('alphaEEL').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "alphaR",
                         w.var('alphaEER').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "nZ",
                         w.var('nZEE').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "zFraction",
                         w.var('zFractionEE').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "s",
                         w.var('sEE').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "sErr",
                         w.var('sEE').getError(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "chi2",
                         parametersToSave["chi2EE"],
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_EE",
                         "chi2Prob",
                         parametersToSave["chi2ProbEE"],
                         basePath="dyShelves/" + runRangeName + "/")
    eeName = "fig/expoFitEE_%s" % (runRangeName)
    if theConfig.useMC:
        eeName = "fig/expoFitEE_%s_MC" % (runRangeName)
    cEE.Print(eeName + ".pdf")
    cEE.Print(eeName + ".root")
    for pad in pads:
        pad.Close()
    pads = formatAndDrawFrame(w,
                              theConfig,
                              frameEE,
                              title="EE",
                              pdf=w.pdf("modelEE"),
                              yMin=yMinimum,
                              yMax=yMaximum)

    leg.Draw("same")

    tools.makeCMSAnnotation(0.18,
                            0.88,
                            lumi,
                            mcOnly=theConfig.useMC,
                            preliminary=theConfig.isPreliminary,
                            year=theConfig.year,
                            ownWork=theConfig.ownWork)
    tools.makeAnnotations(annotationsTitle,
                          color=tools.myColors['AnnBlue'],
                          textSize=0.04,
                          align=31)

    pads[0].SetLogy(1)
    eeName = "fig/expoFitEE_Log_%s" % (runRangeName)
    if theConfig.useMC:
        eeName = "fig/expoFitEE_Log_%s_MC" % (runRangeName)
    cEE.Print(eeName + ".pdf")
    cEE.Print(eeName + ".root")
    for pad in pads:
        pad.Close()

    frameMM = w.var('inv').frame(
        ROOT.RooFit.Title('Invariant mass of #mu#mu lepton pairs'))
    frameMM.GetXaxis().SetTitle('m_{#mu#mu} [GeV]')
    frameMM.GetYaxis().SetTitle("Events / 2.5 GeV")
    ROOT.RooAbsData.plotOn(w.data("dataHistMM"), frameMM)
    #ROOT.RooAbsData.plotOn(w.data("dataHistMM"), frameMM, ROOT.RooFit.Binning(120))
    w.pdf('modelMM').plotOn(frameMM)
    sizeCanvas = 800

    #~ parametersToSave["chi2MM"] = 1.1*frameMM.chiSquare(int(parametersToSave["nParMM"]))
    parametersToSave["chi2MM"] = frameMM.chiSquare(
        int(parametersToSave["nParMM"]))
    parametersToSave["chi2ProbMM"] = TMath.Prob(
        parametersToSave["chi2MM"] *
        (nBinsDY - int(parametersToSave["nParMM"])),
        nBinsDY - int(parametersToSave["nParMM"]))
    log.logHighlighted("Chi2 MM: %f" % parametersToSave["chi2MM"])
    log.logHighlighted("Chi2 probability MM: %f" %
                       parametersToSave["chi2ProbMM"])

    goodnessOfFitMM = '#chi^{2}-prob. = %.3f' % parametersToSave["chi2ProbMM"]
    annotationsTitle = [
        (0.92, 0.47, "%s" % (theConfig.selection.latex)),
        #~ (0.92, 0.52, "%s" % (theConfig.selection.latex)),
        (0.92, 0.44, "%s" % goodnessOfFitMM),
    ]

    residualMode = "pull"
    cMM = ROOT.TCanvas("#mu#mu distribtution", "#mu#mu distribution",
                       sizeCanvas, int(1.25 * sizeCanvas))
    cMM.cd()
    pads = formatAndDrawFrame(w,
                              theConfig,
                              frameMM,
                              title="MM",
                              pdf=w.pdf("modelMM"),
                              yMin=0,
                              yMax=0.05 * yMaximum)

    leg.Draw("same")

    tools.makeCMSAnnotation(0.18,
                            0.88,
                            lumi,
                            mcOnly=theConfig.useMC,
                            preliminary=theConfig.isPreliminary,
                            year=theConfig.year,
                            ownWork=theConfig.ownWork)
    tools.makeAnnotations(annotationsTitle,
                          color=tools.myColors['AnnBlue'],
                          textSize=0.04,
                          align=31)

    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "expo",
                         w.var('cContinuumMM').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "cbMean",
                         w.var('cbmeanMM').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "cbMeanErr",
                         w.var('cbmeanMM').getError(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "nL",
                         w.var('nMML').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "nR",
                         w.var('nMMR').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "alphaL",
                         w.var('alphaMML').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "alphaR",
                         w.var('alphaMMR').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "nZ",
                         w.var('nZMM').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "zFraction",
                         w.var('zFractionMM').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "s",
                         w.var('sMM').getVal(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "sErr",
                         w.var('sMM').getError(),
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "chi2",
                         parametersToSave["chi2MM"],
                         basePath="dyShelves/" + runRangeName + "/")
    tools.storeParameter("expofit",
                         "dyExponent_MM",
                         "chi2Prob",
                         parametersToSave["chi2ProbMM"],
                         basePath="dyShelves/" + runRangeName + "/")
    mmName = "fig/expoFitMM_%s" % (runRangeName)
    if theConfig.useMC:
        mmName = "fig/expoFitMM_%s_MC" % (runRangeName)
    cMM.Print(mmName + ".pdf")
    cMM.Print(mmName + ".root")

    for pad in pads:
        pad.Close()

    pads = formatAndDrawFrame(w,
                              theConfig,
                              frameMM,
                              title="MM",
                              pdf=w.pdf("modelMM"),
                              yMin=yMinimum,
                              yMax=yMaximum)
    legend = ROOT.TLegend(0.5, 0.6, 0.95, 0.94)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    entryHist = ROOT.TH1F()
    entryHist.SetFillColor(ROOT.kWhite)
    legend.AddEntry(entryHist, "Drell-Yan enriched region", "h")
    dataHist = ROOT.TH1F()
    entryHist.SetFillColor(ROOT.kWhite)
    legend.AddEntry(dataHist, "data", "p")
    fitHist = ROOT.TH1F()
    fitHist.SetLineColor(ROOT.kBlue)
    legend.AddEntry(fitHist, "Full Z model", "l")
    expoHist = ROOT.TH1F()
    expoHist.SetLineColor(ROOT.kGreen)
    legend.AddEntry(expoHist, "Exponential component", "l")
    bwHist = ROOT.TH1F()
    bwHist.SetLineColor(ROOT.kRed)
    legend.AddEntry(bwHist, "DSCB #otimes BW component", "l")

    leg.Draw("same")

    tools.makeCMSAnnotation(0.18,
                            0.88,
                            lumi,
                            mcOnly=theConfig.useMC,
                            preliminary=theConfig.isPreliminary,
                            year=theConfig.year,
                            ownWork=theConfig.ownWork)
    tools.makeAnnotations(annotationsTitle,
                          color=tools.myColors['AnnBlue'],
                          textSize=0.04,
                          align=31)

    pads[0].SetLogy(1)
    mmName = "fig/expoFitMM_Log_%s" % (runRangeName)
    if theConfig.useMC:
        mmName = "fig/expoFitMM_Log_%s_MC" % (runRangeName)

    cMM.Print(mmName + ".pdf")
    cMM.Print(mmName + ".root")
    for pad in pads:
        pad.Close()

    if theConfig.useMC:
        w.writeToFile("dyWorkspace_MC.root")
    else:
        w.writeToFile("dyWorkspace.root")
    return w
import sys
sys.path.append('cfg/')
from frameworkStructure import pathes
sys.path.append(pathes.basePath)

import ROOT
import ratios

from setTDRStyle import setTDRStyle
style = setTDRStyle() 
style.SetPadLeftMargin(0.13)
style.SetTitleYOffset(0.9)
style.SetPadTopMargin(0.0675)

from helpers import *    

################## SUMMARY OF CLASS plotTemplate #######################
## Constructors:
# * plotTemplate()
#
## Methods:
# * setPrimaryPlot(plot, drawOption)
#       Plot (histogram, graph) to be drawn first with drawOption, 
#       defining the axes and boundaries, redrawn 
#       after secondary plots by default so it will be on top
#
# * addSecondaryPlot(plot, drawOption)
#       Adds plot (anything with Draw(drawOption) method in root) to 
#       list of secondary plots
#
# * clearSecondaryPlots()
Exemple #27
0
def doPUCorrection(plotData=True,nJets=2,direction="Central",extraArg=""):
    dilepton = "SF"
    bkg = getBackgrounds("TT","DY","DYTauTau")

    nPoints = 0
    setTDRStyle()
    ROOT.gStyle.SetOptFit(111)
    ROOT.gStyle.SetErrorX(0.5)
    
    bins = array('f',[0,7,10,15,31])
    nBins = len(bins)-1
    pointsHist = ROOT.TH1F("h","", nBins,bins)
    
    nVCuts = ["nVert06", "nVert79", "nVert1014", "nVert1530"]
    
    for nVCut in nVCuts:       
        mainConfig = dataMCConfig.dataMCConfig(plot="jzbPlot_puCorr_%dj#jzb50#%s"%(nJets,nVCut),region=direction,runName="Run2015_25ns",plotData=plotData,normalizeToData=False,plotRatio=False,signals=False,useTriggerEmulation=True,personalWork=True,preliminary=False,forPAS=False,forTWIKI=False,backgrounds=bkg,dontScaleTrig=False,plotSyst=False,doPUWeights=False, responseCorr=False)
        
        histSF = produceHistogram("SF", mainConfig)
        histEM = produceHistogram("EMu", mainConfig)
        if mainConfig.plotData:
            R = getattr(mainConfig.rSFOF, direction.lower()).val
        else:
            R = getattr(mainConfig.rSFOF, direction.lower()).valMC
        histSF.Add(histEM,-R)

        tempHist = histSF.Clone()
        tempHist.Scale(1./tempHist.Integral())
        tempHist.SetMinimum(0)
        can = ROOT.TCanvas()
        tempFunc = ROOT.TF1("temf","gaus",-50,50)
        tempHist.Fit(tempFunc,"RQ")
        tempHist.Draw()
        tempFunc.Draw("same")
        ensurePathExists("fig/%s/PUCorr/%d/%dj/%s/"%(mainConfig.jzbType, mainConfig.correctionMode,nJets,direction))
        can.SaveAs("fig/%s/PUCorr/%d/%dj/%s/%s.pdf"%(mainConfig.jzbType, mainConfig.correctionMode,nJets,direction,nVCut.split("nVert")[1]))
        

        ymean = tempFunc.GetParameter(1)
        yerr = tempFunc.GetParError(1)
        
        nPoints+=1
        pointsHist.SetBinContent(nPoints, ymean)
        pointsHist.SetBinError(nPoints, yerr)
        
     
    template = plotTemplate(mainConfig)
    ROOT.gStyle.SetOptFit(111)
    ROOT.gStyle.SetErrorX(0.5)
    template.dilepton = dilepton
    template.changeScale = False
    fitLine = TF1("fitLine", "pol1",0,31)
    fitLine.SetParName(1, "#beta")
    fitLine.SetParameter(1,0.1747)
    fitLine.SetParameter(0,3.78)
    pointsHist.Fit(fitLine, "R%s"%(extraArg))
    
    with open("shelves/%s_%d.pkl"%(mainConfig.jzbType,mainConfig.correctionMode), "r+") as corrFile:        
        corrs = pickle.load(corrFile)
        corrFile.seek(0) 
        corrFile.truncate()
        
        corrs[mainConfig.plotData][direction]["pu"][nJets==2] = fitLine.GetParameter(1)
        pickle.dump(corrs, corrFile)
        corrFile.close()
    
    jetInd = "#geq3j" if nJets == 3 else "=2j"
    template.cutsText = jetInd
    template.labelX = "N_{Vertices}"
    template.labelY = "JZB Peak Position [GeV]"
    template.regionName = direction

    template.setPrimaryPlot(pointsHist, "pe")
    template.addSecondaryPlot(fitLine,"")
    
    template.draw()
    
    template.canvas.Update()
    pointsHist.GetListOfFunctions()
    panel = pointsHist.GetListOfFunctions().FindObject("stats")
    panel.SetX1NDC(0.65)
    panel.SetX2NDC(0.95)
    panel.SetY1NDC(0.14)
    panel.SetY2NDC(0.38)
    template.draw()
    
    template.setFolderName("PUCorr/%d"%(mainConfig.correctionMode))
    dataInd = "Data" if plotData else "MC"
    template.saveAs("puSlope_%dj_%s_%s"%(nJets, direction, dataInd))
def comparePtRes(trackType):
	
	file2016BB = open("default2016Pt/PtResolutionVsPt_%s_BB.pkl"%trackType)
	file2016BE = open("default2016Pt/PtResolutionVsPt_%s_BE.pkl"%trackType)
	file2017BB = open("defaultPt/PtResolutionVsPt_%s_BB.pkl"%trackType)
	file2017BE = open("defaultPt/PtResolutionVsPt_%s_BE.pkl"%trackType)
	file2018BB = open("default2018Pt/PtResolutionVsPt_%s_BB.pkl"%trackType)
	file2018BE = open("default2018Pt/PtResolutionVsPt_%s_BE.pkl"%trackType)

	results2016BB = pickle.load(file2016BB)
	results2016BE = pickle.load(file2016BE)
	results2017BB = pickle.load(file2017BB)
	results2017BE = pickle.load(file2017BE)
	results2018BB = pickle.load(file2018BB)
	results2018BE = pickle.load(file2018BE)

	graph2016BB = getGraph(results2016BB,"2016BB")
	graph2016BE = getGraph(results2016BE,"2016BE")
	graph2017BB = getGraph(results2017BB,"2017BB")
	graph2017BE = getGraph(results2017BE,"2017BE")
	graph2018BB = getGraph(results2018BB,"2018BB")
	graph2018BE = getGraph(results2018BE,"2018BE")
		
	
	ratioBB = 	getRatio(results2016BB,results2017BB,"ratioBB")
	ratioBE = 	getRatio(results2016BE,results2017BE,"ratioBE")
	ratioBB18 = getRatio(results2016BB,results2018BB,"ratioBB18")
	ratioBE18 = getRatio(results2016BE,results2018BE,"ratioBE18")



	canv = TCanvas("c1","c1",800,1200)

	plotPad = TPad("plotPad","plotPad",0,0.3,1,1)
	ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
	style = setTDRStyle()
	gStyle.SetOptStat(0)
	plotPad.UseCurrentStyle()
	ratioPad.UseCurrentStyle()
	plotPad.Draw()	
	ratioPad.Draw()	
	plotPad.cd()
	plotPad.cd()
	plotPad.SetGrid()
	gStyle.SetTitleXOffset(1.45)
	gStyle.SetTitleYOffset(1.55)

	xMax = 0.15
	if trackType == "Inner":
		xMax = 0.3
	if trackType == "Outer":
		xMax = 0.5

	plotPad.DrawFrame(0,0,3100,xMax,";p_{T} [GeV]; p_{T} resolution [%]")

	graph2016BB.Draw("samepe")
	graph2017BB.Draw("samepe")
	graph2018BB.Draw("samepe")
	graph2017BB.SetLineColor(kRed)
	graph2017BB.SetMarkerColor(kRed)
	graph2018BB.SetLineColor(kBlue)
	graph2018BB.SetMarkerColor(kBlue)

	latex = TLatex()
	latex.SetTextFont(42)
	latex.SetTextAlign(31)
	latex.SetTextSize(0.04)
	latex.SetNDC(True)
	latexCMS = TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.055)
	latexCMS.SetNDC(True)
	latexCMSExtra = TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.03)
	latexCMSExtra.SetNDC(True) 

	latex.DrawLatex(0.95, 0.96, "(13 TeV)")

	cmsExtra = "#splitline{Preliminary}{}"
	latexCMS.DrawLatex(0.19,0.88,"CMS")
	if "Simulation" in cmsExtra:
		yLabelPos = 0.81	
	else:
		yLabelPos = 0.84	

	latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra))			


	leg = TLegend(0.52, 0.76, 0.95, 0.91,"%s BB"%trackType,"brNDC")
	leg.SetFillColor(10)
	leg.SetFillStyle(0)
	leg.SetLineColor(10)
	leg.SetShadowColor(0)
	leg.SetBorderSize(1)		
	leg.AddEntry(graph2016BB,"2016","l")
	leg.AddEntry(graph2017BB,"2017","l")
	leg.AddEntry(graph2018BB,"2018","l")

	leg.Draw()

	plotPad.RedrawAxis()


	ratioPad.cd()

	ratioBB.SetLineColor(kRed)
	ratioBB18.SetLineColor(kBlue)
	ratioBB.SetMarkerColor(kRed)
	ratioBB18.SetMarkerColor(kBlue)

	ratioPad.DrawFrame(0,0.5,3100,1.5,";;ratio")

	ratioBB.Draw("samepe")
	ratioBB18.Draw("samepe")

	l = TLine(0,1,3100,1)
	l.SetLineStyle(kDashed)
	l.Draw()
	
	canv.Print("PtResolutionCompare_%s_BB.pdf"%trackType)
	
	
	canv = TCanvas("c1","c1",800,1200)

	plotPad = TPad("plotPad","plotPad",0,0.3,1,1)
	ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
	style = setTDRStyle()
	gStyle.SetOptStat(0)
	plotPad.UseCurrentStyle()
	ratioPad.UseCurrentStyle()
	plotPad.Draw()	
	ratioPad.Draw()	
	plotPad.cd()
	plotPad.cd()
	plotPad.SetGrid()
	gStyle.SetTitleXOffset(1.45)
	gStyle.SetTitleYOffset(1.55)

	xMax = 0.15
	if trackType == "Inner":
		xMax = 0.3
	if trackType == "Outer":
		xMax = 0.5

	plotPad.DrawFrame(0,0,3100,xMax,";p_{T} [GeV]; p_{T} resolution [%]")

	graph2016BE.Draw("samepe")
	graph2017BE.Draw("samepe")
	graph2018BE.Draw("samepe")
	graph2017BE.SetLineColor(kRed)
	graph2017BE.SetMarkerColor(kRed)
	graph2018BE.SetLineColor(kBlue)
	graph2018BE.SetMarkerColor(kBlue)

	latex = TLatex()
	latex.SetTextFont(42)
	latex.SetTextAlign(31)
	latex.SetTextSize(0.04)
	latex.SetNDC(True)
	latexCMS = TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.055)
	latexCMS.SetNDC(True)
	latexCMSExtra = TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.03)
	latexCMSExtra.SetNDC(True) 

	latex.DrawLatex(0.95, 0.96, "(13 TeV)")

	cmsExtra = "#splitline{Preliminary}{}"
	latexCMS.DrawLatex(0.19,0.88,"CMS")
	if "Simulation" in cmsExtra:
		yLabelPos = 0.81	
	else:
		yLabelPos = 0.84	

	latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra))			


	leg = TLegend(0.52, 0.76, 0.95, 0.91,"%s BE"%trackType,"brNDC")
	leg.SetFillColor(10)
	leg.SetFillStyle(0)
	leg.SetLineColor(10)
	leg.SetShadowColor(0)
	leg.SetBorderSize(1)		
	leg.AddEntry(graph2016BE,"2016","l")
	leg.AddEntry(graph2017BE,"2017","l")
	leg.AddEntry(graph2018BE,"2018","l")

	leg.Draw()

	plotPad.RedrawAxis()


	ratioPad.cd()

	ratioBE.SetLineColor(kRed)
	ratioBE18.SetLineColor(kBlue)
	ratioBE.SetMarkerColor(kRed)
	ratioBE18.SetMarkerColor(kBlue)

	ratioPad.DrawFrame(0,0.5,3100,1.5,";;ratio")

	l = TLine(0,1,3100,1)
	l.SetLineStyle(kDashed)
	l.Draw()

	ratioBE.Draw("samepe")
	ratioBE18.Draw("samepe")


	canv.Print("PtResolutionCompare_%s_BE.pdf"%trackType)
Exemple #29
0
def plot():
	import ratios
	from ROOT import TCanvas, TPad, TH1F, TH2F,TH2D, TH1I, THStack, TLegend, TMath, TF1, TFile, TGraph2D
	from setTDRStyle import setTDRStyle
	import pickle
	from defs import sbottom_masses
	from math import sqrt
	
	from corrections import rSFOFDirect
	
	signalDenominatorFile = TFile("/.automount/home/home__home4/institut_1b/schomakers/FrameWork/SignalScan/T6bbllsleptonDenominatorHisto7.root")
	denominatorHisto = TH2F(signalDenominatorFile.Get("massScan"))
	ISRNormalizationHisto = TH2F(signalDenominatorFile .Get("ISRNormalization"))
	ISRNormalizationHistoUp = TH2F(signalDenominatorFile .Get("ISRNormalizationUp"))
	ISRNormalizationHistoDown = TH2F(signalDenominatorFile .Get("ISRNormalizationDown"))
	
	
	latex = ROOT.TLatex()
	latex.SetTextSize(0.03)
	latex.SetNDC(True)
	latexLumi = ROOT.TLatex()
	latexLumi.SetTextFont(42)
	latexLumi.SetTextAlign(31)
	latexLumi.SetTextSize(0.04)
	latexLumi.SetNDC(True)
	latexCMS = ROOT.TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.055)
	latexCMS.SetNDC(True)
	latexCMSExtra = ROOT.TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.03)
	latexCMSExtra.SetNDC(True)
	
	canv = TCanvas("canv", "canv",1024,768)
	plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
	setTDRStyle()
	style=setTDRStyle()	
	style.SetPadRightMargin(0.175)	
	plotPad.UseCurrentStyle()
	plotPad.Draw()	
	plotPad.cd()	
	
	nEvents = -1
	lumi = 35867.
	printLumi = "35.9"
	
	m_neutr_1_fix = False
	#~ m_neutr_1_fix = True

	
	
	path = "shelvesSystematics"
	generalSignalLabel = "T6bbllslepton"
	
	observables = ["mll"]
	leptonCombinations = ["SF-OF"]
	
	massRegions = ["20To60","60To86","86To96","96To150","150To200","200To300","300To400","Above400"]
	nLLRegions = ["lowNll","highNll"]
	MT2Regions = ["highMT2"]
	
	regionCombinations = []
	regions = []
	
	for massRegion in massRegions:
		for nLLRegion in nLLRegions:
			for MT2Region in MT2Regions:
				regions.append("%s_%s_%s"%(massRegion,nLLRegion,MT2Region))
				
	for nLLRegion in nLLRegions:
		regionCombinations.append(nLLRegion)	
			
	
	Graphs = {}
	Histograms = {}			
	uncertaintyArrays = {}
	#~ uncertaintySources = ["Yield","StatUncertainty","SystUncertainty","TotalUncertainty","Efficiency","ISRUncertainty","pileupUncertainty","JESUncertainty","LeptonUncertainty","LeptonFastSimUncertainty","LeptonFullSimUncertainty","BTagUncertaintyLight","BTagUncertaintyHeavy"]
	uncertaintySources = ["Yield","StatUncertainty","SystUncertainty","TotalUncertainty","Efficiency","EfficiencyUnscaled","ISRUncertainty","pileupUncertainty","JESUncertainty","LeptonFullSimUncertainty","LeptonFastSimUncertainty","BTagUncertaintyLight","BTagUncertaintyHeavy","MetUncertainty","ScaleUncertainty"]

	
	for uncertaintySource in uncertaintySources:
		uncertaintyArrays["%s_highNll"%(uncertaintySource)] = []
		uncertaintyArrays["%s_lowNll"%(uncertaintySource)] = []
		for region in regions:
			uncertaintyArrays["%s_%s"%(uncertaintySource,region)] = []
			
	
	
	title = "Simplified Model Scan; m(#tilde{b}) [GeV]; m(#tilde{#chi}_{2}^{0}) [GeV]"

	masses_b = []
	masses_n = []
	
	m_n_min = 150
	m_n_max = 1450
	m_b_min = 700
	m_b_max = 1500
	
	bin_size =25
	nxbins = int(min(500,(m_b_max-m_b_min)/bin_size))
	nybins = int(min(500,(m_n_max-m_n_min)/bin_size))
	
	
	TriggerEffUncertainty = 0.03
	LumiUncertainty = 0.026
	FastSimUncertainty = 0.04
					
	m_b = m_b_min
	while m_b <= m_b_max:
		print m_b
		if m_b < 800:
			stepsize = 25
		else:
			stepsize = 50
		
		M_SBOTTOM = "m_b_"+str(m_b)
		m_sbottom = str(m_b)
		xsection = getattr(sbottom_masses, M_SBOTTOM).cross_section13TeV
		
		m_n = m_n_min
		
		while m_n < m_b:
			
			if not ((m_b == 775 and m_n == 750) or (m_b == 800 and m_n == 150) or (m_b == 950 and m_n == 250) or (m_b == 950 and m_n == 300) or (m_b == 950 and m_n == 500) or (m_b == 950 and m_n == 550) or (m_b == 950 and m_n == 850) or (m_b == 950 and m_n == 900)):	
							
				
				m_neutralino_2 = str(m_n)
				
				masses_b.append(m_b)
				masses_n.append(m_n)
				
				sampleName = "T6bbllslepton_msbottom_%s_mneutralino_%s"%(m_sbottom,m_neutralino_2)
				
				denominator = denominatorHisto.GetBinContent(denominatorHisto.GetXaxis().FindBin(int(sampleName.split("_")[2])),denominatorHisto.GetYaxis().FindBin(int(sampleName.split("_")[4])))
				ISRNormalization = ISRNormalizationHisto.GetBinContent(ISRNormalizationHisto.GetXaxis().FindBin(int(sampleName.split("_")[2])),denominatorHisto.GetYaxis().FindBin(int(sampleName.split("_")[4])))
					
				
	
				Pickles = {}
				Yields = {}
				MCEvents = {}
				JES = {}
				#~ Lepton = {}
				LeptonFastSim = {}
				LeptonFullSim = {}
				Pileup = {}
				ISR= {}
				BTag = {}
				Met = {}
				ScaleShift = {}
				
				Uncertainties = {}	
				
				Pickles["%s_%s"%(m_sbottom,m_neutralino_2)] = loadPickles("%s/%s.pkl"%(path,sampleName))	
				
				
				for region in regions:
					
					if region == "edgeLegacy":
						RSFOF = rSFOFDirect.central.val
					else:
						RSFOF = rSFOFDirect.inclusive.val
	
					
					Yields["EE_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["Val"]
					Yields["EMu_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["Val"]*RSFOF
					Yields["MuMu_%s"%region] =  Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["Val"]
					Yields["SFOF_%s"%region] = Yields["EE_%s"%region] + Yields["MuMu_%s"%region] - Yields["EMu_%s"%region]
					Uncertainties["Yield_%s"%region] = max(Yields["SFOF_%s"%region],0)
					
					MCEvents["EE_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["MCEvents"]
					MCEvents["EMu_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["MCEvents"]
					MCEvents["MuMu_%s"%region] =  Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["MCEvents"]
					MCEvents["SFOF_%s"%region] = MCEvents["EE_%s"%region] + MCEvents["MuMu_%s"%region] - MCEvents["EMu_%s"%region]
					MCEvents["SFOF_%s"%region] = max(MCEvents["SFOF_%s"%region],0)
					
					Uncertainties["Efficiency_%s"%region] = Yields["SFOF_%s"%region]/(xsection*lumi*ISRNormalization)
					Uncertainties["EfficiencyUnscaled_%s"%region] = MCEvents["SFOF_%s"%region]/denominator
					
					if MCEvents["SFOF_%s"%region] > 0:
						Uncertainties["StatUncertainty_%s"%region] = sqrt(MCEvents["EE_%s"%region]+MCEvents["EMu_%s"%region]+MCEvents["MuMu_%s"%region])/MCEvents["SFOF_%s"%region]
					else:
						Uncertainties["StatUncertainty_%s"%region] = 0
					
					### JES Uncertainty
					JES["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["JESMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["JESMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["JESMean"]*RSFOF 
					
					JES["JESUp_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["JESUp"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["JESUp"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["JESUp"]*RSFOF
					JES["JESDown_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["JESDown"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["JESDown"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["JESDown"]*RSFOF
					
					### Only consider bins with a sufficient number of MC events
					### otherwise nearly empty bins will dominate the plots
					if JES["Mean_%s"%region] > 0 and MCEvents["SFOF_%s"%region] > 100:
						Uncertainties["JESUncertainty_%s"%region] = max(abs(JES["JESUp_%s"%region]-JES["Mean_%s"%region])/JES["Mean_%s"%region],abs(JES["JESDown_%s"%region]-JES["Mean_%s"%region])/JES["Mean_%s"%region])
					else:
						Uncertainties["JESUncertainty_%s"%region] = 0
					
					### Lepton FastSim Uncertainty
					
					LeptonFastSim["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EE"%region]["LeptonFastSimMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_MuMu"%region]["LeptonFastSimMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EMu"%region]["LeptonFastSimMean"] 
					LeptonFastSim["MeanShifted_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EE"%region]["LeptonFastSimMean"] * (1+FastSimUncertainty) + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_MuMu"%region]["LeptonFastSimMean"]*(1+FastSimUncertainty)  - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EMu"%region]["LeptonFastSimMean"]*(1+FastSimUncertainty)  
					
					if LeptonFastSim["Mean_%s"%region] > 0:
						Uncertainties["LeptonFastSimUncertainty_%s"%region] = abs(LeptonFastSim["MeanShifted_%s"%region]-LeptonFastSim["Mean_%s"%region])/LeptonFastSim["Mean_%s"%region]
					else:
						Uncertainties["LeptonFastSimUncertainty_%s"%region] = 0
						
					### Lepton FullSim Uncertainty
					
					LeptonFullSim["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EE"%region]["LeptonFullSimMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_MuMu"%region]["LeptonFullSimMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EMu"%region]["LeptonFullSimMean"] 
					LeptonFullSim["MeanShifted_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EE"%region]["LeptonFullSimScaleFactorShifted"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_MuMu"%region]["LeptonFullSimScaleFactorShifted"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EMu"%region]["LeptonFullSimScaleFactorShifted"] 
					
					if LeptonFullSim["Mean_%s"%region] > 0:
						Uncertainties["LeptonFullSimUncertainty_%s"%region] = abs(LeptonFullSim["MeanShifted_%s"%region]-LeptonFullSim["Mean_%s"%region])/LeptonFullSim["Mean_%s"%region]
					else:
						Uncertainties["LeptonFullSimUncertainty_%s"%region] = 0
					
					
					###  Pileup Uncertainty
					Pileup["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["PileupMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["PileupMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["PileupMean"]*RSFOF
					
					Pileup["PileupHigh_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["PileupHigh"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["PileupHigh"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["PileupHigh"]*RSFOF
					Pileup["PileupLow_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["PileupLow"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["PileupLow"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["PileupLow"]*RSFOF 
					
					if Pileup["Mean_%s"%region] > 0 and MCEvents["SFOF_%s"%region] > 100:
						Uncertainties["pileupUncertainty_%s"%region] = max(abs(Pileup["PileupHigh_%s"%region]-Pileup["Mean_%s"%region])/Pileup["Mean_%s"%region],abs(Pileup["PileupLow_%s"%region] -Pileup["Mean_%s"%region])/Pileup["Mean_%s"%region] )
					else:
						Uncertainties["pileupUncertainty_%s"%region] = 0
					
					Uncertainties["pileupUncertainty_%s"%region] = 0.02
					
					### ISR Uncertainty
					ISR["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["ISRMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["ISRMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["ISRMean"]*RSFOF
					
					ISR["ISRUp_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["ISRUp"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["ISRUp"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["ISRUp"]*RSFOF
					ISR["ISRDown_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["ISRDown"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["ISRDown"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["ISRDown"]*RSFOF  
					
					if ISR["Mean_%s"%region] > 0 and MCEvents["SFOF_%s"%region] > 100:
						Uncertainties["ISRUncertainty_%s"%region] = max(abs(ISR["ISRUp_%s"%region]-ISR["Mean_%s"%region])/ISR["Mean_%s"%region],abs(ISR["ISRDown_%s"%region]-ISR["Mean_%s"%region])/ISR["Mean_%s"%region])
					else:
						Uncertainties["ISRUncertainty_%s"%region] = 0
						
					if Yields["SFOF_%s"%region] > 0 and MCEvents["SFOF_%s"%region] > 100:
						Uncertainties["TriggerEffUncertainty_%s"%region] = sqrt((Yields["EE_%s"%region]*TriggerEffUncertainty)**2 + (Yields["MuMu_%s"%region]*TriggerEffUncertainty)**2 + (Yields["EMu_%s"%region]*TriggerEffUncertainty*RSFOF)**2)/Yields["SFOF_%s"%region]
					else:
						Uncertainties["TriggerEffUncertainty_%s"%region] = 0
							
					### BTag Uncertainty
					BTag["Mean_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["BTagMean"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["BTagMean"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["BTagMean"]*RSFOF
					
					BTag["BTagHeavy_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["BTagHeavy"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["BTagHeavy"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["BTagHeavy"]*RSFOF  
					
					BTag["BTagLight_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["BTagLight"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["BTagLight"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["BTagLight"]*RSFOF
					
					if BTag["Mean_%s"%region] > 0 and MCEvents["SFOF_%s"%region] >100:
						Uncertainties["BTagUncertaintyHeavy_%s"%region] = abs(BTag["BTagHeavy_%s"%region]-BTag["Mean_%s"%region])/BTag["Mean_%s"%region]
						Uncertainties["BTagUncertaintyLight_%s"%region] = abs(BTag["BTagLight_%s"%region]-BTag["Mean_%s"%region])/BTag["Mean_%s"%region]
					else:
						Uncertainties["BTagUncertaintyHeavy_%s"%region] = 0
						Uncertainties["BTagUncertaintyLight_%s"%region] = 0
						
					### FastSim Met Uncertainty					
					Met["Met_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["Met"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["Met"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["Met"]*RSFOF
					Met["GenMet_%s"%region] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EE"]["GenMet"] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_MuMu"]["GenMet"] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)][region+"_EMu"]["GenMet"]*RSFOF  
					
					if Yields["SFOF_%s"%region] > 0 and MCEvents["SFOF_%s"%region] >100:
						Uncertainties["MetUncertainty_%s"%region] = 0.5*abs(Met["Met_%s"%region]-Met["GenMet_%s"%region])/Yields["SFOF_%s"%region]
					else:
						Uncertainties["MetUncertainty_%s"%region] = 0
					
					### Scale uncertainty
					Uncertainties["ScaleUncertainty_%s"%region] = 0
					ScaleShift["Mean_%s"%region] = BTag["Mean_%s"%region]
					ScaleShift["MaxShift_%s"%region] = 0
					if BTag["Mean_%s"%region] > 0:
						
						for scaleIndex in range(1,9):
							ScaleShift["ScaleShift%s"%str(scaleIndex)] = Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EE"%region]["ScaleShifted%s"%str(scaleIndex)] + Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_MuMu"%region]["ScaleShifted%s"%str(scaleIndex)] - Pickles["%s_%s"%(m_sbottom,m_neutralino_2)]["%s_EMu"%region]["ScaleShifted%s"%str(scaleIndex)]
							Uncertainties["ScaleUncertainty_%s"%region] = max(Uncertainties["ScaleUncertainty_%s"%region], abs( (ScaleShift["ScaleShift%s"%str(scaleIndex)] - ScaleShift["Mean_%s"%region])/ScaleShift["Mean_%s"%region]))
							if abs( ScaleShift["ScaleShift%s"%str(scaleIndex)] - ScaleShift["Mean_%s"%region])/ScaleShift["Mean_%s"%region] > ScaleShift["MaxShift_%s"%region]:
								ScaleShift["MaxShift_%s"%region] = ScaleShift["ScaleShift%s"%str(scaleIndex)]
								
					
					#~ ### Trigger efficiency	
					#~ if Yields["SFOF_%s"%region] > 0:
						#~ Uncertainties["TriggerEffUncertainty_%s"%region] = sqrt((Yields["EE_%s"%region]*TriggerEffUncertainty)**2 + (Yields["MuMu_%s"%region]*TriggerEffUncertainty)**2 + (Yields["EMu_%s"%region]*TriggerEffUncertainty)**2)/Yields["SFOF_%s"%region]
					#~ else:
						#~ Uncertainties["TriggerEffUncertainty_%s"%region] = 0
					Uncertainties["TriggerEffUncertainty_%s"%region] = TriggerEffUncertainty
							
					### Total syst uncertainty
					Uncertainties["SystUncertainty_%s"%region] = sqrt(Uncertainties["ScaleUncertainty_%s"%region]**2 + Uncertainties["JESUncertainty_%s"%region]**2 + Uncertainties["LeptonFastSimUncertainty_%s"%region]**2 + Uncertainties["LeptonFullSimUncertainty_%s"%region]**2 + Uncertainties["pileupUncertainty_%s"%region]**2 + Uncertainties["ISRUncertainty_%s"%region]**2 + Uncertainties["BTagUncertaintyLight_%s"%region]**2 + Uncertainties["BTagUncertaintyHeavy_%s"%region]**2  + Uncertainties["TriggerEffUncertainty_%s"%region]**2 + LumiUncertainty**2)
					
					### Totalaluncertainty
					Uncertainties["TotalUncertainty_%s"%region] = sqrt(Uncertainties["SystUncertainty_%s"%region]**2 + Uncertainties["StatUncertainty_%s"%region]**2)
			
					for uncertainty in uncertaintySources:
						uncertaintyArrays["%s_%s"%(uncertainty,region)].append(Uncertainties["%s_%s"%(uncertainty,region)])
						
				for regionCombination in regionCombinations:
						
						Yields["EE_%s"%regionCombination] = 0	
						Yields["EMu_%s"%regionCombination] = 0	
						Yields["MuMu_%s"%regionCombination] = 0	
						Yields["SFOF_%s"%regionCombination] = 0
						
						Uncertainties["Yield_%s"%regionCombination] = 0
						
						MCEvents["EE_%s"%regionCombination] = 0
						MCEvents["EMu_%s"%regionCombination] = 0
						MCEvents["MuMu_%s"%regionCombination] = 0
						MCEvents["SFOF_%s"%regionCombination] = 0
						
						JES["Mean_%s"%regionCombination] =  0
						JES["JESUp_%s"%regionCombination] =  0
						JES["JESDown_%s"%regionCombination] =  0
						
						LeptonFastSim["Mean_%s"%regionCombination] =  0
						LeptonFastSim["MeanShifted_%s"%regionCombination] =  0
						
						LeptonFullSim["Mean_%s"%regionCombination] =  0
						LeptonFullSim["MeanShifted_%s"%regionCombination] =  0
						
						Pileup["Mean_%s"%regionCombination] = 0
						Pileup["PileupHigh_%s"%regionCombination] =  0
						Pileup["PileupLow_%s"%regionCombination] =  0
						
						ISR["Mean_%s"%regionCombination] = 0					
						ISR["ISRUp_%s"%regionCombination] = 0
						ISR["ISRDown_%s"%regionCombination] = 0
							
						BTag["Mean_%s"%regionCombination] = 0					
						BTag["BTagHeavy_%s"%regionCombination] = 0
						BTag["BTagLight_%s"%regionCombination] = 0
							
						Met["Met_%s"%regionCombination] = 0					
						Met["GenMet_%s"%regionCombination] = 0
						
						ScaleShift["Mean_%s"%regionCombination] = 0
						ScaleShift["MaxShift_%s"%regionCombination] = 0
						
						
					### Add information of single regions into combinations
						for region in regions:
							#~ etaBin, massBin, bTagBin = region.split('_')	
							#~ if etaBin in regionCombination or massBin in regionCombination or bTagBin in regionCombination:
								
							if regionCombination in region:
									
								Yields["EE_%s"%regionCombination] += Yields["EE_%s"%region]
								Yields["EMu_%s"%regionCombination] += Yields["EMu_%s"%region]
								Yields["MuMu_%s"%regionCombination] += Yields["MuMu_%s"%region]
								Yields["SFOF_%s"%regionCombination] += Yields["SFOF_%s"%region]
								Uncertainties["Yield_%s"%regionCombination] += Uncertainties["Yield_%s"%region]
								
								MCEvents["EE_%s"%regionCombination] += MCEvents["EE_%s"%region]
								MCEvents["EMu_%s"%regionCombination] += MCEvents["EMu_%s"%region]
								MCEvents["MuMu_%s"%regionCombination] += MCEvents["MuMu_%s"%region]
								MCEvents["SFOF_%s"%regionCombination] += MCEvents["SFOF_%s"%region]
								
								JES["Mean_%s"%regionCombination] +=  JES["Mean_%s"%region]
								JES["JESUp_%s"%regionCombination] +=  JES["JESUp_%s"%region]
								JES["JESDown_%s"%regionCombination] +=  JES["JESDown_%s"%region]
								
								LeptonFastSim["Mean_%s"%regionCombination] +=  LeptonFastSim["Mean_%s"%region]
								LeptonFastSim["MeanShifted_%s"%regionCombination] +=  LeptonFastSim["MeanShifted_%s"%region]
								
								LeptonFullSim["Mean_%s"%regionCombination] +=  LeptonFullSim["Mean_%s"%region]
								LeptonFullSim["MeanShifted_%s"%regionCombination] +=  LeptonFullSim["MeanShifted_%s"%region]
								
								Pileup["Mean_%s"%regionCombination] +=  Pileup["Mean_%s"%region]						
								Pileup["PileupHigh_%s"%regionCombination] +=  Pileup["PileupHigh_%s"%region]
								Pileup["PileupLow_%s"%regionCombination] +=  Pileup["PileupLow_%s"%region]
								
								ISR["Mean_%s"%regionCombination] += ISR["Mean_%s"%region]						
								ISR["ISRUp_%s"%regionCombination] += ISR["ISRUp_%s"%region]
								ISR["ISRDown_%s"%regionCombination] += ISR["ISRDown_%s"%region]		
						
								BTag["Mean_%s"%regionCombination] += BTag["Mean_%s"%region]						
								BTag["BTagHeavy_%s"%regionCombination] += BTag["BTagHeavy_%s"%region]
								BTag["BTagLight_%s"%regionCombination] += BTag["BTagLight_%s"%region]		
						
								Met["Met_%s"%regionCombination] += Met["Met_%s"%region]						
								Met["GenMet_%s"%regionCombination] += Met["GenMet_%s"%region]
								
								ScaleShift["Mean_%s"%regionCombination] += ScaleShift["Mean_%s"%region]
								ScaleShift["MaxShift_%s"%regionCombination] += ScaleShift["MaxShift_%s"%region]
						
						##Calculate uncertaities for combinations			
						Uncertainties["Efficiency_%s"%regionCombination] = Yields["SFOF_%s"%regionCombination]/(xsection*lumi*ISRNormalization)
						Uncertainties["EfficiencyUnscaled_%s"%regionCombination] = MCEvents["SFOF_%s"%regionCombination]/denominator
	
							
						if MCEvents["SFOF_%s"%regionCombination] > 0:
							Uncertainties["StatUncertainty_%s"%regionCombination] = sqrt(MCEvents["EE_%s"%regionCombination]+MCEvents["EMu_%s"%regionCombination]+MCEvents["MuMu_%s"%regionCombination])/MCEvents["SFOF_%s"%regionCombination]
						else:
							Uncertainties["StatUncertainty_%s"%regionCombination] = 0
						
						if JES["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if JES["Mean_%s"%regionCombination] > 0:
							Uncertainties["JESUncertainty_%s"%regionCombination] = max(abs(JES["JESUp_%s"%regionCombination]-JES["Mean_%s"%regionCombination])/JES["Mean_%s"%regionCombination],abs(JES["JESDown_%s"%regionCombination]-JES["Mean_%s"%regionCombination])/JES["Mean_%s"%regionCombination])
						else:
							Uncertainties["JESUncertainty_%s"%regionCombination] = 0
							
						if LeptonFastSim["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if LeptonFastSim["Mean_%s"%regionCombination] > 0:
							Uncertainties["LeptonFastSimUncertainty_%s"%regionCombination] = abs(LeptonFastSim["MeanShifted_%s"%regionCombination]-LeptonFastSim["Mean_%s"%regionCombination])/LeptonFastSim["Mean_%s"%regionCombination]
						else:
							Uncertainties["LeptonFastSimUncertainty_%s"%regionCombination] = 0
						
						if LeptonFullSim["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if LeptonFullSim["Mean_%s"%regionCombination] > 0:
							Uncertainties["LeptonFullSimUncertainty_%s"%regionCombination] = abs(LeptonFullSim["MeanShifted_%s"%regionCombination]-LeptonFullSim["Mean_%s"%regionCombination])/LeptonFullSim["Mean_%s"%regionCombination]
						else:
							Uncertainties["LeptonFullSimUncertainty_%s"%regionCombination] = 0
						
						if Pileup["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if Pileup["Mean_%s"%regionCombination] > 0:
							Uncertainties["pileupUncertainty_%s"%regionCombination] = max(abs(Pileup["PileupHigh_%s"%regionCombination]-Pileup["Mean_%s"%regionCombination])/Pileup["Mean_%s"%regionCombination],abs(Pileup["PileupLow_%s"%regionCombination] -Pileup["Mean_%s"%regionCombination])/Pileup["Mean_%s"%regionCombination] )
						else:
							Uncertainties["pileupUncertainty_%s"%regionCombination] = 0
							
						Uncertainties["pileupUncertainty_%s"%regionCombination] = 0.02
						
						if ISR["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if ISR["Mean_%s"%regionCombination] > 0:
							Uncertainties["ISRUncertainty_%s"%regionCombination] = max(abs(ISR["ISRUp_%s"%regionCombination]-ISR["Mean_%s"%regionCombination])/ISR["Mean_%s"%regionCombination],abs(ISR["ISRDown_%s"%regionCombination]-ISR["Mean_%s"%regionCombination])/ISR["Mean_%s"%regionCombination])
						else:
							Uncertainties["ISRUncertainty_%s"%regionCombination] = 0
							
						if BTag["Mean_%s"%regionCombination] > 0 and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if BTag["Mean_%s"%regionCombination] > 0:
							Uncertainties["BTagUncertaintyHeavy_%s"%regionCombination] = abs(BTag["BTagHeavy_%s"%regionCombination]-BTag["Mean_%s"%regionCombination])/BTag["Mean_%s"%regionCombination]
							Uncertainties["BTagUncertaintyLight_%s"%regionCombination] = abs(BTag["BTagLight_%s"%regionCombination]-BTag["Mean_%s"%regionCombination])/BTag["Mean_%s"%regionCombination]
						else:
							Uncertainties["BTagUncertaintyHeavy_%s"%regionCombination] = 0
							Uncertainties["BTagUncertaintyLight_%s"%regionCombination] = 0
							
						if Met["Met_%s"%regionCombination] > 0  and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if Met["Met_%s"%regionCombination] > 0:
							Uncertainties["MetUncertainty_%s"%regionCombination] = 0.5*abs(Met["Met_%s"%regionCombination]-Met["GenMet_%s"%regionCombination])/Yields["SFOF_%s"%regionCombination]
						else:
							Uncertainties["MetUncertainty_%s"%regionCombination] = 0
					
						if ScaleShift["Mean_%s"%regionCombination] > 0  and MCEvents["SFOF_%s"%regionCombination] > 100:
						#~ if ScaleShift["Mean_%s"%regionCombination] > 0:
							Uncertainties["ScaleUncertainty_%s"%regionCombination] = abs( (ScaleShift["MaxShift_%s"%regionCombination] - ScaleShift["Mean_%s"%regionCombination])/ScaleShift["Mean_%s"%regionCombination])
						else:
							Uncertainties["ScaleUncertainty_%s"%regionCombination] = 0
							
							
						#~ if Yields["SFOF_%s"%regionCombination] > 0:
							#~ Uncertainties["TriggerEffUncertainty_%s"%regionCombination] = sqrt((Yields["EE_%s"%regionCombination]*TriggerEffUncertainty)**2 + (Yields["MuMu_%s"%regionCombination]*TriggerEffUncertainty)**2 + (Yields["EMu_%s"%regionCombination]*TriggerEffUncertainty)**2)/Yields["SFOF_%s"%regionCombination]
						#~ else:
							#~ Uncertainties["TriggerEffUncertainty_%s"%regionCombination] = 0
						Uncertainties["TriggerEffUncertainty_%s"%regionCombination] = 0.05
								
						### Total syst uncertainty
						Uncertainties["SystUncertainty_%s"%regionCombination] = sqrt(Uncertainties["ScaleUncertainty_%s"%regionCombination]**2 + Uncertainties["JESUncertainty_%s"%regionCombination]**2 + Uncertainties["LeptonFastSimUncertainty_%s"%regionCombination]**2 + Uncertainties["LeptonFullSimUncertainty_%s"%regionCombination]**2 + Uncertainties["pileupUncertainty_%s"%regionCombination]**2 + Uncertainties["ISRUncertainty_%s"%regionCombination]**2 + Uncertainties["BTagUncertaintyLight_%s"%regionCombination]**2  + Uncertainties["BTagUncertaintyHeavy_%s"%regionCombination]**2  + Uncertainties["TriggerEffUncertainty_%s"%regionCombination]**2 + LumiUncertainty**2)
						
						### Total uncertainty
						Uncertainties["TotalUncertainty_%s"%regionCombination] = sqrt(Uncertainties["SystUncertainty_%s"%regionCombination]**2 + Uncertainties["StatUncertainty_%s"%regionCombination]**2)		
											
						for uncertainty in uncertaintySources:
							uncertaintyArrays["%s_%s"%(uncertainty,regionCombination)].append(Uncertainties["%s_%s"%(uncertainty,regionCombination)])					
								
			m_n += stepsize		
			
		m_b += stepsize
				
	for regionCombination in regionCombinations:
		
		for uncertainty in uncertaintySources:
			if regionCombination == "lowNll":
				regionName = "ttbar_like"
			else:
				regionName = "non_ttbar_like"
			Graphs["%s_%s"%(uncertainty,regionCombination)]=TGraph2D("%s_%s"%(uncertainty,regionName),"%s_%s"%(uncertainty,regionCombination), len(uncertaintyArrays["%s_%s"%(uncertainty,regionCombination)]), array('d',masses_b), array('d',masses_n), array('d',uncertaintyArrays["%s_%s"%(uncertainty,regionCombination)]))
			Graphs["%s_%s"%(uncertainty,regionCombination)].SetNpx(nxbins)
			Graphs["%s_%s"%(uncertainty,regionCombination)].SetNpy(nybins)
			Histograms["%s_%s"%(uncertainty,regionCombination)] = Graphs["%s_%s"%(uncertainty,regionCombination)].GetHistogram()
			Histograms["%s_%s"%(uncertainty,regionCombination)].SetTitle(";m_{#tilde{b}} [GeV]; m_{#tilde{#chi_{2}^{0}}} [GeV]")
		
		region_label = "Signal Region"
			
		if "lowNll" in regionCombination:
			region_label_2 = "ttbar like"
		elif "highNll" in region:
			region_label_2 = "non-ttbar like"		


		plotPad.SetLogz()
		Histograms["Yield_%s"%regionCombination].SetZTitle("SF-OF yield")
		Histograms["Yield_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/Yields/T6bbllslepton_%s.pdf"%(regionCombination))
		
		plotPad.SetLogz(0)
		Histograms["StatUncertainty_%s"%regionCombination].SetZTitle("SF-OF rel. stat. uncertainty")
		Histograms["StatUncertainty_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/statUncertainties/T6bbllslepton_%s_stat_err.pdf"%(regionCombination))
		
		
		Histograms["SystUncertainty_%s"%regionCombination].SetZTitle("SF-OF rel. syst. uncertainty")
		Histograms["SystUncertainty_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/sysUncertainties/T6bbllslepton_%s_syst_err.pdf"%(regionCombination))
		
		
		Histograms["TotalUncertainty_%s"%regionCombination].SetZTitle("SF-OF total rel. uncertainty")
		Histograms["TotalUncertainty_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/totUncertainties/T6bbllslepton_%s_tot_err.pdf"%(regionCombination))
		
		Histograms["Efficiency_%s"%regionCombination].SetZTitle("acceptance #times efficiency")
		Histograms["Efficiency_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/Efficiencies/T6bbllslepton_%s_signalEfficiency.pdf"%(regionCombination))
		
		Histograms["EfficiencyUnscaled_%s"%regionCombination].SetZTitle("acceptance #times efficiency")
		Histograms["EfficiencyUnscaled_%s"%regionCombination].Draw("colz")
		latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
		latexCMS.DrawLatex(0.19,0.89,"CMS")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
		latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
		#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
		latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
		canv.Update()
		canv.Print("fig/Efficiencies/T6bbllslepton_%s_signalEfficiencyUnscaled.pdf"%(regionCombination))
		
		
		
			
		for uncertainty in uncertaintySources:
			if not ( uncertainty == "Yield" or uncertainty == "StatUncertainty" or uncertainty == "SystUncertainty" or uncertainty == "TotalUncertainty" or uncertainty == "Efficiency" or uncertainty == "EfficiencyUnscaled"):			
				Histograms["%s_%s"%(uncertainty,regionCombination)].SetZTitle("%s"%uncertainty)
				Histograms["%s_%s"%(uncertainty,regionCombination)].Draw("colz")
				latexLumi.DrawLatex(0.85, 0.96, "%s fb^{-1} (13 TeV)"%(printLumi,))
				latexCMS.DrawLatex(0.19,0.89,"CMS")
				#~ latexCMSExtra.DrawLatex(0.19,0.85,"Private Work - Simulation")
				latexCMSExtra.DrawLatex(0.19,0.85,"Simulation")
				#~ latexCMSExtra.DrawLatex(0.19,0.85,"Unpublished")
				latex.DrawLatex(0.175, 0.75, "#splitline{Simplified Model}{#splitline{T6bbslepton, m(#tilde{#chi}_{1}^{0})=100 GeV}{#splitline{"+region_label+"}{"+region_label_2+"}}}")
				canv.Update()
				canv.Print("fig/%s/T6bbllslepton_%s_%s.pdf"%(uncertainty,regionCombination,uncertainty))
	
	histoFile = TFile("fig/T6bbllslepton_XSecUpperLimit_and_ExclusionContours.root")
	
	histoXSection = TH2D(histoFile.Get("XSecUpperLimit"))
	graphExpectedUpperLimit = TGraph2D(histoFile.Get("ExpectedUpperLimit"))
	graphExpectedUpperLimitUp = TGraph2D(histoFile.Get("ExpectedUpperLimitUp"))
	graphExpectedUpperLimitDown = TGraph2D(histoFile.Get("ExpectedUpperLimitDown"))
	graphExpectedUpperLimitUp2 = TGraph2D(histoFile.Get("ExpectedUpperLimitUp2"))
	graphExpectedUpperLimitDown2 = TGraph2D(histoFile.Get("ExpectedUpperLimitDown2"))
	graphObservedUpperLimit = TGraph2D(histoFile.Get("ObservedUpperLimit"))
	graphObservedUpperLimitUp = TGraph2D(histoFile.Get("ObservedUpperLimitUp"))
	graphObservedUpperLimitDown = TGraph2D(histoFile.Get("ObservedUpperLimitDown"))
		
	f1 = TFile("fig/SummaryFile.root","RECREATE")
	for regionCombination in regionCombinations:
		Histograms["Yield_%s"%regionCombination].Write()
		Histograms["Efficiency_%s"%regionCombination].Write()
		Histograms["StatUncertainty_%s"%regionCombination].Write()
		Histograms["SystUncertainty_%s"%regionCombination].Write()
		Histograms["TotalUncertainty_%s"%regionCombination].Write()
		
	histoXSection.Write()
	graphExpectedUpperLimit.Write()
	graphExpectedUpperLimitUp.Write()
	graphExpectedUpperLimitDown.Write()
	graphExpectedUpperLimitUp2.Write()
	graphExpectedUpperLimitDown2.Write()
	graphObservedUpperLimit.Write()
	graphObservedUpperLimitUp.Write()
	graphObservedUpperLimitDown.Write()	
	
	f1.Close()			
Exemple #30
0
def compareMassRes(trackType):
	


	cat = ["B","O","E"]
	for c in cat:

		file2016BB = open("defaultPSplit/PResolutionVsP_%s_%s.pkl"%(trackType,c))
		file2017BB = open("cruijffPSplit/PResolutionVsP_%s_%s.pkl"%(trackType,c))
		fileCBB = open("crystalPSplit/PResolutionVsP_%s_%s.pkl"%(trackType,c))

		results2016BB = pickle.load(file2016BB)
		results2017BB = pickle.load(file2017BB)
		resultsCBB = pickle.load(fileCBB)


		graph2016BB = getGraph(results2016BB,"DCBBB")
		graph2017BB = getGraph(results2017BB,"CruijffBB")
		graphCBB = getGraph(resultsCBB,"CBB")
			
		
		ratioBB = 	getRatio(results2016BB,results2017BB,"ratioBB")
		ratioCBB = 	getRatio(results2016BB,resultsCBB,"ratioCBB")


		canv = TCanvas("c1","c1",800,1200)

		plotPad = TPad("plotPad","plotPad",0,0.3,1,1)
		ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
		style = setTDRStyle()
		gStyle.SetOptStat(0)
		plotPad.UseCurrentStyle()
		ratioPad.UseCurrentStyle()
		plotPad.Draw()	
		ratioPad.Draw()	
		plotPad.cd()
		plotPad.cd()
		plotPad.SetGrid()
		gStyle.SetTitleXOffset(1.45)
		gStyle.SetTitleYOffset(1.55)

		xMax = 0.15
		if trackType == "Inner":
			xMax = 0.3
		if trackType == "Outer":
			xMax = 0.5

		plotPad.DrawFrame(0,0,3100,xMax,";p^{#mu} [GeV]; p^{#mu} resolution")

		graph2016BB.Draw("samepe")
		graph2017BB.Draw("samepe")
		graphCBB.Draw("samepe")
		graph2017BB.SetLineColor(kRed)
		graph2017BB.SetMarkerColor(kRed)
		graphCBB.SetLineColor(kBlue)
		graphCBB.SetMarkerColor(kBlue)

		latex = TLatex()
		latex.SetTextFont(42)
		latex.SetTextAlign(31)
		latex.SetTextSize(0.04)
		latex.SetNDC(True)
		latexCMS = TLatex()
		latexCMS.SetTextFont(61)
		latexCMS.SetTextSize(0.055)
		latexCMS.SetNDC(True)
		latexCMSExtra = TLatex()
		latexCMSExtra.SetTextFont(52)
		latexCMSExtra.SetTextSize(0.03)
		latexCMSExtra.SetNDC(True) 

		latex.DrawLatex(0.95, 0.96, "(13 TeV)")

		cmsExtra = "#splitline{Preliminary}{}"
		latexCMS.DrawLatex(0.19,0.88,"CMS")
		if "Simulation" in cmsExtra:
			yLabelPos = 0.81	
		else:
			yLabelPos = 0.84	

		latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra))			


		leg = TLegend(0.52, 0.76, 0.95, 0.91,"%s %s"%(trackType,c),"brNDC")
		leg.SetFillColor(10)
		leg.SetFillStyle(0)
		leg.SetLineColor(10)
		leg.SetShadowColor(0)
		leg.SetBorderSize(1)		
		leg.AddEntry(graph2016BB,"Cruijff","l")
		leg.AddEntry(graph2017BB,"Double CB","l")
		leg.AddEntry(graphCBB,"Crystal Ball","l")

		leg.Draw()

		plotPad.RedrawAxis()


		ratioPad.cd()

		ratioBB.SetLineColor(kRed)
		ratioCBB.SetLineColor(kBlue)

		ratioPad.DrawFrame(0,0.5,3100,1.5,";ratio")

		ratioBB.Draw("samepe")
		ratioCBB.Draw("samepe")


		canv.Print("pResolutionCompareFunc_%s_%s.pdf"%(trackType,c))
def plot():
	import re
	import ratios
	from ROOT import TCanvas, TPad, TH1F, TH2F, TH1I, THStack, TLegend, TMath, TF1, TGraph, TGraph2D, TFile, TObjArray, gROOT
	from setTDRStyle import setTDRStyle
	import pickle
	from defs import sbottom_masses
	from math import sqrt
	
	canv = TCanvas("canv", "canv",800,800)
	plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
	style=setTDRStyle()	
	style.SetPadRightMargin(0.18)	
	style.SetTitleYOffset(1.54)	
	plotPad.UseCurrentStyle()
	plotPad.Draw()	
	plotPad.cd()
	
	exclusionContours = ["obsR","obsR_up","obsR_down","expR","expR_up","expR_down","expR_2up","expR_2down","obsXsecLimit"]
	Graphs = {}
	Histograms = {}
	
	printLumi = "35.9"
	
	m_n_min = 150
	m_n_max = 1550
	#~ m_n_max = 1450
	m_b_min = 700
	m_b_max = 1600
	#~ m_b_max = 1450
	
	
	Exclusions = {}	
	
	for exclusionContour in exclusionContours:
		Exclusions[exclusionContour] = []
		
	masses_b = []
	masses_n = []
	cross_sections = []
		
	m_b = m_b_min
	while m_b <= m_b_max:
		if m_b < 800:
			stepsize = 25
		else:
			stepsize = 50
			
		m_n = m_n_min
		
		while m_n < m_b:
			
			### Privately produced points that were missing before have less statistics
			### than the surrounding points -> cause some strange effects in plot
			### better to ignore them and let root interpolate the histogram
			if not ((m_b == 775 and m_n == 750) or (m_b == 800 and m_n == 150) or (m_b == 950 and m_n == 250) or (m_b == 950 and m_n == 300) or (m_b == 950 and m_n == 500) or (m_b == 950 and m_n == 550) or (m_b == 950 and m_n == 850) or (m_b == 950 and m_n == 900)):	
				limitFile = open("Limits/T6bbllslepton_%s_%s.result.txt"%(str(m_b),str(m_n)),"r")
				masses_b.append(m_b)
				masses_n.append(m_n)
				M_SBOTTOM = "m_b_"+str(m_b)
				xSection = getattr(sbottom_masses, M_SBOTTOM).cross_section13TeV
				xsectionUncert = getattr(sbottom_masses, M_SBOTTOM).cross_sectionUncertainty
				cross_sections.append(xSection)
				
				for line in limitFile:
					
					if "CLs observed asymptotic" in line:
						observed_R = float(re.findall("\d+\.\d+",line)[0])
	
						Exclusions["obsR"].append(observed_R)
						Exclusions["obsR_up"].append(observed_R*(1+xsectionUncert))
						Exclusions["obsR_down"].append(observed_R*(1-xsectionUncert))
						
						Exclusions["obsXsecLimit"].append(observed_R*xSection)
											
					if "CLs expected asymptotic" in line:
						Exclusions["expR"].append(float(re.findall("\d+\.\d+",line)[0]))
						
					if "CLs expected m1sigma asymptotic" in line:
						Exclusions["expR_down"].append(float(re.findall("\d+\.\d+",line)[0]))
						
					if "CLs expected p1sigma asymptotic" in line:
						Exclusions["expR_up"].append(float(re.findall("\d+\.\d+",line)[0]))
					
					if "CLs expected m2sigma asymptotic" in line:
						Exclusions["expR_2down"].append(float(re.findall("\d+\.\d+",line)[0]))
						
					if "CLs expected p2sigma asymptotic" in line:
						Exclusions["expR_2up"].append(float(re.findall("\d+\.\d+",line)[0]))
				
			m_n += stepsize		
		m_b += stepsize
		
	bin_size =12.5
	nxbins = int(min(500,(m_b_max-m_b_min)/bin_size))
	nybins = int(min(500,(m_n_max-m_n_min)/bin_size))
	
	for exclusionContour in exclusionContours:
		Graphs[exclusionContour] = TGraph2D("Graph_%s"%(exclusionContour),exclusionContour, len(Exclusions[exclusionContour]), array('d',masses_b), array('d',masses_n), array('d',Exclusions[exclusionContour]))
	
	dots = TGraph(len(masses_b), array('d',masses_b), array('d',masses_n))
	
	contours = array('d',[1.0])
	
	Histograms["obsXsecLimit"] = Graphs["obsXsecLimit"].GetHistogram()
	Histograms["obsXsecLimit"].SetTitle("Observed cross section limit;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["obsXsecLimit"].GetZaxis().SetRangeUser(0.0002,0.05)
		
	Histograms["expR"] = Graphs["expR"].GetHistogram()	
	Histograms["expR"].SetContour(1,contours)
	Histograms["expR"].SetLineWidth(4)
	Histograms["expR"].SetLineStyle(2)
	Histograms["expR"].SetLineColor(2)
	Histograms["expR"].Smooth()
		
	Histograms["expR_up"] = Graphs["expR_up"].GetHistogram()	
	Histograms["expR_up"].SetContour(1,contours)
	Histograms["expR_up"].SetLineWidth(2)
	Histograms["expR_up"].SetLineStyle(2)
	Histograms["expR_up"].SetLineColor(2)
	Histograms["expR_up"].Smooth()
	
	Histograms["expR_down"] = Graphs["expR_down"].GetHistogram()	
	Histograms["expR_down"].SetContour(1,contours)
	Histograms["expR_down"].SetLineWidth(2)
	Histograms["expR_down"].SetLineStyle(2)
	Histograms["expR_down"].SetLineColor(2)
	Histograms["expR_down"].Smooth()
	
	Histograms["expR_2up"] = Graphs["expR_2up"].GetHistogram()	
	Histograms["expR_2up"].SetContour(1,contours)
	Histograms["expR_2up"].SetLineWidth(2)
	Histograms["expR_2up"].SetLineStyle(2)
	Histograms["expR_2up"].SetLineColor(2)
	Histograms["expR_2up"].Smooth()
	
	Histograms["expR_2down"] = Graphs["expR_2down"].GetHistogram()	
	Histograms["expR_2down"].SetContour(1,contours)
	Histograms["expR_2down"].SetLineWidth(2)
	Histograms["expR_2down"].SetLineStyle(2)
	Histograms["expR_2down"].SetLineColor(2)
	Histograms["expR_2down"].Smooth()
	
	Histograms["obsR"] = Graphs["obsR"].GetHistogram()	
	Histograms["obsR"].SetContour(1,contours)
	Histograms["obsR"].SetLineWidth(4)
	Histograms["obsR"].SetLineStyle(1)
	Histograms["obsR"].SetLineColor(1)
	Histograms["obsR"].Smooth()
	
	Histograms["obsR_up"] = Graphs["obsR_up"].GetHistogram()	
	Histograms["obsR_up"].SetContour(1,contours)
	Histograms["obsR_up"].SetLineWidth(2)
	Histograms["obsR_up"].SetLineStyle(1)
	Histograms["obsR_up"].SetLineColor(1)
	Histograms["obsR_up"].Smooth()
	
	Histograms["obsR_down"] = Graphs["obsR_down"].GetHistogram()	
	Histograms["obsR_down"].SetContour(1,contours)
	Histograms["obsR_down"].SetLineWidth(2)
	Histograms["obsR_down"].SetLineStyle(1)
	Histograms["obsR_down"].SetLineColor(1)
	Histograms["obsR_down"].Smooth()
	
	
	
	latex = ROOT.TLatex()
	latex.SetTextSize(0.03)
	latex.SetNDC(True)
	latexLumi = ROOT.TLatex()
	latexLumi.SetTextFont(42)
	latexLumi.SetTextAlign(31)
	latexLumi.SetTextSize(0.04)
	latexLumi.SetNDC(True)
	latexCMS = ROOT.TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.05)
	latexCMS.SetNDC(True)
	latexCMSExtra = ROOT.TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.0375)
	latexCMSExtra.SetNDC(True)
	
	latexLegendHeader = ROOT.TLatex() 
	latexLegendHeader.SetTextSize(0.025)
	latexLegendHeader.SetNDC(True)
	
	Overlay = ROOT.TGraph(0)
	Overlay.SetPoint(0, 700, 625)
	Overlay.SetPoint(1, 1650, 1575)
	Overlay.SetPoint(2, 700, 1575)
	Overlay.SetPoint(3, 700, 625)
	Overlay.SetFillColor(0)
	
	leg1 = ROOT.TLegend(0.19,0.72,0.83,0.92)
	leg1.SetBorderSize(1)
	leg1.SetLineWidth(2)
	
	leg = ROOT.TLegend(0.195,0.725,0.825,0.82)
	leg.SetTextSize(0.025)
	leg.SetBorderSize(0)
	leg.SetLineWidth(0)
	leg.AddEntry(Histograms["expR"], "Expected limit, #pm 1 (2) #sigma_{exp.}","l")
	leg.AddEntry(Histograms["obsR"], "Observed limit, #pm 1 #sigma_{theory}","l")
	
	plotPad.SetTopMargin(0.08)
	plotPad.SetBottomMargin(0.13)
	plotPad.SetLeftMargin(0.19)
	plotPad.SetRightMargin(0.17)
	
	
	
	
	plotPad.DrawFrame(700,150,1600,1750,";m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	
	plotPad.SetLogz()
	#~ Histograms["obsXsecLimit"].GetYaxis().SetTitleOffset(1.5)
	Histograms["obsXsecLimit"].SetZTitle("95% CL upper limit on #sigma [pb]")
	Histograms["obsXsecLimit"].GetZaxis().SetLabelSize(0.035)
	Histograms["obsXsecLimit"].GetZaxis().SetTitleOffset(1.0)
	Histograms["obsXsecLimit"].Draw("SAME COLZ")
	Histograms["expR_2up"].Draw("SAMECONT3")
	Histograms["expR_2down"].Draw("SAMECONT3")
	Histograms["expR_up"].Draw("SAMECONT3")
	Histograms["expR_down"].Draw("SAMECONT3")
	Histograms["expR"].Draw("SAMECONT3")
	Histograms["obsR_up"].Draw("SAMECONT3")
	Histograms["obsR_down"].Draw("SAMECONT3")
	Histograms["obsR"].Draw("SAMECONT3")
	Overlay.Draw("f")
	
	latexLumi.DrawLatex(0.83, 0.94, "%s fb^{-1} (13 TeV)"%(printLumi))
	latexCMS.DrawLatex(0.185,0.94,"CMS")
	#~ latexCMSExtra.DrawLatex(0.29,0.94,"Preliminary")
	plotPad.RedrawAxis()
	leg1.Draw("same")
	leg.Draw("same")
	latexLegendHeader.DrawLatex(0.2, 0.85, "#splitline{pp#rightarrow#tilde{b}#tilde{b}, #tilde{b}#rightarrow#tilde{#chi}_{2}^{0}b, #tilde{#chi}_{2}^{0}#rightarrow#tilde{l}l/Z#tilde{#chi}_{1}^{0}, #tilde{l}#rightarrow#tilde{#chi}_{1}^{0}l; m_{#tilde{#chi_{1}}^{0}}= 100 GeV}{m_{#tilde{l}} = 0.5(m_{#tilde{#chi}_{2}^{0}}+ m_{#tilde{#chi}_{1}^{0}}); NLO+NLL exclusion}")
	canv.Update()
	canv.Print("fig/LimitPlot.pdf")
	canv.Print("fig/LimitPlot.png")
	
	
	
	Histograms["obsXsecLimit"].SetName("XSecUpperLimit")
	Histograms["expR"].SetName("ExpectedUpperLimit")
	Histograms["expR_up"].SetName("ExpectedUpperLimitUp")
	Histograms["expR_down"].SetName("ExpectedUpperLimitDown")
	Histograms["expR_2up"].SetName("ExpectedUpperLimitUp2")
	Histograms["expR_2down"].SetName("ExpectedUpperLimitDown2")
	Histograms["obsR"].SetName("ObservedUpperLimit")
	Histograms["obsR_up"].SetName("ObservedUpperLimitUp")
	Histograms["obsR_down"].SetName("ObservedUpperLimitDown")
	
	Graphs["expR"].SetName("ExpectedUpperLimit")
	Graphs["expR_up"].SetName("ExpectedUpperLimitUp")
	Graphs["expR_down"].SetName("ExpectedUpperLimitDown")
	Graphs["expR_2up"].SetName("ExpectedUpperLimitUp2")
	Graphs["expR_2down"].SetName("ExpectedUpperLimitDown2")
	Graphs["obsR"].SetName("ObservedUpperLimit")
	Graphs["obsR_up"].SetName("ObservedUpperLimitUp")
	Graphs["obsR_down"].SetName("ObservedUpperLimitDown")
	
	Histograms["expR"].SetTitle("Expected Upper Limit;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["expR_up"].SetTitle("Expected Upper Limit + 1 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["expR_down"].SetTitle("Expected Upper Limit - 1 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["expR_2up"].SetTitle("Expected Upper Limit + 2 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["expR_2down"].SetTitle("Expected Upper Limit - 2 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["obsR"].SetTitle("Observed Upper Limit;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["obsR_up"].SetTitle("Observed Upper Limit + 1 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histograms["obsR_down"].SetTitle("Observed Upper Limit - 1 #sigma;m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	
	f1 = TFile("fig/T6bbllslepton_XSecUpperLimit_and_ExclusionContours.root","RECREATE")
	Histograms["obsXsecLimit"].Write()
	Histograms["expR"].Write()
	Histograms["expR_up"].Write()
	Histograms["expR_down"].Write()
	Histograms["expR_2up"].Write()
	Histograms["expR_2down"].Write()
	Histograms["obsR"].Write()
	Histograms["obsR_up"].Write()
	Histograms["obsR_down"].Write()
	f1.Close()
def someOtherFunction():    
    gROOT.SetBatch()
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)
    gStyle.SetErrorX(0)
    setTDRStyle()

    labelcms  = TPaveText(0.12,0.88,0.5,0.94,"NDCBR")
    labelcms.SetTextAlign(12)
    labelcms.SetTextSize(0.045)
    labelcms.SetFillColor(kWhite)
    labelcms.AddText("CMS Preliminary, #sqrt{s} = 8 TeV")
    labelcms.SetBorderSize(0)

    labelcms2  = TPaveText(0.12,0.85,0.5,0.88,"NDCBR")
    labelcms2.SetTextAlign(12)
    labelcms2.SetTextSize(0.045)
    labelcms2.SetFillColor(kWhite)

    if options.cutMode == "ee":
        labelcms2.AddText("12.2 fb^{-1}, ee channel")
    if options.cutMode == "emu":
        labelcms2.AddText("12.2 fb^{-1}, e#mu channel")
    if options.cutMode == "mumu":
        labelcms2.AddText("12.2 fb^{-1}, #mu#mu channel")

#    labelcms2.AddText("12.2 fb^{-1}, ee,e#mu,#mu#mu channels")

    labelcms2.SetBorderSize(0)

    gStyle.SetPalette(1)
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetCanvasColor(kWhite)
    gStyle.SetCanvasDefH(600)
    gStyle.SetCanvasDefW(600)
    gStyle.SetLabelFont(18,"")
    
    gStyle.SetTitleXOffset(1.2)
    gStyle.SetTitleYOffset(1.2)
    
    mcDists = THStack("mcDists", "MC Distributions")
    cutFlows['other'].SetFillColor(kGreen-3)
    cutFlows['other'].SetLineColor(kBlack)
    mcDists.Add(cutFlows['other'])
    cutFlows['zPlusJets'].SetFillColor(kAzure-2)
    cutFlows['zPlusJets'].SetLineColor(kBlack)
    mcDists.Add(cutFlows['zPlusJets'])
    cutFlows['ttbar'].SetFillColor(kRed+1)
    cutFlows['ttbar'].SetLineColor(kBlack)
    mcDists.Add(cutFlows['ttbar'])
    cutFlows['tW'].SetLineColor(kBlack)
    mcDists.Add(cutFlows['tW'])
    canvy = TCanvas("Control Region Plots", "Control Region Plots")
    canvy.cd()
    leg = TLegend(0.7,0.7,0.94,0.94)
    leg.SetFillStyle(1001)
    leg.SetFillColor(kWhite)
    leg.SetBorderSize(1)
    leg.AddEntry(cutFlows['data'], 'Data', 'p')
    leg.AddEntry(cutFlows['tW'], 'tW','f')
    leg.AddEntry(cutFlows['ttbar'], 't#bar{t}','f')
    leg.AddEntry(cutFlows['zPlusJets'], 'Z/#gamma*+jets','f')
    leg.AddEntry(cutFlows['other'], 'Other','f')
    cutFlows['data'].SetMarkerStyle(20)
    cutFlows['data'].SetMarkerSize(1.2)
    cutFlows['data'].SetLineWidth(1)
    cutFlows['data'].SetMarkerColor(kBlack)
    cutFlows['data'].SetLineColor(kBlack)
    max = TMath.Max(mcDists.GetMaximum(), cutFlows['data'].GetMaximum())
    mcDists.Draw('')
    mcDists.SetMaximum(max * 1.2)
    mcDists.SetMinimum(0)
    mcDists.GetXaxis().SetBinLabel(1,"Lepton Selection")
    mcDists.GetXaxis().SetBinLabel(2,"m_{ll}")
    mcDists.GetXaxis().SetBinLabel(3,"E_{T}^{miss}")
    mcDists.GetXaxis().SetBinLabel(4,"1 jet")
    mcDists.GetXaxis().SetBinLabel(5,"b-tag")
    mcDists.GetXaxis().SetBinLabel(6,"H_{T}")

    mcDists.GetYaxis().SetTitle("events / 12.2 fb^{-1}")
    mcDists.GetYaxis().CenterTitle()
    cutFlows['data'].Draw("e, sames")
    leg.Draw()
    labelcms.Draw()
    labelcms2.Draw()

    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + ".png")
    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + ".pdf")
    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + ".root")
    mcDists.SetMinimum(1)
    mcDists.SetMaximum(10*max)
    canvy.SetLogy()

    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + "_log.png")
    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + "_log.pdf")
    canvy.SaveAs(options.outFolder  + "cutFlow_" + options.cutMode + options.postfix + "_log.root")

    
    canvy.SetLogy(0)

    hextra =TH1F( cutFlows['other'].Clone())
    hextra.Add(cutFlows['zPlusJets'])
    hextra.Add(cutFlows['ttbar'])
    hextra.Add(cutFlows['tW'])
    hextra.Sumw2()
    setex2 = TExec("setex2","gStyle.SetErrorX(0.5)")
    setex2.Draw()
    hextra.Sumw2()
    GE = TGraphAsymmErrors(hextra)
    
    GE.SetFillColor(28)
    GE.SetFillStyle(3018)
    GE.SetMarkerSize(0)
    GE.SetLineWidth(0)
    GE.SetLineColor(kWhite)
    leg.AddEntry(GE,"uncertainty","f")
    mcDists.SetMaximum(max*1.2)
    mcDists.SetMinimum(0)
    GE.Draw("sames, e2")
    setex1 = TExec("setex1","gStyle.SetErrorX(0)")
    setex1.Draw()
    cutFlows['data'].Draw("e, sames")

    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + ".png")
    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + ".pdf")
    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + ".root")

    mcDists.SetMaximum(max * 10)
    mcDists.SetMinimum(1)
    canvy.SetLogy()

    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + "_log.png")
    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + "_log.pdf")
    canvy.SaveAs(options.outFolder  + "error_cutFlow_" + options.cutMode + options.postfix + "_log.root")
Exemple #33
0
    def plot(self) :
        if len(self.data_) == 0 :
            print "No data!"
            return

        setTDRStyle()
        
        leg = TLegend( 0.15, 0.91-(0.045*(len(self.data_)+1)), 0.35, 0.91 )
        leg.SetFillColor(0)
        leg.SetLineColor(0) 
        leg.SetShadowColor(0) 
        leg.SetTextSize(0.035)
        
        mg = TMultiGraph()

        plot = self.fill(self.systematics(),systematics=True)
        plot.SetLineColor(kGray)
        plot.SetFillColor(kGray)
        mg.Add(plot,"2")
        leg.AddEntry(plot,"Systematic uncertainty","f")

        fit0 = []
        fit1 = []
        for idx,key in enumerate(self.data_.keys()) :
            #print "'%s'"%self.titles_[key]
            plot = self.fill(self.data_[key],index=idx)
            plot.SetTitle("")
            plot.SetMarkerStyle(self.markers_[idx])
            plot.SetMarkerSize(self.size_[idx])
            plot.SetLineColor(1)
            plot.SetLineWidth(2)
            mg.Add(plot,"pZ")
            leg.AddEntry(plot,self.titles_[key],"p")
            f0,f1 = self.fit(plot)
            fit0.append(f0)
            fit1.append(f1)

        self.pvalues([i[4] for i in fit0],"p-values from constant fits")
        print "'%s': p0 = %.2f+/-%.2f, chi2/dof = %.2f/%i, p-value = %.2f" \
            %(self.titles_[key],f0[0],f0[1],f0[2],f0[3],f0[4])

        self.pvalues([i[6] for i in fit1],"p-values from linear fits")
        print "'%s': p0 = %.2f+/-%.2f, p1 = %.4f+/-%.4f, chi2/dof = %.2f/%i, p-value = %.2f" \
            %(self.titles_[key],f1[0],f1[1],f1[2],f1[3],f1[4],f1[5],f1[6])
            
        canvas = TCanvas("Closure tests","",900,600)
        mg.Draw("ap")
        mg.GetXaxis().SetTitle("H_{T} (GeV)")
        mg.GetYaxis().SetTitle("( N_{obs} - N_{pred} ) / N_{pred}")
        #mg.GetYaxis().SetRangeUser(-1.25,2.25)
        mg.GetYaxis().SetRangeUser(-2.,4.)
        mg.GetXaxis().SetRangeUser(self.bins_[0],self.bins_[self.nbins_])
        mg.GetXaxis().SetNdivisions(510)
        leg.Draw("same")
        prelim = "CMS Preliminary" if self.prelim_ else "CMS"
        str1 = "#splitline{%s}{L_{int} = %s fb^{-1}, #sqrt{s} = %s TeV}" % ( prelim, self.lumi_, self.energy_ )
        txt1 = TLatex(0.62,(0.91-0.06),str1)
        txt1.SetNDC()
        txt1.SetTextSize(0.04)
        txt1.Draw("same")

        str2 = ""
        temp = self.data_.keys()[0]
        if temp.count("_all") > 0 :
            str2 = "n_{jet} #geq 2"
        elif temp.count("_2") > 0 :
            str2 = "2 #leq n_{jet} #leq 3"
        elif temp.count("_3") > 0 :
            str2 = "n_{jet} #geq 4"
        else :
            str2 = "n_{jet} ERROR!"
        txt2 = TLatex(0.62,0.76,str2)
        txt2.SetNDC()
        txt2.SetTextSize(0.04)
        txt2.Draw()

        canvas.Update()
        canvas.SaveAs(self.label_+"/summary_plot.pdf")
        if not self.batch_ : input("Press any key to continue...")
def plot():
	import re
	import ratios
	from ROOT import TCanvas, TPad, TH1F, TH2F, TH1I, THStack, TLegend, TMath, TF1, TGraph, TGraph2D, TFile, TObjArray, gROOT
	from setTDRStyle import setTDRStyle
	import pickle
	from defs import sbottom_masses
	from math import sqrt
	
	canv = TCanvas("canv", "canv",800,800)
	plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
	style=setTDRStyle()	
	style.SetPadRightMargin(0.18)		
	style.SetTitleYOffset(1.54)	
	plotPad.UseCurrentStyle()
	plotPad.Draw()	
	plotPad.cd()
	
	Graphs = {}
	Histograms = {}
	
	printLumi = "35.9"
	
	m_n_min = 150
	m_n_max = 1550
	m_b_min = 700
	m_b_max = 1600
	
		
	masses_b = []
	masses_n = []
	significances = []
		
	m_b = m_b_min
	while m_b <= m_b_max:
		if m_b < 800:
			stepsize = 25
		else:
			stepsize = 50
			
		m_n = m_n_min
		
		while m_n < m_b:
			
			#~ if not ((m_b == 775 and m_n == 750) or (m_b == 800 and m_n == 150) or (m_b == 950 and m_n == 250) or (m_b == 950 and m_n == 300) or (m_b == 950 and m_n == 500) or (m_b == 950 and m_n == 550) or (m_b == 950 and m_n == 850) or (m_b == 950 and m_n == 900)):	
				
			#~ print "Limits/T6bbllslepton_%s_%s.result.txt"%(str(m_b),str(m_n))
			limitFile = open("Significances/T6bbllslepton_%s_%s.result.txt"%(str(m_b),str(m_n)),"r")
			masses_b.append(m_b)
			masses_n.append(m_n)
			M_SBOTTOM = "m_b_"+str(m_b)
			
			for line in limitFile:
				
				if "observed significance" in line:
					#~ significance = float(re.findall("\d+\.\d+",line)[0])
					significance = float(re.findall(r"[-+]?\d*\.\d+|\d+",line)[0])
					#~ print significance
					
					if significance < -3.5:
						significance = -3.49

					significances.append(significance)
					
			m_n += stepsize		
		m_b += stepsize
		
	bin_size =12.5
	nxbins = int(min(500,(m_b_max-m_b_min)/bin_size))
	nybins = int(min(500,(m_n_max-m_n_min)/bin_size))
	
	
	Graph = TGraph2D("Graph_significance","Local significance", len(significances), array('d',masses_b), array('d',masses_n), array('d',significances))
	Graph.SetNpx(nxbins)
	Graph.SetNpy(nybins)
	
	
	
	Histogram = Graph.GetHistogram()
	Histogram.SetTitle(";m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	Histogram.GetZaxis().SetRangeUser(-3.5,3.5)
	
	
	latex = ROOT.TLatex()
	latex.SetTextSize(0.03)
	latex.SetNDC(True)
	latexLumi = ROOT.TLatex()
	latexLumi.SetTextFont(42)
	latexLumi.SetTextAlign(31)
	latexLumi.SetTextSize(0.04)
	latexLumi.SetNDC(True)
	latexCMS = ROOT.TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.05)
	latexCMS.SetNDC(True)
	latexCMSExtra = ROOT.TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.0375)
	latexCMSExtra.SetNDC(True)
	
	latexLegendHeader = ROOT.TLatex() 
	latexLegendHeader.SetTextSize(0.032)
	latexLegendHeader.SetTextFont(42)
	latexLegendHeader.SetNDC(True)
	
	Overlay = ROOT.TGraph(0)
	Overlay.SetPoint(0, 700, 625)
	Overlay.SetPoint(1, 1650, 1575)
	Overlay.SetPoint(2, 700, 1575)
	Overlay.SetPoint(3, 700, 625)
	Overlay.SetFillColor(0)
	
	oneLine = ROOT.TLine(400, 375, 950, 900)
	oneLine.SetLineStyle(9)
	oneLine.SetLineWidth(2)
	
	leg1 = ROOT.TLegend(0.19,0.78,0.83,0.92)
	leg1.SetBorderSize(1)
	leg1.SetLineWidth(2)
	
	leg = ROOT.TLegend(0.195,0.785,0.825,0.82)
	leg.SetTextSize(0.025)
	leg.SetBorderSize(0)
	leg.SetLineWidth(0)
	
	plotPad.SetTopMargin(0.08)
	plotPad.SetBottomMargin(0.16)
	plotPad.SetLeftMargin(0.19)
	plotPad.SetRightMargin(0.17)
	
	plotPad.DrawFrame(700,150,1600,1750,";m_{#tilde{b}} [GeV]; m_{#tilde{#chi}_{2}^{0}} [GeV]")
	
	Histogram.SetZTitle("Observed Local Significance (#sigma)")
	Histogram.GetZaxis().SetLabelSize(0.045)
	Histogram.GetZaxis().SetTitleSize(0.045)
	Histogram.GetZaxis().SetTitleOffset(1.1)
	Histogram.Draw("SAME COLZ")
	Overlay.Draw("f")
	
	
	latexLumi.DrawLatex(0.83, 0.94, "%s fb^{-1} (13 TeV)"%(printLumi))
	latexCMS.DrawLatex(0.185,0.94,"CMS")
	latexCMSExtra.DrawLatex(0.289,0.94,"Preliminary")
	plotPad.RedrawAxis()
	leg1.Draw("same")
	leg.Draw("same")
	latexLegendHeader.DrawLatex(0.2, 0.84, "#splitline{pp #rightarrow #tilde{b} #tilde{b}, #tilde{b} #rightarrow #tilde{#chi}_{2}^{0} b, #tilde{#chi}_{2}^{0} #rightarrow #tilde{l} l / Z #tilde{#chi}_{1}^{0}, #tilde{l} #rightarrow #tilde{#chi}_{1}^{0} l}{m_{#tilde{#chi_{1}}^{0}} = 100 GeV, m_{#tilde{l}} = 0.5 (m_{#tilde{#chi}_{2}^{0}} + m_{#tilde{#chi}_{1}^{0}})}")
	canv.Update()
	canv.Print("fig/Significances.pdf")
	
	
	
	Histogram.SetName("ObsSignificance")
	
	Graph.SetName("ObsSignificance")
	
	Graph.SetTitle("Observed Local Significance in #sigma")
	
	f1 = TFile("fig/T6bbllslepton_Significance.root","RECREATE")
	Histogram.Write()
	f1.Close()
def plot(path,selection,plots,runRange,isMC,backgrounds,cmsExtra):
	

	
	for name in plots:
		plot = getPlot(name)
		plot.addRegion(selection)
		plot.cleanCuts()	
		plot.cuts = plot.cuts % runRange.runCut	


		if isMC:
			histEE, histMM = getHistograms(path,plot,runRange,True, backgrounds)	
		else:
			histEE, histMM = getHistograms(path,plot,runRange,False, backgrounds)	
			
		
		hCanvas = TCanvas("hCanvas", "Distribution", 800,800)
		
		plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
		setTDRStyle()
		plotPad.UseCurrentStyle()
		
		plotPad.Draw()	
		plotPad.cd()	
				
			
		latex = ROOT.TLatex()
		latex.SetTextFont(42)
		latex.SetTextAlign(31)
		latex.SetTextSize(0.04)
		latex.SetNDC(True)
		latexCMS = ROOT.TLatex()
		latexCMS.SetTextFont(61)
		latexCMS.SetTextSize(0.06)
		latexCMS.SetNDC(True)
		latexCMSExtra = ROOT.TLatex()
		latexCMSExtra.SetTextFont(52)
		latexCMSExtra.SetTextSize(0.045)
		latexCMSExtra.SetNDC(True)		

		intlumi = ROOT.TLatex()
		intlumi.SetTextAlign(12)
		intlumi.SetTextSize(0.03)
		intlumi.SetNDC(True)					
		

		logScale = plot.log

		if logScale == True:
			plotPad.SetLogy()
			
	
		yMax = histMM.GetBinContent(histMM.GetMaximumBin())
		if plot.yMax == 0:
			if logScale:
				yMax = yMax*1000
			else:
				yMax = yMax*1.5
							
		else: yMax = plot.yMax


		plotPad.DrawFrame(plot.firstBin,plot.yMin,plot.lastBin,yMax,"; %s ; %s" %(plot.xaxis,plot.yaxis))
		
		legend = ROOT.TLegend(0.65,0.7,0.9,0.9)
		legend.SetFillStyle(0)
		legend.SetBorderSize(0)	
		legend.AddEntry(histMM,"#mu#mu events","p")
		legend.AddEntry(histEE,"ee events","p")
		histMM.SetMarkerColor(ROOT.kRed)
		histMM.SetLineColor(ROOT.kRed)
		histMM.SetMarkerStyle(20)
		histEE.SetMarkerStyle(21)
		histMM.Draw("samepe")
		histEE.Draw("samepe")
		legend.Draw("same")
		ROOT.gPad.SetLogy(1)
		
		latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)"%runRange.printval)
		

		latexCMS.DrawLatex(0.19,0.88,"CMS")
		if "Simulation" in cmsExtra:
			yLabelPos = 0.81	
		else:
			yLabelPos = 0.84	

		latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra))
		
		
		
		hCanvas.Print("fig/testPlots_%s_%s_%s_%s.pdf"%(selection.name,runRange.label,plot.variablePlotName,plot.additionalName))	
def compareMassRes(trackType):

    fileDefaultBB = open("2016Boosteddefault/MassResolutionVsPt_%s_BB.pkl" %
                         trackType)
    fileORBB = open("2016BoostedWindowLarge/MassResolutionVsPt_%s_BB.pkl" %
                    trackType)
    fileNoBB = open("2016BoostedWindowSmall/MassResolutionVsPt_%s_BB.pkl" %
                    trackType)
    fileDefaultBE = open("2016Boosteddefault/MassResolutionVsPt_%s_BE.pkl" %
                         trackType)
    fileORBE = open("2016BoostedWindowLarge/MassResolutionVsPt_%s_BE.pkl" %
                    trackType)
    fileNoBE = open("2016BoostedWindowSmall/MassResolutionVsPt_%s_BE.pkl" %
                    trackType)

    resultsDefaultBB = pickle.load(fileDefaultBB)
    resultsORBB = pickle.load(fileORBB)
    resultsNoBB = pickle.load(fileNoBB)
    resultsDefaultBE = pickle.load(fileDefaultBE)
    resultsORBE = pickle.load(fileORBE)
    resultsNoBE = pickle.load(fileNoBE)

    graphDefaultBB = getGraph(resultsDefaultBB, "DefaultBB")
    graphORBB = getGraph(resultsORBB, "ORBB")
    graphNoBB = getGraph(resultsNoBB, "NoBB")
    graphDefaultBE = getGraph(resultsDefaultBE, "DefaultBE")
    graphORBE = getGraph(resultsORBE, "ORBE")
    graphNoBE = getGraph(resultsNoBE, "NoBE")

    ratioORBB = getRatio(resultsORBB, resultsDefaultBB, "ratioBBOR")
    ratioNoBB = getRatio(resultsNoBB, resultsDefaultBB, "ratioBBNo")
    ratioORBE = getRatio(resultsORBE, resultsDefaultBE, "ratioBEOR")
    ratioNoBE = getRatio(resultsNoBE, resultsDefaultBE, "ratioBENo")

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
    ratioPad = TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)

    xMax = 6
    if trackType == "Inner":
        xMax = 8
    if trackType == "Outer":
        xMax = 20

    plotPad.DrawFrame(52, 0, 800, xMax,
                      ";p_{T} [GeV]; Z peak resolution [GeV]")

    graphDefaultBB.Draw("samepe")
    graphORBB.Draw("samepe")
    graphNoBB.Draw("samepe")
    graphORBB.SetLineColor(kRed)
    graphORBB.SetMarkerColor(kRed)
    graphNoBB.SetLineColor(kBlue)
    graphNoBB.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BB" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graphDefaultBB, "75-105 GeV", "l")
    leg.AddEntry(graphORBB, "70-110 GeV", "l")
    leg.AddEntry(graphNoBB, "80-100 GeV", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

    ratioORBB.SetLineColor(kRed)
    ratioNoBB.SetLineColor(kBlue)

    ratioPad.DrawFrame(52, 0.5, 800, 1.5, ";;ratio")

    ratioORBB.Draw("samepe")
    ratioNoBB.Draw("samepe")

    canv.Print("massResolutionVsPtWindow2016_%s_BB.pdf" % trackType)

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
    ratioPad = TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)

    xMax = 6
    if trackType == "Inner":
        xMax = 8
    if trackType == "Outer":
        xMax = 20

    plotPad.DrawFrame(52, 0, 452, xMax,
                      ";p_{T} [GeV]; Z peak resolution [GeV]")

    graphDefaultBE.Draw("samepe")
    graphORBE.Draw("samepe")
    graphNoBE.Draw("samepe")
    graphORBE.SetLineColor(kRed)
    graphORBE.SetMarkerColor(kRed)
    graphNoBE.SetLineColor(kBlue)
    graphNoBE.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BE" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graphDefaultBE, "75-105 GeV", "l")
    leg.AddEntry(graphORBE, "70-110 GeV", "l")
    leg.AddEntry(graphNoBE, "80-100 GeV", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

    ratioORBE.SetLineColor(kRed)
    ratioNoBE.SetLineColor(kBlue)

    ratioPad.DrawFrame(52, 0.5, 452, 1.5, ";;ratio")

    ratioORBE.Draw("samepe")
    ratioNoBE.Draw("samepe")

    canv.Print("massResolutionVsPtWindow2016_%s_BE.pdf" % trackType)
Exemple #37
0
def makeMassRes(inputfile, output, funct, trackType, weights):
    style = setTDRStyle()
    ROOT.gStyle.SetTitleYOffset(1.45)
    ROOT.gStyle.SetTitleXOffset(1.45)
    ROOT.gStyle.SetOptFit(0)
    ROOT.gStyle.SetStatX(.9)
    ROOT.gStyle.SetStatY(.9)

    hist_barrel = loadHistos(inputfile, "BB", rebin, trackType, weights)
    hist_other = loadHistos(inputfile, "BE", rebin, trackType, weights)
    resBB = drawMassResGeneric(hist_barrel, output, "BB", funct, trackType)
    resBE = drawMassResGeneric(hist_other, output, "BE", funct, trackType)

    res = ROOT.TCanvas("res", "res", 700, 700)
    res.cd()
    res.SetTickx()
    res.SetTicky()

    resBB.SetMarkerStyle(20)
    resBB.SetMarkerSize(1)
    resBB.SetMarkerColor(ROOT.kRed)
    resBB.SetLineColor(ROOT.kRed)
    resBB.SetFillColor(0)
    resBB.SetTitle("Muon p_{T} resolution vs p_{T}")
    resBB.GetYaxis().SetTitle("Muon p_{T} Resolution")
    #    resBB.GetYaxis().SetTitleOffset(1.5)
    resBB.GetXaxis().SetTitle("p_{T}^{#mu} [GeV]")
    resBB.GetYaxis().SetRangeUser(0, .15)
    resBB.GetXaxis().SetRangeUser(mrange[0], mrange[len(mrange) - 1])
    resBB.GetFunction("fun").SetLineColor(ROOT.kRed + 1)
    resBB.Draw("AP E0")

    resBE.SetMarkerStyle(20)
    resBE.SetMarkerSize(1.0)
    resBE.SetMarkerColor(ROOT.kGreen + 1)
    resBE.SetLineColor(ROOT.kGreen + 1)
    resBE.SetFillColor(0)
    resBE.SetTitle("Muon p_{T} resolution vs p_{T}")
    resBE.GetYaxis().SetTitle("Muon p_{T} Resolution")
    resBE.GetYaxis().SetTitleOffset(1.5)
    #   resBE.GetXaxis().SetTitle("m(#mu^{+}#mu^{-}) [GeV]")
    resBE.GetYaxis().SetRangeUser(0, .15)
    resBE.GetXaxis().SetRangeUser(mrange[0], mrange[len(mrange) - 1])
    resBE.GetFunction("fun").SetLineColor(ROOT.kGreen + 2)
    resBE.Draw("PE0 SAME")

    latexFitBB = ROOT.TLatex()
    latexFitBB.SetTextFont(42)
    latexFitBB.SetTextSize(0.030)
    latexFitBB.SetNDC(True)
    latexFitBB.SetTextColor(ROOT.kRed)

    latexFitBE = ROOT.TLatex()
    latexFitBE.SetTextFont(42)
    latexFitBE.SetTextSize(0.030)
    latexFitBE.SetNDC(True)
    latexFitBE.SetTextColor(ROOT.kGreen + 2)
    latexFitBB.DrawLatex(0.19, 0.78, "BB Category")
    latexFitBE.DrawLatex(0.60, 0.78, "BE+EE Category")
    for par in range(resBB.GetFunction("fun").GetNpar()):
        yPos = 0.74 - 0.04 * (float(par))
        latexFitBB.DrawLatex(
            0.19, yPos, "%s = %5.3g #pm %5.3g" %
            (resBB.GetFunction("fun").GetParName(par),
             resBB.GetFunction("fun").GetParameter(par),
             resBB.GetFunction("fun").GetParError(par)))
        latexFitBE.DrawLatex(
            0.60, yPos, "%s = %5.3g #pm %5.3g" %
            (resBE.GetFunction("fun").GetParName(par),
             resBE.GetFunction("fun").GetParameter(par),
             resBE.GetFunction("fun").GetParError(par)))
    latexFitBB.DrawLatex(
        0.19, 0.54, "#chi^{2}/ndf = %5.1f / %2.0f = %4.2f" %
        (resBB.GetFunction("fun").GetChisquare(),
         resBB.GetFunction("fun").GetNDF(),
         resBB.GetFunction("fun").GetChisquare() /
         resBB.GetFunction("fun").GetNDF()))
    latexFitBE.DrawLatex(
        0.60, 0.54, "#chi^{2}/ndf = %5.1f / %2.0f = %4.2f" %
        (resBE.GetFunction("fun").GetChisquare(),
         resBE.GetFunction("fun").GetNDF(),
         resBE.GetFunction("fun").GetChisquare() /
         resBE.GetFunction("fun").GetNDF()))

    #    leg = ROOT.TLegend(.35,.7,.50,.80,"","brNDC")
    #    leg.AddEntry(resBB,"BB")
    #    leg.AddEntry(resBE,"BE+EE")
    #    leg.SetTextFont(42)
    #    leg.SetBorderSize(0)
    #    leg.SetTextSize(.04)
    #    leg.Draw("SAME")

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "Simulation"  #splitline{Simulation}{Preliminary}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    yLabelPos = 0.84
    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    res.SetGrid()
    saveas = "/PtResolutionVsPt_%s" % trackType
    res.SaveAs(output + saveas + ".png")
    res.SaveAs(output + saveas + ".pdf")
    res.SaveAs(output + saveas + ".root")
    res.SaveAs(output + saveas + ".C")
Exemple #38
0
def main():

    import argparse
    parser = argparse.ArgumentParser(
        usage="makePValuePlot.py [options] -o OUTPUTFILE --card CARD1",
        description="plots pvalue scans for Z' analysis'",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("--card",
                        dest="cards",
                        default=[],
                        action="append",
                        help='add datacard to list of curves to plot')
    parser.add_argument("--smooth",
                        dest="smooth",
                        action="store_true",
                        default=False,
                        help="Smooth observed values")
    parser.add_argument("-c",
                        "--config",
                        dest="config",
                        default='',
                        help="config name")
    parser.add_argument("-t",
                        "--tag",
                        dest="tag",
                        default='',
                        help="limit tag")
    parser.add_argument("--ratioLabel",
                        dest="ratioLabel",
                        default='',
                        help="label for ratio")
    args = parser.parse_args()

    canv = ROOT.TCanvas("c1", "c1", 800, 800)
    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    style = setTDRStyle()
    ROOT.gStyle.SetTitleYOffset(1.15)
    ROOT.gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    plotPad.Draw()
    plotPad.cd()
    plotPad.DrawFrame(200, 5e-4, 3000, 10, ";M [GeV]; local p-Value")
    plotPad.SetLogy()

    leg = ROOT.TLegend(0.52, 0.751, 0.89, 0.92, "", "brNDC")
    leg.SetFillColor(10)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)

    graphs = []

    for index, card in enumerate(args.cards):
        if 'width' in card:
            width = "signif" + card.split('width')[-1].split('_')[0]
        else:
            width = 'signif'

        masses, pValues = getPValues(card)
        graphs.append(
            ROOT.TGraph(len(masses), numpy.array(masses),
                        numpy.array(pValues)))
        label = card.split("_")[-1].split(".")[0]
        if args.smooth:
            smoother = ROOT.TGraphSmooth("normal")
            graphs[index] = deepcopy(
                smoother.SmoothSuper(graphs[index], "linear", 0, 0.005))

        graphs[index].SetLineColor(lineColors[width])
        graphs[index].SetLineStyle(lineStyles[width])
        leg.AddEntry(graphs[index], labels[width], "l")
        graphs[index].Draw("Lsame")
        graphs[index].SetLineWidth(2)

    leg.Draw()

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.03)
    latex.SetNDC(True)
    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    configName = "scanConfiguration_%s" % args.config

    config = __import__(configName)
    chan = config.leptons

    if chan == "elmu":
        latex.DrawLatex(
            0.95, 0.96,
            "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu )")
    elif chan == "elel":
        latex.DrawLatex(0.95, 0.96, "35.9 fb^{-1} (13 TeV, ee)")
    elif chan == "mumu":
        latex.DrawLatex(0.95, 0.96, "36.3 fb^{-1} (13 TeV, #mu#mu )")

    cmsExtra = "Preliminary"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    ZeroSigmaLine = ROOT.TLine(200, 0.5, 3000, 0.5)
    ZeroSigmaLine.SetLineStyle(ROOT.kDashed)
    ZeroSigmaLine.Draw("same")

    OneSigmaLine = ROOT.TLine(200, 0.317 / 2, 3000, 0.317 / 2)
    OneSigmaLine.SetLineStyle(ROOT.kDashed)
    OneSigmaLine.Draw("same")

    TwoSigmaLine = ROOT.TLine(200, 0.0455 / 2, 3000, 0.0455 / 2)
    TwoSigmaLine.SetLineStyle(ROOT.kDashed)
    TwoSigmaLine.Draw("same")

    ThreeSigmaLine = ROOT.TLine(200, 0.0027 / 2, 3000, 0.0027 / 2)
    ThreeSigmaLine.SetLineStyle(ROOT.kDashed)
    ThreeSigmaLine.Draw("same")

    FourSigmaLine = ROOT.TLine(200, 0.00006 / 2, 3000, 0.00006 / 2)
    FourSigmaLine.SetLineStyle(ROOT.kDashed)
    #~ FourSigmaLine.Draw("same")

    FiveSigmaLine = ROOT.TLine(200, 3e-07, 3000, 3e-07)
    FiveSigmaLine.SetLineStyle(ROOT.kDashed)
    #~ FiveSigmaLine.Draw("same")

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    #~ latex.SetNDC(True)
    latex.DrawLatex(3150, 0.5, "0#sigma")
    latex.DrawLatex(3150, 0.317 / 2, "1#sigma")
    latex.DrawLatex(3150, 0.0455 / 2, "2#sigma")
    latex.DrawLatex(3150, 0.0027 / 2, "3#sigma")
    #~ latex.DrawLatex(4200, 0.00006/2, "4#sigma")
    #~ latex.DrawLatex(4200, 3e-7, "5#sigma")

    #~ ROOT.gPad.WaitPrimitive()
    name = "pValues_%s_%s" % (args.config, args.tag)
    if args.smooth:
        name += "_smoothed"
    name = name + ".pdf"
    canv.Print("plots/" + name)
Exemple #39
0
               "unfolded/gen")
        plotData(self.unfoldedData, self.data_kFac, True, "kFac/w", "kFac/o",
                 category + " di" + flavor,
                 "reM_v1/kFac_data_" + flavor + "_" + category + "_" + year,
                 "w/o kFac ratio")
        plotData(self.unfoldedData, self.data, True, "unfolded", "original",
                 category + " di" + flavor,
                 "reM_v1/ratio_data_" + flavor + "_" + category + "_" + year,
                 "after/before")


ROOT.TH1.AddDirectory(0)
ROOT.TH2.AddDirectory(0)
ROOT.gStyle.SetOptStat(0)
ROOT.gStyle.SetPadRightMargin(0.2)
setTDRStyle()
result2016_mu_bb = unfoldedResult("2016", "muon", "bb")
result2016_mu_be = unfoldedResult("2016", "muon", "be")
result2016_el_bb = unfoldedResult("2016", "electron", "bb")
result2016_el_be = unfoldedResult("2016", "electron", "be")
result2017_mu_bb = unfoldedResult("2017", "muon", "bb")
result2017_mu_be = unfoldedResult("2017", "muon", "be")
result2017_el_bb = unfoldedResult("2017", "electron", "bb")
result2017_el_be = unfoldedResult("2017", "electron", "be")
result2018_mu_bb = unfoldedResult("2018", "muon", "bb")
result2018_mu_be = unfoldedResult("2018", "muon", "be")
result2018_el_bb = unfoldedResult("2018", "electron", "bb")
result2018_el_be = unfoldedResult("2018", "electron", "be")

unfoldedData_mu_bb = result2016_mu_bb.unfoldedData.Clone()
unfoldedData_mu_bb.Add(result2017_mu_bb.unfoldedData.Clone())
File: TriggerEfficiency.py
Author: Alejandro Gomez Espinosa
Email: [email protected]
Description: Calculate the Trigger Efficiency
'''

import sys,os,time
import optparse
from collections import defaultdict
from ROOT import *
from setTDRStyle import setTDRStyle
from DataFormats.FWLite import Events, Handle

gROOT.SetBatch()
gROOT.Reset()
setTDRStyle()
gROOT.ForceStyle()
gROOT.SetStyle('tdrStyle')


###### Trick for add date or month to plots
dateKey   = time.strftime("%y%m%d%H%M")
monthKey   = time.strftime("%y%m%d")


################################################################################# Calculate Efficiency
def CalculateEff( inputFile, outputDir, sample, jetAlgo, grooming, weight, FNAL ):
	"""docstring for CalculateEff"""

	#outputFileName = monthKey+'_'+sample+'_TriggerEfficiency_'+jetAlgo+'.pdf'  
	outputFileName = monthKey+'_'+sample+'_TriggerEfficiency_'+jetAlgo+'_HT350.pdf'  
Exemple #41
0
def makePlots(inputfiles,draw,title,legends,outname):
    style = setTDRStyle()
    ROOT.gStyle.SetTitleYOffset(1.45)
    ROOT.gStyle.SetTitleXOffset(1.45)
    ROOT.gStyle.SetOptFit(0)
    ROOT.gStyle.SetStatX(.9)
    ROOT.gStyle.SetStatY(.9)

    c1 = ROOT.TCanvas('c1')
    
    _files=[]
    for i in inputfiles:
        print "Opening %s..." %(i)
        _files.append(ROOT.TFile(i))
        

    _hists=[]
    _hist = ROOT.TH1F()
    _hist.SetDirectory(0)

    if logY: outname+="_log"
    
    o = open(outname+'.txt', 'w')
    for i,f in enumerate(_files):
        for k,p in enumerate(draw):
            histname = "%s" %(p)
            _hist = f.Get(histname).Clone()
            _hist.SetDirectory(0)
            _hists.append(_hist)
            if "Eff" in p:
                o.write('%s \t %5.4f + %5.4f - %5.4f\n' %(legends[i],_hist.GetEfficiency(1),_hist.GetEfficiencyErrorLow(1),_hist.GetEfficiencyErrorUp(1)))            
    o.close()
 
    leg = ROOT.TLegend(0.30,0.15,0.70,0.3);
#    leg = ROOT.TLegend(0.55,0.65,0.90,0.80);
    leg.SetLineColor(0);
    leg.SetFillStyle(0);
    leg.SetBorderSize(0)
    
    k=0
    for hist in _hists:
        if "h_" in draw[0]:
            hist.Scale(1./hist.GetEntries())
        hist.SetLineWidth(2)
        hist.SetLineColor(k+1)
        hist.SetTitle(title)
        
        if k==0 :
            if logY: c1.SetLogy()
            if logX: c1.SetLogx()
            if "Vs" in draw[0]:
                hist.Draw("BOX")
            else: 
                hist.Draw("")
            
            if "h_" not in draw[0]:
                ROOT.gPad.Update()
                graph = hist.GetPaintedGraph()
                graph.SetMinimum(YMIN)
                graph.SetMaximum(YMAX)
                ROOT.gPad.Update()
        else:
            hist.Draw("SAME")

        leg.AddEntry(hist,legends[k],"l")
        k+=1
    
    if len(_hists)>1:
        leg.Draw("SAME")

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)    
    latex.DrawLatex(0.95, 0.96, "(13 TeV)")
    
    cmsExtra = "Private" 
    latexCMS.DrawLatex(0.78,0.88,"CMS")
    yLabelPos = 0.84
    latexCMSExtra.DrawLatex(0.78,yLabelPos,"%s"%(cmsExtra))
    
    c1.SaveAs(outname+".root");
    c1.SaveAs(outname+".pdf");
    c1.SaveAs(outname+".png");