Ejemplo 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)
Ejemplo 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")
Ejemplo 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)
Ejemplo n.º 4
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
Ejemplo n.º 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
Ejemplo n.º 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
Ejemplo n.º 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")
Ejemplo n.º 8
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)
Ejemplo n.º 9
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
Ejemplo n.º 10
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
Ejemplo n.º 11
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
Ejemplo n.º 12
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
Ejemplo n.º 13
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
Ejemplo n.º 14
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
Ejemplo 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
#print threshold_scan

##Prepare the canvas to plot the scan for SL1_L1
can_scan_SL1_L1 = TCanvas("can_scan_SL1_L1","can_scan_SL1_L1", 1000, 800)
can_scan_SL1_L1.SetGrid()
can_scan_SL1_L1.cd()
##Prepare summary TGraph
graph = TGraphAsymmErrors()
n=0
for a in sorted(threshold_scan):
#for a in sorted(run_parameters):
    ##Fill the TGraph with threshold (x-axis) and rate (y-axis)
    #######graph.SetPoint(n,int(run_parameters[a]['VTHR']),float(run_parameters[a]['RATE_SL1_L1']))
    graph.SetPoint(n,int(a),float(threshold_scan[a]))
    n = n+1
graph.SetMarkerSize(1.)
graph.SetMarkerStyle(21)
graph.SetMarkerColor(862)
graph.SetFillColor(868)
graph.SetFillStyle(3844)
graph.SetLineColor(868)
graph.SetLineWidth(2)
graph.SetLineStyle(2)
graph.GetXaxis().SetTitle("threshold [mV]")
graph.GetYaxis().SetTitleOffset(1.2)
graph.GetYaxis().SetTitle("rate [kHz]")
graph.Draw("APL")
latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.04)
latex.SetTextColor(1)
Ejemplo n.º 17
0
def plotQIcalibration(results, outDir = "results", currentMode = ""):
    gROOT.SetBatch(True)
    calibGraphs = []
    gStyle.SetMarkerColor(kBlue)
    gStyle.SetLineColor(kBlack)
    

    #for ch in xrange(1, len(results)+1):   # Number of channels
    for ch in sorted(results.keys()): 
        gr = TGraphAsymmErrors()
        gr.SetMarkerStyle(22)
        gr.SetMarkerSize(1.2)
        gr.SetName("Channel_%d_Charge_vs_DAC" % ch)
        gr.SetTitle("Channel %d  Charge vs DAC value%s" % (ch, "  %s current mode" % currentMode if currentMode in ["low", "high"] else ""))
        

        res = results[ch]
        for i, dacVal in enumerate(sorted(res.keys())):
            mean = res[dacVal]["mean"] * 25.e6  # Convert to fC
            err = res[dacVal]["std"] * 25.e6
   
            # Index of new point
            np = gr.GetN()
            
            # Set value and error
            gr.SetPoint(np, dacVal, mean)
            gr.SetPointError(np, 0., 0., err, err)
 
        calibGraphs.append((gr,ch))

    if outDir[-1] == "/": outDir = outDir[:-1]
    os.system("mkdir -p %s/calibGraphs" % outDir )

    c1 = TCanvas('c1','c1', 1200, 800)
    c1.SetLeftMargin(0.15);
    c1.SetRightMargin(0.25)
    c1.SetBottomMargin(0.25);
    pad1=TPad('p1','p1',0.,0.,1.0,1.0)
    pad1.Draw()

    outF = TFile.Open(outDir + "/calibration.root", "RECREATE")

    fitParams = {}   # Converted to charge by * 25ns

    for i,(gr,ch) in enumerate(calibGraphs):
        gr.Fit('pol1', "Q")   # Q: Quiet mode
        f = gr.GetFunction("pol1")
        p0 = f.GetParameter(0)
        p0_err = f.GetParError(0)
        p1 = f.GetParameter(1)
        p1_err = f.GetParError(1)
        
        fitline = "offset %g #pm %g   slope %g #pm %g" % (p0, p0_err, p1, p1_err)
        
        # Convert to fC
        fitParams[ch] = {"slope":(p1), "offset":(p0)}
        #fitParams[(i+1)] = {"slope":(p1), "offset":(p0)}
        

        gr.GetXaxis().SetTitle("DAC value")
        gr.GetYaxis().SetTitle("Charge [fC]")
        if currentMode == "low":
            gr.GetYaxis().SetTitleOffset(1.37)

        pad1.cd()
        gr.Draw("AP")
        gr.Write()
        txt=TLatex()
        txt.SetNDC(True)
        txt.SetTextFont(43)
        txt.SetTextSize(20)
        txt.SetTextAlign(12)
        txt.DrawLatex(0.40,0.87, fitline)
        Quiet(c1.SaveAs)(outDir + "/calibGraphs/channel_%d.png" % (i+1))
    
