Beispiel #1
0
class vmagnet(object):
    #_____________________________________________________________________________
    def __init__(self):
        #set magnet from configuration dictionary
        self.name = ""
        self.center_z = 0.
        self.center_x = 0.
        self.length = 0.
        self.rad1 = 0.
        self.rad2 = 0.
        self.field = 0.
        #electron or hadron
        self.is_electron = True
        #initial angle
        self.theta_0 = 0.
        #parameters from MAD-X survey
        self.S = 0.
        self.L = 0.
        self.X = 0.
        self.Z = 0.
        self.THETA = 0.
        self.has_survey = False
        #drawing configuration
        self.fill_style = 1000
        self.label_down = False
        self.label = ""
        self.no_label = False
        self.line_col = rt.kBlue
        self.fill_col = rt.kGreen - 2

    #_____________________________________________________________________________
    def read_survey(self, lin):
        #values from MAD-X survey

        self.S = float(lin["S"])
        self.L = float(lin["L"])
        self.X = float(lin["X"])
        self.Z = float(lin["Z"])
        self.THETA = float(lin["THETA"]) + self.theta_0
        self.has_survey = True

    #_____________________________________________________________________________
    def rotate_translateX(self, theta, xt):

        #combined rotation and translation
        self.rotate(theta)
        self.translateX(xt)

    #_____________________________________________________________________________
    def translateX(self, xt):

        #translate the magnet along x

        self.center_x += xt

    #_____________________________________________________________________________
    def rotate(self, theta):
        #rotate by angle theta about the origin

        #get new center_z and center_x by TVector2 rotation
        vec = TVector2(self.center_z, self.center_x).Rotate(theta)
        self.center_z = vec.X()
        self.center_x = vec.Y()

        #rotate along magnet center
        self.THETA = self.THETA - theta

    #_____________________________________________________________________________
    def draw_2d(self):

        #draw only magnets with survey defined
        if not self.has_survey: return

        #self.draw_box()
        self.draw_graph()

    #_____________________________________________________________________________
    def draw_graph(self):

        #inner and outer radius
        if self.center_z < 0:
            rad_right = self.rad1
            rad_left = self.rad2
        else:
            rad_right = self.rad2
            rad_left = self.rad1

        #edge points of the magnet
        vec = []
        vec.append(TVector2(self.length / 2, rad_right))
        vec.append(TVector2(self.length / 2, -rad_right))
        vec.append(TVector2(-self.length / 2, -rad_left))
        vec.append(TVector2(-self.length / 2, rad_left))

        #rotate along magnet axis and move to magnet center
        vpos = TVector2(self.center_z, self.center_x)
        for i in xrange(len(vec)):
            vec[i] = vec[i].Rotate(-self.THETA) + vpos

        #export points to the graph
        self.gbox = TGraph(len(vec) + 1)
        self.gbox.SetLineColor(self.line_col)
        self.gbox.SetLineWidth(2)
        self.gbox.SetFillStyle(self.fill_style)
        self.gbox.SetFillColor(self.fill_col)

        for i in xrange(len(vec)):
            self.gbox.SetPoint(i, vec[i].X(), 100 * vec[i].Y())

        #last point same as the first
        self.gbox.SetPoint(len(vec), vec[0].X(), 100 * vec[0].Y())

        self.gbox.Draw("lfsame")

        #label
        if self.no_label: return
        #lx = (self.center_x + self.rad2)*100 + 4
        lx = (self.center_x + (self.rad1 + self.rad2) / 2) * 100 + 4
        if lx < 30: lx = 30
        align = 12
        #left down
        if (self.center_z < 0 and not self.is_electron) or self.label_down:
            lx = (self.center_x - self.rad2) * 100 - 4
            align = 32
        #right down
        if self.center_z > 0 and self.is_electron:
            lx = (self.center_x - self.rad2) * 100 - 4
            if lx > -25: lx = -25
            align = 32
            #label above the magnet
            if self.center_x < -0.4:
                lx = (self.center_x + self.rad2) * 100 + 4
                align = 12
        if self.label == "":
            self.label = self.name
        #self.glabel = TText(self.center_z, lx, self.label)
        self.glabel = TLatex(self.center_z, lx, self.label)
        self.glabel.SetTextSize(0.03)
        #self.glabel.SetTextSize(0.02)
        self.glabel.SetTextAngle(90)
        self.glabel.SetTextAlign(align)
        self.glabel.Draw("same")

    #_____________________________________________________________________________
    def draw_box(self):

        z1 = self.center_z - self.length / 2
        z2 = z1 + self.length
        x1 = self.center_x - self.rad2
        x2 = x1 + 2 * self.rad2

        #to cm
        x1 *= 100
        x2 *= 100

        #representation as a box
        self.box = TFrame(z1, x1, z2, x2)
        self.box.SetBorderMode(0)
        self.box.SetFillColor(rt.kGray + 1)
        col = rt.kRed
        if self.is_electron == True: col = rt.kBlue
        self.box.SetLineColor(col)
        self.box.SetLineWidth(2)
        #self.box.Draw("same")

        #label
        lx = x2 + 2
        align = 11
        if lx < 0 and lx > -62:
            lx = x1 - 5  # negative lx
            align = 31
        if self.center_z < 0 and self.center_x < 0.1:
            lx = x1 - 2  # negative z and x
            align = 31
        if lx > 0 and lx < 22: lx = 22  # small positive lx
        self.label = TText(z2, lx, self.name)
        self.label.SetTextSize(0.03)
        self.label.SetTextAngle(90)
        self.label.SetTextAlign(align)
Beispiel #2
0
gStyle.SetFrameLineWidth(3)
gStyle.SetOptTitle(1)
gStyle.SetOptStat(0)
gStyle.SetFillColor(2)
gStyle.SetLineWidth(1)
gStyle.SetPadColor(1)

#legend=TLegend(.63,.69,.87,.89,"","#gamma #gamma")
#legend=TLegend(0.57, 0.5, 0.94,0.65,"","b b~")

c = TCanvas("c", "First canvas", 2000, 1900)

cmsname = TLatex(0.15, 1.85, "Trials")
#cmsname=TLatex(0.15,1.85,"CMS #it{#bf{Preliminary}}")
cmsname.SetTextSize(0.036)
cmsname.SetTextAlign(12)
cmsname.SetNDC(1)
cmsname.SetTextFont(61)
#lhefdata=LHEFData(float(root.attrib['version']))
#lhefdata=LHEFData(float(root.attrib['version']))
for child in root1:
    if (child.tag == 'event'):
        lines = child.text.strip().split('\n')
        event_header = lines[0].strip()
        num_part = int(event_header.split()[0].strip())

        a1_1 = [s for s in lines if s.split()[0] == '22']
        a1 = a1_1[1::2]
        a2 = a1_1[0::2]
        b1 = [s for s in lines if s.split()[0] == '5']
Beispiel #3
0
def drawHist(hist, confL, name, colz=True, contour=False, dec=False):

    can = TCanvas()
    can.cd()

    if (dec):
        gStyle.SetPaintTextFormat("3.2f")
    else:
        gStyle.SetPaintTextFormat("3.0f")

    if "metOmeff" in hist.GetName():
        gStyle.SetPaintTextFormat("3.2f")

    gStyle.SetStatX(50)
    #colors = array("i",[3,30, 40, 20, 46, 5, 6, 7, 8, 9,11,4]) #colors >= #levels - 1
    #gStyle.SetPalette(len(colors), colors)
    #levels = array("d",[.01, .20, 0.50, 1, 2, 3, 4, 7,9,10])
    #hist.SetContour(len(levels), levels)
    hist.SetMarkerSize(1.5)
    if colz:
        hist.Draw("colz,same")

    hist.Draw("text30, same")

    if SigSample == "GG_ttn1":
        xlabel = 850
        ylabel = 1400
    elif SigSample == "GG_2stepWZ":
        xlabel = 600
        ylabel = 1400
    elif SigSample == "GG_SLN1":
        xlabel = 400
        ylabel = 1000
    elif SigSample == "BB_onestepC1":
        xlabel = 350
        ylabel = 300

    xlabel = 650
    ylabel = 1500

    if contour:
        g = TGraph2D()
        TH2toTGraph2D(hist, g)
        Ghisto = g.GetHistogram()
        level = array('d', [1.64, 3])
        Ghisto.SetLineWidth(4)
        Ghisto.SetContour(2, level)
        Ghisto.Draw("cont1,list ,same")
        #        confL.SetLineColor(1)
        #        confL.Draw("colz,same")
        tex1 = TLatex()
        if SigSample == "BB_onestepC1":
            tex1.DrawLatex(xlabel, ylabel + 50, "#color[3]{1.64#sigma}")
        else:
            tex1.DrawLatex(xlabel, ylabel + 100, "#color[3]{1.64#sigma}")
        tex1.DrawLatex(xlabel, ylabel, "#color[2]{3#sigma}")

        #sprintf(&title[0],"MET>%d GeV",met);
        #myText(.2,.84,kBlue,title);

        #sprintf(&title[0],"MEFF>%d GeV",meff);
        #myText(.2,.79,kBlue,title);

        #sprintf(&title[0],"Bkg: %3.1f evts",_bkg);
        #myText(.2,.74,kBlue,title);

        #        myLineText(.26, .8 , 0.05, kGreen,"1.64#sigma")
        #        myLineText(.26, .75, 0.05, kRed,  "3#sigma")

    hist.GetYaxis().SetTitleOffset(1.3)
    hist.GetXaxis().SetTitle("Gluino Mass (GeV)")
    hist.GetYaxis().SetTitle("Neutralino Mass (GeV)")
    gStyle.SetTitleX(100.0)  # move title off plot
    gStyle.SetTitleW(0.0)  # title width =0

    tex2 = TLatex()
    if SigSample == "BB_onestepC1":
        tex2.DrawLatex(
            xlabel, ylabel + 100,
            name + " " + str(luminosity) + " fb^{-1}: " + hist.GetName())
    else:
        tex2.DrawLatex(
            xlabel, ylabel + 200,
            name + " " + str(luminosity) + " fb^{-1}: " + hist.GetName())

    # Draw m_gl - m_N1 = 2 (m_W+m_b)
    line = TLine(600, 429.6, 1800, 1629.6)
    line.SetLineColor(16)
    line.SetLineStyle(7)
    line.Draw("same")
    th1 = TLatex(
        1450, 1340,
        "m_{#tilde{g}} - m_{#tilde{#chi}_{1}^{0}} = 2 #left(m_{W}+m_{b}#right)"
    )
    th1.SetTextAngle(30)
    th1.SetTextColor(16)
    th1.SetTextSize(0.03)
    th1.Draw("same")

    # Draw m_gl - m_N1 = 2 m_t
    line2 = TLine(600, 255, 2050, 1680)
    line2.SetLineColor(16)
    line2.SetLineStyle(7)
    line2.Draw("same")
    th2 = TLatex(1550, 1240,
                 "m_{#tilde{g}} - m_{#tilde{#chi}_{1}^{0}} = 2 m_{t}")
    th2.SetTextAngle(30)
    th2.SetTextColor(16)
    th2.SetTextSize(0.03)
    #    th2.Draw("same")

    if "Dm" in hist.GetName():
        line3 = TLine(600, 25, 2100, 25)
        line3.SetLineColor(16)
        line3.SetLineStyle(7)
        line3.Draw("same")
        th3 = TLatex(
            1600, 40,
            "#Delta m = m_{#tilde{#chi}_{1}^{0}} - #left(m_{#tilde{g}} -2 m_{t} #right)"
        )
        #        th3.SetTextAngle(32)
        th3.SetTextColor(16)
        th3.SetTextSize(0.03)
        th3.Draw("same")
        hist.GetYaxis().SetTitle(
            "#Delta m_{#tilde{#chi}_{1}^{0}} (above diagonal) (GeV)")
    can.Update()
    directory = "/afs/cern.ch/user/o/othrif/workarea/results/v48/Plots/" + Dirbase  #+"/Lumi"+str(luminosity)
    if not os.path.exists(directory):
        os.makedirs(directory)
    can.SaveAs(directory + "/" + name + "_" + hist.GetName() + ".pdf")
Beispiel #4
0
def analysis(
    hadron="Lambda_c",
    collision="pp14p0",
    yrange="absy3p0",
    brmode="central",
    model="Pyhia8mode2",
    use_unnorm=1,
):
    gStyle.SetOptStat(0)
    with open(r"databases/significance.yaml") as filesignificance:
        paramsignificance = yaml.safe_load(filesignificance)
    ymin = paramsignificance[hadron][collision][yrange]["ymin"]
    ymax = paramsignificance[hadron][collision][yrange]["ymax"]
    # bin of the final analysis, has to be the binning of efficiency, bkg histos
    binanal = array("d",
                    paramsignificance[hadron][collision][yrange]["binning"])
    nfileyieldth = paramsignificance[hadron][collision][yrange]["theoryfile"]

    nfileeff = paramsignificance[hadron][collision][yrange]["efffile"]
    nhistoeff = paramsignificance[hadron][collision][yrange]["histoeff"]
    nfilebkg = paramsignificance[hadron][collision][yrange]["bkgfile"]
    nhistobkg = paramsignificance[hadron][collision][yrange]["histobkg"]
    nhistoyieldth = paramsignificance[hadron][collision][yrange]["histoyield"]
    nhistoyieldth_norm = paramsignificance[hadron][collision][yrange][
        "histoyield_norm"]

    with open(r"databases/general.yaml") as fileparamgen:
        paramgen = yaml.safe_load(fileparamgen)
    with open(r"databases/theory_yields.yaml") as fileyields:
        paramyields = yaml.safe_load(fileyields)

    textcollision = paramgen["text_string"][collision]
    textrapid = paramgen["text_string"][yrange]
    textmodel = paramgen["text_string"][model]

    sigma_aa_b = paramgen["statistics"][collision]["sigmaAA_b"]
    lumiaa_monthi_invnb = paramgen["statistics"][collision][
        "lumiAA_monthi_invnb"]
    nevt = sigma_aa_b * lumiaa_monthi_invnb * 1e9
    # nevt = 2.*1e9
    bratio = paramgen["branchingratio"][hadron][brmode]
    decaychannel = paramgen["latexparticle"][hadron]

    if hadron == "Chi_c" and yrange == "absy1p44":
        bratio *= 0.8  # chi_c1 and chi_c2 are measured together: non-weighted average of their BRs
        decaychannel = "#chi_{c} #rightarrow J/#psi #gamma"

    yieldmid = paramyields[model][collision][yrange][hadron]
    text = "%s, N_{ev} = %f 10^{9}" % (textmodel, (float)(nevt) / 1.0e9)
    text_a = "%s, %s, BR=%.2f%%" % (decaychannel, textrapid, bratio * 100)
    text_b = "ALICE3 projection, with IRIS, no PID, %s" % textcollision
    fileeff = TFile(nfileeff)
    histoeff = fileeff.Get(nhistoeff)
    filebkg = TFile(nfilebkg)
    hbkgperevent = filebkg.Get(nhistobkg)

    fileyieldth = TFile(nfileyieldth)
    histoyieldth = None

    if use_unnorm == 1:
        histodndptth = fileyieldth.Get(nhistoyieldth)
        histodndptth.Scale(
            1.0 / 70000.0)  # TEMPORARY this is a fix to account for the
        # conversion from a cross-section in mub
        # to yields, sigma=70000 mub
    else:
        histodndptth = fileyieldth.Get(nhistoyieldth_norm)
        integral = 0
        for ibin in range(histodndptth.GetNbinsX()):
            binwdith = histodndptth.GetBinWidth(ibin + 1)
            integral += histodndptth.GetBinContent(ibin + 1) * binwdith
        histodndptth.Scale(1.0 / integral)
        histodndptth.Scale(yieldmid)
        print("yieldmid = %f\n", yieldmid)
        integral = 0
        for ibin in range(histodndptth.GetNbinsX()):
            binwdith = histodndptth.GetBinWidth(ibin + 1)
            integral += histodndptth.GetBinContent(ibin + 1) * binwdith
        print("yieldmid = %f\n", yieldmid)

    if hadron == "Chi_c" and collision == "pp14p0":
        print("scaling signal yield by 0.1")
        histodndptth.Scale(0.1)  # because pythia8 is wrong by a factor ~10

    if hadron == "Chi_c" and yrange == "absy1p44":
        print("scaling bkg by 2*2, and signal by 3.4")
        hbkgperevent.Scale(
            2
        )  # to take approximately into account the worsening of the sig/bkg in the full
        # rapidity range (PbWO4 and W+Sci)
        hbkgperevent.Scale(
            2
        )  # because in |y| < 1.44 we sum chi_c1 and chi_c2 (states are not resolved)
        histodndptth.Scale(
            3.4
        )  # because in |y| < 1.44 we sum chi_c1 and chi_c2 (states are not resolved).
        # Assuming chi_c2/chi_c1 (!!) from Pythia8

    if hadron == "Chi_c" and yrange == "absy0p33":
        print("scaling signal and bkg by 0.23, from |y| < 1.44 to |y| < 0.33")
        hbkgperevent.Scale(
            0.23
        )  # to take into account the reduction of the statistics from |y| < 1.44 to |y| < 0.33
        # (the input file for chi_c is always |y| < 1.44)
        histodndptth.Scale(
            0.23
        )  # to take into account the reduction of the statistics from |y| < 1.44 to |y| < 0.33
        # (the input file for chi_c is always |y| < 1.44)

    histoyieldth = histodndptth.Clone("histoyieldth")

    for ibin in range(histoyieldth.GetNbinsX()):
        binwdith = histoyieldth.GetBinWidth(ibin + 1)
        yieldperevent = histoyieldth.GetBinContent(ibin +
                                                   1) * binwdith * bratio
        histoyieldth.SetBinContent(ibin + 1, yieldperevent)
        histoyieldth.SetBinError(ibin + 1, 0.0)
    histoyieldth = histoyieldth.Rebin(
        len(binanal) - 1, "histoyieldth", binanal)
    histosignfperevent = histoyieldth.Clone("histosignfperevent")
    histosignf = histoyieldth.Clone("histosignf")
    histosigoverbkg = histoyieldth.Clone("histosigoverbkg")

    canvas = TCanvas("canvas", "A Simple Graph Example", 881, 176, 668, 616)
    gStyle.SetOptStat(0)
    canvas.SetHighLightColor(2)
    canvas.Range(-1.25, -4.625, 11.25, 11.625)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetBorderSize(2)
    canvas.SetLogy()
    canvas.SetFrameBorderMode(0)
    canvas.SetFrameBorderMode(0)
    canvas.cd()
    gPad.SetLogy()

    hempty = TH2F(
        "hempty",
        ";p_{T} (GeV/c); Significance(3#sigma)",
        100,
        0.0,
        10.0,
        100,
        ymin,
        ymax,
    )
    hempty.GetXaxis().SetTitle("p_{T} (GeV/c)")
    hempty.GetXaxis().SetLabelFont(42)
    hempty.GetXaxis().SetTitleOffset(1)
    hempty.GetXaxis().SetTitleFont(42)
    hempty.GetYaxis().SetLabelFont(42)
    hempty.GetYaxis().SetTitleOffset(1.35)
    hempty.GetYaxis().SetTitleFont(42)
    hempty.GetZaxis().SetLabelFont(42)
    hempty.GetZaxis().SetTitleOffset(1)
    hempty.GetZaxis().SetTitleFont(42)
    hempty.Draw()

    histosignf = histosignfperevent.Clone("histosignf")
    for ibin in range(histoyieldth.GetNbinsX()):
        yieldperevent = histoyieldth.GetBinContent(ibin + 1)
        bkgperevent = hbkgperevent.GetBinContent(ibin + 1)
        eff = histoeff.GetBinContent(ibin + 1)
        signalperevent = eff * yieldperevent
        significanceperevent = 0
        if bkgperevent > 0:
            significanceperevent = signalperevent / sqrt(signalperevent +
                                                         bkgperevent)
        signaloverbkg = 0
        if bkgperevent > 0:
            signaloverbkg = signalperevent / bkgperevent
        histosignfperevent.SetBinContent(ibin + 1, significanceperevent)
        histosignfperevent.SetBinError(ibin + 1, 0.0)
        histosignf.SetBinContent(ibin + 1, significanceperevent * sqrt(nevt))
        histosignf.SetBinError(ibin + 1, 0.0)
        histosigoverbkg.SetBinContent(ibin + 1, signaloverbkg)
        histosigoverbkg.SetBinError(ibin + 1, 0.0)

    histosignfperevent.SetLineColor(1)
    histosignfperevent.SetMarkerColor(1)
    histosignfperevent.SetLineWidth(1)
    histosignf.SetLineColor(1)
    histosignf.SetMarkerColor(1)
    histosignf.SetLineWidth(2)
    histosignf.Draw("same")
    t_b = TLatex()
    t_b.SetNDC()
    t_b.SetTextFont(42)
    t_b.SetTextColor(1)
    t_b.SetTextSize(0.035)
    t_b.SetTextAlign(12)
    t_b.DrawLatex(0.2, 0.85, text_b)
    t_c = TLatex()
    t_c.SetNDC()
    t_c.SetTextFont(42)
    t_c.SetTextColor(1)
    t_c.SetTextSize(0.03)
    t_c.SetTextAlign(12)
    t_c.DrawLatex(0.2, 0.80, text)
    t_a = TLatex()
    t_a.SetNDC()
    t_a.SetTextFont(42)
    t_a.SetTextColor(1)
    t_a.SetTextSize(0.035)
    t_a.SetTextAlign(12)
    t_a.DrawLatex(0.2, 0.75, text_a)
    canvas.SaveAs(hadron + "_" + collision + "_" + yrange + "_results.pdf")
    canvas.SaveAs(hadron + "_" + collision + "_" + yrange + "_results.C")

    foutput = TFile(
        "foutput" + hadron + "_" + collision + "_" + yrange + ".root",
        "recreate")
    foutput.cd()
    histoeff.Write()
    hbkgperevent.Write()
    histosignfperevent.Write()
    histoyieldth.Write()
    histosignf.Write()
    histodndptth.Write()
    histosigoverbkg.Write()
