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

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

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

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

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

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

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

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

    graph.SetLineWidth(hist.GetLineWidth())
    graph.SetLineStyle(hist.GetLineStyle())
    graph.SetLineColor(hist.GetLineColor())
    graph.SetMarkerSize(hist.GetMarkerSize())
    graph.SetMarkerStyle(hist.GetMarkerStyle())
    graph.SetMarkerColor(hist.GetMarkerColor())
    graph.SetFillStyle(hist.GetFillStyle())
    graph.SetFillColor(hist.GetFillColor())
    return graph
예제 #6
0
def 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
예제 #8
0
파일: utils.py 프로젝트: zucchett/SFrame
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
예제 #9
0
파일: utils.py 프로젝트: zucchett/SFrame
def convertHistToGraph(hist):
    graph = TGraphAsymmErrors(hist.GetNbinsX())
    for i in range(hist.GetNbinsX()):
        graph.SetPoint(i,
                       hist.GetXaxis().GetBinCenter(i), hist.GetBinContent(i))
        graph.SetPointError(i,
                            hist.GetXaxis().GetBinWidth(i) / 2.,
                            hist.GetXaxis().GetBinWidth(i) / 2.,
                            hist.GetBinError(i), hist.GetBinError(i))
    graph.SetLineWidth(hist.GetLineWidth())
    graph.SetLineStyle(hist.GetLineStyle())
    graph.SetLineColor(hist.GetLineColor())
    graph.SetMarkerSize(hist.GetMarkerSize())
    graph.SetMarkerStyle(hist.GetMarkerStyle())
    graph.SetMarkerColor(hist.GetMarkerColor())
    graph.SetFillStyle(hist.GetFillStyle())
    graph.SetFillColor(hist.GetFillColor())
    return graph
예제 #10
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
예제 #11
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
예제 #12
0
def makeEffPlotsVars(tree,
                     varx,
                     numeratorAddSelection,
                     baseSelection,
                     binning,
                     xtitle='',
                     header='',
                     addon='',
                     marker=20,
                     col=1):

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

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

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

    return g_eff
