Esempio n. 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)
Esempio n. 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")
Esempio n. 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)
Esempio n. 4
0
def readDataIntoGraph():
    f = open('HESSj1745_290.dat', "r")
    lines = f.readlines()
    x, y, yHigh, yLow = array('d'), array('d'), array('d'), array('d')
    #  yScale = 10e12
    yScale = 1
    xScale = 1000
    for iLine in lines:
        if iLine.isspace() == True or iLine[0] == '#':
            continue
        tmpList = iLine.split()
        tmpX = xScale * float(tmpList[0]) * float(tmpList[0])
        x.append(xScale * float(tmpList[0]))
        y.append(yScale * float(tmpList[1]) * tmpX)
        yLow.append(yScale * (float(tmpList[1]) - float(tmpList[2])) * tmpX)
        yHigh.append(yScale * (float(tmpList[3]) - float(tmpList[1])) * tmpX)
    f.close()
    listOfZeros = array("d", [0] * len(x))
    gr = TGraphAsymmErrors(len(x), x, y, listOfZeros, listOfZeros, yLow, yHigh)
    #  gr.SetLineColor( color )
    gr.SetLineWidth(2)
    #  gr.SetMarkerColor( color )
    gr.SetMarkerStyle(21)
    gr.GetXaxis().SetTitle('Energy [GeV]')
    gr.GetYaxis().SetTitle('E^{2} x Flux [GeV cm^{-2}s^{-1}]')
    gr.SetTitle('')
    return gr
Esempio n. 5
0
def convertToPoisson(h):
    graph = TGraphAsymmErrors()
    q = (1-0.6827)/2.

    for i in range(1,h.GetNbinsX()+1):
        x=h.GetXaxis().GetBinCenter(i)
        xLow =h.GetXaxis().GetBinLowEdge(i)
        xHigh =h.GetXaxis().GetBinUpEdge(i)
        y=h.GetBinContent(i)
        yLow=0
        yHigh=0
        if y !=0.0:
            yLow = y-Math.chisquared_quantile_c(1-q,2*y)/2.
            yHigh = Math.chisquared_quantile_c(q,2*(y+1))/2.-y
            graph.SetPoint(i-1,x,y)
            graph.SetPointEYlow(i-1,yLow)
            graph.SetPointEYhigh(i-1,yHigh)
            graph.SetPointEXlow(i-1,0.0)
            graph.SetPointEXhigh(i-1,0.0)


    graph.SetMarkerStyle(20)
    graph.SetLineWidth(2)
    graph.SetMarkerSize(1.)
    graph.SetMarkerColor(kBlack)


    return graph
Esempio n. 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
Esempio n. 7
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
Esempio n. 8
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")
Esempio n. 9
0
def makeEffPlotsVars(tree,
                     varx,
                     vary,
                     sel,
                     nbinx,
                     xmin,
                     xmax,
                     nbiny,
                     ymin,
                     ymax,
                     xtitle,
                     ytitle,
                     leglabel=None,
                     header='',
                     addon='',
                     option='pt',
                     marker=20):

    binning = [20, 30, 40, 50, 60, 70, 80, 100, 150, 200]

    c = TCanvas()

    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)
    elif option == 'nvtx':
        _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon,
                      len(vbinning) - 1, array('d', vbinning))
        _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon,
                       len(vbinning) - 1, array('d', vbinning))

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

    g_efficiency = TGraphAsymmErrors()
    g_efficiency.BayesDivide(_ahist_, _hist_)
    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.Draw('ap')

    #    save(c, 'plots/' + addon)

    return copy.deepcopy(g_efficiency)