Beispiel #5
0
def myText(x, y, color=1, size=0.08, text=""):
    l = TLatex()
    l.SetTextSize(size)
    l.SetNDC()
    l.SetTextColor(color)
    l.DrawLatex(x, y, text)
Beispiel #6
0
    
    can = TCanvas('can', 'can', 1100, 800)

    plot_phase_space(can, histos,
                     keyword='isr',
                     output_prefix=args.output_prefix)
    plot_phase_space(can, histos,
                     keyword='elastic',
                     output_prefix=args.output_prefix)

    # -----------------------------------------------------------
    # Plot W
    # -----------------------------------------------------------
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.045)
    
    can.Divide(2,2)

    can.cd(1)
    color_draw(histos['data']['histos_w_inclusive_'], kGray, "")
    color_draw(histos['data']['histos_w_CTOF'], kBlue, "same")
    color_draw(histos['data']['histos_w_pass_angle_CTOF'], kRed, "same")
    latex.DrawLatex(0.45, 0.02, 'W (GeV/c^{2})')
    latex.DrawLatex(0.3, 0.95, 'Data w/ Proton in CTOF')
    latex.SetTextColor(kBlue)
    latex.DrawLatex(0.15, 0.85, 'w/ proton')
    latex.SetTextColor(kRed)
    latex.DrawLatex(0.15, 0.80, 'w/ #Delta #phi cut')
    latex.SetTextColor(kBlack)
    
Beispiel #7
0
def plot_all_components(workdir, root_file_path, info_file, lumi):

    import pandas as pd
    import os

    histo_names = {
        'all': 'gg_zh1_all_{}_generator-level',
        'SM_only': 'gg_zh1_SM_only_{}_generator-level',
        'A_only': 'gg_zh1_A_only_{}_generator-level',
        'qq': 'qq_zh1_{}_generator-level'
    }

    labels = {
        'all': 'gg - all',
        'SM_only': 'gg - SM only.',
        'A_only': 'gg - A only',
        'qq': 'qq'
    }

    types = {
        'mZh': {
            'xlabel': 'm_{inv}(Zh) [GeV]',
            'name': 'mZh'
        },
        'h_pt': {
            'xlabel': 'p_{T}(h) [GeV]',
            'name': 'h_Pt'
        },
        'Z_pt': {
            'xlabel': 'p_{T}(Z) [GeV]',
            'name': 'Z_Pt'
        }
    }

    info = pd.read_csv(info_file, delim_whitespace=True)

    info['xsec_gg_Zh_qq'] = 0.74829 * info['sinba'] * info['sinba']

    info['xsec_gg_Zh_all'] = info['xsec_gg_Zh_all'] * 2.0
    info['xsec_gg_Zh_SM_only'] = info['xsec_gg_Zh_SM_only'] * 2.0
    info['xsec_gg_Zh_A_only'] = info['xsec_gg_Zh_A_only'] * 2.0

    w = {'all': None, 'SM_only': None, 'A_only': None, 'qq': None}
    th = {'all': None, 'SM_only': None, 'A_only': None, 'qq': None}

    tf = TFile(root_file)

    for type in types.keys():

        for component in histo_names.keys():

            th[component] = tf.Get(histo_names[component].format(type))
            xsec = info['xsec_gg_Zh_{}'.format(component)]
            w = get_weight_to_xsec(
                xsec * 1000, 10000)  # xsec * 1000 to convert from pb to fb
            th[component].Scale(w, "width")
            th[component].SetLineColor(style_color[component])
            th[component].SetMarkerColor(style_color[component])
            th[component].SetLineWidth(line_width)
            print('\nw[key]:', w)

        # - Plotting
        c = TCanvas('canvas', 'canvas', 800, 600)

        th['qq'].GetXaxis().SetTitle(types[type]['xlabel'])
        th['qq'].GetYaxis().SetTitle('d#sigma/dm_{Zh^{0}}  [fb/bin]')

        #th['all'].GetXaxis().SetRangeUser(200,1000)
        #th['all'].GetYaxis().SetRangeUser(0.0006,20)
        #h_all.GetYaxis().SetRangeUser(200,1000)

        gPad.SetLeftMargin(0.14)
        gPad.SetBottomMargin(0.15)

        label_posx, label_posy = 0.63, 0.6
        text1 = "2HDM Type-II"
        text2 = "m_{{A}}={:.0f} GeV #Gamma_{{A}}={:.3f} GeV".format(
            info.mA[0], info.Gamma_A[0])
        text3 = "cos(#beta-#alpha)={:.2f}  tan(#beta)={:.2f}".format(
            info.cba[0], info.tb[0])
        text_vshift = 0.06
        label1 = TLatex(label_posx, label_posy, text1)
        label1.SetNDC(True)
        label1.SetTextSize(text_size)
        label2 = TLatex(label_posx, label_posy - text_vshift, text2)
        label2.SetNDC(True)
        label2.SetTextSize(text_size)
        label3 = TLatex(label_posx, label_posy - 2.0 * text_vshift, text3)
        label3.SetNDC(True)
        label3.SetTextSize(text_size)

        legend = TLegend(
            0.65,
            0.70,
            0.85,
            0.82,
        )
        legend.SetTextSize(0.035)

        for key in histo_names.keys():
            legend.AddEntry(th[key], labels[key])

        ############################
        ## --- Linear plot

        c.SetLogy(0)
        #th['all'].GetYaxis().SetRangeUser(0.0006,3.5)

        th['qq'].Draw("SAME hist")
        th['all'].Draw("SAME hist")
        th['SM_only'].Draw("SAME hist")
        th['A_only'].Draw("SAME hist")

        #h_A_only.Draw("SAME")

        label1.Draw("SAME")
        label2.Draw("SAME")
        label3.Draw("SAME")
        legend.Draw("SAME")

        c.SaveAs(
            os.path.join(workdir, '{}_lin.pdf'.format(types[type]['name'])))

        ############################
        ## --- Log plot

        c.Clear()
        c.SetLogy()

        th['qq'].Draw("hist")
        th['all'].Draw("SAME hist")
        th['SM_only'].Draw("SAME hist")
        th['A_only'].Draw("SAME hist")

        label1.Draw("SAME")
        label2.Draw("SAME")
        label3.Draw("SAME")
        legend.Draw("SAME")

        c.SaveAs(
            os.path.join(workdir, '{}_log.pdf'.format(types[type]['name'])))
Beispiel #8
0
h_neutron_long_trans.Draw("colz")

# Eur Phys J (2013) neutron-carbon invariant cross section measurements with pT, xF bins. (NA49, thin target, @158 GeV,  so with tgptype particle)

line1 = TLine(0.05, 0, 1, 0)
line2 = TLine(1, 0, 1, 2.4)
line3 = TLine(1, 2.4, 0.475, 2.4)
line4 = TLine(0.475, 2.4, 0.05, 0.6)
line5 = TLine(0.05, 0.6, 0.05, 0)

lineVector = [line1, line2, line3, line4, line5]
for line in lineVector:
    line.SetLineColor(ROOT.kBlack)
    line.SetLineWidth(3)
    line.Draw()

leg = TLegend(.54, .75, .58, .79)
leg.SetFillStyle(0)
leg.SetLineWidth(4)
leg.Draw()

text = TLatex(.6, .75, "NA49 Coverage")
text.SetTextColor(ROOT.kBlack)
text.SetNDC()
text.SetTextSize(1.4 / 30.)
text.SetTextAlign(11)
#text.DrawLatex(.48, .55, "#Square");
text.Draw()

raw_input("Please press enter to exit.")
relPosX = 0.045
relPosY = 0.035
relExtraDY = 1.2

alignY_ = 3
alignX_ = 1
align_ = 10 * alignX_ + alignY_
cv.cd()
latex = TLatex()
latex.SetNDC()
latex.SetTextAngle(0)
latex.SetTextColor(1)

latex.SetTextFont(42)
latex.SetTextAlign(31)
latex.SetTextSize(lumiTextSize * t)
#latex.DrawLatex(1-r,1-t+lumiTextOffset*t,lumiText);

posX_ = 0
posY_ = 1 - t - relPosY * (1 - t - b)
latex.SetTextFont(cmsTextFont)
latex.SetTextSize(0.8 * cmsTextSize * t)
latex.SetTextAlign(align_)
#latex.DrawLatex(1.3*l, posY_, cmsText);

extraTextSize = extraOverCmsTextSize * cmsTextSize
latex.SetTextFont(extraTextFont)
latex.SetTextAlign(align_)
latex.SetTextSize(0.8 * extraTextSize * t)

#print extraText
Beispiel #10
0
def main(reader_name,
         tags,
         lut_path,
         xmin,
         xmax,
         ymin=None,
         ymax=None,
         tags_name=None,
         logx=False,
         logy=False,
         leg_pos=[0.74, 0.2, 0.90, 0.4],
         particles=None,
         ind_var=0,
         dnch_deta=100,
         rmin=None,
         add_eta_label=True,
         add_alice3_label=True,
         save=None,
         background=False,
         use_p_over_z=True,
         aod=None,
         styles=None,
         study_label="ALICE 3 study"):
    gROOT.LoadMacro(reader_name)
    gROOT.LoadMacro("style.C")
    reader_name = reader_name.split(".")[-2]
    reader = getattr(__import__('ROOT', fromlist=[reader_name]), reader_name)
    getattr(__import__('ROOT', fromlist=["style"]), "style")()
    p = {
        "el": "e",
        "pi": "#pi",
        "ka": "K",
        "pr": "p",
        "de": "d",
        "tr": "t",
        "he3": "^{3}He"
    }
    charge = {"el": 1, "pi": 1, "ka": 1, "pr": 1, "de": 1, "tr": 1, "he3": 2}
    p_colors = {
        "el": "#e41a1c",
        "pi": "#377eb8",
        "ka": "#4daf4a",
        "pr": "#984ea3",
        "de": "#ff7f00",
        "tr": "#999999",
        "he3": "#a65628"
    }

    if particles is not None:
        to_remove = []
        for i in p:
            if i not in particles:
                to_remove.append(i)
        for i in to_remove:
            p.pop(i)

    latex = TLatex()
    latex.SetTextAlign(33)
    canvas = reader_name
    canvas = canvas.replace("lutRead_", "")
    canvas = TCanvas(canvas, canvas, 800, 800)
    canvas.Divide(2, 2)
    drawn = [canvas]
    drawn_graphs = {}
    drawn_frames = {}

    def set_limit(l, v=0):
        if l is None:
            return v
        return l

    if "_dca" in reader_name:
        ymin = set_limit(ymin, 0.1)
        ymax = set_limit(ymax, 1e4)
    elif "_pt" in reader_name:
        ymin = set_limit(ymin, 1)
        ymax = set_limit(ymax, 100)
    elif "_eff" in reader_name:
        ymin = set_limit(ymin, 0)
        ymax = set_limit(ymax, 115)

    def adjust_pad():
        if logx:
            gPad.SetLogx()
        if logy:
            gPad.SetLogy()

    counter = 1
    leg = None
    if tags_name is not None:
        leg = TLegend(*leg_pos)
        if add_eta_label:
            label = f"#eta = {int(ind_var)}"
            if "vs_eta" in reader_name:
                label = "#it{p}_{T} " f"= {int(ind_var)} " "GeV/#it{c}"
            label += " dN_{Ch}/d#eta ="
            label += f" {int(dnch_deta)}"
            if rmin is not None:
                label += "   R_{min} = " + rmin
            else:
                leg.SetHeader()
            leg.SetHeader(label)
        leg.SetLineColor(0)
        drawn.append(leg)

    def draw_study_label(x=0.5, y=0.9):
        latex = TLatex()
        latex.SetTextAlign(13)
        drawn.append(latex.DrawLatexNDC(x, y, " ".join(study_label)))

    for i in p:  # Drawing one canvas per particle species
        c = f"{canvas.GetName()}_{i}"
        c = TCanvas(c, c, 800, 800)
        drawn.append(c)
        adjust_pad()

        frame = c.DrawFrame(xmin, ymin, xmax, ymax, "")
        frame.SetDirectory(0)
        if leg is not None:
            leg.Draw()
        drawn_frames[i] = frame
        g_list = []
        extra = {}
        cols = [
            '#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33'
        ]
        for k, j in enumerate(tags):
            lut = f"{lut_path}/lutCovm.{i}.{j}.dat"
            if j == "":
                lut = f"{lut_path}/lutCovm.{i}.dat"
            if not path.isfile(lut):
                print("LUT file", lut, "does not exist")
                return
            g = reader(lut, ind_var, dnch_deta)
            if g.GetN() <= 0:
                print("Skipping", g.GetName(), "because empty graph")
                continue
            if len(g_list) == 0:
                frame.GetXaxis().SetTitle(g.GetXaxis().GetTitle())
                frame.GetYaxis().SetTitle(g.GetYaxis().GetTitle())
            if use_p_over_z:
                for j in range(g.GetN()):
                    if "_pt" in reader_name:
                        g.SetPoint(j,
                                   g.GetPointX(j) / charge[i],
                                   g.GetPointY(j) / charge[i])
                    else:
                        g.SetPoint(j,
                                   g.GetPointX(j) / charge[i], g.GetPointY(j))
                frame.GetXaxis().SetTitle("#it{p}_{T}/z (GeV/#it{c})")
            col = TColor.GetColor(cols[len(g_list)])
            g.SetLineColor(col)
            g.SetLineStyle(1)
            g.SetLineWidth(3)
            g.Draw("samel")
            if aod is not None:
                f_aod = TFile(aod, "READ")
                if "_eff" in reader_name:
                    extra[g.GetName()] = f_aod.Get(
                        "qa-tracking-efficiency-kaon/pt/num")
                    extra[g.GetName()].Divide(
                        f_aod.Get("qa-tracking-efficiency-kaon/pt/num"),
                        f_aod.Get("qa-tracking-efficiency-kaon/pt/den"), 1, 1,
                        "B")
                    extra[g.GetName()].Scale(100)
                    extra[g.GetName()].Draw("SAME")
                    extra[g.GetName()].SetDirectory(0)
                elif "_pt" in reader_name:
                    extra[g.GetName()] = f_aod.Get(
                        "qa-tracking-efficiency-kaon/pt/num")
                    extra[g.GetName()].Divide(
                        f_aod.Get("qa-tracking-efficiency-kaon/pt/num"),
                        f_aod.Get("qa-tracking-efficiency-kaon/pt/den"), 1, 1,
                        "B")
                    extra[g.GetName()].Scale(100)
                    extra[g.GetName()].Draw("SAME")
                    extra[g.GetName()].SetDirectory(0)
                f_aod.Close()

            print("Drawing", g.GetName())
            if tags_name is not None and counter == 1:
                leg.AddEntry(g, tags_name[k], "l")
            g_list.append(g)
        drawn_graphs[i] = g_list
        if len(g_list) <= 0:
            print("Nothing drawn!")
            continue
        drawn.append(latex.DrawLatexNDC(0.9, 0.9, p[i]))
        draw_study_label(.4, .91)
        gPad.Update()
        canvas.cd(counter)
        clone = c.DrawClonePad()
        if counter != 1:
            l = gPad.GetListOfPrimitives()
            for i in l:
                cn = i.ClassName()
                if cn == "TLegend":
                    l.Remove(i)
                elif cn == "TLatex":
                    if "ALICE" in i.GetTitle():
                        l.Remove(i)
        drawn.append(clone)
        c.SaveAs(f"/tmp/{c.GetName()}.png")
        gPad.Update()
        counter += 1
    canvas_all_species = None
    if len(tags) == 1 or styles is not None:
        canvas_all_species = "all_spec_" + canvas.GetName()
        canvas_all_species = TCanvas(canvas_all_species, canvas_all_species,
                                     800, 800)
        drawn.append(canvas_all_species)
        canvas_all_species.cd()
        drawn_graphs_all_spec = {}
        leg_all_spec = TLegend(*leg_pos)
        leg_all_spec.SetNColumns(2)
        leg_all_spec.SetLineColor(0)
        drawn.append(leg_all_spec)
        for i in drawn_graphs:
            if canvas_all_species.GetListOfPrimitives().GetEntries() == 0:
                drawn_frames[i].Draw()
                leg_all_spec.Draw()
            drawn_graphs_all_spec[i] = []
            for k, g in enumerate(drawn_graphs[i]):
                g = g.Clone()
                drawn_graphs_all_spec[i].append(g)
                g.SetName(g.GetName() + "_color")
                g.SetLineColor(TColor.GetColor(p_colors[i]))
                if styles is not None:
                    g.SetLineStyle(styles[k])
                g.Draw("same")
                if k == 0:
                    leg_all_spec.AddEntry(g, p[i], "L")
        if styles is not None:
            for j, k in enumerate(tags_name):
                g = TGraph()
                g.SetLineWidth(3)
                g.SetLineColor(1)
                g.SetLineStyle(styles[j])
                leg_all_spec.AddEntry(g, k, "L")
                drawn_graphs_all_spec[i].append(g)
        for i in drawn_graphs_all_spec:
            drawn_graphs[i + "_allspec"] = drawn_graphs_all_spec[i]
        if add_alice3_label:
            draw_study_label(.2, .91)
            latex = TLatex()
            latex.SetTextAlign(13)
            latex.SetTextSize(0.04)
            if tags_name is not None and styles is None:
                drawn.append(latex.DrawLatexNDC(0.5, 0.80, tags_name[0]))
            if "vs_eta" in reader_name:
                drawn.append(
                    latex.DrawLatexNDC(
                        0.42, 0.82, "#splitline{" + "#it{p}_{T}" +
                        " = {:.1f} GeV/c".format(ind_var) +
                        " dN_{Ch}/d#eta =" + f" {int(dnch_deta)}" + "}" +
                        ("{R_{min} = " + rmin +
                         "}" if rmin is not None else "")))
            else:
                # drawn.append(latex.DrawLatexNDC(0.55, 0.82, "#splitline{" +
                drawn.append(
                    latex.DrawLatexNDC(
                        0.55, 0.45, "#splitline{" + f"#eta = {int(ind_var)}" +
                        " dN_{Ch}/d#eta =" + f" {int(dnch_deta)}" + "}" +
                        ("{R_{min} = " + rmin +
                         "}" if rmin is not None else "")))

        adjust_pad()
        canvas_all_species.Update()
        canvas_all_species.SaveAs(f"/tmp/{canvas_all_species.GetName()}.png")
        canvas_all_species.SaveAs(f"/tmp/{canvas_all_species.GetName()}.pdf")
        canvas.SaveAs(f"/tmp/lut_{canvas.GetName()}.root")
    if save is not None:
        print("Saving to", save)
        fo = TFile(save, "RECREATE")
        fo.cd()
        for i in drawn_graphs:
            for j in drawn_graphs[i]:
                j.Write(j.GetName().split("/")[-1])
    if not background:
        input("Done, press enter to continue")
