def lumiDependency(path, plotName, selection, runRange, cmsExtra, bins):

    plot = getPlot(plotName)
    plot.addRegion(selection)
    plot.cleanCuts()
    plot.cuts = plot.cuts % runRange.runCut

    label = ""
    if "Forward" in selection.name:
        label = "forward"
    elif "Central" in selection.name:
        label = "central"
    else:
        label = "inclusive"

    corr = getattr(rSFOF, label).val
    corrUncert = getattr(rSFOF, label).err

    runCuts = [[190645, 194643], [194644, 195868], [195915, 198955],
               [198969, 200075], [200091, 201669], [201671, 202972],
               [202973, 205344], [205515, 206512], [206513, 207491],
               [207492, 208686]]
    #~ runCuts = [[190645,194897]]

    #~ xValues = [2,4,6,8,10,12,14,16,18,19.4]
    if bins:
        xValues = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
        xValuesUncert = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]
    else:
        xValues = [1, 3, 5, 7, 9, 11, 13, 15, 17, 18.7]
        xValuesUncert = [1, 1, 1, 1, 1, 1, 1, 1, 1, 0.7]

    yValues = []
    yValuesUncert = []
    yValuesBTagged = []
    yValuesUncertBTagged = []
    yValuesBVeto = []
    yValuesUncertBVeto = []

    sfList = []
    ofList = []

    sfValuesUncert = []
    ofValuesUncert = []

    sfListBTagged = []
    ofListBTagged = []

    sfValuesUncertBTagged = []
    ofValuesUncertBTagged = []

    sfListBVeto = []
    ofListBVeto = []

    sfValuesUncertBVeto = []
    ofValuesUncertBVeto = []

    eeList = []
    mmList = []

    eeValuesUncert = []
    mmValuesUncert = []

    cuts = plot.cuts

    for cutPair in runCuts:
        if bins:
            plot.cuts = plot.cuts + "*(runNr >= %d && runNr <= %d)" % (
                cutPair[0], cutPair[1])
        else:
            plot.cuts = plot.cuts + "*(runNr >= %d && runNr <= %d)" % (
                runCuts[0][0], cutPair[1])

        eeHist, mmHist, emHist = getHistograms(path, plot, runRange, False, [],
                                               label)

        plot.cuts = cuts
        if bins:
            plot.cuts = plot.cuts + "*(runNr >= %d && runNr <= %d)" % (
                cutPair[0], cutPair[1]) + "*(nBJets == 0)"
        else:
            plot.cuts = plot.cuts + "*(runNr >= %d && runNr <= %d)" % (
                runCuts[0][0], cutPair[1]) + "*(nBJets == 0)"

        eeHistBVeto, mmHistBVeto, emHistBVeto = getHistograms(
            path, plot, runRange, False, [], label)

        plot.cuts = cuts
        if bins:
            plot.cuts = plot.cuts + "*(runNr >= %d && runNr <= %d)" % (
                cutPair[0], cutPair[1]) + "*(nBJets >= 1)"
        else:
            plot.cuts = plot.cuts + "*(runNr >= %d && runNr <= %d)" % (
                runCuts[0][0], cutPair[1]) + "*(nBJets >= 1)"

        eeHistBTagged, mmHistBTagged, emHistBTagged = getHistograms(
            path, plot, runRange, False, [], label)

        plot.cuts = cuts

        ee = eeHist.Integral()
        mm = mmHist.Integral()
        sf = eeHist.Integral() + mmHist.Integral()
        of = emHist.Integral() * corr
        eeBTagged = eeHistBTagged.Integral()
        mmBTagged = mmHistBTagged.Integral()
        sfBTagged = eeHistBTagged.Integral() + mmHistBTagged.Integral()
        ofBTagged = emHistBTagged.Integral()
        eeBVeto = eeHistBVeto.Integral()
        mmBVeto = mmHistBVeto.Integral()
        sfBVeto = eeHistBVeto.Integral() + mmHistBVeto.Integral()
        ofBVeto = emHistBVeto.Integral()

        yValues.append(sf - of)
        yValuesUncert.append(getUncert(sf, of, corrUncert))
        sfList.append(sf)
        ofList.append(of)
        sfValuesUncert.append(sf**0.5)
        ofValuesUncert.append((of + (of * corrUncert)**2)**0.5)
        yValuesBTagged.append(sfBTagged - ofBTagged)
        yValuesUncertBTagged.append(getUncert(sfBTagged, ofBTagged,
                                              corrUncert))
        sfListBTagged.append(sfBTagged)
        ofListBTagged.append(ofBTagged)
        sfValuesUncertBTagged.append(sfBTagged**0.5)
        ofValuesUncertBTagged.append(ofBTagged**0.5)
        yValuesBVeto.append(sfBVeto - ofBVeto)
        yValuesUncertBVeto.append(getUncert(sfBVeto, ofBVeto, corrUncert))
        sfListBVeto.append(sfBVeto)
        ofListBVeto.append(ofBVeto)
        sfValuesUncertBVeto.append(sfBVeto**0.5)
        ofValuesUncertBVeto.append(ofBVeto**0.5)
        eeList.append(ee)
        mmList.append(mm)
        eeValuesUncert.append(ee**0.5)
        mmValuesUncert.append(mm**0.5)

    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    style = setTDRStyle()
    style.SetTitleYOffset(1.25)
    plotPad.UseCurrentStyle()
    plotPad.Draw()
    plotPad.cd()
    if bins:
        legend = TLegend(0.45, 0.6, 0.9, 0.95)
    else:
        legend = TLegend(0.19, 0.5, 0.55, 0.85)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    ROOT.gStyle.SetOptStat(0)

    #~ if label == "forward":
    #~ hCanvas.DrawFrame(0,-20,20,200,"; %s ; %s" %("integrated luminosity [fb^{-1}]","Events"))
    #~
    #~ else:

    yMax = sfList[-1] + 150
    yMin = min(min(yValues) - max(yValuesUncert) * 1.25, -10)
    if bins:
        hCanvas.DrawFrame(
            0, yMin, 10, yMax,
            "; %s ; %s" % ("bin number", "Events / approx. 2 fb^{-1}"))
    else:
        hCanvas.DrawFrame(
            0, yMin, 20, yMax,
            "; %s ; %s" % ("integrated luminosity [fb^{-1}]", "Events"))

    zeroLine = ROOT.TLine(0, 0., 20, 0.)
    zeroLine.SetLineWidth(1)
    zeroLine.SetLineColor(ROOT.kBlue)
    zeroLine.SetLineStyle(2)
    zeroLine.Draw("same")

    arg2 = numpy.array(xValues, "d")
    arg4 = numpy.array(xValuesUncert, "d")

    arg3 = numpy.array(yValues, "d")
    arg5 = numpy.array(yValuesUncert, "d")

    sfArray = numpy.array(sfList, "d")
    ofArray = numpy.array(ofList, "d")
    sfUncertArray = numpy.array(sfValuesUncert, "d")
    ofUncertArray = numpy.array(ofValuesUncert, "d")

    arg3BTagged = numpy.array(yValuesBTagged, "d")
    arg5BTagged = numpy.array(yValuesUncertBTagged, "d")

    sfArrayBTagged = numpy.array(sfListBTagged, "d")
    ofArrayBTagged = numpy.array(ofListBTagged, "d")
    sfUncertArrayBTagged = numpy.array(sfValuesUncertBTagged, "d")
    ofUncertArrayBTagged = numpy.array(ofValuesUncertBTagged, "d")

    arg3BVeto = numpy.array(yValuesBVeto, "d")
    arg5BVeto = numpy.array(yValuesUncertBVeto, "d")

    sfArrayBVeto = numpy.array(sfListBVeto, "d")
    ofArrayBVeto = numpy.array(ofListBVeto, "d")
    sfUncertArrayBVeto = numpy.array(sfValuesUncertBVeto, "d")
    ofUncertArrayBVeto = numpy.array(ofValuesUncertBVeto, "d")

    eeArray = numpy.array(eeList, "d")
    mmArray = numpy.array(mmList, "d")
    eeUncertArray = numpy.array(eeValuesUncert, "d")
    mmUncertArray = numpy.array(mmValuesUncert, "d")

    #~ graph1jet = ROOT.TGraphErrors(6,METvalues,Rinout1Jets,METErrors,ErrRinout1Jets)
    graph = ROOT.TGraphErrors(10, arg2, arg3, arg4, arg5)
    graphSF = ROOT.TGraphErrors(10, arg2, sfArray, arg4, sfUncertArray)
    graphOF = ROOT.TGraphErrors(10, arg2, ofArray, arg4, ofUncertArray)

    graphBTagged = ROOT.TGraphErrors(10, arg2, arg3BTagged, arg4, arg5BTagged)

    graphSFBTagged = ROOT.TGraphErrors(10, arg2, sfArrayBTagged, arg4,
                                       sfUncertArrayBTagged)

    graphOFBTagged = ROOT.TGraphErrors(10, arg2, ofArrayBTagged, arg4,
                                       ofUncertArrayBTagged)

    graphBVeto = ROOT.TGraphErrors(10, arg2, arg3BVeto, arg4, arg5BVeto)
    graphSFBVeto = ROOT.TGraphErrors(10, arg2, sfArrayBVeto, arg4,
                                     sfUncertArrayBVeto)
    graphOFBVeto = ROOT.TGraphErrors(10, arg2, ofArrayBVeto, arg4,
                                     ofUncertArrayBVeto)

    graphEE = ROOT.TGraphErrors(10, arg2, eeArray, arg4, eeUncertArray)
    graphMM = ROOT.TGraphErrors(10, arg2, mmArray, arg4, mmUncertArray)
    graph.Draw("Psame")
    graphSF.Draw("Psame")
    graphSF.SetLineColor(ROOT.kRed)
    graphSF.SetMarkerColor(ROOT.kRed)
    graphOF.Draw("Psame")
    graphOF.SetLineColor(ROOT.kBlue)
    graphOF.SetMarkerColor(ROOT.kBlue)

    from ROOT import TH1F, kWhite
    legendHistDing = TH1F()
    legendHistDing.SetFillColor(kWhite)
    if "Signal" in selection.name:
        legend.AddEntry(legendHistDing, "Signal region %s" % label, "h")
    else:
        legend.AddEntry(legendHistDing, "Control region %s" % label, "h")

    legend.AddEntry(graphSF, "Same Flavour", "p")
    legend.AddEntry(graphOF, "Prediction from Opposite Flavour", "p")
    legend.AddEntry(graph, "N_{SF}-N_{prediction}", "p")

    legend.Draw("same")

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

    latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (8 TeV)" % runRange.printval)

    latexCMS.DrawLatex(0.19, 0.89, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.82
    else:
        yLabelPos = 0.85

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

    if bins:
        hCanvas.Print("fig/YieldvsLumi_Bins_%s" %
                      (plot.filename % runRange.label))
    else:
        hCanvas.Print("fig/YieldvsLumi_%s" % (plot.filename % runRange.label))
    #~ if label == "forward":
    #~ hCanvas.DrawFrame(0,-20,20,200,"; %s ; %s" %("integrated luminosity [fb^{-1}]","Events"))
    #~
    #~ else:
    yMax = sfListBTagged[-1] + 150
    yMin = min(min(yValuesBTagged) - max(yValuesUncertBTagged) * 1.25, -10)
    if bins:
        hCanvas.DrawFrame(
            0, yMin, 10, yMax,
            "; %s ; %s" % ("bin number", "Events / approx. 2 fb^{-1}"))
    else:
        hCanvas.DrawFrame(
            0, yMin, 20, yMax,
            "; %s ; %s" % ("integrated luminosity [fb^{-1}]", "Events"))
    zeroLine.Draw("same")
    legend.Clear()
    graphBTagged.Draw("Psame")
    graphSFBTagged.Draw("Psame")
    graphSFBTagged.SetLineColor(ROOT.kRed)
    graphSFBTagged.SetMarkerColor(ROOT.kRed)
    graphOFBTagged.Draw("Psame")
    graphOFBTagged.SetLineColor(ROOT.kBlue)
    graphOFBTagged.SetMarkerColor(ROOT.kBlue)

    from ROOT import TH1F, kWhite
    legendHistDing = TH1F()
    legendHistDing.SetFillColor(kWhite)
    if "Signal" in selection.name:
        legend.AddEntry(legendHistDing, "Signal region %s - b tagged" % label,
                        "h")
    else:
        legend.AddEntry(legendHistDing, "Control region %s - b tagged" % label,
                        "h")

    legend.AddEntry(graphSFBTagged, "Same Flavour", "p")
    legend.AddEntry(graphOFBTagged, "Prediction from Opposite Flavour", "p")
    legend.AddEntry(graphBTagged, "N_{SF}-N_{prediction}", "p")

    legend.Draw("same")

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

    latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (8 TeV)" % runRange.printval)

    latexCMS.DrawLatex(0.19, 0.89, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.82
    else:
        yLabelPos = 0.85

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))
    if bins:
        hCanvas.Print("fig/YieldvsLumi_Bins_BTagged_%s" %
                      (plot.filename % runRange.label))
    else:
        hCanvas.Print("fig/YieldvsLumi_BTagged_%s" %
                      (plot.filename % runRange.label))

    #~ if label == "forward":
    #~ hCanvas.DrawFrame(0,-20,20,200,"; %s ; %s" %("integrated luminosity [fb^{-1}]","Events"))
    #~
    #~ else:
    yMax = sfListBVeto[-1] + 150
    yMin = min(min(yValuesBVeto) - max(yValuesUncertBVeto) * 1.25, -10)
    if bins:
        hCanvas.DrawFrame(
            0, yMin, 10, yMax,
            "; %s ; %s" % ("bin number", "Events / approx. 2 fb^{-1}"))
    else:
        hCanvas.DrawFrame(
            0, yMin, 20, yMax,
            "; %s ; %s" % ("integrated luminosity [fb^{-1}]", "Events"))
    zeroLine.Draw("same")
    legend.Clear()
    graphBVeto.Draw("Psame")
    graphSFBVeto.Draw("Psame")
    graphSFBVeto.SetLineColor(ROOT.kRed)
    graphSFBVeto.SetMarkerColor(ROOT.kRed)
    graphOFBVeto.Draw("Psame")
    graphOFBVeto.SetLineColor(ROOT.kBlue)
    graphOFBVeto.SetMarkerColor(ROOT.kBlue)

    from ROOT import TH1F, kWhite
    legendHistDing = TH1F()
    legendHistDing.SetFillColor(kWhite)
    if "Signal" in selection.name:
        legend.AddEntry(legendHistDing, "Signal region %s - b veto" % label,
                        "h")
    else:
        legend.AddEntry(legendHistDing, "Control region %s - b veto" % label,
                        "h")

    legend.AddEntry(graphSFBVeto, "Same Flavour", "p")
    legend.AddEntry(graphOFBVeto, "Prediction from Opposite Flavour", "p")
    legend.AddEntry(graphBTagged, "N_{SF}-N_{prediction}", "p")
    #~ legend.AddEntry(graph,"SF - OF","p")
    legend.Draw("same")

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

    latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (8 TeV)" % runRange.printval)

    latexCMS.DrawLatex(0.19, 0.89, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.82
    else:
        yLabelPos = 0.85

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))
    if bins:
        hCanvas.Print("fig/YieldvsLumi_Bins_BVeto_%s" %
                      (plot.filename % runRange.label))
    else:
        hCanvas.Print("fig/YieldvsLumi_BVeto_%s" %
                      (plot.filename % runRange.label))
