예제 #1
0
    def getGraph(self):
        from array import array
        from ROOT import TMultiGraph, TLegend, TGraphAsymmErrors
        n = len(self.__x)
        if n != len(self.__y) or n != len(self.__yErrLow) or n != len(
                self.__yErrHigh):
            raise StandardError, "The length of the x(%s), y(%s) and y error(%s,%s) lists does not match" % (
                len(self.__x), len(self.__y), len(
                    self.__yErrLow), len(self.__yErrHigh))

        result = TMultiGraph()
        legendPosition = [
            float(i) for i in self.__getStyleOption("legendPosition").split()
        ]
        legend = TLegend(*legendPosition)
        legend.SetFillColor(0)
        result.SetTitle("%s;%s;%s" %
                        (self.__title, self.__xTitle, self.__yTitle))
        #(refArrays, refLabel) = self.__getRefernceGraphArrays()
        #refGraph = TGraphAsymmErrors(*refArrays)

        #refGraph.SetLineWidth(2)
        #refGraph.SetLineColor(int(self.__config.get("reference","lineColor")))
        #refGraph.SetFillColor(int(self.__config.get("reference","fillColor")))
        #result.Add(refGraph,"L3")
        #legend.AddEntry(refGraph,self.__config.get("reference","name"))

        xErr = array("d", [0 for i in range(n)])
        print "__x = ", self.__x
        print "__y = ", self.__y
        graph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr,
                                  self.__yErrLow, self.__yErrHigh)
        graph.SetLineWidth(2)
        graph.SetFillColor(0)
        graph.SetLineColor(int(self.__getStyleOption("lineColor")))
        graph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        graph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        graph.SetMarkerSize(float(self.__getStyleOption("markerSize")))

        sysGraph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr,
                                     self.__ySysErrLow, self.__ySysErrHigh)
        sysGraph.SetLineWidth(1)
        sysGraph.SetFillColor(0)
        sysGraph.SetLineColor(int(self.__getStyleOption("lineColor")))
        sysGraph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        sysGraph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        sysGraph.SetMarkerSize(float(self.__getStyleOption("markerSize")))

        result.Add(sysGraph, "[]")
        result.Add(graph, "P")
        #        result.SetName("MultiPlots")
        #         result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle))
        result.SetName("MG_%s" % (self.__title))
        legend.AddEntry(graph, self.__getStyleOption("name"))

        #for (x,y,yErr) in zip(self.__x, self.__y, zip(self.__yErrLow,self.__yErrHigh)):
        #    self.__addAnnotaion("hallo",x,y,yErr)

        return (result, legend)
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig,
                             lower1sig, upper2sig, lower2sig):

    channel = np.array(
        [3. * nchannels - 1.5 - 3. * i for i in range(0, nchannels)])
    ey = np.array([0.8 for i in range(0, nchannels)])
    zero = np.zeros(nchannels)

    gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig,
                                    upper1sig, ey, ey)
    gexpect1sig.SetFillColor(kGreen)
    gexpect1sig.SetLineWidth(2)
    gexpect1sig.SetLineStyle(2)

    gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig,
                                    upper2sig, ey, ey)
    gexpect2sig.SetFillColor(kYellow)
    gexpect2sig.SetLineWidth(2)
    gexpect2sig.SetLineStyle(2)

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors(nchannels, obs, channel, zero, ey)
    gobs.SetMarkerStyle(21)
    gobs.SetMarkerSize(1.5)
    gobs.SetLineWidth(2)
    gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    for bin in range(nchannels):
        l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin],
                   channel[bin] + ey[bin])

    # line to separate individual and combined limits
    l.SetLineStyle(1)
    l.SetLineWidth(1)
    l.DrawLine(xmin, 0, xmax, 0)

    # legend
    x1 = gStyle.GetPadLeftMargin() + 0.01
    y2 = 1 - gStyle.GetPadTopMargin() - 0.01
    leg = TLegend(x1, y2 - 0.17, x1 + 0.25, y2)
    leg.SetFillColor(4000)
    leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL")
    leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL")
    leg.AddEntry(gobs, "Observed", "pl")
    leg.Draw()

    return gobs, gexpect1sig, gexpect2sig, leg
예제 #3
0
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig,
                             lower1sig, upper2sig, lower2sig):

    channel = np.array(
        [nchannels - 1.5 - float(i) for i in range(0, nchannels)])
    ey = np.full(nchannels, 0.494)
    zero = np.zeros(nchannels)

    gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig,
                                    upper1sig, ey, ey)
    gexpect1sig.SetFillColor(kGreen)
    gexpect1sig.SetLineWidth(2)
    gexpect1sig.SetLineStyle(2)

    gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig,
                                    upper2sig, ey, ey)
    gexpect2sig.SetFillColor(kYellow)
    gexpect2sig.SetLineWidth(2)
    gexpect2sig.SetLineStyle(2)

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors(nchannels, obs, channel, zero, ey)
    gobs.SetMarkerStyle(21)
    gobs.SetMarkerSize(1.5)
    gobs.SetLineWidth(2)
    #gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    for bin in range(nchannels):
        l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin],
                   channel[bin] + ey[bin])

    # line to separate individual and combined limits
    l.SetLineStyle(1)
    l.SetLineWidth(1)
    l.DrawLine(xmin, 0, xmax, 0)

    # legend
    leg = TLegend(0.75, 0.75, 0.95, 0.9)
    leg.SetFillColor(4000)
    leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL")
    leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL")
    #leg.AddEntry( gobs,        "Observed", "pl" )
    leg.Draw()

    return gobs, gexpect1sig, gexpect2sig, leg
예제 #4
0
    def getGraphSimple(self):
        from array import array
        from ROOT import TMultiGraph, TLegend, TGraphAsymmErrors
        n = len(self.__x)
        if n != len(self.__y) or n != len(self.__yErrLow) or n != len(self.__yErrHigh):
            raise StandardError, "The length of the x(%s), y(%s) and y error(%s,%s) lists does not match"%(len(self.__x), len(self.__y), len(self.__yErrLow), len(self.__yErrHigh))

        legendPosition = [float(i) for i in self.__getStyleOption("legendPosition").split()]
        legend = TLegend(*legendPosition)
        legend.SetFillColor(0)

        xErr = array("d",[0 for i in range(n)])
        print "__x = ", self.__x
        print "__y = ", self.__y
        graph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__yErrLow,self.__yErrHigh)
        graph.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle))
        graph.SetLineWidth(2)
        graph.SetFillColor(0)
        graph.SetLineColor(int(self.__getStyleOption("lineColor")))
        graph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        graph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        graph.SetMarkerSize(float(self.__getStyleOption("markerSize")))
        graph.SetDrawOption("AP")

        return (graph, legend)
예제 #5
0
def convertHistToGraph(hist, useGarwood=False):
    alpha = 1 - 0.6827
    graph = TGraphAsymmErrors(hist.GetNbinsX())
    if useGarwood:
        lastEvent = False
        for i in reversed(range(hist.GetNbinsX())):
            N = hist.GetBinContent(i + 1)
            if not lastEvent and N > 0: lastEvent = True
            if lastEvent and N <= 0.: N = 1.e-6
            L = 0 if N == 0 else ROOT.Math.gamma_quantile(alpha / 2, N, 1.)
            U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1)
            graph.SetPoint(i,
                           hist.GetXaxis().GetBinCenter(i + 1),
                           N if not N == 0 else -1.e99)
            graph.SetPointError(i, 0., 0., N - L, U - N)
    else:
        for i in range(hist.GetNbinsX()):
            graph.SetPoint(i,
                           hist.GetXaxis().GetBinCenter(i + 1),
                           hist.GetBinContent(i + 1))
            graph.SetPointError(i,
                                hist.GetXaxis().GetBinWidth(i + 1) / 2.,
                                hist.GetXaxis().GetBinWidth(i + 1) / 2.,
                                hist.GetBinError(i + 1),
                                hist.GetBinError(i + 1))

    graph.SetLineWidth(hist.GetLineWidth())
    graph.SetLineStyle(hist.GetLineStyle())
    graph.SetLineColor(hist.GetLineColor())
    graph.SetMarkerSize(hist.GetMarkerSize())
    graph.SetMarkerStyle(hist.GetMarkerStyle())
    graph.SetMarkerColor(hist.GetMarkerColor())
    graph.SetFillStyle(hist.GetFillStyle())
    graph.SetFillColor(hist.GetFillColor())
    return graph
예제 #6
0
def makeResidHist(data, bkg):
    pulls = TGraphAsymmErrors(data.GetN())
    pulls.SetName("Pulls")
    pulls.SetLineWidth(data.GetLineWidth())
    pulls.SetLineStyle(data.GetLineStyle())
    pulls.SetLineColor(data.GetLineColor())
    pulls.SetMarkerSize(data.GetMarkerSize())
    pulls.SetMarkerStyle(data.GetMarkerStyle())
    pulls.SetMarkerColor(data.GetMarkerColor())
    pulls.SetFillStyle(data.GetFillStyle())
    pulls.SetFillColor(data.GetFillColor())

    # Add histograms, calculate Poisson confidence interval on sum value
    for i in range(data.GetN()):
        x = data.GetX()[i]
        dyl = data.GetErrorYlow(i)
        dyh = data.GetErrorYhigh(i)
        yy = data.GetY()[i] - bkg.Interpolate(x)  #bkg.GetBinContent(i+1)
        norm = dyl if yy > 0. else dyh
        if norm == 0.:
            yy, dyh, dyl = 0., 0., 0.
        else:
            yy /= norm
            dyh /= norm
            dyl /= norm
        pulls.SetPoint(i, x, yy)
        pulls.SetPointEYhigh(i, dyh)
        pulls.SetPointEYlow(i, dyl)

    return pulls
예제 #7
0
파일: utils.py 프로젝트: zucchett/SFrame
def convertHistToGraph(hist):
    graph = TGraphAsymmErrors(hist.GetNbinsX())
    for i in range(hist.GetNbinsX()):
        graph.SetPoint(i,
                       hist.GetXaxis().GetBinCenter(i), hist.GetBinContent(i))
        graph.SetPointError(i,
                            hist.GetXaxis().GetBinWidth(i) / 2.,
                            hist.GetXaxis().GetBinWidth(i) / 2.,
                            hist.GetBinError(i), hist.GetBinError(i))
    graph.SetLineWidth(hist.GetLineWidth())
    graph.SetLineStyle(hist.GetLineStyle())
    graph.SetLineColor(hist.GetLineColor())
    graph.SetMarkerSize(hist.GetMarkerSize())
    graph.SetMarkerStyle(hist.GetMarkerStyle())
    graph.SetMarkerColor(hist.GetMarkerColor())
    graph.SetFillStyle(hist.GetFillStyle())
    graph.SetFillColor(hist.GetFillColor())
    return graph
예제 #8
0
def histToGraph(hist, name='', keepErrors=True, poissonErrors=True):
    ## Helper method to convert a histogram to a corresponding graph
    #  @hist           TH1 object
    #  @name           name of the graph (default is name of histogram)
    #  @keepErrors     decide if the y-errors should be propagated to the graph
    #  @poissonErrors  decide if the y-errors should be calculated as Poisson errors
    #  @return graph
    if not name:
        name = 'g%s' % (hist.GetName())
    from ROOT import TGraphAsymmErrors
    nBins = hist.GetNbinsX()
    graph = TGraphAsymmErrors(nBins)
    graph.SetNameTitle(name, hist.GetTitle())
    xAxis = hist.GetXaxis()
    for i in xrange(nBins):
        xVal = xAxis.GetBinCenter(i + 1)
        yVal = hist.GetBinContent(i + 1)
        graph.SetPoint(i, xVal, yVal)
        graph.SetPointEXlow(i, abs(xVal - xAxis.GetBinLowEdge(i + 1)))
        graph.SetPointEXhigh(i, abs(xVal - xAxis.GetBinUpEdge(i + 1)))
        if keepErrors:
            if poissonErrors:
                lo, hi = calculatePoissonErrors(yVal)
                graph.SetPointEYlow(i, lo)
                graph.SetPointEYhigh(i, hi)
            else:
                graph.SetPointEYlow(i, hist.GetBinErrorLow(i + 1))
                graph.SetPointEYhigh(i, hist.GetBinErrorUp(i + 1))
    # copy the style
    graph.SetMarkerStyle(hist.GetMarkerStyle())
    graph.SetMarkerColor(hist.GetMarkerColor())
    graph.SetMarkerSize(hist.GetMarkerSize())
    graph.SetLineStyle(hist.GetLineStyle())
    graph.SetLineColor(hist.GetLineColor())
    graph.SetLineWidth(hist.GetLineWidth())
    graph.SetFillColor(hist.GetFillColor())
    graph.SetFillStyle(hist.GetFillStyle())
    return graph
예제 #9
0
    exh_c = np.array(LC_dict['tpr_e_h'])
    eyh_c = np.array(LC_dict['fpr_e_h'])

    # somehow if you call one of the variables before the Draw() method the graph won't work properly
    gr = GAE(n_bins, x, y, exl, exh, eyl, eyh)
    gr_s = GAE(n_bins, x, y, exl, exh, eyl, eyh)

    gr_LC = GAE(1, x_c, y_c, exl_c, exh_c, eyl_c, eyh_c)

    gr_c = gr.Clone()
    gr_sc = gr_s.Clone()

    gr.SetTitle('ROC(zoomed in)')
    #gr.SetMarkerColor(8)
    #gr.SetMarkerStyle(21)
    gr.SetFillColor(632 - 9)
    gr_s.SetTitle('ROC')
    gr_s.SetFillColor(632 - 9)
    gr_sc.SetLineColor(4)

    c1.cd(1)
    gr.GetXaxis().SetRangeUser(0, 0.5)
    gr.GetYaxis().SetRangeUser(0.00001, 0.01)
    gr_c.GetXaxis().SetRangeUser(0, 0.5)
    gr_c.GetXaxis().SetRangeUser(0.00001, 0.01)

    gr_LC.GetXaxis().SetRangeUser(0, 0.5)
    gr_LC.GetYaxis().SetRangeUser(0.00001, 0.01)

    gr_c.SetLineColor(4)