Beispiel #11
0
def plot2BodyDist(theFitter, pars, chi2, ndf, 
                  Err = -1, NP = False, Prefix = "Mjj", Left = False):
    from ROOT import gPad, TLatex, TCanvas, kRed, kCyan, kBlue, \
         RooFit, RooPlot, RooCurve, RooAbsReal, TGraphErrors, TLine, \
         RooWjjMjjFitter

    if pars.includeMuons and pars.includeElectrons:
        modeString = ''
    elif pars.includeMuons:
        modeString = 'Muon'
    elif pars.includeElectrons:
        modeString = 'Electron'
    else:
        modeString = ''

    mf = theFitter.stackedPlot(False, RooWjjMjjFitter.mjj, Left)
    mf.SetName("%s_Stacked" % (Prefix));
    sf = theFitter.residualPlot(mf, "h_background", "dibosonPdf", False)
    sf.SetName("%s_Subtracted" % (Prefix));
    pf = theFitter.residualPlot(mf, "h_total", "", True)
    pf.SetName("%s_Pull" % (Prefix))
    pf2 = pf.emptyClone("%s_Pull_Corrected" % (Prefix))
    pf2.SetMinimum(-5.)
    pf2.SetMaximum(5.)
    corrPull = False
    lf = theFitter.stackedPlot(True, RooWjjMjjFitter.mjj, Left)
    lf.SetName("%s_Stacked_Log" % (Prefix));

    if Err > 0:
        totalPdf = theFitter.getWorkSpace().pdf('totalPdf')
        ## Ntotal = totalPdf.expectedEvents(iset)

        ## print 'Ntotal:',Ntotal
        h_dibosonPdf = sf.getCurve('h_dibosonPdf')
        totalPdf.plotOn(sf,
                        RooFit.ProjWData(theFitter.getWorkSpace().data('data')),
                        RooFit.Normalization(Err, RooAbsReal.Raw),
                        #RooFit.AddTo('h_dibosonPdf', 1., 1.),
                        #RooFit.Invisible(),
                        RooFit.Name('h_ErrUp'),
                        RooFit.Range('RangeForPlot'),
                        RooFit.NormRange('RangeForPlot'),
                        RooFit.LineColor(kRed), RooFit.LineStyle(3))
        h_ErrUp = sf.getCurve('h_ErrUp')
        sf.remove('h_ErrUp', False)

        ErrBand = TGraphErrors(h_dibosonPdf.GetN(), h_dibosonPdf.GetX(),
                               h_dibosonPdf.GetY())
        for pt in range(1, ErrBand.GetN()):
            ErrBand.SetPointError(pt, 0,
                                  h_ErrUp.interpolate(ErrBand.GetX()[pt]))
        ErrBand.SetName("ErrBand")
        ErrBand.SetTitle("Uncertainty")
        ErrBand.SetLineColor(kRed)
##         ErrBand.SetLineWidth(0)
##         ErrBand.SetLineStyle(0)
        ErrBand.SetFillColor(kRed)
        ErrBand.SetFillStyle(3353)

        
        #ErrBand.Draw('ap3')
        #h_ErrUp.Draw('lp')
        #gPad.Update()
        #gPad.WaitPrimitive()
##         h_ErrUp.Draw("al")
##         h_ErrUp.GetXaxis().Set(36, 40., 400.)
##         gPad.Update()
##         gPad.WaitPrimitive()
##         h_UpBand = RooCurve("h_UpBand", "Uncertainty", h_dibosonPdf, h_ErrUp,
##                             1., 1.)
##         h_UpBand.SetLineStyle(3)
##         h_UpBand.SetLineColor(kBlue+1)
##         h_DownBand = RooCurve("h_DownBand", "Uncertainty", h_dibosonPdf, h_ErrUp,
##                               1., -1.)
##         h_DownBand.SetLineStyle(3)
##         h_DownBand.SetLineColor(kBlue+1)

##         sf.addPlotable(h_UpBand, "L")
##         sf.addPlotable(h_DownBand, "L")
        sf.addObject(ErrBand, "3")
        #sf.Print("v")
        sf.drawAfter('h_dibosonPdf', 'ErrBand')
        #sf.Print("v")
        sf.drawAfter('ErrBand', 'theData')
        #sf.Print("v")
        sf.findObject('theLegend').AddEntry(ErrBand, 'Uncertainty', 'f')
        sf.findObject('theLegend').SetY1NDC(sf.findObject('theLegend').GetY1NDC() - 0.057)
        sf.findObject('theLegend').SetY1(sf.findObject('theLegend').GetY1NDC())

        corrPull = True
        pf2.addObject(sub2pull(sf.getHist('theData'),
                               sf.findObject('ErrBand')),
                      'p0')
        for item in range(0, int(pf.numItems())):
            firstItem = pf.getObject(item)
            if (type(firstItem) == TLine):
                newLine = TLine(firstItem)
                newLine.SetY1(4.)
                newLine.SetY2(-4.)
                pf2.addObject(newLine, 'l')
                #SetOwnership(newLine, False)


    if NP:
        NPPdf = theFitter.makeNPPdf();
        NPNorm = 4.*0.11*46.8/12.*pars.intLumi

        if (modeString == 'Electron'):
            if pars.njets == 2:
                NPNorm *= 0.0381
            elif pars.njets == 3:
                NPNorm *= 0.0123
        else:
            if pars.njets == 2:
                NPNorm *= 0.0550
            elif pars.njets == 3:
                NPNorm *= 0.0176

        print '**** N_NP:', NPNorm,'****'

        NPPdf.plotOn(sf, RooFit.ProjWData(theFitter.getWorkSpace().data('data')),
                     RooFit.Normalization(NPNorm, RooAbsReal.Raw),
                     RooFit.AddTo('h_dibosonPdf', 1., 1.),
                     RooFit.Name('h_NP'),
                     RooFit.Range('RangeForPlot'),
                     RooFit.NormRange('RangeForPlot'),
                     RooFit.LineColor(kBlue), RooFit.LineStyle(2))

        h_NP = sf.getCurve('h_NP')

        sf.drawBefore('h_dibosonPdf', 'h_NP')
        #sf.Print("v")
        sf.findObject('theLegend').AddEntry(h_NP, "CDF-like Signal", "L")
        sf.findObject('theLegend').SetY1NDC(sf.findObject('theLegend').GetY1NDC() - 0.057)
        sf.findObject('theLegend').SetY1(sf.findObject('theLegend').GetY1NDC())

    l = TLatex()
    l.SetNDC()
    l.SetTextSize(0.045)
    l.SetTextFont(42)

    cstacked = TCanvas("cstacked", "stacked")
    mf.Draw()
    if (chi2 > 0):
        l.DrawLatex(0.55, 0.49,
                    '#chi^{2}/dof = %0.3f/%d' % (chi2, ndf)
                    )
    pyroot_logon.cmsLabel(cstacked, pars.intLumi/1000, prelim = True)
    cstacked.Print('Wjj_%s_%s_%ijets_Stacked.pdf' % (Prefix, modeString,
                                                     pars.njets))
    cstacked.Print('Wjj_%s_%s_%ijets_Stacked.png' % (Prefix, modeString,
                                                     pars.njets))
    c2 = TCanvas("c2", "stacked_log")
    c2.SetLogy()
    lf.Draw()
    pyroot_logon.cmsPrelim(c2, pars.intLumi/1000)
    c2.Print('Wjj_%s_%s_%ijets_Stacked_log.pdf' % (Prefix, modeString,
                                                    pars.njets))
    c2.Print('Wjj_%s_%s_%ijets_Stacked_log.png' % (Prefix, modeString,
                                                    pars.njets))
    c3 = TCanvas("c3", "subtracted")
    sf.Draw()
    pyroot_logon.cmsLabel(c3, pars.intLumi/1000, prelim = True)
    c3.Print('Wjj_%s_%s_%ijets_Subtracted.pdf' % (Prefix, modeString,
                                                  pars.njets))
    c3.Print('Wjj_%s_%s_%ijets_Subtracted.png' % (Prefix, modeString,
                                                  pars.njets))
    c4 = TCanvas("c4", "pull")
    pf.Draw()
    c4.SetGridy()
    pyroot_logon.cmsPrelim(c4, pars.intLumi/1000)
    c4.Print('Wjj_%s_%s_%ijets_Pull.pdf' % (Prefix, modeString, pars.njets))
    c4.Print('Wjj_%s_%s_%ijets_Pull.png' % (Prefix, modeString, pars.njets))

    c5 = None
    if corrPull:
        c5 = TCanvas("c5", "corrected pull")
        pf2.Draw()
        c5.SetGridy()
        pyroot_logon.cmsPrelim(c5, pars.intLumi/1000)
        c5.Print('Wjj_%s_%s_%ijets_Pull_Corrected.pdf' % (Prefix, modeString,
                                                          pars.njets))
        c5.Print('Wjj_%s_%s_%ijets_Pull_Corrected.png' % (Prefix, modeString,
                                                          pars.njets))

    return ([mf,sf,pf2,lf],[cstacked,c2,c3,c5])
Beispiel #12
0
def main():
    gStyle.SetOptStat(0)
    c1 = TCanvas('c1', 'c1', 3)
    gPad.SetTickx()
    gPad.SetTicky()
    c1.SetLeftMargin(0.12)
    h_frame = TH1F('frame', '', 50, 0, 1000)
    h_frame.SetXTitle('P^{miss}_{T} (GeV)')
    h_frame.SetYTitle('Arbitrary units')
    h_frame.SetMaximum(0.4)

    h_higgsPt = TH1F('h_higgsPt', 'h_higgsPt', 50, 0, 1000)
    h_higgsPtList = []
    for i in range(6):
        h_higgsPtList.append(TH1F(histName_zp2HDM[i], '', 50, 0, 1000))
        h_higgsPtList[i].SetLineWidth(2)
    h_higgsPt_BarList = []
    for i in range(6):
        h_higgsPt_BarList.append(TH1F(histName_bar[i], '', 40, 0, 800))
        h_higgsPt_BarList[i].SetLineWidth(2)
    ## test code
    '''
    ivVectList = getPtList(hApath)
    for fourV in ivVectList:
        h_higgsPt.Fill(fourV.pt)
    '''

    ## loop all combination
    leg = TLegend(0.32, 0.57, 0.87, 0.87)
    leg.SetBorderSize(0)
    for i in range(3):
        ivVectList = getPtList(hApathList[i])
        h_higgsPtList[i].SetLineColor(87 + 4 * i)
        leg.AddEntry(h_higgsPtList[i], legtext[i])
        for fourV in ivVectList:
            h_higgsPtList[i].Fill(fourV.pt)

    for i in range(3):
        ivVectList = getPtList(hApathList_5[i])
        h_higgsPtList[i + 3].SetLineColor(61 + 4 * i)
        leg.AddEntry(h_higgsPtList[i + 3], legtext_5[i])
        for fourV in ivVectList:
            h_higgsPtList[i + 3].Fill(fourV.pt)

    h_frame.Draw('hist')
    #h_higgsPt.Draw('histsame')
    for i in range(6):
        h_higgsPtList[i].DrawNormalized('histsame')
    leg.Draw()
    c1.Print('Zp2HDM_higgsPt.pdf')

    colorList = [95, 91, 87, 61, 65, 69]
    #colorList = [61,95,65,91,69,87]
    ## Baryonic
    info_bar = TLatex(0, 0.255, 'CMS')
    info_bar_2 = TLatex(750, 0.255, '35.9 fb^{-1} (13 TeV)')
    info_bar.SetTextSize(0.03)
    info_bar_2.SetTextSize(0.03)
    info_bar_2.SetTextAlign(31)
    h_frame.SetMaximum(0.25)
    h_frame.SetAxisRange(0., 750., "X")
    leg.Clear()
    for i in range(6):
        ivVectList = getPtList('BaryonicFile/' + hApath_barList[i])
        h_higgsPt_BarList[i].SetLineColor(colorList[i])
        #h_higgsPt_BarList[i].SetLineColor(90-6*i)
        leg.AddEntry(h_higgsPt_BarList[i], legtext_bar[i])
        for fourV in ivVectList:
            h_higgsPt_BarList[i].Fill(fourV.pt)

    h_frame.Draw('hist')
    for i in range(5, -1, -1):
        h_higgsPt_BarList[i].DrawNormalized('histsame')
    leg.Draw()
    info_bar.Draw()
    info_bar_2.Draw()
    c1.Print('Baryonic_higgsPt.pdf')
    f = TFile('rootFile/Zp2HDM_missPt.root', 'recreate')
    for i in range(6):
        h_higgsPtList[i].SetLineColor(1)
        h_higgsPtList[i].Write()

    f.Close()

    f = TFile('rootFile/BaryonicZp_missPt.root', 'recreate')
    for i in range(6):
        h_higgsPt_BarList[i].SetLineColor(1)
        h_higgsPt_BarList[i].Write()

    f.Close()
Beispiel #13
0
def plot(dictHist, option, fitFunction):
    c = TCanvas("c", "c", 600, 300)
    legend = TLegend(0.12, 0.18, 0.35, 0.85)
    legend.AddEntry(None, "#bf{mean[GeV] / sigma[GeV] / ratio}", "")
    color = 1
    hs = THStack("hs", "corrections;mbb [GeV];Number of events;")
    drawOption = ""  #Draw Option for THStack
    for key in dictHist:
        hist = dictHist[key].Clone()
        hist.SetLineColor(color)  # Setting color for the histogram
        #         print 'Current Hist Title: ',hist.GetTitle()
        #         print 'Color Option: ',color
        entries = hist.GetEntries()
        height = hist.GetMaximum()
        mean = hist.GetMean()
        rms = hist.GetRMS()

        xmin = mean - 3 * rms
        xmax = mean + 3 * rms
        #Getting Function of Choice
        if (fitFunction == 'gauss'):
            f = setGauss(mean=mean,
                         rms=rms,
                         height=height,
                         xmin=xmin,
                         xmax=xmax)
        elif (fitFunction == 'bukin'):
            f = setBukin(mean=mean,
                         rms=rms,
                         height=height,
                         xmin=xmin,
                         xmax=xmax)
        else:
            print "Name of the function was not recognized! Selection can be either 'gauss' or 'bukin'."
            assert (False)

        ########### start code specific to the histo and/or fit choice ##################
        if option == "histo":
            hs.Add(hist)
            result = (height, mean, rms)
            drawOption = "nostack"
        elif option == "histo+fit":
            hist.Fit(fitFunction, "RQ", "HISTS", xmin, xmax)
            f = hist.GetFunction(fitFunction)
            if (fitFunction == 'gauss'):
                result = (f.GetParameter(0), f.GetParameter(1),
                          f.GetParameter(2))
            else:
                result = (f.GetParameter(0), f.GetParameter(1),
                          f.GetParameter(2), f.GetParameter(3),
                          f.GetParameter(4), f.GetParameter(5))
            f.SetLineColor(color)
            hs.Add(hist)
            drawOption = "nostack"
        elif option == "fit":
            hist.Fit(fitFunction, "RQ", "RO", xmin, xmax)
            f = hist.GetFunction(fitFunction)
            if (fitFunction == 'gauss'):
                result = (f.GetParameter(0), f.GetParameter(1),
                          f.GetParameter(2))
            else:
                result = (f.GetParameter(0), f.GetParameter(1),
                          f.GetParameter(2), f.GetParameter(3),
                          f.GetParameter(4), f.GetParameter(5))
            f.SetLineColor(color)
            hs.Add(hist)
            drawOption = "nostackRO"
        else:
            print "option", option, "not known"
            assert (False)
        ########## end   code specific to the histo and/or fit choice ##################
        # https://root.cern.ch/doc/master/classTLegend.html
        legend.AddEntry(hist, hist.GetName(), "f")
        legend_text = "#bf{%-.3f/%-.3f/%-.3f}" % (result[1], result[2],
                                                  ratio(result[2], result[1]))
        legend.AddEntry(None, legend_text, "")
        c.Update()

        color += 1
        if (color == 10):  #10 would not be visible
            color = 11

    hs.Draw(drawOption)
    legend.SetBorderSize(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.025)
    legend.SetTextColor(1)
    legend.Draw('Same')
    # https://root.cern.ch/doc/master/classTLatex.html#L3
    t = TLatex()
    t.SetNDC()
    t.SetTextSize(10)
    t.SetTextFont(43)
    t.SetTextAlign(13)
    t.DrawLatex(0.7, 0.85, "#it{#bf{ATLAS} Simulation Internal}")
    t.Draw("Same")

    c.Print("Higgs_" + option + ".pdf")
Beispiel #14
0
def CMS_lumi(pad, lumi_sqrtS="", iPosX=0):

    outOfFrame = False
    if iPosX / 10 == 0: outOfFrame = True

    alignY_ = 3
    alignX_ = 2
    if iPosX / 10 == 0: alignX_ = 1
    if iPosX == 0: alignY_ = 1
    if iPosX / 10 == 1: alignX_ = 1
    if iPosX / 10 == 2: alignX_ = 2
    if iPosX / 10 == 3: alignX_ = 3
    align_ = 10 * alignX_ + alignY_

    H = pad.GetWh()
    W = pad.GetWw()
    l = pad.GetLeftMargin()
    t = pad.GetTopMargin()
    r = pad.GetRightMargin()
    b = pad.GetBottomMargin()
    e = 0.025

    pad.cd()

    lumiText = ""
    if lumi_sqrtS == "":
        lumiText += lumi_13TeV
        lumiText += " (13 TeV)"
    else:
        lumiText += lumi_sqrtS

    print lumiText

    latex = TLatex()
    latex.SetNDC()
    latex.SetTextAngle(0)
    latex.SetTextColor(kBlack)

    extraTextSize = extraOverCmsTextSize * cmsTextSize

    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(lumiTextSize * t)

    latex.DrawLatex(1 - r, 1 - t + lumiTextOffset * t, lumiText)

    if outOfFrame:
        latex.SetTextFont(cmsTextFont)
        latex.SetTextAlign(11)
        latex.SetTextSize(cmsTextSize * t)
        latex.DrawLatex(l, 1 - t + lumiTextOffset * t, cmsText)

    pad.cd()

    posX_ = 0
    if iPosX % 10 <= 1:
        posX_ = l + relPosX * (1 - l - r)
    elif iPosX % 10 == 2:
        posX_ = l + 0.5 * (1 - l - r)
    elif iPosX % 10 == 3:
        posX_ = 1 - r - relPosX * (1 - l - r)

    posY_ = 1 - t - relPosY * (1 - t - b)

    if not outOfFrame:
        latex.SetTextFont(cmsTextFont)
        latex.SetTextSize(cmsTextSize * t)
        latex.SetTextAlign(align_)
        latex.DrawLatex(posX_, posY_, cmsText)
        if writeExtraText:
            latex.SetTextFont(extraTextFont)
            latex.SetTextAlign(align_)
            latex.SetTextSize(extraTextSize * t)
            latex.DrawLatex(posX_, posY_ - relExtraDY * cmsTextSize * t,
                            extraText)
    elif writeExtraText:
        if iPosX == 0:
            posX_ = l + relPosX * (1 - l - r)
            posY_ = 1 - t + lumiTextOffset * t

        latex.SetTextFont(extraTextFont)
        latex.SetTextSize(extraTextSize * t)
        latex.SetTextAlign(align_)
        latex.DrawLatex(posX_, posY_, extraText)

    pad.Update()
Beispiel #15
0
def drawROIGeometry(geometry, is2016):

    outfn = "ROILayout%s.pdf" % ("2016" if is2016 else "2015")

    global box, c, h, leg

    gROOT.Reset()
    gStyle.SetOptStat(0)

    c = TCanvas('c', "MuCTPi Geometry %s" % "2016" if is2016 else "2015", 1400,
                950)
    c.Draw()

    #h = TH2F("h","Muon Geometry",10,-2.6,2.6,10,-6.4,6.4)
    h = TH2F("h", "Muon Geometry %s" % "2016" if is2016 else "2015", 10, -2.6,
             2.6, 10, -0.15, 6.4)
    h.SetXTitle("#eta")
    h.SetYTitle("#phi")
    h.Draw()

    box = TBox()
    box.SetFillStyle(0)
    box.SetLineColor(3)
    box.SetLineColor(3)

    text = TLatex()
    text.SetTextSize(0.005)
    text.SetTextFont(42)
    text.SetTextAlign(22)

    secLabel = TLatex()
    secLabel.SetTextSize(0.008)
    secLabel.SetTextFont(42)
    secLabel.SetTextAlign(22)

    leg = TLegend(0.7, 0.1, 0.9, 0.4)
    leg.SetEntrySeparation(0.05)
    leg.SetNColumns(2)

    #for MIOCT in geometry.getMIOCTs():
    for colorIndex, MioctID in enumerate(drawOrder):
        MIOCT = geometry.getMIOCT(MioctID)
        firstBox = True
        color = colorMap[colorIndex % len(colorMap)]
        #print "Using color ",color
        box.SetLineColor(color)
        box.SetLineWidth(1)

        for Sector in MIOCT.Sectors:
            ymin = 10
            ymax = -10
            for ROI in Sector.ROIs:
                c1_x = float(ROI["etamin"])
                c1_y = float(ROI["phimin"])
                c2_x = float(ROI["etamax"])
                c2_y = float(ROI["phimax"])
                ymin = min(ymin, c1_y)
                ymax = max(ymax, c2_y)
                #print "eta [%f - %f], phi [%f - %f]" % (c1_x,c2_x,c1_y,c2_y)
                b = box.DrawBox(c1_x, c1_y, c2_x, c2_y)
                text.DrawText((c1_x + c2_x) / 2, (c1_y + c2_y) / 2,
                              ROI["roiid"])
                if firstBox:
                    firstBox = False
                    leg.AddEntry(b, "Slot %s" % MIOCT["slot"], "l")
            if Sector["name"].startswith("B"):
                if int(Sector["name"][1:]) < 32:
                    xpos = -0.02
                    ypos = (ymin + ymax) / 2 - 0.05
                else:
                    xpos = 0.02
                    ypos = (ymin + ymax) / 2 + 0.03
                secLabel.DrawText(xpos, ypos, Sector["name"])

    leg.Draw()

    c.Update()
    c.SaveAs(outfn)