Beispiel #2
0
def DrawBazil(diagonal=175, doData=False, pname='limits'):
    import numpy as np
    # 'mstop','mlsp','sm2','sm1','central','sp1','sp2', 'data'
    d = GetDic(pname + '.p', diagonal)
    x = np.array(d['mstop'])
    e = np.array(d['exp'])
    y1max = np.array(d['s+1'])
    y2max = np.array(d['s+2'])
    y1min = np.array(d['s-1'])
    y2min = np.array(d['s-2'])
    # observed
    if (doData): o = np.array(d['obs'])
    else: o = np.array(d['exp'])

    c1 = TCanvas("c1", "CL", 10, 10, 800, 600)
    #c1.SetGrid();

    ymax = 7.5
    ymin = 0.3
    if (diagonal == 'down' or diagonal == 'Down' or diagonal == 'DOWN'):
        ymax = 3.1
        ymin = 0.30
    elif (diagonal == 'up' or diagonal == 'Up' or diagonal == 'UP'):
        ymax = 2.5
        ymin = 0.15

    #c1.DrawFrame(min(x)-2,min(d['sp2']+d['sm2'])-0.2,max(x)+2,max(d['sp2']+d['sm2'])+0.2);
    c1.DrawFrame(min(x), ymin, max(x), ymax)

    n = len(e)
    gr1min = TGraph(n, x, y1min)
    gr1max = TGraph(n, x, y1max)
    gr2min = TGraph(n, x, y2min)
    gr2max = TGraph(n, x, y2max)
    gro = TGraph(n, x, o)
    gre = TGraph(n, x, e)
    gh = TGraph(n, x, np.linspace(0.999, 1, n))
    gr1shade = TGraph(2 * n)
    gr2shade = TGraph(2 * n)

    #color1shade = 3; color2shade = 5;
    color1shade = kOrange
    color2shade = kGreen + 1
    for i in range(n):
        gr1shade.SetPoint(i, x[i], y1max[i] * scalefact)
        gr1shade.SetPoint(n + i, x[n - i - 1], y1min[n - i - 1] * scalefact)
        gr2shade.SetPoint(i, x[i], y2max[i] * scalefact)
        gr2shade.SetPoint(n + i, x[n - i - 1], y2min[n - i - 1] * scalefact)
        gre.SetPoint(i, x[i], e[i] * scalefact)
        gh.SetPoint(i, x[i], np.linspace(0.999, 1, n)[i] * scalefact)
        gro.SetPoint(i, x[i], o[i] * scalefact if doData else e[i] * scalefact)

    gr2shade.SetFillColor(color2shade)
    gr2shade.Draw("f")
    gr1shade.SetFillColor(color1shade)
    gr1shade.Draw("f")
    gh.SetLineWidth(2)
    gh.SetMarkerStyle(0)
    gh.SetLineColor(46)
    gh.SetLineStyle(2)
    gh.Draw("LP")
    gro.SetLineWidth(2)
    gro.SetMarkerStyle(20)
    gro.SetMarkerSize(0.7)
    gro.SetLineColor(1)
    if doData: gro.Draw("LP")
    gre.SetLineWidth(2)
    gre.SetMarkerStyle(0)
    gre.SetLineColor(1)
    gre.SetLineStyle(6)
    gre.Draw("LP")

    gre.SetTitle("Expected")
    gro.SetTitle("Observed")
    gr1shade.SetTitle("Expected 1#sigma")
    gr2shade.SetTitle("Expected 2#sigma")

    leg = TLegend(.1, .65, .4, .9)
    leg.AddEntry(gro)
    leg.AddEntry(gre)
    leg.AddEntry(gr1shade, '', 'f')
    leg.AddEntry(gr2shade, '', 'f')
    leg.SetFillColor(0)
    leg.Draw("same")

    gre.SetFillColor(0)
    gro.SetFillColor(0)
    gr1shade.SetLineColor(color1shade)
    gr2shade.SetLineColor(color2shade)

    tit = "m_{#tilde{t}_{1}} - m_{#tilde{#chi}_{1}^{0}} = "
    dm = "0"
    ymax = 4.1
    ymin = 0.3
    if (diagonal == 'down' or diagonal == 'Down' or diagonal == 'DOWN'):
        tit += "182.5 GeV"  #" + 7.5 GeV"
        dm = "m7p5"
        ymax = 2.2
        ymin = 0.15

    elif (diagonal == 'up' or diagonal == 'Up' or diagonal == 'UP'):
        tit += "167.5 GeV"  #" - 7.5 GeV"
        dm = "7p5"
        ymax = 3.3
        ymin = 0.30
    else:
        tit += "175 GeV"
    Title = TLatex()
    Title.SetTextSize(0.060)
    Title.DrawLatexNDC(.42, .84, tit)
    Xaxis = TLatex()
    Xaxis.SetTextFont(42)
    Xaxis.DrawLatexNDC(0.8, 0.03, "m_{#tilde{t}_{1}} (GeV)")
    Yaxis = TLatex()
    Yaxis.SetTextFont(42)
    Yaxis.SetTextAngle(90)
    Yaxis.DrawLatexNDC(0.05, 0.15, "95% CL limit on signal strength")
    textCMS = TLatex()
    textCMS.SetTextSize(0.06)
    textCMS.SetTextSizePixels(22)
    textCMS.SetTextAlign(12)
    textCMS.DrawLatexNDC(.12, .93, "CMS")
    textLumi = TLatex()
    textLumi.SetTextFont(42)
    textLumi.SetTextSize(0.06)
    textLumi.SetTextSizePixels(22)
    textLumi.DrawLatexNDC(.58, .91, "%1.1f fb^{-1} (13 TeV)" % (lumi))  #35.9

    name = "brazil_%i" % diagonal
    name = "brazil_%s" % pname
    for form in ['pdf', 'png']:
        c1.Print(outputdir + name + '.%s' % form)