#    for g in adcGraphs:
 #       
  #      g.Write()

   # for g in chargeGraphs:
    #    g.Write()

    #outF.Write()
    outF.Close()
    return fitParams
Ejemplo n.º 18
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
    ]
Ejemplo n.º 19
0
def draw(hist, data, back, sign, snorm=1, ratio=0, poisson=True, log=False):

    groupList = plt.cfg.getGroupPlot()

    # If not present, create BkgSum
    #if not 'BkgSum' in hist.keys():
    #    hist['BkgSum'] = hist['DATA'].Clone("BkgSum") if 'DATA' in hist else hist[back[0]].Clone("BkgSum")
    #    hist['BkgSum'].Reset("MICES")
    #    for i, s in enumerate(back): hist['BkgSum'].Add(hist[s].GetPtr())
    hist['BkgSum'].SetMarkerStyle(0)

    # Some style
    for i, s in enumerate(data):
        hist[s].SetMarkerStyle(20)
        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'].SetBinErrorOption(TH1.kPoisson)
        data_graph = TGraphAsymmErrors(hist['DATA'].GetNbinsX())
        data_graph.SetMarkerStyle(hist['DATA'].GetMarkerStyle())
        data_graph.SetMarkerSize(hist['DATA'].GetMarkerSize())
        res_graph = data_graph.Clone()
        for i in range(hist['DATA'].GetNbinsX()):
            N = hist['DATA'].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'].GetXaxis().GetBinCenter(i + 1),
                                N if not N == 0 else -1.e99)
            data_graph.SetPointError(
                i, hist['DATA'].GetXaxis().GetBinWidth(i + 1) / 2.,
                hist['DATA'].GetXaxis().GetBinWidth(i + 1) / 2., N - L, U - N)
            res_graph.SetPoint(i, hist['DATA'].GetXaxis().GetBinCenter(i + 1),
                               N / B if not B == 0 and not N == 0 else -1.e99)
            res_graph.SetPointError(
                i, hist['DATA'].GetXaxis().GetBinWidth(i + 1) / 2.,
                hist['DATA'].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")
    bkg = THStack(
        "Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";" +
        hist['BkgSum'].GetYaxis().GetTitle())

    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    n = len(
        [x for x in data + back + ['BkgSum'] + sign if groupList[x]['plot']])
    for i, s in enumerate(sign):
        if 'sublabel' in groupList[s]: n += 1
        if 'subsublabel' in groupList[s]: n += 1
    leg = TLegend(0.7, 0.9 - 0.05 * n, 0.95, 0.9)
    #leg.SetNColumns(3)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    if len(data) > 0:
        #leg.AddEntry( hist[data[0]] , groupList[data[0]]['label'], "pl")
        leg.AddEntry(
            hist[data[0]], '%s [%.1f]' %
            (groupList[data[0]]['label'], hist[data[0]].Integral()), "pl")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s] if s == 'BkgSum' else hist[s],
                     '%s [%.1f]' % (groupList[s]['label'], hist[s].Integral()),
                     "f")
    for i, s in enumerate(sign):
        if groupList[s]['plot']:
            #leg.AddEntry( hist[s] if s=='BkgSum' else hist[s] , groupList[s]['label'], "fl")
            leg.AddEntry(
                hist[s] if s == 'BkgSum' else hist[s],
                '%s [%.1f]' % (groupList[s]['label'], hist[s].Integral()),
                "fl")

            #print samples[s]
            if 'sublabel' in groupList[s]:
                leg.AddEntry(
                    hist[s] if s == 'BkgSum' else hist[s],
                    groupList[s]['sublabel'].replace("m_{#Chi}=1 GeV", ""), "")
            if 'subsublabel' in groupList[s]:
                leg.AddEntry(
                    hist[s] if s == 'BkgSum' else hist[s],
                    groupList[s]['subsublabel'].replace("m_{#Chi}=1 GeV",
                                                        ""), "")

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[-1].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 poisson: data_graph.Draw("SAME, PE")
    elif len(data) > 0: hist['DATA'].Draw("SAME, PE")
    for i, s in enumerate(sign):
        if groupList[s]['plot']:
            hist[s].DrawNormalized("SAME, HIST",
                                   hist[s].Integral() * snorm)  # signals

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

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

    #set range on stack
    bkg.SetMinimum(5.e-1 if log else 1.0)

    leg.Draw()

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

    if ratio:
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*1)
        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)
        errLine.SetLineColor(1)
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*1)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*1)
        #err.GetYaxis().SetTitleOffset(err.GetYaxis().GetTitleOffset()*1)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if 'DATA' in hist:
            res = hist['DATA'].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'], hist['BkgSum'])
                drawKolmogorov(hist['DATA'], hist['BkgSum'])
                if len(sign) != 0: drawSB(hist['BkgSum'], hist[sign[0]])
                #drawRelativeYield( hist['DATA'] , hist['BkgSum'] )
        else:
            res = None
    c1.Update()

    # return list of objects created by the draw() function
    if not ratio:
        return [
            c1, bkg, leg, data_graph if poisson else None,
            res_graph if poisson else None
        ]
    else:
        return [
            c1, bkg, leg, err, errLine, res, data_graph if poisson else None,
            res_graph if poisson else None
        ]