Beispiel #16
0
def doULPlot(suffix):

    xbins = array('d', [])
    xbins_env = array('d', [])
    ybins_exp = array('d', [])
    ybins_obs = array('d', [])
    ybins_1s = array('d', [])
    ybins_2s = array('d', [])
    ybins_th = array('d', [])

    for i in range(len(mass)):
        curFile = "higgsCombine_lim_%s%03d%s.Asymptotic.mH%03d.root" % (
            options.signalmodel, mass[i], suffix, mass[i])
        print "curFile: %s" % curFile
        if options.lvqqBR:
            sf = table_signalscale[mass[i]] * xsDict_lvj[mass[i]]
            #*0.1057*0.577; # BR(W->munu)*BR(H->bb)
        else:
            sf = table_signalscale[mass[i]] * xsDict[mass[i]]

        curAsymLimits = getAsymLimits(curFile)
        #print mass[i]
        #print curAsymLimits
        #raw_input("zixu")
        xbins.append(mass[i] / 1000.)
        #GeV->TeV
        xbins_env.append(mass[i] / 1000.)
        ybins_exp.append(curAsymLimits[3] * sf)
        ybins_obs.append(curAsymLimits[0] * sf)
        ybins_2s.append(curAsymLimits[1] * sf)
        ybins_1s.append(curAsymLimits[2] * sf)
        #ybins_th.append(sf);#/20.); #*0.25);
        if options.lvqqBR:
            ybins_th.append(xsDict_lvj[mass[i]])
            #/20.); #*0.25);
        else:
            ybins_th.append(xsDict[mass[i]])
            #/20.); #*0.25);

    for i in range(len(mass) - 1, -1, -1):
        curFile = "higgsCombine_lim_%s%03d%s.Asymptotic.mH%03d.root" % (
            options.signalmodel, mass[i], suffix, mass[i])
        print "curFile: %s" % curFile
        if options.lvqqBR:
            sf = table_signalscale[mass[i]] * xsDict_lvj[mass[i]]
            #*0.1057*0.577; # BR(W->munu)*BR(H->bb)
        else:
            sf = table_signalscale[mass[i]] * xsDict[mass[i]]

        curAsymLimits = getAsymLimits(curFile)
        xbins_env.append(mass[i] / 1000.)
        ybins_2s.append(curAsymLimits[5] * sf)
        ybins_1s.append(curAsymLimits[4] * sf)

    nPoints = len(mass)
    curGraph_exp = ROOT.TGraphAsymmErrors(nPoints, xbins, ybins_exp)
    curGraph_obs = ROOT.TGraphAsymmErrors(nPoints, xbins, ybins_obs)
    curGraph_th = ROOT.TGraph(nPoints, xbins, ybins_th)
    curGraph_1s = ROOT.TGraphAsymmErrors(nPoints * 2, xbins_env, ybins_1s)
    curGraph_2s = ROOT.TGraphAsymmErrors(nPoints * 2, xbins_env, ybins_2s)

    curGraph_obs.SetMarkerStyle(20)
    curGraph_obs.SetLineWidth(3)
    curGraph_obs.SetLineStyle(1)
    curGraph_obs.SetMarkerSize(1.6)
    curGraph_exp.SetMarkerSize(1.3)
    curGraph_exp.SetMarkerColor(ROOT.kBlack)

    curGraph_exp.SetLineStyle(2)
    curGraph_exp.SetLineWidth(3)
    curGraph_exp.SetMarkerSize(2)
    curGraph_exp.SetMarkerStyle(24)
    curGraph_exp.SetMarkerColor(ROOT.kBlack)

    #curGraph_th.SetLineStyle(ROOT.kDashed);
    curGraph_th.SetFillStyle(3344)
    curGraph_th.SetLineWidth(2)
    curGraph_th.SetMarkerSize(2)
    curGraph_th.SetLineColor(ROOT.kRed)

    curGraph_1s.SetFillColor(ROOT.kGreen)
    curGraph_1s.SetFillStyle(1001)
    curGraph_1s.SetLineStyle(ROOT.kDashed)
    curGraph_1s.SetLineWidth(3)

    curGraph_2s.SetFillColor(ROOT.kYellow)
    curGraph_2s.SetFillStyle(1001)
    curGraph_2s.SetLineStyle(ROOT.kDashed)
    curGraph_2s.SetLineWidth(3)

    oneLine = ROOT.TF1("oneLine", "1", 799, 1001)
    oneLine.SetLineColor(ROOT.kRed)
    oneLine.SetLineWidth(3)

    setStyle()

    can_SM = ROOT.TCanvas("can_SM", "can_SM", 630, 600)

    hrl_SM = can_SM.DrawFrame(mass[0] / 1000. - 0.01, 1e-4,
                              mass[nPoints - 1] / 1000. + 0.01, 1e2)

    if options.signalmodel == "BulkGravWW":
        if options.lvqqBR:
            hrl_SM.GetYaxis().SetTitle(
                "#sigma_{95%} (pp #rightarrow G_{Bulk} #rightarrow WW #rightarrow l#nuqq') (pb)"
            )
        else:
            hrl_SM.GetYaxis().SetTitle(
                "#sigma_{95%} (pp #rightarrow G_{Bulk} #rightarrow WW) (pb)")
    elif options.signalmodel == "WprimeWZ":
        if options.lvqqBR:
            hrl_SM.GetYaxis().SetTitle(
                "#sigma_{95%} (pp #rightarrow W' #rightarrow WZ #rightarrow l#nuqq') (pb)"
            )
        else:
            hrl_SM.GetYaxis().SetTitle(
                "#sigma_{95%} (pp #rightarrow W' #rightarrow WZ) (pb)")
    elif options.signalmodel == "WprimeWZ-HVT-A":
        if options.lvqqBR:
            hrl_SM.GetYaxis().SetTitle(
                "#sigma_{95%} (pp #rightarrow W' #rightarrow WZ #rightarrow l#nuqq') (pb)"
            )
        else:
            hrl_SM.GetYaxis().SetTitle(
                "#sigma_{95%} (pp #rightarrow W' #rightarrow WZ) (pb)")

    hrl_SM.GetYaxis().SetTitleOffset(1.35)
    hrl_SM.GetYaxis().SetTitleSize(0.045)
    hrl_SM.GetYaxis().SetTitleFont(42)

    if options.signalmodel == "BulkGravWW":
        hrl_SM.GetXaxis().SetTitle("M_{G_{Bulk}} (TeV)")
    elif options.signalmodel == "WprimeWZ":
        hrl_SM.GetXaxis().SetTitle("M_{W'} (TeV)")
    elif options.signalmodel == "WprimeWZ-HVT-A":
        hrl_SM.GetXaxis().SetTitle("M_{W'} (TeV)")

    hrl_SM.GetXaxis().SetTitleSize(0.045)
    hrl_SM.GetXaxis().SetTitleFont(42)

    hrl_SM.GetXaxis().SetNdivisions(510)
    hrl_SM.GetYaxis().SetNdivisions(505)
    can_SM.SetGridx(1)
    can_SM.SetGridy(1)

    curGraph_2s.Draw("F")
    curGraph_1s.Draw("Fsame")
    if options.keepblind == 0:
        curGraph_obs.Draw("PLsame")
    curGraph_exp.Draw("Lsame")
    curGraph_th.Draw("Csame")

    leg2 = ROOT.TLegend(0.32, 0.67, 0.9, 0.92)

    leg2.SetFillColor(0)
    leg2.SetShadowColor(0)
    leg2.SetTextFont(42)
    leg2.SetTextSize(0.035)

    leg2.AddEntry(curGraph_1s, "Asympt. CL_{S}  Expected #pm 1 s.d.", "LF")
    leg2.AddEntry(curGraph_2s, "Asympt. CL_{S}  Expected #pm 2 s.d.", "LF")
    if options.signalmodel == "BulkGravWW":
        if options.lvqqBR:
            leg2.AddEntry(
                curGraph_th,
                "#sigma_{TH} #times BR(G_{Bulk}#rightarrow WW#rightarrow l#nuqq'), #tilde{k}=0.5",
                "L")
        else:
            leg2.AddEntry(
                curGraph_th,
                "#sigma_{TH} #times BR(G_{Bulk}#rightarrow WW), #tilde{k}=0.5",
                "L")
    elif options.signalmodel == "WprimeWZ":
        if options.lvqqBR:
            leg2.AddEntry(
                curGraph_th,
                "#sigma_{TH} #times BR(W'_{HVT B}#rightarrow WZ#rightarrow l#nuqq')",
                "L")
        else:
            leg2.AddEntry(curGraph_th,
                          "#sigma_{TH} #times BR(W'_{HVT B}#rightarrow WZ)",
                          "L")
    elif options.signalmodel == "WprimeWZ-HVT-A":
        if options.lvqqBR:
            leg2.AddEntry(
                curGraph_th,
                "#sigma_{TH} #times BR(W'_{HVT A}#rightarrow WZ#rightarrow l#nuqq')",
                "L")
        else:
            leg2.AddEntry(curGraph_th,
                          "#sigma_{TH} #times BR(W'_{HVT A}#rightarrow WZ)",
                          "L")
    leg2.AddEntry(curGraph_obs, "Asympt. CL_{S} Observed", "LP")

    #ROOT.gPad.SetLogx();
    #hrl_SM.GetXaxis().SetMoreLogLabels()
    #hrl_SM.GetXaxis().SetNoExponent()
    ROOT.gPad.SetLogy()

    can_SM.Update()
    can_SM.RedrawAxis()
    can_SM.RedrawAxis("g")
    can_SM.Update()

    leg2.Draw()
    line = TLine(1.1, 1e-4, 1.1, 1e0)
    line.SetLineWidth(2)
    line.SetLineColor(kBlack)
    line.SetLineStyle(9)
    line.Draw()

    banner = TLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)" % (Lumi))
    banner.SetNDC()
    banner.SetTextSize(0.038)
    banner.SetTextFont(42)
    banner.SetTextAlign(31)
    banner.SetLineWidth(2)
    banner.Draw()
    CMStext = TLatex(0.15, 0.96, "CMS")
    CMStext.SetNDC()
    CMStext.SetTextSize(0.041)
    CMStext.SetTextFont(61)
    CMStext.SetTextAlign(11)
    CMStext.SetLineWidth(2)
    CMStext.Draw()
    if suffix == "_el_HP":
        Extratext = TLatex(0.241, 0.96, "Preliminary W#rightarrow e#nu")
        Extratext.SetNDC()
        Extratext.SetTextSize(0.032)
        Extratext.SetTextFont(52)
        Extratext.SetTextAlign(11)
        Extratext.SetLineWidth(2)
        Extratext.Draw()
    elif suffix == "_mu_HP":
        Extratext = TLatex(0.241, 0.96, "Preliminary W#rightarrow #mu#nu")
        Extratext.SetNDC()
        Extratext.SetTextSize(0.032)
        Extratext.SetTextFont(52)
        Extratext.SetTextAlign(11)
        Extratext.SetLineWidth(2)
        Extratext.Draw()
    elif suffix == "_em_HP":
        Extratext = TLatex(0.241, 0.96, "Preliminary W#rightarrow l#nu")
        Extratext.SetNDC()
        Extratext.SetTextSize(0.032)
        Extratext.SetTextFont(52)
        Extratext.SetTextAlign(11)
        Extratext.SetLineWidth(2)
        Extratext.Draw()

    #CMS_lumi.lumi_13TeV = "%s fb^{-1}"%(Lumi)
    #CMS_lumi.writeExtraText = 1
    #CMS_lumi.extraText = "Preliminary"

    #iPos = 11
    #if(iPos == 0):
    #    CMS_lumi.relPosX = 0.15

    #CMS_lumi.CMS_lumi(can_SM, 4, 11)

    os.system("mkdir -p %s/LimitResult/" % (os.getcwd()))
    os.system("mkdir -p %s/LimitResult/Limit_%s_sys%s/" %
              (os.getcwd(), options.signalmodel, options.Sys))

    can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s.png" %
                  (options.signalmodel, options.Sys, suffix))
    can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s.pdf" %
                  (options.signalmodel, options.Sys, suffix))
    #can_SM.SaveAs("./LimitResult/Limit_sys%s/Lim%s.root"%(options.Sys, suffix));
    can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s.C" %
                  (options.signalmodel, options.Sys, suffix))

    ROOT.gPad.SetLogx()
    hrl_SM.GetXaxis().SetMoreLogLabels()
    hrl_SM.GetXaxis().SetNoExponent()

    can_SM.Update()
    can_SM.RedrawAxis()
    can_SM.RedrawAxis("g")
    leg2.Draw()
    can_SM.Update()

    can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s_Logx.png" %
                  (options.signalmodel, options.Sys, suffix))
    can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s_Logx.pdf" %
                  (options.signalmodel, options.Sys, suffix))
    can_SM.SaveAs("./LimitResult/Limit_%s_sys%s/Lim%s_Logx.C" %
                  (options.signalmodel, options.Sys, suffix))
