コード例 #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)
コード例 #2
0
def bestfit():

    xmin = -10
    xmax = 6

    c, h = draw_canvas_histo(
        xmin, xmax, "Best fit #mu = #sigma/#sigma_{SM} at m_{H} = 125 GeV")

    # line at SM expectation of mu = 1
    l = TLine()
    l.SetLineStyle(2)
    l.DrawLine(1.0, -1.0, 1.0, -1.0 + nchannels)

    mu = np.array([-0.4, -4.734, -2.014])
    upper = np.array([2.12, 3.688, 1.80])
    lower = np.array([2.08, 3.754, 1.8224])

    channel = np.array([1.5, 0.5, -0.5])
    zero = np.zeros(nchannels)

    gmu = TGraphAsymmErrors(nchannels, mu, channel, lower, upper, zero, zero)
    gmu.SetMarkerStyle(21)
    gmu.SetMarkerSize(1.5)
    gmu.SetLineColor(2)
    gmu.SetLineWidth(2)
    gmu.Draw("pz")

    #draw_disclaimer()

    c.RedrawAxis()
    c.Modified()
    c.Update()
    c.SaveAs("bestfit.pdf")
コード例 #3
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)
コード例 #4
0
def getEff(name, den_input, num_input, rebin=0, xtitle='', ytitle=''):
    c = TCanvas(name + '_Canvas')
    legend = TLegend(0.8, 0.1, 0.999, 0.6)
    legend.SetFillColor(kWhite)
    den = den_input.Clone()
    num = num_input.Clone()
    if rebin != 0:
        den.Rebin(rebin)
        num.Rebin(rebin)
    error_bars = TGraphAsymmErrors()
    error_bars.Divide(num, den, "cl=0.683 b(1,1) mode")
    error_bars.SetLineWidth(3)
    if xtitle == '':
        error_bars.GetXaxis().SetTitle(num.GetXaxis().GetTitle())
    else:
        error_bars.GetXaxis().SetTitle(xtitle)
    if ytitle == '':
        error_bars.GetYaxis().SetTitle(num.GetYaxis().GetTitle())
    else:
        error_bars.GetYaxis().SetTitle(ytitle)
    error_bars.GetXaxis().SetRangeUser(400, 2000)
    error_bars.SetLineColor(kBlack)
    error_bars.SetMaximum(1.01)
    error_bars.SetMinimum(0.)
    if ytitle == '':
        error_bars.GetYaxis().SetTitle("Trigger rate")
    else:
        error_bars.GetYaxis().SetTitle(ytitle)
    error_bars.SetTitle('')
    error_bars.Draw('AP')
    c.SaveAs('pdf/' + name + '.pdf')
    c.Write(name + '_Canvas')
    error_bars.Write(name)
コード例 #5
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
コード例 #6
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
コード例 #7
0
def ratioplot():
    # create required parts

    leg = getLegend()
    latex = getLatex()
    c = TCanvas()
    c.SetLogy()

    #Draw input histograms
    hists = ['h_frac_recoil_', 'h_full_recoil_']
    label = ['recoil with MET triggers', 'recoil without MET triggers']
    combineHist(hists, label, leg)
    #leg.Draw()
    #c.SaveAs("Combinehists_D.pdf")

    ratio = []
    h1 = f.Get('h_frac_recoil_')
    #h1=setHistStyle(h1,bins)
    h2 = f.Get('h_full_recoil_')
    #h2=setHistStyle(h2,bins)

    h3 = createRatio(h1, h2)
    gr = TGraphAsymmErrors(h1, h2)
    gr.GetXaxis().SetRangeUser(0, 1500)
    gr.GetYaxis().SetRangeUser(0, 1.2)
    gr.SetMarkerStyle(20)
    gr.SetMarkerSize(0.5)
    gr.SetLineColor(1)
    gr.GetYaxis().SetTitle("Trigger Efficiency")
    gr.GetXaxis().SetTitle("Recoil [GeV]")
    gr.SetTitle("")

    # print ("ratio",ratio )
    # c, pad1, pad2 = createCanvasPads()
    #
    # # draw everything
    # pad1.cd()
    # h1.Draw()
    # h2.Draw("same")
    # to avoid clipping the bottom zero, redraw a small axis
    # h1.GetYaxis().SetLabelSize(0.0)
    # axis = TGaxis(-5, 20, -5, 220, 20, 220, 510, "")
    # axis.SetLabelFont(43)
    # axis.SetLabelSize(15)
    # axis.Draw()
    # pad2.cd()
    gr.Draw()
    latex.DrawLatex(0.41, 0.93, "Trigger Efficincy in MET Run2017E")
    xmin = 0.0
    line = TLine(max(xmin, gr.GetXaxis().GetXmin()), 1, 1500, 1)
    line.SetLineColor(1)
    line.SetLineWidth(1)
    line.SetLineStyle(7)
    line.Draw()
    #h3.Draw('pl')
    c.SaveAs("test.pdf")
コード例 #8
0
def getDataPoissonErrors(hist,
                         kPoisson=False,
                         drawZeroBins=False,
                         drawXbars=False,
                         centerBin=True):
    '''Make data poisson errors for a histogram with two different methods:
       - TH1.kPoisson
       - chi-squared quantile   
    '''
    # https://github.com/DESY-CMS-SUS/cmgtools-lite/blob/8_0_25/TTHAnalysis/python/plotter/mcPlots.py#L70-L102
    # https://github.com/DESY-CMS-SUS/cmgtools-lite/blob/8_0_25/TTHAnalysis/python/plotter/susy-1lep/RcsDevel/plotDataPredictWithSyst.py#L12-L21

    if kPoisson: hist.SetBinErrorOption(TH1D.kPoisson)

    Nbins = hist.GetNbinsX()
    xaxis = hist.GetXaxis()
    alpha = (1 - 0.6827) / 2.

    graph = TGraphAsymmErrors(Nbins)
    graph.SetName(hist.GetName() + "_graph")
    graph.SetTitle(hist.GetTitle())
    for i in xrange(1, Nbins + 1):
        N = hist.GetBinContent(i)
        if N <= 0 and not drawZeroBins: continue
        dN = hist.GetBinError(i)
        yscale = 1
        if centerBin:
            x = xaxis.GetBinCenter(i)
        else:
            x = xaxis.GetBinLowEdge(i)
        if N > 0 and dN > 0 and abs(dN**2 / N -
                                    1) > 1e-4:  # check is error is Poisson
            yscale = (dN**2 / N)
            N = (N / dN)**2
        if kPoisson:
            EYlow = hist.GetBinErrorLow(i)
            EYup = hist.GetBinErrorUp(i)
        else:
            EYlow = (N - Math.chisquared_quantile_c(1 - alpha, 2 * N) /
                     2.) if N > 0 else 0
            EYup = Math.chisquared_quantile_c(alpha, 2 * (N + 1)) / 2. - N
        y = yscale * N
        EXup = xaxis.GetBinUpEdge(i) - x if drawXbars else 0
        EXlow = x - xaxis.GetBinLowEdge(i) if drawXbars else 0
        graph.SetPoint(i - 1, x, y)
        graph.SetPointError(i - 1, EXlow, EXup, EYlow, EYup)
        #print ">>> getDataPoissonErrors - bin %2d: (x,y) = ( %3.1f - %4.2f + %4.2f, %4.2f - %4.2f + %4.2f )"%(i,x,EXlow,EXup,y,EYlow,EYup)
    graph.SetLineWidth(hist.GetLineWidth())
    graph.SetLineColor(hist.GetLineColor())
    graph.SetLineStyle(hist.GetLineStyle())
    graph.SetMarkerSize(hist.GetMarkerSize())
    graph.SetMarkerColor(hist.GetMarkerColor())
    graph.SetMarkerStyle(hist.GetMarkerStyle())
    return graph