예제 #10
0
def limit():
    method = ''
    channel = "bb"
    particleP = "Z'"
    particle = channel
    multF = ZPTOBB
    THEORY = ['A1', 'B3']

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

    if SY:
        filename = "./combine/limits/MANtag_study/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt"
    else:
        filename = "./combine/limits/MANtag_study/" + BTAGGING + "/" + YEAR + "_M%d.txt"
    if CATEGORY != "":
        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

        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0] * multF)
        Exp0s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][2] * multF,
                            val[m][4] * multF - val[m][3] * multF)
        Exp2s.SetPoint(n, m, val[m][3] * multF)
        Exp2s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][1] * multF,
                            val[m][5] * multF - val[m][3] * multF)
        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])

    for t in THEORY:
        Theory[t] = TGraphAsymmErrors()
        addXZH = True
        for m in sorted(HVT[t]['W']['XS'].keys()):
            if m < mass[0] or m > mass[-1]: continue
            if m > 4500:
                continue  ## for now because I don't have the higher mass xs FIXME
            XsZ, XsZ_Up, XsZ_Down = 0., 0., 0.
            if addXZH:
                XsZ = 1000. * HVT[t]['Z']['XS'][
                    m] * 0.12  #temporary BR value set to 0.12 FIXME
                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]))

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

            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)")
    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)
    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
    drawCMS(LUMI, "Work in Progress", 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/MANtag_study/" + YEAR +
             suffix + ".png")
    c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR +
             suffix + ".pdf")
    if 'ah' in channel or 'sl' in channel:
        c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR +
                 suffix + ".C")
        c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + 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,
        print ""

    return
예제 #11
0
def makePlot(finname,foutname,plottitle='',masstitle='',scale=False):
  xsecs = resonantXsecs if 'resonant' in finname else fcncXsecs
  points = {}
  if BLIND:
    cls = [2.5, 16, 50, 84, 97.5]
  else:
    cls = [2.5, 16, 50, 84, 97.5,'Observed']
  xaxis = []
  for cl in cls:
    points[cl] = []
  xsec=1
  for l in open(finname):
    try:
      if l.strip()[0]=='#':
        continue
      if 'MASS' in l:
        if scale:
          xsec = xsecs[int(l.split()[1])] 
        if VERBOSE:
          print ''
          stdout.write('$%6s$ & $%7.3g$'%(l.split()[1],xsec/(0.667)))
        xaxis.append(float(l.split()[1]))
      else:
        cl,val = parseLine(l)
        points[cl].append(val/xsec)
        if VERBOSE and (cl==50 or cl=='Observed'):
          stdout.write(' & $%10.4g$'%(val/xsec))
    except:
      pass
  if VERBOSE:
    print ''
  
  N = len(xaxis)
  up1Sigma=[]; up2Sigma=[]
  down1Sigma=[]; down2Sigma=[]
  for iM in xrange(N):
    up1Sigma.append(points[84][iM]-points[50][iM])
    up2Sigma.append(points[97.5][iM]-points[50][iM])
    down1Sigma.append(-points[16][iM]+points[50][iM])
    down2Sigma.append(-points[2.5][iM]+points[50][iM])
  
  up1Sigma = array('f',up1Sigma)
  up2Sigma = array('f',up2Sigma)
  down1Sigma = array('f',down1Sigma)
  down2Sigma = array('f',down2Sigma)
  cent = array('f',points[50])
  if not BLIND:
    obs = array('f',points['Observed'])
  xarray = array('f',xaxis)

  xsecarray = array('f',[xsecs[xx] for xx in xaxis])
  xsecarrayLow = array('f',[0.0625*xsecs[xx] for xx in xaxis])
  onearray = array('f',[1 for xx in xaxis])
  graphXsec = TGraph(N,xarray,xsecarray)
  graphXsecLow = TGraph(N,xarray,xsecarrayLow)
  graphOne = TGraph(N,xarray,onearray)

  zeros = array('f',[0 for i in xrange(N)])
  graphCent = TGraph(N,xarray,cent)
  if not BLIND:
    graphObs = TGraph(N,xarray,obs)
  graph1Sigma = TGraphAsymmErrors(N,xarray,cent,zeros,zeros,down1Sigma,up1Sigma)
  graph2Sigma = TGraphAsymmErrors(N,xarray,cent,zeros,zeros,down2Sigma,up2Sigma)
  c = TCanvas('c','c',700,600)
  c.SetLogy()
  c.SetLeftMargin(.15)
  graph2Sigma.GetXaxis().SetTitle(masstitle+' [GeV]')
  if scale:
    graph2Sigma.GetYaxis().SetTitle('Upper limit [#sigma/#sigma_{theory}]')  
  else:
    graph2Sigma.GetYaxis().SetTitle("Upper limit [#sigma] [pb]")  
  graph2Sigma.SetLineColor(5)
  graph1Sigma.SetLineColor(3)
  graph2Sigma.SetFillColor(5)
  graph1Sigma.SetFillColor(3)
  graph2Sigma.SetMinimum(0.5*min(points[2.5]))
  if scale:
    graph2Sigma.SetMaximum(10*max(max(points[97.5]),max(xsecarray),4))
  else:
    graph2Sigma.SetMaximum(10*max(max(points[97.5]),max(xsecarray)))
  graphCent.SetLineWidth(2)
  graphCent.SetLineStyle(2)
  if not BLIND:
    graphObs.SetLineColor(1)
    graphObs.SetLineWidth(3)
  graph1Sigma.SetLineStyle(0)
  graph2Sigma.SetLineStyle(0)
 
  leg = TLegend(0.55,0.7,0.9,0.9)
  leg.AddEntry(graphCent,'Expected','L')
  if not BLIND:
    leg.AddEntry(graphObs,'Observed','L')
  leg.AddEntry(graph1Sigma,'1 #sigma','F')
  leg.AddEntry(graph2Sigma,'2 #sigma','F')
  leg.SetFillStyle(0)
  leg.SetBorderSize(0)

  graph2Sigma.Draw('A3')
  graph1Sigma.Draw('3 same')
  graphCent.Draw('same L')
  if not BLIND:
    graphObs.Draw('same L')
  if scale:
    graphOne.SetLineColor(2)
    graphOne.SetLineWidth(2)
    graphOne.SetLineStyle(2)
    graphOne.Draw('same L')
  else:
    graphXsec.SetLineColor(2)
    graphXsecLow.SetLineColor(4)
    subscript = 'SR' if 'Resonant' in plottitle else 'FC'
    if 'Resonant' in plottitle:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=0.1}{m_{#chi}=100 GeV}'%(subscript,subscript),'l')
    else:
      leg.AddEntry(graphXsec,'Theory a_{%s}=b_{%s}=0.1'%(subscript,subscript),'l')
#    leg.AddEntry(graphXsecLow,'Theory a_{%s}=b_{%s}=0.025'%(subscript,subscript),'l')
    for g in [graphXsec]:
      g.SetLineWidth(2)
      g.SetLineStyle(2)
      g.Draw('same L')
  leg.Draw()
  label = TLatex()
  label.SetNDC()
  label.SetTextFont(62)
  label.SetTextAlign(11)
  label.DrawLatex(0.19,0.85,"CMS")
  label.SetTextFont(52)
  label.DrawLatex(0.28,0.85,"Preliminary")
  label.SetTextFont(42)
  label.SetTextSize(0.6*c.GetTopMargin())
  label.DrawLatex(0.19,0.77,plottitle)
  if scale:
    if 'Resonant' in plottitle:
      label.DrawLatex(0.19,0.7,"a_{SR} = b_{SR} = 0.1")
      label.DrawLatex(0.19,0.64,"m_{#chi}=100 GeV")
    else:
      label.DrawLatex(0.19,0.7,"a_{FC} = b_{FC} = 0.1")
  label.SetTextSize(0.5*c.GetTopMargin())
  label.SetTextFont(42)
  label.SetTextAlign(31) # align right
  label.DrawLatex(0.9, 0.94,"%.1f fb^{-1} (13 TeV)"%(plotConfig.lumi))
  c.SaveAs(foutname+'.pdf')
  c.SaveAs(foutname+'.png')
예제 #12
0
def limit(method, channel):
    particle = channel[1:2]
    particleP = particle + "'" if channel.startswith('X') else channel[0]
    THEORY = ['A1', 'B3'] if channel.startswith('X') else []

    suffix = ""
    if method == "hvt": suffix = "_HVT"
    if method == "cls": suffix = "_CLs"
    if method == "monoH": suffix = "_monoH"

    filename = "./combine/" + method + "/" + channel + "_M%d.txt"
    mass, val = fillValues(filename)

    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
        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0])
        Exp0s.SetPoint(n, m, val[m][3])
        Exp1s.SetPoint(n, m, val[m][3])
        Exp1s.SetPointError(n, 0., 0., val[m][3] - val[m][2],
                            val[m][4] - val[m][3])
        Exp2s.SetPoint(n, m, val[m][3])
        Exp2s.SetPointError(n, 0., 0., val[m][3] - val[m][1],
                            val[m][5] - val[m][3])
        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])

    for t in THEORY:
        Theory[t] = TGraphAsymmErrors()
        for m in sorted(HVT[t]['Z']['XS'].keys()):
            if m < mass[0] or m > mass[-1]: continue
            XsW, XsW_Up, XsW_Down, XsZ, XsZ_Up, XsZ_Down = 0., 0., 0., 0., 0., 0.
            XsZ = 1000. * HVT[t]['Z']['XS'][m] * HVT[t]['Z']['BR'][m]
            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]))

            n = Theory[t].GetN()
            Theory[t].SetPoint(n, m, XsW + XsZ)
            Theory[t].SetPointError(n, 0., 0.,
                                    (XsW - XsW_Down) + (XsZ - XsZ_Down),
                                    (XsW_Up - XsW) + (XsZ_Up - XsZ))

            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 +
                              "h) (fb)")
    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)
    Exp2s.GetYaxis().SetRangeUser(0.01, 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))
    drawAnalysis(channel)
    drawRegion(channel, True)
    drawCMS(LUMI, YEAR, "Preliminary")  #Preliminary

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

    leg = TLegend(0.55, 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()
    """
    if True and channel.endswith('sl'):
        mass, val = fillValues("./combine/alpha/X"+particle+"Hbonly_M%d.txt")
        Exp, Obs = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(mass):
            if not m in val: continue
            Exp.SetPoint(Exp.GetN(), m, val[m][3])
            Obs.SetPoint(Obs.GetN(), m, val[m][0])
        Exp.SetLineWidth(3)
        Exp.SetLineColor(602) #602
        Exp.SetLineStyle(5)
        Obs.SetLineWidth(3)
        Obs.SetLineColor(602)
        Exp.Draw("SAME, L")
        Obs.Draw("SAME, L")
        
        mass15, val15 = fillValues("./combine/Vh_2015/X"+particle+"h_M%d.txt")
        Exp15, Obs15 = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(mass15):
            if not m in val: continue
            Exp15.SetPoint(Exp15.GetN(), m, val15[m][3]*multF*Theory['B3'].GetY()[i]*(0.625 if particle=='V' and m>3000 else 1.))
            Obs15.SetPoint(Obs15.GetN(), m, val15[m][0]*multF*Theory['B3'].GetY()[i]*(0.625 if particle=='V' and m>3000 else 1.))
        Exp15.SetLineWidth(3)
        Exp15.SetLineColor(856) #602
        Exp15.SetLineStyle(6)
        Obs15.SetLineWidth(3)
        Obs15.SetLineColor(856)
        Exp15.Draw("SAME, L")
        #Obs15.Draw("SAME, L")
        
        leg2.AddEntry(Exp, "1+2 b-tag", "l")
    """
    if True and channel == 'AZh':
        massLL, valLL = fillValues("./combine/AZh/AZhll_M%d.txt")
        ExpLL, ObsLL = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massLL):
            if not m in val: continue
            ExpLL.SetPoint(ExpLL.GetN(), m, valLL[m][3] * multF)
            ObsLL.SetPoint(ObsLL.GetN(), m, valLL[m][0] * multF)
        ExpLL.SetLineWidth(3)
        ExpLL.SetLineColor(833)  #602
        ExpLL.SetLineStyle(5)
        ObsLL.SetLineWidth(3)
        ObsLL.SetLineColor(833)
        ExpLL.Draw("SAME, L")
        #ObsLL.Draw("SAME, L")

        massNN, valNN = fillValues("./combine/AZh/AZhnn_M%d.txt")
        ExpNN, ObsNN = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massNN):
            if not m in val: continue
            ExpNN.SetPoint(ExpNN.GetN(), m, valNN[m][3] * multF)
            ObsNN.SetPoint(ObsNN.GetN(), m, valNN[m][0] * multF)
        ExpNN.SetLineWidth(3)
        ExpNN.SetLineColor(855)  #602
        ExpNN.SetLineStyle(6)
        ObsNN.SetLineWidth(3)
        ObsNN.SetLineColor(855)
        ExpNN.Draw("SAME, L")
        #ObsNN.Draw("SAME, L")

        leg2.AddEntry(ExpLL,
                      "Expected, A #rightarrow Zh #rightarrow llb#bar{b}", "l")
        leg2.AddEntry(ExpNN,
                      "Expected, A #rightarrow Zh #rightarrow #nu#nub#bar{b}",
                      "l")

    if method == 'combo':
        massAH, valAH = fillValues("./combine/dijet/X" + particle +
                                   "Hah_M%d.txt")
        ExpAH = TGraphAsymmErrors()
        for i, m in enumerate(massAH):
            if not m in val: continue
            ExpAH.SetPoint(ExpAH.GetN(), m, valAH[m][3] * multF)
        ExpAH.SetLineWidth(2)
        ExpAH.SetLineColor(602)  #602
        ExpAH.SetLineStyle(4)
        ExpAH.Draw("SAME, L")

        massSL, valSL = fillValues("./combine/alpha/X" + particle +
                                   "Hsl_M%d.txt")
        ExpSL = TGraphAsymmErrors()
        for i, m in enumerate(massSL):
            if not m in val: continue
            ExpSL.SetPoint(ExpSL.GetN(), m, valSL[m][3] * multF)
        ExpSL.SetLineWidth(3)
        ExpSL.SetLineColor(860 - 9)  #602
        ExpSL.SetLineStyle(7)
        ExpSL.Draw("SAME, L")

        leg2.AddEntry(ExpAH, "B2G-17-002", "l")
        leg2.AddEntry(ExpSL, "B2G-17-004", "l")

    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("plotsLimit/Exclusion/" + channel + suffix + ".png")
    c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".pdf")
    if 'ah' in channel or 'sl' in channel:
        c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".C")
        c1.Print("plotsLimit/Exclusion/" + channel + 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,
        print ""

    print "p1s[",
    for i in range(Exp0s.GetN()):
        print Exp0s.GetY()[i] + Exp1s.GetErrorYhigh(i), ",",
    print "],"
    print "m1s[",
    for i in range(Exp0s.GetN()):
        print Exp0s.GetY()[i] - Exp1s.GetErrorYlow(i), ",",
    print "],"
    print "[",
    for i in range(Exp0s.GetN()):
        print Exp0s.GetY()[i], ",",
    print "]"

    #if not 'ah' in channel and not 'sl' in channel: return

    # ---------- 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, YEAR, "Preliminary")
    drawAnalysis(channel[1:3])
    c2.Print("plotsLimit/Significance/" + channel + suffix + ".png")
    c2.Print("plotsLimit/Significance/" + channel + suffix + ".pdf")
    #    c2.Print("plotsLimit/Significance/"+channel+suffix+".root")
    #    c2.Print("plotsLimit/Significance/"+channel+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, YEAR, "Preliminary")
    drawAnalysis(channel[1:3])
    c3.Print("plotsLimit/pValue/" + channel + suffix + ".png")
    c3.Print("plotsLimit/pValue/" + channel + suffix + ".pdf")
    #    c3.Print("plotsLimit/pValue/"+channel+suffix+".root")
    #    c3.Print("plotsLimit/pValue/"+channel+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, YEAR, "Preliminary")
    drawAnalysis(channel[1:3])
    c4.Print("plotsLimit/BestFit/" + channel + suffix + ".png")
    c4.Print("plotsLimit/BestFit/" + channel + suffix + ".pdf")
    #    c4.Print("plotsLimit/BestFit/"+channel+suffix+".root")
    #    c4.Print("plotsLimit/BestFit/"+channel+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()
예제 #13
0
    0,
] * len(brazil_data))
rms = array("d", list(map(itemgetter(2), brazil_data)))
rms2 = array("d", [2 * r for r in rms])
low_2sigma = array("d", list(map(itemgetter(3), brazil_data)))
low_1sigma = array("d", list(map(itemgetter(4), brazil_data)))
high_1sigma = array("d", list(map(itemgetter(5), brazil_data)))
high_2sigma = array("d", list(map(itemgetter(6), brazil_data)))