예제 #13
0
def MakeOneHist(histogramName):

    HeaderLabel = TPaveLabel(header_x_left, header_y_bottom, header_x_right,
                             header_y_top, HeaderText, "NDC")
    HeaderLabel.SetTextAlign(32)
    HeaderLabel.SetBorderSize(0)
    HeaderLabel.SetFillColor(0)
    HeaderLabel.SetFillStyle(0)

    LumiLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right,
                           topLeft_y_top, LumiText, "NDC")
    LumiLabel.SetBorderSize(0)
    LumiLabel.SetFillColor(0)
    LumiLabel.SetFillStyle(0)

    NormLabel = TPaveLabel()
    NormLabel.SetDrawOption("NDC")
    NormLabel.SetX1NDC(topLeft_x_left)
    NormLabel.SetX2NDC(topLeft_x_right)

    NormLabel.SetBorderSize(0)
    NormLabel.SetFillColor(0)
    NormLabel.SetFillStyle(0)

    NormText = ""
    if arguments.normalizeToUnitArea:
        NormText = "Scaled to unit area"

    Legend = TLegend()
    Legend.SetBorderSize(0)
    Legend.SetFillColor(0)
    Legend.SetFillStyle(0)

    Canvas = TCanvas(histogramName)
    Histograms = []
    LegendEntries = []

    colorIndex = 0

    for source in input_sources:  # loop over different input sources in config file
        dataset_file = "condor/%s/%s.root" % (source['condor_dir'],
                                              source['dataset'])
        inputFile = TFile(dataset_file)
        NumHistogramObj = inputFile.Get("OSUAnalysis/" +
                                        source['num_channel'] + "/" +
                                        histogramName)
        if 'condor_dir_den' in source:  # If specified, take the denominator histogram from a different condor directory.
            dataset_fileDen = "condor/%s/%s.root" % (source['condor_dir_den'],
                                                     source['dataset'])
            inputFileDen = TFile(dataset_fileDen)
            DenHistogramObj = inputFileDen.Get("OSUAnalysis/" +
                                               source['den_channel'] + "/" +
                                               histogramName)
        else:  # Default is to use the same condor directory
            DenHistogramObj = inputFile.Get("OSUAnalysis/" +
                                            source['den_channel'] + "/" +
                                            histogramName)
        if not NumHistogramObj:
            print "WARNING:  Could not find histogram " + source[
                'num_channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return
        if not DenHistogramObj:
            print "WARNING:  Could not find histogram " + source[
                'den_channel'] + "/" + histogramName + " in file " + dataset_file + ".  Will skip it and continue."
            return

        Histogram = NumHistogramObj.Clone()
        if Histogram.Class().InheritsFrom("TH2"):
            Histogram.SetName(Histogram.GetName() + "__" + source['dataset'])
        Histogram.SetDirectory(0)
        DenHistogram = DenHistogramObj.Clone()
        DenHistogram.SetDirectory(0)
        inputFile.Close()

        if arguments.rebinFactor:
            RebinFactor = int(arguments.rebinFactor)
            #don't rebin histograms which will have less than 5 bins or any gen-matching histograms
            if Histogram.GetNbinsX() >= RebinFactor * 5 and Histogram.GetTitle(
            ).find("GenMatch") is -1 and not Histogram.Class().InheritsFrom(
                    "TH2"):
                Histogram.Rebin(RebinFactor)
                DenHistogram.Rebin(RebinFactor)

        xAxisLabel = Histogram.GetXaxis().GetTitle()
        unitBeginIndex = xAxisLabel.find("[")
        unitEndIndex = xAxisLabel.find("]")

        if unitBeginIndex is not -1 and unitEndIndex is not -1:  #x axis has a unit
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(
                Histogram.GetXaxis().GetBinWidth(1)
            ) + " " + xAxisLabel[unitBeginIndex + 1:unitEndIndex] + " width)"
        else:
            yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(
                Histogram.GetXaxis().GetBinWidth(1)) + " width)"
        if arguments.normalizeToUnitArea:
            yAxisLabel = yAxisLabel + " (Unit Area Norm.)"

        #Histogram = ROOT.TGraphAsymmErrors(NumHistogramObj,DenHistogramObj)
        if arguments.noTGraph or Histogram.Class().InheritsFrom("TH2"):
            Histogram.Divide(DenHistogram)
        else:
            Histogram = TGraphAsymmErrors(Histogram, DenHistogram)

        if not arguments.makeFancy:
            fullTitle = Histogram.GetTitle()
            splitTitle = fullTitle.split(":")
            #    print splitTitle
            histoTitle = splitTitle[1].lstrip(" ")
        else:
            histoTitle = ""

        if 'color' in source:
            Histogram.SetMarkerColor(colors[source['color']])
            Histogram.SetLineColor(colors[source['color']])
        else:
            Histogram.SetMarkerColor(colors[colorList[colorIndex]])
            Histogram.SetLineColor(colors[colorList[colorIndex]])
            colorIndex = colorIndex + 1
            if colorIndex is len(colorList):
                colorIndex = 0

        markerStyle = 20
        if 'marker' in source:
            markerStyle = markers[source['marker']]
        if 'fill' in source:
            markerStyle = markerStyle + fills[source['fill']]

        Histogram.SetMarkerStyle(markerStyle)

        Histogram.SetLineWidth(line_width)
        Histogram.SetFillStyle(0)

        LegendEntries.append(source['legend_entry'])
        Histograms.append(Histogram)

    ### scaling histograms as per user's specifications
    for histogram in Histograms:
        if arguments.normalizeToUnitArea and histogram.Integral() > 0:
            histogram.Scale(1. / histogram.Integral())

    ### formatting histograms and adding to legend
    legendIndex = 0
    for histogram in Histograms:
        Legend.AddEntry(histogram, LegendEntries[legendIndex], "LEP")
        legendIndex = legendIndex + 1

    ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis
    finalMax = 0
    if arguments.noTGraph:
        for histogram in Histograms:
            currentMax = histogram.GetMaximum() + histogram.GetBinError(
                histogram.GetMaximumBin())
            if (currentMax > finalMax):
                finalMax = currentMax
    finalMax = 1.5 * finalMax
    if finalMax is 0:
        finalMax = 1
    if arguments.setYMax:
        finalMax = float(arguments.setYMax)

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots

    yAxisMin = 0.0001
    if arguments.setYMin:
        yAxisMin = float(arguments.setYMin)

    if makeRatioPlots or makeDiffPlots:
        Canvas.SetFillStyle(0)
        Canvas.Divide(1, 2)
        Canvas.cd(1)
        gPad.SetPad(0, 0.25, 1, 1)
        gPad.SetMargin(0.15, 0.05, 0.01, 0.07)
        gPad.SetFillStyle(0)
        gPad.Update()
        gPad.Draw()
        if arguments.setLogY:
            gPad.SetLogy()
        Canvas.cd(2)
        gPad.SetPad(0, 0, 1, 0.25)
        #format: gPad.SetMargin(l,r,b,t)
        gPad.SetMargin(0.15, 0.05, 0.4, 0.01)
        gPad.SetFillStyle(0)
        gPad.SetGridy(1)
        gPad.Update()
        gPad.Draw()

        Canvas.cd(1)

    histCounter = 0
    plotting_options = ""
    if arguments.plot_hist:
        plotting_options = "HIST"

    for histogram in Histograms:
        if histogram.Class().InheritsFrom("TH2"):
            histogram.SetTitle(histoTitle)
            histogram.Draw("colz")
            DatasetName = histogram.GetName()
            DatasetName = DatasetName[
                DatasetName.rfind('__') +
                2:]  # substring starting with the last underscore
            DatasetLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom,
                                      topLeft_x_right, topLeft_y_top,
                                      DatasetName, "NDC")
            DatasetLabel.SetBorderSize(0)
            DatasetLabel.SetFillColor(0)
            DatasetLabel.SetFillStyle(0)
            DatasetLabel.Draw()
            outputFile.cd()
            Canvas.SetName(histogram.GetName())
            Canvas.Write()
            if arguments.makeFancy:
                HeaderLabel.Draw()

        else:
            if histogram.InheritsFrom("TGraph") and histCounter == 0:
                plotting_options = "AP"
            histogram.SetTitle(histoTitle)
            histogram.Draw(plotting_options)
            histogram.GetXaxis().SetTitle(xAxisLabel)
            histogram.GetYaxis().SetTitle(yAxisLabel)
            if histogram.InheritsFrom("TH1"):
                histogram.SetMaximum(finalMax)
                histogram.SetMinimum(yAxisMin)
            if makeRatioPlots or makeDiffPlots:
                histogram.GetXaxis().SetLabelSize(0)
        if histCounter is 0:
            if histogram.InheritsFrom("TH1"):
                plotting_options = plotting_options + " SAME"
            elif histogram.InheritsFrom("TGraph"):
                plotting_options = "P"
        histCounter = histCounter + 1

    if histogram.Class().InheritsFrom("TH2"):
        return

    #legend coordinates, empirically determined :-)
    x_left = 0.1677852
    x_right = 0.9647651
    y_min = 0.6765734
    y_max = 0.9

    Legend.SetX1NDC(x_left)
    Legend.SetY1NDC(y_min)
    Legend.SetX2NDC(x_right)
    Legend.SetY2NDC(y_max)
    Legend.Draw()

    if arguments.makeFancy:
        HeaderLabel.Draw()

    #drawing the ratio or difference plot if requested

    if makeRatioPlots or makeDiffPlots:
        Canvas.cd(2)
        if makeRatioPlots:
            Comparison = ratioHistogram(Histograms[0], Histograms[1])
        elif makeDiffPlots:
            Comparison = Histograms[0].Clone("diff")
            Comparison.Add(Histograms[1], -1)
            Comparison.SetTitle("")
            Comparison.GetYaxis().SetTitle("hist1-hist2")
        Comparison.GetXaxis().SetTitle(xAxisLabel)
        Comparison.GetYaxis().CenterTitle()
        Comparison.GetYaxis().SetTitleSize(0.1)
        Comparison.GetYaxis().SetTitleOffset(0.5)
        Comparison.GetXaxis().SetTitleSize(0.15)
        Comparison.GetYaxis().SetLabelSize(0.1)
        Comparison.GetXaxis().SetLabelSize(0.15)
        if makeRatioPlots:
            RatioYRange = 1.15
            if arguments.ratioYRange:
                RatioYRange = float(arguments.ratioYRange)
            Comparison.GetYaxis().SetRangeUser(-1 * RatioYRange, RatioYRange)
        elif makeDiffPlots:
            YMax = Comparison.GetMaximum()
            YMin = Comparison.GetMinimum()
            if YMax <= 0 and YMin <= 0:
                Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 0)
            elif YMax >= 0 and YMin >= 0:
                Comparison.GetYaxis().SetRangeUser(0, 1.2 * YMax)
            else:  #axis crosses y=0
                if abs(YMax) > abs(YMin):
                    Comparison.GetYaxis().SetRangeUser(-1.2 * YMax, 1.2 * YMax)
                else:
                    Comparison.GetYaxis().SetRangeUser(-1.2 * YMin, 1.2 * YMin)

        Comparison.GetYaxis().SetNdivisions(205)
        Comparison.Draw("E0")

    outputFile.cd()
    Canvas.Write()

    if arguments.savePDFs:
        Canvas.SaveAs("efficiency_histograms_pdfs/" + histogramName + ".pdf")