Esempio n. 10
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
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
Esempio n. 12
0
def fixData(hist, useGarwood=True, cutGrass=False, maxPoisson=False):
    if hist == None: return
    varBins = False
    data = TGraphAsymmErrors()
    alpha = 1 - 0.6827

    for i in list(reversed(range(0, hist.GetNbinsX()))):
        #print "bin", i, "x:", hist.GetX()[i], "y:", hist.GetY()[i]
        # X error bars to 0 - do not move this, otherwise the first bin will disappear, thanks Wouter and Rene!
        N = max(hist.GetBinContent(i + 1), 0.)  # Avoid unphysical bins
        data.SetPoint(i, hist.GetXaxis().GetBinCenter(i + 1), N)
        if not varBins:
            data.SetPointEXlow(i, 0)
            data.SetPointEXhigh(i, 0)
        # Garwood confidence intervals
        if (useGarwood):
            L = ROOT.Math.gamma_quantile(alpha / 2, N, 1.) if N > 0 else 0.
            U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1)
            # maximum between Poisson and Sumw2 error bars
            EL = N - L if not maxPoisson else max(N -
                                                  L, hist.GetBinErrorLow(i))
            EU = U - N if not maxPoisson else max(U -
                                                  N, hist.GetBinErrorHigh(i))
            data.SetPointEYlow(i, EL)
            data.SetPointEYhigh(i, EU)
        else:
            data.SetPointEYlow(i, math.sqrt(N))
            data.SetPointEYhigh(i, math.sqrt(N))
        # Cut grass
        if cutGrass and data.GetY()[i] > 0.: cutGrass = False
        # Treatment for 0 bins


#        if abs(hist.GetY()[i])<=1.e-6:
#            if cutGrass: hist.SetPointError(i, hist.GetErrorXlow(i), hist.GetErrorXhigh(i), 1.e-6, 1.e-6, )
#            if (hist.GetX()[i]>65 and hist.GetX()[i]<135 and hist.GetY()[i]==0): hist.SetPointError(i, hist.GetErrorXlow(i), hist.GetErrorXhigh(i), 1.e-6, 1.e-6, )
#            hist.SetPoint(i, hist.GetX()[i], -1.e-4)
# X error bars
#if hist.GetErrorXlow(i)<1.e-4:
#    binwidth = hist.GetX()[1]-hist.GetX()[0]
#    hist.SetPointEXlow(i, binwidth/2.)
#    hist.SetPointEXhigh(i, binwidth/2.)
    data.SetMarkerColor(hist.GetMarkerColor())
    data.SetMarkerStyle(hist.GetMarkerStyle())
    data.SetMarkerSize(hist.GetMarkerSize())
    #data.SetLineSize(hist.GetLineSize())
    return data
Esempio n. 13
0
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
Esempio n. 14
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
Esempio n. 15
0
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
Esempio n. 16
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
	ey_hi_mu = grMu.GetErrorYhigh(i)
	ey_hi_ele = grEle.GetErrorYhigh(i)
	if y_mu < 1.e-9 or y_ele < 1.e-9:
		ey_hi_ratio = 0.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)