Ejemplo n.º 20
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]
Ejemplo n.º 21
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)
	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)
Ejemplo n.º 23
0
                      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()
Ejemplo n.º 24
0
def draw_geff(target_dir,
              c_title,
              ext,
              t,
              title,
              h_name,
              h_bins,
              to_draw,
              denom_cut,
              extra_num_cut,
              opt,
              color,
              marker_st=1,
              marker_sz=1):
    c = TCanvas("c", "c", 600, 600)
    c.Clear()
    gPad.SetGrid(1)
    gStyle.SetStatStyle(0)
    gStyle.SetOptStat(0)
    gStyle.SetOptFit(0)
    t.Draw(to_draw + ">>num_" + h_name + h_bins, extra_num_cut + denom_cut,
           "goff")
    num = TH1F(gDirectory.Get("num_" + h_name))
    if not num:
        sys.exit('num does not exist')
    num = TH1F(num.Clone("eff_" + h_name))

    t.Draw(to_draw + ">>denom_" + h_name + h_bins, denom_cut, "goff")
    den = TH1F(gDirectory.Get("denom_" + h_name).Clone("denom_" + h_name))
    eff = TGraphAsymmErrors(num, den)
    if not "same" in opt:
        num.Reset()
        num.GetYaxis().SetRangeUser(0., 1.05)
        num.SetStats(0)
        num.SetTitle(title)
        num.Draw()

    eff.SetLineWidth(2)
    eff.SetLineColor(color)
    eff.SetMarkerStyle(marker_st)
    eff.SetMarkerColor(color)
    eff.SetMarkerSize(marker_sz)
    eff.Draw(opt + " same")

    ## Do fit in the flat region
    if "eta" in c_title:
        xmin = eta_min
        xmax = eta_max
    else:
        xmin = -999.
        xmax = 999.

    f1 = TF1("fit1", "pol0", xmin, xmax)
    r = eff.Fit("fit1", "RQS")
    ptstats = TPaveStats(0.25, 0.35, 0.75, 0.55, "brNDC")
    ptstats.SetName("stats")
    ptstats.SetBorderSize(0)
    ptstats.SetLineWidth(0)
    ptstats.SetFillColor(0)
    ptstats.SetTextAlign(11)
    ptstats.SetTextFont(42)
    ptstats.SetTextSize(.05)
    ptstats.SetTextColor(kRed)
    ptstats.SetOptStat(0)
    ptstats.SetOptFit(1111)
    chi2 = int(r.Chi2())
    ndf = int(r.Ndf())
    ##   prob = r.Prob()
    round(2.675, 2)
    p0 = f1.GetParameter(0)
    p0e = f1.GetParError(0)
    ptstats.AddText("#chi^{2} / ndf: %d/%d" % (chi2, ndf))
    ##   ptstats.AddText("Fit probability: %f %" %(prob))
    ptstats.AddText("Efficiency: %f #pm %f %%" % (p0, p0e))
    ptstats.Draw("same")
    pt = TPaveText(0.09899329, 0.9178322, 0.8993289, 0.9737762, "blNDC")
    pt.SetName("title")
    pt.SetBorderSize(1)
    pt.SetFillColor(0)
    pt.SetFillStyle(0)
    pt.SetTextFont(42)
    pt.AddText(eff.GetTitle())
    pt.Draw("same")
    c.Modified()
    c.SaveAs(target_dir + c_title + ext)