mg = TMultiGraph()
#mg.SetTitle(title)
mg.SetTitle(job_id)

brazil_yellow = TGraphAsymmErrors(len(brazil_data), x, mean, xerr, xerr,
                                  low_2sigma, high_2sigma)
brazil_yellow.SetFillColor(5)
brazil_yellow.SetFillStyle(1001)
brazil_yellow.SetLineColor(3)
brazil_yellow.SetLineWidth(10)
brazil_yellow.SetMarkerColor(3)

brazil_green = TGraphAsymmErrors(len(brazil_data), x, mean, xerr, xerr,
                                 low_1sigma, high_1sigma)
brazil_green.SetFillColor(3)
brazil_green.SetFillStyle(1001)
brazil_green.SetLineColor(3)
brazil_green.SetLineWidth(3)

mg.Add(brazil_yellow)
mg.Add(brazil_green)
mg.Draw("a3")
예제 #14
0
def make1DLimitPlot(xtitle, xvals, obs, exp, exp1plus, exp1minus, exp2plus, exp2minus, theory):
    gStyle.SetOptTitle(0)

    axisTitleSize = 0.041
    axisTitleOffset = 1.2
    axisTitleSizeRatioX   = 0.18
    axisLabelSizeRatioX   = 0.12
    axisTitleOffsetRatioX = 0.94
    axisTitleSizeRatioY   = 0.15
    axisLabelSizeRatioY   = 0.108
    axisTitleOffsetRatioY = 0.32

    leftMargin   = 0.15
    rightMargin  = 0.12
    topMargin    = 0.05
    bottomMargin = 0.14
    bottomMargin2 = 0.22

    #c1 = TCanvas() #'c1', '', 200, 10, 700, 500 )
    c1 = TCanvas( "c1", "c2", 200, 10, 700, 600 )

    c1.SetHighLightColor(2)
    c1.SetFillColor(0)
    c1.SetBorderMode(0)
    c1.SetBorderSize(2)
    c1.SetLeftMargin(leftMargin)
    c1.SetRightMargin(rightMargin)
    c1.SetTopMargin(topMargin)
    c1.SetBottomMargin(bottomMargin)
    c1.SetFrameBorderMode(0)
    c1.SetFrameBorderMode(0)
    c1.SetLogy(1)
    #c1.SetLogx(1)
    c1.SetTickx(1)
    c1.SetTicky(1)
    #c1.SetGridx(True);
    #c1.SetGridy(True);
    if "c#tau" in xtitle:
        c1.SetLogx(1);

    exp2sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
           array('d', [0]), array('d', [0]), array('d', exp2minus), array('d', exp2plus))
    exp2sigma_xsec.Sort()
    exp2sigma_xsec.Draw('A3')
    exp2sigma_xsec.SetFillStyle(1001);
    exp2sigma_xsec.SetFillColor(kOrange);
    exp2sigma_xsec.SetLineColor(kOrange);
    exp2sigma_xsec.GetYaxis().SetRangeUser(0.001,100);
    exp2sigma_xsec.GetXaxis().SetLimits(0.8*min(xvals),1.1*max(xvals));
    #exp2sigma_xsec.GetXaxis().SetTitle('m_{1} [GeV]')
    #exp2sigma_xsec.GetXaxis().SetTitle('c#tau [cm]')
    exp2sigma_xsec.GetXaxis().SetTitle(xtitle)
    exp2sigma_xsec.GetXaxis().SetTitleOffset(axisTitleOffset)
    exp2sigma_xsec.GetYaxis().SetTitle('95% C.L. #sigma(pp #rightarrow #chi_{1} #chi_{1} #mu^{+} #mu^{-}) [pb]')
    exp2sigma_xsec.GetYaxis().SetTitleOffset(axisTitleOffset+0.1)

    exp1sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
            array('d', [0]), array('d', [0]), array('d', exp1minus), array('d', exp1plus))
    exp1sigma_xsec.Sort()
    exp1sigma_xsec.SetFillStyle(1001);
    exp1sigma_xsec.SetFillColor(kGreen+1);
    exp1sigma_xsec.SetLineColor(kGreen+1);
    exp1sigma_xsec.Draw('3 SAME')

    exp_xsec = TGraph(len(xvals), array('d', xvals), array('d', exp))
    exp_xsec.Sort()
    exp_xsec.SetLineWidth(2)
    exp_xsec.SetLineStyle(1)
    exp_xsec.SetLineColor(kRed)
    exp_xsec.Draw('C SAME')

    obs_xsec = TGraph(len(xvals), array('d', xvals), array('d', obs))
    obs_xsec.Sort()
    obs_xsec.SetLineWidth(3)
    obs_xsec.SetLineColor(kBlack)
    obs_xsec.SetMarkerColor(kBlack)
    obs_xsec.SetMarkerStyle(20)
    obs_xsec.SetMarkerSize(1)
    obs_xsec.Draw('PC SAME')

    theory_xsec = TGraph(len(xvals), array('d', xvals), array('d', theory))
    theory_xsec.Sort()
    theory_xsec.SetLineWidth(2)
    theory_xsec.SetLineStyle(8)
    theory_xsec.SetLineColor(kBlue)
    theory_xsec.Draw('C SAME')

    leg = TLegend(0.50,0.70,0.8,0.90);
    leg.SetBorderSize(0);
    leg.SetFillStyle(0);
    leg.AddEntry(theory_xsec, "Theory", "l");
    leg.AddEntry(obs_xsec, "Observed Limit", "pl");
    leg.AddEntry(exp_xsec, "Expected Limit", "l");
    leg.AddEntry(exp1sigma_xsec, "#pm 1 std. dev.", "f");
    leg.AddEntry(exp2sigma_xsec, "#pm 2 std. dev.", "f");
    leg.Draw()

    drawCMSLogo(c1, 13, 122450)

    # TCanvas.Update() draws the frame, after which one can change it
    # c1.Update()
    # c1.Modified()
    # c1.Update()

    c1.RedrawAxis()
    c1.Draw()
    
    wait(True)
예제 #15
0
                             800)
can_HV_scan_SL1_L1.SetGrid()
can_HV_scan_SL1_L1.cd()
##Prepare summary TGraph
graph_HV_L1 = TGraphAsymmErrors()
n = 0
for a in sorted(HV_scan_L1):
    #for a in sorted(run_parameters):
    ##Fill the TGraph with threshold (x-axis) and rate (y-axis)
    #######graph.SetPoint(n,int(run_parameters[a]['VTHR']),float(run_parameters[a]['RATE_SL1_L1']))
    graph_HV_L1.SetPoint(n, int(a), float(HV_scan_L1[a]))
    n = n + 1