Esempio n. 18
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
Esempio n. 19
0
def draw(hist, data, back, sign, snorm=1, ratio=0, poisson=False, log=False):
    # If not present, create BkgSum
    if not 'BkgSum' in hist.keys():
        hist['BkgSum'] = hist['data_obs'].Clone(
            "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
        hist['BkgSum'].Reset("MICES")
        for i, s in enumerate(back):
            hist['BkgSum'].Add(hist[s])
    hist['BkgSum'].SetMarkerStyle(0)

    # Some style
    for i, s in enumerate(data):
        hist[s].SetMarkerStyle(21)
        hist[s].SetMarkerSize(1.25)
    for i, s in enumerate(sign):
        hist[s].SetLineWidth(3)

    for i, s in enumerate(data + back + sign + ['BkgSum']):
        addOverflow(hist[s], False)  # Add overflow

    # Set Poisson error bars
    #if len(data) > 0: hist['data_obs'].SetBinErrorOption(1) # doesn't work

    # Poisson error bars for data
    if poisson:
        alpha = 1 - 0.6827
        hist['data_obs'].SetBinErrorOption(TH1.kPoisson)
        data_graph = TGraphAsymmErrors(hist['data_obs'].GetNbinsX())
        data_graph.SetMarkerStyle(hist['data_obs'].GetMarkerStyle())
        data_graph.SetMarkerSize(hist['data_obs'].GetMarkerSize())
        res_graph = data_graph.Clone()
        for i in range(hist['data_obs'].GetNbinsX()):
            N = hist['data_obs'].GetBinContent(i + 1)
            B = hist['BkgSum'].GetBinContent(i + 1)
            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)
            data_graph.SetPoint(
                i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1),
                N if not N == 0 else -1.e99)
            data_graph.SetPointError(
                i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
                hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., N - L,
                U - N)
            res_graph.SetPoint(i,
                               hist['data_obs'].GetXaxis().GetBinCenter(i + 1),
                               N / B if not B == 0 and not N == 0 else -1.e99)
            res_graph.SetPointError(
                i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
                hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
                (N - L) / B if not B == 0 else -1.e99,
                (U - N) / B if not B == 0 else -1.e99)

    # Create stack
    bkg = THStack("Bkg",
                  ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events")
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    n = len([x for x in data + back + ['BkgSum'] + sign if samples[x]['plot']])
    for i, s in enumerate(sign):
        if 'sublabel' in samples[s]: n += 1
        if 'subsublabel' in samples[s]: n += 1
    #leg = TLegend(0.68, 0.9-0.05*n, 0.93, 0.9)
    leg = TLegend(0.68 - 0.05, 0.9 - 0.05 * n, 0.93, 0.9)  #DCMS
    leg.SetTextSize(0.03)  #DCMS
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("Signal x-sec=%.0f pb" % (1 * snorm))
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], samples[data[0]]['label'], "ple1")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s], samples[s]['label'], "f")
    for i, s in enumerate(sign):
        leg.AddEntry(hist[s], samples[s]['label'], "f")

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[-1].GetXaxis().GetTitle(), 1000,
                 800 if ratio else 700)

    if ratio:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), ratio)
        setBotPad(c1.GetPad(2), ratio)
    c1.cd(1)
    c1.GetPad(bool(ratio)).SetTopMargin(0.06)
    c1.GetPad(bool(ratio)).SetRightMargin(0.05)
    c1.GetPad(bool(ratio)).SetTicks(1, 1)
    if log:
        c1.GetPad(bool(ratio)).SetLogy()
        #c1.GetPad(bool(ratio)).SetLogx()

    # Draw
    bkg.Draw("HIST")  # stack
    hist['BkgSum'].Draw("SAME, E2")  # sum of bkg
    if poisson: data_graph.Draw("SAME, PE")
    elif len(data) > 0: hist['data_obs'].Draw("SAME, PE")
    for i, s in enumerate(sign):
        if samples[s]['plot']:
            hist[s].DrawNormalized("SAME, HIST",
                                   hist[s].Integral() * snorm)  # signals

    bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075)

    # Determine range
    if 'data_obs' in hist:
        bkg.SetMaximum((2.5 if log else 1.2) * max(
            bkg.GetMaximum(),
            hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) +
            hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
        bkg.SetMinimum(
            max(
                min(
                    hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
                    )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.)
    else:
        bkg.SetMaximum(bkg.GetMaximum() * (2.5 if log else 1.2))
        bkg.SetMinimum(5.e-1 if log else 0.)
    if log:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        bkg.GetYaxis().SetMoreLogLabels(True)

    leg.Draw()
    #drawCMS(LUMI, "Preliminary")
    #drawRegion(channel)
    #drawAnalysis("LL")

    setHistStyle(bkg, 1.2 if ratio else 1.1)
    setHistStyle(hist['BkgSum'], 1.2 if ratio else 1.1)

    if ratio:
        c1.cd(2)
        err = hist['BkgSum'].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / Bkg")
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if hist['BkgSum'].GetBinContent(i) > 0:
                err.SetBinError(
                    i, hist['BkgSum'].GetBinError(i) /
                    hist['BkgSum'].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(2)
        errLine.SetFillStyle(0)
        errLine.SetLineColor(2)  #L#
        errLine.SetLineStyle(2)  #L#
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if 'data_obs' in hist:
            res = hist['data_obs'].Clone("Residues")
            for i in range(0, res.GetNbinsX() + 1):
                if hist['BkgSum'].GetBinContent(i) > 0:
                    res.SetBinContent(
                        i,
                        res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
                    res.SetBinError(
                        i,
                        res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))
            setBotStyle(res)
            if poisson: res_graph.Draw("SAME, PE0")
            else: res.Draw("SAME, PE0")
            if len(err.GetXaxis().GetBinLabel(
                    1)) == 0:  # Bin labels: not a ordinary plot
                drawRatio(hist['data_obs'], hist['BkgSum'])
                drawKolmogorov(hist['data_obs'], hist['BkgSum'])
        else:
            res = None
    c1.Update()

    # return list of objects created by the draw() function
    return [
        c1, bkg, leg, err if ratio else None, errLine if ratio else None,
        res if ratio else None, data_graph if poisson else None,
        res_graph if poisson else None
    ]
Esempio n. 20
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
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()
Esempio n. 22
0
        rates.append((float(pileup), emtf_rate, emtf_rate_err, emtf2026_rate,
                      emtf2026_rate_err))

    print rates

    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()
Esempio n. 23
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)
Esempio n. 24
0
## 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,
                               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)
Esempio n. 25
0
import math
from ROOT import TFile, TCanvas, TGraph, TGraphAsymmErrors
import array

Binning_PT = array.array("d", [0, 30, 35, 40, 50, 60, 75, 95, 120, 150, 200])
OutFile = TFile("OutPutFR.root")

HistoNum = OutFile.Get("histoLooseNumerator")
HistoNum = HistoNum.Rebin(len(Binning_PT) - 1, "", Binning_PT)

HistoDeNum = OutFile.Get("histoDenominator")
HistoDeNum = HistoDeNum.Rebin(len(Binning_PT) - 1, "", Binning_PT)

fakeRate = TGraphAsymmErrors(HistoNum, HistoDeNum, "")

canv = TCanvas("canv", "histograms", 0, 0, 600, 600)
canv.SetLogy()
fakeRate.GetXaxis().SetRangeUser(0, 200)
fakeRate.GetXaxis().SetTitle("#tau p_{T} [GeV]")
fakeRate.GetYaxis().SetRangeUser(0.01, 0.5)
fakeRate.SetTitle('Jet to Tau Fake Rate')
fakeRate.SetMarkerStyle(20)

fakeRate.Draw()

canv.SaveAs("jetToTauFR.pdf")
Esempio n. 26
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...")
Esempio n. 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...")
Esempio n. 28
0
def main(argv):

    LOADTREE_ANADIR = "/net/user/jfeintzeig/2012/PointSources/FinalFiles/MonteCarlo/"

    tr = TChain("MasterTree")
    tr.Add(LOADTREE_ANADIR + "PrunedNugenUpgoing4866.root")
    tr.Add(LOADTREE_ANADIR + "PrunedNugenDowngoing4866.root")

    tr.GetEntries()

    MCzenith = ctypes.c_double(0)
    tr.SetBranchAddress("MCPrimary1.zenith", MCzenith)

    MCazimuth = ctypes.c_double(0)
    tr.SetBranchAddress("MCPrimary1.azimuth", MCazimuth)

    eneMC = ctypes.c_double(0)
    tr.SetBranchAddress("MCPrimary1.energy", eneMC)

    SMPEzenith = ctypes.c_double(0)
    tr.SetBranchAddress("SplineMPE.zenith", SMPEzenith)

    SMPEazimuth = ctypes.c_double(0)
    tr.SetBranchAddress("SplineMPE.azimuth", SMPEazimuth)

    ene = ctypes.c_double(0)
    tr.SetBranchAddress("SplineMPEMuEXDifferential.energy", ene)

    err1 = ctypes.c_double(0)
    tr.SetBranchAddress("SplineMPEParaboloidFitParams.err1", err1)

    err2 = ctypes.c_double(0)
    tr.SetBranchAddress("SplineMPEParaboloidFitParams.err2", err2)

    oneW = ctypes.c_double(0)
    tr.SetBranchAddress("I3MCWeightDict.OneWeight", oneW)

    nEv = ctypes.c_double(0)
    tr.SetBranchAddress("I3MCWeightDict.NEvents", nEv)

    h = TH2D("pull", "pull", 50, 1, 9, 100, 0.01, 20)
    h.SetStats(0)
    h.GetXaxis().SetTitle("log_{10}(MuEx_energy [GeV])")
    h.GetYaxis().SetTitle("Pull: #Delta#Psi/#sigma_{parab.}")
    g = TGraphAsymmErrors(50)
    medians = [[] for i in range(0, 50)]
    mediansW = [[] for i in range(0, 50)]

    go = TGraph(50)
    go.SetMarkerStyle(22)
    go.SetMarkerColor(4)

    hEneW = TH1D(
        "hEneW",
        "MCPrimary energy; log_{10}(E [GeV]); #frac{d#Phi}{dE} [GeV^{-1} cm^{-2} s^{-1} sr^{-1} ( #frac{E}{GeV} )^{-2} ",
        100, 1, 9.5)
    hREneW = TH1D(
        "hREneW",
        "Reco energy SplineMPEMuEXDiff; log_{10}(E [GeV]); #frac{d#Phi}{dE} [GeV^{-1} cm^{-2} s^{-1} sr^{-1} ( #frac{E}{GeV} )^{-2}",
        100, 1, 9)

    for i in range(0, tr.GetEntries()):
        tr.GetEntry(i)
        #if not hem(SMPEzenith.value):
        #    continue
        #if pSigma(err1.value,err2.value)>np.radians(5.):
        #    continue
        w = weight(oneW.value, eneMC.value, nEv.value)
        hEneW.Fill(log10(eneMC.value), w)
        hREneW.Fill(log10(ene.value), w)
        dAngle = SpaceAngleRad(MCzenith.value, MCazimuth.value,
                               SMPEzenith.value, SMPEazimuth.value)
        h.Fill(log10(ene.value), dAngle / pSigma(err1.value, err2.value), w)
        if h.GetXaxis().FindBin(log10(ene.value)) > 0 and h.GetXaxis().FindBin(
                log10(ene.value)) < 51:
            medians[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(
                dAngle / pSigma(err1.value, err2.value))
            mediansW[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(w)
        #if i>200:
        #break
    npoints = 0

    for i in range(1, h.GetNbinsX() + 1):
        if len(medians[i - 1]) > 3:
            g.SetPoint(
                npoints,
                h.GetXaxis().GetBinCenter(i),
                weighted_percentile(0.5, np.asarray(medians[i - 1]),
                                    np.asarray(mediansW[i - 1])))
            g.SetPointError(
                npoints, 0., 0.,
                weighted_percentile(0.5 - 0.341, np.asarray(medians[i - 1]),
                                    np.asarray(mediansW[i - 1])),
                weighted_percentile(0.5 + 0.341, np.asarray(medians[i - 1]),
                                    np.asarray(mediansW[i - 1])))
            npoints += 1

    c0 = TCanvas()
    hEneW.Draw()

    g.Set(npoints)
    g.SetMarkerStyle(20)
    gStyle.SetPalette(1)
    gStyle.SetOptLogz(1)
    spline = TSpline5("spl", TGraph(g))
    filename = "SplineforCorr_IC86I.root"
    #if hem(0.):
    #    filename=filename+"down.root"
    #else:
    #    filename=filename+"up.root"
    fout = TFile(filename, "RECREATE")
    spline.Write()
    fout.Close()

    print "loading RescaledSigma_IC86_SplineMPE.C"
    ROOT.gROOT.ProcessLine(".L RescaledSigma_IC86_SplineMPE.C+")
    try:
        ROOT.loadSplines()
    except:
        pass
    npoints = 0
    for i in range(1, h.GetNbinsX() + 1):
        if len(medians[i - 1]) > 3:
            #if hem(0.):
            #plotZen=0.
            #else:
            #plotZen=100.
            go.SetPoint(
                npoints,
                h.GetXaxis().GetBinCenter(i),
                ROOT.RescaledSigma_IC86_SplineMPE(
                    1., pow(10,
                            h.GetXaxis().GetBinCenter(i))))
            npoints += 1
    go.Set(npoints)

    del medians[:]
    del medians
    del mediansW[:]
    del mediansW

    c = TCanvas()
    c.SetLogy()
    c.SetGridx()
    c.SetGridy()
    h.SetMinimum(1)
    h.Draw("colz")
    g.Draw("pl same")
    go.Draw("pl same")
    spline.Draw("lp same")

    h2 = TH2D("pull - corrected", "pull - corrected", 50, 1, 9, 100, 0.01, 20)
    h2.GetXaxis().SetTitle("log_{10}(E [GeV])")
    h2.GetYaxis().SetTitle("Pull_{corr}: #Delta#Psi/f_{corr}(#sigma_{parab.})")

    g2 = TGraphAsymmErrors(50)
    medians2 = [[] for i in range(0, 50)]
    medians2W = [[] for i in range(0, 50)]
    g2.SetMarkerStyle(20)

    for i in range(0, tr.GetEntries()):
        tr.GetEntry(i)
        #if not hem(SMPEzenith.value): continue
        #if pSigma(err1.value,err2.value)>np.radians(5.):
        #    continue
        w = weight(oneW.value, eneMC.value, nEv.value)
        dAngle = SpaceAngleRad(MCzenith.value, MCazimuth.value,
                               SMPEzenith.value, SMPEazimuth.value)
        h2.Fill(
            log10(ene.value), dAngle /
            (pSigma(err1.value, err2.value) * spline.Eval(log10(ene.value))),
            w)
        if h.GetXaxis().FindBin(log10(ene.value)) > 0 and h.GetXaxis().FindBin(
                log10(ene.value)) < 51:
            medians2[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(
                dAngle / (pSigma(err1.value, err2.value) *
                          spline.Eval(log10(ene.value))))
            medians2W[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(w)
        #if i>200:
        #break

    npoints = 0
    for i in range(1, h2.GetNbinsX() + 1):
        if len(medians2[i - 1]) > 3:
            g2.SetPoint(
                npoints,
                h.GetXaxis().GetBinCenter(i),
                weighted_percentile(0.5, np.asarray(medians2[i - 1]),
                                    np.asarray(medians2W[i - 1])))
            g2.SetPointError(
                npoints, 0., 0.,
                weighted_percentile(0.5 - 0.341, np.asarray(medians2[i - 1]),
                                    np.asarray(medians2W[i - 1])),
                weighted_percentile(0.5 + 0.341, np.asarray(medians2[i - 1]),
                                    np.asarray(medians2W[i - 1])))
            npoints += 1

    del medians2[:]
    del medians2
    del medians2W[:]
    del medians2W

    g2.Set(npoints)
    c2 = TCanvas()
    c2.SetLogy()
    c2.SetGridx()
    c2.SetGridy()
    h2.SetStats(0)
    h2.SetMinimum(1)
    h2.Draw("colz")
    g2.Draw("pl same")

    h3 = TH2D("pull - corrected xcheck", "pull - corrected xcheck", 50, 1, 9,
              100, 0.01, 20)
    h3.GetXaxis().SetTitle("log_{10}(E [GeV])")
    h3.GetYaxis().SetTitle("Pull_{corr}: #Delta#Psi/f_{corr}(#sigma_{parab.})")
    g3 = TGraphAsymmErrors(50)
    medians3 = [[] for i in range(0, 50)]
    medians3W = [[] for i in range(0, 50)]
    g3.SetMarkerStyle(20)
    SigmaBins = [(0.5, 0.6, 1), (0.6, 0.7, 2), (0.7, 0.9, 4), (0.9, 1.3, 1),
                 (1.3, 1.7, 2)]
    h_pdf_corr = []
    for b in range(len(SigmaBins)):
        h_pdf_corr.append(
            TH1D("h_pdf_corr" + str(b),
                 "h_pdf_corr" + str(b) + ";#Delta#Psi [deg]", 50, 0, 3))
        h_pdf_corr[-1].SetLineColor(SigmaBins[b][2])
        h_pdf_corr[-1].SetLineWidth(2)

    for i in range(0, tr.GetEntries()):
        tr.GetEntry(i)
        #if not hem(SMPEzenith.value): continue
        #if pSigma(err1.value,err2.value)>np.radians(5.):
        #    continue
        w = weight(oneW.value, eneMC.value, nEv.value)
        dAngle = SpaceAngleRad(MCzenith.value, MCazimuth.value,
                               SMPEzenith.value, SMPEazimuth.value)
        pull = dAngle / ROOT.RescaledSigma_IC86_SplineMPE(
            pSigma(err1.value, err2.value), ene.value)
        s_cor = ROOT.RescaledSigma_IC86_SplineMPE(
            pSigma(err1.value, err2.value), ene.value)
        h3.Fill(log10(ene.value), pull, w)
        for b in range(len(SigmaBins)):
            if SigmaBins[b][0] <= np.degrees(
                    s_cor) and SigmaBins[b][1] > np.degrees(s_cor):
                h_pdf_corr[b].Fill(np.degrees(dAngle), w)

        if h.GetXaxis().FindBin(log10(ene.value)) > 0 and h.GetXaxis().FindBin(
                log10(ene.value)) < 51:
            medians3[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(pull)
            medians3W[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(w)
        #if i>200:
        #break

    npoints = 0
    for i in range(1, h2.GetNbinsX() + 1):
        if len(medians3[i - 1]) > 3:
            g3.SetPoint(
                npoints,
                h.GetXaxis().GetBinCenter(i),
                weighted_percentile(0.5, np.asarray(medians3[i - 1]),
                                    np.asarray(medians3W[i - 1])))
            g3.SetPointError(
                npoints, 0., 0.,
                weighted_percentile(0.5 - 0.341, np.asarray(medians3[i - 1]),
                                    np.asarray(medians3W[i - 1])),
                weighted_percentile(0.5 + 0.341, np.asarray(medians3[i - 1]),
                                    np.asarray(medians3W[i - 1])))
            npoints += 1

    c30 = TCanvas()
    leg = ROOT.TLegend(0.7, 0.7, 1., 1.)
    ffunc = []
    for b in range(3):
        h_pdf_corr[b].Sumw2()
        if b == 0:
            h_pdf_corr[b].Draw("HIST")
        else:
            h_pdf_corr[b].Draw("same HIST")

        ffunc.append(TF1("ffunc" + str(b), CircGaus, 0.001, 3., 2))
        ffunc[-1].SetLineColor(SigmaBins[b][2])
        ffunc[-1].SetParameter(0, 1.)
        ffunc[-1].SetParameter(1, 1.)

        h_pdf_corr[b].Fit(ffunc[-1], "R")
        ffunc[-1].Draw("same")
        leg.AddEntry(
            h_pdf_corr[b],
            "range: " + str(SigmaBins[b][0]) + " to " + str(SigmaBins[b][1]) +
            " #sigma_{fit}=" + '{:.2f}'.format(ffunc[-1].GetParameter(0)), "l")
    leg.Draw()

    c31 = TCanvas()
    leg1 = ROOT.TLegend(0.7, 0.7, 1., 1.)
    ffunc = []
    for b in range(3, 5):
        h_pdf_corr[b].Sumw2()
        if b == 0:
            h_pdf_corr[b].Draw("HIST")
        else:
            h_pdf_corr[b].Draw("same HIST")
        ffunc.append(TF1("ffunc" + str(b), CircGaus, 0.001, 3., 2))
        ffunc[-1].SetLineColor(SigmaBins[b][2])
        ffunc[-1].SetParameter(0, 1.)
        ffunc[-1].SetParameter(1, 1.)

        h_pdf_corr[b].Fit(ffunc[-1], "R")
        ffunc[-1].Draw("same")
        leg1.AddEntry(
            h_pdf_corr[b],
            "range: " + str(SigmaBins[b][0]) + " to " + str(SigmaBins[b][1]) +
            " #sigma_{fit}=" + '{:.2f}'.format(ffunc[-1].GetParameter(0)), "l")
    leg1.Draw()

    g3.Set(npoints)
    c3 = TCanvas()
    c3.SetLogy()
    c3.SetGridx()
    c3.SetGridy()
    h3.SetStats(0)
    h3.SetMinimum(1)
    h3.Draw("colz")
    g3.Draw("pl same")
    c3.SaveAs("RescaledSigma_IC86_SplineMPE_corrected.png")
    raw_input("Press Enter to continue...")
Esempio n. 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')
Esempio n. 30
0
def draw(hist,
         channel,
         data,
         back,
         sign,
         snorm=1,
         lumi=-1,
         ratio=0,
         log=False):
    # If not present, create BkgSum
    if not 'BkgSum' in hist.keys():
        hist['BkgSum'] = hist['data_obs'].Clone(
            "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
        hist['BkgSum'].Reset("MICES")
        for i, s in enumerate(back):
            hist['BkgSum'].Add(hist[s])
    hist['BkgSum'].SetMarkerStyle(0)

    # Set Poisson error bars
    #if len(data) > 0: hist['data_obs'].SetBinErrorOption(1) # doesn't work

    alpha = 1 - 0.6827
    hist['data_obs'].SetBinErrorOption(TH1.kPoisson)
    data_graph = TGraphAsymmErrors(hist['data_obs'].GetNbinsX())
    data_graph.SetMarkerStyle(hist['data_obs'].GetMarkerStyle())
    data_graph.SetMarkerSize(hist['data_obs'].GetMarkerSize())
    res_graph = data_graph.Clone()
    for i in range(hist['data_obs'].GetNbinsX()):
        N = hist['data_obs'].GetBinContent(i + 1)
        B = hist['BkgSum'].GetBinContent(i + 1)
        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)
        data_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1),
                            N if not N == 0 else -1.e99)
        data_graph.SetPointError(
            i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
            hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., N - L, U - N)
        res_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1),
                           N / B if not B == 0 and not N == 0 else -1.e99)
        res_graph.SetPointError(
            i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
            hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2.,
            (N - L) / B if not B == 0 else -1.e99,
            (U - N) / B if not B == 0 else -1.e99)

    # Create stack
    bkg = THStack("Bkg",
                  ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events")
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    n = len([x for x in data + back + ['BkgSum'] + sign if sample[x]['plot']])
    leg = TLegend(0.7, 0.9 - 0.05 * n, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pl")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s], sample[s]['label'], "f")
    for i, s in enumerate(sign):
        if sample[s]['plot']:
            leg.AddEntry(hist[s],
                         sample[s]['label'].replace("m_{#Chi}=1 GeV",
                                                    ""), "fl")

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[0].GetXaxis().GetTitle(), 800,
                 800 if ratio else 600)

    if ratio:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), ratio)
        setBotPad(c1.GetPad(2), ratio)
    c1.cd(1)
    c1.GetPad(bool(ratio)).SetTopMargin(0.06)
    c1.GetPad(bool(ratio)).SetRightMargin(0.05)
    c1.GetPad(bool(ratio)).SetTicks(1, 1)
    if log:
        c1.GetPad(bool(ratio)).SetLogy()

    # Draw
    bkg.Draw("HIST")  # stack
    hist['BkgSum'].Draw("SAME, E2")  # sum of bkg
    #if len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data
    data_graph.Draw("SAME, PE")
    for i, s in enumerate(sign):
        if sample[s]['plot']:
            hist[s].DrawNormalized("SAME, HIST",
                                   hist[s].Integral() * snorm)  # signals

    bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075)
    bkg.SetMaximum((2. if log else 1.2) * max(
        bkg.GetMaximum(),
        hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) +
        hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
    bkg.SetMinimum(
        max(
            min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
            )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.)
    if log:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        bkg.GetYaxis().SetMoreLogLabels(True)

    #if log: bkg.SetMinimum(1)
    leg.Draw()
    drawCMS(lumi, "Preliminary")
    drawRegion(channel)
    drawAnalysis(channel)

    #if nm1 and not cutValue is None: drawCut(cutValue, bkg.GetMinimum(), bkg.GetMaximum()) #FIXME
    if len(sign) > 0:
        if channel.startswith('X') and len(sign) > 0:
            drawNorm(0.9 - 0.04 * (n + 1),
                     "#sigma(X) #times B(X #rightarrow Vh) = %.1f pb" % snorm)
            #elif "SR" in channel: drawNorm(0.9-0.04*(n+1), "DM+bb/tt, scaled by %.0f" % snorm, "m_{#chi}=1 GeV, scalar mediator")
        elif "SR" in channel:
            drawNorm(0.9 - 0.04 * (n + 1), "DM+bb/tt, m_{#chi}=1 GeV",
                     "scalar mediator")

    setHistStyle(bkg, 1.2 if ratio else 1.1)
    setHistStyle(hist['BkgSum'], 1.2 if ratio else 1.1)

    if ratio:
        c1.cd(2)
        err = hist['BkgSum'].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / Bkg")
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if hist['BkgSum'].GetBinContent(i) > 0:
                err.SetBinError(
                    i, hist['BkgSum'].GetBinError(i) /
                    hist['BkgSum'].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(1)
        errLine.SetFillStyle(0)
        res = hist['data_obs'].Clone("Residues")
        for i in range(0, res.GetNbinsX() + 1):
            if hist['BkgSum'].GetBinContent(i) > 0:
                res.SetBinContent(
                    i,
                    res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
                res.SetBinError(
                    i,
                    res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))
        setBotStyle(res)
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if len(data) > 0:
            #res.Draw("SAME, PE0")
            res_graph.Draw("SAME, PE0")


#            if len(err.GetXaxis().GetBinLabel(1))==0: # Bin labels: not a ordinary plot
#                drawRatio(hist['data_obs'], hist['BkgSum'])
#                drawKolmogorov(hist['data_obs'], hist['BkgSum'])

    c1.Update()

    # return list of objects created by the draw() function
    return [c1, bkg, leg, err, errLine, res, data_graph, res_graph]