Beispiel #17
0
def plot_2D_FakeCR():

    myfilename = (
        "/coepp/cephfs/mel/mmilesi/ttH/MergedDatasets/Merged_v030/Merged_Melb15_ttH_030_DxAOD_p2559/tops/410000.PowhegPythiaEvtGen_P2012_ttbar_hdamp172p5_nonallhad.root",
        "/coepp/cephfs/mel/mmilesi/ttH/MiniNTup/25ns_v7/25ns_v7/tops/410000.PowhegPythiaEvtGen_P2012_ttbar_hdamp172p5_nonallhad.root"
    )[bool(useGroupNTup)]
    #myfilename = ("/coepp/cephfs/mel/mmilesi/ttH/MergedDatasets/Merged_v031/Merged_Melb15_ttH_031-01_DxAOD_p2559/tops/410000.PowhegPythiaEvtGen_P2012_ttbar_hdamp172p5_nonallhad.root","TO_BE_ADDED")[bool(useGroupNTup)]

    myfile = TFile(myfilename)
    mytree = gDirectory.Get("physics")

    gROOT.LoadMacro(
        "$ROOTCOREBIN/user_scripts/HTopMultilepAnalysis/ROOT_TTreeFormulas/largeEtaEvent.cxx+"
    )
    from ROOT import largeEtaEvent

    mytree_weight = "3.209 * mcEventWeight * weight_pileup * weight_lepton_trig_HTop[0] * weight_lepton_reco_HTop[0] * weight_lepton_iso_HTop[0] * weight_lepton_ID_HTop[0] * weight_lepton_TTVA_HTop[0] * weight_jet_JVT_HTop[0] * weight_jet_MV2c20_SFFix77[0]"
    trig_dec = "( passHLT == 1 )"
    trigmatching = "( ( lep_isTrigMatched[0] == 1 && ( ( lep_flavour[0] == 11 && lep_pt[0] > 25e3 ) || ( lep_flavour[0] == 13 && lep_pt[0] > 21e3 ) ) ) || ( lep_isTrigMatched[1] == 1 && ( ( lep_flavour[1] == 11 && lep_pt[1] > 25e3 ) || ( lep_flavour[1] == 13 && lep_pt[1] > 21e3 ) ) ) )"
    lep_tag_trigmatch = "( lep_tag_isTightSelected[0] == 1 && lep_tag_isTrigMatched[0] == 1 && ( ( lep_tag_flavour[0] == 11 && lep_tag_pt[0] > 25e3 ) || ( lep_tag_flavour[0] == 13 && lep_tag_pt[0] > 21e3 ) ) )"
    el_eta = "( nel == 0 || ( nel > 0 && Max$( TMath::Abs(el_caloCluster_eta) ) < 1.37 ) )"
    nbjets = "( njets_mv2c20_Fix77 > 0 )"
    njets = "( njets > 1 && njets <= 4 )"
    nleptons = "( nlep == 2 && Min$( lep_pt ) > 10e3 )"
    flavour_cut = "( 1 )"
    same_sign = "( isSS01 == 1 )"
    tau_veto = "( ntau == 0 )"
    zpeak_veto = "( ( nmuon == 1 && nel == 1 ) || ( TMath::Abs( mll01 - 91.187e3 ) > 7.5e3 ) )"
    truth_cut = "( 1 )"
    if useTruth:
        # Select non-prompt or QMisID probe leptons
        #
        truth_cut = "( isMC==0 || ( isMC==1 && ( ( lep_probe_truthType[0] != 6 && lep_probe_truthType[0] != 2 ) || ( lep_probe_isChFlip[0] == 1 ) ) ) )"

    if useGroupNTup:
        mytree_weight = "3.209 * mcWeightOrg * pileupEventWeight_090 * weight_tag * weight_probe * JVT_EventWeight * MV2c20_77_EventWeight"
        trig_dec = "( passEventCleaning == 1 && ( isMC == 1 && HLT_e24_lhmedium_L1EM18VH == 1 ) || ( isMC == 0 && HLT_e24_lhmedium_L1EM20VH == 1 ) || ( HLT_e60_lhmedium == 1 ) || ( HLT_e120_lhloose == 1 ) || ( HLT_mu20_iloose_L1MU15 == 1 ) || ( HLT_mu50 == 1 ) )"
        trigmatching = "( ( lep_isTrigMatch_0 == 1 && ( ( TMath::Abs( lep_ID_0 ) == 11 && lep_Pt_0 > 25e3 ) || ( TMath::Abs( lep_ID_0 ) == 13 && lep_Pt_0 > 21e3 ) ) ) || ( lep_isTrigMatch_1 == 1 && ( ( TMath::Abs( lep_ID_1 ) == 11 && lep_Pt_1 > 25e3 ) || ( TMath::Abs( lep_ID_1 ) == 13 && lep_Pt_1 > 21e3 ) ) ) )"
        lep_tag_trigmatch = "( lep_Tag_isTightSelected == 1 && lep_Tag_isTrigMatch == 1 && ( ( TMath::Abs( lep_Tag_ID ) == 11 && lep_Tag_Pt > 25e3 ) || ( TMath::Abs( lep_Tag_ID ) == 13 && lep_Tag_Pt > 21e3 ) ) )"
        el_eta = "( largeEtaEvent( nelectrons,lep_ID_0,lep_ID_1,lep_EtaBE2_0,lep_EtaBE2_1 ) == 0 )"
        nbjets = "( nJets_OR_MV2c20_77 > 0 )"
        njets = "( nJets_OR > 1 && nJets_OR <= 4 )"
        nleptons = "( nleptons == 2 && ( lep_Pt_0 > 10e3 && lep_Pt_1 > 10e3 ) )"
        flavour_cut = "( 1 )"
        same_sign = "( isSS01 == 1 )"
        tau_veto = "( nTaus_OR_Pt25 == 0 )"
        zpeak_veto = "( ( nmuons == 1 && nelectrons == 1 ) || ( TMath::Abs( Mll01 - 91.187e3 ) > 7.5e3 ) )"
        truth_cut = "( 1 )"
        if useTruth:
            # Select non-prompt or QMisID probe leptons
            #
            truth_cut = "( isMC==0 || ( isMC==1 && lep_Probe_isPrompt != 1 ) )"

    hist_list = []

    basecut = "(" + trig_dec + " && " + trigmatching + " && " + lep_tag_trigmatch + " && " + el_eta + " && " + njets + " && " + nbjets + " && " + nleptons + " && " + flavour_cut + " && " + same_sign + " && " + tau_veto + " && " + zpeak_veto + " && " + truth_cut + " && "

    varProbeType = ('lep_probe_truthType', 'TO_BE_ADDED')[bool(useGroupNTup)]
    varProbeOrigin = ('lep_probe_truthOrigin',
                      'TO_BE_ADDED')[bool(useGroupNTup)]
    varProbeChFlip = ('lep_probe_isChFlip',
                      'lep_Probe_isBremsElec')[bool(useGroupNTup)]

    varTagType = ('lep_tag_truthType', 'TO_BE_ADDED')[bool(useGroupNTup)]
    varTagOrigin = ('lep_tag_truthOrigin', 'TO_BE_ADDED')[bool(useGroupNTup)]
    varTagChFlip = ('lep_tag_isChFlip',
                    'lep_Tag_isBremsElec')[bool(useGroupNTup)]

    # ------------
    #    Muons
    # ------------

    sel_FAKE_MU_PROBE_T = basecut + "( ( isProbeMuEvent == 1 ) && ( muon_probe_isTightSelected[0] == 1 ) ) )"
    sel_FAKE_MU_PROBE_L = basecut + "( ( isProbeMuEvent == 1 ) && ( muon_probe_isTightSelected[0] == 0 ) ) )"

    if useGroupNTup:
        sel_FAKE_MU_PROBE_T = basecut + "( ( TMath::Abs( lep_Probe_ID ) == 13 ) && ( lep_Probe_isTightSelected == 1 ) ) )"
        sel_FAKE_MU_PROBE_L = basecut + "( ( TMath::Abs( lep_Probe_ID ) == 13 ) && ( lep_Probe_isTightSelected == 0 ) ) )"

    print "sel_FAKE_MU_PROBE_T: \n", sel_FAKE_MU_PROBE_T
    print "sel_FAKE_MU_PROBE_L: \n", sel_FAKE_MU_PROBE_L

    h_FAKE_MU_PROBE_T_type_VS_origin = TH2D("FAKE_MU_PROBE_T_type_VS_origin",
                                            "FAKE_MU_PROBE_T_type_VS_origin",
                                            18, 0.0, 18.0, 40, 0.0, 40.0)
    hist_list.append(h_FAKE_MU_PROBE_T_type_VS_origin)
    h_FAKE_MU_PROBE_T_type_VS_origin.GetXaxis().SetTitle(
        "Probe lep (T) truthType")
    h_FAKE_MU_PROBE_T_type_VS_origin.GetYaxis().SetTitle(
        "Probe lep (T) truthOrigin")
    h_FAKE_MU_PROBE_L_type_VS_origin = TH2D("FAKE_MU_PROBE_L_type_VS_origin",
                                            "FAKE_MU_PROBE_L_type_VS_origin",
                                            18, 0.0, 18.0, 40, 0.0, 40.0)
    hist_list.append(h_FAKE_MU_PROBE_L_type_VS_origin)
    h_FAKE_MU_PROBE_L_type_VS_origin.GetXaxis().SetTitle(
        "Probe lep (L!T) truthType")
    h_FAKE_MU_PROBE_L_type_VS_origin.GetYaxis().SetTitle(
        "Probe lep (L!T) truthOrigin")

    mytree.Project("FAKE_MU_PROBE_T_type_VS_origin",
                   varProbeOrigin + ":" + varProbeType,
                   "%s * (%s)" % (mytree_weight, sel_FAKE_MU_PROBE_T), "text")
    mytree.Project("FAKE_MU_PROBE_L_type_VS_origin",
                   varProbeOrigin + ":" + varProbeType,
                   "%s * (%s)" % (mytree_weight, sel_FAKE_MU_PROBE_L), "text")

    # Normalise to unity
    #
    if doNorm:
        if h_FAKE_MU_PROBE_T_type_VS_origin.Integral() > 0:
            h_FAKE_MU_PROBE_T_type_VS_origin.Scale(
                1.0 / h_FAKE_MU_PROBE_T_type_VS_origin.Integral())
        if h_FAKE_MU_PROBE_L_type_VS_origin.Integral() > 0:
            h_FAKE_MU_PROBE_L_type_VS_origin.Scale(
                1.0 / h_FAKE_MU_PROBE_L_type_VS_origin.Integral())

    # -----------------------------------------

    h_FAKE_MU_TAG_T_type_VS_origin = TH2D("FAKE_MU_TAG_T_type_VS_origin",
                                          "FAKE_MU_TAG_T_type_VS_origin", 18,
                                          0.0, 18.0, 40, 0.0, 40.0)
    hist_list.append(h_FAKE_MU_TAG_T_type_VS_origin)
    h_FAKE_MU_TAG_T_type_VS_origin.GetXaxis().SetTitle(
        "Tag lep ( Probe (T) ) truthType")
    h_FAKE_MU_TAG_T_type_VS_origin.GetYaxis().SetTitle(
        "Tag lep ( Probe (T) ) truthOrigin")
    h_FAKE_MU_TAG_L_type_VS_origin = TH2D("FAKE_MU_TAG_L_type_VS_origin",
                                          "FAKE_MU_TAG_L_type_VS_origin", 18,
                                          0.0, 18.0, 40, 0.0, 40.0)
    hist_list.append(h_FAKE_MU_TAG_L_type_VS_origin)
    h_FAKE_MU_TAG_L_type_VS_origin.GetXaxis().SetTitle(
        "Tag lep ( Probe (L!T) ) truthType")
    h_FAKE_MU_TAG_L_type_VS_origin.GetYaxis().SetTitle(
        "Tag lep ( Probe (L!T) ) truthOrigin")

    mytree.Project("FAKE_MU_TAG_T_type_VS_origin",
                   varTagOrigin + ":" + varTagType,
                   "%s * (%s)" % (mytree_weight, sel_FAKE_MU_PROBE_T), "text")
    mytree.Project("FAKE_MU_TAG_L_type_VS_origin",
                   varTagOrigin + ":" + varTagType,
                   "%s * (%s)" % (mytree_weight, sel_FAKE_MU_PROBE_L), "text")

    # Normalise to unity
    #
    if doNorm:
        if h_FAKE_MU_TAG_T_type_VS_origin.Integral() > 0:
            h_FAKE_MU_TAG_T_type_VS_origin.Scale(
                1.0 / h_FAKE_MU_TAG_T_type_VS_origin.Integral())
        if h_FAKE_MU_TAG_L_type_VS_origin.Integral() > 0:
            h_FAKE_MU_TAG_L_type_VS_origin.Scale(
                1.0 / h_FAKE_MU_TAG_L_type_VS_origin.Integral())

    #--------------------------------------------------------------------------------
    # probe truthOrigin VS tag truthOrigin
    """
  h_FAKE_MU_PROBE_T_ProbeOrigin_VS_TagOrigin = TH2D("FAKE_MU_PROBE_T_ProbeOrigin_VS_TagOrigin", "FAKE_MU_PROBE_T_ProbeOrigin_VS_TagOrigin", 40, 0.0, 40.0, 40, 0.0, 40.0)
  hist_list.append(h_FAKE_MU_PROBE_T_ProbeOrigin_VS_TagOrigin)
  h_FAKE_MU_PROBE_T_ProbeOrigin_VS_TagOrigin.GetXaxis().SetTitle("Tag lep (T) truthOrigin")
  h_FAKE_MU_PROBE_T_ProbeOrigin_VS_TagOrigin.GetYaxis().SetTitle("Probe lep (T) truthOrigin")
  h_FAKE_MU_PROBE_L_ProbeOrigin_VS_TagOrigin = TH2D("FAKE_MU_PROBE_L_ProbeOrigin_VS_TagOrigin", "FAKE_MU_PROBE_L_ProbeOrigin_VS_TagOrigin", 40, 0.0, 40.0, 40, 0.0, 40.0)
  hist_list.append(h_FAKE_MU_PROBE_L_ProbeOrigin_VS_TagOrigin)
  h_FAKE_MU_PROBE_L_ProbeOrigin_VS_TagOrigin.GetXaxis().SetTitle("Tag lep (L!T) truthOrigin")
  h_FAKE_MU_PROBE_L_ProbeOrigin_VS_TagOrigin.GetYaxis().SetTitle("Probe lep (L!T) truthOrigin")

  mytree.Project("FAKE_MU_PROBE_T_ProbeOrigin_VS_TagOrigin", varProbeOrigin + ":" + varTagOrigin, "%s * (%s)" %(mytree_weight, sel_FAKE_MU_PROBE_T), "text" )
  mytree.Project("FAKE_MU_PROBE_L_ProbeOrigin_VS_TagOrigin", varProbeOrigin + ":" + varTagOrigin, "%s * (%s)" %(mytree_weight, sel_FAKE_MU_PROBE_L), "text" )

  h_FAKE_MU_PROBE_T_ProbeOrigin_VS_TagOrigin.Scale(1.0/h_FAKE_MU_PROBE_T_ProbeOrigin_VS_TagOrigin.Integral())
  h_FAKE_MU_PROBE_L_ProbeOrigin_VS_TagOrigin.Scale(1.0/h_FAKE_MU_PROBE_L_ProbeOrigin_VS_TagOrigin.Integral())
  """

    # ------------
    #  Electrons
    # ------------

    sel_FAKE_EL_PROBE_T = basecut + "( ( isProbeElEvent == 1 ) && ( el_probe_isTightSelected[0] == 1 ) ) )"
    sel_FAKE_EL_PROBE_L = basecut + "( ( isProbeElEvent == 1 ) && ( el_probe_isTightSelected[0] == 0 ) ) )"

    if useGroupNTup:
        sel_FAKE_EL_PROBE_T = basecut + "( ( TMath::Abs( lep_Probe_ID ) == 11 ) && ( lep_Probe_isTightSelected == 1 ) ) )"
        sel_FAKE_EL_PROBE_L = basecut + "( ( TMath::Abs( lep_Probe_ID ) == 11 ) && ( lep_Probe_isTightSelected == 0 ) ) )"

    print "sel_FAKE_EL_PROBE_T: \n", sel_FAKE_EL_PROBE_T
    print "sel_FAKE_EL_PROBE_L: \n", sel_FAKE_EL_PROBE_L

    h_FAKE_EL_PROBE_T_type_VS_origin = TH2D("FAKE_EL_PROBE_T_type_VS_origin",
                                            "FAKE_EL_PROBE_T_type_VS_origin",
                                            18, 0.0, 18.0, 40, 0.0, 40.0)
    hist_list.append(h_FAKE_EL_PROBE_T_type_VS_origin)
    h_FAKE_EL_PROBE_T_type_VS_origin.GetXaxis().SetTitle(
        "Probe lep (T) truthType")
    h_FAKE_EL_PROBE_T_type_VS_origin.GetYaxis().SetTitle(
        "Probe lep (T) truthOrigin")
    h_FAKE_EL_PROBE_L_type_VS_origin = TH2D("FAKE_EL_PROBE_L_type_VS_origin",
                                            "FAKE_EL_PROBE_L_type_VS_origin",
                                            18, 0.0, 18.0, 40, 0.0, 40.0)
    hist_list.append(h_FAKE_EL_PROBE_L_type_VS_origin)
    h_FAKE_EL_PROBE_L_type_VS_origin.GetXaxis().SetTitle(
        "Probe lep (L!T) truthType")
    h_FAKE_EL_PROBE_L_type_VS_origin.GetYaxis().SetTitle(
        "Probe lep (L!T) truthOrigin")

    h_FAKE_EL_PROBE_T_isChFlip = TH1D("FAKE_EL_PROBE_T_isChFlip",
                                      "FAKE_EL_PROBE_T_isChFlip", 2, -0.5, 1.5)
    hist_list.append(h_FAKE_EL_PROBE_T_isChFlip)
    h_FAKE_EL_PROBE_T_isChFlip.GetXaxis().SetTitle("Probe lep (T) isChFlip")
    h_FAKE_EL_PROBE_L_isChFlip = TH1D("FAKE_EL_PROBE_L_isChFlip",
                                      "FAKE_EL_PROBE_L_isChFlip", 2, -0.5, 1.5)
    hist_list.append(h_FAKE_EL_PROBE_L_isChFlip)
    h_FAKE_EL_PROBE_L_isChFlip.GetXaxis().SetTitle("Probe lep (L!T) isChFlip")

    mytree.Project("FAKE_EL_PROBE_T_type_VS_origin",
                   varProbeOrigin + ":" + varProbeType,
                   "%s * (%s)" % (mytree_weight, sel_FAKE_EL_PROBE_T), "text")
    mytree.Project("FAKE_EL_PROBE_L_type_VS_origin",
                   varProbeOrigin + ":" + varProbeType,
                   "%s * (%s)" % (mytree_weight, sel_FAKE_EL_PROBE_L), "text")
    #mytree.Project("FAKE_EL_PROBE_T_isChFlip", varProbeChFlip, "%s * (%s)" %(mytree_weight, sel_FAKE_EL_PROBE_T), "text" )
    #mytree.Project("FAKE_EL_PROBE_L_isChFlip", varProbeChFlip, "%s * (%s)" %(mytree_weight, sel_FAKE_EL_PROBE_L), "text" )

    # Normalise to unity
    #
    if doNorm:
        if h_FAKE_EL_PROBE_T_type_VS_origin.Integral() > 0:
            h_FAKE_EL_PROBE_T_type_VS_origin.Scale(
                1.0 / h_FAKE_EL_PROBE_T_type_VS_origin.Integral())
        if h_FAKE_EL_PROBE_L_type_VS_origin.Integral() > 0:
            h_FAKE_EL_PROBE_L_type_VS_origin.Scale(
                1.0 / h_FAKE_EL_PROBE_L_type_VS_origin.Integral())
        if h_FAKE_EL_PROBE_T_isChFlip.Integral() > 0:
            h_FAKE_EL_PROBE_T_isChFlip.Scale(
                1.0 / h_FAKE_EL_PROBE_T_isChFlip.Integral())
        if h_FAKE_EL_PROBE_L_isChFlip.Integral() > 0:
            h_FAKE_EL_PROBE_L_isChFlip.Scale(
                1.0 / h_FAKE_EL_PROBE_L_isChFlip.Integral())

    # -----------------------------------------

    h_FAKE_EL_TAG_T_type_VS_origin = TH2D("FAKE_EL_TAG_T_type_VS_origin",
                                          "FAKE_EL_TAG_T_type_VS_origin", 18,
                                          0.0, 18.0, 40, 0.0, 40.0)
    hist_list.append(h_FAKE_EL_TAG_T_type_VS_origin)
    h_FAKE_EL_TAG_T_type_VS_origin.GetXaxis().SetTitle(
        "Tag lep ( Probe (T) ) truthType")
    h_FAKE_EL_TAG_T_type_VS_origin.GetYaxis().SetTitle(
        "Tag lep ( Probe (T) ) truthOrigin")
    h_FAKE_EL_TAG_L_type_VS_origin = TH2D("FAKE_EL_TAG_L_type_VS_origin",
                                          "FAKE_EL_TAG_L_type_VS_origin", 18,
                                          0.0, 18.0, 40, 0.0, 40.0)
    hist_list.append(h_FAKE_EL_TAG_L_type_VS_origin)
    h_FAKE_EL_TAG_L_type_VS_origin.GetXaxis().SetTitle(
        "Tag lep ( Probe (L!T) ) truthType")
    h_FAKE_EL_TAG_L_type_VS_origin.GetYaxis().SetTitle(
        "Tag lep ( Probe (L!T) ) truthOrigin")

    mytree.Project("FAKE_EL_TAG_T_type_VS_origin",
                   varTagOrigin + ":" + varTagType,
                   "%s * (%s)" % (mytree_weight, sel_FAKE_EL_PROBE_T), "text")
    mytree.Project("FAKE_EL_TAG_L_type_VS_origin",
                   varTagOrigin + ":" + varTagType,
                   "%s * (%s)" % (mytree_weight, sel_FAKE_EL_PROBE_L), "text")

    # Normalise to unity
    #
    if doNorm:
        if h_FAKE_EL_TAG_T_type_VS_origin.Integral() > 0:
            h_FAKE_EL_TAG_T_type_VS_origin.Scale(
                1 / h_FAKE_EL_TAG_T_type_VS_origin.Integral())
        if h_FAKE_EL_TAG_L_type_VS_origin.Integral() > 0:
            h_FAKE_EL_TAG_L_type_VS_origin.Scale(
                1 / h_FAKE_EL_TAG_L_type_VS_origin.Integral())

    #--------------------------------------------------------------------------------
    # probe truthOrigin VS tag truthOrigin
    """
  h_FAKE_EL_PROBE_T_ProbeOrigin_VS_TagOrigin = TH2D("FAKE_EL_PROBE_T_ProbeOrigin_VS_TagOrigin", "FAKE_EL_PROBE_T_ProbeOrigin_VS_TagOrigin", 40, 0.0, 40.0, 40, 0.0, 40.0)
  hist_list.append(h_FAKE_EL_PROBE_T_ProbeOrigin_VS_TagOrigin)
  h_FAKE_EL_PROBE_T_ProbeOrigin_VS_TagOrigin.GetXaxis().SetTitle("Tag lep (T) truthOrigin")
  h_FAKE_EL_PROBE_T_ProbeOrigin_VS_TagOrigin.GetYaxis().SetTitle("Probe lep (T) truthOrigin")
  h_FAKE_EL_PROBE_L_ProbeOrigin_VS_TagOrigin = TH2D("FAKE_EL_PROBE_L_ProbeOrigin_VS_TagOrigin", "FAKE_EL_PROBE_L_ProbeOrigin_VS_TagOrigin", 40, 0.0, 40.0, 40, 0.0, 40.0)
  hist_list.append(h_FAKE_EL_PROBE_L_ProbeOrigin_VS_TagOrigin)
  h_FAKE_EL_PROBE_L_ProbeOrigin_VS_TagOrigin.GetXaxis().SetTitle("Tag lep (L!T) truthOrigin")
  h_FAKE_EL_PROBE_L_ProbeOrigin_VS_TagOrigin.GetYaxis().SetTitle("Probe lep (L!T) truthOrigin")

  mytree.Project("FAKE_EL_PROBE_T_ProbeOrigin_VS_TagOrigin",  varProbeOrigin + ":" + varTagOrigin, "%s * (%s)" %(mytree_weight, sel_FAKE_EL_PROBE_T), "text" )
  mytree.Project("FAKE_EL_PROBE_L_ProbeOrigin_VS_TagOrigin",  varProbeOrigin + ":" + varTagOrigin, "%s * (%s)" %(mytree_weight, sel_FAKE_EL_PROBE_L), "text" )

  h_FAKE_EL_PROBE_T_ProbeOrigin_VS_TagOrigin.Scale(1.0/h_FAKE_EL_PROBE_T_ProbeOrigin_VS_TagOrigin.Integral())
  h_FAKE_EL_PROBE_L_ProbeOrigin_VS_TagOrigin.Scale(1.0/h_FAKE_EL_PROBE_L_ProbeOrigin_VS_TagOrigin.Integral())
  """

    # ------------------------------------------------------------------

    set_fancy_2D_style()

    gStyle.SetPaintTextFormat("2.1f")

    for hist in hist_list:

        #c = TCanvas("c1","Temp",50,50,700,900)
        c = TCanvas("c1", "Temp", 50, 50, 800, 900)

        legend = TLegend(0.2, 0.8, 0.7, 0.85)
        # (x1,y1 (--> bottom left corner), x2, y2 (--> top right corner) )
        legend.SetHeader("2 Lep SS Fake CR")
        legend.SetBorderSize(0)  # no border
        legend.SetFillStyle(0)
        # Legend transparent background
        legend.SetTextSize(0.04)  # Increase entry font size!
        legend.SetTextFont(42)  # Helvetica
        leg_ATLAS = TLatex()
        leg_lumi = TLatex()
        leg_ATLAS.SetTextSize(0.03)
        leg_ATLAS.SetNDC()
        leg_lumi.SetTextSize(0.03)
        leg_lumi.SetNDC()

        hist.Draw("colz text")

        legend.Draw()
        leg_ATLAS.DrawLatex(0.2, 0.75, "#bf{#it{ATLAS}} Work In Progress")
        leg_lumi.DrawLatex(0.2, 0.7,
                           "#sqrt{s} = 13 TeV, #int L dt = 3.2 fb^{-1}")

        canvasname = (hist.GetName(),
                      hist.GetName() + "_TruthCut")[bool(useTruth)]
        c.SaveAs(canvasname + ".png")
Beispiel #18
0
    print ihist.GetName()
    #ihist.SetMaximum(10000)
    #ihist.GetYaxis().SetTitle("a.u")
    #ihist.Scale(1/300000.)
    if not legOnly:
        ihist.Draw("same, hist")