graph_HV_L1.SetMarkerSize(1.)
graph_HV_L1.SetMarkerStyle(21)
graph_HV_L1.SetMarkerColor(418)
graph_HV_L1.SetFillColor(868)
graph_HV_L1.SetFillStyle(3844)
graph_HV_L1.SetLineColor(418 - 1)
graph_HV_L1.SetLineWidth(2)
graph_HV_L1.SetLineStyle(2)
graph_HV_L1.GetXaxis().SetTitle("HV [V]")
graph_HV_L1.GetYaxis().SetTitleOffset(1.2)
graph_HV_L1.GetYaxis().SetTitle("efficiency")
graph_HV_L1.GetYaxis().SetRangeUser(0, 1.01)
graph_HV_L1.Draw("APL")
latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.04)
latex.SetTextColor(1)
latex.SetTextFont(42)
latex.SetTextAlign(33)
예제 #16
0
def make_ratioplot(name,
                   ttbar_file=0,
                   qcd_file=0,
                   signal_files=[],
                   histo=0,
                   rebin=1,
                   minx=0,
                   maxx=0,
                   miny=0,
                   maxy=0,
                   logy=False,
                   xtitle='',
                   ytitle='',
                   textsizefactor=1,
                   signal_legend=[],
                   outfile=0,
                   signal_colors=[],
                   signal_zoom=1,
                   qcd_zoom=1,
                   ttbar_zoom=1,
                   ttbar_legend='t#bar{t}',
                   qcd_legend='QCD from MC',
                   dosys=False,
                   docms=True,
                   legendtitle=''):

    ###canvas setting up
    canvas = 0
    canvas = TCanvas(name, '', 0, 0, 600, 600)
    canvas.SetLeftMargin(0.15)
    canvas.SetRightMargin(0.05)
    canvas.SetTopMargin(0.10)
    canvas.SetBottomMargin(0.10)
    charsize = 0.04
    offset = 1.9

    ###latex label
    latex = 0
    latex = TLatex(0.6, 0.7, '13 TeV, 2.69 fb^{-1}')
    latex.SetTextSize(charsize)
    latex.SetNDC(1)
    latex.SetTextFont(42)

    ###legend setting up
    #legend=TLegend(0.0,0.75,0.99,1.04)
    legend = TLegend(0.4, 0.6, 0.94, 0.95)
    legend.SetNColumns(2)
    legend.SetHeader('')
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)

    ###mc stack
    stack = THStack(name + '_stack', '')

    qcd_histo = qcd_file.Get(histo).Clone(name + '_make_plot')
    qcd_histo.Rebin(rebin)
    ttbar_histo = ttbar_file.Get(histo).Clone()
    ttbar_histo.Rebin(rebin)
    ttbar_histo.SetFillColor(kRed - 9)
    ttbar_histo.SetLineColor(kRed - 9)
    ttbar_histo.SetMarkerColor(kRed - 9)
    if ttbar_zoom != 1:
        ttbar_histo.Scale(ttbar_zoom)
    legend.AddEntry(ttbar_histo, ttbar_legend, 'f')
    qcd_histo.SetFillColor(kOrange - 5)
    qcd_histo.SetLineColor(kOrange - 5)
    qcd_histo.SetMarkerColor(kOrange - 5)
    if qcd_zoom != 1:
        qcd_histo.Scale(qcd_zoom)
    legend.AddEntry(qcd_histo, qcd_legend, 'f')

    sum_mc = qcd_histo.Clone(histo + 'tmp')
    sum_mc.Add(ttbar_histo)
    stack.Add(ttbar_histo)
    stack.Add(qcd_histo)

    sum_mc.SetLineColor(kBlack)
    sum_mc.SetFillStyle(0)
    err = TGraphAsymmErrors(sum_mc)
    legend.AddEntry(err, 'Total uncertainty', 'f')

    if legendtitle == '':
        legend.AddEntry(0, "", '')
        legend.AddEntry(0, "g_{RS} #rightarrow t#bar{t} (2pb)", '')
    else:
        legend.AddEntry(0, "", '')
        legend.AddEntry(0, legendtitle, '')

    ###signal setting up
    signal_histos = []
    colors = [
        kBlack, kRed, kOrange, kBlue, kGreen + 3, 44, 45, 46, 47, 48, 49, 50,
        51, 52, 53, 54, 55, 56, 57, 58, 59, 60
    ]
    styles = [
        1, 3, 5, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 1, 1, 1
    ]
    if signal_colors != []:
        colors = signal_colors
    for i in range(len(signal_files)):
        signal_histos.append(signal_files[i].Get(histo).Clone())
        signal_histos[i].SetLineWidth(3)
        signal_histos[i].SetLineStyle(styles[i])
        signal_histos[i].SetLineColor(colors[i])
        signal_histos[i].SetMarkerColor(colors[i])
        signal_histos[i].Rebin(rebin)
        if signal_zoom != 1:
            signal_histos[i].Scale(signal_zoom)
        legend.AddEntry(signal_histos[i], signal_legend[i], 'l')

    ###mc shape line
    ttbar_line = 0
    ttbar_line = ttbar_histo.Clone()
    ttbar_line.SetLineColor(kBlack)
    ttbar_line.SetFillStyle(0)

    ###mc errors
    if dosys:
        sys_diff_qcd = []
        sys_diff_ttbar = []
        for imtt in range(1, ttbar_histo.GetNbinsX() + 1):
            sys_diff_qcd.append([])
            sys_diff_ttbar.append([])

        #adding stat uncertainties <--removed
        # for imtt in range(1,ttbar_histo.GetNbinsX()+1):
        #   sys_diff_ttbar[imtt-1].append(ttbar_histo.GetBinError(imtt))
        #   sys_diff_ttbar[imtt-1].append(-ttbar_histo.GetBinError(imtt))
        #   sys_diff_qcd[imtt-1].append(qcd_histo.GetBinError(imtt))
        #   sys_diff_qcd[imtt-1].append(-qcd_histo.GetBinError(imtt))
        #adding flat uncertainties
        for imtt in range(1, ttbar_histo.GetNbinsX() + 1):
            #ttbar
            for i in [
                    2.4,  #pdf
                    10.0,  #mu
                    3.0,  #xsec
                    6.0,  #toppt
                    1.0,  #lumi
                    3.5,  #jec
                    3.0,  #jer
                    10.0,  #btag
                    #3.0,#trig
                    10.0,  #toptag
                    3.0
            ]:  #pileup
                sys_diff_ttbar[imtt - 1].append(
                    i / 100.0 * ttbar_histo.GetBinContent(imtt))
                sys_diff_ttbar[imtt - 1].append(
                    -i / 100.0 * ttbar_histo.GetBinContent(imtt))
            closureunc = 5.0
            # if '1b' in histo:
            #   closureunc=5.0
            # elif '2b' in histo:
            #   closureunc=10.0
            for i in [
                    2.0,  #modmass
                    closureunc
            ]:  #closure
                sys_diff_qcd[imtt - 1].append(i / 100.0 *
                                              qcd_histo.GetBinContent(imtt))
                sys_diff_qcd[imtt - 1].append(-i / 100.0 *
                                              qcd_histo.GetBinContent(imtt))
            # #3% trigger
            # sys_diff_ttbar[imtt-1].append(0.03*ttbar_histo.GetBinContent(imtt))
            # sys_diff_ttbar[imtt-1].append(-0.03*ttbar_histo.GetBinContent(imtt))
            # #2.7% lumi
            # sys_diff_ttbar[imtt-1].append(0.023*ttbar_histo.GetBinContent(imtt))
            # sys_diff_ttbar[imtt-1].append(-0.023*ttbar_histo.GetBinContent(imtt))
            # #15% ttbar
            # #sys_diff_ttbar[imtt-1].append(0.15*ttbar_histo.GetBinContent(imtt))
            # #sys_diff_ttbar[imtt-1].append(-0.15*ttbar_histo.GetBinContent(imtt))
            # #2.8% QCD
            # sys_diff_qcd[imtt-1].append(0.028*qcd_histo.GetBinContent(imtt))
            # sys_diff_qcd[imtt-1].append(-0.028*qcd_histo.GetBinContent(imtt))
        #combining uncertainties
        sys_tot_ttbar = []
        sys_tot_qcd = []
        sys_tot = []
        sys_global_ttbar = [0.0, 0.0]
        sys_global_qcd = [0.0, 0.0]
        nevt_global = [0.0, 0.0, 0.0]
        for imtt in range(1, ttbar_histo.GetNbinsX() + 1):
            uperr_qcd = 0
            downerr_qcd = 0
            uperr_ttbar = 0
            downerr_ttbar = 0
            for error in sys_diff_ttbar[imtt - 1]:
                if error < 0:
                    downerr_ttbar = downerr_ttbar + error * error
                else:
                    uperr_ttbar = uperr_ttbar + error * error
            for error in sys_diff_qcd[imtt - 1]:
                if error < 0:
                    downerr_qcd = downerr_qcd + error * error
                else:
                    uperr_qcd = uperr_qcd + error * error
            sys_tot_ttbar.append(
                [math.sqrt(downerr_ttbar),
                 math.sqrt(uperr_ttbar)])
            sys_tot_qcd.append([math.sqrt(downerr_qcd), math.sqrt(uperr_qcd)])
            sys_tot.append([
                math.sqrt(downerr_qcd + downerr_ttbar),
                math.sqrt(uperr_qcd + uperr_ttbar)
            ])
            sys_global_qcd[0] = sys_global_qcd[0] + downerr_qcd
            sys_global_qcd[1] = sys_global_qcd[1] + uperr_qcd
            sys_global_ttbar[0] = sys_global_ttbar[0] + downerr_ttbar
            sys_global_ttbar[1] = sys_global_ttbar[1] + uperr_ttbar
            # nevt_global[0]=nevt_global[0]+data_histo.GetBinContent(imtt)
            nevt_global[1] = nevt_global[1] + qcd_histo.GetBinContent(imtt)
            nevt_global[2] = nevt_global[2] + ttbar_histo.GetBinContent(imtt)
            #print 'ttbar+qcd',math.sqrt(uperr_qcd+uperr_ttbar),math.sqrt(downerr_qcd+downerr_ttbar)
            #print 'qcd',math.sqrt(uperr_qcd),math.sqrt(downerr_qcd)
            #print 'ttbar',math.sqrt(uperr_ttbar),math.sqrt(downerr_ttbar)
            err.SetPointEYhigh(imtt - 1, math.sqrt(uperr_qcd + uperr_ttbar))
            err.SetPointEYlow(imtt - 1, math.sqrt(downerr_qcd + downerr_ttbar))
        sys_global = [0.0, 0.0]
        sys_global[0] = math.sqrt(sys_global_qcd[0] + sys_global_ttbar[0])
        sys_global[1] = math.sqrt(sys_global_qcd[1] + sys_global_ttbar[1])
        sys_global_qcd[0] = math.sqrt(sys_global_qcd[0])
        sys_global_qcd[1] = math.sqrt(sys_global_qcd[1])
        sys_global_ttbar[0] = math.sqrt(sys_global_ttbar[0])
        sys_global_ttbar[1] = math.sqrt(sys_global_ttbar[1])
        # print name
        # print "\hline"
        # print "Multijet QCD & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1],sys_global_qcd[1],sys_global_qcd[0])
        # print "SM ttbar & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[2],sys_global_ttbar[1],sys_global_ttbar[0])
        # print "\hline"
        # print "Total background & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1]+nevt_global[2],sys_global[1],sys_global[0])
        # print 'DATA & %.0f' %nevt_global[0]

    err.SetFillStyle(3145)
    err.SetFillColor(kGray + 1)

    ###drawing top
    canvas.cd()
    stack.Draw('hist')
    stack.GetXaxis().SetTitle(ttbar_histo.GetXaxis().GetTitle())
    stack.GetYaxis().SetTitle(ttbar_histo.GetYaxis().GetTitle())
    stack.GetXaxis().SetLabelSize(charsize)
    stack.GetXaxis().SetTitleSize(charsize)
    stack.GetYaxis().SetLabelSize(charsize)
    stack.GetYaxis().SetTitleSize(charsize)
    stack.GetYaxis().SetTitleOffset(offset)
    if minx != 0 or maxx != 0:
        stack.GetXaxis().SetRangeUser(minx, maxx)
    #else:
    #  stack.GetXaxis().SetRangeUser(0,4000)
    if miny != 0 or maxy != 0:
        stack.SetMaximum(maxy)
        stack.SetMinimum(miny)
    else:
        if logy:
            stack.SetMaximum(stack.GetMaximum() * 10)
            stack.SetMinimum(0.2)
        else:
            stack.SetMaximum(stack.GetMaximum() * 2.0)
            stack.SetMinimum(0.001)
    err.Draw('2')
    sum_mc.Draw('samehist')
    if ttbar_file != 0:
        ttbar_line.Draw('samehist')
    for i in signal_histos:
        i.Draw('samehist')
    if logy:
        canvas.SetLogy()
    legend.Draw()

    latex2text = ''
    if 'ldy_0b' in name:
        latex2text = '#Deltay < 1; 0 b tag'
    elif 'ldy_1b' in name:
        latex2text = '#Deltay < 1; 1 b tag'
    elif 'ldy_2b' in name:
        latex2text = '#Deltay < 1; 2 b tag'
    elif 'hdy_0b' in name:
        latex2text = '#Deltay > 1; 0 b tag'
    elif 'hdy_1b' in name:
        latex2text = '#Deltay > 1; 1 b tag'
    elif 'hdy_2b' in name:
        latex2text = '#Deltay > 1; 2 b tag'
    latex2 = TLatex(0.19, 0.7, latex2text)
    latex2.SetTextSize(0.03)
    latex2.SetNDC(1)
    latex2.SetTextFont(42)
    latex2.Draw()

    if docms:
        if '3000' in name:
            CMS_lumi.CMS_lumi(canvas, 3, 11)
        elif '1000' in name:
            CMS_lumi.CMS_lumi(canvas, 2, 11)
        elif '300' in name:
            CMS_lumi.CMS_lumi(canvas, 1, 11)
        elif '36' in name:
            CMS_lumi.CMS_lumi(canvas, 0, 11)

    ###saving
    canvas.SaveAs('pdf/' + name + '.pdf')
    if outfile != 0:
        canvas.Write()
예제 #17
0
def limit2HDM():
    global signals
    signals = range(800, 2000 + 1, 50)
    multF = HTOBB
    THEORY = ['T1', 'T2']

    mass, val = fillValues("./combine/AZh/AZh_M%d.txt")
    Obs0s = TGraph()
    Exp0s = TGraph()
    Exp1s = TGraphAsymmErrors()
    Exp2s = TGraphAsymmErrors()

    massB, valB = fillValues("./combine/BBAZh/BBAZh_M%d.txt")
    Obs0sB = TGraph()
    Exp0sB = TGraph()
    Exp1sB = TGraphAsymmErrors()
    Exp2sB = TGraphAsymmErrors()

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

        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0] * multF)
        Exp0s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][2] * multF,
                            val[m][4] * multF - val[m][3] * multF)
        Exp2s.SetPoint(n, m, val[m][3] * multF)
        Exp2s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][1] * multF,
                            val[m][5] * multF - val[m][3] * multF)

        Obs0sB.SetPoint(n, m, valB[m][0] * multF)
        Exp0sB.SetPoint(n, m, valB[m][3] * multF)
        Exp1sB.SetPoint(n, m, valB[m][3] * multF)
        Exp1sB.SetPointError(n, 0., 0.,
                             valB[m][3] * multF - valB[m][2] * multF,
                             valB[m][4] * multF - valB[m][3] * multF)
        Exp2sB.SetPoint(n, m, valB[m][3] * multF)
        Exp2sB.SetPointError(n, 0., 0.,
                             valB[m][3] * multF - valB[m][1] * multF,
                             valB[m][5] * multF - valB[m][3] * multF)

    col = 629
    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp0s.SetLineColor(1)
    #    Exp1s.SetFillColorAlpha(col, 0.4) #kGreen+1
    #    Exp1s.SetLineColorAlpha(col, 0.4)
    #    Exp2s.SetFillColorAlpha(col, 0.2) #kOrange
    #    Exp2s.SetLineColorAlpha(col, 0.2)
    Exp1s.SetFillColor(417)
    Exp1s.SetLineColor(417)
    Exp2s.SetFillColor(800)
    Exp2s.SetLineColor(800)

    colB = 922
    Exp2sB.SetLineWidth(2)
    Obs0sB.SetLineStyle(9)
    Obs0sB.SetLineWidth(3)
    Obs0sB.SetMarkerStyle(0)
    Obs0sB.SetLineColor(colB)
    Exp0sB.SetLineStyle(8)
    Exp0sB.SetLineWidth(3)
    Exp0sB.SetLineColor(colB)
    Exp1sB.SetFillColorAlpha(colB, 0.4)  #kGreen+1
    Exp1sB.SetLineColorAlpha(colB, 0.4)
    Exp2sB.SetFillColorAlpha(colB, 0.2)  #kOrange
    Exp2sB.SetLineColorAlpha(colB, 0.2)

    Exp2s.GetXaxis().SetTitle("m_{A} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle(
        "#sigma(A) #bf{#it{#Beta}}(A #rightarrow Zh) #bf{#it{#Beta}}(h #rightarrow bb) (fb)"
    )
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

    Theory = {}
    #for t in THEORY:
    #    Theory[t] = TGraphAsymmErrors()
    #    for m in sorted(THDM[t]['ggA'].keys()):
    #        if m < mass[0] or m > mass[-1]: continue
    #        Xs, Xs_Up, Xs_Down = 0., 0., 0.
    #        Xs = THDM[t]['ggA'][m]
    #        Xs_Up = Xs*(1.+math.sqrt((THDM['PDF']['ggA'][m][0]-1.)**2 + (THDM['QCD']['ggA'][m][0]-1.)**2))
    #        Xs_Down = Xs*(1.-math.sqrt((1.-THDM['PDF']['ggA'][m][1])**2 + (1.-THDM['QCD']['ggA'][m][1])**2))
    #        n = Theory[t].GetN()
    #        Theory[t].SetPoint(n, m, Xs)
    #        Theory[t].SetPointError(n, 0., 0., (Xs-Xs_Down), (Xs_Up-Xs))

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

    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).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    Exp0s.Draw("SAME, L")
    #    Exp2sB.Draw("SAME, 3")
    #    Exp1sB.Draw("SAME, 3")
    Exp0sB.Draw("SAME, L")
    if not options.blind:
        Obs0s.Draw("SAME, L")
        Obs0sB.Draw("SAME, L")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    #setHistStyle(Exp2s)