Beispiel #3
0
def plotUpperLimits(labels, values):
    # see CMS plot guidelines: https://ghm.web.cern.ch/ghm/plots/

    N = len(labels)
    yellow = TGraph(2 * N)  # yellow band
    green = TGraph(2 * N)  # green band
    median = TGraph(N)  # median line

    up2s = []
    for i in range(N):
        file_name = "../model/higgsCombine." + labels[
            i] + ".AsymptoticLimits.mH120.root"
        limit = getLimits(file_name)
        up2s.append(limit[4])
        yellow.SetPoint(i, values[i], limit[4])  # + 2 sigma
        green.SetPoint(i, values[i], limit[3])  # + 1 sigma
        median.SetPoint(i, values[i], limit[2])  # median
        green.SetPoint(2 * N - 1 - i, values[i], limit[1])  # - 1 sigma
        yellow.SetPoint(2 * N - 1 - i, values[i], limit[0])  # - 2 sigma

    W = 800
    H = 600
    T = 0.08 * H
    B = 0.12 * H
    L = 0.12 * W
    R = 0.04 * W
    c = TCanvas("c", "c", 100, 100, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    c.cd()
    frame = c.DrawFrame(1.4, 0.001, 4.1, 10)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(0.9)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    frame.GetYaxis().SetTitle("95% upper limit on signal strength")
    #    frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}")
    #    frame.GetYaxis().SetTitle("95% upper limit on #sigma #times BR / (#sigma #times BR)_{SM}")
    #    frame.GetXaxis().SetTitle("background systematic uncertainty [%]")
    frame.GetXaxis().SetTitle("c#tau [mm]")
    frame.SetMinimum(0)
    frame.SetMaximum(max(up2s) * 1.05)
    frame.GetXaxis().SetLimits(min(values), max(values))

    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    yellow.Draw('F')

    green.SetFillColor(ROOT.kGreen + 1)
    green.SetLineColor(ROOT.kGreen + 1)
    green.SetFillStyle(1001)
    green.Draw('Fsame')

    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')

    #CMS_lumi.CMS_lumi(c,14,11)
    ROOT.gPad.SetTicks(1, 1)
    ROOT.gPad.SetLogx()
    frame.Draw('sameaxis')

    x1 = 0.15
    x2 = x1 + 0.24
    y2 = 0.76
    y1 = 0.60
    legend = TLegend(x1, y1, x2, y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.041)
    legend.SetTextFont(42)
    legend.AddEntry(median, "Asymptotic CL_{s} expected", 'L')
    legend.AddEntry(green, "#pm 1 std. deviation", 'f')
    #    legend.AddEntry(green, "Asymptotic CL_{s} #pm 1 std. deviation",'f')
    legend.AddEntry(yellow, "#pm 2 std. deviation", 'f')
    #    legend.AddEntry(green, "Asymptotic CL_{s} #pm 2 std. deviation",'f')
    legend.Draw()

    print " "
    c.SaveAs("UpperLimit.png")
    c.Close()
Beispiel #4
0
def illustration(name):

    if "Forward" in name:
        label = "forward"
    else:
        if "Central" in name:
            label = "central"
        else:
            label = "inclusive"

    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    style = setTDRStyle()
    plotPad.UseCurrentStyle()
    plotPad.Draw()
    plotPad.cd()
    hCanvas.DrawFrame(0, 0, 3, 2, "; %s ; %s" % ("r_{#mu e}", "R_{SF/OF}"))

    legend = TLegend(0.55, 0.18, 0.9, 0.525)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    ROOT.gStyle.SetOptStat(0)

    x = array("f", [
        getattr(rMuE, label).val - getattr(rMuE, label).err,
        getattr(rMuE, label).val + getattr(rMuE, label).err
    ])
    y = array("f", [1., 1.])
    ey = array("f", [1, 1])
    ex = array("f", [0, 0])
    ge = ROOT.TGraphErrors(2, x, y, ex, ey)
    ge.SetFillColor(ROOT.kGreen + 3)
    ge.SetLineColor(ROOT.kGreen + 3)
    ge.SetFillStyle(3001)
    ge.Draw("SAME 3")
    x = array("f", [0, 3])
    #~ y= array("f", [1.175, 1.175]) # 1.237
    #~ y= array([rMuEs[region], rMuEs[region]],"f") # 1.237
    y = array(
        "f",
        [getattr(rSFOFFact, label).SF.val,
         getattr(rSFOFFact, label).SF.val])
    ey = array(
        "f",
        [getattr(rSFOFFact, label).SF.err,
         getattr(rSFOFFact, label).SF.err])
    ex = array("f", [0.0, 0.0])
    ge2 = ROOT.TGraphErrors(2, x, y, ex, ey)
    ge2.SetFillColor(ROOT.kBlue - 3)
    ge2.SetLineColor(ROOT.kBlue - 3)
    ge2.SetFillStyle(3002)
    ge2.Draw("SAME 3")

    #~ print 0.5*((1+getattr(rMuE,label).val-1)+ 1./(1+getattr(rMuE,label).val-1))*getattr(rSFOFTrig,label).val
    #~ print getattr(rSFOFFact,label).SF.val
    #~ print 0.5*((getattr(rMuE,label).val-0.183218)+1./(getattr(rMuE,label).val-0.183218))*1.084055
    #~ print "0.5*((x-%f)+1./(x-%f))*%f"%(getattr(rMuE,label).val-1,getattr(rMuE,label).val-1,getattr(rSFOFTrig,label).val)
    #~ rSFOFLine = TF1("rSFOF%s"%label,"0.5*((x-%f)+1./(x-%f))*%f"%(getattr(rMuE,label).val-1,getattr(rMuE,label).val-1,getattr(rSFOFTrig,label).val),0.,3.)
    rSFOFLine = TF1("rSFOF%s" % label,
                    "0.5*((x)+1./(x))*%f" % (getattr(rSFOFTrig, label).val),
                    0., 3.)
    rSFOFLine.SetLineColor(ROOT.kRed)
    rSFOFLine.SetLineWidth(2)
    #~ rSFOFTrigUp = TF1("rSFOFUp%s"%label,"0.5*((x-%f)+1./(x-%f))*%f"%(getattr(rMuE,label).val-1,getattr(rMuE,label).val-1,getattr(rSFOFTrig,label).val+getattr(rSFOFTrig,label).err),0.,3.)
    rSFOFTrigUp = TF1(
        "rSFOFUp%s" % label, "0.5*((x)+1./(x))*%f" %
        (getattr(rSFOFTrig, label).val + getattr(rSFOFTrig, label).err), 0.,
        3.)
    rSFOFTrigUp.SetLineColor(ROOT.kBlack)
    rSFOFTrigUp.SetLineWidth(2)
    rSFOFTrigUp.SetLineStyle(ROOT.kDashed)
    #~ rSFOFTrigDown = TF1("rSFOFDown%s"%label,"0.5*((x-%f)+1./(x-%f))*%f"%(getattr(rMuE,label).val-1,getattr(rMuE,label).val-1,getattr(rSFOFTrig,label).val-getattr(rSFOFTrig,label).err),0.,3.)
    rSFOFTrigDown = TF1(
        "rSFOFDown%s" % label, "0.5*((x)+1./(x))*%f" %
        (getattr(rSFOFTrig, label).val - getattr(rSFOFTrig, label).err), 0.,
        3.)
    rSFOFTrigDown.SetLineColor(ROOT.kBlack)
    rSFOFTrigDown.SetLineWidth(2)
    rSFOFTrigDown.SetLineStyle(ROOT.kDashed)

    rmueline = ROOT.TF1("rmueline", "%s" % getattr(rSFOFFact, label).SF.val, 0,
                        3)
    rmueline.SetLineColor(ROOT.kBlue)
    rmueline.SetLineWidth(3)
    rmueline.SetLineStyle(2)
    rmueline.Draw("SAME")

    line1 = ROOT.TLine(
        getattr(rMuE, label).val, 0,
        getattr(rMuE, label).val, 2)
    line1.Draw("Same")
    line1.SetLineWidth(2)
    line1.SetLineColor(ROOT.kGreen + 3)
    legendHistDing = ROOT.TH1F()
    legendHistDing.SetFillColor(ROOT.kWhite)
    legend.AddEntry(legendHistDing, "Factorization method:", "h")
    legend.AddEntry(rSFOFLine, "R_{SF/OF} (r_{#mu e})", "l")
    legend.AddEntry(rSFOFTrigDown,
                    "R_{SF/OF} (r_{#mu e}) #pm 1 #sigma on R_{T} ", "l")
    legend.AddEntry(ge, "measured r_{#mu e} #pm 1 #sigma", "fl")
    legend.AddEntry(ge2, "measured R_{SF/OF} #pm 1 #sigma", "fl")

    legend.Draw("SAME")

    rSFOFLine.Draw("SAME")
    rSFOFTrigUp.Draw("SAME")
    rSFOFTrigDown.Draw("SAME")

    latex = ROOT.TLatex()
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latex.DrawLatex(0.15, 0.96, "%s dilepton selection" % label.title())

    hCanvas.Print("fig/rMuEPropaganda_%s.pdf" % label)
def plotBlockComparison(treeBlockA,
                        treeBlockB,
                        variable,
                        additionalCut,
                        nBins,
                        firstBin,
                        lastBin,
                        labelX,
                        labelY,
                        suffix,
                        log=False,
                        signal=False):

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

    legend = TLegend(0.7, 0.55, 0.95, 0.95)
    legend.SetFillStyle(0)
    legend.SetBorderSize(1)

    minMll = 20

    ROOT.gStyle.SetOptStat(0)
    Cutlabel = ROOT.TLatex()
    Cutlabel.SetTextAlign(12)
    Cutlabel.SetTextSize(0.03)
    Labelin = ROOT.TLatex()
    Labelin.SetTextAlign(12)
    Labelin.SetTextSize(0.07)
    Labelin.SetTextColor(ROOT.kRed + 2)
    Labelout = ROOT.TLatex()
    Labelout.SetTextAlign(12)
    Labelout.SetTextSize(0.07)
    Labelout.SetTextColor(ROOT.kBlack)

    EMuhistBlockA = createHistoFromTree(treeBlockA, variable, additionalCut,
                                        nBins, firstBin, lastBin, -1)

    EMuhistBlockB = createHistoFromTree(treeBlockB, variable, additionalCut,
                                        nBins, firstBin, lastBin, -1)

    EMuhistBlockB.Scale(9.2 / 10.4)
    print EMuhistBlockA.Integral()
    print EMuhistBlockB.Integral()
    EMuhistBlockA.SetMarkerStyle(21)
    EMuhistBlockB.SetMarkerStyle(22)
    EMuhistBlockA.SetMarkerColor(ROOT.kGreen + 3)
    EMuhistBlockB.SetMarkerColor(ROOT.kBlack)
    EMuhistBlockA.SetLineColor(ROOT.kGreen + 3)
    EMuhistBlockB.SetLineColor(ROOT.kBlack)

    if log:
        yMin = 0.1
        yMax = max(EMuhistBlockA.GetBinContent(EMuhistBlockA.GetMaximumBin()),
                   EMuhistBlockB.GetBinContent(
                       EMuhistBlockB.GetMaximumBin())) * 10
        plotPad.SetLogy()
    else:
        yMin = 0
        yMax = max(EMuhistBlockA.GetBinContent(EMuhistBlockA.GetMaximumBin()),
                   EMuhistBlockB.GetBinContent(
                       EMuhistBlockB.GetMaximumBin())) * 1.5
    hCanvas.DrawFrame(firstBin, yMin, lastBin, yMax,
                      "; %s ; %s" % (labelX, labelY))

    EMuhistBlockA.Draw("samep")
    EMuhistBlockB.Draw("samep")

    legend.AddEntry(EMuhistBlockA, "First 9.2 fb^{-1}", "p")
    legend.AddEntry(EMuhistBlockB, "Second 10.4 fb^{-1} scaled", "p")
    #~
    latex = ROOT.TLatex()
    latex.SetTextSize(0.043)
    latex.SetTextFont(42)
    latex.SetNDC(True)
    latex.DrawLatex(
        0.13, 0.95,
        "CMS Preliminary,    #sqrt{s} = 8 TeV,     #scale[0.6]{#int}Ldt = 9.2-10.4 fb^{-1}"
    )
    #~

    legend.Draw("same")

    ratioPad.cd()

    ratioGraphs = ratios.RatioGraph(EMuhistBlockA,
                                    EMuhistBlockB,
                                    firstBin,
                                    lastBin,
                                    title="Bl. A / Bl. B",
                                    yMin=0.0,
                                    yMax=2,
                                    ndivisions=10,
                                    color=ROOT.kGreen + 3,
                                    adaptiveBinning=0.25)

    ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8)
    if signal:
        name = "OFUnblinding_SignalRegion_%s_%s.pdf"
    else:
        name = "OFUnblinding_Inclusive_%s_%s.pdf"
    if variable == "p4.M()":

        hCanvas.Print(name % (suffix, "Mll"))
    else:
        hCanvas.Print(name % (suffix, variable))
        hCanvas.Clear()
        iPt) * fDataOverFONLL['min'].GetParameter(0) * 1.e-6 - extrapCross
    hCrossSecExtrap.SetBinContent(iPt, extrapCross)
    hCrossSecExtrap.SetBinError(iPt, 0.)
    gCrossSecExtrap.SetPoint(iPt - 1, ptCent, extrapCross)
    gCrossSecExtrapSyst.SetPoint(iPt - 1, ptCent, extrapCross)
    gCrossSecExtrap.SetPointError(iPt - 1, 0.4, 0.4, systLow, systHigh)
    gCrossSecExtrapSyst.SetPointError(iPt - 1, 0.4, 0.4, systLow, systHigh)

legFit = TLegend(0.2, 0.7, 0.4, 0.9)
legFit.SetTextSize(0.045)
legFit.SetBorderSize(0)
legFit.SetFillStyle(0)

cFit = TCanvas('cFit', '', 500, 500)
hFrame = cFit.DrawFrame(ptMinMeas, 0., ptMaxMeas,
                        hDataOverFONLL['min'].GetMaximum() * 2,
                        ';#it{p}_{T} (GeV/#it{c});data/FONLL')
hFrame.GetYaxis().SetDecimals()
for var in ['cent', 'min', 'max']:
    hDataOverFONLL[var].Draw('same')
    fDataOverFONLL[var].Draw('same')
    legFit.AddEntry(hDataOverFONLL[var], f'{legNamesFONLL[var]}', 'p')
legFit.Draw()

leg = TLegend(0.3, 0.7, 0.7, 0.9)
leg.SetTextSize(0.045)
leg.SetBorderSize(0)
leg.SetFillStyle(0)
leg.AddEntry(hCrossSec, f'measured', 'p')
leg.AddEntry(hCrossSecExtrap, f'extrapolated', 'p')
leg.AddEntry(hFONLL['cent'], f'FONLL + PYTHIA8 decayer', 'f')
Beispiel #7
0
    else:
        effAcc = hEffAccFD.GetBinContent(iPt + 1)
        frac = fFD

    crossSec, crossSecUnc = ComputeCrossSection(rawYield, rawYieldUnc, effAcc,
                                                1., ptMax - ptMin, 1., sigmaMB,
                                                nEv, BR)
    hCrossSection.SetBinContent(iPt + 1, crossSec)
    hCrossSection.SetBinError(iPt + 1, crossSecUnc)

SetGlobalStyle()
cCrossSec = TCanvas('cCrossSec', '', 700, 800)
hCrossSection.Draw()

cFrac = TCanvas('cFrac', '', 800, 800)
cFrac.DrawFrame(hPromptFrac.GetBinLowEdge(1), 0., ptMax, 1.,
                ';#it{p}_{T} (GeV/#it{c}); fraction')
hPromptFrac.Draw('same')
hFDFrac.Draw('same')

cEff = TCanvas('cEff', '', 800, 800)
cEff.DrawFrame(hPromptFrac.GetBinLowEdge(1), 1.e-4, ptMax, 1.,
               ';#it{p}_{T} (GeV/#it{c}); (Acc#times#font[152]{e})')
hEffAccPrompt.Draw('same')
hEffAccFD.Draw('same')

outFile = TFile(args.outFileName)
hCrossSection.Write()
hRawYields.Write()
hEffAccPrompt.Write()
hEffAccFD.Write()
hPromptFrac.Write()
Beispiel #8
0
    PtMin, 0., PtMax, hSignal[1].GetMaximum() * 2,
    ';#it{p}_{T} (GeV/#it{c}); raw yields / #it{N}_{events}')
for iFile, _ in enumerate(inputfilenames):
    hSignal[iFile].Draw('same')
leg.Draw()
cSignal.cd(2).DrawFrame(
    PtMin, 0., PtMax, hRatioSignal[1].GetMaximum() * 2,
    ';#it{p}_{T} (GeV/#it{c}); ratio of raw yields / #it{N}_{events}')
for iFile, _ in enumerate(inputfilenames):
    if iFile == 0:
        continue
    hRatioSignal[iFile].Draw('same')

cRatioSignal = TCanvas('cRatioSignal', '', 800, 800)
cRatioSignal.DrawFrame(
    PtMin, 0.5, PtMax, hRatioSignal[1].GetMaximum() * 2,
    ';#it{p}_{T} (GeV/#it{c}); ratio of raw yields / #it{N}_{events}')
for iFile, _ in enumerate(inputfilenames):
    hRatioSignal[iFile].Draw('same')
leg.Draw()

cBkg = TCanvas('cBkg', '', 1000, 500)
cBkg.Divide(2, 1)
cBkg.cd(1).DrawFrame(
    PtMin, hBackground[0].GetMinimum() * 0.5, PtMax,
    hBackground[0].GetMaximum() * 2,
    ';#it{p}_{T} (GeV/#it{c}); background(3#sigma) / #it{N}_{events}')
cBkg.cd(1).SetLogy()
for iFile, _ in enumerate(inputfilenames):
    hBackground[iFile].Draw('same')