コード例 #9
0
def makeEffPlotsVars(tree,
                     varx,
                     vary,
                     sel,
                     nbinx,
                     xmin,
                     xmax,
                     nbiny,
                     ymin,
                     ymax,
                     xtitle,
                     ytitle,
                     leglabel=None,
                     header='',
                     addon='',
                     option='pt',
                     marker=20,
                     col=1):

    binning = [20, 200] if args.onebin else [
        20, 30, 40, 50, 60, 70, 80, 100, 150, 200
    ]

    if option == 'pt':
        _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon,
                      len(binning) - 1, array('d', binning))
        _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon,
                       len(binning) - 1, array('d', binning))
    elif option == 'eta':
        _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, nbinx, xmin, xmax)
        _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, nbinx, xmin,
                       xmax)

    tree.Draw(varx + ' >> ' + _hist_.GetName(), sel)
    tree.Draw(varx + ' >> ' + _ahist_.GetName(), sel + ' && ' + vary)

    g_efficiency = TGraphAsymmErrors()
    g_efficiency.Divide(_ahist_, _hist_, "cl=0.683 b(1,1) mode")
    g_efficiency.GetXaxis().SetTitle(xtitle)
    g_efficiency.GetYaxis().SetTitle('efficiency')
    g_efficiency.GetYaxis().SetNdivisions(507)
    g_efficiency.SetLineWidth(3)
    g_efficiency.SetName(header)
    g_efficiency.SetMinimum(0.)
    g_efficiency.GetYaxis().SetTitleOffset(1.3)
    g_efficiency.SetMarkerStyle(marker)
    g_efficiency.SetMarkerSize(1)
    g_efficiency.SetMarkerColor(col)
    g_efficiency.SetLineColor(col)
    g_efficiency.Draw('ap')

    #    save(c, 'plots/' + addon)
    return g_efficiency
コード例 #10
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
コード例 #11
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
コード例 #12
0
def makeEffPlotsVars(tree,
                     varx,
                     numeratorAddSelection,
                     baseSelection,
                     binning,
                     xtitle='',
                     header='',
                     addon='',
                     marker=20,
                     col=1):

    _denomHist_ = TH1F('h_effp_' + addon, 'h_effp' + addon,
                       len(binning) - 1, binning)
    _nominatorHist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon,
                           len(binning) - 1, binning)

    tree.Draw(varx + ' >> ' + _denomHist_.GetName(), baseSelection)
    tree.Draw(varx + ' >> ' + _nominatorHist_.GetName(),
              baseSelection + ' && ' + numeratorAddSelection)

    g_eff = TGraphAsymmErrors()
    g_eff.Divide(_nominatorHist_, _denomHist_, "cl=0.683 b(1,1) mode")
    g_eff.GetXaxis().SetTitle(xtitle)
    g_eff.GetYaxis().SetTitle('efficiency')
    g_eff.GetYaxis().SetNdivisions(507)
    g_eff.SetLineWidth(3)
    g_eff.SetName(header)
    g_eff.SetMinimum(0.)
    g_eff.GetYaxis().SetTitleOffset(1.3)
    g_eff.SetMarkerStyle(marker)
    g_eff.SetMarkerSize(1)
    g_eff.SetMarkerColor(col)
    g_eff.SetLineColor(col)
    g_eff.Draw('ap')

    return g_eff
コード例 #13
0
ファイル: FormattingUtils.py プロジェクト: pradloff/analyses
def fixPlots_withErrors(middleGraph):

    thisBandsGraph = TGraphAsymmErrors()
    thisBandsGraph.SetName(middleGraph.GetName())
    thisBandsGraph.SetMarkerStyle(middleGraph.GetMarkerStyle())
    thisBandsGraph.SetMarkerSize(middleGraph.GetMarkerSize())
    thisBandsGraph.SetMarkerColor(middleGraph.GetMarkerColor())
    thisBandsGraph.SetLineColor(middleGraph.GetLineColor())

    for iPoint in xrange(0, middleGraph.GetN()):
        # Retrieve middle graph for (x,y) coordinates
        dataPointX = Double(0)
        dataPointY = Double(0)
        dataErrorX = Double(0)

        middleGraph.GetPoint(iPoint, dataPointX, dataPointY)
        dataErrorX = middleGraph.GetErrorX(iPoint)
        dataErrorY = middleGraph.GetErrorY(iPoint)

        dataPointY = fabs(dataPointY - 1)

        if (iPoint < middleGraph.GetN()):
            #if(dataPointY != 0 and iPoint < middleGraph.GetN()):

            print "fixPlots:", dataPointX

            thisBandsGraph.SetPoint(iPoint, dataPointX, dataPointY)
            thisBandsGraph.SetPointError(iPoint, dataErrorX, dataErrorX,
                                         dataErrorY, dataErrorY)

            #if (dataPointY == 0) :

            #thisBandsGraph.SetPoint(iPoint, dataPointX, dataPointY)
            #thisBandsGraph.SetPointError(iPoint, dataErrorX, dataErrorX, dataErrorY, dataErrorY)

    return thisBandsGraph