#    Exp2s.GetXaxis().SetTitleSize(0.045)
#    Exp2s.GetYaxis().SetTitleSize(0.04)
#    Exp2s.GetXaxis().SetLabelSize(0.04)
#    Exp2s.GetYaxis().SetLabelSize(0.04)
#    Exp2s.GetXaxis().SetTitleOffset(1)
#    Exp2s.GetYaxis().SetTitleOffset(1.25)
    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)
    Exp2s.GetYaxis().SetRangeUser(0.5, 1.e3)
    Exp2s.GetXaxis().SetRangeUser(mass[0], mass[-1])
    drawAnalysis('AZh')
    drawRegion('AZHsl', True)
    drawCMS(LUMI, "")  #Preliminary
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)

    # legend
    leg = TLegend(0.6, 0.90, 0.99, 0.90)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(None, "gg #rightarrow A #rightarrow Zh",
                 "")  #"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")
    leg.AddEntry(None, "", "")
    leg.AddEntry(None, "bbA #rightarrow Zh", "")
    leg.AddEntry(Obs0sB, "Observed", "l")
    leg.AddEntry(Exp0sB, "Expected", "l")
    leg.SetY1(leg.GetY2() - leg.GetNRows() * 0.045)
    leg.Draw()

    #    latex = TLatex()
    #    latex.SetNDC()
    #    latex.SetTextSize(0.040)
    #    latex.SetTextFont(42)
    #    latex.DrawLatex(0.65, leg.GetY1()-0.045, "cos(#beta-#alpha)=0.25, tan(#beta)=1")

    #    legB = TLegend(0.12, 0.4-4*0.3/5., 0.65, 0.4)
    legB = TLegend(0.15, 0.27, 0.68, 0.27)
    legB.SetBorderSize(0)
    legB.SetFillStyle(0)  #1001
    legB.SetFillColor(0)
    for t in THEORY:
        legB.AddEntry(Theory[t], theoryLabel[t], "fl")
    legB.AddEntry(None, "cos(#beta-#alpha)=0.25, tan(#beta)=1", "")
    legB.SetY1(legB.GetY2() - legB.GetNRows() * 0.045)
    legB.Draw()

    c1.GetPad(0).RedrawAxis()
    leg.Draw()

    c1.Update()

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

    c1.Print("plotsLimit/Exclusion/THDM.png")
    c1.Print("plotsLimit/Exclusion/THDM.pdf")
예제 #18
0
def makeBiasPlot(output,
                 muFile,
                 chan,
                 interference,
                 printStats=False,
                 obs2="",
                 ratioLabel=""):

    mu = open(muFile, 'r')

    limits = {}
    mux = []
    muy = []
    mu1SigLow = []
    mu1SigHigh = []
    mu2SigLow = []
    mu2SigHigh = []
    for entry in mu:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        mux.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        muy.append(limits[massPoint][medianNr])
        mu1SigLow.append(limits[massPoint][lower1Sig])
        mu1SigHigh.append(limits[massPoint][upper1Sig])
        mu2SigLow.append(limits[massPoint][lower2Sig])
        mu2SigHigh.append(limits[massPoint][upper2Sig])

    muX = numpy.array(mux)
    muY = numpy.array(muy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    if printStats: print "length of mux: ", len(mux)
    if printStats: print "length of mu1SigLow: ", len(mu1SigLow)
    if printStats: print "length of mu1SigHigh: ", len(mu1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(mux)):
        values2.append(mu2SigLow[x])
        xPointsForValues2.append(mux[x])
    for x in range(len(mux) - 1, 0 - 1, -1):
        values2.append(mu2SigHigh[x])
        xPointsForValues2.append(mux[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(mux)):
        values.append(mu1SigLow[x])
        xPointsForValues.append(mux[x])
    for x in range(len(mux) - 1, 0 - 1, -1):
        values.append(mu1SigHigh[x])
        xPointsForValues.append(mux[x])
    if printStats: print "length of values: ", len(values)

    mu2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    mu1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "mu2Sig: ", mu2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "mu1Sig: ", mu1Sig
    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, mu2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kYellow + 1)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, mu1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
    plotPad.Draw()
    plotPad.cd()

    muX = numpy.array(mux)
    muY = numpy.array(muy)
    GraphMU = TGraph(len(muX), muX, muY)
    GraphMU.SetLineWidth(3)
    GraphMU.SetLineStyle(2)
    GraphMU.SetLineColor(ROOT.kBlue)

    #Draw the graphs:
    DummyGraph = TH1F("DummyGraph", "", 100, 10, 40)
    DummyGraph.GetXaxis().SetTitle("#Lambda [TeV]")
    DummyGraph.GetYaxis().SetTitle("#hat{#mu}")
    gStyle.SetOptStat(0)
    if "Des" in output:
        DummyGraph.GetXaxis().SetRangeUser(10, 28)
    else:
        DummyGraph.GetXaxis().SetRangeUser(10, 40)

    DummyGraph.SetMinimum(-2)
    DummyGraph.SetMaximum(10)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()
    DummyGraph.SetLineColor(ROOT.kWhite)
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphMU.Draw("lpsame")
    else:
        GraphMU.Draw("lp")
    plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    leg.AddEntry(GraphMU, "median value", "l")
    if (FULL):
        leg.AddEntry(GraphErr1Sig, "1#sigma quantile", "f")
        leg.AddEntry(GraphErr2Sig, "2#sigma quantile", "f")

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()
    maxX = 40
    if "Des" in output:
        maxX = 28
    line = ROOT.TLine(10, 0, maxX, 0)
    if "mu1" in output:
        line = ROOT.TLine(10, 1, maxX, 1)
    line.SetLineStyle(ROOT.kDashed)
    line.Draw("same")

    plotPad.RedrawAxis()

    cCL.Update()
    printPlots(cCL, output)
예제 #19
0
def pullsVertical(fileName):

    content = filterPullFile(fileName)
    nbins, off = len(content), 0.10

    b_pulls = TH1F("b_pulls", ";;Pulls", nbins, 0. - off, nbins - off)
    s_pulls = TH1F("s_pulls", ";;Pulls", nbins, 0. + off, nbins + off)  #

    for i, s in enumerate(content):
        l = s.split()
        b_pulls.GetXaxis().SetBinLabel(i + 1, l[0])
        s_pulls.GetXaxis().SetBinLabel(i + 1, l[0])
        b_pulls.SetBinContent(i + 1, float(l[1]))
        b_pulls.SetBinError(i + 1, float(l[2]))
        s_pulls.SetBinContent(i + 1, float(l[3]))
        s_pulls.SetBinError(i + 1, float(l[4]))

    b_pulls.SetFillStyle(3005)
    b_pulls.SetFillColor(923)
    b_pulls.SetLineColor(923)
    b_pulls.SetLineWidth(1)
    b_pulls.SetMarkerStyle(20)
    b_pulls.SetMarkerSize(1.25)

    s_pulls.SetLineColor(602)
    s_pulls.SetMarkerColor(602)
    s_pulls.SetMarkerStyle(24)  #24
    s_pulls.SetLineWidth(1)

    b_pulls.GetYaxis().SetRangeUser(-2.5, 2.5)

    # Graphs
    h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins)
    B_pulls = TGraphAsymmErrors(nbins)
    S_pulls = TGraphAsymmErrors(nbins)

    boxes = []

    canvas = TCanvas("canvas", "Pulls", 600, 150 + nbins * 10)  #nbins*20)
    canvas.cd()
    canvas.SetGrid(0, 1)
    canvas.GetPad(0).SetTopMargin(0.01)
    canvas.GetPad(0).SetRightMargin(0.01)
    canvas.GetPad(0).SetBottomMargin(0.05)
    canvas.GetPad(0).SetLeftMargin(0.25)  #(0.25)#(0.065)
    canvas.GetPad(0).SetTicks(1, 1)

    for i, s in enumerate(content):
        l = s.split()
        if "1034h" in l[0]: l[0] = "CMS_PDF_13TeV"
        h_pulls.GetYaxis().SetBinLabel(i + 1, l[0].replace('CMS2016_', ''))  #C
        #y1 = gStyle.GetPadBottomMargin()
        #y2 = 1. - gStyle.GetPadTopMargin()
        #h = (y2 - y1) / float(nbins)
        #y1 = y1 + float(i) * h
        #y2 = y1 + h
        #box = TPaveText(0, y1, 1, y2, 'NDC')
        #box.SetFillColor(0)
        #box.SetTextSize(0.02)
        #box.SetBorderSize(0)
        #box.SetTextAlign(12)
        #box.SetMargin(0.005)
        #if i % 2 == 0:
        #    box.SetFillColor(18)
        #box.Draw()
        #boxes.append(box)
        B_pulls.SetPoint(i + 1, float(l[1]), float(i + 1) - 0.3)  #C
        B_pulls.SetPointError(i + 1, float(l[2]), float(l[2]), 0., 0.)  #C

    for i, s in enumerate(content):
        l = s.split()
        S_pulls.SetPoint(i + 1, float(l[3]), float(i + 1) - 0.7)  #C
        S_pulls.SetPointError(i + 1, float(l[4]), float(l[4]), 0., 0.)  #C

    h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta")
    h_pulls.GetXaxis().SetLabelOffset(-0.01)
    h_pulls.GetXaxis().SetTitleOffset(.6)
    h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0)

    B_pulls.SetFillColor(1)
    B_pulls.SetLineColor(1)
    B_pulls.SetLineStyle(1)
    B_pulls.SetLineWidth(2)
    B_pulls.SetMarkerColor(1)
    B_pulls.SetMarkerStyle(20)
    B_pulls.SetMarkerSize(1)  #(0.75)

    S_pulls.SetFillColor(629)
    S_pulls.SetLineColor(629)
    S_pulls.SetMarkerColor(629)
    S_pulls.SetLineWidth(2)
    S_pulls.SetMarkerStyle(20)
    S_pulls.SetMarkerSize(1)

    box1 = TBox(-1., 0., 1., nbins)
    box1.SetFillStyle(3001)
    #box1.SetFillStyle(0)
    box1.SetFillColor(417)
    box1.SetLineWidth(2)
    box1.SetLineStyle(2)
    box1.SetLineColor(417)

    box2 = TBox(-2., 0., 2., nbins)
    box2.SetFillStyle(3001)
    #box2.SetFillStyle(0)
    box2.SetFillColor(800)
    box2.SetLineWidth(2)
    box2.SetLineStyle(2)
    box2.SetLineColor(800)

    leg = TLegend(0.1, -0.05, 0.7, 0.08)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    leg.SetNColumns(2)
    leg.AddEntry(B_pulls, "B-only fit", "lp")
    leg.AddEntry(S_pulls, "S+B fit", "lp")
    if text: leg.AddEntry(0, text, "")

    h_pulls.Draw("")
    box2.Draw()
    box1.Draw()
    B_pulls.Draw("P6SAME")
    S_pulls.Draw("P6SAME")
    leg.Draw()

    #    drawCMS(35867, "Preliminary")
    #    drawAnalysis("VH")
    #    drawRegion(outName)

    canvas.Print(outName + ".png")
    canvas.Print(outName + ".pdf")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
예제 #20
0
def makeLimitPlot(output,
                  obs,
                  exp,
                  chan,
                  interference,
                  printStats=False,
                  obs2="",
                  ratioLabel=""):

    fileObs = open(obs, 'r')
    fileExp = open(exp, 'r')

    observedx = []
    observedy = []
    obsLimits = {}
    xSecs = getFittedXSecCurve("CI_%s" % interference, 1.3)
    for entry in fileObs:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1]) * xSecs.Eval(
            int(float(entry.split()[0])))
        if massPoint not in obsLimits: obsLimits[massPoint] = []
        obsLimits[massPoint].append(limitEntry)
    if printStats: print "len obsLimits:", len(obsLimits)
    for massPoint in sorted(obsLimits):
        observedx.append(massPoint)
        observedy.append(numpy.mean(obsLimits[massPoint]))
        if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint])
                > 0.05):
            print massPoint, " mean: ", numpy.mean(
                obsLimits[massPoint]), " std dev: ", numpy.std(
                    obsLimits[massPoint]), " from: ", obsLimits[massPoint]

    if not obs2 == "":
        fileObs2 = open(obs2, 'r')

        observedx2 = []
        observedy2 = []
        obsLimits2 = {}
        for entry in fileObs2:
            massPoint = float(entry.split()[0])
            limitEntry = float(entry.split()[1]) * xSecs.Eval(
                int(float(entry.split()[0])))
            if massPoint not in obsLimits2: obsLimits2[massPoint] = []
            obsLimits2[massPoint].append(limitEntry)
        if printStats: print "len obsLimits:", len(obsLimits2)
        for massPoint in sorted(obsLimits2):
            observedx2.append(massPoint)
            observedy2.append(numpy.mean(obsLimits2[massPoint]))
            if (numpy.std(obsLimits2[massPoint]) /
                    numpy.mean(obsLimits2[massPoint]) > 0.05):
                print massPoint, " mean: ", numpy.mean(
                    obsLimits2[massPoint]), " std dev: ", numpy.std(
                        obsLimits2[massPoint]
                    ), " from: ", obsLimits2[massPoint]

    limits = {}
    expectedx = []
    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []
    for entry in fileExp:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1]) * xSecs.Eval(
            int(float(entry.split()[0])))
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        expectedx.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        expectedy.append(limits[massPoint][medianNr])
        expected1SigLow.append(limits[massPoint][lower1Sig])
        expected1SigHigh.append(limits[massPoint][upper1Sig])
        expected2SigLow.append(limits[massPoint][lower2Sig])
        expected2SigHigh.append(limits[massPoint][upper2Sig])

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    if printStats: print "length of expectedx: ", len(expectedx)
    if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(expectedx)):
        values2.append(expected2SigLow[x])
        xPointsForValues2.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values2.append(expected2SigHigh[x])
        xPointsForValues2.append(expectedx[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(expectedx)):
        values.append(expected1SigLow[x])
        xPointsForValues.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values.append(expected1SigHigh[x])
        xPointsForValues.append(expectedx[x])
    if printStats: print "length of values: ", len(values)

    exp2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    exp1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "exp2Sig: ", exp2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "exp1Sig: ", exp1Sig
    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kOrange)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen + 1)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)

    xSecCurves = []
    xSecCurves.append(getFittedXSecCurve("CI_%s" % interference, 1.3))

    #Draw the graphs:
    plotPad.SetLogy()
    DummyGraph = TH1F("DummyGraph", "", 100, 10, 46)
    DummyGraph.GetXaxis().SetTitle("#Lambda [TeV]")
    if chan == "mumu":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrow#mu#mu +X) [pb]"
        )
    elif chan == "elel":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrowee +X) [pb]")
    elif chan == "elmu":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrow#font[12]{ll}) [pb]"
        )

    gStyle.SetOptStat(0)
    DummyGraph.GetXaxis().SetRangeUser(10, 46)

    DummyGraph.SetMinimum(5e-4)
    DummyGraph.SetMaximum(1)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")
    if not EXPONLY:
        GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    for curve in xSecCurves:
        print curve.Eval(28)
        #curve.Draw()
        curve.Draw("sameR")

    plCMS = TPaveLabel(.15, .81, .25, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.15, .76, .275, .82, "Supplementary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    #plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    leg = TLegend(0.440517, 0.523051, 0.834885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")
        print ratioLabels
        leg.AddEntry(GraphObs, "%s Observed 95%% CL limit" % ratioLabels[1],
                     "l")
        leg.AddEntry(GraphObs2, "%s Observed 95%% CL limit" % ratioLabels[0],
                     "l")

    else:
        if not EXPONLY:
            leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f")
            leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f")

    leg.AddEntry(xSecCurves[0], labels[interference], "l")
    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    elif "2017" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "42.1 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "41.5 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "41.5 fb^{-1} (13 TeV, ee) + 42.1 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plotPad.RedrawAxis()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(200, 1, 5500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

    cCL.Update()
    printPlots(cCL, output)