leg.Draw()
Beispiel #9
0
def crossSectionValuePlot(group,groups,keys_no_comb,
                          sigmas,stats,systs,lumis,tots):
    delChars = '#\\/+.~${}><,?[]|&^_!@%*()-`;:\'\"'
    sigmas_lcl = array('d',sigmas[:])
    stats_lcl  = array('d',stats[:])
    systs_lcl  = array('d',systs[:])
    tots_lcl   = array('d',tots[:])
    lumis_lcl  = array('d',lumis[:])
    
    if 'combined' in groups[group]:
        sig, sta, sys, tot = getCSInfo(groups[group]['combined'])
        sigmas_lcl.insert(0,sig)
        stats_lcl.insert(0,sta)
        systs_lcl.insert(0,sys)
        tots_lcl.insert(0,tot)
        lumis_lcl.insert(0,sig*lumi_err/100.0)

    sigmas_lcl.insert(0,mc_info['sigma'])
    stats_lcl.insert(0,mc_info['theory_err'])
    systs_lcl.insert(0,mc_info['theory_err'])
    tots_lcl.insert(0,mc_info['theory_err'])
    lumis_lcl.insert(0,mc_info['theory_err'])

    for i in range(1,len(sigmas_lcl)):
        tots_lcl[i] = hypot(tots_lcl[i],lumis_lcl[i])

    yvals   = array('d',[i*2 for i in range(1,len(sigmas_lcl)+1)])
    yerrs   = array('d',[0 for i in range(len(sigmas_lcl))])
    toterrs = array('d',stats_lcl[0:1] +tots_lcl[1:len(tots_lcl)])

    gStats = TGraphErrors(len(sigmas_lcl),sigmas_lcl,yvals,stats_lcl,yerrs)
    gTotes = TGraphErrors(len(sigmas_lcl),sigmas_lcl,yvals,toterrs,yerrs)
    
    canv = TCanvas(group+'val','',500,500)
    canv.cd()
    frame = canv.DrawFrame(1,0,1.35*mc_info['sigma'],2*(len(sigmas_lcl)+1))
    frame.GetXaxis().SetTitle("Cross Section (pb)")
    unshitify(frame)
    gTotes.SetMarkerColor(2)
    gTotes.SetMarkerStyle(20)
    gTotes.SetLineColor(4)
    gTotes.SetLineWidth(2)
    gTotes.Draw("PE1")
    gStats.SetMarkerColor(2)
    gStats.SetMarkerStyle(20)
    gStats.SetLineColor(1)
    gStats.SetLineWidth(2)
    gStats.Draw("PE1")

    tex1 = TLatex()
    tex1.SetTextSize(0.04)
    tex2 = TLatex()
    tex2.SetTextSize(0.03)
    xmin = 1
    xmax = 1.30*mc_info['sigma']
    xscale = xmax - xmin
    xpad = xmin + (xmax-xmin)*xpadfactor

    ymin = 0
    ymax = 2*(len(sigmas_lcl)+1)
    yscale = ymax-ymin
    ypad = ymin + yscale*ypadfactor

    for i in range(len(sigmas_lcl)):        
        if i == 0:
            tex1.DrawLatex(xpad,yvals[i]-0.009*yscale,
                          "#font[132]{Theory Prediction}")
            tex2.DrawLatex(xpad,yvals[i]-0.065*yscale,
                          "#font[132]{%.2f #pm %.2f pb}"%(sigmas_lcl[i],
                                                          stats_lcl[i]))
        else:
            if('combined' in groups[group]):
                if( i == 1 ):
                    tex1.DrawLatex(xpad,yvals[i]-0.009*yscale,
                              "#font[132]{BLUE Combination}")
                else:
                   tex1.DrawLatex(xpad,yvals[i]-0.009*yscale,
                          "#font[132]{%s: %s}"%(group,
                                                keys_no_comb[i-2]))
            else:
                if 'combined' in group:
                    tex1.DrawLatex(xpad,yvals[i]-0.009*yscale,
                          "#font[132]{BLUE Comb.: %s}"%keys_no_comb[i-1])
                else:                    
                    tex1.DrawLatex(xpad,yvals[i]-0.009*yscale,
                          "#font[132]{%s: %s}"%(group,
                                                keys_no_comb[i-1]))            
                
            tex2.DrawLatex(xpad,yvals[i]-0.065*yscale,
                          "#font[132]{%.2f #pm "%sigmas_lcl[i]+
                          "%.2f (stat.) #pm "%stats_lcl[i]+
                          "%.2f (syst.) #pm "%systs_lcl[i]+
                          "%.2f (lumi.) pb}"%lumis_lcl[i])       

    #flavor text
    tex1.DrawLatex(0.85*xpad,yvals[-1] + 0.95*ypad,
                   "#font[132]{%s}"%luminosity)
    
    for i,flav in enumerate(flavor_text.split('\\')):
        tex1.DrawLatex(3.7*xpad,
                       yvals[-1] + (1.20-0.50*i)*ypad,
                       "#font[132]{%s}"%flav)
       
    tex1.DrawLatex(xmin,ymax+0.08,
                   "#font[132]{CMS Preliminary 2011}")
    tex1.DrawLatex(xmin+0.78*xscale,
                   ymax+0.08,
                   "#font[132]{#sqrt{s} = 7 TeV}")

    saneName = group.translate(None,delChars)
    valName = saneName+"_CS_value_plot"

    canv.Print(valName+".png")
    canv.Print(valName+".eps")
    canv.Print(valName+".pdf")
def main():
    from sys import argv
    from ROOT import TCanvas, TPad, TH1F, TH2F, TH1I, THStack, TLegend, TF1, TGraphErrors, TTree
    from numpy import array
    import numpy as n

    from setTDRStyle import setTDRStyle
    region = "SignalNonRectCombinedConstrained"

    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)

    style = setTDRStyle()
    plotPad.UseCurrentStyle()
    plotPad.Draw()
    plotPad.cd()

    #~ result=([name,0., parameters,parametersError,parametersMass,parametersChi2,parametersLogLH0,parametersLogLH1, project, region, title, name])

    bckgOnlyPkl = loadToysForBackgroundOnly(region)
    bckgOnlyHist = TH1F("bckgOnlyHist", "bckgOnlyHist", 50, -1, 22)
    nTest = 0
    nTestLarger = 0

    nominatorHist = ROOT.TH1F("nominatorHist", "nominatorHist", 1, 0, 1)
    nominatorHistFull = ROOT.TH1F("nominatorHist", "nominatorHist", 1, 0, 1)
    denominatorHist = ROOT.TH1F("denominatorHist", "denominatorHist", 1, 0, 1)
    denominatorHistFull = ROOT.TH1F("denominatorHist", "denominatorHist", 1, 0,
                                    1)

    for index, value in bckgOnlyPkl[2].iteritems():
        if not index == "38ed30c9":
            if bckgOnlyPkl[4][index] > 0:
                denominatorHistFull.Fill(0.5)
                if -2 * (bckgOnlyPkl[7][index] -
                         bckgOnlyPkl[6][index]) >= 2 * 4.3808:
                    nominatorHistFull.Fill(0.5)
                if bckgOnlyPkl[4][index] < 90 and bckgOnlyPkl[4][index] > 0:
                    bckgOnlyHist.Fill(
                        -2 * (bckgOnlyPkl[7][index] - bckgOnlyPkl[6][index]))
                    nTest = nTest + 1
                    denominatorHist.Fill(0.5)
                    if -2 * (bckgOnlyPkl[7][index] -
                             bckgOnlyPkl[6][index]) >= 2 * 4.3808:
                        nTestLarger = nTestLarger + 1
                        nominatorHist.Fill(0.5)
    print nTest, nTestLarger

    hCanvas.Clear()
    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    plotPad.UseCurrentStyle()
    plotPad.Draw()
    plotPad.cd()
    hCanvas.DrawFrame(
        -1, 0, 18,
        bckgOnlyHist.GetBinContent(bckgOnlyHist.GetMaximumBin()) + 20,
        "; %s ; %s" % ("-2*(log(L_{1})-log(L_{0}))", "N_{Results}"))
    chi2Shape = ROOT.TF1("chi2Shape", "[2]*TMath::GammaDist(x,[0],[1],2)", 0,
                         18)
    chi2Shape.SetParameters(1.5, 0, 200)
    #~ chi2Shape.Draw("same")
    #~ bckgOnlyHist.Fit("chi2Shape")
    hCanvas.DrawFrame(
        -1, 0, 22,
        bckgOnlyHist.GetBinContent(bckgOnlyHist.GetMaximumBin()) + 20,
        "; %s ; %s" % ("-2*(log(L_{1})-log(L_{0}))", "N_{Results}"))

    latex = ROOT.TLatex()
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latex.DrawLatex(
        0.15, 0.96,
        "CMS Simulation  #sqrt{s} = 8 TeV,     #scale[0.6]{#int}Ldt = %s fb^{-1}"
        % 19.4)
    latex = ROOT.TLatex()
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    #~ latex.DrawLatex(0.6, 0.6, "#splitline{fit of #chi^{2} dist., NDF = %.2f}{#chi^{2}/N_{dof} %.2f}"%(chi2Shape.GetParameter(0)*2,chi2Shape.GetChisquare()/chi2Shape.GetNDF()))

    observedLine = ROOT.TLine(
        2 * 4.3808, 0, 2 * 4.3808,
        bckgOnlyHist.GetBinContent(bckgOnlyHist.GetMaximumBin()) + 20)
    observedLine.SetLineColor(ROOT.kRed)
    observedLine.SetLineStyle(2)
    observedLine.Draw("same")
    bckgOnlyHist.Draw("samepe")
    #~ chi2Shape.Draw("same")
    ROOT.gStyle.SetOptStat(0)
    ROOT.gStyle.SetOptFit(0)

    legend = ROOT.TLegend(0.5, 0.75, 0.95, 0.95)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextFont(42)
    legend.AddEntry(observedLine, "observed", "l")
    hist = ROOT.TH1F()
    hist.SetLineColor(ROOT.kWhite)

    #~ efficiencyObject = ROOT.TEfficiency(nominatorHist,denominatorHist)
    #~ uncertaintyUp = efficiencyObject.Wilson(nTestLarger,nTest,0.69,ROOT.kTRUE)
    #~ uncertaintyDown = efficiencyObject.Wilson(nTestLarger,nTest,0.69,ROOT.kFALSE)
    #~ print uncertaintyUp

    pValue = getEffciency(nominatorHist, denominatorHist)
    pValueFull = getEffciency(nominatorHistFull, denominatorHistFull)

    #~ legend.AddEntry(hist,"p-Value low mass: %.3f + %.3f - %.3f (%.2f #sigma)"%(pValue[0],pValue[1],pValue[2], ROOT.TMath.NormQuantile(1.0-pValue[0]/2)))
    legend.AddEntry(
        hist, "p-Value: %.3f + %.3f - %.3f (%.2f #sigma)" %
        (pValueFull[0], pValueFull[1], pValueFull[2],
         ROOT.TMath.NormQuantile(1.0 - pValue[0] / 2)))
    legend.Draw("same")
    hCanvas.Print("significanceStudy_BackgroundOnly.pdf")
    hCanvas.Print("significanceStudy_BackgroundOnly.root")

    print nTest, nTestLarger
Beispiel #11
0
    hYieldPromptReco.SetBinContent(iPt + 1, nRecoPromptWeighted)
    hYieldPromptReco.SetBinError(iPt + 1,
                                 nRecoPromptWeighted / math.sqrt(nRecoPrompt))
    hYieldFDReco.SetBinContent(iPt + 1, nRecoFDWeighted)
    hYieldFDReco.SetBinError(iPt + 1, nRecoFDWeighted / math.sqrt(nRecoFD))

leg = TLegend(0.6, 0.2, 0.8, 0.4)
leg.SetTextSize(0.045)
leg.SetFillStyle(0)
leg.AddEntry(hEffPrompt, "Prompt", "p")
leg.AddEntry(hEffFD, "Feed-down", "p")

hEffPrompt.SetDirectory(0)
hEffFD.SetDirectory(0)
cEff = TCanvas('cEff', '', 800, 800)
cEff.DrawFrame(PtMin[0], 1.e-5, PtMax[nPtBins - 1], 1.,
               ';#it{p}_{T} (GeV/#it{c});(Acc #times #epsilon);')
cEff.SetLogy()
hEffPrompt.Draw('same')
hEffFD.Draw('same')
leg.Draw()

outFile = TFile(args.outFileName, 'recreate')
hEffPrompt.Write()
hEffFD.Write()
hYieldPromptGen.Write()
hYieldFDGen.Write()
hYieldPromptReco.Write()
hYieldFDReco.Write()
outFile.Close()

if not args.batch:
Beispiel #12
0
        "higgsCombineExpectedMuNoSys.MultiDimFit.mH120.root"
    ],
    'both': [
        "higgsCombineExpectedBothFullUncertainty.MultiDimFit.mH120.root",
        "higgsCombineExpectedBothNoTau.MultiDimFit.mH120.root",
        "higgsCombineExpectedBothNoSys.MultiDimFit.mH120.root"
    ],
}

gROOT.SetBatch()
gStyle.SetOptStat(0)

c1 = TCanvas("c1", "Expected Bias Band Graph", 200, 10, 800, 800)

#c1.SetGrid();
c1.DrawFrame(0.85, 0.75, 1.15, 1.25)
c1.cd()

leg = TLegend(0.6, 0.7, 0.89, 0.89)

file_full_el_exp = TFile(
    "higgsCombineExpectedElFullUncertainty.MultiDimFit.mH120.root")