コード例 #14
0
    def doit():
        frame = h.ProfileX(hname + "_frame", 1, -1, "s")
        gr1 = TGraphAsymmErrors(h.GetNbinsX())
        gr2 = TGraphAsymmErrors(h.GetNbinsX())
        gr1_aspt = TGraphAsymmErrors(h.GetNbinsX())
        gr2_aspt = TGraphAsymmErrors(h.GetNbinsX())
        # Apply gaussian fits
        for i in xrange(h.GetNbinsX()):
            h_py = h.ProjectionY("_py", i + 1, i + 1)

            if 50 <= i <= 60:  # high pT, not enough entries (300 bins -> 150)
                h_py.Rebin(2)
            elif i >= 78:  # low pT, resolution affected by finite bin width
                h_py = h.ProjectionY("_py", i + 1,
                                     i + 2)  # merge i & (i+1) entries
                if i == 82:  # even lower pT, resolution affected by finite bin width
                    h_py = h.ProjectionY("_py", i + 1,
                                         i + 4)  # merge i & (i+4) entries
                elif i >= 82:
                    continue

            if h_py.Integral() < 20: continue
            r = h_py.Fit("gaus", "SNQ", "", -1, 1.2)
            #r = h_py.Fit("gaus", "SNQ", "", h_py.GetMean() - 0.04*5, h_py.GetMean() + 0.04*5)
            mean, sigma, meanErr, sigmaErr = r.Parameter(1), r.Parameter(
                2), r.ParError(1), r.ParError(2)
            gr1.SetPoint(i, h.GetXaxis().GetBinCenter(i + 1), mean)
            gr1.SetPointError(i, 0, 0, sigma, sigma)
            gr2.SetPoint(i, h.GetXaxis().GetBinCenter(i + 1), sigma)
            gr2.SetPointError(i, 0, 0, sigmaErr, sigmaErr)
            gr1_aspt.SetPoint(i, 1.0 / h.GetXaxis().GetBinCenter(i + 1), mean)
            gr1_aspt.SetPointError(i, 0, 0, sigma, sigma)
            gr2_aspt.SetPoint(i, 1.0 / h.GetXaxis().GetBinCenter(i + 1), sigma)
            gr2_aspt.SetPointError(i, 0, 0, sigmaErr, sigmaErr)
        # Draw
        h.Draw("COLZ")
        gPad.SetLogx(0)
        #draw_cms_lumi()
        #gPad.Print("figures_perf/" + hname + "_omtf" + ".png")
        #gPad.Print("figures_perf/" + hname + "_omtf" + ".pdf")
        #
        frame.Reset()
        frame.SetBins(50, 0, 50)
        frame.GetXaxis().SetTitle("gen p_{T} [GeV]")
        frame.GetYaxis().SetTitle("#Delta(p_{T})/p_{T} bias")
        frame.SetMaximum(0.5)
        frame.SetMinimum(-0.5)
        frame.SetStats(0)
        frame.Draw()
        gr1_aspt.SetLineColor(col)
        gr1_aspt.SetMarkerColor(col)
        gr1_aspt.Draw("p")
        gPad.SetLogx()
        draw_cms_lumi()
        gPad.Print("figures_perf/" + hname + "_bias" + "_omtf" + ".png")
        gPad.Print("figures_perf/" + hname + "_bias" + "_omtf" + ".pdf")
        #
        frame.GetXaxis().SetTitle("gen p_{T} [GeV]")
        frame.GetYaxis().SetTitle("#Delta(p_{T})/p_{T} resolution")
        frame.SetMaximum(0.6)
        frame.SetMinimum(0.0)
        frame.SetStats(0)
        frame.Draw()
        gr2_aspt.SetLineColor(col)
        gr2_aspt.SetMarkerColor(col)
        gr2_aspt.Draw("p")
        #gr2_aspt.Fit("pol1", "", "", 10, 40)
        gPad.SetLogx()
        draw_cms_lumi()
        gPad.Print("figures_perf/" + hname + "_res" + "_omtf" + ".png")
        gPad.Print("figures_perf/" + hname + "_res" + "_omtf" + ".pdf")
        #
        h.cache = [frame, gr1, gr2, gr1_aspt, gr2_aspt]
コード例 #15
0
def significanceSB(cutlist, labellist):

    basecut = labellist[0]
    dim = len(cutlist)
    significance = [0] * (dim + 1)

    file = {}
    tree = {}
    effs = {}
    hist = {}
    GrAsym = {}
    yErrorUp = {}
    yErrorDown = {}
    totEve = 0
    GrAsym = TGraphAsymmErrors()
    cuts = ""

    for j, c in enumerate(cutlist):
        s = 0.
        b = 0.
        cuts += cutlist[0] if j == 0 else " && " + cutlist[j]
        print "cuts = ", cuts
        for num1, v in enumerate(signals):
            #print "Signal = ", v
            for num2, filename in enumerate(samples[v]['files']):
                #print "Signal rootfile read = ",  filename
                file[filename] = TFile(NTUPLESIG + filename + ".root",
                                       "READ")  # Read TFile
                tree[filename] = file[filename].Get("Events")  # Read TTree
                nevents = float(sample[filename]['nevents'])
                xs = float(sample[filename]['xsec']) * float(
                    sample[filename]['kfactor'])
                LumiMC = nevents / xs
                Weight = float(LUMI) / float(LumiMC)

                sig_entries = tree[filename].GetEntries(cuts)
                #print "s = ", float(sig_entries) * float(Weight)
                s += float(sig_entries) * float(Weight)
            print "TOT SIG = ", s

        for num1, k in enumerate(back):
            #print "backgrounds = ", k
            for num2, filename in enumerate(samples[k]['files']):
                #print "backgrounds rootfile read = ",  filename
                file[filename] = TFile(NTUPLEDIR + filename + ".root",
                                       "READ")  # Read TFile
                tree[filename] = file[filename].Get("Events")  # Read TTree
                nevents = float(sample[filename]['nevents'])
                xs = float(sample[filename]['xsec']) * float(
                    sample[filename]['kfactor'])
                LumiMC = nevents / xs
                Weight = float(LUMI) / float(LumiMC)

                bkg_entries = tree[filename].GetEntries(cuts)
                #print "b = ", float(bkg_entries) * float(Weight)
                b += float(bkg_entries) * float(Weight)
            print "TOT BKG = ", b

        ##End of cutlist
        #COMPUTE
        #print "s = ", s
        #print "b = ", b
        #print "sqrt(b) = ",  math.sqrt(b)
        #print "significance = ",  float(s/math.sqrt(b))
        significance[j] = float(s / math.sqrt(b))
        yErrorUp[j] = float(
            TEfficiency.ClopperPearson(math.sqrt(b), s, 0.68, True) -
            significance[j])
        yErrorDown[j] = float(
            significance[j] -
            TEfficiency.ClopperPearson(math.sqrt(b), s, 0.68, False))
        GrAsym.SetPoint(j, j + 0.5, significance[j])
        GrAsym.SetPointError(j, 0, 0, yErrorUp[j], yErrorDown[j])

    for k, cs in enumerate(labellist):
        GrAsym.GetHistogram().GetXaxis().Set(dim, 0, dim)
        GrAsym.GetHistogram().GetXaxis().SetBinLabel(k + 1,
                                                     "%s" % labellist[k])

    GrAsym.SetLineColor(2)
    GrAsym.SetLineWidth(3)
    GrAsym.SetMarkerStyle(8)
    GrAsym.SetMarkerColor(2)

    c1 = TCanvas("c1", "Signals Acceptance", 800, 600)
    c1.cd()
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)

    gStyle.SetOptStat(0)

    #GrAsym.SetMaximum(1.3)
    #GrAsym.SetMinimum(0.)

    GrAsym.GetHistogram().GetXaxis().SetTitle("")
    GrAsym.GetHistogram().GetYaxis().SetTitle("Significance (S/#sqrt{B})")

    GrAsym.Draw("pa")
    drawCMS(LUMI, "Work In Progress")
    drawRegion(basecut)

    if not os.path.exists('plots/Signal/Significance/'):
        os.system('mkdir -p plots/Signal/Significance/')
    c1.Print("plots/Signal/Significance/Sigf_SB_" + basecut + ".png")
    c1.Print("plots/Signal/Significance/Sigf_SB_" + basecut + ".pdf")
    #if not options.runBash: raw_input("Press Enter to continue...")
    pass