xTitle = h_top.GetXaxis().GetTitle()
yTitle = h_top.GetYaxis().GetTitle()

setTitle(hs, xTitle, yTitle)
gPad.RedrawAxis()

ll = TLatex()
ll.SetNDC(kTRUE)
ll.SetTextSize(0.05)
ll.DrawLatex(0.63, 0.92, "3000 fb^{-1} (14 TeV)")

prel = TLatex()
prel.SetNDC(kTRUE)
prel.SetTextFont(52)
prel.SetTextSize(0.05)
prel.DrawLatex(0.18, 0.92, "Simulation")

cms = TLatex()
cms.SetNDC(kTRUE)
cms.SetTextFont(61)
cms.SetTextSize(0.05)
cms.DrawLatex(0.10, 0.92, "CMS")
if var != 'hTPrimeMRecoBoost' and not legOnly:
    leg.Draw()
Beispiel #19
0
def drawEtaValues():
    """Function to draw the eta.

    Function to draw the eta references on top of an already existing
    TCanvas. The lines and labels drawn are collected inside a list and
    the list is returned to the user to extend the live of the objects
    contained, otherwise no lines and labels will be drawn, since they
    will be garbage-collected as soon as this function returns.
    """

    # Add eta labels
    keep_alive = []
    etas = [-3.4, -3.0, -2.8, -2.6, -2.4, -2.2,
            -2.0, -1.8, -1.6, -1.4, -1.2, -1., -0.8, -0.6, -0.4, -0.2, 0., 0.2,
            0.4, 0.6, 0.8, 1., 1.2, 1.4, 1.6, 1.8, 2., 2.2, 2.4, 2.6, 2.8, 3.0,
            3.4]

    etax = 2940.
    etay = 1240.
    lineL = 100.
    offT = 10.

    for ieta in etas:
        th = 2*atan(exp(-ieta))
        talign = 21

        #IP
        lineh = TLine(-20.,0.,20.,0.)
        lineh.Draw()
        linev = TLine(0.,-10.,0.,10.)
        linev.Draw()
        keep_alive.append(lineh)
        keep_alive.append(linev)

        x1 = 0
        y1 = 0
        if ieta>-1.6 and ieta<1.6:
            x1 = etay/tan(th)
            y1 = etay
        elif ieta <=-1.6:
            x1 = -etax
            y1 = -etax*tan(th)
            talign = 11
        elif ieta>=1.6:
            x1 = etax
            y1 = etax*tan(th)
            talign = 31
        x2 = x1+lineL*cos(th)
        y2 = y1+lineL*sin(th)
        xt = x2
        yt = y2+offT

        line1 = TLine(x1,y1,x2,y2)
        line1.Draw()
        keep_alive.append(line1)

        text = "%3.1f" % ieta
        t1 = TLatex(xt, yt, '%s' % ('#eta = 0' if ieta == 0 else text))
        t1.SetTextSize(0.03)
        t1.SetTextAlign(talign)
        t1.Draw()
        keep_alive.append(t1)
    return keep_alive
Beispiel #20
0
#c4.SetLogy(1)

#expected95.SetMinimum(0.0001);
expected95.SetMaximum(0.0057)
expected95.Draw("a3")
expected95.GetXaxis().SetTitle("Diphoton Mass [GeV/c^{2}]")
expected95.GetYaxis().SetTitle("#sigma(G_{RS} #rightarrow #gamma #gamma)[pb]")
expected68.Draw("3same")
expected_p.Draw("csame")
observed_p.Draw("cpsame")
theory.Draw("same")

latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.04)
latex.SetTextAlign(31)  # align right
latex.DrawLatex(0.45, 0.95, "CMS Preliminary")

latex2 = TLatex()
latex2.SetNDC()
latex2.SetTextSize(0.04)
latex2.SetTextAlign(31)  # align right
latex2.DrawLatex(0.87, 0.95, "19.37 fb^{-1} at #sqrt{s} = 8 TeV")

latex4 = TLatex()
latex4.SetNDC()
latex4.SetTextSize(0.04)
latex4.SetTextAlign(31)  # align right
latex4.DrawLatex(0.80, 0.87, "")
Beispiel #21
0
    def show(self, outDir, genPseudoData):
        if len(self.mc) == 0:
            print '%s is empty' % self.name
            return
        canvas = TCanvas('c_' + self.name, 'C', 600, 600)
        canvas.cd()
        t1 = TPad("t1", "t1", 0.0, 0.20, 1.0, 1.0)
        t1.SetBottomMargin(0)
        t1.Draw()
        t1.cd()
        self.garbageList.append(t1)

        frame = None
        # leg = TLegend(0.15,0.9,0.9,0.95)
        leg = TLegend(0.6, 0.7, 0.92, 0.89)
        leg.SetBorderSize(0)
        leg.SetFillStyle(0)
        leg.SetTextFont(42)
        leg.SetTextSize(0.04)
        nlegCols = 0

        maxY = 1.0
        if self.data is not None:
            leg.AddEntry(self.data, self.data.GetTitle(), 'p')
            frame = self.data.Clone('frame')
            self.garbageList.append(frame)
            maxY = self.data.GetMaximum() * 1.1
            frame.Reset('ICE')
        elif genPseudoData:
            leg.AddEntry('pseudodata', 'Pseudo-data', 'p')

        totalMC = None
        stack = THStack('mc', 'mc')
        for h in self.mc:
            stack.Add(h, 'hist')
            leg.AddEntry(h, h.GetTitle(), 'f')
            nlegCols = nlegCols + 1
            if totalMC is None:
                totalMC = h.Clone('totalmc')
                self.garbageList.append(totalMC)
                totalMC.SetDirectory(0)
            else:
                totalMC.Add(h)

        if totalMC is not None:
            maxY = max(totalMC.GetMaximum(), maxY)
            if frame is None:
                frame = totalMC.Clone('frame')
                frame.Reset('ICE')
                self.garbageList.append(frame)
            if genPseudoData and self.data is None and totalMC.ClassName(
            ).find('TH1') >= 0:
                self.data = totalMC.Clone('pseudodata')
                self.data.Sumw2()
                self.data.SetLineColor(1)
                self.data.SetMarkerStyle(20)
                self.data.SetMarkerColor(1)
                self.data.SetFillStyle(0)
                self.data.SetFillColor(0)
                if self.name.find('flow') < 0:
                    self.data.Reset('ICE')
                    for i in xrange(0, int(totalMC.Integral())):
                        self.data.Fill(totalMC.GetRandom())

        if self.data is not None: nlegCols = nlegCols + 1
        if nlegCols == 0:
            print '%s is empty' % self.name
            return

        frame.GetYaxis().SetRangeUser(1e-2, 1.2 * maxY)
        frame.SetDirectory(0)
        frame.Draw()
        frame.GetYaxis().SetTitleOffset(1.6)
        stack.Draw('hist same')
        if self.data is not None: self.data.Draw('P same')
        # leg.SetNColumns(nlegCols)
        leg.SetNColumns(2)
        leg.Draw()

        ## Draw CMS Preliminary label
        tlat = TLatex()
        tlat.SetNDC()
        tlat.SetTextFont(62)
        tlat.SetTextSize(0.04)
        tlat.SetTextAlign(31)
        #        prelim_text = 'CMS Preliminary, #sqrt{s} = 8 TeV'
        prelim_text = 'CMS Preliminary, #sqrt{s} = 13 TeV'
        tlat.DrawLatex(0.92, 0.95, prelim_text)

        if totalMC is None or self.data is None:
            t1.SetPad(0, 0, 1, 1)
            t1.SetBottomMargin(0.12)
        else:
            canvas.cd()
            t2 = TPad("t2", "t2", 0.0, 0.0, 1.0, 0.2)
            self.garbageList.append(t2)
            t2.SetTopMargin(0)
            t2.SetBottomMargin(0.4)
            t2.SetGridy()
            t2.Draw()
            t2.cd()
            ratio = self.data.Clone('ratio')
            self.garbageList.append(ratio)
            ratio.Divide(totalMC)
            ratio.SetDirectory(0)
            ratio.Draw('e1')
            ratio.GetYaxis().SetRangeUser(0.62, 1.38)
            ratio.GetYaxis().SetTitle('Data/#SigmaBkg')
            ratio.GetYaxis().SetNdivisions(5)
            ratio.GetYaxis().SetLabelSize(0.15)
            ratio.GetYaxis().SetTitleSize(0.18)
            ratio.GetXaxis().SetLabelSize(0.18)
            ratio.GetXaxis().SetTitleSize(0.2)
            ratio.GetYaxis().SetTitleOffset(0.3)
            ratio.GetXaxis().SetTitleOffset(0.8)

        canvas.cd()
        canvas.Modified()
        canvas.Update()
        for ext in ['pdf', 'png']:
            canvas.SaveAs(outDir + '/' + self.name + '.' + ext)
Beispiel #22
0
    def draw_atlas_label(self,
                         luminosity=None,
                         sqrt_s=None,
                         custom_label=None,
                         atlas_label=None):
        """Draws an ATLAS stamp on the plot, with an optional categorization
        label.

        It is recommended that you construct the Plot with plot_header = True
        in order to make space for the label.

        Args:
            luminosity: The integrated luminosity, in pb^-1
            sqrt_s: The center of mass energy, in MeV
            label: The label to put after 'ATLAS', None to exclude the 'ATLAS'
                categorization entirely
        """
        # Change context to the plot pad
        self._plot.cd()

        # Create the latex object
        # TODO: Consider using TPaveText to overwrite drawn graphs and
        # histograms. At least for scatter plots.
        # TODO: Increase readability: Create two sets of constants -
        # one for plots with ratio and one for plots without. Select the
        # correct one in draw_ratio_histogram.
        stamp = TLatex()

        # Style it
        stamp.SetTextColor(self.PLOT_ATLAS_STAMP_TEXT_COLOR)
        stamp.SetTextSize(
            (self.PLOT_ATLAS_STAMP_TEXT_SIZE_WITH_RATIO
             if self._ratio_plot else self.PLOT_ATLAS_STAMP_TEXT_SIZE))
        stamp.SetTextFont(self.PLOT_ATLAS_STAMP_TEXT_FONT)
        stamp.SetNDC()

        top = (self.PLOT_ATLAS_STAMP_TOP_WITH_RATIO
               if self._ratio_plot else self.PLOT_ATLAS_STAMP_TOP)

        # Print an ATLAS label on top
        if atlas_label is not None:
            # Draw the label
            stamp.SetTextFont(self.PLOT_ATLAS_STAMP_ATLAS_TEXT_FONT)
            stamp.DrawLatex(self.PLOT_ATLAS_STAMP_LEFT, top, 'ATLAS')
            stamp.SetTextFont(self.PLOT_ATLAS_STAMP_TEXT_FONT)
            stamp.DrawLatex(self.PLOT_ATLAS_STAMP_ATLAS_LABEL_LEFT, top,
                            atlas_label)
            top -= (self.PLOT_ATLAS_STAMP_TEXT_SIZE_WITH_RATIO if self.
                    _ratio_plot else self.PLOT_ATLAS_STAMP_TEXT_SIZE) * 1.3

        # Draw the luminosity and sqrt(s)
        if luminosity is not None or sqrt_s is not None:
            text = ''
            if sqrt_s is not None:
                text += '#sqrt{{s}} = {0:.0f} TeV'.format(sqrt_s / 1.0e6)
                if luminosity is not None:
                    text += ', '
            if luminosity is not None:
                if luminosity >= 1000.0:
                    text += '{0:.1f} fb^{{-1}}'.format(luminosity / 1000.0)
                elif luminosity > 100.0:
                    text += '{0:.2f} fb^{{-1}}'.format(luminosity / 1000.0)
                else:
                    text += '{0:.1f} pb^{{-1}}'.format(luminosity)

            stamp.DrawLatex(self.PLOT_ATLAS_STAMP_LEFT, top, text)
            top -= (self.PLOT_ATLAS_STAMP_TEXT_SIZE_WITH_RATIO if self.
                    _ratio_plot else self.PLOT_ATLAS_STAMP_TEXT_SIZE) * 1.3

        # If requested, draw the custom label or the 'ATLAS' label,
        # preferring the former
        if custom_label is not None:
            # Draw each line of text, decreasing top for each step
            for text in [t for t in custom_label if t is not None]:
                stamp.DrawLatex(self.PLOT_ATLAS_STAMP_LEFT, top, text)
                top -= (self.PLOT_ATLAS_STAMP_TEXT_SIZE_WITH_RATIO if self.
                        _ratio_plot else self.PLOT_ATLAS_STAMP_TEXT_SIZE) * 1.3
Beispiel #23
0
    # leg_kin.Draw("same")

    # cnv.cd(2)
    # ROOT.gPad.SetTicks(1,1)
    cnv.SetTicks(1, 1)
    hmin, hmax = minmax(histos[spotsize + "_tru_E"],
                        histos[spotsize + "_rec_E"])
    histos[spotsize + "_tru_E"].Draw("hist")
    histos[spotsize + "_rec_E"].Draw("e same")
    leg_kin.Draw("same")

    s = TLatex()
    s.SetNDC(1)
    s.SetTextAlign(13)
    s.SetTextColor(ROOT.kBlack)
    s.SetTextSize(0.035)
    s.DrawLatex(
        0.52, 0.65,
        ROOT.Form("Tru: #SigmaN_{e^{+}}/BX/Shot=%.2f" % (properties["NtruP"])))
    s.DrawLatex(
        0.52, 0.60,
        ROOT.Form("Acc: #SigmaN_{e^{+}}/BX/Shot=%.2f" % (properties["NaccP"])))
    s.DrawLatex(
        0.52, 0.55,
        ROOT.Form("Rec: #SigmaN_{e^{+}}/BX/Shot=%.2f" % (properties["NrecP"])))

    cnv.SaveAs(fn + "_" + spotsize + "_CDR.pdf")
    cnv.SaveAs(allpdf)

leg_ntot = TLegend(0.15, 0.70, 0.50, 0.87)
leg_ntot.SetFillStyle(4000)  # will be transparent
ROOT.gStyle.SetPadTickX(1)
ROOT.gStyle.SetPadTickY(1)

legend = TLegend(0.15, 0.5, 0.35, 0.6)
legend2 = TLegend(0.65, 0.5, 0.85, 0.6)

l = TLatex()
l.SetNDC()
l.SetTextFont(72)
p = TLatex()
p.SetNDC()
p.SetTextFont(42)
q = TLatex()
q.SetNDC()
q.SetTextFont(42)
q.SetTextSize(0.03)
r = TLatex()
r.SetNDC()
r.SetTextFont(42)
r.SetTextSize(0.03)
s = TLatex()
s.SetNDC()
s.SetTextFont(42)
s.SetTextSize(0.03)

canvas = ROOT.TCanvas('draw', 'draw', 0, 0, 800, 800)
pad = ROOT.TPad()
canvas.cd()

infile = ROOT.TFile('../data/ntuple_v2_500.root', 'open')
intree = infile.Get('SimpleJet')
Beispiel #25
0
def setCMSLumiStyle(pad, iPosX, **kwargs):
    global outOfFrame, lumiTextSize, lumiText
    if iPosX / 10 == 0:
        outOfFrame = True
    lumiTextSize_ = lumiTextSize
    relPosX_ = kwargs.get('relPosX', relPosX)
    lumiText_ = kwargs.get('lumiText', lumiText)
    if outOfFrame:
        lumiTextSize_ *= 0.90

    if 'era' in kwargs:  # one era
        era = kwargs.get('era')
        setCMSEra(era, **kwargs)
    elif 'eras' in kwargs:  # list of multiple eras
        eras = kwargs.get('eras')
        setCMSEra(*eras, **kwargs)

    #if lumiText=="":
    #  if iPeriod==1:
    #    lumiText += lumi_7TeV
    #    lumiText += " (7 TeV)"
    #  elif iPeriod==2:
    #    lumiText += lumi_8TeV
    #    lumiText += " (8 TeV)"
    #  elif iPeriod==3:
    #    lumiText = lumi_8TeV
    #    lumiText += " (8 TeV)"
    #    lumiText += " + "
    #    lumiText += lumi_7TeV
    #    lumiText += " (7 TeV)"
    #  elif iPeriod==4:
    #    lumiText += lumi_13TeV
    #    lumiText += " (13 TeV)"
    #  elif iPeriod==7:
    #    if outOfFrame: lumiTextSize_ *= 0.85
    #    lumiText += lumi_13TeV
    #    lumiText += " (13 TeV)"
    #    lumiText += " + "
    #    lumiText += lumi_8TeV
    #    lumiText += " (8 TeV)"
    #    lumiText += " + "
    #    lumiText += lumi_7TeV
    #    lumiText += " (7 TeV)"
    #  elif iPeriod==12:
    #    lumiText += "8 TeV"
    #  else:
    #    if outOfFrame: lumiTextSize_ *= 0.90
    #    if iPeriod==13:
    #      lumiText += lumi_13TeV
    #      lumiText += " (13 TeV)"
    #    elif iPeriod==2016:
    #      lumiText += lumi_2016
    #      lumiText += " (13 TeV)"
    #    elif iPeriod==2017:
    #      lumiText += lumi_2017
    #      lumiText += " (13 TeV)"
    #    elif iPeriod==2018:
    #      lumiText += lumi_2018
    #      lumiText += " (13 TeV)"
    #    elif iPeriod==14:
    #      lumiText += lumi_14TeV
    #      lumiText += " (14 TeV, 200 PU)"
    ##print lumiText

    alignY_ = 3
    alignX_ = 2
    if iPosX == 0: alignY_ = 1
    if iPosX / 10 == 0: alignX_ = 1
    elif iPosX / 10 == 1: alignX_ = 1
    elif iPosX / 10 == 2: alignX_ = 2
    elif iPosX / 10 == 3: alignX_ = 3
    align = 10 * alignX_ + alignY_
    extraTextSize = extraOverCmsTextSize * cmsTextSize

    H = pad.GetWh() * pad.GetHNDC()
    W = pad.GetWw() * pad.GetWNDC()
    l = pad.GetLeftMargin()
    t = pad.GetTopMargin()
    r = pad.GetRightMargin()
    b = pad.GetBottomMargin()
    e = 0.025
    scale = float(H) / W if W > H else 1  # float(W)/H
    pad.cd()

    latex = TLatex()
    latex.SetNDC()
    latex.SetTextAngle(0)
    latex.SetTextColor(kBlack)
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(lumiTextSize_ * t)

    if lumiText_:
        latex.DrawLatex(1 - r, 1 - t + lumiTextOffset * t, lumiText_)

    if iPosX == 0:
        relPosX_ = relPosX_ * (50 * t * scale) * (cmsTextSize / 0.84)
        posX = l + relPosX_ * (1 - l - r)
        posY = 1 - t + lumiTextOffset * t
    else:
        posX = 0
        posY = 1 - t - relPosY * (1 - t - b)
        if iPosX % 10 <= 1:
            posX = l + relPosX_ * (1 - l - r)  # left aligned
        elif iPosX % 10 == 2:
            posX = l + 0.5 * (1 - l - r)  # centered
        elif iPosX % 10 == 3:
            posX = 1 - r - relPosX_ * (1 - l - r)  # right aligned

    if outOfFrame:
        TGaxis.SetExponentOffset(-0.12 * float(H) / W, 0.015, 'y')
        latex.SetTextFont(cmsTextFont)
        latex.SetTextAlign(11)
        latex.SetTextSize(cmsTextSize * t)
        latex.DrawLatex(l, 1 - t + lumiTextOffset * t, cmsText)
        if writeExtraText:
            latex.SetTextFont(extraTextFont)
            latex.SetTextSize(extraTextSize * t)
            latex.SetTextAlign(align)
            latex.DrawLatex(posX, posY, extraText)
    elif drawLogo:
        posX = l + 0.045 * (1 - l - r) * W / H
        posY = 1 - t - 0.045 * (1 - t - b)
        xl_0 = posX
        yl_0 = posY - 0.15
        xl_1 = posX + 0.15 * H / W
        yl_1 = posY
        CMS_logo = TASImage("CMS-BW-label.png")
        pad_logo = TPad("logo", "logo", xl_0, yl_0, xl_1, yl_1)
        pad_logo.Draw()
        pad_logo.cd()
        CMS_logo.Draw('X')
        pad_logo.Modified()
        pad.cd()
    else:
        latex.SetTextFont(cmsTextFont)
        latex.SetTextSize(cmsTextSize * t)
        latex.SetTextAlign(align)
        latex.DrawLatex(posX, posY, cmsText)
        if writeExtraText:
            latex.SetTextFont(extraTextFont)
            latex.SetTextAlign(align)
            latex.SetTextSize(extraTextSize * t)
            latex.DrawLatex(posX, posY - relExtraDY * cmsTextSize * t,
                            extraText)

    pad.Update()
        outHist[i].SetLineWidth(2)
        outHist[i].Draw("same")
        outName[i] = testFiles[i][:-5]
        outEst[i] = BGNormalization

    l = TLegend(0.40, 0.70, 0.7, 0.9, "", "brNDC")
    l.SetBorderSize(0)
    l.SetFillColor(0)
    l.SetTextSize(.03)
    #    l.AddEntry(hist_Data, "Data", "p")
    #    l.AddEntry(outHist[i], "BG Est.(one  tau Iso Reverted)", "lpf")
    #    l.AddEntry(hist_Estimation_ff, "BG Est.(both tau Iso Reverted)", "lpf")
    l.Draw()

    #Text in Histogram
    t = TLatex()
    t.SetNDC()
    t.SetTextFont(62)
    t.SetTextAlign(12)
    t.SetTextSize(0.025)
    t.DrawLatex(0.1, .92, "CMS Preliminary 2012")
    t.DrawLatex(0.5, .92, "#sqrt{s} = 8 TeV, L = 19.0 fb^{-1}")
    t.DrawLatex(0.5, .60, "Data, SS, 10 GeV Tau LooseIso")
    t.DrawLatex(0.5, .52, "Data = " + str(DataNormalization))
    for i in range(len(testFiles)):
        t.SetTextColor(i + 2)
        t.DrawLatex(0.5, .52 - ((i + 1) / 20.),
                    outName[i] + " = " + str(outEst[i]))

    canvas.SaveAs("Data_SS_10_GeV_MuTau_LooseIso.pdf")