file_full_mu_exp = TFile(
    "higgsCombineExpectedMuFullUncertainty.MultiDimFit.mH120.root")
file_full_both_exp = TFile(
    "higgsCombineExpectedBothFullUncertainty.MultiDimFit.mH120.root")

file_full_el_obs = TFile(
    "higgsCombineElFullUncertainty.MultiDimFit.mH120.root")
file_full_mu_obs = TFile(
    "higgsCombineMuFullUncertainty.MultiDimFit.mH120.root")
Beispiel #13
0
from ROOT import TTree, TFile, gROOT, gStyle, TCanvas, TGraph, TLegend
from array import array

f = TFile('mleak_chk.no_leak.root')
tr = f.Get('tr')

gROOT.SetStyle('Plain')

c = TCanvas('c', 'c', 640, 480)
c.SetTopMargin(0.05)
c.SetRightMargin(0.05)

gStyle.SetGridStyle(1)
gStyle.SetGridColor(16)
c.SetGrid()
h = c.DrawFrame(0, 0, 8000, 1200)
N = tr.GetEntries()

tr.Draw('committed_AS/1000:Entry$', '', 'goff')
g1 = TGraph(tr.GetSelectedRows(), tr.GetV2(), tr.GetV1())
g1.SetLineWidth(2)
g1.Draw('')

tr.Draw('memFree/1000:Entry$', '', 'goff')
g2 = TGraph(tr.GetSelectedRows(), tr.GetV2(), tr.GetV1())
g2.SetLineWidth(2)
g2.SetLineStyle(2)
g2.Draw('')

tr.Draw('swapFree/1000:Entry$', '', 'goff')
g3 = TGraph(tr.GetSelectedRows(), tr.GetV2(), tr.GetV1())
Beispiel #14
0
def main(): #pylint: disable=too-many-statements
    SetGlobalStyle(padleftmargin=0.18, padbottommargin=0.14, titleoffsety=1.6, maxdigits=2, optstat=0)

    inFileFONLL = TFile.Open('fonll/feeddown/DmesonLcPredictions_502TeV_y05_FFee_BRpythia8_SepContr_PDG2020.root')
    hFONLLPromptD0 = inFileFONLL.Get('hD0Kpipred_max')
    hFONLLPromptDplus = inFileFONLL.Get('hDpluskpipipred_max')
    hFONLLPromptDs = inFileFONLL.Get('hDsPhipitoKkpipred_max')
    hFONLLNonPromptD0 = inFileFONLL.Get('hD0KpifromBpred_central_corr')
    hFONLLNonPromptDplus = inFileFONLL.Get('hDpluskpipifromBpred_central_corr')
    hFONLLNonPromptDs = inFileFONLL.Get('hDsPhipitoKkpifromBpred_central_corr')

    binLims = np.array([0., 1., 2., 3., 4., 5., 6., 7., 8., 10., 12., 16., 24.], 'd')
    nBins = 12

    hFONLLPromptD0 = hFONLLPromptD0.Rebin(nBins, 'hFONLLPromptD0', binLims)
    hFONLLPromptDplus = hFONLLPromptDplus.Rebin(nBins, 'hFONLLPromptDplus', binLims)
    hFONLLPromptDs = hFONLLPromptDs.Rebin(nBins, 'hFONLLPromptDs', binLims)
    hFONLLNonPromptD0 = hFONLLNonPromptD0.Rebin(nBins, 'hFONLLNonPromptD0', binLims)
    hFONLLNonPromptDplus = hFONLLNonPromptDplus.Rebin(nBins, 'hFONLLNonPromptDplus', binLims)
    hFONLLNonPromptDs = hFONLLNonPromptDs.Rebin(nBins, 'hFONLLNonPromptDs', binLims)

    hFONLLNPfracD0 = hFONLLPromptD0.Clone('hFONLLNPfracD0')
    hFONLLNPfracD0.Divide(hFONLLNonPromptD0, hFONLLNPfracD0)
    hFONLLNPfracDplus = hFONLLPromptDplus.Clone('hFONLLNPfracDplus')
    hFONLLNPfracDplus.Divide(hFONLLNonPromptDplus, hFONLLNPfracDplus)
    hFONLLNPfracDs = hFONLLPromptDs.Clone('hFONLLNPfracDs')
    hFONLLNPfracDs.Divide(hFONLLNonPromptDs, hFONLLNPfracDs)

    SetObjectStyle(hFONLLNPfracD0, color=kRed, linewitdh=2, markerstyle=0, fillstyle=0)
    SetObjectStyle(hFONLLNPfracDplus, color=kGreen, linewitdh=2, markerstyle=0, fillstyle=0)
    SetObjectStyle(hFONLLNPfracDs, color=kOrange, linewitdh=2, markerstyle=0, fillstyle=0)

    mesonList = ['D0', 'D+', 'Ds']
    histoList = [hFONLLNPfracD0, hFONLLNPfracDplus, hFONLLNPfracDs]

    print(*binLims, sep=' ')
    for meson, histo in zip(mesonList, histoList):
        valueList = []
        for iBin in range(1, nBins + 1):
            valueList.append(f'{histo.GetBinContent(iBin):.3f}')
        print(meson)
        print(*valueList, sep=' ')

    legMeson = TLegend(0.65, 0.6, 0.85, 0.8)
    legMeson.SetTextSize(0.04)
    legMeson.SetFillStyle(0)
    legMeson.AddEntry(hFONLLNPfracD0, 'D^{0}', 'l')
    legMeson.AddEntry(hFONLLNPfracDplus, 'D^{+}', 'l')
    legMeson.AddEntry(hFONLLNPfracDs, 'D_{s}^{+}', 'l')

    cFrac = TCanvas('cFrac', '', 500, 500)
    hFrame = cFrac.DrawFrame(0., 0.01, 24., 1.05, ';#it{p}_{T} (GeV/#it{c}); #it{f}_{non-prompt}')
    hFrame.GetYaxis().SetDecimals()
    hFrame.Draw('axis same')
    hFONLLNPfracD0.Draw('same')
    hFONLLNPfracDplus.Draw('same')
    hFONLLNPfracDs.Draw('same')
    legMeson.Draw('same')
    cFrac.Update()

    TFile('./NaturalNonPromptFrac_FONLL_FFee_BRpythia8.root', 'recreate')
    hFONLLNPfracD0.Write()
    hFONLLNPfracDplus.Write()
    hFONLLNPfracDs.Write()
    cFrac.Write()

    input('Press enter to exit')
    updatemgrsvc.newEvent( gauditime )
    #updatemgrsvc.update()
    globalcenter = element.geometry().toGlobal( origin )
    #print timeiter, ' ', \
    #      gauditime.format(True,"%D %T"), " --> ", \
    #      '(',  globalcenter.x() , ",", globalcenter.y(), ",", globalcenter.z(), ")"
    #print timeiter, gauditime.nanoformat(True), gauditime.year(False)
    timeiter += timeinterval
    
    xgraph.SetPoint( ipoint, timeiter - roottimeoffset, globalcenter.x() )
    if abs( globalcenter.x() ) > xmax:
        xmax = abs( globalcenter.x() )
    ipoint +=1

canvas = TCanvas('c1')
frame = canvas.DrawFrame(timebegin- roottimeoffset,-1.1*xmax,timeend- roottimeoffset,1.1*xmax)
frame.SetTitle(element.name())
frame.GetXaxis().SetTimeDisplay(True)

period = timeend - timebegin
if period < 25*3600:
    frame.GetXaxis().SetTimeFormat("%H:%M")
else:
    frame.GetXaxis().SetTimeFormat("%d/%m")
xgraph.SetMarkerStyle(20)    
xgraph.SetMarkerSize(0.5)    
xgraph.Draw("P")

canvas.Print('globalposition.eps')

Beispiel #16
0
def crossSectionRatioPlot(group,groups,keys_no_comb,
                          sigmas,stats,systs,lumis,tots):
    delChars = '#\\/+.~${}><,?[]|&^_!@%*()-`;:\'\"'
    sigmas_lcl = array('d',sigmas[:])
    stats_lcl  = array('d',stats[:])
    systs_lcl  = array('d',systs[:])
    tots_lcl   = array('d',tots[:])
    lumis_lcl  = array('d',lumis[:])
    tots_theory = array('d')
    
    if 'combined' in groups[group]:
        sig, sta, sys, tot = getCSInfo(groups[group]['combined'])
        sigmas_lcl.insert(0,sig)
        stats_lcl.insert(0,sta)
        systs_lcl.insert(0,sys)
        tots_lcl.insert(0,tot)
        lumis_lcl.insert(0,sig*lumi_err/100.0)
    
    for i in range(len(sigmas_lcl)):
        tots_lcl[i] = tots_lcl[i]/sigmas_lcl[i]
        sigmas_lcl[i] = sigmas_lcl[i]/mc_info['sigma']        
        tots_theory.append(hypot(tots_lcl[i],
                                 mc_info['theory_err']/mc_info['sigma']))
    
    yvals   = array('d',[i*2 for i in range(1,len(sigmas_lcl)+1)])    
    xones   = array('d',[1 for i in range(len(sigmas_lcl))])
    x1serrs = array('d',[lumi_err/100.0 for i in range(len(sigmas_lcl))])
    yerrs   = array('d',[0 for i in range(len(sigmas_lcl))])
    y1serrs = array('d',[2 for i in range(len(sigmas_lcl))])

    gStats = TGraphErrors(len(sigmas_lcl),sigmas_lcl,yvals,tots_lcl,yerrs)
    gTotes = TGraphErrors(len(sigmas_lcl),sigmas_lcl,yvals,tots_theory,yerrs)
    gLine  = TGraphErrors(len(sigmas_lcl),xones,yvals,x1serrs,y1serrs)

    lOne = TLine(1,0,1,2*(len(sigmas_lcl)+1))    
    
    canv = TCanvas(group+'val','',500,500)
    canv.cd()
    frame = canv.DrawFrame(0.1,0,2,2*(len(sigmas_lcl)+1))
    frame.GetXaxis().SetTitle("Ratio (CMS/Theory)")
    unshitify(frame)
    gLine.SetFillColor(6)
    gLine.SetFillStyle(3004)
    gLine.Draw("E2")
    lOne.SetLineWidth(2)
    lOne.SetLineColor(6)
    lOne.Draw()
    gTotes.SetMarkerColor(2)
    gTotes.SetMarkerStyle(20)
    gTotes.SetLineColor(4)
    gTotes.SetLineWidth(2)
    gTotes.Draw("PE1")
    gStats.SetMarkerColor(2)
    gStats.SetMarkerStyle(20)
    gStats.SetLineColor(1)
    gStats.SetLineWidth(2)
    gStats.Draw("PE1")    

    tex1 = TLatex()
    tex1.SetTextSize(0.04)
    tex2 = TLatex()
    tex2.SetTextSize(0.03)    
    xmin = 0.1
    xmax = 2.0
    xscale = xmax - xmin
    xpad = xmin + xscale*xpadfactor

    ymin = 0
    ymax = 2*(len(sigmas_lcl)+1)
    yscale = ymax-ymin
    ypad = ymin + yscale*ypadfactor

    for i in range(len(sigmas_lcl)):
        if('combined' in groups[group]):
            if( i == 0 ):
                tex2.DrawLatex(0.75*xpad,yvals[i]-0.009*yscale,
                               "#font[132]{BLUE Combination}")
            else:
                tex2.DrawLatex(0.75*xpad,yvals[i]-0.009*yscale,
                               "#font[132]{%s: %s}"%(group,
                                                     keys_no_comb[i-1]))
        else:
            if 'combined' in group:
                tex2.DrawLatex(0.75*xpad,yvals[i]-0.009*yscale,
                               "#font[132]{BLUE Comb.: %s}"%keys_no_comb[i])
            else:
                tex2.DrawLatex(0.75*xpad,yvals[i]-0.009*yscale,
                               "#font[132]{%s: %s}"%(group,
                                                     keys_no_comb[i]))
                
        tex2.DrawLatex(4.60*xpad,yvals[i]-0.009*yscale,
                       "#font[132]{%.2f #pm "%sigmas_lcl[i]+
                       "%.2f_{exp} #pm "%tots_lcl[i]+
                       "%.2f_{theo}}"%(mc_info['theory_err']/mc_info['sigma']))

    #flavor text
    tex1.DrawLatex(0.85*xpad,yvals[-1] + 0.95*ypad,
                   "#font[132]{%s}"%luminosity)
    
    for i,flav in enumerate(flavor_text.split('\\')):
        tex1.DrawLatex(3.7*xpad,
                       yvals[-1] + (1.40-0.50*i)*ypad,
                       "#font[132]{%s}"%flav)
        

    tex1.DrawLatex(xmin,ymax+0.08,
                   "#font[132]{CMS Preliminary 2011}")
    tex1.DrawLatex(xmin+0.78*xscale,
                   ymax+0.08,
                   "#font[132]{#sqrt{s} = 7 TeV}")

    #lumi uncertainty
    tex1.SetTextColor(6)
    tex1.DrawLatex(3.7*xpad,
                   yvals[0] - 1.5*ypad,
                   "#font[132]{lumi. uncertainty %.1f}"%lumi_err
                   + "%")                      
    
    saneName = group.translate(None,delChars)
    valName = saneName+"_CS_ratio_plot"

    canv.Print(valName+".png")
    canv.Print(valName+".eps")
    canv.Print(valName+".pdf")