コード例 #16
0
def makeBand(middleGraph, lowerGraph, upperGraph, noorder):

    bandsGraph = TGraphAsymmErrors()
    bandsGraph.SetName(middleGraph.GetName())
    bandsGraph.SetMarkerStyle(middleGraph.GetMarkerStyle())
    bandsGraph.SetMarkerColor(middleGraph.GetMarkerColor())
    bandsGraph.SetLineColor(middleGraph.GetLineColor())

    x1 = Double(0)
    x2 = Double(0)
    x3 = Double(0)
    y = []
    y.append(Double(0))
    y.append(Double(0))
    y.append(Double(0))

    tmp = Double(0)

    if lowerGraph.GetN() != upperGraph.GetN() or lowerGraph.GetN(
    ) != middleGraph.GetN():
        print "Plots don't have the same number of points!"
        print "Lower: ", lowerGraph.GetN()
        print "Upper: ", upperGraph.GetN()
        print "Middle: ", middleGraph.GetN()
        return 0

    #again a hack to forget about the 1st point
    for iPoint in xrange(1, lowerGraph.GetN()):
        middleGraph.GetPoint(iPoint, x1, y[0])
        lowerGraph.GetPoint(iPoint, x1, y[1])
        upperGraph.GetPoint(iPoint, x1, y[2])

        if (iPoint == lowerGraph.GetN() - 1): x2 = x1
        else: upperGraph.GetPoint(iPoint + 1, x2, buf)

        if (iPoint == 0): x3 = x1
        else: upperGraph.GetPoint(iPoint - 1, x3, buf)

        tmp = Double(0)
        yup = Double(0)
        yce = Double(0)
        ydn = Double(0)

        if noorder == 0:
            yce = y[0]
            ydn = y[1]
            yup = y[2]

        elif noorder == 1:
            tmp = y[2]
            if y[1] < y[2]:
                y[2] = y[1]
                y[1] = tmp

            yce = y[0]
            ydn = y[1]
            yup = y[2]

        else:
            for p in [0, 1, 2]:
                for q in [0, 1, 2]:
                    if y[q] > y[q + 1]:
                        tmp = y[q + 1]
                        y[q + 1] = y[q]
                        y[q] = tmp

            ydn = y[0]
            yce = y[1]
            yup = y[2]

        bandsGraph.SetPoint(iPoint, x1, yce)

        ex0 = Double(lowerGraph.GetErrorX(iPoint))

        binwl = Double(0)
        binwh = Double(0)

        if (ex0 == 0):
            binwl = (x1 - x3) / 2.
            binwh = (x2 - x1) / 2.
            if binwl == 0.: binwl = binwh
            if binwh == 0.: binwh = binwl
        else:
            binwl = ex0
            binwh = ex0

        dxl = Double(yce - ydn)
        dxh = Double(yup - yce)

        if noorder == 0:
            if dxl < 0:
                tmp = -dxl
                dxl = dxh
                dxh = tmp

        bandsGraph.SetPointError(iPoint, binwl, binwh, dxl, dxh)

    return bandsGraph