Beispiel #27
0
def limit():
    method = ''
    channel = "bb"
    if INCLUDEACC:
        particleP = "X"
    else:
        particleP = "Z'"
    particle = 'b#bar{b}'
    multF = ZPTOBB
    THEORY = ['A1', 'B3']
    if INCLUDEACC: THEORY.append('SSM')

    suffix = "_" + BTAGGING
    if ISMC: suffix += "_MC"
    if SY: suffix += "_comb"
    #if method=="cls": suffix="_CLs"
    if INCLUDEACC: suffix += "_acc"

    if SY:
        filename = "./combine/limits/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt"
    else:
        filename = "./combine/limits/" + BTAGGING + "/" + YEAR + "_M%d.txt"
    if CATEGORY != "":
        if SY:
            if CATEGORY == 'bb_bq':
                filename = filename.replace(
                    BTAGGING + "/combined_run2/",
                    BTAGGING + "/combined_run2/" + CATEGORY + "_combined_")
            else:
                filename = filename.replace(
                    BTAGGING + "/combined_run2/", BTAGGING +
                    "/single_category/combined_run2/" + CATEGORY + "_")
        else:
            filename = filename.replace(
                BTAGGING + "/",
                BTAGGING + "/single_category/" + CATEGORY + "_")
        suffix += "_" + CATEGORY
    if ISMC: filename = filename.replace(".txt", "_MC.txt")
    mass, val = fillValues(filename)

    #print "mass =",mass
    #print "val =", val

    Obs0s = TGraph()
    Exp0s = TGraph()
    Exp1s = TGraphAsymmErrors()
    Exp2s = TGraphAsymmErrors()
    Sign = TGraph()
    pVal = TGraph()
    Best = TGraphAsymmErrors()
    Theory = {}

    for i, m in enumerate(mass):
        if not m in val:
            print "Key Error:", m, "not in value map"
            continue

        if INCLUDEACC:
            acc_factor = ACCEPTANCE[m]
        else:
            acc_factor = 1.

        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0] * multF * acc_factor)
        Exp0s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp1s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp1s.SetPointError(n, 0., 0.,
                            (val[m][3] - val[m][2]) * multF * acc_factor,
                            (val[m][4] - val[m][3]) * multF * acc_factor)
        Exp2s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp2s.SetPointError(n, 0., 0.,
                            (val[m][3] - val[m][1]) * multF * acc_factor,
                            (val[m][5] - val[m][3]) * multF * acc_factor)
        if len(val[m]) > 6: Sign.SetPoint(n, m, val[m][6])
        if len(val[m]) > 7: pVal.SetPoint(n, m, val[m][7])
        if len(val[m]) > 8: Best.SetPoint(n, m, val[m][8])
        if len(val[m]) > 10:
            Best.SetPointError(n, 0., 0., abs(val[m][9]), val[m][10])
        #print "m =", m, " --> Xsec*Br =", val[m][3]

    for t in THEORY:
        Theory[t] = TGraphAsymmErrors()
        Xs_dict = HVT[t]['Z']['XS'] if t != 'SSM' else SSM['Z']
        for m in sorted(Xs_dict.keys()):
            if INCLUDEACC and t != 'SSM':
                acc_factor = ACCEPTANCE[m]
            else:
                acc_factor = 1.
            if m < SIGNALS[0] or m > SIGNALS[-1]: continue
            #if m < mass[0] or m > mass[-1]: continue
            #if t!= 'SSM' and m>4500: continue ## I don't have the higher mass xs
            if m > 4500: continue
            XsZ, XsZ_Up, XsZ_Down = 0., 0., 0.
            if t != 'SSM':
                XsZ = 1000. * HVT[t]['Z']['XS'][m] * SSM["BrZ"][
                    m]  #assuming the same BR as the SSM Z' one
                XsZ_Up = XsZ * (1. + math.hypot(HVT[t]['Z']['QCD'][m][0] - 1.,
                                                HVT[t]['Z']['PDF'][m][0] - 1.))
                XsZ_Down = XsZ * (1. -
                                  math.hypot(1. - HVT[t]['Z']['QCD'][m][0],
                                             1. - HVT[t]['Z']['PDF'][m][0]))
            else:
                XsZ = 1000. * SSM['Z'][m] * SSM["BrZ"][m]
                XsZ_Up = XsZ * (1. +
                                math.hypot(HVT['A1']['Z']['QCD'][m][0] - 1.,
                                           HVT['A1']['Z']['PDF'][m][0] - 1.))
                XsZ_Down = XsZ * (1. -
                                  math.hypot(1. - HVT['A1']['Z']['QCD'][m][0],
                                             1. - HVT['A1']['Z']['PDF'][m][0]))

            n = Theory[t].GetN()
            Theory[t].SetPoint(n, m, XsZ * acc_factor)
            Theory[t].SetPointError(n, 0., 0., (XsZ - XsZ_Down) * acc_factor,
                                    (XsZ_Up - XsZ) * acc_factor)

            Theory[t].SetLineColor(theoryLineColor[t])
            Theory[t].SetFillColor(theoryFillColor[t])
            Theory[t].SetFillStyle(theoryFillStyle[t])
            Theory[t].SetLineWidth(2)
            #Theory[t].SetLineStyle(7)

    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp1s.SetFillColor(417)  #kGreen+1
    Exp1s.SetLineColor(417)  #kGreen+1
    Exp2s.SetFillColor(800)  #kOrange
    Exp2s.SetLineColor(800)  #kOrange
    Exp2s.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle(
        "#sigma(" + particleP + ") #bf{#it{#Beta}}(" + particleP +
        " #rightarrow " + particle +
        "){} (fb)".format(" #times #Alpha" if INCLUDEACC else ""))
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

    Sign.SetLineWidth(2)
    Sign.SetLineColor(629)
    Sign.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Sign.GetXaxis().SetTitleSize(Sign.GetXaxis().GetTitleSize() * 1.1)
    Sign.GetYaxis().SetTitle("Significance")

    pVal.SetLineWidth(2)
    pVal.SetLineColor(629)
    pVal.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    pVal.GetXaxis().SetTitleSize(pVal.GetXaxis().GetTitleSize() * 1.1)
    pVal.GetYaxis().SetTitle("local p-Value")

    Best.SetLineWidth(2)
    Best.SetLineColor(629)
    Best.SetFillColor(629)
    Best.SetFillStyle(3003)
    Best.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Best.GetXaxis().SetTitleSize(Best.GetXaxis().GetTitleSize() * 1.1)
    Best.GetYaxis().SetTitle("Best Fit (pb)")

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.050)
    Exp2s.GetYaxis().SetTitleSize(0.050)
    Exp2s.GetXaxis().SetLabelSize(0.045)
    Exp2s.GetYaxis().SetLabelSize(0.045)
    Exp2s.GetXaxis().SetTitleOffset(0.90)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    if INCLUDEACC:
        Exp2s.GetYaxis().SetRangeUser(0.05, 5.e3)
    else:
        Exp2s.GetYaxis().SetRangeUser(0.1, 5.e3)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    #Exp2s.GetXaxis().SetRangeUser(mass[0], min(mass[-1], MAXIMUM[channel] if channel in MAXIMUM else 1.e6))
    Exp2s.GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1])
    #drawAnalysis(channel)
    drawAnalysis("")
    #drawRegion(channel, True)
    drawRegion("", True)
    #drawCMS(LUMI, "Simulation Preliminary") #Preliminary
    if CATEGORY == "":
        #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
        drawCMS(LUMI, "Preliminary")
        #drawCMS(LUMI, "", suppressCMS=True)
    else:
        #drawCMS(LUMI, "Work in Progress, "+CAT_LABELS[CATEGORY], suppressCMS=True)
        drawCMS(LUMI, "Preliminary   " + CAT_LABELS[CATEGORY])
        #drawCMS(LUMI, CAT_LABELS[CATEGORY], suppressCMS=True)

    # legend
    top = 0.9
    nitems = 4 + len(THEORY)

    leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.98, top)
    #leg = TLegend(0.45, top-nitems*0.3/5., 0.98, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected", "l")
    leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    for t in THEORY:
        leg.AddEntry(Theory[t], theoryLabel[t], "fl")
    leg.Draw()
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.045)
    latex.SetTextFont(42)
    #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h")

    leg2 = TLegend(0.12, 0.225 - 2 * 0.25 / 5., 0.65, 0.225)
    leg2.SetBorderSize(0)
    leg2.SetFillStyle(0)  #1001
    leg2.SetFillColor(0)
    c1.GetPad(0).RedrawAxis()

    leg2.Draw()
    if not options.blind: Obs0s.Draw("SAME, L")
    c1.GetPad(0).Update()

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".png")
    c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".pdf")
    if 'ah' in channel or 'sl' in channel:
        c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".C")
        c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix +
                 ".root")

    for t in THEORY:
        print "Model", t, ":",
        for m in range(mass[0], mass[-1], 1):
            if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == (
                    Theory[t].Eval(m + 1) > Obs0s.Eval(m + 1)):
                print m, "(obs)",
            if not (Theory[t].Eval(m) > Exp0s.Eval(m)) == (
                    Theory[t].Eval(m + 1) > Exp0s.Eval(m + 1)):
                print m, "(exp)",
        print ""

    return  ##FIXME

    # ---------- Significance ----------
    c2 = TCanvas("c2", "Significance", 800, 600)
    c2.cd()
    c2.GetPad(0).SetTopMargin(0.06)
    c2.GetPad(0).SetRightMargin(0.05)
    c2.GetPad(0).SetTicks(1, 1)
    c2.GetPad(0).SetGridx()
    c2.GetPad(0).SetGridy()
    Sign.GetYaxis().SetRangeUser(0., 5.)
    Sign.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".png")
    c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".pdf")
    #    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".root")
    #    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".C")

    # ---------- p-Value ----------
    c3 = TCanvas("c3", "p-Value", 800, 600)
    c3.cd()
    c3.GetPad(0).SetTopMargin(0.06)
    c3.GetPad(0).SetRightMargin(0.05)
    c3.GetPad(0).SetTicks(1, 1)
    c3.GetPad(0).SetGridx()
    c3.GetPad(0).SetGridy()
    c3.GetPad(0).SetLogy()
    pVal.Draw("AL3")
    pVal.GetYaxis().SetRangeUser(2.e-7, 0.5)

    ci = [
        1., 0.317310508, 0.045500264, 0.002699796, 0.00006334, 0.000000573303,
        0.000000001973
    ]
    line = TLine()
    line.SetLineColor(922)
    line.SetLineStyle(7)
    text = TLatex()
    text.SetTextColor(922)
    text.SetTextSize(0.025)
    text.SetTextAlign(12)
    for i in range(1, len(ci) - 1):
        line.DrawLine(pVal.GetXaxis().GetXmin(), ci[i] / 2,
                      pVal.GetXaxis().GetXmax(), ci[i] / 2)
        text.DrawLatex(pVal.GetXaxis().GetXmax() * 1.01, ci[i] / 2,
                       "%d #sigma" % i)

    drawCMS(LUMI, "Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".png")
    c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".pdf")
    #    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".root")
    #    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".C")

    # --------- Best Fit ----------
    c4 = TCanvas("c4", "Best Fit", 800, 600)
    c4.cd()
    c4.GetPad(0).SetTopMargin(0.06)
    c4.GetPad(0).SetRightMargin(0.05)
    c4.GetPad(0).SetTicks(1, 1)
    c4.GetPad(0).SetGridx()
    c4.GetPad(0).SetGridy()
    Best.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".png")
    c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".pdf")
    #    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".root")
    #    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".C")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    if 'ah' in channel:
        outFile = TFile("bands.root", "RECREATE")
        outFile.cd()
        pVal.Write("graph")
        Best.Write("best")
        outFile.Close()