예제 #14
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
예제 #15
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
예제 #16
0
def trigger_efficiency(year, separate=False):
    from root_numpy import root2array, fill_hist
    from aliases import triggers, triggers_PFHT, triggers_Jet, triggers_BTag
    import numpy as np
    #spec_triggers = {"PFHT": triggers_PFHT, "Jet": triggers_Jet, "BTag": triggers_BTag}
    spec_triggers = {
        "HT/Jet": "(" + triggers_PFHT + " || " + triggers_Jet + ")",
        "BTag": triggers_BTag
    }
    spec_triggers_colors = {
        "PFHT": 418,
        "Jet": 4,
        "BTag": 6,
        "HT/Jet": 4,
        "total": 2
    }

    hist_pass = TH1F("pass", "pass", 100, 0., 10000.)
    if separate:
        hist_pass_spec = {}
        for trig in spec_triggers.keys():
            hist_pass_spec[trig] = TH1F("pass_" + trig, "pass_" + trig, 100,
                                        0., 10000.)
    hist_all = TH1F("all", "all", 100, 0., 10000.)

    file_list = []

    data_2016_letters = ["B", "C", "D", "E", "F", "G", "H"]
    data_2017_letters = ["B", "C", "D", "E", "F"]
    data_2018_letters = ["A", "B", "C", "D"]

    sample_names = []
    if year == '2016':
        letters = data_2016_letters
    elif year == '2017':
        letters = data_2017_letters
    elif year == '2018':
        letters = data_2018_letters
    else:
        print "unknown year"
        sys.exit()
    for letter in letters:
        #dir_content =  os.listdir(TRIGGERDIR+"/SingleMuon_{}_{}/".format(year, letter)) ## intended to run directly on ntuples
        #for entry in dir_content:
        #    if "_flatTuple" in entry: file_list.append(TRIGGERDIR+"/SingleMuon_{}_{}/".format(year, letter)+entry)
        file_list.append(TRIGGERDIR +
                         "/SingleMuon_{}_{}.root".format(year, letter))
        print "appending:", TRIGGERDIR + "/SingleMuon_{}_{}.root".format(
            year, letter)

    for file_name in file_list:
        temp_array = root2array(file_name,
                                treename='tree',
                                branches='jj_mass_widejet',
                                selection="jj_deltaEta_widejet<1.1")
        fill_hist(hist_all, temp_array)
        temp_array = root2array(file_name,
                                treename='tree',
                                branches='jj_mass_widejet',
                                selection="jj_deltaEta_widejet<1.1 && " +
                                triggers)
        fill_hist(hist_pass, temp_array)
        if separate:
            for trig in spec_triggers.keys():
                temp_array = root2array(
                    file_name,
                    treename='tree',
                    branches='jj_mass_widejet',
                    selection="jj_deltaEta_widejet<1.1 && " +
                    spec_triggers[trig])
                fill_hist(hist_pass_spec[trig], temp_array)
        temp_array = None

    import array
    from aliases import dijet_bins
    binning = []
    for num in dijet_bins:
        if num <= 10000: binning.append(num)
    #binning = range(0,1500,100)+range(1500,2000,100)+range(2000,3100,150)+range(3100,10000,300)
    binning_ = array.array('d', binning)
    hist_pass2 = hist_pass.Rebin(
        len(binning_) - 1, "hist_pass_rebinned", binning_)
    hist_all2 = hist_all.Rebin(
        len(binning_) - 1, "hist_all_rebinned", binning_)

    if separate:
        hist_pass_spec2 = {}
        for trig in spec_triggers.keys():
            hist_pass_spec2[trig] = hist_pass_spec[trig].Rebin(
                len(binning_) - 1, "hist_pass_" + trig + "_rebinned", binning_)

    hist_pass2.Sumw2()
    hist_all2.Sumw2()
    eff = TGraphAsymmErrors()
    eff.Divide(hist_pass2, hist_all2)

    eff.SetMarkerColor(spec_triggers_colors["total"])
    if separate:
        eff.SetMarkerStyle(5)
    else:
        eff.SetMarkerStyle(1)
    eff.SetLineColor(spec_triggers_colors["total"])
    eff.SetLineWidth(2)

    if separate:
        eff_spec = {}
        for trig in spec_triggers.keys():
            hist_pass_spec2[trig].Sumw2()
            eff_spec[trig] = TGraphAsymmErrors()
            eff_spec[trig].Divide(hist_pass_spec2[trig], hist_all2)
            eff_spec[trig].SetMarkerColor(spec_triggers_colors[trig])
            eff_spec[trig].SetMarkerStyle(1)
            eff_spec[trig].SetLineColor(spec_triggers_colors[trig])
            eff_spec[trig].SetLineWidth(2)

    one_line = TGraph()
    one_line.SetPoint(0, 0., 1.)
    one_line.SetPoint(1, 10000., 1.)
    one_line.SetLineStyle(2)

    c1 = TCanvas("c1", "Trigger Efficiency", 800, 800)
    c1.cd(1)
    eff.Draw("AP")
    one_line.Draw("L")
    eff.SetTitle(";m_{jj} (GeV);trigger efficiency")
    eff.SetMinimum(0.)
    eff.SetMaximum(1.4)  #0.65

    ## new
    dijet_bin_centers = []
    for b, lthr in enumerate(dijet_bins[:-1]):
        if lthr < 1200 or lthr > 2500: continue
        dijet_bin_centers.append(0.5 * (dijet_bins[b] + dijet_bins[b + 1]))
    print "total trigger efficiency:"
    for cval in dijet_bin_centers:
        print cval, ":", eff.Eval(cval)
    ## end new

    if separate:
        leg = TLegend(0.65, 0.75, 0.9, 0.95)
        leg.AddEntry(eff, "total")
        for trig in spec_triggers.keys():
            leg.AddEntry(eff_spec[trig], trig + "-based")
            eff_spec[trig].Draw("P SAME")
            ## new
            print trig, "trigger efficiency"
            for cval in dijet_bin_centers:
                print cval, ":", eff_spec[trig].Eval(cval)
            ## end new
        leg.Draw()

    eff.GetXaxis().SetTitleSize(0.045)
    eff.GetYaxis().SetTitleSize(0.045)
    eff.GetYaxis().SetTitleOffset(1.1)
    eff.GetXaxis().SetTitleOffset(1.05)
    eff.GetXaxis().SetLimits(700., 5000.)
    c1.SetTopMargin(0.05)
    #drawCMS(-1, "Preliminary", year=year) #Preliminary
    #drawCMS(-1, "Work in Progress", year=year, suppressCMS=True)
    drawCMS(-1, "", year=year, suppressCMS=True)
    drawAnalysis("")

    suffix = ""
    if separate: suffix = "_sep"

    c1.Print("plots/Efficiency/trigger_" + year + suffix + ".pdf")
    c1.Print("plots/Efficiency/trigger_" + year + suffix + ".png")