コード例 #17
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')
コード例 #18
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
コード例 #19
0
def makeplot_single(
    h1_sig=None,
    h1_bkg=None,
    h1_data=None,
    sig_legends_=None,
    bkg_legends_=None,
    sig_colors_=None,
    bkg_colors_=None,
    hist_name_=None,
    sig_scale_=1.0,
    dir_name_="plots",
    output_name_=None,
    extraoptions=None
    ):

    if h1_sig ==  None or h1_bkg == None:
        print("nothing to plot...")
        return
    os.system("mkdir -p "+dir_name_)
    os.system("cp index.php "+dir_name_)
    s_color = [632, 617, 839, 800, 1]
    b_color = [920, 2007, 2005, 2003, 2001, 2011]
    if sig_colors_:
        s_color = sig_colors_
    if bkg_colors_:
        b_color = bkg_colors_
    for idx in range(len(h1_sig)):
        h1_sig[idx].SetLineWidth(3)
        h1_sig[idx].SetLineColor(s_color[idx])
    for idx in range(len(h1_bkg)):
        h1_bkg[idx].SetLineWidth(2)
        h1_bkg[idx].SetLineColor(b_color[idx])
        h1_bkg[idx].SetFillColorAlpha(b_color[idx], 1)
    if h1_data:
        h1_data.SetBinErrorOption(1)
        h1_data.SetLineColor(1)
        h1_data.SetLineWidth(2)
        h1_data.SetMarkerColor(1)
        h1_data.SetMarkerStyle(20)

    myC = r.TCanvas("myC","myC", 600, 600)
    myC.SetTicky(1)
    pad1 = r.TPad("pad1","pad1", 0.05, 0.33,0.95, 0.97)
    pad1.SetBottomMargin(0.027)
    pad1.SetRightMargin( rightMargin )
    pad1.SetLeftMargin( leftMargin )
    pad2 = r.TPad("pad2","pad2", 0.05, 0.04, 0.95, 0.31)
    pad2.SetBottomMargin(0.4)
    pad2.SetTopMargin(0.05)
    pad2.SetRightMargin( rightMargin )
    pad2.SetLeftMargin( leftMargin )

    pad2.Draw()
    pad1.Draw()

    pad1.cd()

    for idx in range(len(h1_sig)):
        print("before signal scaling",h1_sig[idx].Integral())
        h1_sig[idx].Scale(sig_scale_)
        print("after signal scaling",h1_sig[idx].Integral())
        
    stack = r.THStack("stack", "stack")
    nS = np.zeros(h1_bkg[0].GetNbinsX())
    eS = np.zeros(h1_bkg[0].GetNbinsX())
    #hist_all is used to make the data/mc ratio. remove signal for the moment due to signal is scaled right now
    hist_all = h1_sig[0].Clone("hist_all")
    hist_all.Scale(0.0)
    hist_s = h1_sig[0].Clone("hist_s")
    hist_b = h1_bkg[0].Clone("hist_b")
    for idx in range(len(h1_bkg)):
        stack.Add(h1_bkg[idx])
        for ib in range(h1_bkg[0].GetNbinsX()):
            nS[ib] += h1_bkg[idx].GetBinContent(ib+1)
            eS[ib] = math.sqrt(eS[ib]*eS[ib] + h1_bkg[idx].GetBinError(ib+1)*h1_bkg[idx].GetBinError(ib+1))
        hist_all.Add(h1_bkg[idx]) 
        if idx > 0:
            hist_b.Add(h1_bkg[idx]) 
            
    for idx in range(len(h1_sig)):
        print("ggH signal yield: ", hist_s.Integral())
        if idx > 0:
            hist_temp = h1_sig[idx].Clone(h1_sig[idx].GetName()+"_temp")
            #hist_all.Add(hist_temp)
            hist_s.Add(h1_sig[idx])
        print("all signal yield: ", hist_s.Integral())

    stack.SetTitle("")
    
    maxY = 0.0
    if "stack_signal" in extraoptions and extraoptions["stack_signal"]:
        for idx in range(len(h1_sig)):
            h1_sig[idx].SetFillColorAlpha(s_color[idx], 1)
            stack.Add(h1_sig[idx])
            for ib in range(h1_bkg[0].GetNbinsX()):
                nS[ib] += h1_sig[idx].GetBinContent(ib+1)
                eS[ib] = math.sqrt(eS[ib]*eS[ib] + h1_sig[idx].GetBinError(ib+1)*h1_sig[idx].GetBinError(ib+1))
        if stack.GetMaximum() > maxY:
            maxY = stack.GetMaximum()
        #if "SR" in h.GetTitle(): 
        stack.Draw("hist")
    else:
        stack.Draw("hist")
        if stack.GetMaximum() > maxY:
            maxY = stack.GetMaximum()
        for idx in range(len(h1_sig)):
            if h1_sig[idx].GetMaximum() > maxY:
                maxY = h1_sig[idx].GetMaximum()
            if "SR" in h1_bkg[0].GetTitle():
                #h1_sig[idx].Draw("samehist")
                hist_s.Draw("samehist")

    ##draw  stack total unc on top of total histogram
    box = r.TBox(0,0,1,1,)
    box.SetFillStyle(3002)
    box.SetLineWidth(0)
    box.SetFillColor(r.kBlack)
    for idx in range(h1_bkg[0].GetNbinsX()):
        box.DrawBox(h1_bkg[0].GetBinCenter(idx+1)-0.5*h1_bkg[0].GetBinWidth(idx+1), nS[idx]-eS[idx], h1_bkg[0].GetBinCenter(idx+1)+0.5*h1_bkg[0].GetBinWidth(idx+1), nS[idx]+eS[idx])

    if h1_data:
        if h1_data.GetMaximum() > maxY:
            maxY = h1_data.GetMaximum()+np.sqrt(h1_data.GetMaximum())
        #if not "SR" in h1_data.GetTitle() or "fail" in h1_data.GetTitle():  
        if True:
            #print("debug h1_data.GetName()",h1_data.GetName(), h1_data.GetTitle())           
            TGraph_data = TGraphAsymmErrors(h1_data)
            for i in range(TGraph_data.GetN()):
                #data point
                var_x, var_y = Double(0.), Double(0.)
                TGraph_data.GetPoint(i,var_x,var_y)    
                if np.fabs(var_y) < 1e-5:
                    TGraph_data.SetPoint(i,var_x,-1.0)
                    TGraph_data.SetPointEYlow(i,-1)
                    TGraph_data.SetPointEYhigh(i,-1)
                    #print("zero bins in the data TGraph: bin",i+1)
                else:
                    TGraph_data.SetPoint(i,var_x,var_y)
                    err_low = var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y))
                    TGraph_data.SetPointEYlow(i, var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y)))
                    TGraph_data.SetPointEYhigh(i, (0.5*TMath.ChisquareQuantile(1.-0.1586555,2.*(var_y+1))) - var_y)
        
            TGraph_data.SetMarkerColor(1)
            TGraph_data.SetMarkerSize(1)
            TGraph_data.SetMarkerStyle(20)
            TGraph_data.Draw("same P")

    stack.GetYaxis().SetTitle("Events")
    stack.GetYaxis().SetTitleOffset(1.05)
    stack.GetYaxis().SetTitleSize(0.08)
    stack.GetYaxis().SetLabelSize(0.06)
    #stack.GetYaxis().CenterTitle()
    stack.GetXaxis().SetLabelSize(0.)
    #stack.GetXaxis().SetLabelOffset(0.013)
    #if "xaxis_range" in extraoptions:
    #    stack.GetXaxis().SetRangeUser(float(extraoptions["xaxis_range"][0]),float(extraoptions["xaxis_range"][1]))

    leg = r.TLegend(0.2, 0.60, 0.9, 0.88)
    leg.SetNColumns(3)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.05)
    for idx in range(len(h1_bkg)):
        leg.AddEntry(h1_bkg[idx], bkg_legends_[idx], "F")
    if "SR" in hist_s.GetTitle():
        leg.AddEntry(hist_s, 'HH #times {:1.2}'.format(sig_scale_), "L")

    leg.AddEntry(box, "Total  unc", "F")
    if h1_data:
        leg.AddEntry(h1_data, "Data", "ep")
    leg.Draw()

    pad2.cd()
    pad2.SetGridy(1)
    
    ratio = None
    ratio_Low  = 0.0
    ratio_High  = 4
    
    if h1_data:      
        ratio = TGraphAsymmErrors(h1_data)
        for i in range(ratio.GetN()):
            
            #bkg prediction
            imc = Double(hist_all.GetBinContent(i+1))
            #data point
            var_x, var_y = Double(0.), Double(0.)
            if not ("SR" in h1_data.GetTitle() and (i>5 and i<9)):
            	ratio.GetPoint(i,var_x,var_y)    
            if var_y == 0.:
                ratio.SetPoint(i,var_x,-1.0)
                ratio.SetPointEYlow(i,-1)
                ratio.SetPointEYhigh(i,-1)
                continue
            ratio.SetPoint(i,var_x,var_y/imc)
            err_low = (var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y)))/imc
            err_high = ((0.5*TMath.ChisquareQuantile(1.-0.1586555,2.*(var_y+1))) - var_y)/imc
            ratio.SetPointEYlow(i, err_low)
            ratio.SetPointEYhigh(i, err_high)
        
        ratio.SetMarkerColor(1)
        ratio.SetMarkerSize(1)
        ratio.SetMarkerStyle(20)
        ratio.GetXaxis().SetTitle("j_{2} regressed mass [GeV]")
        #myC.Update()
        
        if "ratio_range" in extraoptions:
            ratio_Low = extraoptions["ratio_range"][0]
            ratio_High = extraoptions["ratio_range"][1]
        ratio.GetYaxis().SetTitle("data/mc")
        ratio.GetYaxis().SetRangeUser(ratio_Low, ratio_High)
        ratio.GetXaxis().SetRangeUser(50, 220)
        ratio.SetTitle("")
        ratio.Draw("same AP")
        pad2.Update()
        
        print(ratio.GetTitle(),ratio.GetName(),"debug")
    else:
        ratio = h1_sig[0].Clone("ratio")
        ratio_High = 0.0
        for ibin in range(1,ratio.GetNbinsX()+1):
            s = hist_s.GetBinContent(ibin) 
            b = hist_b.GetBinContent(ibin)
            L = 0.0
            if b > 0.0:
                L = s/math.sqrt(b)
                if L > ratio_High:
                    ratio_High = L
            ratio.SetBinContent(ibin, L)
        if ratio_High > 1.0:
            ratio_High = 1.0
        ratio.GetYaxis().SetRangeUser(ratio_Low, ratio_High*1.2)
        ratio.GetYaxis().SetTitle("S/#sqrt{B}")
        ratio.Draw("samehist")
    ratio.SetLineColor(1)
    ratio.SetLineWidth(2)
    ratio.SetMarkerStyle(20)
    ratio.SetMarkerColor(1)
    ratio.SetFillColorAlpha(1, 0)
    ratio.GetXaxis().SetTitleOffset(0.94)
    ratio.GetXaxis().SetTitleSize(0.18)
    ratio.GetXaxis().SetLabelSize(0.12)
    ratio.GetXaxis().SetLabelOffset(0.013)
    ratio.GetYaxis().SetTitleOffset(0.40)
    ratio.GetYaxis().SetTitleSize(0.17)
    ratio.GetYaxis().SetLabelSize(0.13)
    ratio.GetYaxis().SetTickLength(0.01)
    ratio.GetYaxis().SetNdivisions(505)
    #if "xaxis_range" in extraoptions:
    #    ratio.GetXaxis().SetRangeUser(float(extraoptions["xaxis_range"][0]),float(extraoptions["xaxis_range"][1]))

    #draw  stack total unc on the ratio plot to present the background uncertainty
    box_ratio = r.TBox(0,0,1,1,)
    box_ratio.SetFillStyle(3002)
    box_ratio.SetLineWidth(0)
    box_ratio.SetFillColor(r.kBlack)
    for idx in range(h1_bkg[0].GetNbinsX()):
        if np.fabs(nS[idx])> 1e-06: 
            box_ratio.DrawBox(h1_bkg[0].GetBinCenter(idx+1)-0.5*h1_bkg[0].GetBinWidth(idx+1), (nS[idx]-eS[idx])/nS[idx], h1_bkg[0].GetBinCenter(idx+1)+0.5*h1_bkg[0].GetBinWidth(idx+1), (nS[idx]+eS[idx])/nS[idx])
        else:
            print("blinded Higgs peak region") 
    
    if "xaxis_label" in extraoptions and extraoptions["xaxis_label"] != None:
        x_title = extraoptions["xaxis_label"]
        ratio.GetXaxis().SetTitle(x_title)
    ratio.GetYaxis().CenterTitle()

    ##########draw CMS preliminary
    pad1.cd()
    tex1 = r.TLatex(leftMargin, 0.91, "CMS")
    tex1.SetNDC()
    tex1.SetTextFont(61)
    tex1.SetTextSize(0.070)
    tex1.SetLineWidth(2)
    tex1.Draw()
    tex2 = r.TLatex(leftMargin+0.12,0.912,"Internal")
    tex2.SetNDC()
    tex2.SetTextFont(52)
    tex2.SetTextSize(0.055)
    tex2.SetLineWidth(2)
    tex2.Draw()

    lumi_value = 137
    if "lumi_value" in extraoptions:
        lumi_value = extraoptions["lumi_value"]
    tex3 = r.TLatex(0.72,0.912,"%d"%lumi_value+" fb^{-1} (13 TeV)")
    tex3.SetNDC()
    tex3.SetTextFont(42)
    tex3.SetTextSize(0.055)
    tex3.SetLineWidth(2)
    tex3.Draw()
    outFile = dir_name_
    if output_name_:
        outFile = outFile + "/" +output_name_
    else:
        outFile = outFile + "/" + hist_name_

    #print("maxY = "+str(maxY))
    stack.SetMaximum(maxY*1.7)

    #print everything into txt file
    text_file = open(outFile+"_linY.txt", "w")
    text_file.write("bin    |   x    ")
    for idx in range(len(h1_bkg)):
        text_file.write(" | %21s"%bkg_legends_[idx])
    text_file.write(" | %21s"%("total B"))
    for idx in range(len(sig_legends_)):
        text_file.write(" | %25s"%sig_legends_[idx])
    if h1_data:
        text_file.write(" | data | data/mc")
    text_file.write("\n-------------")
    for idx in range(24*(len(h1_bkg) + 1)+ 29*len(sig_legends_)):
        text_file.write("-")
    if h1_data:
        text_file.write("-------")
    text_file.write("\n")
    for ibin in range(0,h1_sig[0].GetNbinsX()+1):
        text_file.write("%3d"%ibin+"   ")
        text_file.write(" | %6.3f"%h1_data.GetBinCenter(ibin)+" ")
        for idx in range(len(h1_bkg)):
            text_file.write(" | %7.3f "%h1_bkg[idx].GetBinContent(ibin)+"$\\pm$"+ " %7.3f"%h1_bkg[idx].GetBinError(ibin))
        text_file.write(" | %7.3f "%hist_b.GetBinContent(ibin)+"$\\pm$"+ " %7.3f"%hist_b.GetBinError(ibin))
        for idx in range(len(sig_legends_)):
            text_file.write(" | %9.3f "%h1_sig[idx].GetBinContent(ibin)+"$\\pm$"+ " %9.3f"%h1_sig[idx].GetBinError(ibin))
        if h1_data:
            text_file.write(" | %d"%h1_data.GetBinContent(ibin) +  " | %7.3f "%h1_data.GetBinContent(ibin) +"$\\pm$"+ " %7.3f"%h1_data.GetBinError(ibin))
        text_file.write("\n\n")
        
    #print yield table for AN
    text_file.write("print yield table for AN\n")
    bkg_all = 0
    bkg_all_errsq = 0
    for idx in range(len(h1_bkg)):
        bkg_tmp = h1_bkg[idx].GetBinContent(7)+h1_bkg[idx].GetBinContent(8)+h1_bkg[idx].GetBinContent(9)
        bkg_errsq_tmp = h1_bkg[idx].GetBinError(7)*h1_bkg[idx].GetBinError(7)+h1_bkg[idx].GetBinError(8)*h1_bkg[idx].GetBinError(8)+h1_bkg[idx].GetBinError(9)*h1_bkg[idx].GetBinError(9)
        bkg_all += bkg_tmp
        bkg_all_errsq += bkg_errsq_tmp
        text_file.write("%s"%(bkg_legends_[idx])+"& %7.2f"%(bkg_tmp)+"$\\pm$"+ "%7.2f"%np.sqrt(bkg_errsq_tmp)+"\n")
    text_file.write("total background & %7.2f"%(bkg_all)+"$\\pm$"+ "%7.2f"%np.sqrt(bkg_all_errsq)+"\n")
    
    text_file.write("\ggHH SM ($\kapl=1$) & %7.2f"%((h1_sig[0].GetBinContent(7)+h1_sig[0].GetBinContent(8)+h1_sig[0].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.1f"%(sig_scale_*np.sqrt(h1_sig[0].GetBinError(7)*h1_sig[0].GetBinError(7)+h1_sig[0].GetBinError(8)*h1_sig[0].GetBinError(8)+h1_sig[0].GetBinError(9)*h1_sig[0].GetBinError(9)))+"\n")
    text_file.write("\VBFHH SM ($\kapl=1$) & %7.2f"%((h1_sig[1].GetBinContent(7)+h1_sig[1].GetBinContent(8)+h1_sig[1].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.1f"%(sig_scale_*np.sqrt(h1_sig[1].GetBinError(7)*h1_sig[1].GetBinError(7)+h1_sig[1].GetBinError(8)*h1_sig[1].GetBinError(8)+h1_sig[1].GetBinError(9)*h1_sig[1].GetBinError(9)))+"\n")
    
    text_file.write("HH bin 8 value %s"%h1_sig[0].GetBinContent(8)+"\n")
    text_file.write("HH bin 9 value %s"%h1_sig[0].GetBinContent(9)+"\n")
    text_file.write("HH bin 7 value %s"%h1_sig[0].GetBinContent(7)+"\n")

    text_file.write("HH bin 8 error %s"%h1_sig[0].GetBinError(8)+"\n")
    text_file.write("HH bin 9 error %s"%h1_sig[0].GetBinError(9)+"\n")
    text_file.write("HH bin 7 error %s"%h1_sig[0].GetBinError(7)+"\n")
    
    text_file.write("total & %7.2f"%(bkg_all+(h1_sig[0].GetBinContent(7)+h1_sig[0].GetBinContent(8)+h1_sig[0].GetBinContent(9)+h1_sig[1].GetBinContent(7)+h1_sig[1].GetBinContent(8)+h1_sig[1].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.2f"%(np.sqrt((h1_sig[0].GetBinError(7)*h1_sig[0].GetBinError(7)+h1_sig[0].GetBinError(8)*h1_sig[0].GetBinError(8)+h1_sig[0].GetBinError(9)*h1_sig[0].GetBinError(9))/(sig_scale_*sig_scale_)+(h1_sig[1].GetBinError(7)*h1_sig[1].GetBinError(7)+h1_sig[1].GetBinError(8)*h1_sig[1].GetBinError(8)+h1_sig[1].GetBinError(9)*h1_sig[1].GetBinError(9))/(sig_scale_*sig_scale_)+bkg_all_errsq))+"\n")
    
    text_file.close()
    os.system("cp "+outFile+"_linY.txt "+outFile+"_logY.txt")

    pad1.RedrawAxis()
    myC.SaveAs(outFile+"_linY.png")
    myC.SaveAs(outFile+"_linY.pdf")
    myC.SaveAs(outFile+"_linY.C")
    pad1.cd()
    stack.SetMaximum(maxY*100.0)
    stack.SetMinimum(0.5)
    pad1.SetLogy()
    pad1.RedrawAxis()
    myC.SaveAs(outFile+"_logY.png")
    myC.SaveAs(outFile+"_logY.pdf")
    myC.SaveAs(outFile+"_logY.C")
    #save histogram and ratio to root file
    outFile_root = r.TFile(outFile+".root", "recreate")
    outFile_root.cd()
    for idx in range(len(h1_bkg)):
        h1_bkg[idx].Write()
    for idx in range(len(sig_legends_)):
        h1_sig[idx].Write()
    if  h1_data:
        h1_data.Write()
        ratio.Write()
    #outFile_root.Write()
    outFile_root.Close()
コード例 #20
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)
コード例 #21
0
    gr_denom = TGraphAsymmErrors(len(rates))
    gr_numer = TGraphAsymmErrors(len(rates))

    for i, x in enumerate(rates):
        pu, emtf_rate, emtf_rate_err, emtf2026_rate, emtf2026_rate_err = x
        gr_denom.SetPoint(i, pu, emtf_rate)
        gr_denom.SetPointError(i, 0, 0, emtf_rate_err, emtf_rate_err)
        gr_numer.SetPoint(i, pu, emtf2026_rate)
        gr_numer.SetPointError(i, 0, 0, emtf2026_rate_err, emtf2026_rate_err)

    gr_denom.SetMarkerStyle(20)
    gr_denom.SetMarkerSize(1.4)
    gr_denom.SetMarkerColor(632)  # kRed
    gr_denom.SetLineWidth(2)
    gr_denom.SetLineColor(632)  # kRed

    gr_numer.SetMarkerStyle(20)
    gr_numer.SetMarkerSize(1.4)
    gr_numer.SetMarkerColor(600)  # kBlue
    gr_numer.SetLineWidth(2)
    gr_numer.SetLineColor(600)  # kBlue

    frame = TH1F("frame", "; PU; Trigger rate [kHz]", 100, 0, 350)
    frame.SetMinimum(0)
    frame.SetMaximum(25)
    frame.Draw()

    #gr_denom.Draw("P")
    gr_numer.Draw("P")
コード例 #22
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')
コード例 #23
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...")
コード例 #24
0
	else:
		ey_hi_ratio = y_ratio * math.hypot(ey_hi_mu / y_mu, ey_hi_ele / y_ele)

	grRatio.SetPoint(i, x, y_ratio)
	grRatio.SetPointEXlow(i, ex_lo)
	grRatio.SetPointEXhigh(i, ex_hi)
	grRatio.SetPointEYlow(i, ey_lo_ratio)
	grRatio.SetPointEYhigh(i, ey_hi_ratio)

if True:
    grRatio.SetMarkerStyle(20)
    grRatio.SetMarkerSize(1.5)
    grRatio.SetMarkerColor(1)

    grRatio.SetLineStyle(1)
    grRatio.SetLineColor(1)
    grRatio.SetLineWidth(1)

    grRatio.GetXaxis().SetLabelSize(0.04)
    grRatio.GetXaxis().SetTitleSize(0.04)
    grRatio.GetXaxis().SetTitleOffset(1.25)

    grRatio.GetYaxis().SetLabelSize(0.04)
    grRatio.GetYaxis().SetTitleSize(0.04)
    grRatio.GetYaxis().SetTitleOffset(1.5)
#    grRatio.GetYaxis().SetRangeUser(ylo, yhi)

grRatio.Draw("ALP")

fOutput = TFile('durp.root', 'recreate')
grRatio.Write('durp')
コード例 #25
0
ファイル: DrawLimits.py プロジェクト: DryRun/StatisticalTools
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)
gxs.SetLineColor(ROOT.kRed)
コード例 #26
0
def plotDataOverMCEff(hist_mc_tight,
                      hist_mc_loose,
                      hist_data_tight,
                      hist_data_loose,
                      plot_name='fakerate.pdf'):

    g = TGraphAsymmErrors(hist_mc_tight)
    g.Divide(hist_mc_tight, hist_mc_loose)
    g.GetYaxis().SetTitle('Fake rate')
    g.GetXaxis().SetTitle(hist_mc_tight.GetXaxis().GetTitle())
    g.GetYaxis().SetTitleOffset(1.2)
    g.GetYaxis().SetTitleOffset(1.3)

    g.SetLineColor(2)
    g.SetMarkerColor(2)

    g_data = TGraphAsymmErrors(hist_data_tight)
    g_data.Divide(hist_data_tight, hist_data_loose)
    g_data.GetYaxis().SetTitle('Fake rate')
    g_data.GetXaxis().SetTitle(hist_data_tight.GetXaxis().GetTitle())
    g_data.GetYaxis().SetTitleOffset(1.2)
    g_data.GetYaxis().SetTitleOffset(1.3)
    g_data.SetMarkerColor(1)

    g_vals = g.GetY()
    g_data_vals = g_data.GetY()

    g_ratio = g_data.Clone('ratio')

    for i in xrange(g_data.GetN()):
        ratio = g_data_vals[i] / g_vals[i] if g_vals[i] else 0.
        g_ratio.SetPoint(i, g.GetX()[i], ratio)

        rel_y_low = math.sqrt((g_data.GetErrorYlow(i) / g_data_vals[i])**2 + (
            g.GetErrorYlow(i) /
            g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0.

        g_ratio.SetPointEYlow(i, rel_y_low * ratio)

        rel_y_high = math.sqrt(
            (g_data.GetErrorYhigh(i) / g_data_vals[i])**2 +
            (g.GetErrorYhigh(i) /
             g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0.

        g_ratio.SetPointEYhigh(i, rel_y_high * ratio)

    # Gymnastics to get same label sizes etc in ratio and main plot
    ytp_ratio = 2.
    xtp_ratio = 2.

    # hr.GetYaxis().SetNdivisions(4)

    g_ratio.GetYaxis().SetTitleSize(g.GetYaxis().GetTitleSize() * xtp_ratio)
    g_ratio.GetXaxis().SetTitleSize(g.GetXaxis().GetTitleSize() * ytp_ratio)

    g_ratio.GetYaxis().SetTitleOffset(g.GetYaxis().GetTitleOffset() /
                                      xtp_ratio)
    g_ratio.GetXaxis().SetTitleOffset(
        g.GetXaxis().GetTitleOffset())  # / ytp_ratio)

    g_ratio.GetYaxis().SetLabelSize(g.GetYaxis().GetLabelSize() * xtp_ratio)
    g_ratio.GetXaxis().SetLabelSize(g.GetXaxis().GetLabelSize() * ytp_ratio)

    g_data.GetXaxis().SetLabelColor(0)
    g_data.GetXaxis().SetLabelSize(0)
    g.GetXaxis().SetLabelColor(0)
    g.GetXaxis().SetLabelSize(0)

    g_ratio.GetXaxis().SetTitle(g.GetXaxis().GetTitle())

    # maxy = 1.1 * min(g.GetMaximum(), g_data.GetMaximum(), 0.2)
    g.GetYaxis().SetRangeUser(0.001, 0.2)

    cv, pad, padr = HistDrawer.buildCanvas()

    pad.cd()

    g.Draw('AP')
    g_data.Draw('P')

    legend = TLegend(0.23, 0.73, 0.43, 0.91)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetLineColor(0)
    legend.SetLineWidth(0)

    legend.AddEntry(g.GetName(), 'MC', 'lep')
    legend.AddEntry(g_data.GetName(), 'Observed', 'lep')

    legend.Draw()

    padr.cd()
    g_ratio.GetYaxis().SetRangeUser(0.51, 1.49)
    g_ratio.GetYaxis().SetTitle('Obs/MC')
    g_ratio.Draw('AP')

    drawRatioLines(g_ratio)

    cv.Print(plot_name)
コード例 #27
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...")
コード例 #28
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")
コード例 #29
0
def ratioplot():
    # create required parts
    leg = getLegend()
    latex = getLatex()
    c = SetCanvas()
    #c.SetLogy()
    #c = TCanvas()
    #c.SetLogy()

    h1 = f.Get('h_num_calo_')  #'calo',pf
    h1 = setHistStyle(h1, bins)
    h2 = f.Get('h_den_calo_')
    h2 = setHistStyle(h2, bins)

    h11 = f2.Get('h_num_calo_')
    h11 = setHistStyle(h11, bins)
    h21 = f2.Get('h_den_calo_')
    h21 = setHistStyle(h21, bins)

    gr = TGraphAsymmErrors(30)
    #gr.Divide(h1,h2)
    gr = TGraphAsymmErrors(h1, h2)
    gr2 = TGraphAsymmErrors(h11, h21)
    gr2.SetMarkerStyle(20)
    gr2.GetXaxis().SetRangeUser(0, 1000)
    gr2.SetMarkerSize(1.5)
    gr2.SetLineColor(2)
    gr2.SetLineWidth(1)
    gr2.SetMarkerColor(2)

    gr.GetXaxis().SetRangeUser(0, 1000)
    # gr.GetYaxis().SetRangeUser(0.0001,1.2)
    gr.SetMarkerStyle(20)
    gr.SetMarkerSize(1.5)
    gr.SetLineColor(1)
    gr.SetLineWidth(1)
    gr.SetMarkerColor(1)
    gr.GetYaxis().SetTitle("Trigger Efficiency")
    gr.GetXaxis().SetTitle("MET [GeV]")
    gr.SetTitle("")

    #base histogram
    histogram_base = TH1F("histogram_base", "", 1000, 0, 1000.)
    histogram_base.SetTitle("")
    histogram_base.SetStats(0)
    histogram_base.SetMarkerSize(2)
    #histogram_base.SetMinimum(0.0)
    histogram_base.SetMaximum(1.2)
    histogram_base.GetXaxis().SetTitle("Online E_{T}^{miss} (GeV)")
    histogram_base.GetYaxis().SetTitle("Efficiency")
    histogram_base = setHistStyle(histogram_base, bins)

    histogram_base.Draw("HIST")
    # c.SaveAs()

    gr.Draw('P same')
    gr2.Draw('P same')
    latex.DrawLatex(0.49, 0.93, " EGamma Run2018C, 13 TeV")
    xmin = 0.0
    line = TLine(max(xmin, gr.GetXaxis().GetXmin()), 1, 1000, 1)
    line.SetLineColor(1)
    line.SetLineWidth(1)
    line.SetLineStyle(7)
    line.Draw()
    leg.AddEntry(gr, 'With HBHENoise filter', 'P')
    leg.AddEntry(gr2, 'Without HBHENoise filter', 'P')
    leg.Draw()

    txt = 'Path: HLT_PFMETTypeOne200_HBHE_BeamHaloCleaned'
    texcms = AddText(txt)
    texcms.Draw("same")

    c.SaveAs('testTurnOn_EGamma.png')
コード例 #30
0
])
theory_v = TVectorD(7, theory_a)
mass_a = array("d", [1500, 1750, 2000, 2250, 2500, 3000, 3250, 3500])
mass_v = TVectorD(7, mass_a)
err_a = array("d", [0, 0, 0, 0, 0, 0, 0, 0])
err_v = TVectorD(7, err_a)

## theory_a = array("d",[0.0006434760289,0.0005751010031,0.0005231099785,0.0005344069796,0.0005340549978])
## theory_v = TVectorD(5,theory_a)
## mass_a = array("d",[1750,2000,2500,2750,3000])
## mass_v = TVectorD(5,mass_a)
## err_a = array("d",[0,0,0,0,0,0])
## err_v = TVectorD(5,err_a)

theory = TGraphAsymmErrors(mass_v, theory_v, err_v, err_v, err_v, err_v)
theory.SetLineColor(4)
theory.SetLineStyle(9)
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,