Beispiel #28
0
    input_rootfile = args.input_file
    output_pdfname = args.output_prefix + '.pdf'
    rootfile = TFile(input_rootfile)
    histos = load_histos(rootfile)

    for k, v in histos.items():
        print(k, v)

    setup_global_options()

    can = TCanvas('can', 'can', 800, 1100)

    lab = TLatex()
    lab.SetNDC()
    lab.SetTextFont(42)
    lab.SetTextSize(0.05)
    lab.SetTextColor(1)

    can.Print('{}['.format(output_pdfname))

    # add_text_page(can, lab, text='W Monitoring Plots', save_name=output_pdfname)

    plot_sector_page(can,
                     histos,
                     'histos_w_CTOF_{}',
                     lab,
                     save_name=output_pdfname,
                     title='(CTOF)',
                     xtitle='W')

    plot_sector_page(can,
Beispiel #29
0
def train_and_apply():

    np.random.seed(1)
    ROOT.gROOT.SetBatch()

    #Extract data from root file
    tree = uproot.open("out_all.root")["outA/Tevts"]
    branch_mc = [
        "MC_B_P", "MC_B_eta", "MC_B_phi", "MC_B_pt", "MC_D0_P", "MC_D0_eta",
        "MC_D0_phi", "MC_D0_pt", "MC_Dst_P", "MC_Dst_eta", "MC_Dst_phi",
        "MC_Dst_pt", "MC_Est_mu", "MC_M2_miss", "MC_mu_P", "MC_mu_eta",
        "MC_mu_phi", "MC_mu_pt", "MC_pis_P", "MC_pis_eta", "MC_pis_phi",
        "MC_pis_pt", "MC_q2"
    ]
    branch_rec = [
        "B_P", "B_eta", "B_phi", "B_pt", "D0_P", "D0_eta", "D0_phi", "D0_pt",
        "Dst_P", "Dst_eta", "Dst_phi", "Dst_pt", "Est_mu", "M2_miss", "mu_P",
        "mu_eta", "mu_phi", "mu_pt", "pis_P", "pis_eta", "pis_phi", "pis_pt",
        "q2"
    ]
    nvariable = len(branch_mc)
    x_train = tree.array(branch_mc[0], entrystop=options.maxevents)
    for i in range(1, nvariable):
        x_train = np.vstack(
            (x_train, tree.array(branch_mc[i], entrystop=options.maxevents)))
    x_test = tree.array(branch_rec[0], entrystop=options.maxevents)
    for i in range(1, nvariable):
        x_test = np.vstack(
            (x_test, tree.array(branch_rec[i], entrystop=options.maxevents)))
    x_train = x_train.T
    x_test = x_test.T
    x_test = array2D_float(x_test)
    #Different type of reconstruction variables

    #BN normalization
    gamma = 0
    beta = 0.2

    ar = np.array(x_train)
    a = K.constant(ar[:, 0])
    mean = K.mean(a)
    var = K.var(a)
    x_train = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
    for i in range(1, nvariable):
        a = K.constant(ar[:, i])
        mean = K.mean(a)
        var = K.var(a)
        a = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
        x_train = np.vstack((x_train, a))
    x_train = x_train.T

    ar = np.array(x_test)
    a = K.constant(ar[:, 0])
    mean = K.mean(a)
    var = K.var(a)
    x_test = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
    for i in range(1, nvariable):
        a = K.constant(ar[:, i])
        mean = K.mean(a)
        var = K.var(a)
        a = K.eval(K.batch_normalization(a, mean, var, gamma, beta))
        x_test = np.vstack((x_test, a))
    x_test = x_test.T

    #Add noise, remain to be improved
    noise = np.random.normal(loc=0.0, scale=0.01, size=x_train.shape)
    x_train_noisy = x_train + noise
    noise = np.random.normal(loc=0.0, scale=0.01, size=x_test.shape)
    x_test_noisy = x_test + noise
    x_train = np.clip(x_train, -1., 1.)
    x_test = np.clip(x_test, -1., 1.)
    x_train_noisy = np.clip(x_train_noisy, -1., 1.)
    x_test_noisy = np.clip(x_test_noisy, -1., 1.)

    # Network parameters
    input_shape = (x_train.shape[1], )
    batch_size = 128
    latent_dim = 2

    # Build the Autoencoder Model
    # First build the Encoder Model
    inputs = Input(shape=input_shape, name='encoder_input')
    x = inputs

    # Shape info needed to build Decoder Model
    shape = K.int_shape(x)

    # Generate the latent vector
    latent = Dense(latent_dim, name='latent_vector')(x)

    # Instantiate Encoder Model
    encoder = Model(inputs, latent, name='encoder')
    encoder.summary()

    # Build the Decoder Model
    latent_inputs = Input(shape=(latent_dim, ), name='decoder_input')
    x = Dense(shape[1])(latent_inputs)
    x = Reshape((shape[1], ))(x)
    outputs = Activation('tanh', name='decoder_output')(x)

    # Instantiate Decoder Model
    decoder = Model(latent_inputs, outputs, name='decoder')
    decoder.summary()

    # Autoencoder = Encoder + Decoder
    # Instantiate Autoencoder Model
    autoencoder = Model(inputs, decoder(encoder(inputs)), name='autoencoder')
    autoencoder.summary()

    autoencoder.compile(loss='mse', optimizer='adam')

    # Train the autoencoder
    autoencoder.fit(x_train_noisy,
                    x_train,
                    validation_data=(x_test_noisy, x_test),
                    epochs=options.epochs,
                    batch_size=batch_size)

    # Predict the Autoencoder output from corrupted test imformation
    x_decoded = autoencoder.predict(x_test_noisy)

    # Draw Comparision Plots
    c = TCanvas("c", "c", 700, 700)
    fPads1 = TPad("pad1", "Run2", 0.0, 0.29, 1.00, 1.00)
    fPads2 = TPad("pad2", "", 0.00, 0.00, 1.00, 0.29)
    fPads1.SetBottomMargin(0.007)
    fPads1.SetLeftMargin(0.10)
    fPads1.SetRightMargin(0.03)
    fPads2.SetLeftMargin(0.10)
    fPads2.SetRightMargin(0.03)
    fPads2.SetBottomMargin(0.25)
    fPads1.Draw()
    fPads2.Draw()
    fPads1.cd()
    nbin = 50
    min = -1.
    max = 1.
    variable = "P^{B}"
    lbin = (max - min) / nbin
    lbin = str(float((max - min) / nbin))
    xtitle = branch_rec[options.branch - 1]
    ytitle = "Events/" + lbin + "GeV"
    h_rec = TH1D("h_rec", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max)
    h_rec.Sumw2()
    h_pre = TH1D("h_pre", "" + ";%s;%s" % (xtitle, ytitle), nbin, min, max)
    h_pre.Sumw2()
    for i in range(x_test_noisy.shape[0]):
        h_rec.Fill(x_test_noisy[i][options.branch - 1])
        h_pre.Fill(x_decoded[i][options.branch - 1])
    h_rec = UnderOverFlow1D(h_rec)
    h_pre = UnderOverFlow1D(h_pre)
    maxY = TMath.Max(h_rec.GetMaximum(), h_pre.GetMaximum())
    h_rec.SetLineColor(2)
    h_rec.SetFillStyle(0)
    h_rec.SetLineWidth(2)
    h_rec.SetLineStyle(1)
    h_pre.SetLineColor(3)
    h_pre.SetFillStyle(0)
    h_pre.SetLineWidth(2)
    h_pre.SetLineStyle(1)
    h_rec.SetStats(0)
    h_pre.SetStats(0)
    h_rec.GetYaxis().SetRangeUser(0, maxY * 1.1)
    h_rec.Draw("HIST")
    h_pre.Draw("same HIST")
    h_rec.GetYaxis().SetTitleSize(0.06)
    h_rec.GetYaxis().SetTitleOffset(0.78)
    theLeg = TLegend(0.5, 0.45, 0.95, 0.82, "", "NDC")
    theLeg.SetName("theLegend")
    theLeg.SetBorderSize(0)
    theLeg.SetLineColor(0)
    theLeg.SetFillColor(0)
    theLeg.SetFillStyle(0)
    theLeg.SetLineWidth(0)
    theLeg.SetLineStyle(0)
    theLeg.SetTextFont(42)
    theLeg.SetTextSize(.05)
    theLeg.AddEntry(h_rec, "Reconstruction", "L")
    theLeg.AddEntry(h_pre, "Prediction", "L")
    theLeg.SetY1NDC(0.9 - 0.05 * 6 - 0.005)
    theLeg.SetY1(theLeg.GetY1NDC())
    fPads1.cd()
    theLeg.Draw()
    title = TLatex(
        0.91, 0.93, "AE prediction compare with reconstruction, epochs=" +
        str(options.epochs))
    title.SetNDC()
    title.SetTextSize(0.05)
    title.SetTextFont(42)
    title.SetTextAlign(31)
    title.SetLineWidth(2)
    title.Draw()
    fPads2.cd()
    h_Ratio = h_pre.Clone("h_Ratio")
    h_Ratio.Divide(h_rec)
    h_Ratio.SetLineColor(1)
    h_Ratio.SetLineWidth(2)
    h_Ratio.SetMarkerStyle(8)
    h_Ratio.SetMarkerSize(0.7)
    h_Ratio.GetYaxis().SetRangeUser(0, 2)
    h_Ratio.GetYaxis().SetNdivisions(504, 0)
    h_Ratio.GetYaxis().SetTitle("Pre/Rec")
    h_Ratio.GetYaxis().SetTitleOffset(0.35)
    h_Ratio.GetYaxis().SetTitleSize(0.13)
    h_Ratio.GetYaxis().SetTitleSize(0.13)
    h_Ratio.GetYaxis().SetLabelSize(0.11)
    h_Ratio.GetXaxis().SetLabelSize(0.1)
    h_Ratio.GetXaxis().SetTitleOffset(0.8)
    h_Ratio.GetXaxis().SetTitleSize(0.14)
    h_Ratio.SetStats(0)
    axis1 = TGaxis(min, 1, max, 1, 0, 0, 0, "L")
    axis1.SetLineColor(1)
    axis1.SetLineWidth(1)
    for i in range(1, h_Ratio.GetNbinsX() + 1, 1):
        D = h_rec.GetBinContent(i)
        eD = h_rec.GetBinError(i)
        if D == 0: eD = 0.92
        B = h_pre.GetBinContent(i)
        eB = h_pre.GetBinError(i)
        if B < 0.1 and eB >= B:
            eB = 0.92
            Err = 0.
        if B != 0.:
            Err = TMath.Sqrt((eD * eD) / (B * B) + (D * D * eB * eB) /
                             (B * B * B * B))
            h_Ratio.SetBinContent(i, D / B)
            h_Ratio.SetBinError(i, Err)
        if B == 0.:
            Err = TMath.Sqrt((eD * eD) / (eB * eB) + (D * D * eB * eB) /
                             (eB * eB * eB * eB))
            h_Ratio.SetBinContent(i, D / 0.92)
            h_Ratio.SetBinError(i, Err)
        if D == 0 and B == 0:
            h_Ratio.SetBinContent(i, -1)
            h_Ratio.SetBinError(i, 0)
        h_Ratio.Draw("e0")
        axis1.Draw()

    c.SaveAs(branch_rec[options.branch - 1] + "_comparision.png")
Beispiel #30
0
def makesob_plots(calcsig,
                  sigstr_BCuts,
                  samples,
                  dirname,
                  vararray,
                  signal,
                  selarray=None,
                  hist_config=None,
                  legend_config=None,
                  extratag=""):
    """
    Filter cuts by a significance threshold, plot signal-over-background (SOB) for each cut that passed the
    threshold, and save signal and background counts and errors for each "significant" cut into a table.

    SOB is defined as $\frac{S}{\sqrt{B}}$.

    :param calcsig: whether to recalculate tables of signal and background event counts and errors using `signif`
    :param sigstr_BCuts: list of background cut names
    :param samples: `SampleManager` containing the (full-dimensional) simulated data
    :param dirname: directory to save logs and histograms to
    :param vararray: variables of interest (dependent variables) to aggregate counts and error estimates for
    :param signal: name of signal (independent variable) to count
    :param selarray: list of cuts (see `makeselection` for format)
    :param hist_config: dict of `ROOT` plotting options
    :param legend_config: legend plotting options
    :param extratag: log file ending string (optional)
    """
    # Set up ROOT plot
    c1 = TCanvas('c1', 'Significance', 200, 10, 1500, 700)
    c1.SetBottomMargin(0.4)
    c1.SetRightMargin(0.18)
    c1.SetLeftMargin(0.1)
    # p1 = TPad("p1","p1",0.0,0.0,1.0,1.0,0)#TPad(name,     title,     xlow,     ylow,    xup,    yup, color )
    # p1.SetBottomMargin(1.7)
    # p1.GetFrame().SetBorderSize(5)
    # p1.SetRightMargin(0.01)#percent of the pad height
    # p1.SetLeftMargin(0.1)
    # p1.SetBottomMargin(0.5)
    # p1.Draw()

    # get the cut set name and corresponding significance
    xname_all = []  # cut names for x labels
    # signame = []
    sig_all = []
    sig_err_all = []
    bkg_all = []
    bkg_err_all = []
    sigstr_BaseCuts = sigstr_BCuts  # base cut string
    basecut_listvalue = 0  # index number of the base cut in the xname_all list
    sig_cut_plots = []

    # xname, ysig, signame = signif(sampManElG,vararray, selarray, hist_config,{}, "log")

    # If calcsig != 0 ach
    # If recalculating from scratch, call signif to count background and signal events
    if calcsig:
        xname_all, bkg_all, bkg_err_all, sig_all, sig_err_all, sig_cut_plots = signif(
            samples, vararray, signal, dirname, selarray, hist_config, {}, "")
    # If loading background and signal events from a file already logged by signif, then load them
    else:
        ftable = dirname + "/Selected/" + signal + "TOTAL_table"
        n = 0
        with open(ftable, 'r') as f:
            lines = f.readlines()
            # print "read first line of the table we just saved" + str(lines[1])
            for line in lines:
                n = n + 1
                listline = line.split()
                # print line
                if n > 1:
                    # print listline[5]

                    # Add background and significance to their respective
                    # arrays for the plot generation.
                    xname_all.append(str(listline[0]))
                    bkg_all.append(float(listline[1]))
                    bkg_err_all.append(float(listline[2]))
                    sig_all.append(float(listline[3]))
                    sig_err_all.append(float(listline[4]))
                    sig_cut_plots.append(str(listline[5]))
                    # print sig_all[0]

        f.close()

    # if (debug):
    # print "The bigger lists : sig_all[0]= " + str(sig_all[0])+ "bkg_all[1]=" + str(bkg_all[1])
    print "size of bigger array is " + str(len(sig_all))
    # check the list of lists is correct - update: it is ot a list of lists anymore but leaving for future.
    # row_format = '{:<4}' * len(sig_all)
    # for v in zip(*sig_all):
    #    #if (debug):
    #   print (row_format.format(*v))
    # print sig_all

    # Cuts and associated values that are deemed significant by Punzi's criterion
    xname = []
    # signame = []
    sig = [
    ]  # it is alist of lists for significance for all the signal samples
    sig_err = [
    ]  # it is alist of lists for significance for all the signal samples
    # bkg = [[] for i in range(len(signame))]
    bkg = []
    bkg_err = []
    sig_cut_for_plots = [
    ]  # exact string of selection cuts to be used later to make plots
    histall = []

    sig_max = 0.
    bkg_max = 0.

    # for j in range(len(signame)):# loop on signal samples
    sig_max = sig_all[0]
    bkg_max = bkg_all[0]
    signif_max = sig_max / bkg_max
    # if (debug):
    print "signif_max  " + str(signif_max)
    # sig[j].append(sig_all[j][0])
    sig.append(sig_max)
    bkg.append(bkg_all[0])
    sig_err.append(sig_err_all[0])
    bkg_err.append(bkg_err_all[0])
    xname.append(xname_all[0])
    sig_cut_for_plots.append(sig_cut_plots[0])
    # if (debug):
    # print "j   " + str(j) + "   " + str(sig_all[j][0]/bkg_all[0])
    for i in range(1, len(xname_all)):  # loop on cuts sets
        signif_cut = sig_all[i] / math.sqrt(
            bkg_all[i])  # compute variance assuming
        # print sigstr_BaseCuts
        # print "cut i : " + str(xname_all[i])
        if xname_all[i] == sigstr_BaseCuts:  # if the cut is a base cut, print
            print "Base cut for this signal is : " + xname_all[i]
            # print  " ith bin in xname_all[i]  " + str(i)
            basecut_listvalue = i
            # if (debug):
            print "i   " + str(i) + "  " + xname_all[i] + "    " + str(
                signif_cut)
        if signif_cut > (
                1.015 * signif_max
        ):  # append significant events to list of relevant counts
            print "i   " + str(i) + "  " + xname_all[i] + "    " + str(
                signif_cut)
            signif_max = signif_cut
            # if (debug):
            print " new signif_max  " + str(signif_max) + "   " + str(i)
            sig.append(sig_all[i])
            bkg.append(bkg_all[i])
            sig_err.append(sig_err_all[i])
            bkg_err.append(bkg_err_all[i])
            xname.append(xname_all[i])
            sig_cut_for_plots.append(sig_cut_plots[i])
            # signame.append(signame_all[i+1])
    if debug:
        print sig_all[1]
        print sig[1]
        print "How many cuts ?   " + str(len(xname[0]))

    # n= int(len(xname))
    # nsig= int(len(signame))
    nhist = ["_sig", "_bkg", "_bkgsqrt", "_sob", "_sosqrtb"]

    # Bin 0 contains the underflow
    # Bin 1 contains the first bin with low-edge ( xlow INCLUDED).
    # The second to last bin (bin# nbins) contains the upper-edge (xup EXCLUDED).
    # The Last bin (bin# nbins+1) contains the overflow.

    # Make the SOB plot for ALL cuts
    histName_All = signal + "_h_SOB_ALL"
    nall = int(len(xname_all))
    histNameAll = ROOT.TH1F(histName_All, "", nall + 1, 0, nall + 1)
    for i in range(len(xname_all)):  # loop on cuts sets
        histNameAll.SetBinContent(i + 1, sig_all[i] / (math.sqrt(bkg_all[i])))
        # histNameAll.SetBinError(i+1, sig_err[i])#
    histNameAll.Draw()
    histNameAll.GetYaxis().SetTitle('S/#\sqrt B')
    histNameAll.GetXaxis().SetTitle('Cut combination')
    savename_all = str(dirname + "/Selected/" + signal + "_SOsqrtB_ALL")
    c1.SaveAs(savename_all + ".png")
    c1.SaveAs(savename_all + ".pdf")

    c1.Modified()
    c1.Update()

    #################################################
    # for i in range(len(signame)):
    if debug:
        print "Histogram " + signal
    n = int(len(xname))
    for j in range(len(nhist)):
        histName = signal + "_h" + nhist[j]
        # if (debug):
        # print histName
        histall.append(ROOT.TH1F(histName, "", n + 1, 0, n + 1))
        # if (debug):
        # print"histogram name is = " + histall[j].GetName()
    # for j in range(len(signame)):# loop on signal samples
    if debug:
        print signal
    n = int(len(xname))
    bscut = basecut_listvalue
    print " basecut_listvalue = " + str(basecut_listvalue)
    for k in range(len(nhist)):
        for i in range(len(xname)):  # loop on cuts sets
            if (debug):
                print "signal  and cut set  " + str(j) + "  " + str(i)
                print xname[i] + "has significance" + str(
                    ysig[i]
                )  # first index is signal sample, second index is cut
                print str(i) + "   sig[i]   " + str(sig[i])
                print nhist[k]
            # sig = round(float(ysig[i]),2)
            # if (debug):
            # print histall[k].GetName()

            histall[k].GetXaxis().SetBinLabel(i + 1, xname[i])
            # print "bscut  =" + str(bscut)
            # print "length of xname_all[j] arra  =" + str(len(xname_all))
            # print "xname_all[j][bscut]    " + xname_all[bscut]
            histall[k].GetXaxis().SetBinLabel(
                n + 1, "X" + xname_all[bscut]
            )  # notice it is from the initial, bigger cutlist

            # print sig_cut_plots[i]
            # print "base cut value = " + str(bscut) + str(sig_all[j][bscut])
            if nhist[k] == '_sig':
                histall[k].SetBinContent(i + 1, sig[i])
                histall[k].SetBinError(i + 1, sig_err[i])  #
                histall[k].SetBinContent(n + 1, sig_all[bscut])
                histall[k].SetBinError(n + 1, sig_err_all[bscut])  #

                # histall[j][k].GetXaxis().SetBinLabel(i+1, xname[j][i])
                # print "n+1 bin label = " + histall[j][k].GetXaxis().GetBinLabel(n+1)
                # if (debug):
                # print "n+1 bin content " + str(histall[k].GetBinContent(n+1))
            if nhist[k] == '_bkg':
                histall[k].SetBinContent(i + 1, bkg[i])
                histall[k].SetBinError(i + 1, bkg_err[i])  #
                histall[k].SetBinContent(n + 1, bkg_all[bscut])
                histall[k].SetBinError(n + 1, bkg_err_all[bscut])  #
                if (debug):
                    print histall[k].GetBinContent(i + 1)
            if nhist[k] == '_bkgsqrt':
                percenterr = (bkg_err[i] / bkg[i]) / 2
                berr = percenterr * math.sqrt(bkg[i])
                berr_bscut = ((bkg_err_all[bscut] / bkg_all[bscut]) /
                              2) * math.sqrt(bkg_all[bscut])
                histall[k].SetBinContent(i + 1, math.sqrt(bkg[i]))
                histall[k].SetBinError(i + 1, berr)  #
                histall[k].SetBinContent(n + 1, math.sqrt(bkg_all[bscut]))
                histall[k].SetBinError(n + 1, berr_bscut)  #
                if debug:
                    print histall[k].GetBinContent(i + 1)
                    print Sigh.GetXaxis().GetBinLabel(i + 1)

    gStyle.SetOptStat(0)
    # for j in range(len(signame)):
    for k in range(len(nhist)):
        if nhist[k] == "_sob":
            histall[k] = doratio(histall[0], histall[1])
            histall[k].GetYaxis().SetTitle('S/B')
            if debug:
                print "sob" + str(histall[k].GetBinContent(1))
        if nhist[k] == "_sosqrtb":
            histall[k] = doratio(histall[0], histall[2])
            histall[k].GetYaxis().SetTitle('S/#\sqrt B')
        if nhist[k] == "_sig":
            histall[k].GetYaxis().SetTitle('Signal')
        if nhist[k] == "_bkg":
            histall[k].GetYaxis().SetTitle('Total Background')
        if nhist[k] == "_bkgsqrt":
            histall[k].GetYaxis().SetTitle('Sqrt Total Background')

        histall[k].SetLineColor(k + 2)
        histall[k].SetLineWidth(4)
        # histall[k].GetXaxis().LabelsOption("v")
        histall[k].GetXaxis().SetLabelSize(0.025)  # percentage of pad size
        # histall[k].GetXaxis().SetTitleSize(0.10)
        # histall[k].GetXaxis().SetTitleOffset(1.0)
        histall[k].GetYaxis().SetTitleSize(0.06)
        histall[k].GetYaxis().SetTitleOffset(0.8)
        histall[k].GetYaxis().SetLabelSize(0.04)
        histall[k].GetYaxis().CenterTitle()
        histall[k].GetYaxis().SetNdivisions(510, True)
        if debug:
            print histall[k].GetXaxis().GetBinLabel(i + 1)

    maxy = 0.0
    miny = 0.0
    # for j in range(len(signame)):
    sn = signal
    # sob bin with max value
    sob_max_bin = 0
    for k in range(len(nhist)):
        maxvalue = histall[k].GetBinContent((histall[k].GetMaximumBin()))
        minvalue = histall[k].GetBinContent((histall[k].GetMinimumBin()))
        maxy = maxvalue
        miny = minvalue
        if maxvalue > maxy:
            maxy = maxvalue
        if minvalue > miny:
            miny = minvalue

        histall[k].SetMaximum(maxvalue + 0.5 * maxvalue)
        histall[k].SetMinimum(minvalue - 0.5 * minvalue)
        if k == 4:
            sob_max_bin = histall[k].GetMaximumBin()
        # sigstr_BaseCut[]
        # = histall[k].SetBinContent((n+a, histall[k].GetXaxis().GetBinLabel(i+1)))

    # for j in range(len(signame)):
    sn = signal

    for k in range(len(nhist)):
        if k == 2:
            continue
        c1.Modified()
        c1.Update()
        if k == 1:
            gPad.SetLogy()
        else:
            gPad.SetLogy(0)
        legend = TLegend(0.1, 0.7, 0.5, 0.89, " ")  # x1,y1,x2,y2
        maxcut = histall[k].GetXaxis().GetBinLabel(sob_max_bin)
        maxvalue = round(histall[k].GetBinContent(sob_max_bin), 2)
        # legend. AddEntry(histall[j][k] , signame[j] + ' (' + maxcut + ')' , "")
        print signal
        # p1.cd()
        histall[k].Draw()
        c1.Modified()
        c1.Update()
        BC = 0
        BC = round(histall[k].GetBinContent(n + 1), 2)
        print str(c1.GetUxmax()) + "  " + str(BC)
        # p1.Update();
        l = ROOT.TLine(c1.GetUxmin(), BC, c1.GetUxmax(), BC)

        l.SetLineColor(4)
        l.SetLineWidth(2)
        l.Draw()

        latex = TLatex()
        latex.SetNDC()
        latex.SetTextSize(0.04)
        latex.SetTextAlign(12)  # 12 center, 31align right
        latex.DrawLatex(0.2, 0.85, signal)
        latex.DrawLatex(0.2, 0.75, 'Max Cut ' + maxcut)
        latex.DrawLatex(
            0.2, 0.65,
            'Base Value = ' + str(BC) + ' Max Value  ' + str(maxvalue))
        latex.SetTextAlign(31)  # align right
        latex.DrawLatex(0.25, 0.93, " 36 fb^{-1} at #sqrt{s} = 13 TeV")
        latex.DrawLatex(0.8, 0.93, "CMS Internal")

        # legend.SetShadowColor(0);
        # legend.SetFillColor(0);
        # legend.SetLineColor(0);
        # legend.Draw('same')
        savename = str(dirname + "/Selected/" + signal + str(nhist[k]))
        c1.SaveAs(savename + ".png")
        c1.SaveAs(savename + ".pdf")
        # c1.SaveAs(savename + ".C")
        # c1.SaveAs(savename + ".root")
        c1.Modified()
        c1.Update()

        # for n in range(len(signame)):
        ftable = dirname + "/Selected/" + signal + "_selected_table"
        with open(ftable, 'w+') as f:
            f.write(
                "cutname total_b total_b_err total_s total_s_err  cut_array_used\n"
            )
            for j in range(len(xname)):
                # print signal
                print('%15s   %5s    %5s  %5s  %5s  %5s' %
                      (str(xname[j]), str(bkg[j]), str(bkg_err[j]), str(
                          sig[j]), str(sig_err[j]), sig_cut_for_plots[j]))
                # f.write('%15s   %5s    %5s  %5s  %5s  %5s' %(str(xname[j]),  str(bkg[j]), str(bkg_err[j]) , str(sig[j]) , str(sig_err[j]) , sig_cut_for_plots[j]))
                f.write('%15s   %5f    %5f  %5f  %5f  %5s\n' %
                        (xname[j], bkg[j], bkg_err[j], sig[j], sig_err[j],
                         sig_cut_for_plots[j]))
        f.close()
    print "Total number of cut combinations used for plotting: " + str(
        len(xname_all))