Beispiel #17
0
        SetObjectStyle(gRatioFDOverFONLL, color=kBlack, fillstyle=0)

    lineFONLLFD = TLine(ptMinFD, 1., ptMaxFD, 1.)
    lineFONLLFD.SetLineColor(kAzure + 4)
    lineFONLLFD.SetLineWidth(2)

# protection for log scale
if sigmaMin <= 0:
    sigmaMin = 1.e-3
if args.logx and ptMin <= 0:
    print('WARNING: disabling log scale for x axis because minimum pT <= 0!')
    args.logx = False

cCrossSec = TCanvas('cCrossSec', '', 700, 800)
hFrame = cCrossSec.DrawFrame(
    ptMin, sigmaMin, ptMax, sigmaMax,
    ';#it{p}_{T} (GeV/#it{c});#frac{d#sigma}{d#it{p}_{T}} (#mub GeV^{-1} #it{c})'
)
hFrame.GetXaxis().SetMoreLogLabels()
cCrossSec.SetLogy()
if args.logx:
    cCrossSec.SetLogx()

if args.logx:
    legPrompt = TLegend(0.65, 0.75, 0.85, 0.9)
    legFD = TLegend(0.25, 0.2, 0.45, 0.35)
else:
    legPrompt = TLegend(0.6, 0.8, 0.8, 0.95)
    legFD = TLegend(0.6, 0.62, 0.8, 0.77)
legPrompt.SetTextSize(0.045)
legPrompt.SetBorderSize(0)
legPrompt.SetFillStyle(0)
Beispiel #18
0
                    metavar='text',
                    default='FONLL.txt',
                    help='input FONLL txt file name')
args = parser.parse_args()

SetGlobalStyle(padleftmargin=0.16, padbottommargin=0.14)

dfModel = pd.read_csv(args.infileFONLL, sep=' ')

gFONLL = TGraphAsymmErrors(len(dfModel))
for iPt, (ptMin, ptMax, crossSec, crossSecMin, crossSecMax) in enumerate(zip(\
    dfModel['ptmin'].values, dfModel['ptmax'].values, dfModel['central'].values, dfModel['min'].values, dfModel['max'].values)):

    print((ptMin + ptMax) / 2, crossSec)
    gFONLL.SetPoint(iPt, (ptMin + ptMax) / 2, crossSec / (ptMax - ptMin))
    gFONLL.SetPointError(iPt, (ptMax - ptMin) / 2, (ptMax - ptMin) / 2,
                         (crossSec - crossSecMin) / (ptMax - ptMin),
                         (crossSecMax - crossSec) / (ptMax - ptMin))

SetObjectStyle(gFONLL, color=864, fillalpha=0.2, markerstyle=20)

cFONLL = TCanvas('cFONLL', '', 500, 500)
cFONLL.DrawFrame(
    0., 1.e4, 24., 1.e8,
    ';d#it{p}_{T} (GeV/#it{c});(d^{2}#sigma/d#it{p}_{T}d#it{y}) (pb^{-1} GeV^{-1} #it{c})'
)
cFONLL.SetLogy()
gFONLL.Draw('2')
gFONLL.Draw('PX')