예제 #17
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)
    def doit():
        frame = h.ProfileX(hname + "_frame", 1, -1, "s")
        gr1 = TGraphAsymmErrors(h.GetNbinsX())
        gr2 = TGraphAsymmErrors(h.GetNbinsX())
        gr1_aspt = TGraphAsymmErrors(h.GetNbinsX())
        gr2_aspt = TGraphAsymmErrors(h.GetNbinsX())
        # Apply gaussian fits
        for i in xrange(h.GetNbinsX()):
            h_py = h.ProjectionY("_py", i + 1, i + 1)

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

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

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

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

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

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

    g_ratio = g_data.Clone('ratio')

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

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

        g_ratio.SetPointEYlow(i, rel_y_low * ratio)

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

        g_ratio.SetPointEYhigh(i, rel_y_high * ratio)

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

    # hr.GetYaxis().SetNdivisions(4)

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

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

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

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

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

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

    cv, pad, padr = HistDrawer.buildCanvas()

    pad.cd()

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

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

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

    legend.Draw()

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

    drawRatioLines(g_ratio)

    cv.Print(plot_name)
	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)

grRatio.Draw("ALP")
예제 #21
0
    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()

    #gr_denom.Draw("P")
예제 #22
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...")
예제 #23
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)
##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)
latex.SetTextFont(42)
latex.SetTextAlign(33)
예제 #25
0
def limit(channel, signal):
    multF = 1.  # in fb
    filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_scalar" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    if (options.mediator == 'SC'):
        filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_scalar" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    elif (options.mediator == 'PS'):
        filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_pseudo" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    else:
        print 'WRONG mediator type'
    mass, val = fillValues(filename)

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

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

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

    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp1s.SetFillColor(417)  #kGreen+1
    Exp1s.SetLineColor(417)  #kGreen+1
    Exp2s.SetFillColor(800)  #kOrange
    Exp2s.SetLineColor(800)  #kOrange
    Exp2s.GetXaxis().SetTitle("m_{#phi} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle("#sigma/#sigma_{th}")
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

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

    pVal.SetLineWidth(2)
    pVal.SetLineColor(629)
    pVal.GetXaxis().SetTitle("m_{#phi} (GeV)")
    pVal.GetXaxis().SetTitleSize(pVal.GetXaxis().GetTitleSize() * 1.1)
    pVal.GetYaxis().SetTitle("local p-Value")

    Best.SetLineWidth(2)
    Best.SetLineColor(629)
    Best.SetFillColor(629)
    Best.SetFillStyle(3003)
    Best.GetXaxis().SetTitle("m_{#phi} (GeV)")
    Best.GetXaxis().SetTitleSize(Best.GetXaxis().GetTitleSize() * 1.1)
    Best.GetYaxis().SetTitle("Best Fit (pb)")

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogx()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #Theory[0].Draw("SAME, L")
    #Theory[1].Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.045)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetTitleSize(0.04)
    Exp2s.GetXaxis().SetLabelSize(0.04)
    Exp2s.GetYaxis().SetLabelSize(0.04)
    Exp2s.GetXaxis().SetTitleOffset(1)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetRangeUser(0.1, 1000.)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    Exp2s.GetXaxis().SetRangeUser(mass[0], mass[-1])
    drawAnalysis("tDM")
    drawRegion(channel, True)
    drawCMS(LUMI, "Preliminary")

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

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

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

    # legend
    top = 0.9
    nitems = 4 + 2

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

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

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

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

    return

    # ---------- Significance ----------
    c2 = TCanvas("c2", "Significance", 800, 600)
    c2.cd()
    c2.GetPad(0).SetTopMargin(0.06)
    c2.GetPad(0).SetRightMargin(0.05)
    c2.GetPad(0).SetTicks(1, 1)
    c2.GetPad(0).SetGridx()
    c2.GetPad(0).SetGridy()
    Sign.GetYaxis().SetRangeUser(0., 5.)
    Sign.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c2.Print("plotsLimit_" + options.name + "/Significance/" + channel +
                 "_" + options.mediator + "_" + options.bjets + ".png")
        c2.Print("plotsLimit_" + options.name + "/Significance/" + channel +
                 "_" + options.mediator + "_" + options.bjets + ".pdf")
#    c2.Print("plotsLimit/Significance/"+channel+suffix+".root")
#    c2.Print("plotsLimit/Significance/"+channel+suffix+".C")

# ---------- p-Value ----------
    c3 = TCanvas("c3", "p-Value", 800, 600)
    c3.cd()
    c3.GetPad(0).SetTopMargin(0.06)
    c3.GetPad(0).SetRightMargin(0.05)
    c3.GetPad(0).SetTicks(1, 1)
    c3.GetPad(0).SetGridx()
    c3.GetPad(0).SetGridy()
    c3.GetPad(0).SetLogy()
    pVal.Draw("AL3")
    pVal.GetYaxis().SetRangeUser(2.e-7, 0.5)

    ci = [
        1., 0.317310508, 0.045500264, 0.002699796, 0.00006334, 0.000000573303,
        0.000000001973
    ]
    line = TLine()
    line.SetLineColor(922)
    line.SetLineStyle(7)
    text = TLatex()
    text.SetTextColor(922)
    text.SetTextSize(0.025)
    text.SetTextAlign(12)
    for i in range(1, len(ci) - 1):
        line.DrawLine(pVal.GetXaxis().GetXmin(), ci[i] / 2,
                      pVal.GetXaxis().GetXmax(), ci[i] / 2)
        text.DrawLatex(pVal.GetXaxis().GetXmax() * 1.01, ci[i] / 2,
                       "%d #sigma" % i)

    drawCMS(LUMI, "Preliminary")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c3.Print("plotsLimit_" + options.name + "/pValue/" + channel + suffix +
                 "_" + options.mediator + "_" + options.bjets + ".png")
        c3.Print("plotsLimit_" + options.name + "/pValue/" + channel + suffix +
                 "_" + options.mediator + "_" + options.bjets + ".pdf")
#    c3.Print("plotsLimit/pValue/"+channel+suffix+".root")
#    c3.Print("plotsLimit/pValue/"+channel+suffix+".C")

# --------- Best Fit ----------
    c4 = TCanvas("c4", "Best Fit", 800, 600)
    c4.cd()
    c4.GetPad(0).SetTopMargin(0.06)
    c4.GetPad(0).SetRightMargin(0.05)
    c4.GetPad(0).SetTicks(1, 1)
    c4.GetPad(0).SetGridx()
    c4.GetPad(0).SetGridy()
    Best.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c4.Print("plotsLimit_" + options.name + "/BestFit/" + channel +
                 suffix + "_" + options.mediator + "_" + options.bjets +
                 ".png")
        c4.Print("plotsLimit_" + options.name + "/BestFit/" + channel +
                 suffix + "_" + options.mediator + "_" + options.bjets +
                 ".pdf")


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

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
예제 #26
0
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)
latex.SetTextColor(1)
latex.SetTextFont(42)
예제 #27
0
def pullsVertical(fileName):

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

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

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

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

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

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

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

    boxes = []

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

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

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

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

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

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

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

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

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

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

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

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

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
예제 #28
0
for layer in range(1, 35):

    print 'producing trend plot for layer ' + str(layer)

    graphs.append(TGraphAsymmErrors())
    eff_vs_lumi = graphs[-1]
    xlabels = add_points(eff_vs_lumi, hiteffdir + "/" + era, layer, usePU)

    eff_vs_lumi.SetTitle(get_layer_name(layer))
    eff_vs_lumi.GetYaxis().SetTitle("hit efficiency")
    if usePU == 0: eff_vs_lumi.GetXaxis().SetTitle("inst. lumi [x10^{30}]")
    else: eff_vs_lumi.GetXaxis().SetTitle("PU")

    eff_vs_lumi.SetMarkerStyle(20)
    eff_vs_lumi.SetMarkerSize(.8)
    eff_vs_lumi.Draw("AP")

    eff_vs_lumi_lastpt = TGraphAsymmErrors()
    npt = eff_vs_lumi.GetN()
    x, y = ROOT.Double(0), ROOT.Double(0)
    eff_vs_lumi.GetPoint(npt - 1, x, y)
    eff_vs_lumi_lastpt.SetPoint(0, x, y)
    eff_vs_lumi_lastpt.SetMarkerStyle(24)
    eff_vs_lumi_lastpt.SetMarkerColor(2)
    eff_vs_lumi_lastpt.Draw("P")

    if usePU == 0:
        c1.Print("SiStripHitEffTrendPlotVsLumi_layer" + str(layer) + ".png")
    else:
        c1.Print("SiStripHitEffTrendPlotVsPU_layer" + str(layer) + ".png")
예제 #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()