can_scan_SL1_L1 = TCanvas("can_scan_SL1_L1","can_scan_SL1_L1", 1000, 800)
can_scan_SL1_L1.SetGrid()
can_scan_SL1_L1.cd()
##Prepare summary TGraph
graph = TGraphAsymmErrors()
n=0
for a in sorted(threshold_scan):
#for a in sorted(run_parameters):
    ##Fill the TGraph with threshold (x-axis) and rate (y-axis)
    #######graph.SetPoint(n,int(run_parameters[a]['VTHR']),float(run_parameters[a]['RATE_SL1_L1']))
    graph.SetPoint(n,int(a),float(threshold_scan[a]))
    n = n+1
graph.SetMarkerSize(1.)
graph.SetMarkerStyle(21)
graph.SetMarkerColor(862)
graph.SetFillColor(868)
graph.SetFillStyle(3844)
graph.SetLineColor(868)
graph.SetLineWidth(2)
graph.SetLineStyle(2)
graph.GetXaxis().SetTitle("threshold [mV]")
graph.GetYaxis().SetTitleOffset(1.2)
graph.GetYaxis().SetTitle("rate [kHz]")
graph.Draw("APL")
latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.04)
latex.SetTextColor(1)
latex.SetTextFont(42)
latex.SetTextAlign(33)
latex.SetTextSize(0.04)
예제 #22
0
def limit(channel, signal):
    multF = 1.  # in fb
    filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_scalar" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    if (options.mediator == 'SC'):
        filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_scalar" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    elif (options.mediator == 'PS'):
        filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_pseudo" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    else:
        print 'WRONG mediator type'
    mass, val = fillValues(filename)

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

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

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

    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_{#phi} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle("#sigma/#sigma_{th}")
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

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

    pVal.SetLineWidth(2)
    pVal.SetLineColor(629)
    pVal.GetXaxis().SetTitle("m_{#phi} (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_{#phi} (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).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogx()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #Theory[0].Draw("SAME, L")
    #Theory[1].Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.045)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetTitleSize(0.04)
    Exp2s.GetXaxis().SetLabelSize(0.04)
    Exp2s.GetYaxis().SetLabelSize(0.04)
    Exp2s.GetXaxis().SetTitleOffset(1)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetRangeUser(0.1, 1000.)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    Exp2s.GetXaxis().SetRangeUser(mass[0], mass[-1])
    drawAnalysis("tDM")
    drawRegion(channel, True)
    drawCMS(LUMI, "Preliminary")

    if True:
        if (options.mediator == 'SC'):
            massT, valT = fillValues("./limitOutput_" + options.name + "/" +
                                     signal.replace('tttDM', 'tDM') +
                                     "_MChi1_MPhi%d_scalar" + options.bjets +
                                     "_" + channel +
                                     "_AsymptoticLimits_grepOutput.txt")
        elif (options.mediator == 'PS'):
            massT, valT = fillValues("./limitOutput_" + options.name + "/" +
                                     signal.replace('tttDM', 'tDM') +
                                     "_MChi1_MPhi%d_pseudo" + options.bjets +
                                     "_" + channel +
                                     "_AsymptoticLimits_grepOutput.txt")
        ExpT, ObsT = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massT):
            if not m in val: continue
            ExpT.SetPoint(ExpT.GetN(), m, valT[m][3] * multF)
            ObsT.SetPoint(ObsT.GetN(), m, valT[m][0] * multF)
        ExpT.SetLineWidth(3)
        ExpT.SetLineColor(602)  #602
        ExpT.SetLineStyle(5)
        ObsT.SetLineWidth(3)
        ObsT.SetLineColor(602)
        ExpT.SetMarkerStyle(21)
        ObsT.SetMarkerStyle(22)
        ExpT.SetMarkerColor(602)
        ObsT.SetMarkerColor(602)
        ExpT.Draw("SAME, PC")
        #if not options.blind: ObsT.Draw("SAME, P")

        if (options.mediator == 'SC'):
            massTTT, valTTT = fillValues("./limitOutput_" + options.name +
                                         "/" +
                                         signal.replace('tttDM', 'ttDM') +
                                         "_MChi1_MPhi%d_scalar" +
                                         options.bjets + "_" + channel +
                                         "_AsymptoticLimits_grepOutput.txt")
        elif (options.mediator == 'PS'):
            massTTT, valTTT = fillValues("./limitOutput_" + options.name +
                                         "/" +
                                         signal.replace('tttDM', 'ttDM') +
                                         "_MChi1_MPhi%d_pseudo" +
                                         options.bjets + "_" + channel +
                                         "_AsymptoticLimits_grepOutput.txt")

        ExpTTT, ObsTTT = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massTTT):
            if not m in val: continue
            ExpTTT.SetPoint(ExpTTT.GetN(), m, valTTT[m][3] * multF)
            ObsTTT.SetPoint(ObsTTT.GetN(), m, valTTT[m][0] * multF)
        ExpTTT.SetLineWidth(3)
        ExpTTT.SetLineColor(634)  #602
        ExpTTT.SetLineStyle(5)
        ObsTTT.SetLineWidth(3)
        ObsTTT.SetLineColor(634)
        ExpTTT.SetMarkerStyle(21)
        ObsTTT.SetMarkerStyle(22)
        ExpTTT.SetMarkerColor(634)
        ObsTTT.SetMarkerColor(634)
        ExpTTT.Draw("SAME, PC")
        #if not options.blind: ObsTTT.Draw("SAME, P")

    # legend
    top = 0.9
    nitems = 4 + 2

    leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.95, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL limits")
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected (t+DM, tt+DM)", "l")
    leg.AddEntry(Exp1s, "#pm 1 s. d.", "f")
    leg.AddEntry(Exp2s, "#pm 2 s. d.", "f")
    if True:
        leg.AddEntry(ExpT, "Expected (t+DM)", "p")
        leg.AddEntry(ExpTTT, "Expected (tt+DM)", "p")

    leg.Draw()
    c1.GetPad(0).RedrawAxis()
    c1.GetPad(0).Update()
    if gROOT.IsBatch():
        c1.Print("plotsLimit_" + options.name + "/Exclusion_" + channel + "_" +
                 options.mediator + "_" + options.bjets + ".png")
        c1.Print("plotsLimit_" + options.name + "/Exclusion_" + channel + "_" +
                 options.mediator + "_" + options.bjets + ".pdf")

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

    #    print "p1s[",
    #    for i in range(Exp0s.GetN()):
    #        print Exp0s.GetY()[i]+Exp1s.GetErrorYhigh(i), ",",
    #    print "],"
    #    print "m1s[",
    #    for i in range(Exp0s.GetN()):
    #        print Exp0s.GetY()[i]-Exp1s.GetErrorYlow(i), ",",
    #    print "],"
    #    print "[",
    #    for i in range(Exp0s.GetN()):
    #        print Exp0s.GetY()[i], ",",
    #    print "]"

    return

    # ---------- 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")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c2.Print("plotsLimit_" + options.name + "/Significance/" + channel +
                 "_" + options.mediator + "_" + options.bjets + ".png")
        c2.Print("plotsLimit_" + options.name + "/Significance/" + channel +
                 "_" + options.mediator + "_" + options.bjets + ".pdf")
#    c2.Print("plotsLimit/Significance/"+channel+suffix+".root")
#    c2.Print("plotsLimit/Significance/"+channel+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")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c3.Print("plotsLimit_" + options.name + "/pValue/" + channel + suffix +
                 "_" + options.mediator + "_" + options.bjets + ".png")
        c3.Print("plotsLimit_" + options.name + "/pValue/" + channel + suffix +
                 "_" + options.mediator + "_" + options.bjets + ".pdf")
#    c3.Print("plotsLimit/pValue/"+channel+suffix+".root")
#    c3.Print("plotsLimit/pValue/"+channel+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")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c4.Print("plotsLimit_" + options.name + "/BestFit/" + channel +
                 suffix + "_" + options.mediator + "_" + options.bjets +
                 ".png")
        c4.Print("plotsLimit_" + options.name + "/BestFit/" + channel +
                 suffix + "_" + options.mediator + "_" + options.bjets +
                 ".pdf")