input()
Beispiel #19
0
def plotLimits(model, lambdas, helicity):

    Mmin = [400 + i * 100 for i in range(29)]
    if model == "CI": Mmin = [800 + i * 100 for i in range(25)]

    N = len(Mmin)
    yellow = TGraph(2*N)    # yellow band
    green = TGraph(2*N)     # green band
    median = TGraph(N)      # median
    
    for i in range(N):
        limit = getCross(Mmin[i], model, lambdas, helicity)
        print Mmin[i], limit[0], limit[1], limit[2], limit[3], limit[4]
        yellow.SetPoint(    i,    Mmin[i], limit[4]) # + 2 sigma
        green.SetPoint(     i,    Mmin[i], limit[3]) # + 1 sigma
        median.SetPoint(    i,    Mmin[i], limit[2]) # median
        green.SetPoint(  2*N-1-i, Mmin[i], limit[1]) # - 1 sigma
        yellow.SetPoint( 2*N-1-i, Mmin[i], limit[0]) # - 2 sigma
    
    W = 800
    H  = 600
    T = 0.08*H
    B = 0.12*H
    L = 0.12*W
    R = 0.04*W
    c = TCanvas("c","c",100,100,W,H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin( L/W )
    c.SetRightMargin( R/W )
    c.SetTopMargin( T/H )
    c.SetBottomMargin( B/H )
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    c.cd()
    if model == "ADD":
        frame = c.DrawFrame(Mmin[0], 2, Mmin[-1], 10)
    else:
        frame = c.DrawFrame(Mmin[0], 2, Mmin[-1], 50)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(0.9)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    frame.GetYaxis().SetTitle("95% limit of #Lambda_{T}")
    if model == "CI": frame.GetYaxis().SetTitle("95% limit of #Lambda")
    frame.GetXaxis().SetTitle("M_{#font[12]{l}#font[12]{l}}^{min} (GeV)")
    #frame.SetMinimum(0)
    #frame.SetMaximum(max(up2s)*1.05)
    #frame.GetXaxis().SetLimits(min(values),max(values))
 
    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    yellow.Draw('F')
 
    green.SetFillColor(ROOT.kGreen+1)
    green.SetLineColor(ROOT.kGreen+1)
    green.SetFillStyle(1001)
    green.Draw('Fsame')
 
    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')
 
    CMS_lumi.CMS_lumi(c,13,11)
    ROOT.gPad.SetTicks(1,1)
    frame.Draw('sameaxis')
 
    x1 = 0.42
    x2 = x1 + 0.24
    y2 = 0.86
    y1 = 0.70
    legend = TLegend(x1,y1,x2,y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.041)
    legend.SetTextFont(42)
    legend.AddEntry(median, "Asymptotic CL_{s} expected of %s%s"%(model, helicity),'L')
    legend.AddEntry(green, "#pm 1 std. deviation",'f')
    legend.AddEntry(yellow,"#pm 2 std. deviation",'f')
    legend.Draw()

    c.SaveAs("%slimits/%sLimit_ee_LimitVsMmin%s.png"%(model, model, helicity))
    c.Close()
Beispiel #20
0
def plotUpperLimits(labels, values):
    # see CMS plot guidelines: https://ghm.web.cern.ch/ghm/plots/

    N = len(labels)
    yellow = TGraph(2 * N)  # yellow band
    green = TGraph(2 * N)  # green band
    median = TGraph(N)  # median line

    up2s = []
    for i in range(N):
        # file_name = "higgsCombine"+labels[i]+"AsymptoticLimits.mH125.root"
        file_name = "higgsCombine.AsymptoticLimits.mH125." + labels[i] + ".root"
        limit = getLimits(file_name)
        # print'limit = ',limit
        # print'values[i] = ',values[i]
        up2s.append(limit[4])
        yellow.SetPoint(i, values[i], limit[4])  # + 2 sigma
        green.SetPoint(i, values[i], limit[3])  # + 1 sigma
        median.SetPoint(i, values[i], limit[2])  # median
        green.SetPoint(2 * N - 1 - i, values[i], limit[1])  # - 1 sigma
        yellow.SetPoint(2 * N - 1 - i, values[i], limit[0])  # - 2 sigma

    W = 800
    H = 600
    T = 0.08 * H
    B = 0.12 * H
    L = 0.12 * W
    R = 0.04 * W
    c = TCanvas("c", "c", 100, 100, W, H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    # c.SetLogy()
    # gPad.SetLogy()
    c.cd()
    # ROOT.gPad.SetLogy()
    # c.SetLogy()
    frame = c.DrawFrame(1.4, 0.001, 4.1, 10)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(0.9)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    # frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}")

    if (args.atlas_compare):
        frame.GetYaxis().SetTitle(
            "95% CL limits on #sigma(gg#rightarrow X)#times B(X#rightarrow HH) [pb]"
        )
    elif (args.CMS_compare):
        frame.GetYaxis().SetTitle(
            "95% CL limit on #sigma(gg#rightarrow X#rightarrow HH) (fb)")
#    frame.GetYaxis().SetTitle("95% upper limit on #sigma #times BR / (#sigma #times BR)_{SM}")
# frame.GetXaxis().SetTitle("background systematic uncertainty [%]")
#if(args.SM_Radion): frame.GetXaxis.SetTitle("Standard Model")
#else: frame.GetXaxis().SetTitle("Radion Mass (GeV)")
# frame.SetMinimum(0)
# frame.SetMinimum(1) # need Minimum > 0 for log scale
    frame.SetMinimum(1.000001)  # need Minimum > 0 for log scale
    # frame.SetMaximum(max(up2s)*1.05)
    # frame.SetMaximum(max(up2s)*2)
    # frame.SetMaximum(1000.)

    if (args.atlas_compare):
        frame.SetMaximum(7 * 1e2)  # ATLAS
    elif (args.CMS_compare):
        frame.SetMaximum(8 * 1e4)  # CMS HH
    #frame.GetXaxis().SetLimits(min(values),max(values))
    # frame.SetLogy()
    frame.GetXaxis().SetLimits(min(values) - 10, max(values) + 10)

    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    yellow.Draw('F')

    green.SetFillColor(ROOT.kGreen + 1)
    green.SetLineColor(ROOT.kGreen + 1)
    green.SetFillStyle(1001)
    green.Draw('Fsame')

    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')

    CMS_lumi.CMS_lumi(c, 4, 11)
    ROOT.gPad.SetTicks(1, 1)
    frame.Draw('sameaxis')

    # yboost = 0.075
    yboost = -0.2

    x1 = 0.15
    x2 = x1 + 0.24
    y2 = 0.76 + yboost
    y1 = 0.60 + yboost
    legend = TLegend(x1, y1, x2, y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.041)
    legend.SetTextFont(42)
    legend.AddEntry(median, "AsymptoticLimits CL_{s} expected", 'L')
    legend.AddEntry(green, "#pm 1 std. deviation", 'f')
    #    legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 1 std. deviation",'f')
    legend.AddEntry(yellow, "#pm 2 std. deviation", 'f')
    # legend.AddEntry("","STAT Only","")
    #    legend.AddEntry(green, "AsymptoticLimits CL_{s} #pm 2 std. deviation",'f')
    legend.Draw()

    label = TLatex()
    label.SetNDC()
    label.SetTextAngle(0)
    label.SetTextColor(kBlack)
    label.SetTextFont(42)
    label.SetTextSize(0.045)
    label.SetLineWidth(2)
    label.DrawLatex(0.7, 0.7 + yboost, "STAT only")
    print " "
    # c.SaveAs("UpperLimit.png")

    outFile = ''
    if (args.CMS_compare):
        outFile += "CMS_Compare_"
    if (args.atlas_compare):
        outFile += "atlas_Compare_"

    if args.SM_Radion: outFile += "SM_"

    c.SaveAs(outFile + "UpperLimit.pdf")
    c.SaveAs(outFile + "UpperLimit.C")
    c.Close()
    legAbs = TLegend(0.18, 0.815, 0.45, 0.965)
    legAbs.SetTextSize(0.045)
    legAbs.SetBorderSize(1)
    legAbs.SetFillColor(kWhite)
    legAbs.SetHeader(f'#rho = {gAbsVar.GetCorrelationFactor():0.3f}')
    if removeOutliersRel:
        legAbs.AddEntry(gRelVar, 'considered', 'p')
        legAbs.AddEntry(gRelVarOutliers, 'outliers', 'p')

if doRelVar:
    cRelVar = TCanvas('cRelVar', '', 800, 800)
    minVals = np.min(relVar, axis=0)
    maxVals = np.max(relVar, axis=0)
    hFrameRel = cRelVar.DrawFrame(
        minVals[0] - 0.5 * abs(minVals[0]), minVals[1] - 0.5 * abs(minVals[1]),
        maxVals[0] + 0.5 * abs(maxVals[0]), maxVals[1] + 0.5 * abs(maxVals[1]),
        f";relative variation of {varName['var1']};relative variation of {varName['var2']}"
    )
    hFrameRel.GetYaxis().SetDecimals()
    hFrameRel.GetYaxis().SetNdivisions(505)
    hFrameRel.GetXaxis().SetNdivisions(505)
    SetObjectStyle(gRelVar, color=kAzure + 4, markerstyle=kFullCircle)
    gRelVar.Draw('P')
    if removeOutliersRel:
        SetObjectStyle(gRelVarOutliers,
                       color=kRed + 1,
                       markerstyle=kFullCircle)
        gRelVarOutliers.Draw('P')
        legRel.Draw()
    cRelVar.SaveAs(f'{outFileName}_RelativeVariation.pdf')
if doAbsVar:
Beispiel #22
0
def limit_canvas(limits_, signal_, oname_):

    m = [mp.mass for mp in limits_]
    exp = [mp.exp for mp in limits_]
    exp68up = [mp.exp68up for mp in limits_]
    exp68dn = [mp.exp68dn for mp in limits_]
    exp95up = [mp.exp95up for mp in limits_]
    exp95dn = [mp.exp95dn for mp in limits_]
    obs = [mp.obs for mp in limits_]

    N = len(limits_)
    gExp = TGraph()
    g68 = TGraph(2*N)
    g95 = TGraph(2*N)
    gObs = TGraph()
    gTH = get_theory_XsecBR_graph(signal_)

    for a in range(0,N):
        gExp.SetPoint(a,m[a],exp[a])
        gObs.SetPoint(a,m[a],obs[a])
        g68.SetPoint(a,m[a],exp68dn[a])
        g95.SetPoint(a,m[a],exp95dn[a])
        g68.SetPoint(N+a,m[N-a-1],exp68up[N-a-1])
        g95.SetPoint(N+a,m[N-a-1],exp95up[N-a-1])

    trans = 0
    up = 0
    if signal_ == 'n':
        trans = 0.770776
        up = 3
    if signal_ == 'w':
        trans = 0.836432
        up = 10
    if signal_ == 'r':
        trans = 0.899902
        up = 4

    gExp.SetLineStyle(2)
    gExp.SetLineWidth(4)
    gExp.SetLineColor(TColor.GetColor('#112288'))
    #gExp.Print()

    g68.SetLineStyle(1)
    g68.SetLineWidth(0)
    g68.SetLineColor(kBlack)
    g68.SetFillColor(TColor.GetColor('#4488dd'))

    g95.SetLineStyle(1)
    g95.SetLineWidth(0)
    g95.SetLineColor(kBlack)
    g95.SetFillColor(TColor.GetColor('#99bbff'))

    gObs.SetLineStyle(1)
    gObs.SetLineWidth(4)
    gObs.SetLineColor(kBlack)
    gObs.SetMarkerStyle(21)
    gObs.SetMarkerSize(0.8)

    gTH.SetLineStyle(7)
    gTH.SetLineWidth(4)
    gTH.SetMarkerSize(0)
    gTH.SetMarkerColor(kRed+1)
    gTH.SetLineColor(kRed+1)

    leg = TLegend(0.58,0.633,0.969,0.908)
    leg.SetFillColor(0)
    leg.SetBorderSize(0)
    leg.AddEntry(gExp,'Expected (95% CL)','l')
    leg.AddEntry(gObs,'Observed (95% CL)','l')
    leg.AddEntry(gTH,signal_dict[signal_][1],'l')
    leg.AddEntry(g68,'#pm1#sigma Expected','f')
    leg.AddEntry(g95,'#pm2#sigma Expected','f')

    text_TL = TPaveText(0.18,0.830,0.44,0.900,'NDC')
    text_TL.AddText(label_TL)
    text_TL.SetFillColor(0)
    text_TL.SetTextAlign(12)
    text_TL.SetTextSize(0.06)
    text_TL.SetTextFont(42)

    text_TR = TPaveText(0.586,0.923,0.999,0.997,'NDC')
    text_TR.AddText(label_TR)
    text_TR.SetFillColor(0)
    text_TR.SetTextAlign(32)
    text_TR.SetTextSize(0.055)
    text_TR.SetTextFont(42)

    c = TCanvas('c','c',950,750)
    c.SetTopMargin(0.08)
    c.SetRightMargin(0.02)
    c.SetBottomMargin(0.135)
    c.SetLeftMargin(0.11)
    #c.SetGrid()
    c.SetLogy()

    #hr = c.DrawFrame(0.401,0.001,3.999,1000)
    #hr = c.DrawFrame(0.401,0.001,4.199,1000)
    hr = c.DrawFrame(0.401,0.001,5.199,1000)
    gExp.Sort()
    gTH.Print()
    g95.Draw('f')
    g95.Print()
    g68.Draw('f')
    gTH.Draw('L')
    gExp.Draw('L')

#Don't draw observed for blind analysis
#    gObs.Sort()
#    gObs.Draw('L')

    hr.GetXaxis().SetTitle('M_{'+signal_dict[signal_][0]+'} [TeV]')
    hr.GetYaxis().SetTitle('Upper limit on #sigma_{'+signal_dict[signal_][0]+'} #times B('+signal_dict[signal_][0]+' #rightarrow t#bar{t}) [pb]')
    #hr.GetYaxis().SetTitle('\\mathrm{Upper~limit~on~}\\sigma_{'+signal_dict[signal_][0]+'}\\times\\mathscr{B}('+signal_dict[signal_][0]+' \\rightarrow t\\bar{t}) [pb]')
    hr.GetXaxis().SetTitleSize(0.055)
    hr.GetYaxis().SetTitleSize(0.055)
    hr.GetXaxis().SetTitleFont(42)
    hr.GetYaxis().SetTitleFont(42)
    hr.GetXaxis().SetTitleOffset(1.00)
    hr.GetYaxis().SetTitleOffset(0.98)
    hr.GetXaxis().SetLabelSize(0.045)
    hr.GetYaxis().SetLabelSize(0.045)

    name = TString(oname_)
    if name.Contains("com"):
        tl = TLine(trans, 1e-3, trans, up)
        tl.SetLineStyle(ROOT.kDashed)
        tl.SetLineColor(kGray+1)
        tl.SetLineWidth(3)
        tl.Draw()

    c.Update()
    text_TL.Draw('same')
    text_TR.Draw('same')
    leg.Draw()

    c.SaveAs(oname_+'.pdf')
    c.Close()
    setTDRStyle()
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()

    legend = TLegend(0.7, 0.55, 0.95, 0.95)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)

    yMin = 0
    yMax = max(eeHist.GetBinContent(eeHist.GetMaximumBin()),
               mmHist.GetBinContent(mmHist.GetMaximumBin())) * 1.5
    hCanvas.DrawFrame(
        0, yMin, 2.5, yMax,
        "; %s ; %s" % ("|#eta^{leading}|", "N_{events} / 0.1 [a.u.]"))
    ROOT.gStyle.SetOptStat(0)

    eeHist.SetLineColor(ROOT.kRed)
    eeHist.SetLineWidth(2)
    eeHist.SetLineStyle(2)
    #~ eeHist.SetLineColor(ROOT.kRed)
    fakeHist = ROOT.TH1F()
    fakeHist.SetLineColor(ROOT.kWhite)
    legend.SetHeader("t#bar{t} Simulation")
    legend.AddEntry(eeHist, "e^{#pm}e^{#mp}", "l")
    legend.AddEntry(mmHist, "#mu^{#pm}#mu^{#mp}", "l")

    eeHist.Draw("samehist")
    mmHist.Draw("samehist")
Beispiel #24
0
def plotUpperLimits(labels, masses, **kwargs):
    print color("plotUpperLimits()", color="magenta", prepend=">>>\n>>> ")
    # https://raw.githubusercontent.com/nucleosynthesis/HiggsAnalysis-CombinedLimit/combine_tutorial_SWAN/combine_tutorials_2016/combine_intro/plotPvalue.py

    # SIGNAL strength & mass
    extralabel = kwargs.get('extralabel', "")

    # LOOP over LABELS
    for label in labels:
        print color("plotUpperLimits - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

        N = len(masses)
        yellow = TGraph(2 * N)  # yellow band
        green = TGraph(2 * N)  # green band
        median = TGraph(N)  # median line

        up2s = []
        down2s = []
        for i, mass in enumerate(masses):
            filename = getOutputFilename(label, mass, extralabel=extralabel)
            limits = getLimits(filename)
            yellow.SetPoint(i, mass, limits[4])  # + 2 sigma
            green.SetPoint(i, mass, limits[3])  # + 1 sigma
            median.SetPoint(i, mass, limits[2])  # median
            green.SetPoint(2 * N - 1 - i, mass, limits[1])  # - 1 sigma
            yellow.SetPoint(2 * N - 1 - i, mass, limits[0])  # - 2 sigma
            down2s.append(limits[0])
            up2s.append(limits[4])

        ymax = max(up2s) * 1.20
        ymin = min(down2s)
        doLog = ymin and ymax / min(down2s) > 4
        xtitle = "m_{X} [GeV]"
        ytitle = "95% upper limit on #sigma#timesBR(X #rightarrow #tau#tau) [pb]"
        if "bbA" in extralabel:
            xtitle = "m_{A} [GeV]"
            ytitle = "95% upper limit on #sigma#timesBR(A #rightarrow #tau#tau) [pb]"

        W, H = 800, 600
        T, B = 0.08 * H, 0.12 * H
        L, R = 0.12 * W, 0.04 * W
        canvas = TCanvas("canvas", "canvas", 100, 100, W, H)
        canvas.SetFillColor(0)
        canvas.SetBorderMode(0)
        canvas.SetFrameFillStyle(0)
        canvas.SetFrameBorderMode(0)
        canvas.SetTopMargin(T / H)
        canvas.SetBottomMargin(B / H)
        canvas.SetLeftMargin(L / W)
        canvas.SetRightMargin(R / W)
        canvas.SetTickx(0)
        canvas.SetTicky(0)
        canvas.SetGrid()
        canvas.cd()
        if doLog:
            ymin = 0.1  #10**(floor(log(ymin,10))-1)
            ymax = 1000  #10**(ceil(log(ymax,10))+1)
            #ymin, ymax = 0.1, 1000
            canvas.SetLogy()
        else:
            ymin *= 0 if ymin > 0 else 1.20

        frame = canvas.DrawFrame(min(masses), ymin, max(masses), ymax)
        frame.GetYaxis().SetTitleSize(0.055)
        frame.GetXaxis().SetTitleSize(0.055)
        frame.GetXaxis().SetLabelSize(0.044)
        frame.GetYaxis().SetLabelSize(0.044)
        frame.GetXaxis().SetLabelOffset(0.010)
        frame.GetXaxis().SetTitleOffset(1.04)
        frame.GetYaxis().SetTitleOffset(1.08)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(True)
        frame.GetYaxis().SetTitle(ytitle)
        frame.GetXaxis().SetTitle(xtitle)

        yellow.SetFillColor(kOrange)
        yellow.SetLineColor(kOrange)
        yellow.SetFillStyle(1001)
        yellow.Draw('F')

        green.SetFillColor(kGreen + 1)
        green.SetLineColor(kGreen + 1)
        green.SetFillStyle(1001)
        green.Draw('Fsame')

        median.SetLineColor(1)
        median.SetLineWidth(2)
        median.SetLineStyle(2)
        median.Draw('Lsame')

        CMS_lumi.CMS_lumi(canvas, 13, 0)
        gPad.SetTicks(1, 1)
        gPad.Modified()
        frame.Draw('sameaxis')

        width = 0.28
        height = 0.20
        #x1 = 0.16; x2 = x1 + width # Left
        x2 = 0.80
        x1 = x2 - width  # Right
        x2 = x1 + width

        y1 = 0.68
        y2 = y1 + height
        legend = TLegend(x1, y1, x2, y2)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.040)
        legend.SetTextFont(62)
        legend.SetHeader("%s" % (label_dict[label + extralabel]))
        legend.SetTextFont(42)
        legend.AddEntry(median, "Asymptotic CL_{s} expected", 'L')
        legend.AddEntry(green, "#pm 1 std. deviation", 'f')
        #legend.AddEntry(green, "Asymptotic CL_{s} #pm 1 std. deviation",'f')
        legend.AddEntry(yellow, "#pm 2 std. deviation", 'f')
        #legend.AddEntry(green, "Asymptotic CL_{s} #pm 2 std. deviation",'f')
        legend.Draw()

        print " "
        canvas.SaveAs("%s/upperLimit-%s%s.png" %
                      (PLOTS_DIR, label, extralabel))
        canvas.SaveAs("%s/upperLimit-%s%s%s.pdf" %
                      (PLOTS_DIR, label, extralabel))
        canvas.Close()
    hRho00Charm.SetBinError(iPt + 1,
                            ciRho00VsNonPromptFrac[iPt].GetBinError(1))

    hRho00Beauty.SetBinContent(iPt + 1,
                               ciRho00VsNonPromptFrac[iPt].GetBinContent(1000))
    hRho00Beauty.SetBinError(iPt + 1,
                             ciRho00VsNonPromptFrac[iPt].GetBinError(1000))

cRho00VsPromptFrac.Modified()
cRho00VsPromptFrac.Update()

cRho00VsNonPromptFrac.Modified()
cRho00VsNonPromptFrac.Update()

cRho00vsPt = TCanvas('cRho00vsPt', '', 500, 500)
cRho00vsPt.DrawFrame(ptMins[0], 0., ptMaxs[-1], 0.6,
                     ';#it{p}_{T} (GeV/#it{c});#it{#rho}_{00}')
lineNoPolVsPt.Draw('same')
hRho00Charm.DrawCopy('same')
hRho00Beauty.DrawCopy('same')

leg = TLegend(0.2, 0.2, 0.5, 0.35)
leg.SetTextSize(0.045)
leg.SetFillStyle(0)
leg.SetBorderSize(0)
leg.AddEntry(hRho00Charm, 'c #rightarrow D*^{+}', 'pl')
leg.AddEntry(hRho00Beauty, 'b #rightarrow D*^{+}', 'pl')
leg.Draw()

# output
outFileName = inputCfg['output']['file']
Beispiel #26
0
def plotPValues(labels, masses0, **kwargs):
    print color("plotPValues()", color="magenta", prepend=">>>\n>>> ")

    # SIGNAL strength & mass
    bins = kwargs.get('bins', [])
    ymin = 0.00005

    # LOOP over LABELS
    for label in labels:
        print color("plotPValues - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

        masses = array('d', [])
        zeros = array('d', [])
        limitObs = array('d', [])
        limitExps = []

        up2s = []
        for i, mass in enumerate(masses0):
            bin = -1
            if bins: bin = bins[i]
            filename = getOutputFilename(label,
                                         mass,
                                         method="ProfileLikelihood",
                                         bin=bin,
                                         extralabel=".SignifObs")
            limitObs.append(getLimits(filename, brazilian=False))
            masses.append(mass)
            zeros.append(0.0)

        v_masses = TVectorD(len(masses), masses)
        v_zeros = TVectorD(len(zeros), zeros)
        v_limitObs = TVectorD(len(limitObs), limitObs)
        v_limitExps = []
        for limitExp in limitExps:
            v_limitExps.append(TVectorD(len(limitExp), limitExp))

        W = 800
        H = 600
        T = 0.08 * H
        B = 0.12 * H
        L = 0.12 * W
        R = 0.04 * W
        canvas = TCanvas("canvas", "canvas", 100, 100, W, H)
        canvas.SetFillColor(0)
        canvas.SetBorderMode(0)
        canvas.SetFrameFillStyle(0)
        canvas.SetFrameBorderMode(0)
        canvas.SetLeftMargin(L / W)
        canvas.SetRightMargin(R / W)
        canvas.SetTopMargin(T / H)
        canvas.SetBottomMargin(B / H)
        canvas.SetTickx(0)
        canvas.SetTicky(0)
        canvas.SetGrid()
        canvas.SetLogy()  # log
        canvas.cd()

        frame = canvas.DrawFrame(1.4, 0.001, 4.1, 10)
        frame.GetYaxis().CenterTitle()
        frame.GetYaxis().SetTitleSize(0.05)
        frame.GetXaxis().SetTitleSize(0.05)
        frame.GetXaxis().SetLabelSize(0.04)
        frame.GetYaxis().SetLabelSize(0.04)
        frame.GetYaxis().SetTitleOffset(1.14)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(False)
        frame.GetYaxis().SetTitle("local p-value")
        #frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}")
        frame.GetXaxis().SetTitle("X#rightarrow#tau#tau mass [GeV]")
        frame.SetMinimum(ymin)
        frame.SetMaximum(1.5)
        frame.GetXaxis().SetLimits(min(masses), max(masses))

        latex = TLatex()
        latex.SetTextSize(0.4 * canvas.GetTopMargin())
        latex.SetTextColor(2)
        f1 = TF1("f1", "0.15866", min(masses), max(masses))
        f1.SetLineColor(2)
        f1.SetLineWidth(2)
        f1.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.15866 * 1.1, "1#sigma")
        f2 = TF1("f2", "0.02275", min(masses), max(masses))
        f2.SetLineColor(2)
        f2.SetLineWidth(2)
        f2.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.02275 * 1.1, "2#sigma")
        f3 = TF1("f3", "0.0013499", min(masses), max(masses))
        f3.SetLineColor(2)
        f3.SetLineWidth(2)
        f3.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.0013499 * 1.1, "3#sigma")

        graph_limitExps = []
        colors = [4, 2, 3, 6, 7, 8]
        for i, v_limitExp in enumerate(v_limitExps):
            graph_limitExps.append(
                TGraphAsymmErrors(v_masses, v_limitExp, v_zeros, v_zeros,
                                  v_zeros, v_zeros))
            graph_limitExps[-1].SetLineColor(colors[i])
            graph_limitExps[-1].SetLineWidth(2)
            graph_limitExps[-1].SetLineStyle(2)
            graph_limitExps[-1].Draw("Lsame")

        graph_limitObs = TGraphAsymmErrors(v_masses, v_limitObs, v_zeros,
                                           v_zeros, v_zeros, v_zeros)
        graph_limitObs.SetLineColor(1)
        graph_limitObs.SetLineWidth(2)
        graph_limitObs.Draw("Csame")

        CMS_lumi.CMS_lumi(canvas, 13, 0)
        gPad.SetTicks(1, 1)
        frame.Draw('sameaxis')

        x1 = 0.62
        x2 = x1 + 0.24
        y1 = 0.15
        y2 = y1 + 0.20
        legend = TLegend(x1, y1, x2, y2)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.041)
        legend.SetTextFont(42)
        legend.SetHeader("%s" % (label_dict[label]))
        legend.AddEntry(graph_limitObs, "observed", 'L')  #p-value
        legend.Draw("same")
        gPad.RedrawAxis()

        print " "
        canvas.SaveAs("%s/p-value-local-%s.png" % (PLOTS_DIR, label))
        canvas.SaveAs("%s/p-value-local-%s.pdf" % (PLOTS_DIR, label))
        canvas.Close()