Ejemplo n.º 25
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...")
Ejemplo n.º 26
0
##Prepare the canvas to plot the HV scan for SL1_L1
can_HV_scan_SL1_L1 = TCanvas("can_HV_scan_SL1_L1", "can_HV_scan_SL1_L1", 1000,
                             800)
can_HV_scan_SL1_L1.SetGrid()
can_HV_scan_SL1_L1.cd()
##Prepare summary TGraph
graph_HV_L1 = TGraphAsymmErrors()
n = 0
for a in sorted(HV_scan_L1):
    #for a in sorted(run_parameters):
    ##Fill the TGraph with threshold (x-axis) and rate (y-axis)
    #######graph.SetPoint(n,int(run_parameters[a]['VTHR']),float(run_parameters[a]['RATE_SL1_L1']))
    graph_HV_L1.SetPoint(n, int(a), float(HV_scan_L1[a]))
    n = n + 1
graph_HV_L1.SetMarkerSize(1.)
graph_HV_L1.SetMarkerStyle(21)
graph_HV_L1.SetMarkerColor(418)
graph_HV_L1.SetFillColor(868)
graph_HV_L1.SetFillStyle(3844)
graph_HV_L1.SetLineColor(418 - 1)
graph_HV_L1.SetLineWidth(2)
graph_HV_L1.SetLineStyle(2)
graph_HV_L1.GetXaxis().SetTitle("HV [V]")
graph_HV_L1.GetYaxis().SetTitleOffset(1.2)
graph_HV_L1.GetYaxis().SetTitle("efficiency")
graph_HV_L1.GetYaxis().SetRangeUser(0, 1.01)
graph_HV_L1.Draw("APL")
latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.04)
Ejemplo 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...")
Ejemplo n.º 28
0
def nuisance_plot(input_file_, orien_, sticker_, oname_):

    pars = get_parameters_from_file(input_file_)
    #adjust_parameters(pars)

    N = len(pars)

    g68 = TGraph(2 * N + 7)
    g95 = TGraph(2 * N + 7)
    gPR = TGraphAsymmErrors(N)

    for i in range(0, N):
        x = pars[i].value
        y = i + 1.5
        xerr = pars[i].error
        yerr = 0.

        if orien_ == 'h':
            x, y = y, x
            xerr, yerr = yerr, xerr

        gPR.SetPoint(i, x, y)
        gPR.SetPointEXlow(i, xerr)
        gPR.SetPointEYlow(i, yerr)
        gPR.SetPointEXhigh(i, xerr)
        gPR.SetPointEYhigh(i, yerr)

    for a in range(0, N + 3):

        if orien_ == 'h':
            g68.SetPoint(a, a, -1)
            g95.SetPoint(a, a, -2)
            g68.SetPoint(a + 1 + N + 2, N + 2 - a, 1)
            g95.SetPoint(a + 1 + N + 2, N + 2 - a, 2)

        else:
            g68.SetPoint(a, -1, a)
            g95.SetPoint(a, -2, a)
            g68.SetPoint(a + 1 + N + 2, 1, N + 2 - a)
            g95.SetPoint(a + 1 + N + 2, 2, N + 2 - a)

    gPR.SetLineStyle(1)
    gPR.SetLineWidth(1)
    gPR.SetLineColor(1)
    gPR.SetMarkerStyle(21)
    gPR.SetMarkerSize(1.25)

    g68.SetFillColor(kGreen)
    g95.SetFillColor(kYellow)

    if orien_ == 'h':
        text_TL = TPaveText(0.100, 0.925, 0.440, 0.995, 'NDC')
        text_TR = TPaveText(0.587, 0.925, 0.999, 0.993, 'NDC')

    else:
        text_TL = TPaveText(0.370, 0.945, 0.590, 0.995, 'NDC')
        text_TR = TPaveText(0.600, 0.945, 0.995, 0.993, 'NDC')

    text_TL.AddText(label_TL)
    text_TL.SetFillColor(0)
    text_TL.SetTextAlign(12)
    text_TL.SetTextSize(0.06)
    text_TL.SetTextFont(42)

    text_TR.AddText(sticker_)
    text_TR.SetFillColor(0)
    text_TR.SetTextAlign(32)
    text_TR.SetTextSize(0.05)
    text_TR.SetTextFont(42)

    if orien_ == 'h':
        c = TCanvas('c', 'c', 1000, 700)
        c.SetTopMargin(0.08)
        c.SetRightMargin(0.02)
        c.SetBottomMargin(0.16)
        c.SetLeftMargin(0.11)

    else:
        c = TCanvas('c', 'c', 700, 1000)
        c.SetTopMargin(0.06)
        c.SetRightMargin(0.02)
        c.SetBottomMargin(0.12)
        c.SetLeftMargin(0.35 * 700 / 650)

    c.SetTickx()
    c.SetTicky()

    c.Update()
    g95.Draw('AF')
    g68.Draw('F')
    gPR.Draw('P')
    text_TL.Draw('same')
    text_TR.Draw('same')

    ax_1 = g95.GetHistogram().GetYaxis()
    ax_2 = g95.GetHistogram().GetXaxis()
    if orien_ == 'h': ax_1, ax_2 = ax_2, ax_1

    ax_1.Set(N + 2, 0, N + 2)
    ax_1.SetNdivisions(-414)
    for i in range(0, N):
        ax_1.SetBinLabel(i + 2, pars[i].name)

    g95.SetTitle('')
    ax_2.SetTitle('post-fit nuisance parameters values')
    #ax_2.SetTitle('deviation in units of #sigma')
    ax_1.SetTitleSize(0.050)
    ax_2.SetTitleSize(0.050)
    ax_1.SetTitleOffset(1.4)
    ax_2.SetTitleOffset(1.0)
    ax_1.SetLabelSize(0.05)
    #ax_2.SetLabelSize(0.05)
    ax_1.SetRangeUser(0, N + 2)
    ax_2.SetRangeUser(-2.4, 2.4)

    g95.GetHistogram().Draw('axis,same')

    c.SaveAs(oname_ + '.pdf')

    c.Close()
Ejemplo 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')
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()