#    c4.Print("plotsLimit/BestFit/"+channel+suffix+".root")
#    c4.Print("plotsLimit/BestFit/"+channel+suffix+".C")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
예제 #23
0
def makeLimitPlot(output,
                  obs,
                  exp,
                  chan,
                  printStats=False,
                  obs2="",
                  ratioLabel=""):

    fileObs = open(obs, 'r')
    fileExp = open(exp, 'r')

    observedx = []
    observedy = []
    obsLimits = {}
    for entry in fileObs:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in obsLimits: obsLimits[massPoint] = []
        obsLimits[massPoint].append(limitEntry)
    if printStats: print "len obsLimits:", len(obsLimits)
    for massPoint in sorted(obsLimits):
        observedx.append(massPoint)
        observedy.append(numpy.mean(obsLimits[massPoint]))
        if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint])
                > 0.05):
            print massPoint, " mean: ", numpy.mean(
                obsLimits[massPoint]), " std dev: ", numpy.std(
                    obsLimits[massPoint]), " from: ", obsLimits[massPoint]

    if not obs2 == "":
        fileObs2 = open(obs2, 'r')

        observedx2 = []
        observedy2 = []
        obsLimits2 = {}
        for entry in fileObs2:
            massPoint = float(entry.split()[0])
            limitEntry = float(entry.split()[1])
            if massPoint not in obsLimits2: obsLimits2[massPoint] = []
            obsLimits2[massPoint].append(limitEntry)
        if printStats: print "len obsLimits:", len(obsLimits2)
        for massPoint in sorted(obsLimits2):
            observedx2.append(massPoint)
            observedy2.append(numpy.mean(obsLimits2[massPoint]))
            if (numpy.std(obsLimits2[massPoint]) /
                    numpy.mean(obsLimits2[massPoint]) > 0.05):
                print massPoint, " mean: ", numpy.mean(
                    obsLimits2[massPoint]), " std dev: ", numpy.std(
                        obsLimits2[massPoint]
                    ), " from: ", obsLimits2[massPoint]

    limits = {}
    expectedx = []
    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []
    for entry in fileExp:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        expectedx.append(massPoint)
        expectedy.append(limits[massPoint][medianNr])
        expected1SigLow.append(limits[massPoint][lower1Sig])
        expected1SigHigh.append(limits[massPoint][upper1Sig])
        expected2SigLow.append(limits[massPoint][lower2Sig])
        expected2SigHigh.append(limits[massPoint][upper2Sig])

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    if printStats: print "length of expectedx: ", len(expectedx)
    if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(expectedx)):
        values2.append(expected2SigLow[x])
        xPointsForValues2.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values2.append(expected2SigHigh[x])
        xPointsForValues2.append(expectedx[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(expectedx)):
        values.append(expected1SigLow[x])
        xPointsForValues.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values.append(expected1SigHigh[x])
        xPointsForValues.append(expectedx[x])
    if printStats: print "length of values: ", len(values)

    exp2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    exp1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "exp2Sig: ", exp2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "exp1Sig: ", exp1Sig
    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kYellow + 1)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)
    smoother = TGraphSmooth("normal")
    smoother2 = TGraphSmooth("normal")

    zprimeX = []
    zprimeY = []
    fileZPrime = open('tools/xsec_SSM.txt', 'r')
    for entries in fileZPrime:
        entry = entries.split()
        zprimeX.append(float(entry[0]))
        zprimeY.append(float(entry[1]) * 1.3 / 1928)
    zpX = numpy.array(zprimeX)
    zpY = numpy.array(zprimeY)
    GraphZPrime = TGraph(481, zpX, zpY)
    GraphZPrimeSmooth = smoother2.SmoothSuper(GraphZPrime, "linear")
    GraphZPrimeSmooth.SetLineWidth(3)
    GraphZPrimeSmooth.SetLineColor(ROOT.kGreen + 3)
    GraphZPrimeSmooth.SetLineStyle(2)

    zprimePsiX = []
    zprimePsiY = []
    fileZPrimePsi = open('tools/xsec_PSI.txt', 'r')
    for entries in fileZPrimePsi:
        entry = entries.split()
        zprimePsiX.append(float(entry[0]))
        zprimePsiY.append(float(entry[1]) * 1.3 / 1928)
    zpPsiX = numpy.array(zprimePsiX)
    zpPsiY = numpy.array(zprimePsiY)
    GraphZPrimePsi = TGraph(481, zpPsiX, zpPsiY)
    GraphZPrimePsiSmooth = smoother.SmoothSuper(GraphZPrimePsi, "linear")
    GraphZPrimePsiSmooth.SetLineWidth(3)
    GraphZPrimePsiSmooth.SetLineColor(ROOT.kBlue)

    #Draw the graphs:
    plotPad.SetLogy()
    if "Moriond" in output:
        DummyGraph = TH1F("DummyGraph", "", 100, 120, 4500)
    else:
        DummyGraph = TH1F("DummyGraph", "", 100, 400, 4500)
    DummyGraph.GetXaxis().SetTitle("M [GeV]")
    if chan == "mumu":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrow#mu#mu+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu#mu+X)"
        )
    elif chan == "elel":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)"
        )
    elif chan == "elmu":
        DummyGraph.GetYaxis().SetTitle(
            "#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)"
        )

    gStyle.SetOptStat(0)
    if "Moriond" in output:
        DummyGraph.GetXaxis().SetRangeUser(120, 4500)
    else:
        DummyGraph.GetXaxis().SetRangeUser(400, 4500)

    DummyGraph.SetMinimum(1e-8)
    DummyGraph.SetMaximum(4e-4)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")

    GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    if not SPIN2:
        GraphZPrimeSmooth.Draw("lsame")
        GraphZPrimePsiSmooth.Draw("lsame")

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")

        leg.AddEntry(GraphObs, "% Observed 95% CL limit" % ratioLabel[1], "l")
        leg.AddEntry(GraphObs2, "%s Observed 95% CL limit" % ratioLabel[0],
                     "l")

    else:
        leg.AddEntry(GraphObs, "Observed 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Expected 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Expected 95% CL limit, 1 s.d.", "f")
            leg.AddEntry(GraphErr2Sig, "Expected 95% CL limit, 2 s.d.", "f")

    leg1 = TLegend(0.665517, 0.483051, 0.834885, 0.623051, "", "brNDC")
    leg1.SetTextSize(0.032)

    if not SPIN2:
        leg1.AddEntry(GraphZPrimePsiSmooth, "Z'_{#Psi} (LOx1.3)", "l")
        leg1.AddEntry(GraphZPrimeSmooth, "Z'_{SSM} (LOx1.3)", "l")

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    leg1.SetLineWidth(0)
    leg1.SetLineStyle(0)
    leg1.SetLineColor(0)
    leg1.Draw("hist")
    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetBorderSize(0)
    plPrelim.Draw()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(400, 1, 4500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(400, 0.9, 4500, 1.1, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

    cCL.Update()
    printPlots(cCL, output)
예제 #24
0
theory.SetLineWidth(3)

observed_p = TGraphAsymmErrors(massv, obsv, masserrv, masserrv, obserrv,
                               obserrv)
observed_p.SetLineColor(ROOT.kBlack)
observed_p.SetLineWidth(2)
observed_p.SetMarkerStyle(20)
expected_p = TGraphAsymmErrors(massv, expv, masserrv, masserrv, experrv,
                               experrv)
expected_p.SetLineColor(ROOT.kBlack)
expected_p.SetLineWidth(2)
expected_p.SetLineStyle(2)

expected68 = TGraphAsymmErrors(massv, expv, masserrv, masserrv, exp68Lv,
                               exp68Hv)
expected68.SetFillColor(ROOT.kGreen)
expected95 = TGraphAsymmErrors(massv, expv, masserrv, masserrv, exp95Lv,
                               exp95Hv)
expected95.SetFillColor(ROOT.kYellow)

c4 = TCanvas("c4", "Diphoton c = 01 Limits", 1000, 800)

c4.SetBottomMargin(0.15)
c4.SetRightMargin(0.06)

#c4.SetLogy(1)

#expected95.SetMinimum(0.0001);
expected95.SetMaximum(0.0057)
expected95.Draw("a3")
expected95.GetXaxis().SetTitle("Diphoton Mass [GeV/c^{2}]")
예제 #25
0
def makeLimitPlot(output,
                  obs,
                  exp,
                  chan,
                  printStats=False,
                  obs2="",
                  ratioLabel=""):
    #fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE")
    fileObs = open(obs, 'r')
    fileExp = open(exp, 'r')

    observedx = []
    observedy = []
    obsLimits = {}
    for entry in fileObs:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in obsLimits: obsLimits[massPoint] = []
        obsLimits[massPoint].append(limitEntry)
    if printStats: print "len obsLimits:", len(obsLimits)
    for massPoint in sorted(obsLimits):
        observedx.append(massPoint)
        observedy.append(numpy.mean(obsLimits[massPoint]))
        if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint])
                > 0.05):
            print massPoint, " mean: ", numpy.mean(
                obsLimits[massPoint]), " std dev: ", numpy.std(
                    obsLimits[massPoint]), " from: ", obsLimits[massPoint]

    if not obs2 == "":
        fileObs2 = open(obs2, 'r')

        observedx2 = []
        observedy2 = []
        obsLimits2 = {}
        for entry in fileObs2:
            massPoint = float(entry.split()[0])
            limitEntry = float(entry.split()[1])
            if massPoint not in obsLimits2: obsLimits2[massPoint] = []
            obsLimits2[massPoint].append(limitEntry)
        if printStats: print "len obsLimits:", len(obsLimits2)
        for massPoint in sorted(obsLimits2):
            observedx2.append(massPoint)
            observedy2.append(numpy.mean(obsLimits2[massPoint]))
            if (numpy.std(obsLimits2[massPoint]) /
                    numpy.mean(obsLimits2[massPoint]) > 0.05):
                print massPoint, " mean: ", numpy.mean(
                    obsLimits2[massPoint]), " std dev: ", numpy.std(
                        obsLimits2[massPoint]
                    ), " from: ", obsLimits2[massPoint]

    limits = {}
    expectedx = []
    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []
    for entry in fileExp:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        expectedx.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        expectedy.append(limits[massPoint][medianNr])
        expected1SigLow.append(limits[massPoint][lower1Sig])
        expected1SigHigh.append(limits[massPoint][upper1Sig])
        expected2SigLow.append(limits[massPoint][lower2Sig])
        expected2SigHigh.append(limits[massPoint][upper2Sig])

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    xPointsForErrors = []
    if printStats: print "length of expectedx: ", len(expectedx)
    if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(expectedx)):
        values2.append(expected2SigLow[x])
        xPointsForValues2.append(expectedx[x])
        xPointsForErrors.append(0)
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values2.append(expected2SigHigh[x])
        xPointsForValues2.append(expectedx[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(expectedx)):
        values.append(expected1SigLow[x])
        xPointsForValues.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values.append(expected1SigHigh[x])
        xPointsForValues.append(expectedx[x])
    if printStats: print "length of values: ", len(values)

    exp2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    exp1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    xPointsErrors = numpy.array(xPointsForErrors)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "exp2Sig: ", exp2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "exp1Sig: ", exp1Sig

    GraphErr2SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY,
                                               numpy.array(xPointsErrors),
                                               numpy.array(xPointsErrors),
                                               numpy.array(expected2SigLow),
                                               numpy.array(expected2SigHigh))
    GraphErr1SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY,
                                               numpy.array(xPointsErrors),
                                               numpy.array(xPointsErrors),
                                               numpy.array(expected1SigLow),
                                               numpy.array(expected1SigHigh))

    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kOrange)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen + 1)
    #cCL=TCanvas("cCL", "cCL",0,0,567,384)
    cCL = TCanvas("cCL", "cCL", 0, 0, 600, 450)
    gStyle.SetOptStat(0)
    gStyle.SetPadRightMargin(0.063)
    gStyle.SetPadLeftMargin(0.14)
    gStyle.SetPadBottomMargin(0.12)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)

    if SPIN2:
        signals = ["RS_kMpl01", "RS_kMpl005", "RS_kMpl001"]
    elif GUT:
        signals = ["ssm", "psi", "kai", "eta", "I", "S", "N"]
    else:
        signals = ["ssm", "psi"]

    xSecCurves = []
    for signal in signals:
        xSecCurves.append(getXSecCurve(signal, kFacs[signal]))
        #xSecCurves.append(getXSecCurve(signal,kFacs[signal],massDependent=True))

#Draw the graphs:
    plotPad.SetLogy()
    DummyGraph = TH1F("DummyGraph", "", 100, 200, 5500)
    DummyGraph.GetXaxis().SetTitle("M [GeV]")
    if SPIN2:
        DummyGraph.GetYaxis().SetTitle(
            "[#sigma#upoint#font[12]{B}] G_{KK} / [#sigma#upoint#font[12]{B}] Z"
        )
    else:
        DummyGraph.GetYaxis().SetTitle(
            "[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z")

#	if SPIN2:
#	    	if chan=="mumu":
#       	 		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")
#	else:
#    		if chan=="mumu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")

    gStyle.SetOptStat(0)
    DummyGraph.GetXaxis().SetRangeUser(200, 5500)

    DummyGraph.SetMinimum(1e-8)
    DummyGraph.SetMaximum(1e-4)
    DummyGraph.GetXaxis().SetLabelSize(0.055)
    DummyGraph.GetXaxis().SetTitleSize(0.055)
    DummyGraph.GetXaxis().SetTitleOffset(1.05)
    DummyGraph.GetYaxis().SetLabelSize(0.055)
    DummyGraph.GetYaxis().SetTitleSize(0.055)
    DummyGraph.GetYaxis().SetTitleOffset(1.3)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")
    if not EXPONLY:
        GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    for curve in xSecCurves:
        curve.Draw("lsame")

    plCMS = TPaveLabel(.16, .81, .27, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.16, .76, .27, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    if "2017" in output or "Combination" in output:
        plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    #leg=TLegend(0.540517,0.623051,0.834885,0.878644,"","brNDC")   Default
    leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC")
    if SPIN2:
        leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC")
#    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.0425)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")
        print ratioLabels
        leg.AddEntry(GraphObs, "%s Obs. 95%% CL limit" % ratioLabels[1], "l")
        leg.AddEntry(GraphObs2, "%s Obs. 95%% CL limit" % ratioLabels[0], "l")

    else:
        if not EXPONLY:
            leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f")
            leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f")

    leg1 = TLegend(0.7, 0.4, 0.9, 0.55, "", "brNDC")
    leg1.SetTextSize(0.05)
    if GUT:
        leg1 = TLegend(0.6, 0.35, 0.75, 0.623051, "", "brNDC")
    if SPIN2:
        leg1 = TLegend(0.7, 0.35, 0.9, 0.58, "G_{KK} (LO x 1.6)", "brNDC")
        leg1.SetTextSize(0.045)
    for index, signal in enumerate(signals):
        xSecCurves[index].SetName(labels[signal])
        xSecCurves[index].Write(labels[signal])
        leg1.AddEntry(xSecCurves[index], labels[signal], "l")
    leg1.SetBorderSize(0)

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    leg1.SetLineWidth(0)
    leg1.SetLineStyle(0)
    leg1.SetFillStyle(0)
    leg1.SetLineColor(0)
    leg1.Draw("hist")
    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                                "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .27, .885, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                "NBNDC")

    elif "2017" in output or "Combination" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "42.4 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                                "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "41.4 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .27, .885, .9, .99,
                "77.3 fb^{-1} (13 TeV, ee) + 78.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plotPad.SetTicks(1, 1)
    plotPad.RedrawAxis()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(200, 1, 5500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

#GraphErr2SigForHEPData.SetName("graph2Sig")
#GraphErr2SigForHEPData.Write("graph2Sig")

#GraphErr1SigForHEPData.SetName("graph1Sig")
#GraphErr1SigForHEPData.Write("graph1Sig")

#GraphExp.SetName("graphExp")
#GraphExp.Write("graphExp")

#GraphObs.SetName("graphObs")
#GraphObs.Write("graphObs")

#fileForHEPData.Write()
#fileForHEPData.Close()
    cCL.Update()
    printPlots(cCL, output)
예제 #26
0
    def getGraph(self,dset):
        from array import array
        from ROOT import TMultiGraph, TLegend, TGraphAsymmErrors
        n = len(self.__x)
        if n != len(self.__y) or n != len(self.__yErrLow) or n != len(self.__yErrHigh):
            raise StandardError, "The length of the x(%s), y(%s) and y error(%s,%s) lists does not match"%(len(self.__x), len(self.__y), len(self.__yErrLow), len(self.__yErrHigh))

        result = TMultiGraph()
        legendPosition = [float(i) for i in self.__getStyleOption("legendPosition").split()]
        legend = TLegend(*legendPosition)
        legend.SetFillColor(0)
        result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle))
        #(refArrays, refLabel) = self.__getRefernceGraphArrays()
        #refGraph = TGraphAsymmErrors(*refArrays)

        #refGraph.SetLineWidth(2)
        #refGraph.SetLineColor(int(self.__config.get("reference","lineColor")))
        #refGraph.SetFillColor(int(self.__config.get("reference","fillColor")))
        #result.Add(refGraph,"L3")
        #legend.AddEntry(refGraph,self.__config.get("reference","name"))

        xErr = array("d",[0 for i in range(n)])
        print "__x = ", self.__x
        print "__y = ", self.__y
        lst = []

        for inc in range (0,n):
            d={}
            d['run']=self.__runs[inc]
            d['x']=self.__x[inc]
            d['y']=self.__y[inc]
            d['yErr']=self.__yErrLow[inc]
            d['yTitle']=self.__yTitle
            if self.__config.has_option(self.__section,"yMin") and self.__config.has_option(self.__section,"yMax") :
                d['ymin']=float(self.__config.get(self.__section,"yMin"))
                d['ymax']=float(self.__config.get(self.__section,"yMax"))
            else:
                d['ymin']=0
                d['ymax']=0
            lst.append(d)


        obj ={}
        obj[self.__title]=lst
 #finalObj[self.__title]=lst                                                                                                                           
        #finalList.append(finalObj)                                                                                                                   

       # save_path = './JSON_A/'
        #completeName = os.path.join(save_path, self.__title+".json")
        if not os.path.exists("JSON_RECO"):
            os.makedirs("JSON_RECO")
        if not os.path.exists("JSON_RECO/"+dset):
            os.makedirs("JSON_RECO/"+dset)
        with open("./JSON_RECO/"+dset+"/"+self.__title+".json", 'w') as outfile:
            json.dump(obj, outfile,indent=4)
        print  json.dumps(obj,indent=2)

        graph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__yErrLow,self.__yErrHigh)
        graph.SetLineWidth(2)
        graph.SetFillColor(0)
        graph.SetLineColor(int(self.__getStyleOption("lineColor")))
        graph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        graph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        graph.SetMarkerSize(float(self.__getStyleOption("markerSize")))

        sysGraph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__ySysErrLow,self.__ySysErrHigh)
        sysGraph.SetLineWidth(1)
        sysGraph.SetFillColor(0)
        sysGraph.SetLineColor(int(self.__getStyleOption("lineColor")))
        sysGraph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        sysGraph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        sysGraph.SetMarkerSize(float(self.__getStyleOption("markerSize")))
        #TOMAS removed sys error from the plot
        #result.Add(sysGraph,"[]")
        result.Add(graph,"P")