Beispiel #27
0
    gr_d30 = TGraph(3, energyArr, dummyDoubleArr)

    iAngle = 40
    dummyDoubleArr = array('d')
    dummyDoubleArr.append(ratioDict[iAngle][0])
    dummyDoubleArr.append(ratioDict[iAngle][1])
    dummyDoubleArr.append(ratioDict[iAngle][2])

    gr_d40 = TGraph(3, energyArr, dummyDoubleArr)

    styleGraph(gr_d20, 1)
    styleGraph(gr_d30, 2)
    styleGraph(gr_d40, 3)

    c1 = TCanvas('c1', 'A Simple Graph Example', 0, 0, 800, 600)
    myFrame = c1.DrawFrame(0, 1, 110, 1.03)
    myFrame.GetXaxis().SetLabelSize(0.03)
    myFrame.GetXaxis().SetTitle("Energy [GeV]")
    myFrame.GetYaxis().SetTitle("Correction")

    gr_d20.Draw("P2 same")
    gr_d30.Draw("P2 same")
    gr_d40.Draw("P2 same")

    leg = TLegend(0.35, 0.14, 0.64, 0.36)
    leg.SetBorderSize(0)
    leg.SetTextSize(0.03)
    leg.AddEntry(gr_d20, "20 degree", "p")
    leg.AddEntry(gr_d30, "30 degree", "p")
    leg.AddEntry(gr_d40, "40 degree", "p")
Beispiel #28
0
    ';#it{p}_{T} (GeV/#it{c});mean (GeV/#it{c}^{2})')
hFrameMean.GetYaxis().SetNdivisions(505)
hFrameMean.GetYaxis().SetDecimals()
hMeanMC.DrawCopy('same')
hMeanData.DrawCopy('same')
legPars.Draw()
cMeanSigma.cd(2).DrawFrame(ptLims[0], 0, ptLims[-1], 0.015,
                           ';#it{p}_{T} (GeV/#it{c});FWHM (GeV/#it{c}^{2})')
hFWHMMC.DrawCopy('same')
hFWHMData.DrawCopy('same')
legPars.Draw()
cMeanSigma.Modified()
cMeanSigma.Update()

cEfficiency = TCanvas('cEfficiency', '', 800, 800)
hFrameEff = cEfficiency.DrawFrame(ptLims[0], 0., ptLims[-1], 1.,
                                  ';#it{p}_{T} (GeV/#it{c});efficiency')
hFrameEff.GetYaxis().SetDecimals()
for cut in hEffMC:
    hEffMC[cut].DrawCopy('epsame')
    hEffData[cut].DrawCopy('epsame')
legEff.Draw()
cEfficiency.Modified()
cEfficiency.Update()

cPtInt = TCanvas('cPtInt', '', 800, 800)
cPtInt.Divide(2, 2)
cPtInt.cd(1)
hMassKKSigRegionMC[-1].DrawCopy('E')
hSideBandsMC[-1].DrawCopy('hist same')
fMassKKwoPhiMC[-1].Draw('same')
legMassKK.Draw()
Beispiel #29
0
def plotUpperLimits(sample_limits):
    # adapted from: https://wiki.physik.uzh.ch/cms/limits:brazilianplotexample
    # see CMS plot guidelines: https://ghm.web.cern.ch/ghm/plots/
    labels = list(sample_limits.keys())
    print(labels)
    values = [float(label.replace('p','.')) for label in labels]

    N = len(labels)
    yellow = TGraph(2*N)    # yellow band
    green = TGraph(2*N)     # green band
    median = TGraph(N)      # median line

    up2s = [ ]
    for i in range(N):
        #file_name = "higgsCombine"+labels[i]+"Asymptotic.mH125.root"
        #limit = getLimits(file_name)
        limit = sample_limits[labels[i]]
        up2s.append(limit['up2'])
        yellow.SetPoint(    i,    values[i], limit['up2'] ) # + 2 sigma
        green.SetPoint(     i,    values[i], limit['up1'] ) # + 1 sigma
        median.SetPoint(    i,    values[i], limit['nom'] ) # median
        green.SetPoint(  2*N-1-i, values[i], limit['dn1'] ) # - 1 sigma
        yellow.SetPoint( 2*N-1-i, values[i], limit['dn2'] ) # - 2 sigma

    W = 800
    H  = 600
    T = 0.08*H
    B = 0.12*H
    L = 0.12*W
    R = 0.04*W
    c = TCanvas("c","c",100,100,W,H)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin( L/W )
    c.SetRightMargin( R/W )
    c.SetTopMargin( T/H )
    c.SetBottomMargin( B/H )
    c.SetTickx(0)
    c.SetTicky(0)
    c.SetGrid()
    c.cd()
    frame = c.DrawFrame(1.4,0.001, 4.1, 10)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetXaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetLabelSize(0.04)
    frame.GetYaxis().SetTitleOffset(1.1)
    frame.GetYaxis().SetMaxDigits(3)
    #frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().CenterTitle(True)
    #frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}")
    #frame.GetYaxis().SetTitle("95% upper limit on #sigma #times BR / (#sigma #times BR)_{SM}")
    frame.GetYaxis().SetTitle("95% upper limit on #sigma_{h} #times BR / #sigma_{h}")
    #frame.GetXaxis().SetTitle("background systematic uncertainty [%]")
    frame.GetXaxis().SetTitle("m_{a} [GeV]")
    frame.SetMinimum(0)
    #frame.SetMaximum(max(up2s)*1.05)
    frame.SetMaximum(max(up2s)*1.4)
    #frame.SetMinimum(1.e-4)
    #frame.SetMaximum(1.e-2)
    #ROOT.gPad.SetLogy()
    #frame.GetXaxis().SetLimits(min(values),max(values))
    frame.GetXaxis().SetLimits(0., 1.2) # GeV

    yellow.SetFillColor(ROOT.kOrange)
    yellow.SetLineColor(ROOT.kOrange)
    yellow.SetFillStyle(1001)
    yellow.Draw('F')

    green.SetFillColor(ROOT.kGreen+1)
    green.SetLineColor(ROOT.kGreen+1)
    green.SetFillStyle(1001)
    green.Draw('Fsame')

    median.SetLineColor(1)
    median.SetLineWidth(2)
    median.SetLineStyle(2)
    median.Draw('Lsame')

    #CMS_lumi.CMS_lumi(c,14,11)
    #ROOT.gPad.SetTicks(1,1)
    #frame.Draw('sameaxis')

    x1 = 0.15
    x2 = x1 + 0.24
    y2 = 0.86
    y1 = 0.70
    legend = TLegend(x1,y1,x2,y2)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextSize(0.041)
    legend.SetTextFont(42)
    legend.AddEntry(median, "Asymptotic CL_{s} expected",'L')
    legend.AddEntry(green, "#pm 1 std. deviation",'f')
    #legend.AddEntry(green, "Asymptotic CL_{s} #pm 1 std. deviation",'f')
    legend.AddEntry(yellow,"#pm 2 std. deviation",'f')
    #legend.AddEntry(green, "Asymptotic CL_{s} #pm 2 std. deviation",'f')
    legend.Draw()

    print " "
    c.Draw()
    c.Update()
    c.Print("Plots/UpperLimits%s.eps"%(''))
	setTDRStyle()		
	plotPad.UseCurrentStyle()
	#~ ratioPad.UseCurrentStyle()
	plotPad.Draw()	
	#~ ratioPad.Draw()	
	#~ plotPad.cd()	

	legend = TLegend(0.7, 0.75, 0.95, 0.95)
	legend.SetFillStyle(0)
	legend.SetBorderSize(0)
	
	
	
	yMin=0
	yMax = max(eeHist.GetBinContent(eeHist.GetMaximumBin()),eeHist.GetBinContent(mmHist.GetMaximumBin()))*1.5
	hCanvas.DrawFrame(0,yMin,30,yMax,"; %s ; %s" %("m(ll) [GeV]","N_{events} / 0.5 GeV"))
	ROOT.gStyle.SetOptStat(0)
	
	#~ eeHist.SetLineColor(ROOT.kRed)
	#~ eeHist.SetLineColor(ROOT.kRed)
	fakeHist = ROOT.TH1F()
	fakeHist.SetLineColor(ROOT.kWhite)
	legend.SetHeader("Data")
	legend.AddEntry(eeHist,"e^{#pm}e^{#mp} + #mu^{#pm}#mu^{#mp}","p")
	#~ legend.AddEntry(mmHist,"e^{#pm}#mu^{#mp}","l")
	
	eeHist.Draw("same")
	#~ emHist.Draw("samehist")
	legend.Draw("same")
	
	line1 = ROOT.TLine(20,0,20,yMax)