#        result.SetName("MultiPlots")
#         result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle))
        result.SetName("MG_%s"%(self.__title))
        legend.AddEntry(graph, self.__getStyleOption("name"))
        
        #for (x,y,yErr) in zip(self.__x, self.__y, zip(self.__yErrLow,self.__yErrHigh)):
        #    self.__addAnnotaion("hallo",x,y,yErr)

        return (result, legend)
예제 #27
0
def makePlot1D(filepath, foutname, plottitle='', masstitle=''):
    br = 1 if 'Resonant' in plottitle else 0.68
    limits = parseLimitFiles2D(filepath, br)

    xaxis = []
    xseclist = []
    xsecerr = []
    cent = []
    obs = []
    up1 = []
    up2 = []
    down1 = []
    down2 = []
    maxval = 0
    minval = 999
    for m in sorted(limits):
        l = limits[m]
        xaxis.append(m)
        xseclist.append(l.xsec)
        xsecerr.append(l.xsec * .2)
        cent.append(l.cent)
        up1.append(l.up1 - l.cent)
        up2.append(l.up2 - l.cent)
        down1.append(l.cent - l.down1)
        down2.append(l.cent - l.down2)
        obs.append(l.obs)
        maxval = max(maxval, l.up2)
        minval = min(minval, l.down2)

    N = len(xaxis)

    up1Sigma = array('f', up1)
    up2Sigma = array('f', up2)
    down1Sigma = array('f', down1)
    down2Sigma = array('f', down2)
    cent = array('f', cent)
    obs = array('f', obs)
    xarray = array('f', xaxis)
    xsecarray = array('f', xseclist)
    xsecerrarray = array('f', xsecerr)
    zeros = array('f', [0 for i in xrange(N)])

    graphXsec = TGraphErrors(N, xarray, xsecarray, zeros, xsecerrarray)

    graphCent = TGraph(N, xarray, cent)
    graphObs = TGraph(N, xarray, obs)
    graph1Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down1Sigma,
                                    up1Sigma)
    graph2Sigma = TGraphAsymmErrors(N, xarray, cent, zeros, zeros, down2Sigma,
                                    up2Sigma)

    c = TCanvas('c', 'c', 700, 600)
    c.SetLogy()
    c.SetLeftMargin(.15)

    graph2Sigma.GetXaxis().SetTitle(masstitle + ' [GeV]')
    graph2Sigma.GetYaxis().SetTitle(
        '95% C.L. upper limit [#sigma/#sigma_{theory}]')
    c2 = root.kOrange
    c1 = root.kGreen + 1
    graph2Sigma.SetLineColor(c2)
    graph1Sigma.SetLineColor(c1)
    graph2Sigma.SetFillColor(c2)
    graph1Sigma.SetFillColor(c1)
    graph2Sigma.SetMinimum(0.5 * minval)
    graph2Sigma.SetMaximum(10 * maxval)
    graphCent.SetLineWidth(2)
    graphCent.SetLineStyle(2)
    graphObs.SetLineColor(1)
    graphObs.SetLineWidth(3)
    graphObs.SetMarkerStyle(20)
    graphObs.SetMarkerSize(1)
    graphObs.SetMarkerColor(1)
    graph1Sigma.SetLineStyle(0)
    graph2Sigma.SetLineStyle(0)

    leg = TLegend(0.55, 0.7, 0.9, 0.9)
    leg.AddEntry(graphCent, 'Expected', 'L')
    if not BLIND:
        leg.AddEntry(graphObs, 'Observed', 'Lp')
    leg.AddEntry(graph1Sigma, '1 std. dev.', 'F')
    leg.AddEntry(graph2Sigma, '2 std. dev.', 'F')
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)

    graph2Sigma.Draw('A3')
    graph1Sigma.Draw('3 same')
    graphCent.Draw('same L')
    if not BLIND:
        graphObs.Draw('same Lp')

    subscript = 'SR' if 'Resonant' in plottitle else 'FC'
    coupling = '0.1' if 'Resonant' in plottitle else '0.25'

    graphXsec.SetLineColor(2)
    graphXsec.SetLineWidth(2)
    graphXsec.SetLineStyle(2)
    graphXsec.SetFillColor(2)
    graphXsec.SetFillStyle(3005)
    graphXsec.Draw('same L3')
    '''
  if not scale:
    if 'Resonant' in plottitle:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=100 GeV}'%(subscript,subscript,coupling),'l')
    else:
      leg.AddEntry(graphXsec,'Theory #splitline{a_{%s}=b_{%s}=%s}{m_{#chi}=10 GeV}'%(subscript,subscript,coupling),'l')
  '''
    if not BLIND:
        findIntersect1D(graphObs, graphXsec, xaxis[0], xaxis[-1])
    findIntersect1D(graphCent, graphXsec, xaxis[0], xaxis[-1])

    leg.Draw()

    label = TLatex()
    label.SetNDC()
    label.SetTextSize(0.8 * c.GetTopMargin())
    label.SetTextFont(62)
    label.SetTextAlign(11)
    label.DrawLatex(0.15, 0.94, "CMS")
    label.SetTextFont(52)
    label.SetTextSize(0.6 * c.GetTopMargin())
    #  label.DrawLatex(0.25,0.94,"Preliminary")
    label.SetTextFont(42)
    label.SetTextSize(0.7 * c.GetTopMargin())
    label.DrawLatex(0.19, 0.83, plottitle)
    if 'Resonant' in plottitle:
        label.DrawLatex(0.19, 0.75, "a_{SR} = b_{SR} = %s" % coupling)
        label.DrawLatex(0.19, 0.68, "m_{#chi}=100 GeV")
    else:
        label.DrawLatex(0.19, 0.75, "g_{DM}^{V}=1,g_{q}^{V}=0.25")
        label.DrawLatex(0.19, 0.68, "m_{#chi}=1 GeV")
    label.SetTextSize(0.6 * c.GetTopMargin())
    label.SetTextFont(42)
    label.SetTextAlign(31)  # align right
    label.DrawLatex(0.95, 0.94, "%.1f fb^{-1} (13 TeV)" % (plotConfig.lumi))

    c.SaveAs(foutname + '.pdf')
    c.SaveAs(foutname + '.png')
예제 #28
0
            exp1sigma = TGraphAsymmErrors(3, x, y_exp, zeros, zeros,
                                          y_err1down, y_err1up)
            exp2sigma = TGraphAsymmErrors(3, x, y_exp, zeros, zeros,
                                          y_err2down, y_err2up)
            explim = TGraph(3, x, y_exp)
            obslim = TGraph(3, x, y_obs)
            obslim.SetLineWidth(3)
            explim.SetLineWidth(3)
            explim.SetLineStyle(2)
            explim.SetTitle('')
            obslim.SetTitle('')
            exp2sigma.SetTitle('')
            exp1sigma.SetTitle('')
            #obslim.SetMinimum(0.001);
            #duesigma=TGraphAsymmErrors(3,)
            exp1sigma.SetFillColor(kGreen + 1)
            exp2sigma.SetFillColor(kOrange)
            exp2sigma.SetMaximum(150)
            exp2sigma.SetMinimum(0.07)
            exp2sigma.Draw('a3lp')
            exp2sigma.GetXaxis().SetTitle("Z' mass [TeV]")
            exp2sigma.GetXaxis().SetRangeUser(1.4, 2.6)
            exp2sigma.GetYaxis().SetTitle("Upper cross section limit [pb]")

            sizefactor = 1.6
            exp2sigma.GetXaxis().SetTitleSize(
                sizefactor * exp2sigma.GetXaxis().GetTitleSize())
            exp2sigma.GetYaxis().SetTitleSize(
                sizefactor * exp2sigma.GetYaxis().GetTitleSize())
            exp2sigma.GetXaxis().SetLabelSize(
                sizefactor * exp2sigma.GetXaxis().GetLabelSize())
예제 #29
0
def pullsVertical_noBonly(fileName):

    content = filterPullFile(fileName)
    nbins, off = len(content), 0.10

    # Graphs
    h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins)
    S_pulls = TGraphAsymmErrors(nbins)

    boxes = []

    canvas = TCanvas("canvas", "Pulls", 720, 300 + nbins * 18)  #nbins*20)
    canvas.cd()
    canvas.SetGrid(0, 1)
    canvas.SetTopMargin(0.01)
    canvas.SetRightMargin(0.01)
    canvas.SetBottomMargin(0.10)
    canvas.SetLeftMargin(0.40)
    canvas.SetTicks(1, 1)

    for i, s in enumerate(content):
        l = s.split()
        h_pulls.GetYaxis().SetBinLabel(i + 1, l[0])
        S_pulls.SetPoint(i, float(l[3]), float(i + 1) - 0.5)
        S_pulls.SetPointError(i, float(l[4]), float(l[4]), 0., 0.)

    h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta")
    h_pulls.GetXaxis().SetLabelOffset(0.0)
    h_pulls.GetXaxis().SetTitleOffset(0.8)
    h_pulls.GetXaxis().SetLabelSize(0.045)
    h_pulls.GetXaxis().SetTitleSize(0.050)
    h_pulls.GetYaxis().SetLabelSize(0.046)
    h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0)

    S_pulls.SetFillColor(kBlack)
    S_pulls.SetLineColor(kBlack)
    S_pulls.SetMarkerColor(kBlack)
    S_pulls.SetLineWidth(2)
    S_pulls.SetMarkerStyle(20)
    S_pulls.SetMarkerSize(1)

    box1 = TBox(-1., 0., 1., nbins)
    #box1.SetFillStyle(3001) # 3001 checkered
    #box1.SetFillStyle(0)
    box1.SetFillColor(kGreen + 1)  # 417
    box1.SetLineWidth(2)
    box1.SetLineStyle(2)
    box1.SetLineColor(kGreen + 1)  # 417

    box2 = TBox(-2., 0., 2., nbins)
    #box2.SetFillStyle(3001) # 3001 checkered
    #box2.SetFillStyle(0)
    box2.SetFillColor(kOrange)  # 800
    box2.SetLineWidth(2)
    box2.SetLineStyle(2)
    box2.SetLineColor(kOrange)  # 800

    leg = TLegend(0.01, 0.01, 0.3, 0.15)
    leg.SetTextSize(0.05)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    #leg.SetNColumns(2)
    leg.AddEntry(S_pulls, "S+B fit", "lp")
    if text: leg.AddEntry(0, text, "")

    h_pulls.Draw("")
    box2.Draw()
    box1.Draw()
    S_pulls.Draw("P6SAME")
    leg.Draw()
    canvas.RedrawAxis()

    canvas.Print(outName + ".png")
    canvas.Print(outName + ".pdf")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
예제 #30
0
vexh = array('d',exh)
vey1l = array('d',ey1l)
vey1h = array('d',ey1h)
vey2l = array('d',ey2l)
vey2h = array('d',ey2h)

g1   = TGraphAsymmErrors(len(vx),vx,vy1,vexl,vexh,vey1l,vey1h)
g2   = TGraphAsymmErrors(len(vx),vx,vy2,vexl,vexh,vey2l,vey2h)
gObs = TGraph(len(vx),vx,vyObs)
gExp = TGraph(len(vx),vx,vyExp)
gxs  = TGraph(len(vx),vx,vxs)
gExpDinko = TGraph(len(massesTeV_v),massesTeV_v,xs_exp_limits)
for i in range(0,len(massesTeV_v)):
  print "exp limit Dinko: "+str(xs_exp_limits[i])

g2.SetFillColor(ROOT.kYellow)
g2.SetLineColor(ROOT.kYellow)
g1.SetFillColor(ROOT.kGreen)
g1.SetLineColor(ROOT.kGreen)
gExp.SetLineWidth(2)
gExp.SetLineStyle(9)
gExpDinko.SetLineWidth(2)
gExpDinko.SetLineStyle(2)
gObs.SetLineWidth(2)
gObs.SetLineStyle(1)
gObs.SetLineColor(ROOT.kBlue+1)
gObs.SetMarkerColor(ROOT.kBlue+1)
gObs.SetMarkerStyle(21)
gObs.SetMarkerSize(1.5)
gxs.SetLineStyle(5)
gxs.SetLineWidth(3)