def save(imgdir,
         imgname,
         redraw_axis=True,
         dot_pdf=True,
         dot_root=False,
         dot_c=False,
         additional=[]):
    if redraw_axis:
        gPad.RedrawAxis()
    #gPad.Modified(); gPad.Update()
    gPad.Print(imgdir + imgname + ".png")
    if dot_pdf:
        gPad.Print(imgdir + imgname + ".pdf")
    if dot_root:

        def save_for_root(p):
            if p.ClassName() == "TPad" or p.ClassName() == "TCanvas":
                for pp in p.GetListOfPrimitives():
                    save_for_root(pp)
            p.Write()

        tfile = TFile.Open(imgdir + imgname + ".root", "RECREATE")
        save_for_root(gPad)

        if additional:
            for a in additional:
                a.Write()
        tfile.Close()
    if dot_c:
        gPad.Print(imgdir + imgname + ".C")
Example #2
0
def gPadSet():
    gPad.SetTickx(1)
    gPad.SetTicky(1)
    gPad.SetLeftMargin(0.12)
    gPad.SetRightMargin(1.4)
    gPad.SetBottomMargin(0.10)
    gPad.SetFrameLineWidth(2)
    gPad.RedrawAxis()
Example #3
0
def SaveRatio(hSS, hOS, process, output):

    idata = process.split('_')[0]
    suffix = process.split('_ss_')[-1]

    #print "hSS : " , hSS
    #print "hOS : " , hOS

    name = '%s_%s' % (idata, suffix)
    hratio = hSS.Clone('hratio_%s' % name)
    hratio.Divide(hOS)

    hratio.SetMarkerStyle(20)
    hratio.SetMarkerSize(1.25)
    hratio.SetFillColor(418)
    hratio.SetFillStyle(1001)
    hratio.SetLineColor(1)
    hratio.SetLineStyle(1)
    hratio.SetLineWidth(2)

    c1 = TCanvas('hratio_%s' % name, 'hratio_%s' % name, 800, 600)
    if suffix.split('_')[-1] == '2d':
        TGaxis.SetMaxDigits(2)
        #fout = TFile.Open( 'plots/%s/Object_studies/Ratio_%s_%s_%s.root' %(_token,_token,_isample,_ivar), 'RECREATE' )
        c1.SetRightMargin(0.2)
        hratio.SetAxisRange(0.00001, 0.01, "Z")
        hratio.SetTitle('')
        hratio.GetZaxis().SetTitle('N_SS/N_OS (%s)' % idata)
        hratio.GetXaxis().SetTitle('Lepton1 eta')
        hratio.GetYaxis().SetTitle('Lepton2 eta')
        hratio.Draw('colztextE')
    else:
        hratio.SetTitle('')
        hratio.GetYaxis().SetTitle('N_SS/N_OS Ratio (%s)' % idata)
        hratio.Draw('PE')

    c1.cd()
    if '2016' in output: CMS_lumi.lumi_13TeV = "35.87 fb^{-1}"
    elif '2017' in output: CMS_lumi.lumi_13TeV = "41.53 fb^{-1}"
    elif '2018' in output: CMS_lumi.lumi_13TeV = "59.74 fb^{-1}"
    CMS_lumi.writeExtraText = 1
    CMS_lumi.extraText = "Preliminary"
    CMS_lumi.CMS_lumi(c1, 4, 0)
    gPad.RedrawAxis()

    #c1.cd()
    #if '2016' in _token:
    #    drawCMS("35.87", "Object Study")
    #elif '2017' in _token:
    #    drawCMS("41.53", "Object Study")
    #elif '2018' in _token:
    #    drawCMS("59.74", "Object Study")

    c1.Print('%s/Ratio_%s.png' % (output, name))
    #c1.Print( '%s/Ratio_%s.pdf' %(output,name) )
    TGaxis.SetMaxDigits(5)
 def draw(self):
     if not self.histoFinalized:
         self.finalizeHistograms()
     self.canSup.cd()
     self.h1.Draw()
     self.h2.Draw('same')
     if self.legend == None:
         self.setUpLegend()
     self.legend.Draw()
     gPad.RedrawAxis()
     self.canSup.SaveAs(self.canSup.GetName() + '.png')
     self.canEff.cd()
     # if self.eff == None:
     #     self.computeEff()
     self.eff.GetYaxis().SetRangeUser(0.0001, 2)
     self.eff.Draw()
     self.canEff.SaveAs(self.canEff.GetName() + '.png')
Example #5
0
def Frame(gPad, width=2):
    gPad.Update()
    gPad.RedrawAxis()
    l = ROOT.TLine()
    l.SetLineWidth(width)
    lm = gPad.GetLeftMargin()
    rm = 1. - gPad.GetRightMargin()
    tm = 1. - gPad.GetTopMargin()
    bm = gPad.GetBottomMargin()
    #top
    l.DrawLineNDC(lm, tm, rm, tm)
    #right
    l.DrawLineNDC(rm, bm, rm, tm)
    #bottom
    l.DrawLineNDC(lm, bm, rm, bm)
    #top
    l.DrawLineNDC(lm, bm, lm, tm)
Example #6
0
 def __draw_cut(h, show=True):
     if show:
         fit = h.GetListOfFunctions()[1]
         xmin, xmax = fit.GetParameter(1) - 3 * fit.GetParameter(
             2), fit.GetParameter(1) + 3 * fit.GetParameter(2)
         b = Draw.box(xmin,
                      -10,
                      xmax,
                      1e7,
                      line_color=2,
                      width=2,
                      fillstyle=3001,
                      style=7)
         h.Draw('same')
         b.Draw('l')
         Draw.legend([b], ['cut (3 sigma)'],
                     'lf',
                     .59,
                     y2=.656,
                     margin=.45,
                     scale=1.25)
         gPad.RedrawAxis()
Example #7
0
hs.SetMinimum(0.1)
gPad.SetLogy()

hs.Draw("Hist")
h_bkg.Draw("e2 same")
h_data.Draw("same")

for ihist in reversed(templates[5:8]):
    print 'overlaying, ', ihist.GetName()
    ihist.Draw("ehist same")

xTitle = h_top.GetXaxis().GetTitle()
yTitle = h_top.GetYaxis().GetTitle()

setTitle(hs, xTitle)
gPad.RedrawAxis()
ll = TLatex()
ll.SetNDC(kTRUE)
ll.SetTextSize(0.05)
ll.DrawLatex(0.78, 0.92, "0.53 fb^{-1} (13 TeV)")
#2.2

cms = TLatex()
cms.SetNDC(kTRUE)
cms.SetTextFont(61)
cms.SetTextSize(0.08)
cms.DrawLatex(0.12, 1 - t + 0.2 * t, "CMS")

sel = TLatex()
sel.SetNDC(kTRUE)
sel.SetTextSize(0.065)
Example #8
0
def plot(ana, histos, h_legend, minY, maxY, minX, maxX, whatX, whatY, c1=0):
    global stack, leg, dum
    #	print what
    #	gROOT.SetBatch(True)                                        # suppress root window popping up #! better: sys.argv.append('b')
    gROOT.ProcessLine(
        "gErrorIgnoreLevel = kWarning;"
    )  # suppress standard output of the form: "Info in <TCanvas::Print>: ... has been created" and
    #                                                                                                           "Info in <TCanvas::SaveAs>: ... has been created"
    #prepare the layout
    if c1 == 0:
        c1 = TCanvas('c1', '', 800, 600)
    c1.SetLogy()
    dum = histo.Clone()
    #	dum.Reset()
    dum.SetMinimum(minY)
    dum.SetMaximum(maxY)
    dum.GetXaxis().SetRangeUser(minX, maxX)
    #        last = dum.FindLastBinAbove(0,1)
    #        last = last + 0.5 * last
    #        dum.GetXaxis().SetRange(0,last+10)
    dum.GetXaxis().SetTitleSize(0.038)
    dum.GetYaxis().SetTitleSize(0.04)
    dum.GetXaxis().SetLabelSize(0.03)
    dum.GetYaxis().SetLabelSize(0.03)
    dum.GetXaxis().SetTitleOffset(1.2)
    dum.GetYaxis().SetTitleOffset(1.1)
    dum.SetXTitle(whatX)
    dum.SetYTitle(whatY)
    dum.SetTitle('')
    dum.SetStats(0)
    dum.Draw()

    tex = TLatex(
        0.89, 0.93,
        "#scale[0.8]{CMSSW_7_2_3}                    #scale[0.6]{ #sqrt{s} = 13 TeV, #int L dt = 4 fb^{-1}, bx = 25 ns, PU = 20}"
    )
    tex.SetNDC()
    tex.SetTextAlign(31)
    tex.SetTextFont(42)
    tex.SetTextSize(0.047)
    tex.SetLineWidth(2)
    tex.Draw()
    #CMS_lumi_v2( c1, 14, 11 )
    #        tex1 = TLatex(0.15,0.89,"CMSSW_7_2_3 ")
    #        tex1.SetNDC()
    #        tex1.SetTextAlign(13)
    #        tex1.SetTextFont(61)
    #        tex1.SetTextSize(0.045)
    #        tex1.SetLineWidth(2)
    #        tex1.Draw()
    # a legend
    #	leg = TLegend(0.63,0.525,0.87,0.875) #for 33 TeV
    #        leg = TLegend(0.65,0.65,0.9,0.9)
    leg = TLegend(0.6545226, 0.534965, 0.8944724, 0.8846154)  #fits best
    leg.SetBorderSize(1)
    leg.SetTextFont(62)
    leg.SetTextSize(0.035)
    leg.SetLineColor(0)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    leg.SetFillColor(0)
    leg.SetFillStyle(1001)
    if ana == 'TTbar':
        title = ' t#bar{t}'
        leg.AddEntry(histo, title, 'l')
    elif ana == 'WJets':
        leg.AddEntry(histo, 'W+jets', 'l')
    elif ana == 'DYJets':
        leg.AddEntry(histo, 'DY+jets', 'l')
    elif ana == 'QCD':
        leg.AddEntry(histo, 'QCD', 'l')
    elif ana == 'SingleTop':
        leg.AddEntry(histo, 't / #bar{t}', 'l')
    elif ana == 'TTH':
        leg.AddEntry(histo, 'ttH', 'l')
    elif ana == 'TTW':
        leg.AddEntry(histo, 'ttW', 'l')
    elif ana == 'TTZ':
        leg.AddEntry(histo, 'ttZ', 'l')
    elif ana == 'T1tttt_1500_100':
        leg.AddEntry(histo, 'T1t^{4}(1500,100)', 'l')
    elif ana == 'T1tttt_1200_800':
        leg.AddEntry(histo, 'T1t^{4}(1200,800)', 'l')
    elif ana == 'T5tttt_1000_280':
        leg.AddEntry(histo, 'T5t^{4}(1000,280)', 'l')
    elif ana == 'T5tttt_1300_280':
        leg.AddEntry(histo, 'T5t^{4}(1300,280)', 'l')
    elif ana == 'T5tttt_1000_285':
        leg.AddEntry(histo, 'T5t^{4}(1000,285)', 'l')
    elif ana == 'T5tttt_1300_285':
        leg.AddEntry(histo, 'T5t^{4}(1300,285)', 'l')
    elif ana == 'T1ttbbWW_1300_290':
        leg.AddEntry(histo, 'T1t^{2}b^{2}W^{2}(1300,290)', 'l')
    elif ana == 'T1ttbbWW_1300_295':
        leg.AddEntry(histo, 'T1t^{2}b^{2}W^{2}(1300,295)', 'l')
    elif ana == 'T1ttbbWW_1000_715':
        leg.AddEntry(histo, 'T1t^{2}b^{2}W^{2}(1000,715)', 'l')
    elif ana == 'T1ttbbWW_1000_720':
        leg.AddEntry(histo, 'T1t^{2}b^{2}W^{2}(1000,720)', 'l')
    elif ana == 'SqGl_1300_100':
        leg.AddEntry(histo, 'SqGl(1300,100)', 'l')
# bgrd stack
    if histos != 0 and h_legend != 0:
        stack = THStack('stack', '')
        N = len(histos)
        for i in range(N):
            h = histos[i][0]
            stack.Add(h)
        for i in range(N - 1, -1, -1):
            h = histos[i][0]
            t = h_legend[h]
            leg.AddEntry(h, t, 'f')
        # draw bgrds + signals
#            stack.Draw('samehist')
        stack.Draw('same')

#histo.Draw('samehist')
    histo.Draw('same')
    leg.Draw("same")
    gPad.RedrawAxis()

    c1.SaveAs(dir_png_noCuts + what + ".png")
    c1.SaveAs(dir_pdf_noCuts + what + ".pdf")
    c1.SaveAs(dir_root_noCuts + what + ".root")
def plotDistributionComparisonPlot(cfg):

    multiGraph = TMultiGraph()
    multiGraph.SetName("triggerRateMultiGraph")

    tfiles = []

    histograms = []

    canvas = TCanvas("canvas", "canvas", 800, 800)
    '''Contains the legend'''
    legend = TLegend(0.3, 0.7, 0.90, 0.9)
    '''Maximum value container, used to scale histograms'''
    maximumY = float("-inf")

    pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
    pad1.SetBottomMargin(0.05)  # Upper and lower plot are joined
    #pad1.SetBottomMargin(0) # Upper and lower plot are joined
    pad1.SetGridx()  # Vertical grid
    pad1.Draw()  # Draw the upper pad: pad1
    pad1.cd()  # pad1 becomes the current pad

    for histogramFileNameAndTitle in cfg.plots:
        tfile = TFile(histogramFileNameAndTitle[0])
        tfiles.append(tfile)
        histogram = tfile.Get(histogramFileNameAndTitle[1])
        histograms.append(histogram)
        if histogram.ClassName() == "TH1F":
            histogram.SetStats(0)  # No statistics on upper plot
        maximumY = histogram.GetMaximum(
        ) if histogram.GetMaximum() > maximumY else maximumY
        legend.AddEntry(histogram, histogramFileNameAndTitle[2], "l")

    # histograms[0] settings
    histograms[0].SetMarkerColor(4)
    histograms[0].SetLineColor(4)
    histograms[0].SetLineWidth(1)

    # Y axis histograms[0] plot settings
    histograms[0].GetYaxis().SetTitleSize(20)
    histograms[0].GetYaxis().SetTitleFont(43)
    histograms[0].GetYaxis().SetTitleOffset(1.55)

    #histograms[0].Scale(1./histograms[0].GetEntries())
    if histograms[0].ClassName() == "TH1F":
        histograms[0].Draw(
            "SAME HIST")  # Draw histograms[1] on top of histograms[0]
    else:
        histograms[0].Draw(
            "SAME APE")  # Draw histograms[1] on top of histograms[0]
        #multiGraph.Add(histograms[0])

    if getattr(cfg, "xRange", None) is not None:
        histograms[0].GetXaxis().SetRangeUser(cfg.xRange[0], cfg.xRange[1])
        gPad.RedrawAxis()

    if getattr(cfg, "xAxisLabel", None) is not None:
        histograms[0].GetXaxis().SetTitle(cfg.xAxisLabel)
        gPad.RedrawAxis()

    if getattr(cfg, "yAxisLabel", None) is not None:
        histograms[0].GetYaxis().SetTitle(cfg.yAxisLabel)
        gPad.RedrawAxis()

    if getattr(cfg, "yRange", None) is not None:
        histograms[0].GetYaxis().SetRangeUser(cfg.yRange[0], cfg.yRange[1])
        gPad.RedrawAxis()
    else:
        maximumY *= 1.1
        histograms[0].GetYaxis().SetRangeUser(1e-6, maximumY)

    if getattr(cfg, "logY", False):
        canvas.SetLogy()

    # histograms[1] settings
    histograms[1].SetMarkerColor(2)
    histograms[1].SetLineColor(2)
    histograms[1].SetLineWidth(1)
    #histograms[1].Scale(1./histograms[1].GetEntries())
    if histograms[1].ClassName() == "TH1F":
        histograms[1].Draw(
            "SAME HIST")  # Draw histograms[1] on top of histograms[0]
    else:
        histograms[1].Draw(
            "SAME PE")  # Draw histograms[1] on top of histograms[0]
        #multiGraph.Add(histograms[1])

    #if multiGraph.GetListOfGraphs() != None:
    #  multiGraph.Draw("SAME PE")

    # Do not draw the Y axis label on the upper plot and redraw a small
    # axis instead, in order to avoid the first label (0) to be clipped.
    #histograms[0].GetYaxis().SetLabelSize(0.)
    #axis = TGaxis( 0, 20, 0, maximumY, 20, maximumY, 510,"")
    #axis.SetLabelFont(43) # Absolute font size in pixel (precision 3)
    #axis.SetLabelSize(15)
    #axis.Draw()

    # Adding a small text with the chi-squared

    chiSquared = 0
    if (histograms[0].ClassName() == "TGraph") or (histograms[0].ClassName()
                                                   == "TGraphErrors"):
        numberOfBins = histograms[0].GetN()
        numberOfDegreesOfFreedom = numberOfBins
    else:
        numberOfBins = histograms[0].GetNbinsX()
        numberOfDegreesOfFreedom = numberOfBins

    for x in xrange(
            1, numberOfBins + 1
    ):  # numberOfBins contains last bin, numberOfBins+1 contains the overflow (latter excluded), underflow also excluded
        if (histograms[0].ClassName()
                == "TGraph") or (histograms[0].ClassName() == "TGraphErrors"):
            binContent0 = histograms[0].GetY()[x - 1]
        else:
            binContent0 = histograms[0].GetBinContent(x)
        if (histograms[1].ClassName()
                == "TGraph") or (histograms[1].ClassName() == "TGraphErrors"):
            binContent1 = histograms[1].GetY()[x - 1]
        else:
            binContent1 = histograms[1].GetBinContent(x)
        bin0ErrorSquared = binContent0
        bin1ErrorSquared = binContent1
        #bin1ErrorSquared = 0
        if (binContent0 == 0) and (binContent1 == 0):
            numberOfDegreesOfFreedom -= 1  #No data means one less degree of freedom
        else:
            binDifferenceSquared = (binContent0 - binContent1)**2
            chiSquaredTerm = binDifferenceSquared / (bin0ErrorSquared +
                                                     bin1ErrorSquared)
            chiSquared += chiSquaredTerm
            if chiSquaredTerm > chiSquaredWarningThreshold:
                if (histograms[0].ClassName()
                        == "TGraph") or (histograms[0].ClassName()
                                         == "TGraphErrors"):
                    print "Bin", x, "-", histograms[0].GetX()[
                        x - 1], "has a CS=", chiSquaredTerm
                else:
                    print "Bin", x, "-", histograms[0].GetBinCenter(
                        x), "has a CS=", chiSquaredTerm

    chiSquareLabel = TPaveText(0.7, 0.6, 0.9, 0.4)
    chiSquareLabel.AddText("#chi^{2}/ndf = " + str(chiSquared) + "/" +
                           str(numberOfDegreesOfFreedom) + " = " +
                           str(chiSquared / numberOfDegreesOfFreedom))
    chiSquareLabel.Draw()
    print "FINAL CS IS", format(
        chiSquared,
        ".2f") + "/" + str(numberOfDegreesOfFreedom) + " = " + format(
            chiSquared / numberOfDegreesOfFreedom, ".2f")
    legend.SetHeader(
        "#chi^{2}/ndf = " + format(chiSquared, ".2f") + "/" +
        str(numberOfDegreesOfFreedom) + " = " +
        format(chiSquared / numberOfDegreesOfFreedom, ".2f"), "C")
    legend.Draw()
    # lower plot will be in pad
    canvas.cd()  # Go back to the main canvas before defining pad2
    pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3)
    pad2.SetTopMargin(0)
    pad2.SetBottomMargin(0.2)
    pad2.SetGridx()  # vertical grid
    pad2.Draw()
    pad2.cd()  # pad2 becomes the current pad
    pad2.SetGridy()

    # Define the ratio plot
    ratioPlot = TGraphErrors(histograms[0])
    ratioPlot.SetName("ratioPlot")
    graph_histo0 = TGraphErrors(histograms[0])
    graph_histo1 = TGraphErrors(histograms[1])
    ratioPlot.SetLineColor(1)
    ratioPlot.SetMinimum(0.6)  # Define Y ..
    ratioPlot.SetMaximum(1.5)  # .. range
    #ratioPlot.Sumw2()
    #ratioPlot.SetStats(0)      # No statistics on lower plot

    #Dividing point by point

    for index in xrange(0, ratioPlot.GetN()):
        if graph_histo1.GetY()[index] == 0:
            ratioPlot.GetY()[index] = 0
            ratioPlot.GetEY()[index] = 0
        else:
            ratioPlot.GetY()[index] /= graph_histo1.GetY()[index]
            ratioPlot.GetEY()[index] = sqrt(
                ((graph_histo1.GetY()[index])**2 *
                 (graph_histo0.GetEY()[index])**2 +
                 (graph_histo0.GetY()[index])**2 *
                 (graph_histo1.GetEY()[index])**2) /
                (graph_histo1.GetY()[index])**4)

    ratioPlot.SetMarkerStyle(21)

    if getattr(cfg, "xRange", None) is not None:
        ratioPlot.GetXaxis().SetRangeUser(cfg.xRange[0], cfg.xRange[1])
        gPad.RedrawAxis()

    if getattr(cfg, "yRangeRatio", None) is not None:
        ratioPlot.GetYaxis().SetRangeUser(cfg.yRangeRatio[0],
                                          cfg.yRangeRatio[1])
        gPad.RedrawAxis()

    ratioPlot.Draw("APE")  # Draw the ratio plot

    line0 = TLine(ratioPlot.GetXaxis().GetXmin(), 1,
                  ratioPlot.GetXaxis().GetXmax(), 1)
    line0.SetLineColor(2)
    line0.SetLineWidth(2)
    line0.SetLineStyle(2)
    line0.Draw()

    # Ratio plot (ratioPlot) settings
    ratioPlot.SetTitle("")  # Remove the ratio title

    # Y axis ratio plot settings
    ratioPlot.GetYaxis().SetTitle("Ratio #frac{blue}{red}")
    ratioPlot.GetYaxis().SetNdivisions(505)
    ratioPlot.GetYaxis().SetTitleSize(20)
    ratioPlot.GetYaxis().SetTitleFont(43)
    ratioPlot.GetYaxis().SetTitleOffset(1.55)
    ratioPlot.GetYaxis().SetLabelFont(
        43)  # Absolute font size in pixel (precision 3)
    ratioPlot.GetYaxis().SetLabelSize(15)

    # X axis ratio plot settings
    ratioPlot.GetXaxis().SetTitleSize(20)
    ratioPlot.GetXaxis().SetTitleFont(43)
    ratioPlot.GetXaxis().SetTitleOffset(4.)
    ratioPlot.GetXaxis().SetLabelFont(
        43)  # Absolute font size in pixel (precision 3)
    ratioPlot.GetXaxis().SetLabelSize(15)

    xRangeBinning = getattr(cfg, "simplifiedRatioPlotXRangeBinning", None)
    if xRangeBinning is not None:
        simplifiedRatioPlot = TGraphErrors(len(xRangeBinning) - 1)
        simplifiedRatioPlot.SetName("simplifiedRatioPlot")
        ratioPlotIndex = 0

        for idx in xrange(0, simplifiedRatioPlot.GetN()):
            yAverage = 0.
            yMax = float("-inf")
            yMin = float("+inf")

            nPoints = 0.
            simplifiedRatioPlot.GetX()[idx] = (xRangeBinning[idx] +
                                               xRangeBinning[idx + 1]) / 2.
            simplifiedRatioPlot.GetEX()[idx] = (xRangeBinning[idx + 1] -
                                                xRangeBinning[idx]) / 2.

            while (ratioPlot.GetX()[ratioPlotIndex] < xRangeBinning[idx]):
                ratioPlotIndex += 1
            while ((ratioPlotIndex < ratioPlot.GetN()) and
                   (ratioPlot.GetX()[ratioPlotIndex] < xRangeBinning[idx + 1])
                   and
                   (ratioPlot.GetX()[ratioPlotIndex] >= xRangeBinning[idx])):
                yAverage += ratioPlot.GetY()[ratioPlotIndex]
                if (yMax < ratioPlot.GetY()[ratioPlotIndex] +
                        ratioPlot.GetEY()[ratioPlotIndex]):
                    yMax = ratioPlot.GetY()[ratioPlotIndex] + ratioPlot.GetEY(
                    )[ratioPlotIndex]
                if (yMin > ratioPlot.GetY()[ratioPlotIndex] -
                        ratioPlot.GetEY()[ratioPlotIndex]):
                    yMin = ratioPlot.GetY()[ratioPlotIndex] - ratioPlot.GetEY(
                    )[ratioPlotIndex]
                nPoints += 1.
                ratioPlotIndex += 1

            simplifiedRatioPlot.GetY()[idx] = yAverage / nPoints
            simplifiedRatioPlot.GetEY()[idx] = (yMax - yMin) / 2.

    saveFile = TFile(cfg.saveFileName, "RECREATE")
    saveFile.cd()
    canvas.Write()
    histograms[0].Write()
    histograms[1].Write()
    if multiGraph.GetListOfGraphs() != None:
        multiGraph.Write()
    ratioPlot.Write()
    if xRangeBinning is not None:
        simplifiedRatioPlot.Write()
    saveFile.Close()
    for tfile in tfiles:
        tfile.Close()
Example #10
0
def main():
    # usage description
    usage = "Example: ./scripts/plotLimits.py -M Asymptotic -l logs -f qq --massrange 1200 7000 100"

    # input parameters
    parser = ArgumentParser(
        description='Script that plots limits for specified mass points',
        epilog=usage)

    parser.add_argument("-M",
                        "--method",
                        dest="method",
                        required=True,
                        choices=[
                            'ProfileLikelihood', 'HybridNew', 'Asymptotic',
                            'MarkovChainMC', 'theta'
                        ],
                        help="Method to calculate upper limits",
                        metavar="METHOD")

    results_group = parser.add_mutually_exclusive_group(required=True)
    results_group.add_argument("-l",
                               "--logs_path",
                               dest="logs_path",
                               help="Path to log files",
                               metavar="LOGS_PATH")
    results_group.add_argument("-r",
                               "--results_file",
                               dest="results_file",
                               help="Path to a file containing results",
                               metavar="RESULTS_FILE")

    parser.add_argument("-f",
                        "--final_state",
                        dest="final_state",
                        required=True,
                        help="Final state (e.g. qq, qg, gg)",
                        metavar="FINAL_STATE")

    parser.add_argument(
        "--postfix",
        dest="postfix",
        default='',
        help="Postfix for the output plot name (default: %(default)s)")

    parser.add_argument(
        "--fileFormat",
        dest="fileFormat",
        default='pdf',
        help="Format of the output plot (default: %(default)s)")

    parser.add_argument("--extraText",
                        dest="extraText",
                        default='Simulation Preliminary',
                        help="Extra text on the plot (default: %(default)s)")

    parser.add_argument(
        "--lumi_sqrtS",
        dest="lumi_sqrtS",
        default='1 fb^{-1} (13 TeV)',
        help=
        "Integrated luminosity and center-of-mass energy (default: %(default)s)"
    )

    parser.add_argument("--printResults",
                        dest="printResults",
                        default=False,
                        action="store_true",
                        help="Print results to the screen")

    mass_group = parser.add_mutually_exclusive_group(required=True)
    mass_group.add_argument(
        "--mass",
        type=int,
        nargs='*',
        default=1000,
        help=
        "Mass can be specified as a single value or a whitespace separated list (default: %(default)i)"
    )
    mass_group.add_argument(
        "--massrange",
        type=int,
        nargs=3,
        help="Define a range of masses to be produced. Format: min max step",
        metavar=('MIN', 'MAX', 'STEP'))
    mass_group.add_argument("--masslist",
                            help="List containing mass information")

    args = parser.parse_args()

    # mass points for which resonance shapes will be produced
    input_masses = []

    if args.massrange != None:
        MIN, MAX, STEP = args.massrange
        input_masses = range(MIN, MAX + STEP, STEP)
    elif args.masslist != None:
        # A mass list was provided
        print "Will create mass list according to", args.masslist
        masslist = __import__(args.masslist.replace(".py", ""))
        input_masses = masslist.masses
    else:
        input_masses = args.mass
    # sort masses
    input_masses.sort()

    # arrays holding results
    masses = array('d')
    xs_obs_limits = array('d')
    xs_exp_limits = array('d')
    masses_exp = array('d')
    xs_exp_limits_1sigma = array('d')
    xs_exp_limits_1sigma_up = array('d')
    xs_exp_limits_2sigma = array('d')
    xs_exp_limits_2sigma_up = array('d')

    if args.logs_path != None:

        logs_path = os.path.join(os.getcwd(), args.logs_path)

        for mass in input_masses:

            print ">> Reading results for %s resonance with m = %i GeV..." % (
                args.final_state, int(mass))

            masses.append(mass)
            if args.method == 'Asymptotic': masses_exp.append(mass)

            logName = 'limits_%s_%s_m%i.log' % (args.method, args.final_state,
                                                int(mass))

            if args.method == 'theta': logName = logName.replace('limits_', '')

            log_file = open(os.path.join(logs_path, logName), 'r')

            foundMethod = False

            # read the log file
            for line in log_file:
                if args.method == 'Asymptotic':
                    if re.search("^Observed Limit: r", line):
                        xs_obs_limits.append(float(line.split()[-1]))
                    if re.search("^Expected 50.0%: r", line):
                        xs_exp_limits.append(float(line.split()[-1]))
                    if re.search("^Expected 16.0%: r", line):
                        xs_exp_limits_1sigma.append(float(line.split()[-1]))
                    if re.search("^Expected 84.0%: r", line):
                        xs_exp_limits_1sigma_up.append(float(line.split()[-1]))
                    if re.search("^Expected  2.5%: r", line):
                        xs_exp_limits_2sigma.append(float(line.split()[-1]))
                    if re.search("^Expected 97.5%: r", line):
                        xs_exp_limits_2sigma_up.append(float(line.split()[-1]))
                elif args.method == 'theta':
                    if re.search('^# x; y; yerror', line):
                        foundMethod = True
                    if line.split()[0] == '0' and foundMethod:
                        xs_obs_limits.append(float(line.split()[1]))
                else:
                    if re.search(' -- ' + args.method, line):
                        foundMethod = True
                    if re.search("^Limit: r", line) and foundMethod:
                        xs_obs_limits.append(float(line.split()[3]))

            if len(masses) != len(xs_obs_limits):
                print "** ERROR: ** Could not find observed limit for m =", int(
                    mass), "GeV. Aborting."
                sys.exit(1)

            if args.method == 'Asymptotic':
                if len(masses) != len(xs_exp_limits):
                    print "** ERROR: ** Could not find expected limit for m =", int(
                        mass), "GeV. Aborting."
                    sys.exit(1)

                if len(masses) != len(xs_exp_limits_1sigma):
                    print "** ERROR: ** Could not find expected 1 sigma down limit for m =", int(
                        mass), "GeV. Aborting."
                    sys.exit(1)

                if len(masses) != len(xs_exp_limits_1sigma_up):
                    print "** ERROR: ** Could not find expected 1 sigma up limit for m =", int(
                        mass), "GeV. Aborting."
                    sys.exit(1)

                if len(masses) != len(xs_exp_limits_2sigma):
                    print "** ERROR: ** Could not find expected 2 sigma down limit for m =", int(
                        mass), "GeV. Aborting."
                    sys.exit(1)

                if len(masses) != len(xs_exp_limits_2sigma_up):
                    print "** ERROR: ** Could not find expected 2 sigma up limit for m =", int(
                        mass), "GeV. Aborting."
                    sys.exit(1)
        if args.method == 'Asymptotic':
            # complete the expected limit arrays
            for i in range(0, len(masses)):
                masses_exp.append(masses[len(masses) - i - 1])
                xs_exp_limits_1sigma.append(
                    xs_exp_limits_1sigma_up[len(masses) - i - 1])
                xs_exp_limits_2sigma.append(
                    xs_exp_limits_2sigma_up[len(masses) - i - 1])
    else:
        print ">> Importing results..."

        sys.path.insert(0, os.path.dirname(args.results_file))

        results = __import__(
            os.path.basename(args.results_file).replace(".py", ""))

        all_masses = np.array(results.masses)
        all_masses_exp = np.array(results.masses_exp)
        indices = []
        indices_exp = []

        # search for indices of input_masses
        for mass in input_masses:
            where = np.where(all_masses == mass)[0]
            if len(where) == 0:
                print "** WARNING: ** Cannot find results for m =", int(
                    mass
                ), "GeV in the provided results file. Skipping this mass point."
            indices.extend(where)
            if len(all_masses_exp) > 0:
                where = np.where(all_masses_exp == mass)[0]
                if len(where) == 0:
                    print "** WARNING: ** Cannot find results for m =", int(
                        mass
                    ), "GeV in the provided results file. Skipping this mass point."
                indices_exp.extend(where)

        # sort indices
        indices.sort()
        indices_exp.sort()

        for i in indices:
            masses.append(results.masses[i])
            xs_obs_limits.append(results.xs_obs_limits[i])
            if len(all_masses_exp) > 0:
                xs_exp_limits.append(results.xs_exp_limits[i])
        for i in indices_exp:
            masses_exp.append(results.masses_exp[i])
            xs_exp_limits_1sigma.append(results.xs_exp_limits_1sigma[i])
            xs_exp_limits_2sigma.append(results.xs_exp_limits_2sigma[i])

    if args.printResults:
        print "masses =", masses.tolist()
        print "xs_obs_limits =", xs_obs_limits.tolist()
        print "xs_exp_limits =", xs_exp_limits.tolist()
        print ""
        print "masses_exp =", masses_exp.tolist()
        print "xs_exp_limits_1sigma =", xs_exp_limits_1sigma.tolist()
        print "xs_exp_limits_2sigma =", xs_exp_limits_2sigma.tolist()

    # import ROOT stuff
    from ROOT import kTRUE, kFALSE, gROOT, gStyle, gPad, TGraph, TCanvas, TLegend
    from ROOT import kGreen, kYellow, kWhite

    gROOT.SetBatch(kTRUE)
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)
    gStyle.SetTitleFont(42, "XYZ")
    gStyle.SetTitleSize(0.06, "XYZ")
    gStyle.SetLabelFont(42, "XYZ")
    gStyle.SetLabelSize(0.05, "XYZ")
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetFrameBorderMode(0)
    gStyle.SetCanvasColor(kWhite)
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)
    gStyle.SetPadLeftMargin(0.15)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadBottomMargin(0.15)
    gROOT.ForceStyle()

    # theory curves: gg
    massesS8 = array('d', [
        1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0,
        1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0,
        2800.0, 2900.0, 3000.0, 3100.0, 3200.0, 3300.0, 3400.0, 3500.0, 3600.0,
        3700.0, 3800.0, 3900.0, 4000.0, 4100.0, 4200.0, 4300.0, 4400.0, 4500.0,
        4600.0, 4700.0, 4800.0, 4900.0, 5000.0, 5100.0, 5200.0, 5300.0, 5400.0,
        5500.0, 5600.0, 5700.0, 5800.0, 5900.0, 6000.0
    ])
    xsS8 = array('d', [
        5.46E+02, 3.12E+02, 1.85E+02, 1.12E+02, 7.19E+01, 4.59E+01, 3.02E+01,
        2.01E+01, 1.37E+01, 9.46E+00, 6.55E+00, 4.64E+00, 3.27E+00, 2.36E+00,
        1.70E+00, 1.24E+00, 9.11E-01, 6.69E-01, 4.97E-01, 3.71E-01, 2.78E-01,
        2.07E-01, 1.55E-01, 1.19E-01, 9.26E-02, 7.08E-02, 5.43E-02, 4.15E-02,
        3.22E-02, 2.50E-02, 1.92E-02, 1.51E-02, 1.19E-02, 9.25E-03, 7.35E-03,
        5.86E-03, 4.53E-03, 3.66E-03, 2.91E-03, 2.33E-03, 1.86E-03, 1.45E-03,
        1.12E-03, 8.75E-04, 6.90E-04, 5.55E-04, 4.47E-04, 3.63E-04, 2.92E-04,
        2.37E-04, 1.97E-04
    ])

    graph_xsS8 = TGraph(len(massesS8), massesS8, xsS8)
    graph_xsS8.SetLineWidth(3)
    graph_xsS8.SetLineStyle(8)
    graph_xsS8.SetLineColor(6)

    # theory curves: qg
    massesString = array('d', [
        1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0,
        1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0,
        2800.0, 2900.0, 3000.0, 3100.0, 3200.0, 3300.0, 3400.0, 3500.0, 3600.0,
        3700.0, 3800.0, 3900.0, 4000.0, 4100.0, 4200.0, 4300.0, 4400.0, 4500.0,
        4600.0, 4700.0, 4800.0, 4900.0, 5000.0, 5100.0, 5200.0, 5300.0, 5400.0,
        5500.0, 5600.0, 5700.0, 5800.0, 5900.0, 6000.0, 6100.0, 6200.0, 6300.0,
        6400.0, 6500.0, 6600.0, 6700.0, 6800.0, 6900.0, 7000.0, 7100.0, 7200.0,
        7300.0, 7400.0, 7500.0, 7600.0, 7700.0, 7800.0, 7900.0, 8000.0, 8100.0,
        8200.0, 8300.0, 8400.0, 8500.0, 8600.0, 8700.0, 8800.0, 8900.0, 9000.0,
        9100., 9200., 9300., 9400., 9500., 9600., 9700., 9800., 9900., 10000.
    ])
    xsString = array('d', [
        8316.184311558545, 5312.93137758767, 3435.0309937336524,
        2304.4139502741305, 1569.8115447896687, 1090.9516635659693,
        770.901859690924, 551.9206062572061, 399.69535383507633,
        293.77957451762086, 218.15126842827823, 162.87634729465125,
        123.17685479653694, 93.63530805932386, 71.53697229809124,
        55.37491301647483, 42.75271508357369, 33.36378355470234,
        26.06619302090876, 20.311817606835643, 16.1180931789545,
        12.768644973921226, 10.142660425967444, 8.057990848043234,
        6.400465846290908, 5.115134438331436, 4.132099789492928,
        3.3193854239538734, 2.6581204529344302, 2.157554604919995,
        1.7505176068913348, 1.4049155245498584, 1.140055677916783,
        0.9253251132104159, 0.7522038169131606, 0.6119747371392215,
        0.49612321727328523, 0.40492020959456737, 0.33091999402250655,
        0.27017917021492555, 0.2201693919322846, 0.17830700070267996,
        0.14564253802358157, 0.11940534430331146, 0.09694948234356839,
        0.0793065371847468, 0.06446186373361917, 0.05282660618352478,
        0.0428516302310620888, 0.0348997638039910363, 0.0283334766442618227,
        0.0231416918363592127, 0.0187417921340763783, 0.0153501307395115115,
        0.0124396534127133717, 0.0100542205744949455, 0.0081744954858627415,
        0.0066338099362915941, 0.0053365711503318145, 0.00430912459914657443,
        0.00346381039244064343, 0.00278602671711227174, 0.00225154342228859257,
        0.0018082930150063248, 0.00143929440338502119, 0.0011581373956044489,
        0.00091869589873893118, 0.00073410823691329855, 0.00058669382997948734,
        0.0004661568745858897, 0.000368716655469570365,
        0.000293168485206959169, 0.000230224535021638668,
        0.000182317101888465142, 0.000143263359883433282,
        0.000112630538527214965, 0.000088189175598406759,
        0.000068708474367442343, 0.000053931726669273556,
        0.0000416417855733682702, 0.0000326529676755488658,
        0.0000254365480426201587, 0.0000198410151166864761,
        0.0000154034425617473576, 0.0000119095554601641413,
        9.2537574320108232e-6, 7.2155417437856749e-6, 5.6130924422251982e-6,
        4.36634755605624901e-6, 3.39717456406994868e-6, 2.6766018046173896e-6
    ])

    massesQstar = array('d', [
        1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0,
        1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0,
        2800.0, 2900.0, 3000.0, 3100.0, 3200.0, 3300.0, 3400.0, 3500.0, 3600.0,
        3700.0, 3800.0, 3900.0, 4000.0, 4100.0, 4200.0, 4300.0, 4400.0, 4500.0,
        4600.0, 4700.0, 4800.0, 4900.0, 5000.0, 5100.0, 5200.0, 5300.0, 5400.0,
        5500.0, 5600.0, 5700.0, 5800.0, 5900.0, 6000.0, 6100.0, 6200.0, 6300.0,
        6400.0, 6500.0, 6600.0, 6700.0, 6800.0, 6900.0, 7000.0, 7100.0, 7200.0,
        7300.0, 7400.0, 7500.0, 7600.0, 7700.0, 7800.0, 7900.0, 8000.0, 8100.0,
        8200.0, 8300.0, 8400.0, 8500.0, 8600.0, 8700.0, 8800.0, 8900.0, 9000.0
    ])
    xsQstar = array('d', [
        0.4101E+03, 0.2620E+03, 0.1721E+03, 0.1157E+03, 0.7934E+02, 0.5540E+02,
        0.3928E+02, 0.2823E+02, 0.2054E+02, 0.1510E+02, 0.1121E+02, 0.8390E+01,
        0.6328E+01, 0.4807E+01, 0.3674E+01, 0.2824E+01, 0.2182E+01, 0.1694E+01,
        0.1320E+01, 0.1033E+01, 0.8116E+00, 0.6395E+00, 0.5054E+00, 0.4006E+00,
        0.3182E+00, 0.2534E+00, 0.2022E+00, 0.1616E+00, 0.1294E+00, 0.1038E+00,
        0.8333E-01, 0.6700E-01, 0.5392E-01, 0.4344E-01, 0.3503E-01, 0.2827E-01,
        0.2283E-01, 0.1844E-01, 0.1490E-01, 0.1205E-01, 0.9743E-02, 0.7880E-02,
        0.6373E-02, 0.5155E-02, 0.4169E-02, 0.3371E-02, 0.2725E-02, 0.2202E-02,
        0.1779E-02, 0.1437E-02, 0.1159E-02, 0.9353E-03, 0.7541E-03, 0.6076E-03,
        0.4891E-03, 0.3935E-03, 0.3164E-03, 0.2541E-03, 0.2039E-03, 0.1635E-03,
        0.1310E-03, 0.1049E-03, 0.8385E-04, 0.6699E-04, 0.5347E-04, 0.4264E-04,
        0.3397E-04, 0.2704E-04, 0.2151E-04, 0.1709E-04, 0.1357E-04, 0.1077E-04,
        0.8544E-05, 0.6773E-05, 0.5367E-05, 0.4251E-05, 0.3367E-05, 0.2666E-05,
        0.2112E-05, 0.1673E-05, 0.1326E-05
    ])

    graph_xsString = TGraph(len(massesString), massesString, xsString)
    graph_xsString.SetLineWidth(3)
    graph_xsString.SetLineStyle(8)
    graph_xsString.SetLineColor(9)

    graph_xsQstar = TGraph(len(massesQstar), massesQstar, xsQstar)
    graph_xsQstar.SetLineWidth(3)
    graph_xsQstar.SetLineStyle(2)
    graph_xsQstar.SetLineColor(1)

    # theory curves: qq
    massesTh = array('d', [
        1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0,
        1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0,
        2800.0, 2900.0, 3000.0, 3100.0, 3200.0, 3300.0, 3400.0, 3500.0, 3600.0,
        3700.0, 3800.0, 3900.0, 4000.0, 4100.0, 4200.0, 4300.0, 4400.0, 4500.0,
        4600.0, 4700.0, 4800.0, 4900.0, 5000.0, 5100.0, 5200.0, 5300.0, 5400.0,
        5500.0, 5600.0, 5700.0, 5800.0, 5900.0, 6000.0, 6100.0, 6200.0, 6300.0,
        6400.0, 6500.0, 6600.0, 6700.0, 6800.0, 6900.0, 7000.0, 7100.0, 7200.0,
        7300.0, 7400.0, 7500.0, 7600.0, 7700.0, 7800.0, 7900.0, 8000.0, 8100.0,
        8200.0, 8300.0, 8400.0, 8500.0, 8600.0, 8700.0, 8800.0, 8900.0, 9000.0
    ])

    xsAxi = array('d', [
        0.1849E+03, 0.1236E+03, 0.8473E+02, 0.5937E+02, 0.4235E+02, 0.3069E+02,
        0.2257E+02, 0.1680E+02, 0.1263E+02, 0.9577E+01, 0.7317E+01, 0.5641E+01,
        0.4374E+01, 0.3411E+01, 0.2672E+01, 0.2103E+01, 0.1658E+01, 0.1312E+01,
        0.1041E+01, 0.8284E+00, 0.6610E+00, 0.5294E+00, 0.4250E+00, 0.3417E+00,
        0.2752E+00, 0.2220E+00, 0.1792E+00, 0.1449E+00, 0.1172E+00, 0.9487E-01,
        0.7686E-01, 0.6219E-01, 0.5033E-01, 0.4074E-01, 0.3298E-01, 0.2671E-01,
        0.2165E-01, 0.1755E-01, 0.1422E-01, 0.1152E-01, 0.9322E-02, 0.7539E-02,
        0.6092E-02, 0.4917E-02, 0.3965E-02, 0.3193E-02, 0.2568E-02, 0.2062E-02,
        0.1653E-02, 0.1323E-02, 0.1057E-02, 0.8442E-03, 0.6728E-03, 0.5349E-03,
        0.4242E-03, 0.3357E-03, 0.2644E-03, 0.2077E-03, 0.1627E-03, 0.1271E-03,
        0.9891E-04, 0.7686E-04, 0.5951E-04, 0.4592E-04, 0.3530E-04, 0.2704E-04,
        0.2059E-04, 0.1562E-04, 0.1180E-04, 0.8882E-05, 0.6657E-05, 0.4968E-05,
        0.3693E-05, 0.2734E-05, 0.2016E-05, 0.1481E-05, 0.1084E-05, 0.7903E-06,
        0.5744E-06, 0.4160E-06, 0.3007E-06
    ])
    xsDiquark = array('d', [
        0.5824E+02, 0.4250E+02, 0.3172E+02, 0.2411E+02, 0.1862E+02, 0.1457E+02,
        0.1153E+02, 0.9211E+01, 0.7419E+01, 0.6019E+01, 0.4912E+01, 0.4031E+01,
        0.3323E+01, 0.2750E+01, 0.2284E+01, 0.1903E+01, 0.1590E+01, 0.1331E+01,
        0.1117E+01, 0.9386E+00, 0.7900E+00, 0.6658E+00, 0.5618E+00, 0.4745E+00,
        0.4010E+00, 0.3391E+00, 0.2869E+00, 0.2428E+00, 0.2055E+00, 0.1740E+00,
        0.1473E+00, 0.1246E+00, 0.1055E+00, 0.8922E-01, 0.7544E-01, 0.6376E-01,
        0.5385E-01, 0.4546E-01, 0.3834E-01, 0.3231E-01, 0.2720E-01, 0.2288E-01,
        0.1922E-01, 0.1613E-01, 0.1352E-01, 0.1132E-01, 0.9463E-02, 0.7900E-02,
        0.6584E-02, 0.5479E-02, 0.4551E-02, 0.3774E-02, 0.3124E-02, 0.2581E-02,
        0.2128E-02, 0.1750E-02, 0.1437E-02, 0.1177E-02, 0.9612E-03, 0.7833E-03,
        0.6366E-03, 0.5160E-03, 0.4170E-03, 0.3360E-03, 0.2700E-03, 0.2162E-03,
        0.1725E-03, 0.1372E-03, 0.1087E-03, 0.8577E-04, 0.6742E-04, 0.5278E-04,
        0.4114E-04, 0.3192E-04, 0.2465E-04, 0.1894E-04, 0.1448E-04, 0.1101E-04,
        0.8322E-05, 0.6253E-05, 0.4670E-05
    ])
    xsWprime = array('d', [
        0.8811E+01, 0.6024E+01, 0.4216E+01, 0.3010E+01, 0.2185E+01, 0.1610E+01,
        0.1200E+01, 0.9043E+00, 0.6875E+00, 0.5271E+00, 0.4067E+00, 0.3158E+00,
        0.2464E+00, 0.1932E+00, 0.1521E+00, 0.1201E+00, 0.9512E-01, 0.7554E-01,
        0.6012E-01, 0.4792E-01, 0.3827E-01, 0.3059E-01, 0.2448E-01, 0.1960E-01,
        0.1571E-01, 0.1259E-01, 0.1009E-01, 0.8090E-02, 0.6483E-02, 0.5193E-02,
        0.4158E-02, 0.3327E-02, 0.2660E-02, 0.2125E-02, 0.1695E-02, 0.1351E-02,
        0.1075E-02, 0.8546E-03, 0.6781E-03, 0.5372E-03, 0.4248E-03, 0.3353E-03,
        0.2642E-03, 0.2077E-03, 0.1629E-03, 0.1275E-03, 0.9957E-04, 0.7757E-04,
        0.6027E-04, 0.4670E-04, 0.3610E-04, 0.2783E-04, 0.2140E-04, 0.1641E-04,
        0.1254E-04, 0.9561E-05, 0.7269E-05, 0.5510E-05, 0.4167E-05, 0.3143E-05,
        0.2364E-05, 0.1774E-05, 0.1329E-05, 0.9931E-06, 0.7411E-06, 0.5523E-06,
        0.4108E-06, 0.3055E-06, 0.2271E-06, 0.1687E-06, 0.1254E-06, 0.9327E-07,
        0.6945E-07, 0.5177E-07, 0.3863E-07, 0.2888E-07, 0.2162E-07, 0.1622E-07,
        0.1218E-07, 0.9156E-08, 0.6893E-08
    ])
    xsZprime = array('d', [
        0.5027E+01, 0.3398E+01, 0.2353E+01, 0.1663E+01, 0.1196E+01, 0.8729E+00,
        0.6450E+00, 0.4822E+00, 0.3638E+00, 0.2769E+00, 0.2123E+00, 0.1639E+00,
        0.1272E+00, 0.9933E-01, 0.7789E-01, 0.6134E-01, 0.4848E-01, 0.3845E-01,
        0.3059E-01, 0.2440E-01, 0.1952E-01, 0.1564E-01, 0.1256E-01, 0.1010E-01,
        0.8142E-02, 0.6570E-02, 0.5307E-02, 0.4292E-02, 0.3473E-02, 0.2813E-02,
        0.2280E-02, 0.1848E-02, 0.1499E-02, 0.1216E-02, 0.9864E-03, 0.8002E-03,
        0.6490E-03, 0.5262E-03, 0.4264E-03, 0.3453E-03, 0.2795E-03, 0.2260E-03,
        0.1826E-03, 0.1474E-03, 0.1188E-03, 0.9566E-04, 0.7690E-04, 0.6173E-04,
        0.4947E-04, 0.3957E-04, 0.3159E-04, 0.2516E-04, 0.2001E-04, 0.1587E-04,
        0.1255E-04, 0.9906E-05, 0.7795E-05, 0.6116E-05, 0.4785E-05, 0.3731E-05,
        0.2900E-05, 0.2247E-05, 0.1734E-05, 0.1334E-05, 0.1022E-05, 0.7804E-06,
        0.5932E-06, 0.4492E-06, 0.3388E-06, 0.2544E-06, 0.1903E-06, 0.1417E-06,
        0.1051E-06, 0.7764E-07, 0.5711E-07, 0.4186E-07, 0.3055E-07, 0.2223E-07,
        0.1612E-07, 0.1164E-07, 0.8394E-08
    ])

    graph_xsAxi = TGraph(len(massesTh), massesTh, xsAxi)
    graph_xsAxi.SetLineWidth(3)
    graph_xsAxi.SetLineStyle(3)
    graph_xsAxi.SetLineColor(63)

    graph_xsDiquark = TGraph(len(massesTh), massesTh, xsDiquark)
    graph_xsDiquark.SetLineWidth(3)
    graph_xsDiquark.SetLineStyle(9)
    graph_xsDiquark.SetLineColor(8)

    graph_xsWprime = TGraph(len(massesTh), massesTh, xsWprime)
    graph_xsWprime.SetLineWidth(3)
    graph_xsWprime.SetLineStyle(7)
    graph_xsWprime.SetLineColor(46)

    graph_xsZprime = TGraph(len(massesTh), massesTh, xsZprime)
    graph_xsZprime.SetLineWidth(3)
    graph_xsZprime.SetLineStyle(5)
    graph_xsZprime.SetLineColor(38)

    # limits
    graph_exp_2sigma = (TGraph(len(masses_exp), masses_exp,
                               xs_exp_limits_2sigma)
                        if len(xs_exp_limits_2sigma) > 0 else TGraph(0))
    graph_exp_2sigma.SetFillColor(kYellow)

    graph_exp_1sigma = (TGraph(len(masses_exp), masses_exp,
                               xs_exp_limits_1sigma)
                        if len(xs_exp_limits_2sigma) > 0 else TGraph(0))
    graph_exp_1sigma.SetFillColor(kGreen + 1)

    graph_exp = (TGraph(len(masses), masses, xs_exp_limits)
                 if len(xs_exp_limits_2sigma) > 0 else TGraph(0))
    #graph_exp.SetMarkerStyle(24)
    graph_exp.SetLineWidth(3)
    graph_exp.SetLineStyle(2)
    graph_exp.SetLineColor(4)

    graph_obs = TGraph(len(masses), masses, xs_obs_limits)
    graph_obs.SetMarkerStyle(20)
    graph_obs.SetLineWidth(3)
    #graph_obs.SetLineStyle(1)
    graph_obs.SetLineColor(1)

    c = TCanvas("c", "", 800, 800)
    c.cd()

    legend = TLegend(.60, .55, .90, .70)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.03)
    legend.SetHeader('95% CL upper limits')

    if len(xs_exp_limits_2sigma) > 0:
        graph_exp_2sigma.GetXaxis().SetTitle("%s resonance mass [GeV]" %
                                             (args.final_state))
        graph_exp_2sigma.GetYaxis().SetTitle(
            "#sigma #times #it{B} #times #it{A} [pb]")
        graph_exp_2sigma.GetYaxis().SetTitleOffset(1.1)
        graph_exp_2sigma.GetYaxis().SetRangeUser(1e-02, 1e+03)
        #graph_exp_2sigma.GetXaxis().SetNdivisions(1005)

        graph_exp_2sigma.Draw("AF")
        graph_exp_1sigma.Draw("F")
        graph_exp.Draw("L")
        graph_obs.Draw("LP")

        legend.AddEntry(graph_obs, "Observed", "lp")
        legend.AddEntry(graph_exp, "Expected", "lp")
        legend.AddEntry(graph_exp_1sigma, "#pm 1#sigma", "F")
        legend.AddEntry(graph_exp_2sigma, "#pm 2#sigma", "F")
    else:
        graph_obs.GetXaxis().SetTitle("%s resonance mass [GeV]" %
                                      (args.final_state))
        graph_obs.GetYaxis().SetTitle(
            "#sigma #times #it{B} #times #it{A} [pb]")
        graph_obs.GetYaxis().SetTitleOffset(1.1)
        graph_obs.GetYaxis().SetRangeUser(1e-02, 1e+03)
        #graph_obs.GetXaxis().SetNdivisions(1005)

        graph_obs.Draw("ALP")

        legend.AddEntry(graph_obs, "Observed", "lp")

    if args.final_state == 'gg':
        graph_xsS8.Draw("L")
    elif args.final_state == 'qg':
        graph_xsQstar.Draw("L")
        graph_xsString.Draw("L")
    elif args.final_state == 'qq':
        graph_xsAxi.Draw("L")
        graph_xsDiquark.Draw("L")
        graph_xsWprime.Draw("L")
        graph_xsZprime.Draw("L")

    legend.Draw()

    if args.final_state == 'gg':
        legendTh = TLegend(.60, .80, .90, .84)
        legendTh.SetBorderSize(0)
        legendTh.SetFillColor(0)
        legendTh.SetFillStyle(0)
        legendTh.SetTextFont(42)
        legendTh.SetTextSize(0.03)
        legendTh.AddEntry(graph_xsS8, "S8", "l")
        legendTh.Draw()
    elif args.final_state == 'qg':
        legendTh = TLegend(.60, .80, .90, .88)
        legendTh.SetBorderSize(0)
        legendTh.SetFillColor(0)
        legendTh.SetFillStyle(0)
        legendTh.SetTextFont(42)
        legendTh.SetTextSize(0.03)
        legendTh.AddEntry(graph_xsString, "String", "l")
        legendTh.AddEntry(graph_xsQstar, "Excited quark", "l")
        legendTh.Draw()
    elif args.final_state == 'qq':
        legendTh = TLegend(.60, .72, .90, .88)
        legendTh.SetBorderSize(0)
        legendTh.SetFillColor(0)
        legendTh.SetFillStyle(0)
        legendTh.SetTextFont(42)
        legendTh.SetTextSize(0.03)
        legendTh.AddEntry(graph_xsAxi, "Axigluon/coloron", "l")
        legendTh.AddEntry(graph_xsDiquark, "Scalar diquark", "l")
        legendTh.AddEntry(graph_xsWprime, "W' SSM", "l")
        legendTh.AddEntry(graph_xsZprime, "Z' SSM", "l")
        legendTh.Draw()

    # draw the lumi text on the canvas
    CMS_lumi.extraText = args.extraText
    CMS_lumi.lumi_sqrtS = args.lumi_sqrtS  # used with iPeriod = 0 (free form)
    iPos = 11
    iPeriod = 0

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)

    gPad.RedrawAxis()

    c.SetLogy()
    fileName = 'xs_limit_%s_%s.%s' % (args.method, args.final_state + (
        ('_' + args.postfix) if args.postfix != '' else ''),
                                      args.fileFormat.lower())
    c.SaveAs(fileName)
    print "Plot saved to '%s'" % (fileName)
Example #11
0
def cutflow(Region='SignalRegion',
            removeEvents=False,
            logY=True,
            normalise=True,
            singlePlots=False,
            drawOptions='HIST',
            weightedORraw='weighted'):
    # removeEvents=True
    PreSelectionName = 'PreSelection'
    # Region='HIGHSidebandRegion'
    PlotBGStack = False
    StackBG = False
    # singlePlots=False
    # normalise=True
    # logY=True
    # drawOptions='HIST TEXT90'

    channel = 'ZZ'

    channelTex = {
        'WPWP': 'W^{+}W^{+}',
        'WPWM': 'W^{+}W^{-}',
        'WMWM': 'W^{-}W^{-}',
        'WPZ': 'W^{+}Z',
        'WMZ': 'W^{-}Z',
        'ZZ': 'ZZ'
    }
    plotstyle = [(1, 1), (1, 2), (2, 1), (2, 2), (4, 1), (4, 2)]

    PreSelectionCuts = [
        ('nocuts', 'All'),
        ('common', 'CommonModules'),
        # ('corrections','JetCorrections'),
        # ('cleaner','JetCleaner'),
        ('AK4pfidfilter', 'AK4 PFID-Filter'),
        ('AK8pfidfilter', 'AK8 PFID-Filter'),
        ('AK8N2sel', 'N_{AK8} #geq 2'),
        ('invMAk8sel', 'M_{jj-AK8} > 1050 GeV'),
        ('detaAk8sel', '|#Delta#eta_{jj-AK8}|<1.3')
    ]

    SelectionCuts = [  #('preselection','PreSelection-check'),
        ('softdropAK8sel', '65 GeV <M_{SD}< 105 GeV'),
        ('tau21sel', '0 #leq #tau_{2}/#tau_{1}<0.35'),
        ('deltaR48', '#Delta R(AK4,leading AK8) > 1.3'),
        # ('VVRegion','VVRegion'),
        ('AK4N2sel', 'N_{AK4} #geq 2'),
        ('OpSignsel', '#eta_{1-AK4} #eta_{2-AK4} < 0'),
        ('detaAk4sel', '|#Delta#eta_{jj-AK4}| > 3.0'),
        ('invMAk4sel_1p0', 'M_{jj-AK4} > 1.0 TeV')
    ]

    Cuts = PreSelectionCuts + SelectionCuts
    # Cuts=SelectionCuts

    QCDColor = rt.kAzure + 7
    WJetsColor = rt.kRed - 4
    ZJetsColor = rt.kOrange - 2
    path = '/nfs/dust/cms/user/albrechs/UHH2_Output/'

    datasets = [  #(filename, Name for Legend, Linestyle, Color)
        ('MC.MC_aQGC_%sjj_hadronic.root' % channel, channelTex[channel], 1, 28
         )  #,
        # ('MC.MC_QCD.root','QCD',1,QCDColor),
        # ('MC.MC_WJetsToQQ_HT600ToInf.root','W+JetsToQQ',1,WJetsColor),
        # ('MC.MC_ZJetsToQQ_HT600ToInf.root','Z+JetsToQQ',1,ZJetsColor),
        # ('Data.DATA.root','Data',1,1)
    ]

    gROOT.ProcessLine("gErrorIgnoreLevel = 2001;")
    PreSelectionFiles = []
    SelectionFiles = []

    if removeEvents:
        PreSelectionName = PreSelectionName + 'RmEvent'
        Region = Region + 'RmEvent'

    for dataset in datasets:
        PreSelectionFiles.append(
            TFile(path + PreSelectionName +
                  "/uhh2.AnalysisModuleRunner.%s" % dataset[0]))
        # SelectionFiles.append(TFile(path+Region+'/backup/'+"/uhh2.AnalysisModuleRunner.%s"%dataset[0]))
        SelectionFiles.append(
            TFile(path + Region +
                  "/uhh2.AnalysisModuleRunner.%s" % dataset[0]))
    gROOT.ProcessLine("gErrorIgnoreLevel = 0;")

    yTitle = 'NEvents_%s' % weightedORraw
    if (normalise):
        yTitle = yTitle + '/N_%s' % Cuts[0][1]

    canv = TCanvas('cutflow_canvas', 'cutflow_canvas', 1000, 500)
    if (not singlePlots):
        legend = TLegend(0.7, 0.7, 0.9, 0.95)
        legend.SetFillStyle(0)
        legend.SetTextSize(0.02)
        legend.SetMargin(0.4)

    NCuts = len(Cuts)
    # NMETFilter=0
    # if 'common' in Cuts[:][0]:
    #     NMETFilter=PreSelectionFiles[0].Get('cf_metfilters').GetNbinsX()
    #     for i in range(1,PreSelectionFiles[0].Get('cf_metfilters').GetNbinsX()):
    #         Cuts.insert(Cuts.index(('common','CommonModules')),(PreSelectionFiles[0].Get('cf_metfilters').GetXaxis().GetBinLabel(i),PreSelectionFiles[0].Get('cf_metfilters').GetXaxis().GetBinLabel(i)))
    #     NCuts=NCuts+NMETFilter
    print('Plotting Cutflow of', NCuts, 'Cuts.')
    # for dataset in datasets:
    BGStack = THStack('MCBackground', 'MCBackground')

    TotalMinimum = 10**10
    NBG = 0
    for l in range(len(datasets)):
        print('checking', datasets[l][1])
        if normalise:
            if ((len(Cuts) == len(PreSelectionCuts)) or
                (len(Cuts) == (len(PreSelectionCuts) + len(SelectionCuts)))):
                Norm = PreSelectionFiles[l].Get(Cuts[0][0] + '/NEvents_%s' %
                                                weightedORraw).GetBinContent(1)
            else:
                Norm = SelectionFiles[l].Get(Cuts[0][0] + '/NEvents_%s' %
                                             weightedORraw).GetBinContent(1)
        else:
            Norm = 1
        if (len(Cuts) > len(PreSelectionCuts)):
            CurrentMinimum = SelectionFiles[l].Get(
                SelectionCuts[-1][0] +
                '/NEvents_%s' % weightedORraw).GetBinContent(1) / Norm
        else:
            CurrentMinimum = PreSelectionFiles[l].Get(
                PreSelectionCuts[-1][0] +
                '/NEvents_%s' % weightedORraw).GetBinContent(1) / Norm
        print(CurrentMinimum, TotalMinimum)

        if (CurrentMinimum < TotalMinimum):
            print('setting ', datasets[l][1], 'as new minimum')
            TotalMinimum = CurrentMinimum
        if (datasets[l][1] == 'QCD' or datasets[l][1] == 'W+JetsToQQ'
                or datasets[l][1] == 'Z+JetsToQQ'):
            # NBG= NBG + PreSelectionFiles[l].Get(Cuts[0][0]+'/NEvents_%s'%weightedORraw).GetBinContent(1)
            NBG = NBG + Norm
    cutflows = []
    for i in range(len(datasets)):
        if (singlePlots):
            legend = TLegend(0.75, 0.6, 1, 0.9)
            legend.SetFillStyle(0)
            legend.SetTextSize(0.02)
            legend.SetMargin(0.4)

        print('Drawing', datasets[i][1])
        currentCutflow = TH1F(datasets[i][1], datasets[i][1], NCuts, 0, NCuts)
        cutflows.append(currentCutflow)
        #filling the current cutflow (with NEvents_weighted or NEvents_raw)
        if (normalise):
            if (StackBG and
                (datasets[i][1] == 'QCD' or datasets[i][1] == 'W+JetsToQQ'
                 or datasets[i][1] == 'Z+JetsToQQ')):
                NAll = NBG
            else:
                if ((len(Cuts) == len(PreSelectionCuts))
                        or (len(Cuts)
                            == (len(PreSelectionCuts) + len(SelectionCuts)))):
                    NAll = PreSelectionFiles[i].Get(
                        PreSelectionCuts[0][0] +
                        '/NEvents_%s' % weightedORraw).GetBinContent(1)
                else:
                    NAll = SelectionFiles[i].Get(
                        SelectionCuts[0][0] +
                        '/NEvents_%s' % weightedORraw).GetBinContent(1)

        else:
            NAll = 1
        for j in range(NCuts):
            cut = Cuts[j]
            if ((len(Cuts) == len(PreSelectionCuts)) or
                (len(Cuts) == (len(PreSelectionCuts) + len(SelectionCuts)))
                    and j < len(PreSelectionCuts)):
                NEvents = PreSelectionFiles[i].Get(
                    cut[0] + '/NEvents_%s' % weightedORraw).GetBinContent(1)
            else:
                NEvents = SelectionFiles[i].Get(cut[0] + '/NEvents_%s' %
                                                weightedORraw).GetBinContent(1)
                # NEvents=NAll
            currentCutflow.GetXaxis().SetBinLabel(j + 1, cut[1])
            currentCutflow.Fill(j + 0.5, NEvents / NAll)
        #cosmectics for and draw current cutflow
        currentCutflow.SetLineColor(datasets[i][3])
        currentCutflow.SetMarkerSize(1.4)
        currentCutflow.GetYaxis().SetTitle(yTitle)
        HistMax = currentCutflow.GetMaximum()
        if (logY):
            if (singlePlots):
                MAX = float(10**(magnitude(HistMax) + 3))
                MIN = float(10**(magnitude(currentCutflow.GetMinimum()) - 1))
            else:
                MAX = float(10**(magnitude(HistMax) + 2))
                MIN = float(10**(magnitude(TotalMinimum) - 1))

            MIN += float(10**(magnitude(MIN)))
        else:
            MAX = 1.1 * HistMax
            MIN = 0.
        currentCutflow.GetYaxis().SetRangeUser(MIN, MAX)
        print('RangeUser=(', MIN, ',', MAX, ')')
        print('drawOptions:', drawOptions)
        if (datasets[i][1] == 'Data'):
            # legend.AddEntry(currentCutflow,datasets[i][1],'lep')
            # currentCutflow.SetMarkerStyle(8)
            # currentCutflow.Draw(drawOptions+'HP')
            legend.AddEntry(currentCutflow, datasets[i][1], 'l')
            currentCutflow.Draw(drawOptions)
            if (not singlePlots and ('SAME' not in drawOptions)):
                drawOptions = drawOptions + 'SAME'
        elif (StackBG
              and (datasets[i][1] == 'QCD' or datasets[i][1] == 'W+JetsToQQ'
                   or datasets[i][1] == 'Z+JetsToQQ')):
            legend.AddEntry(currentCutflow, datasets[i][1], 'f')
            currentCutflow.SetFillColor(datasets[i][3])
            BGStack.Add(currentCutflow, drawOptions)
            # currentCutflow.Draw(drawOptions)
            PlotBGStack = True
        else:
            legend.AddEntry(currentCutflow, datasets[i][1], 'l')
            currentCutflow.Draw(drawOptions)
            if (not singlePlots and ('SAME' not in drawOptions)):
                drawOptions = drawOptions + 'SAME'

        if (singlePlots):
            legend.Draw()
            if (logY):
                canv.SetLogy()
            # canv.SetGrid()
            canv.SetTicks()
            gPad.RedrawAxis()
            canv.Print('cutflows/' + Region + '_cutflow_%s_%s.eps' %
                       (datasets[i][1], weightedORraw))
    if (not singlePlots):
        if (PlotBGStack):
            BGStack.Draw(drawOptions)
        legend.Draw()
        if (logY):
            canv.SetLogy()
        # canv.SetGrid()
        canv.SetTicks()
        gPad.RedrawAxis()
        canv.Print('cutflows/' + Region + '_cutflow_%s.eps' % weightedORraw)
def coverlay(hists,
             xtitle,
             ytitle,
             name,
             runtype,
             tlabel,
             xlabel,
             xlabel_eta,
             sellabel,
             comparePerReleaseSuffix="",
             norm="",
             ndim=1):

    gStyle.SetOptStat(111110)
    c = TCanvas()
    if ndim == 1:
        c.SetRightMargin(0.10)
    elif ndim == 2:
        c.SetRightMargin(0.15)
    c.SetLeftMargin(0.12)
    c.SetBottomMargin(0.10)
    # Upper plot will be in pad1
    # pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
    # pad1.SetBottomMargin(0.03)  # Upper and lower plot are joined
    # pad1.Draw()             # Draw the upper pad: pad1
    # pad1.cd()              # pad1 becomes the current pad
    # c.SetLogy(0)
    # if any(subname in name for subname in ['isoPt', 'outOfConePt', 'IsoRaw', 'deepTau']):
    #     c.SetLogy()
    if ndim == 1:
        c.SetLogy()
    if ndim == 2:
        c.SetLogz()

    ymax = max([hist.GetMaximum() for hist in hists])
    # leg = TLegend(0.65, 0.65, 0.85, 0.9)
    # configureLegend(leg, 1)

    hratios = []
    for i_hist, hist in enumerate(hists):

        hist.SetMaximum(ymax * 1.2)
        hist.SetMinimum(0.)
        # if c.GetLogy > 0:
        if c.GetLogy > 0:
            hist.SetMinimum(0.001)
        hist.GetXaxis().SetTitleSize(0.04)
        hist.GetXaxis().SetLabelSize(0.04)
        hist.GetYaxis().SetTitleSize(0.04)
        hist.GetYaxis().SetLabelSize(0.04)
        hist.GetXaxis().SetTitle(xtitle)
        hist.GetYaxis().SetTitle(ytitle)

        if i_hist == 0:
            if ndim == 1:
                hist.SetMarkerSize(0.)
                hist.Draw('h')
                # gPad.Update()
                hist.SetStats(1)
                # st = hist.GetListOfFunctions().FindObject("stats")
                # # st.SetOptStat(1110)
                # # st = c.GetPrimitive("stats")
                # # st.SetNDC()
                # st.SetX1NDC(0.7)
                # st.SetX2NDC(0.85)
            elif ndim == 2:
                hist.SetMarkerSize(1.2)
                min_bincontent = 0.005
                if norm == "abs":
                    gStyle.SetPaintTextFormat("g")
                else:
                    gStyle.SetPaintTextFormat("4.2f")
                    hist.SetMaximum(100)
                    hist.SetMinimum(0.0049)
                if norm == "global":
                    integral = hist.Integral(1, hist.GetNbinsX(), 1,
                                             hist.GetNbinsY())
                    for i in range(1, hist.GetNbinsX() + 1):
                        for j in range(1, hist.GetNbinsY() + 1):
                            bincontent = hist.GetBinContent(
                                i, j) / integral * 100 if integral > 0 else 0
                            bincontent = min_bincontent if (
                                bincontent > 0 and
                                bincontent < min_bincontent) else bincontent
                            hist.SetBinContent(i, j, bincontent)
                elif norm == "col":
                    for i in range(1, hist.GetNbinsX() + 1):
                        integral = hist.Integral(i, i, 1, hist.GetNbinsY())
                        for j in range(1, hist.GetNbinsY() + 1):
                            bincontent = hist.GetBinContent(
                                i, j) / integral * 100 if integral > 0 else 0
                            bincontent = min_bincontent if (
                                bincontent > 0 and
                                bincontent < min_bincontent) else bincontent
                            hist.SetBinContent(i, j, bincontent)
                elif norm == "row":
                    for j in range(1, hist.GetNbinsY() + 1):
                        integral = hist.Integral(1, hist.GetNbinsX(), j, j)
                        for i in range(1, hist.GetNbinsX() + 1):
                            bincontent = hist.GetBinContent(
                                i, j) / integral * 100 if integral > 0 else 0
                            bincontent = min_bincontent if (
                                bincontent > 0 and
                                bincontent < min_bincontent) else bincontent
                            hist.SetBinContent(i, j, bincontent)
                hist.Draw("COLZ TEXT")
                gPad.RedrawAxis()
        #     hist_TAR = hist.Clone()
        else:
            if ndim == 1:
                hist.Draw('hsame')
            elif ndim == 2:
                hist.Draw("TEXTCOLZsame")
        #     # ihr = hist.Clone()
        #     # ihr.Sumw2()
        #     #ihr.Divide(hists[0])
        #
        #     # ihr = hist_TAR.Clone()
        #     # ihr.Divide(hist)
        #     ihr = hist.Clone()
        #     ihr.Divide(hist_TAR)
        #
        #     ihr.SetStats(0)
        #     ihr.SetLineColor(hist.GetLineColor())
        #     ihr.SetMarkerColor(hist.GetMarkerColor())
        #     ihr.SetMarkerStyle(hist.GetMarkerStyle())
        #     hratios.append(ihr)
        #
        # leg.AddEntry(hist, hist.GetName(), "l")

    # leg.Draw()
    #
    # xshift = 0.0
    # yshift = ymax*1.4
    # if tlabel.find('QCD') != -1:
    #     # pad1.SetTopMargin(0.1)
    #     xshift = 0.0
    #     # yshift = ymax*1.45
    # if runtype.find('TTbarTau') != -1:
    #     xshift = 0.78
    tex2 = TLatex(0.95, 0.96, tlabel)
    tex2.SetNDC()
    tex2.SetTextAlign(32)
    tex2.SetTextFont(42)
    tex2.SetTextSize(0.043)
    tex2.Draw()

    seltex = TLatex(0.02, 0.96, sellabel)
    seltex.SetNDC()
    seltex.SetTextAlign(12)
    seltex.SetTextFont(42)
    seltex.SetTextSize(0.023)
    seltex.Draw()

    #
    # # lower plot will be in pad
    # c.cd()          # Go back to the main canvas before defining pad2
    # pad2 = TPad("pad2", "pad2", 0, 0.0, 1, 0.27)
    # pad2.SetTopMargin(0.03)
    # pad2.SetBottomMargin(0.35)
    # pad2.Draw()
    # pad2.cd()
    # for ii, hist in enumerate(hratios):
    #     hist.GetXaxis().SetTitle(xtitle)
    #     hist.GetXaxis().SetTitleOffset(0.83)
    #     hist.GetXaxis().SetNdivisions(507)
    #     hist.GetYaxis().SetTitle('ratio')
    #     hist.GetYaxis().SetNdivisions(503)
    #     hist.SetMinimum(0.75)
    #     hist.SetMaximum(1.25)
    #     hist.GetYaxis().SetTitleOffset(0.45)
    #     hist.GetYaxis().SetTitleSize(0.16)
    #     hist.GetYaxis().SetLabelSize(0.16)
    #     hist.GetXaxis().SetTitleSize(0.16)
    #     hist.GetXaxis().SetLabelSize(0.16)
    #     if ii == 0:
    #         hist.Draw('ep')
    #     else:
    #         hist.Draw('epsame')

    c.cd()  # Go back to the main canvas
    save(
        c,
        ('compare_' + runtype + comparePerReleaseSuffix +
         '/taumatching/hist_' + name + '_' + norm + 'norm_' + str(ndim) + 'D'))
    c = None
    gStyle.SetOptStat(0)
    def painter(self, h_data, h_mc_list):
        #print(type(h_mc_list[5]))
        k = 1
        while k < len(h_mc_list):
            h_sum_mc = h_mc_list[0].Clone()
            h_sum_mc.Add(h_mc_list[k])
            k+=1
        
        
            
            
        h_ratio = h_data.Clone()
        h_ratio.Divide(h_sum_mc)
        
        mcSumHistWithoutErrors = h_sum_mc.Clone()
        h_sum_mc.Sumw2()
        mcSumRatioHist = h_sum_mc.Clone()
        mcSumRatioHist.Divide(mcSumHistWithoutErrors)
        

        c3 = ROOT.TCanvas ("c3", "ph_et in",600,600)
        gStyle.SetOptStat(0)
        
        pad1 = ROOT.TPad("pad1","This is pad1",0.01,0.40,1,1.0)
        pad2 = ROOT.TPad("pad2","This is pad2",0.01,0.01,1,0.39)
        pad1.SetBorderSize(0)
        pad1.SetBottomMargin(0.0)
        pad1.Draw()
        pad2.SetBorderSize(0)
        pad2.SetTopMargin(0.)
        pad2.SetBottomMargin(0.40)
        pad2.Draw()
        pad1.cd(0)
        if 'lepmet_dphi' in h_mc_list[0].GetName():
            pad1.SetLogy()
            self.minYaxispad1 = 1
            
        pt =  ROOT.TPaveText(0.13,0.65,0.6,0.88,"NDC")
       
    #    pt.SetFillStyle(1)
        pt.SetFillColor(0)
        #pt.SetFillStyle(1)
        pt.SetTextAlign(12)
    #    pt.SetLineStyle(0)

        pt.AddText('#it{ATLAS} #bf{#bf{Work in Progress}}')
        pt.AddText('#bf{#bf{3.22fb^{-1}, #sqrt{S}=13 TeV}}')
        pt.AddText('#bf{#bf{SR}}')
        pt.AddText('#bf{#bf{2015}}')
        
        sizemclist = len(h_mc_list)
        
        for i in reversed(range(sizemclist)):
            h_mc_list[i].SetLineColor(36)
        
        
        h_data.SetLineColor(ROOT.kBlack)
        #h_data.SetMarkerSize(1.5)

        h_data.SetLineWidth(2)
        h_data.SetMarkerStyle(15)
        
        for i in reversed(range(sizemclist)):
            h_mc_list[i].SetFillColor(7-i)
            
       

        h_data.GetYaxis().SetRangeUser(self.minYaxispad1,  self.maxYaxispad1)
        #self.h_data.GetXaxis().SetRangeUser(40, 140)
        h_data.SetLineWidth(2)
        ######################
        h_data.GetYaxis().SetTitle("#scale[2]{%s}"%self.SetTitleY)
        h_data.GetYaxis().SetLabelSize(0.05)
        #h_data.GetYaxis().SetTitleSize(0.09)
        h_data.GetYaxis().SetTitleOffset(1.53)
        
        h_data.SetTitle('')
        h_data.Draw('E0')
        
        for i in reversed(range(sizemclist)):
            h_mc_list[i].Draw('hist same')

        h_data.Draw("E0  same ")
        pt.Draw("'NDC' same")

        legend1 = ROOT.TLegend(0.70,0.88,0.52,0.7)
        legend1.SetLineColor(0)
        legend1.SetFillStyle(1)
        legend2 = ROOT.TLegend(0.88,0.88,0.70,0.7)
        legend2.SetLineColor(0)
        legend2.SetFillStyle(1)
        
        legend1.AddEntry( h_data ,"Data","lp")
        
        for i in reversed(range(int(sizemclist/2),sizemclist)):
            legend1.AddEntry( h_mc_list[i], str(h_mc_list[i].GetTitle()),"f")
        legend1.Draw()
        
        for i in reversed(range(0,int(sizemclist/2))):
            legend2.AddEntry( h_mc_list[i], str(h_mc_list[i].GetTitle()),"f")
        legend2.Draw()
        
        

        gr1 = ROOT.TGraph(2)
        gr1.SetPoint(0, -1, 1)
        gr1.SetPoint(1, 100, 1)
        gr1.SetLineStyle(7)

        gPad.RedrawAxis()
        c3.Update()

        mcSumRatioHist.SetFillColor(ROOT.kGreen -9)
        #mcSumRatioHist.SetLineColor(ROOT.kGreen -9)
        h_ratio.SetTitle('')

        pad2.cd(0)


        h_ratio.SetMarkerStyle(15)
        #h_ratio.SetMarkerSize(1.50)
        h_ratio.SetLineColor(ROOT.kBlack)
         
        #h_ratio.GetYaxis().SetLabelOffset(0.01) #сдвиг цифр
        
        #h_ratio.GetYaxis().SetLabelFont(2)
        h_ratio.GetXaxis().SetLabelSize(0.07)
        h_ratio.GetYaxis().SetTitle("#scale[2.4]{Data / Model  }")
        h_ratio.GetXaxis().SetTitle("#scale[2.4]{%s}"%self.SetTitleX)
        h_ratio.GetXaxis().SetLabelOffset(0.01)
        h_ratio.GetYaxis().SetTitleOffset(1.4)
        #####################################
        h_ratio.GetXaxis().SetTitleOffset(2.4)
        #h_ratio.GetXaxis().SetTitleSize(0.1)

       
       # h_ratio.GetXaxis().SetRangeUser(40, 140)
        h_ratio.SetLineWidth(2)
        h_ratio.Draw("E")
        mcSumRatioHist.Draw(' E2 same')
        h_ratio.Draw("E same")
        gr1.Draw('same')
        h_ratio.GetYaxis().SetRangeUser(self.minYaxispad2, self.maxYaxispad2)
        gPad.RedrawAxis()

        legend2.AddEntry( mcSumRatioHist,"Stat.Uncert.","f")

       # c3.cd(1)
       # legend1.Draw('same')


        pad1.Update()
        pad2.Update()
        c3.Update()
        c3.SaveAs('fff.pdf')
        c3.Draw()
        return c3
Example #14
0
 def setaxes(self, *args, **kwargs):
   """Make axis."""
   verbosity = LOG.getverbosity(self,kwargs)
   hists     = [ ]
   binning   = [ ]
   for arg in args[:]:
     if hasattr(arg,'GetXaxis'):
       hists.append(arg)
     elif isinstance(arg,Ratio):
       hists.append(arg.frame)
     elif isnumber(arg):
       binning.append(arg)
   if not hists:
     LOG.warning("Plot.setaxes: No objects (TH1, TGraph, ...) given in args %s to set axis..."%(args))
     return 0, 0, 100, 100
   frame         = hists[0]
   if len(binning)>=2:
     xmin, xmax  = binning[:2]
   else:
     xmin, xmax  = frame.GetXaxis().GetXmin(), frame.GetXaxis().GetXmax()
   nbins         = frame.GetXaxis().GetNbins()
   binwidth      = float(xmax-xmin)/nbins
   xmin          = kwargs.get('xmin',         xmin             )
   xmax          = kwargs.get('xmax',         xmax             )
   ymin          = kwargs.get('ymin',         None             )
   ymax          = kwargs.get('ymax',         None             )
   ratiorange    = kwargs.get('rrange',       None             )
   binlabels     = kwargs.get('binlabels',    None             )
   intbins       = kwargs.get('intbins',      True             ) # allow integer binning
   logx          = kwargs.get('logx',         False            )
   logy          = kwargs.get('logy',         False            )
   ymargin       = kwargs.get('ymargin',      None             ) or (1.3 if logy else 1.2) # margin between hist maximum and plot's top
   logyrange     = kwargs.get('logyrange',    None             ) or 3 # log(y) range from hist maximum to ymin
   negativey     = kwargs.get('negativey',    True             ) # allow negative y values
   xtitle        = kwargs.get('xtitle',       frame.GetTitle() )
   ytitle        = kwargs.get('ytitle',       None             )
   latex         = kwargs.get('latex',        True             ) # automatically format strings as LaTeX
   grid          = kwargs.get('grid',         False            )
   ycenter       = kwargs.get('center',       False            )
   nxdivisions   = kwargs.get('nxdiv',        510              )
   nydivisions   = kwargs.get('nydiv',        510              )
   main          = kwargs.get('main',         False            ) # main panel of ratio plot
   scale         = 600./min(gPad.GetWh()*gPad.GetHNDC(),gPad.GetWw()*gPad.GetWNDC())
   xtitlesize    = kwargs.get('xtitlesize',   _tsize           )*scale
   ytitlesize    = kwargs.get('ytitlesize',   _tsize           )*scale
   xlabelsize    = kwargs.get('xlabelsize',   _lsize           )*scale
   ylabelsize    = kwargs.get('ylabelsize',   _lsize           )*scale
   ytitleoffset  = kwargs.get('ytitleoffset', 1.0              )*1.27/scale
   xtitleoffset  = kwargs.get('xtitleoffset', 1.0              )*1.00
   xlabeloffset  = kwargs.get('xlabeloffset', -0.008*scale if logx else 0.007 )
   if main:
     xtitlesize  = 0.0
     xlabelsize  = 0.0
   if latex:
     xtitle      = makelatex(xtitle)
   LOG.verb("Plot.setaxes: Binning (%s,%.1f,%.1f)"%(nbins,xmin,xmax),verbosity,2)
   
   if ratiorange:
     ymin, ymax  = 1-ratiorange, 1+ratiorange
   if intbins and nbins<15 and int(xmin)==xmin and int(xmax)==xmax and binwidth==1:
     LOG.verb("Plot.setaxes: Setting integer binning for (%r,%s,%d,%d)!"%(xtitle,nbins,xmin,xmax),verbosity,1)
     binlabels   = [str(i) for i in range(int(xmin),int(xmax)+1)]
     xlabelsize   *= 1.6
     xlabeloffset *= 0.88*scale
   if logy:
     ylabelsize   *= 1.08
   if logx:
     xlabelsize   *= 1.08
   if binlabels:
     nxdivisions = 15
   
   # GET HIST MAX
   hmaxs = [ ]
   hmins = [ 0 ]
   if isinstance(frame,THStack):
     hmaxs.append(frame.GetMaximum())
     #frame = frame.GetStack().Last()
     for hist in hists:
       hmaxs.append(getTGraphYRange(hist)[1] if isinstance(hist,TGraph) else hist.GetMaximum())
   else:
     for hist in hists:
       ymin1, ymax1 = getTGraphYRange(hist) if isinstance(hist,TGraph) else hist.GetMinimum(), hist.GetMaximum()
       if negativey:
         hmins.append(ymin1)
       hmaxs.append(ymax1)
     if ymin==None:
       ymin = min(hmins)*(1.1 if ymin>0 else 0.9)
   hmax = max(hmaxs)
   hmin = min(hmins)
   
   # SET AXES RANGES
   if ymin==None:
     ymin = 0
   if logy:
     if not ymin or ymin<=0: # avoid zero or negative ymin for log plots
       ymin = 10**(magnitude(hmax)-logyrange) #max(0.1,10**(magnitude(ymax)-3))
       frame.SetMinimum(ymin)
       LOG.verb("Plot.setaxes: logy=%s, hmax=%6.6g, magnitude(hmax)=%s, logyrange=%s, ymin=%.6g"%(
                               logy,hmax,magnitude(hmax),logyrange,ymin),verbosity,2)
     if ymax==None:
       if hmax>ymin>0:
         span = abs(log10(hmax/ymin))*ymargin
         ymax = ymin*(10**span)
         LOG.verb("Plot.setaxes: log10(hmax/ymin)=%6.6g, span=%6.6g, ymax=%.6g"%(log10(hmax/ymin),span,ymax),verbosity,2)
       else:
         ymax = hmax*ymargin
     gPad.Update(); gPad.SetLogy()
   elif ymax==None:
     ymax = hmax*ymargin
   if logx:
     if not xmin: xmin = 0.1
     xmax *= 0.9999999999999
     gPad.Update(); gPad.SetLogx()
   if grid:
     gPad.SetGrid()
   #frame.GetXaxis().SetLimits(xmin,xmax)
   frame.GetXaxis().SetRangeUser(xmin,xmax)
   frame.SetMinimum(ymin)
   frame.SetMaximum(ymax)
   
   if ytitle==None:
     #ytitle = "Events"
     if "multiplicity" in xtitle.lower():
       ytitle = "Events"
     elif hmax<1.:
       ytitle = "A.U."
     else:
       for hist in hists:
         if isinstance(hist,TH1) and hist.GetName()!='hframe':
           hist0 = hist; break # default frame might have wrong binning
       else:
         hist0 = frame
       binwidth  = hist0.GetXaxis().GetBinWidth(0)
       binwidstr = ("%.3f"%binwidth).rstrip('0').rstrip('.')
       units     = re.findall(r' [\[(](.+)[)\]]',xtitle) #+ re.findall(r' (.+)',xtitle)
       if hist0.GetXaxis().IsVariableBinSize():
         if units:
           ytitle = "Events / "+units[-1]
         else:
           ytitle = "Events / bin size"
       elif units:
         if binwidth!=1:
           ytitle = "Events / %s %s"%(binwidstr,units[-1])
         else:
           ytitle = "Events / "+units[-1]
       elif binwidth!=1:
         ytitle = "Events / "+binwidstr
       else:
         ytitle = "Events"
       LOG.verb("Plot.setaxes: ytitle=%r, units=%s, binwidth=%s, binwidstr=%r"%(ytitle,units,binwidth,binwidstr),verbosity,2)
   
   # alphanumerical bin labels
   if binlabels:
     if len(binlabels)<nbins:
       LOG.warning("Plot.setaxes: len(binlabels)=%d < %d=nbins"%(len(binlabels),nbins))
     for i, binlabel in zip(range(1,nbins+1),binlabels):
       frame.GetXaxis().SetBinLabel(i,binlabel)
     #frame.GetXaxis().LabelsOption('h')
   
   # X axis
   frame.GetXaxis().SetTitleSize(xtitlesize)
   frame.GetXaxis().SetTitleOffset(xtitleoffset)
   frame.GetXaxis().SetLabelSize(xlabelsize)
   frame.GetXaxis().SetLabelOffset(xlabeloffset)
   frame.GetXaxis().SetNdivisions(nxdivisions)
   frame.GetXaxis().SetTitle(xtitle)
   
   # Y axis
   if ymax>=1e4:
     ylabelsize *= 0.95
   if ycenter:
     frame.GetYaxis().CenterTitle(True)
   frame.GetYaxis().SetTitleSize(ytitlesize)
   frame.GetYaxis().SetTitleOffset(ytitleoffset)
   frame.GetYaxis().SetLabelSize(ylabelsize)
   frame.GetYaxis().SetNdivisions(nydivisions)
   frame.GetYaxis().SetTitle(ytitle)
   gPad.RedrawAxis()
   gPad.Update()
   
   if verbosity>=1:
     print ">>> Plot.setaxes: xtitle=%r, [hmin,hmax] = [%.6g,%.6g], [xmin,xmax] = [%.6g,%.6g], [ymin,ymax] = [%.6g,%.6g]"%(
                              xtitle,hmin,hmax,xmin,xmax,ymin,ymax)
   elif verbosity>=2:
     print ">>> Plot.setaxes: frame=%s"%(frame)
     print ">>> Plot.setaxes: hists=%s"%(hists)
     print ">>> Plot.setaxes: [hmin,hmax] = [%.6g,%.6g], [xmin,xmax] = [%.6g,%.6g], [ymin,ymax] = [%.6g,%.6g]"%(hmin,hmax,xmin,xmax,ymin,ymax)
     print ">>> Plot.setaxes: xtitlesize=%4.4g, xlabelsize=%4.4g, xtitleoffset=%4.4g, xtitle=%r"%(xtitlesize,xlabelsize,xtitleoffset,xtitle)
     print ">>> Plot.setaxes: ytitlesize=%4.4g, ylabelsize=%4.4g, ytitleoffset=%4.4g, ytitle=%r"%(ytitlesize,ylabelsize,ytitleoffset,ytitle)
     print ">>> Plot.setaxes: scale=%4.4g, nxdivisions=%s, nydivisions=%s, ymargin=%.3f, logyrange=%.3f"%(scale,nxdivisions,nydivisions,ymargin,logyrange)
   if main:
     #if any(a!=None and a!=b for a, b in [(self.xmin,xmin),(self.xmax,xmax)]):
     #  LOG.warning("Plot.setaxes: x axis range changed: [xmin,xmax] = [%6.6g,%6.6g] -> [%6.6g,%6.6g]"%(
     #              self.xmin,self.xmax,xmin,xmax))
     #if any(a!=None and a!=b for a, b in [(self.ymin,ymin),(self.ymax,ymax)]):
     #  LOG.warning("Plot.setaxes: y axis range changed: [ymin,ymax] = [%6.6g,%6.6g] -> [%6.6g,%6.6g]"%(
     #              self.ymin,self.ymax,ymin,ymax))
     self.xmin, self.xmax = xmin, xmax
     self.ymin, self.ymax = ymin, ymax
   return xmin, xmax, ymin, ymax
Example #15
0
def PlotVariables(output_dir,
                  dataset_name,
                  variable,
                  weight_names,
                  region,
                  Location,
                  Bkg_processes,
                  Lumi,
                  Lumi_label,
                  category,
                  LOG=False):

    bkg_names = []
    label_names = []
    for Bkg_process in Bkg_processes:
        if Bkg_process == 9:
            continue
        bkg_names.append(Bkg_processes[Bkg_process]['folder_name'])
        label_names.append([
            Bkg_processes[Bkg_process]['folder_name'],
            Bkg_processes[Bkg_process]['latex_name'],
            Bkg_processes[Bkg_process]['color'], 0
        ])

    signal_name = [Bkg_processes[9]['folder_name']]

    Scaling = False

    #LOG = False

    c = []
    p1 = []
    p2 = []

    plot_count = 0

    data_hist = []
    data_for_ratio = []
    bkg_for_ratio = []
    signal_hist = []
    bkg_stack = []
    legend = []
    tex1 = []
    tex2 = []
    tex3 = []
    printing = False

    prefix = Location + "output_" + region + "_sh/"
    mc_prefix = prefix

    DATA = pd.read_csv(prefix + '/' + dataset_name + '/tbl_' +
                       variable[Properties.Name] + weight_names + '.csv',
                       comment='#')
    tmp1_name, tmp2 = variable[Properties.Name].split('--')

    data_hist.append(
        CreateHistogramNP(DATA, tmp1_name,
                          variable[Properties.HistName] + "_data",
                          variable[Properties.AxisLabels], 'n', 1, 1,
                          variable[Properties.Rebin]))
    data_for_ratio.append(data_hist[plot_count].Clone())
    bkg_stack.append(THStack("Background", "Full_Background"))
    if printing:
        print("Data", data_hist[plot_count].Integral())

    if ('W' in region) or ('Z' in region) or ('SR' in region) and not (
            "mindphi" in variable[Properties.Name].lower()):
        legend_args = (0.7, 0.55, 0.95, 0.91, '', 'NDC')
    else:
        legend_args = (0.18, 0.55, 0.55, 0.91, '', 'NDC')

    if 'mindPhi' in variable[0] or (
            'electron' in variable[Properties.Name].lower()
            and 'phi' in variable[Properties.Name].lower()):
        legend_args = (0.18, 0.55, 0.55, 0.91, '', 'NDC')

    #take legend parametrisation out of for loop later
    legend.append(TLegend(*legend_args))
    legend[plot_count].SetFillStyle(0)

    legend[plot_count].AddEntry(data_hist[plot_count], 'Data', 'p')

    if not (len(signal_name) == 0):
        SIGNAL = pd.read_csv(mc_prefix + '/' + signal_name[0] + '/tbl_' +
                             variable[Properties.Name] + weight_names + '.csv',
                             comment='#')
        signal_hist.append(
            CreateHistogramNP(SIGNAL, tmp1_name,
                              variable[Properties.HistName] + "_signal",
                              variable[Properties.AxisLabels],
                              variable[Properties.Weight], 1, Lumi,
                              variable[Properties.Rebin]))
        if 'SR' in region:
            legend[plot_count].AddEntry(signal_hist[plot_count],
                                        'VBF H#rightarrow Inv', 'l')

    for bkg_name in bkg_names:

        bkg_file = pd.read_csv(mc_prefix + '/' + bkg_name + '/tbl_' +
                               variable[Properties.Name] + weight_names +
                               '.csv',
                               comment='#')

        color = 2
        addLeg = False
        if (groupBy):
            bkg_file = bkg_file.dropna().groupby(tmp1_name).sum()
            bkg_file.reset_index(inplace=True)

        #print bkg_name
        index_leg = [['', '', 0, 0]]
        for label_name in label_names:
            if label_name[0] in bkg_name:
                # print "In_check"
                color = label_name[2]
                if label_name[3] == 0:
                    #print bkg_name, label_name[0], "in label check"
                    addLeg = True
                    label_name[3] = 1
                    index_leg = label_name
                break

        bkg_hist = CreateHistogramNP(
            bkg_file, tmp1_name,
            variable[Properties.HistName] + bkg_name + "_mc" + str(plot_count),
            variable[Properties.AxisLabels], variable[Properties.Weight],
            color, Lumi, variable[Properties.Rebin])

        #Scaling
        if Scaling:
            if "DY" in bkg_name:
                print("Scaling DY")
                bkg_hist.Scale(1.15)
            if "WJETS" in bkg_name:
                bkg_hist.Scale(1.171714)

        bkg_hist.GetXaxis().SetRangeUser(
            variable[Properties.Axis_low],
            variable[Properties.Axis_high])  #- Really strange!
        bkg_stack[plot_count].Add(bkg_hist)

        if bkg_names.index(bkg_name) == 0:
            bkg_for_ratio.append(bkg_hist.Clone())
        else:
            bkg_for_ratio[plot_count].Add(bkg_hist)

        if addLeg:
            if not (bkg_hist.Integral() == 0):
                # print bkg_name, bkg_hist.Integral()
                addLeg = False
                legend[plot_count].AddEntry(bkg_hist, index_leg[1], 'f')
            else:
                for label_name in label_names:
                    if label_name[0] in bkg_name:
                        label_name[
                            3] = 0  # return to the state label_not_drawn, not elegant check. return to it after the EXO workdshop!
                        break

    #WORK IN PROGRESS

    printing = False
    c.append(ROOT.TCanvas("c" + str(plot_count), "2 Graphs", 900, 1000))
    p2.append(ROOT.TPad("p2", "p3", 0., 0., 1., 0.28))
    p2[plot_count].Draw()
    p2[plot_count].SetTopMargin(0.001)
    p2[plot_count].SetBottomMargin(0.3)
    p2[plot_count].SetGrid()

    p1.append(ROOT.TPad("p1", "p1", 0., 0.3, 1., 1.))
    p1[plot_count].Draw()
    p1[plot_count].SetBottomMargin(0.001)
    p1[plot_count].cd()

    data_hist[plot_count].SetLineColor(1)

    data_hist[plot_count].GetXaxis().SetRangeUser(
        variable[Properties.Axis_low], variable[Properties.Axis_high])

    if LOG:
        p1[plot_count].SetLogy(1)

    data_hist[plot_count].Draw("e1")

    bkg_stack[plot_count].Draw("hist same")
    bkg_for_ratio[plot_count].SetFillColor(1)
    bkg_for_ratio[plot_count].SetMarkerSize(0)
    bkg_for_ratio[plot_count].SetFillStyle(3018)
    bkg_for_ratio[plot_count].Draw("E2 same")

    if LOG:
        data_hist[plot_count].GetYaxis().SetRangeUser(
            0.2, 1000 * bkg_for_ratio[plot_count].GetMaximum())
    else:
        data_hist[plot_count].GetYaxis().SetRangeUser(
            0, 1.7 * bkg_for_ratio[plot_count].GetMaximum())
        if data_hist[plot_count].Integral() > 0:
            data_hist[plot_count].GetYaxis().SetRangeUser(
                0.1, 1.7 * bkg_for_ratio[plot_count].GetMaximum())
    if 'mjj' in variable[Properties.Name] or 'nomu' in variable[
            Properties.Name].lower():
        data_hist[plot_count].GetYaxis().SetRangeUser(
            0.1, 1.3 * bkg_for_ratio[plot_count].GetMaximum())
        bkg_stack[plot_count].GetYaxis().SetRangeUser(
            0.1, 1.3 * bkg_for_ratio[plot_count].GetMaximum())

    data_hist[plot_count].GetXaxis().SetLabelSize(0.1)
    data_hist[plot_count].GetYaxis().SetTitleOffset(1.15)
    data_hist[plot_count].GetXaxis().SetTitleSize(.12)

    data_hist[plot_count].Draw("e1 same")

    if not (len(signal_name) == 0):
        signal_hist[plot_count].SetLineWidth(4)
        signal_hist[plot_count].SetFillStyle(0)
        if 'vtr' in category.lower():
            signal_hist[plot_count].Scale(1.5)
        else:
            signal_hist[plot_count].Scale(5)
        signal_hist[plot_count].Draw("hist same")

    #gPad.Draw()
    legend[plot_count].Draw()
    tex = Styling(region, "CMS", "Work in Progress", Lumi_label)
    tex1.append(tex[0])
    tex2.append(tex[1])
    tex3.append(tex[2])

    tex1[plot_count].Draw("goff")
    tex2[plot_count].Draw("goff")
    tex3[plot_count].Draw("goff")
    #gPad.Update();
    gPad.RedrawAxis()

    p2[plot_count].cd()
    #r = ROOT.TGraph(20);
    #r.SetTitle("");
    data_for_ratio[plot_count].Divide(bkg_for_ratio[plot_count])
    data_for_ratio[plot_count].GetXaxis().SetRangeUser(
        variable[Properties.Axis_low], variable[Properties.Axis_high])

    data_for_ratio[plot_count].GetYaxis().SetRangeUser(-0.49, 2.49)
    data_for_ratio[plot_count].GetYaxis().SetTitle("Data / Pred.")
    data_for_ratio[plot_count].GetXaxis().SetTitleSize(.12)
    data_for_ratio[plot_count].GetYaxis().SetTitleSize(.12)
    data_for_ratio[plot_count].GetYaxis().SetTitleOffset(0.57)
    data_for_ratio[plot_count].GetYaxis().SetLabelSize(0.1)
    data_for_ratio[plot_count].GetXaxis().SetLabelSize(0.1)
    data_for_ratio[plot_count].Draw("P0")
    bkg_band = bkg_for_ratio[plot_count].Clone()
    bkg_band_d = bkg_for_ratio[plot_count].Clone()
    bkg_band.Divide(bkg_band_d)
    bkg_band.SetFillColor(1)
    bkg_band.SetMarkerSize(0)
    bkg_band.SetFillStyle(3018)
    bkg_band.Draw("E2 same")
    #        c[plot_count].Draw()

    gPad.RedrawAxis()

    if not (LOG):
        c[plot_count].SaveAs(output_dir + "/" + tmp1_name + ".pdf")
        c[plot_count].SaveAs(output_dir + "/" + tmp1_name + ".png")
        c[plot_count].SaveAs(output_dir + "/" + tmp1_name + ".C")
        c[plot_count].SaveAs(output_dir + "/" + tmp1_name + ".root")
    else:
        c[plot_count].SaveAs(output_dir + "/" + tmp1_name + "_log.pdf")
        c[plot_count].SaveAs(output_dir + "/" + tmp1_name + "_log.png")
        c[plot_count].SaveAs(output_dir + "/" + tmp1_name + "_log.C")
        c[plot_count].SaveAs(output_dir + "/" + tmp1_name + "_log.root")

    plot_count += 1
    return True
Example #16
0
def plotPValues(labels, masses0, **kwargs):
    print color("plotPValues()", color="magenta", prepend=">>>\n>>> ")

    # SIGNAL strength & mass
    bins = kwargs.get('bins', [])
    ymin = 0.00005

    # LOOP over LABELS
    for label in labels:
        print color("plotPValues - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

        masses = array('d', [])
        zeros = array('d', [])
        limitObs = array('d', [])
        limitExps = []

        up2s = []
        for i, mass in enumerate(masses0):
            bin = -1
            if bins: bin = bins[i]
            filename = getOutputFilename(label,
                                         mass,
                                         method="ProfileLikelihood",
                                         bin=bin,
                                         extralabel=".SignifObs")
            limitObs.append(getLimits(filename, brazilian=False))
            masses.append(mass)
            zeros.append(0.0)

        v_masses = TVectorD(len(masses), masses)
        v_zeros = TVectorD(len(zeros), zeros)
        v_limitObs = TVectorD(len(limitObs), limitObs)
        v_limitExps = []
        for limitExp in limitExps:
            v_limitExps.append(TVectorD(len(limitExp), limitExp))

        W = 800
        H = 600
        T = 0.08 * H
        B = 0.12 * H
        L = 0.12 * W
        R = 0.04 * W
        canvas = TCanvas("canvas", "canvas", 100, 100, W, H)
        canvas.SetFillColor(0)
        canvas.SetBorderMode(0)
        canvas.SetFrameFillStyle(0)
        canvas.SetFrameBorderMode(0)
        canvas.SetLeftMargin(L / W)
        canvas.SetRightMargin(R / W)
        canvas.SetTopMargin(T / H)
        canvas.SetBottomMargin(B / H)
        canvas.SetTickx(0)
        canvas.SetTicky(0)
        canvas.SetGrid()
        canvas.SetLogy()  # log
        canvas.cd()

        frame = canvas.DrawFrame(1.4, 0.001, 4.1, 10)
        frame.GetYaxis().CenterTitle()
        frame.GetYaxis().SetTitleSize(0.05)
        frame.GetXaxis().SetTitleSize(0.05)
        frame.GetXaxis().SetLabelSize(0.04)
        frame.GetYaxis().SetLabelSize(0.04)
        frame.GetYaxis().SetTitleOffset(1.14)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(False)
        frame.GetYaxis().SetTitle("local p-value")
        #frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}")
        frame.GetXaxis().SetTitle("X#rightarrow#tau#tau mass [GeV]")
        frame.SetMinimum(ymin)
        frame.SetMaximum(1.5)
        frame.GetXaxis().SetLimits(min(masses), max(masses))

        latex = TLatex()
        latex.SetTextSize(0.4 * canvas.GetTopMargin())
        latex.SetTextColor(2)
        f1 = TF1("f1", "0.15866", min(masses), max(masses))
        f1.SetLineColor(2)
        f1.SetLineWidth(2)
        f1.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.15866 * 1.1, "1#sigma")
        f2 = TF1("f2", "0.02275", min(masses), max(masses))
        f2.SetLineColor(2)
        f2.SetLineWidth(2)
        f2.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.02275 * 1.1, "2#sigma")
        f3 = TF1("f3", "0.0013499", min(masses), max(masses))
        f3.SetLineColor(2)
        f3.SetLineWidth(2)
        f3.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.0013499 * 1.1, "3#sigma")

        graph_limitExps = []
        colors = [4, 2, 3, 6, 7, 8]
        for i, v_limitExp in enumerate(v_limitExps):
            graph_limitExps.append(
                TGraphAsymmErrors(v_masses, v_limitExp, v_zeros, v_zeros,
                                  v_zeros, v_zeros))
            graph_limitExps[-1].SetLineColor(colors[i])
            graph_limitExps[-1].SetLineWidth(2)
            graph_limitExps[-1].SetLineStyle(2)
            graph_limitExps[-1].Draw("Lsame")

        graph_limitObs = TGraphAsymmErrors(v_masses, v_limitObs, v_zeros,
                                           v_zeros, v_zeros, v_zeros)
        graph_limitObs.SetLineColor(1)
        graph_limitObs.SetLineWidth(2)
        graph_limitObs.Draw("Csame")

        CMS_lumi.CMS_lumi(canvas, 13, 0)
        gPad.SetTicks(1, 1)
        frame.Draw('sameaxis')

        x1 = 0.62
        x2 = x1 + 0.24
        y1 = 0.15
        y2 = y1 + 0.20
        legend = TLegend(x1, y1, x2, y2)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.041)
        legend.SetTextFont(42)
        legend.SetHeader("%s" % (label_dict[label]))
        legend.AddEntry(graph_limitObs, "observed", 'L')  #p-value
        legend.Draw("same")
        gPad.RedrawAxis()

        print " "
        canvas.SaveAs("%s/p-value-local-%s.png" % (PLOTS_DIR, label))
        canvas.SaveAs("%s/p-value-local-%s.pdf" % (PLOTS_DIR, label))
        canvas.Close()
Example #17
0
def main():
    # usage description
    usage = "Example: ./scripts/plotLimits.py -M Asymptotic -l logs -f qq --massrange 1200 7000 100"

    # input parameters
    parser = ArgumentParser(description='Script that plots limits for specified mass points',epilog=usage)
    parser.add_argument('analysis', type=str, help='Analysis name')
    parser.add_argument('model', type=str, help='Model name')

    parser.add_argument("-M", "--method", dest="method", required=True,
                        choices=['ProfileLikelihood', 'HybridNew', 'Asymptotic', 'MarkovChainMC', 'theta', 'HybridNewGrid'],
                        help="Method to calculate upper limits",
                        metavar="METHOD")
    parser.add_argument('--fit_function', type=str, default="f4", help="Name of fit function used for background estimate")
    parser.add_argument('--timesAE', action='store_true', help="Set y-axis to sigma*BR*A*e, instead of sigma*BR")
    parser.add_argument('--fitTrigger', action='store_true', help="Use trigger fit")
    parser.add_argument('--correctTrigger', action='store_true', help="Use trigger correction")
    parser.add_argument('--useMCTrigger', action='store_true', help="Use MC trigger emulation")
    #results_group = parser.add_mutually_exclusive_group(required=True)
    #results_group.add_argument("-l", "--logs_path", dest="logs_path",
    #                           help="Path to log files",
    #                           metavar="LOGS_PATH")
    #results_group.add_argument("-r", "--results_file", dest="results_file",
    #                           help="Path to a file containing results",
    #                           metavar="RESULTS_FILE")

    #parser.add_argument("-f", "--final_state", dest="final_state", required=True,
    #                    help="Final state (e.g. qq, qg, gg)",
    #                    metavar="FINAL_STATE")

    #parser.add_argument("-f2", "--finalstate2", dest="final_state2", required=True, help="hG,lG,hR, or lR", metavar="FINAL_STATE2")
    parser.add_argument("--noSyst", action="store_true", help="Make plots for limits without systematics")
    parser.add_argument("--freezeNuisances", type=str, help="Make plots for limits with frozen nuisance parameters")
    parser.add_argument("--postfix", dest="postfix", default='', help="Postfix for the output plot name (default: %(default)s)")

    parser.add_argument("--fileFormat", dest="fileFormat", default='pdf', help="Format of the output plot (default: %(default)s)")
    parser.add_argument("--saveObjects", type=str, help="Save plot objects")
    parser.add_argument("--extraText", dest="extraText", default='', help="Extra text on the plot (default: %(default)s)")

    parser.add_argument("--lumi_sqrtS", dest="lumi_sqrtS", default='19.7 fb^{-1} (8 TeV)', help="Integrated luminosity and center-of-mass energy (default: %(default)s)")

    parser.add_argument("--printResults", dest="printResults", default=False, action="store_true", help="Print results to the screen")

    mass_group = parser.add_mutually_exclusive_group(required=True)
    mass_group.add_argument("--mass",
                            type=int,
                            nargs = '*',
                            default = 1000,
                            help="Mass can be specified as a single value or a whitespace separated list (default: %(default)i)"
                            )
    mass_group.add_argument("--massrange",
                            type=int,
                            nargs = 3,
                            help="Define a range of masses to be produced. Format: min max step",
                            metavar = ('MIN', 'MAX', 'STEP')
                            )
    mass_group.add_argument("--masslist",
                            help = "List containing mass information"
                            )

    args = parser.parse_args()

    if args.method == 'HybridNew':
        searchmethod = 'Hybrid New'

    # mass points for which resonance shapes will be produced
    input_masses = []

    if args.massrange != None:
        MIN, MAX, STEP = args.massrange
        input_masses = range(MIN, MAX+STEP, STEP)
    elif args.masslist != None:
        # A mass list was provided
        print "Will create mass list according to", args.masslist
        masslist = __import__(args.masslist.replace(".py",""))
        input_masses = masslist.masses
    else:
        input_masses = args.mass
    # sort masses
    input_masses.sort()

    from ROOT import kTRUE, kFALSE, gROOT, gStyle, gPad, TGraph, TCanvas, TLegend, TF1, TFile
    from ROOT import kGreen, kYellow, kWhite

    # Make acc*eff TGraph
    ae_x = array('d',[325, 350, 400, 500, 600, 750, 900, 1200])
    if args.timesAE:
        ae_y = np.ones(len(ae_x))
    else:
        ae_y = array('d', [])
        for mass in ae_x:
            ae_y.append(analysis_config.simulation.get_signal_AE(args.analysis, args.model, int(mass)))
    acceptance_times_efficiency = TGraph(len(ae_x), ae_x, ae_y)
    #xs = array('d',[250,300,400,500,600,750,900,1200])

    #trigger_correctionl = TF1("trigbbl_efficiency", "(1. / (1. + TMath::Exp(-1. * (x - [0]) / [1])))**[2]", 175, 400)
    #trigger_correctionl.SetParameter(0, 1.82469e+02)
    #trigger_correctionl.SetParameter(1,  2.87768e+01)
    #trigger_correctionl.SetParameter(2,  9.11659e-01)

    #trigger_correctionh = TF1("trigbbh_efficiency", "(1. / (1. + TMath::Exp(-1. * (x - [0]) / [1])))**[2]", 300, 600)
    #trigger_correctionh.SetParameter(0, 3.61785e+02)
    #trigger_correctionh.SetParameter(1,  3.16523e+01)
    #trigger_correctionh.SetParameter(2,  4.84357e-01)
    #if args.timesAE:
    #    ys = np.ones(len(xs))
    #else:
    #    if args.analysis == "trigbbh_CSVTM" and args.model == "Hbb":
    #    	#ys = array('d',[188./19751.,1304./19993.,2697./49494.,881./19999.,534./19598.])
    #		ys = array('d',[24./19737.,188./19751.,1171./19984.,1419./19992.,1304./19993.,2697./49494.,881./19999.,534./19598.])
    #		#graphMod = trigger_correctionh
    #    elif args.analysis == "trigbbl_CSVTM" and args.model == "Hbb":
    #		#ys = array('d',[30./2797.,1583./19995.,1295./19996.,999./19996.,528./19999.])
    #		ys = array('d',[574./19737.,763./39502.,651./19984.,583./19992.,984./39986.,1905./98988.,656./39998.,369./39196.])
    #		#graphMod = trigger_correctionh
    #    elif args.analysis == "trigbbh_CSVTM" and args.model == "RSG":
    #		#ys = array('d',[109./19751.,488./19993.,954./49494.,328./19999.,182./19598.])
    #		ys = array('d',[40./19977.,30./2797.,1522./19991.,1640./19396.,1583./19995.,1295./19996.,999./19996.,528./19999.])
    #		#graphMod = trigger_correctionl
    #    elif args.analysis == "trigbbl_CSVTM" and args.model == "RSG":
    #		#ys = array('d',[23./2797.,599./19995.,448./19996.,338./19996.,190./19999.])
    #		ys = array('d',[696./19977.,137./5594.,797./19991.,652./19396.,1206./39990.,891./39992.,675./39992.,379./39998.])
    #		#graphMod = trigger_correctionl

    ##ys = array('d',[1,1,1,1,1,1,1,1,])   

    #acceptance_times_efficiency = TGraph(len(xs),xs,ys)


    # arrays holding results
    masses = array('d')
    xs_obs_limits = array('d')
    xs_exp_limits = array('d')
    masses_exp = array('d')
    xs_exp_limits_1sigma = array('d')
    xs_exp_limits_1sigma_up = array('d')
    xs_exp_limits_2sigma = array('d')
    xs_exp_limits_2sigma_up = array('d')

    for mass in input_masses:
        print ">> Reading results for %s %s resonance with m = %i GeV..."%(args.analysis, args.model, int(mass))
        masses.append(mass)
        masses_exp.append(mass)

        # For masses above 1100, you scaled down the signal by 10 by hand, to help the limit setting.
        #if args.analysis == "trigbbh_CSVTM" and mass >= 1100:
        input_xs = 1./100.
        #else:
        #    input_xs = 1.

        if args.method == "HybridNewGrid":
            found_limit = {"obs":False, "exp0":False, "exp1":False, "exp2":False, "exp-1":False, "exp-2":False}
            for what in found_limit.keys():
                log_file_path = limit_config.get_combine_log_path_grid(args.analysis, args.model, mass, args.fit_function, what, systematics=(not args.noSyst), frozen_nps=args.freezeNuisances, fitTrigger=args.fitTrigger, correctTrigger=args.correctTrigger, useMCTrigger=args.useMCTrigger)
                print "Reading log file from " + log_file_path
                log_file = open(log_file_path, 'r')
                for line in log_file:
                    if re.search("^Limit: r <", line) and re.search("95%", line):
                        found_limit[what] = True
                        this_limit = float(line.split()[3])/acceptance_times_efficiency.Eval(mass)
                        print "Found limit for " + what + " = " + str(this_limit)
                        if what == "obs":
                            xs_obs_limits.append(this_limit * input_xs)
                        elif what == "exp0":
                            xs_exp_limits.append(this_limit * input_xs)
                        elif what == "exp1":
                            xs_exp_limits_1sigma_up.append(this_limit * input_xs)
                        elif what == "exp2":
                            xs_exp_limits_2sigma_up.append(this_limit * input_xs)
                        elif what == "exp-1":
                            xs_exp_limits_1sigma.append(this_limit * input_xs)
                        elif what == "exp-2":
                            xs_exp_limits_2sigma.append(this_limit * input_xs)
            if not found_limit["obs"]:
                xs_obs_limits.append(0)
            if not found_limit["exp0"]:
                xs_exp_limits.append(0)
            if not found_limit["exp1"]:
                xs_exp_limits_1sigma.append(0)
            if not found_limit["exp2"]:
                xs_exp_limits_1sigma_up.append(0)
            if not found_limit["exp-1"]:
                xs_exp_limits_2sigma.append(0)
            if not found_limit["exp-2"]:
                xs_exp_limits_2sigma_up.append(0)
            if len(masses) != len(xs_obs_limits):
                print "** ERROR: ** Could not find observed limit for m =", int(mass), "GeV. Aborting."
                sys.exit(1)
        else:
            print "Reading log file from " + limit_config.get_combine_log_path(args.analysis, args.model, mass, args.fit_function, args.method, systematics=(not args.noSyst), frozen_nps=args.freezeNuisances, fitTrigger=args.fitTrigger, correctTrigger=args.correctTrigger, useMCTrigger=args.useMCTrigger)
            if not os.path.exists((limit_config.get_combine_log_path(args.analysis, args.model, mass, args.fit_function, args.method, systematics=(not args.noSyst), frozen_nps=args.freezeNuisances, fitTrigger=args.fitTrigger, correctTrigger=args.correctTrigger, useMCTrigger=args.useMCTrigger))):
                print "[plot_limits] WARNING : Log file not found! Setting limits to zero and skipping this point."
                print "[plot_limits] WARNING : \t{}".format(limit_config.get_combine_log_path(args.analysis, args.model, mass, args.fit_function, args.method, systematics=(not args.noSyst), frozen_nps=args.freezeNuisances, fitTrigger=args.fitTrigger, correctTrigger=args.correctTrigger, useMCTrigger=args.useMCTrigger))
                xs_obs_limits.append(0)
                xs_exp_limits.append(0)
                xs_exp_limits_1sigma.append(0)
                xs_exp_limits_1sigma_up.append(0)
                xs_exp_limits_2sigma.append(0)
                xs_exp_limits_2sigma_up.append(0)
                continue
            log_file = open(limit_config.get_combine_log_path(args.analysis, args.model, mass, args.fit_function, args.method, systematics=(not args.noSyst), frozen_nps=args.freezeNuisances, fitTrigger=args.fitTrigger, correctTrigger=args.correctTrigger, useMCTrigger=args.useMCTrigger))

            foundMethod = False
            middle = 0
            # read the log file
            found_limit = {"obs":False, "exp":False, "exp+1":False, "exp+2":False, "exp-1":False, "exp-2":False}
            for line in log_file:
                if args.method == 'Asymptotic':
                    if re.search("^Observed Limit: r", line):
                        xs_obs_limits.append(float(line.split()[-1])/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["obs"] = True
                        if mass == 325 and args.model == "ZPrime":
                            print "[debug] ZPrime 325 GeV limit = {}".format(xs_obs_limits[-1])
                            print "[debug] \tA*e={}, input_xs={}".format(acceptance_times_efficiency.Eval(mass), input_xs)
                    if re.search("^Expected 50.0%: r", line):
                        middle = float(line.split()[-1])
                        found_limit["exp"] = True
                        xs_exp_limits.append(middle/acceptance_times_efficiency.Eval(mass) * input_xs)
                    if re.search("^Expected 16.0%: r", line):
                        xs_exp_limits_1sigma.append((float(line.split()[-1]))/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["exp-1"] = True
                    if re.search("^Expected 84.0%: r", line):
                        xs_exp_limits_1sigma_up.append(float(line.split()[-1])/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["exp+1"] = True
                    if re.search("^Expected  2.5%: r", line):
                        xs_exp_limits_2sigma.append(float(line.split()[-1])/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["exp-2"] = True
                    if re.search("^Expected 97.5%: r", line):
                        xs_exp_limits_2sigma_up.append(float(line.split()[-1])/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["exp+2"] = True
                elif args.method == 'theta':
                    if re.search('^# x; y; yerror', line):
                        foundMethod = True
                    if line.split()[0] == '0' and foundMethod:
                        xs_obs_limits.append(float(line.split()[1])/acceptance_times_efficiency.Eval(mass) * input_xs)
                else:
                    searchmethod = "Hybrid New"
                    if re.search(' -- ' + searchmethod, line):
                        foundMethod = True
                    if re.search("^Limit: r", line) and foundMethod:
                        xs_obs_limits.append(float(line.split()[3])/acceptance_times_efficiency.Eval(mass) * input_xs)
                        found_limit["obs"] = True
                        print "[debug] Found limit " + str(xs_obs_limits[-1])

            if not found_limit["obs"]:
                xs_obs_limits.append(0)
            if not found_limit["exp"]:
                xs_exp_limits.append(0)
            if not found_limit["exp+1"]:
                xs_exp_limits_1sigma.append(0)
            if not found_limit["exp+2"]:
                xs_exp_limits_1sigma_up.append(0)
            if not found_limit["exp-1"]:
                xs_exp_limits_2sigma.append(0)
            if not found_limit["exp-2"]:
                xs_exp_limits_2sigma_up.append(0)
            if len(masses) != len(xs_obs_limits):
                print "** ERROR: ** Could not find observed limit for m =", int(mass), "GeV. Aborting."
                sys.exit(1)

        if args.method == 'Asymptotic' or args.method == 'HybridNewGrid':
            if len(masses) != len(xs_exp_limits):
                print "** ERROR: ** Could not find expected limit for m =", int(mass), "GeV. Aborting."
                print "masses = ",
                print masses
                print "xs_exp_limits = ",
                print xs_exp_limits
                sys.exit(1)

            if len(masses) != len(xs_exp_limits_1sigma):
                print "** ERROR: ** Could not find expected 1 sigma down limit for m =", int(mass), "GeV. Aborting."
                print "masses = ",
                print masses
                print "xs_exp_limits_1sigma = ",
                print xs_exp_limits_1sigma
                sys.exit(1)

            if len(masses) != len(xs_exp_limits_1sigma_up):
                print "** ERROR: ** Could not find expected 1 sigma up limit for m =", int(mass), "GeV. Aborting."
                print "masses = ",
                print masses
                print "xs_exp_limits_1sigma_up = ",
                print xs_exp_limits_1sigma_up
                sys.exit(1)

            if len(masses) != len(xs_exp_limits_2sigma):
                print "** ERROR: ** Could not find expected 2 sigma down limit for m =", int(mass), "GeV. Aborting."
                sys.exit(1)

            if len(masses) != len(xs_exp_limits_2sigma_up):
                print "** ERROR: ** Could not find expected 2 sigma up limit for m =", int(mass), "GeV. Aborting."
                sys.exit(1)
    if args.method == 'Asymptotic' or args.method == 'HybridNewGrid':
        # complete the expected limit arrays
        for i in range(0,len(masses)):
            masses_exp.append( masses[len(masses)-i-1] )
            xs_exp_limits_1sigma.append( xs_exp_limits_1sigma_up[len(masses)-i-1] )
            xs_exp_limits_2sigma.append( xs_exp_limits_2sigma_up[len(masses)-i-1] )

    if args.printResults:
        print "masses =", masses.tolist()
        print "xs_obs_limits =", xs_obs_limits.tolist()
        print "xs_exp_limits =", xs_exp_limits.tolist()
        print ""
        print "masses_exp =", masses_exp.tolist()
        print "xs_exp_limits_1sigma =", xs_exp_limits_1sigma.tolist()
        print "xs_exp_limits_2sigma =", xs_exp_limits_2sigma.tolist()


    gROOT.SetBatch(kTRUE);
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)
    gStyle.SetTitleFont(42, "XYZ")
    gStyle.SetTitleSize(0.05, "XYZ")
    gStyle.SetLabelFont(42, "XYZ")
    gStyle.SetLabelSize(0.05, "XYZ")
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetFrameBorderMode(0)
    gStyle.SetCanvasColor(kWhite)
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)
    gStyle.SetPadLeftMargin(0.15)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadBottomMargin(0.15)
    gROOT.ForceStyle()

    # theory curves: gg
    massesS8 = array('d', [1000.0,1100.0,1200.0,1300.0,1400.0,1500.0,1600.0,1700.0,1800.0,1900.0,2000.0,2100.0,2200.0,2300.0,2400.0,2500.0,2600.0,2700.0,2800.0,2900.0,3000.0,3100.0,3200.0,3300.0,3400.0,3500.0,3600.0,3700.0,3800.0,3900.0,4000.0,4100.0,4200.0,4300.0,4400.0,4500.0,4600.0,4700.0,4800.0,4900.0,5000.0,5100.0,5200.0,5300.0,5400.0,5500.0,5600.0,5700.0,5800.0,5900.0,6000.0])
    xsS8 = array('d', [5.46E+02,3.12E+02,1.85E+02,1.12E+02,7.19E+01,4.59E+01,3.02E+01,2.01E+01,1.37E+01,9.46E+00,6.55E+00,4.64E+00,3.27E+00,2.36E+00,1.70E+00,1.24E+00,9.11E-01,6.69E-01,4.97E-01,3.71E-01,2.78E-01,2.07E-01,1.55E-01,1.19E-01,9.26E-02,7.08E-02,5.43E-02,4.15E-02,3.22E-02,2.50E-02,1.92E-02,1.51E-02,1.19E-02,9.25E-03,7.35E-03,5.86E-03,4.53E-03,3.66E-03,2.91E-03,2.33E-03,1.86E-03,1.45E-03,1.12E-03,8.75E-04,6.90E-04,5.55E-04,4.47E-04,3.63E-04,2.92E-04,2.37E-04,1.97E-04])

    graph_xsS8 = TGraph(len(massesS8),massesS8,xsS8)
    graph_xsS8.SetLineWidth(3)
    graph_xsS8.SetLineStyle(8)
    graph_xsS8.SetLineColor(6)

    # theory curves: qg
    massesString = array('d', [1000.0,1100.0,1200.0,1300.0,1400.0,1500.0,1600.0,1700.0,1800.0,1900.0,2000.0,2100.0,2200.0,2300.0,2400.0,2500.0,2600.0,2700.0,2800.0,2900.0,3000.0,3100.0,3200.0,3300.0,3400.0,3500.0,3600.0,3700.0,3800.0,3900.0,4000.0,4100.0,4200.0,4300.0,4400.0,4500.0,4600.0,4700.0,4800.0,4900.0,5000.0,5100.0,5200.0,5300.0,5400.0,5500.0,5600.0,5700.0,5800.0,5900.0,6000.0,6100.0,6200.0,6300.0,6400.0,6500.0,6600.0,6700.0,6800.0,6900.0,7000.0,7100.0,7200.0,7300.0,7400.0,7500.0,7600.0,7700.0,7800.0,7900.0,8000.0,8100.0,8200.0,8300.0,8400.0,8500.0,8600.0,8700.0,8800.0,8900.0,9000.0,9100.,9200.,9300.,9400.,9500.,9600.,9700.,9800.,9900.,10000.])
    xsString = array('d', [8316.184311558545,5312.93137758767,3435.0309937336524,2304.4139502741305,1569.8115447896687,1090.9516635659693,770.901859690924,551.9206062572061,399.69535383507633,293.77957451762086,218.15126842827823,162.87634729465125,123.17685479653694,93.63530805932386,71.53697229809124,55.37491301647483,42.75271508357369,33.36378355470234,26.06619302090876,20.311817606835643,16.1180931789545,12.768644973921226,10.142660425967444,8.057990848043234,6.400465846290908,5.115134438331436,4.132099789492928,3.3193854239538734,2.6581204529344302,2.157554604919995,1.7505176068913348,1.4049155245498584,1.140055677916783,0.9253251132104159,0.7522038169131606,0.6119747371392215,0.49612321727328523,0.40492020959456737,0.33091999402250655,0.27017917021492555,0.2201693919322846,0.17830700070267996,0.14564253802358157,0.11940534430331146,0.09694948234356839,0.0793065371847468,0.06446186373361917,0.05282660618352478,
                           0.0428516302310620888,0.0348997638039910363,0.0283334766442618227,0.0231416918363592127,0.0187417921340763783,0.0153501307395115115,0.0124396534127133717,0.0100542205744949455,0.0081744954858627415,0.0066338099362915941,0.0053365711503318145,0.00430912459914657443,0.00346381039244064343,0.00278602671711227174,0.00225154342228859257,0.0018082930150063248,0.00143929440338502119,0.0011581373956044489,0.00091869589873893118,0.00073410823691329855,0.00058669382997948734,0.0004661568745858897,0.000368716655469570365,0.000293168485206959169,0.000230224535021638668,0.000182317101888465142,0.000143263359883433282,0.000112630538527214965,0.000088189175598406759,0.000068708474367442343,0.000053931726669273556,0.0000416417855733682702,0.0000326529676755488658,0.0000254365480426201587,0.0000198410151166864761,0.0000154034425617473576,0.0000119095554601641413,9.2537574320108232e-6,7.2155417437856749e-6,5.6130924422251982e-6,4.36634755605624901e-6,3.39717456406994868e-6,2.6766018046173896e-6])

    massesQstar = array('d', [1000.0,1100.0,1200.0,1300.0,1400.0,1500.0,1600.0,1700.0,1800.0,1900.0,2000.0,2100.0,2200.0,2300.0,2400.0,2500.0,2600.0,2700.0,2800.0,2900.0,3000.0,3100.0,3200.0,3300.0,3400.0,3500.0,3600.0,3700.0,3800.0,3900.0,4000.0,4100.0,4200.0,4300.0,4400.0,4500.0,4600.0,4700.0,4800.0,4900.0,5000.0,5100.0,5200.0,5300.0,5400.0,5500.0,5600.0,5700.0,5800.0,5900.0,6000.0,6100.0,6200.0,6300.0,6400.0,6500.0,6600.0,6700.0,6800.0,6900.0,7000.0,7100.0,7200.0,7300.0,7400.0,7500.0,7600.0,7700.0,7800.0,7900.0,8000.0,8100.0,8200.0,8300.0,8400.0,8500.0,8600.0,8700.0,8800.0,8900.0,9000.0])
    xsQstar = array('d', [0.4101E+03,0.2620E+03,0.1721E+03,0.1157E+03,0.7934E+02,0.5540E+02,0.3928E+02,0.2823E+02,0.2054E+02,0.1510E+02,0.1121E+02,0.8390E+01,0.6328E+01,0.4807E+01,0.3674E+01,0.2824E+01,0.2182E+01,0.1694E+01,0.1320E+01,0.1033E+01,0.8116E+00,0.6395E+00,0.5054E+00,0.4006E+00,0.3182E+00,0.2534E+00,0.2022E+00,0.1616E+00,0.1294E+00,0.1038E+00,0.8333E-01,0.6700E-01,0.5392E-01,0.4344E-01,0.3503E-01,0.2827E-01,0.2283E-01,0.1844E-01,0.1490E-01,0.1205E-01,0.9743E-02,0.7880E-02,0.6373E-02,0.5155E-02,0.4169E-02,0.3371E-02,0.2725E-02,0.2202E-02,0.1779E-02,0.1437E-02,0.1159E-02,0.9353E-03,0.7541E-03,0.6076E-03,0.4891E-03,0.3935E-03,0.3164E-03,0.2541E-03,0.2039E-03,0.1635E-03,0.1310E-03,0.1049E-03,0.8385E-04,0.6699E-04,0.5347E-04,0.4264E-04,0.3397E-04,0.2704E-04,0.2151E-04,0.1709E-04,0.1357E-04,0.1077E-04,0.8544E-05,0.6773E-05,0.5367E-05,0.4251E-05,0.3367E-05,0.2666E-05,0.2112E-05,0.1673E-05,0.1326E-05])

    graph_xsString = TGraph(len(massesString),massesString,xsString)
    graph_xsString.SetLineWidth(3)
    graph_xsString.SetLineStyle(8)
    graph_xsString.SetLineColor(9)

    graph_xsQstar = TGraph(len(massesQstar),massesQstar,xsQstar)
    graph_xsQstar.SetLineWidth(3)
    graph_xsQstar.SetLineStyle(2)
    graph_xsQstar.SetLineColor(1)

    # theory curves: qq
    massesTh = array('d', [1000.0,1100.0,1200.0,1300.0,1400.0,1500.0,1600.0,1700.0,1800.0,1900.0,2000.0,2100.0,2200.0,2300.0,2400.0,2500.0,2600.0,2700.0,2800.0,2900.0,3000.0,3100.0,3200.0,3300.0,3400.0,3500.0,3600.0,3700.0,3800.0,3900.0,4000.0,4100.0,4200.0,4300.0,4400.0,4500.0,4600.0,4700.0,4800.0,4900.0,5000.0,5100.0,5200.0,5300.0,5400.0,5500.0,5600.0,5700.0,5800.0,5900.0,6000.0,6100.0,6200.0,6300.0,6400.0,6500.0,6600.0,6700.0,6800.0,6900.0,7000.0,7100.0,7200.0,7300.0,7400.0,7500.0,7600.0,7700.0,7800.0,7900.0,8000.0,8100.0,8200.0,8300.0,8400.0,8500.0,8600.0,8700.0,8800.0,8900.0,9000.0])

    xsAxi = array('d', [0.1849E+03,0.1236E+03,0.8473E+02,0.5937E+02,0.4235E+02,0.3069E+02,0.2257E+02,0.1680E+02,0.1263E+02,0.9577E+01,0.7317E+01,0.5641E+01,0.4374E+01,0.3411E+01,0.2672E+01,0.2103E+01,0.1658E+01,0.1312E+01,0.1041E+01,0.8284E+00,0.6610E+00,0.5294E+00,0.4250E+00,0.3417E+00,0.2752E+00,0.2220E+00,0.1792E+00,0.1449E+00,0.1172E+00,0.9487E-01,0.7686E-01,0.6219E-01,0.5033E-01,0.4074E-01,0.3298E-01,0.2671E-01,0.2165E-01,0.1755E-01,0.1422E-01,0.1152E-01,0.9322E-02,0.7539E-02,0.6092E-02,0.4917E-02,0.3965E-02,0.3193E-02,0.2568E-02,0.2062E-02,0.1653E-02,0.1323E-02,0.1057E-02,0.8442E-03,0.6728E-03,0.5349E-03,0.4242E-03,0.3357E-03,0.2644E-03,0.2077E-03,0.1627E-03,0.1271E-03,0.9891E-04,0.7686E-04,0.5951E-04,0.4592E-04,0.3530E-04,0.2704E-04,0.2059E-04,0.1562E-04,0.1180E-04,0.8882E-05,0.6657E-05,0.4968E-05,0.3693E-05,0.2734E-05,0.2016E-05,0.1481E-05,0.1084E-05,0.7903E-06,0.5744E-06,0.4160E-06,0.3007E-06])
    xsDiquark = array('d', [0.5824E+02,0.4250E+02,0.3172E+02,0.2411E+02,0.1862E+02,0.1457E+02,0.1153E+02,0.9211E+01,0.7419E+01,0.6019E+01,0.4912E+01,0.4031E+01,0.3323E+01,0.2750E+01,0.2284E+01,0.1903E+01,0.1590E+01,0.1331E+01,0.1117E+01,0.9386E+00,0.7900E+00,0.6658E+00,0.5618E+00,0.4745E+00,0.4010E+00,0.3391E+00,0.2869E+00,0.2428E+00,0.2055E+00,0.1740E+00,0.1473E+00,0.1246E+00,0.1055E+00,0.8922E-01,0.7544E-01,0.6376E-01,0.5385E-01,0.4546E-01,0.3834E-01,0.3231E-01,0.2720E-01,0.2288E-01,0.1922E-01,0.1613E-01,0.1352E-01,0.1132E-01,0.9463E-02,0.7900E-02,0.6584E-02,0.5479E-02,0.4551E-02,0.3774E-02,0.3124E-02,0.2581E-02,0.2128E-02,0.1750E-02,0.1437E-02,0.1177E-02,0.9612E-03,0.7833E-03,0.6366E-03,0.5160E-03,0.4170E-03,0.3360E-03,0.2700E-03,0.2162E-03,0.1725E-03,0.1372E-03,0.1087E-03,0.8577E-04,0.6742E-04,0.5278E-04,0.4114E-04,0.3192E-04,0.2465E-04,0.1894E-04,0.1448E-04,0.1101E-04,0.8322E-05,0.6253E-05,0.4670E-05])
    xsWprime = array('d', [0.8811E+01,0.6024E+01,0.4216E+01,0.3010E+01,0.2185E+01,0.1610E+01,0.1200E+01,0.9043E+00,0.6875E+00,0.5271E+00,0.4067E+00,0.3158E+00,0.2464E+00,0.1932E+00,0.1521E+00,0.1201E+00,0.9512E-01,0.7554E-01,0.6012E-01,0.4792E-01,0.3827E-01,0.3059E-01,0.2448E-01,0.1960E-01,0.1571E-01,0.1259E-01,0.1009E-01,0.8090E-02,0.6483E-02,0.5193E-02,0.4158E-02,0.3327E-02,0.2660E-02,0.2125E-02,0.1695E-02,0.1351E-02,0.1075E-02,0.8546E-03,0.6781E-03,0.5372E-03,0.4248E-03,0.3353E-03,0.2642E-03,0.2077E-03,0.1629E-03,0.1275E-03,0.9957E-04,0.7757E-04,0.6027E-04,0.4670E-04,0.3610E-04,0.2783E-04,0.2140E-04,0.1641E-04,0.1254E-04,0.9561E-05,0.7269E-05,0.5510E-05,0.4167E-05,0.3143E-05,0.2364E-05,0.1774E-05,0.1329E-05,0.9931E-06,0.7411E-06,0.5523E-06,0.4108E-06,0.3055E-06,0.2271E-06,0.1687E-06,0.1254E-06,0.9327E-07,0.6945E-07,0.5177E-07,0.3863E-07,0.2888E-07,0.2162E-07,0.1622E-07,0.1218E-07,0.9156E-08,0.6893E-08])
    xsZprime = array('d', [0.5027E+01,0.3398E+01,0.2353E+01,0.1663E+01,0.1196E+01,0.8729E+00,0.6450E+00,0.4822E+00,0.3638E+00,0.2769E+00,0.2123E+00,0.1639E+00,0.1272E+00,0.9933E-01,0.7789E-01,0.6134E-01,0.4848E-01,0.3845E-01,0.3059E-01,0.2440E-01,0.1952E-01,0.1564E-01,0.1256E-01,0.1010E-01,0.8142E-02,0.6570E-02,0.5307E-02,0.4292E-02,0.3473E-02,0.2813E-02,0.2280E-02,0.1848E-02,0.1499E-02,0.1216E-02,0.9864E-03,0.8002E-03,0.6490E-03,0.5262E-03,0.4264E-03,0.3453E-03,0.2795E-03,0.2260E-03,0.1826E-03,0.1474E-03,0.1188E-03,0.9566E-04,0.7690E-04,0.6173E-04,0.4947E-04,0.3957E-04,0.3159E-04,0.2516E-04,0.2001E-04,0.1587E-04,0.1255E-04,0.9906E-05,0.7795E-05,0.6116E-05,0.4785E-05,0.3731E-05,0.2900E-05,0.2247E-05,0.1734E-05,0.1334E-05,0.1022E-05,0.7804E-06,0.5932E-06,0.4492E-06,0.3388E-06,0.2544E-06,0.1903E-06,0.1417E-06,0.1051E-06,0.7764E-07,0.5711E-07,0.4186E-07,0.3055E-07,0.2223E-07,0.1612E-07,0.1164E-07,0.8394E-08])

    graph_xsAxi = TGraph(len(massesTh),massesTh,xsAxi)
    graph_xsAxi.SetLineWidth(3)
    graph_xsAxi.SetLineStyle(3)
    graph_xsAxi.SetLineColor(63)

    graph_xsDiquark = TGraph(len(massesTh),massesTh,xsDiquark)
    graph_xsDiquark.SetLineWidth(3)
    graph_xsDiquark.SetLineStyle(9)
    graph_xsDiquark.SetLineColor(8)

    graph_xsWprime = TGraph(len(massesTh),massesTh,xsWprime)
    graph_xsWprime.SetLineWidth(3)
    graph_xsWprime.SetLineStyle(7)
    graph_xsWprime.SetLineColor(46)

    graph_xsZprime = TGraph(len(massesTh),massesTh,xsZprime)
    graph_xsZprime.SetLineWidth(3)
    graph_xsZprime.SetLineStyle(5)
    graph_xsZprime.SetLineColor(38)

    # limits
    if args.method == "Asymptotic" or args.method == "HybridNewGrid":
        graph_exp_2sigma = ( TGraph(len(masses_exp),masses_exp,xs_exp_limits_2sigma) if len(xs_exp_limits_2sigma) > 0 else TGraph(0) )
        graph_exp_2sigma.SetFillColor(kYellow)

        graph_exp_1sigma = ( TGraph(len(masses_exp),masses_exp,xs_exp_limits_1sigma) if len(xs_exp_limits_2sigma) > 0 else TGraph(0) )
        graph_exp_1sigma.SetFillColor(kGreen+1)

        graph_exp = ( TGraph(len(masses),masses,xs_exp_limits) if len(xs_exp_limits_2sigma) > 0 else TGraph(0) )
        #graph_exp.SetMarkerStyle(24)
        graph_exp.SetLineWidth(3)
        graph_exp.SetLineStyle(2)
        graph_exp.SetLineColor(4)

    graph_obs = TGraph(len(masses),masses,xs_obs_limits)
    graph_obs.SetMarkerStyle(20)
    graph_obs.SetLineWidth(3)
    #graph_obs.SetLineStyle(1)
    graph_obs.SetLineColor(1)

    c = TCanvas("c", "",800,800)
    c.cd()

    legend = TLegend(.58,.72,.90,.90)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.03)
    legend.SetHeader('95% CL upper limits')

    if len(xs_exp_limits_2sigma) > 0 and (args.method == "Asymptotic" or args.method == "HybridNewGrid"):
        frame = graph_exp_2sigma.GetHistogram().Clone()
    else:
        frame = graph_obs.GetHistogram().Clone()
    frame.Reset()
    frame.GetXaxis().SetTitle("Resonance mass [GeV]")
    frame.GetXaxis().SetTitleOffset(1.05)
    if args.timesAE:
        #if args.model == "ZPrime":
        #    frame.GetYaxis().SetTitle("#sigma #times BR(c#bar{c},b#bar{b}) #times #it{A} #times #epsilon [pb]")
        #else:
        frame.GetYaxis().SetTitle("#sigma #times BR(b#bar{b}) #times #it{A} #times #epsilon [pb]")
    else:
        #if args.model == "ZPrime":
        #    frame.GetYaxis().SetTitle("#sigma #times BR(c#bar{c},b#bar{b}) [pb]")
        #else:
        frame.GetYaxis().SetTitle("#sigma #times BR(b#bar{b}) [pb]")
    frame.GetYaxis().SetTitleOffset(1.2)
    if args.timesAE:
        frame.GetYaxis().SetRangeUser(1e-03,1e+01)
    else:
        frame.GetYaxis().SetRangeUser(1e-01,5e+02)
    frame.Draw("axis")

    if len(xs_exp_limits_2sigma) > 0 and (args.method == "Asymptotic" or args.method == "HybridNewGrid"):
        graph_exp_2sigma.GetXaxis().SetTitle("Resonance mass [GeV]")
        graph_exp_2sigma.GetXaxis().SetTitleOffset(1.1)
        graph_exp_2sigma.GetYaxis().SetTitle("#sigma #times #it{B} [pb]")
        graph_exp_2sigma.GetYaxis().SetTitleOffset(1.1)
        #graph_exp_2sigma.GetYaxis().SetRangeUser(1e-03,1e+02)
        #graph_exp_2sigma.GetXaxis().SetNdivisions(1005)

        graph_exp_2sigma.Draw("F")
        graph_exp_1sigma.Draw("F")
        graph_exp.Draw("L")
        graph_obs.Draw("LP")

        legend.AddEntry(graph_obs,"Observed","lp")
        legend.AddEntry(graph_exp,"Expected","lp")
        legend.AddEntry(graph_exp_1sigma,"#pm 1#sigma","F")
        legend.AddEntry(graph_exp_2sigma,"#pm 2#sigma","F")
    else:
        graph_obs.GetXaxis().SetTitle("Resonance mass [GeV]")
        graph_obs.GetYaxis().SetTitle("#sigma #times #it{B} [pb]")
        graph_obs.GetYaxis().SetTitleOffset(1.1)
        graph_obs.GetYaxis().SetRangeUser(1e-02,1e+03)
        #graph_obs.GetXaxis().SetNdivisions(1005)

        graph_obs.Draw("LP")

        legend.AddEntry(graph_obs,"Observed","lp")

        #if args.final_state == 'gg' :
        #    graph_xsS8.Draw("L")
        #elif args.final_state == 'qg' :
        #    graph_xsQstar.Draw("L")
        #    graph_xsString.Draw("L")
        #elif args.final_state == 'qq' :
        #    graph_xsAxi.Draw("L")
        #    graph_xsDiquark.Draw("L")
        #    graph_xsWprime.Draw("L")
        #    graph_xsZprime.Draw("L")
        
    legend.Draw()

    #legendTh = TLegend(.60,.72,.90,.88)
    #legendTh.SetBorderSize(0)
    #legendTh.SetFillColor(0)
    #legendTh.SetFillStyle(0)
    #legendTh.SetTextFont(42)
    #legendTh.SetTextSize(0.03)
    #legendTh.AddEntry(graph_xsAxi,"Axigluon/coloron","l")
    #legendTh.AddEntry(graph_xsDiquark,"Scalar diquark","l")
    #legendTh.AddEntry(graph_xsWprime,"W' SSM","l")
    #legendTh.AddEntry(graph_xsZprime,"Z' SSM","l")
    #legendTh.Draw()

    # draw the lumi text on the canvas
    CMS_lumi.extraText = args.extraText
    CMS_lumi.lumi_sqrtS = args.lumi_sqrtS # used with iPeriod = 0 (free form)
    iPos = 11
    iPeriod = 0

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)

    gPad.RedrawAxis()

    c.SetLogy()
    postfix = ( ('_' + args.postfix) if args.postfix != '' else '' )
    if args.noSyst:
        postfix += "_noSyst"
    if args.freezeNuisances:
        postfix += "_" + args.freezeNuisances.replace(",", "_")
    if args.fitTrigger:
        postfix += "_fitTrigger"
    elif args.correctTrigger:
        postfix += "_correctTrigger"
    if args.useMCTrigger:
        postfix += "_useMCTrigger"
    fileName = limit_config.paths["limit_plots"] + '/xs_limit_%s_%s_%s_%s.%s'%(args.method,args.analysis, args.model + postfix, args.fit_function, args.fileFormat.lower())
    if args.timesAE:
        fileName = fileName.replace("xs_limit", "xsAE_limit")
    c.SaveAs(fileName)
    print "Plot saved to '%s'"%(fileName)

    graph_obs.Print("all")
    if args.saveObjects:
        output_file = args.saveObjects
        if args.timesAE:
            output_file = output_file.replace(".root", "_timesAE.root")
        f = TFile(output_file, "RECREATE")
        if args.method == "Asymptotic" or args.method == "HybridNewGrid":
            graph_exp_2sigma.SetName("graph_exp_2sigma")
            graph_exp_2sigma.Write()
            graph_exp_1sigma.SetName("graph_exp_1sigma")
            graph_exp_1sigma.Write()
            graph_exp.SetName("graph_exp")
            graph_exp.Write()
        graph_obs.SetName("graph_obs")
        graph_obs.Write()
        f.Close()
Example #18
0
def fixOverlay():
  gPad.RedrawAxis()
Example #19
0
    def exportPlot(self,logY=True,path="./output/pT_plots",rebin=True):

        plottitle="transverse momentum of AK%i Jets (%s-Operator) in %s - %s"%(self.jetRadius,self.OpName,self.channel,self.LastCut)
        canv = TCanvas(plottitle,plottitle,600,600)
        
        #turning off the standard Statistic-Box
        gStyle.SetOptStat(0)
        gStyle.SetOptStat(0)

        legend = TLegend(0.5,0.7,0.9,0.9)
        
        drawOptions="Hist"
        if(logY):
            canv.SetLogy()
            
        stack=THStack(plottitle,plottitle)
            
        if(rebin):
            BGHist=self.BHist.Rebin(len(self.dijetbinning)-1,"new binning",self.dijetbinning)
        else:
            BGHist=self.BHist

        #Cosmetics:
        BGHist.SetFillColor(867)
        BGHist.SetLineColor(867)
        
        BGHist.SetTitle(plottitle)
        BGHist.GetXaxis().SetTitle('pT_{leading-AK8} [GeV/c^{2}]')
        BGHist.GetYaxis().SetTitle('Events')
        BGHist.GetXaxis().SetRangeUser(0,9000)
        BGHist.GetYaxis().SetRangeUser(10**(-5),10**2)
        BGHist.GetYaxis().SetTitleOffset(1.3)

        legend.AddEntry(BGHist,"QCD","f")

        BGHistErr=BGHist.Clone()
        BGHistErr.SetFillColor(rt.kGray+2)
        BGHistErr.SetFillStyle(3204)
        BGHistErr.Draw('E2')
        BGHist.Draw("SAME"+drawOptions)
        BGHistErr.Draw('E2SAME')

        stack=THStack('stack',plottitle)
        # stack.Add(BGHist)
        
        histcounter=1
        
        #number of Parameters to plot:        
        n=6
        med=(sets[self.OpName][0]-1)/2 -1

        for i in range(n):
            index= i * med/n
            if(rebin):
                hist=self.SHists[index].Rebin(len(self.dijetbinning)-1,"new binning",self.dijetbinning)
            else:
                hist=self.SHists[index]
            # hist.Add(BGHist)    
            hist.SetLineColor(histcounter)
            hist.SetMarkerStyle(8)
            hist.SetMarkerSize(0.6)
            hist.SetMarkerColor(histcounter)
            # hist.Draw("SAME"+drawOptions)
            stack.Add(hist)
            legend.AddEntry(hist,"%sjj (%s=%.1fTeV^{-4})"%(self.channel,self.OpName,self.getPoint(index)))#maybe to -6?
            histcounter+=1
        canv.SetTitle(plottitle)
        # stack.Draw('nostack'+drawOptions)
        # stack.GetXaxis().SetRangeUser(0,9000)
        # stack.Draw('nostack'+drawOptions)
        # stack.Draw('nostackep'+SAME)
        # stack.GetXaxis().SetRangeUser(0,9000)
        stack.Draw('nostackep'+'SAME')
        
        legend.Draw()
        gPad.RedrawAxis()
        canv.Update()
        canv.Print("%s/%s_AK%i_%s.eps"%(path,self.channel,self.jetRadius,self.OpName))
        del stack
Example #20
0
def plotter(plotdir,
            plot,
            xTitle,
            logY,
            channels=['VV'],
            includeData=False,
            scaleSignal=0,
            UserRange=[None, None, None, None],
            initPath=''):

    # channelTex={'WPWP':'W^{+}W^{+}', 'WPWM':'W^{+}W^{-}','WMWM':'W^{-}W^{-}','WPZ':'W^{+}Z','WMZ':'W^{-}Z','ZZ':'ZZ'}
    channelTex = {'ZZ': 'ZZ'}
    # plotstyle=[(1,1),(1,2),(2,1),(2,2),(4,1),(4,2)]
    plotstyle = [(1, 1)]
    #             0              1                       2                        3             4              5             6
    # Backgrounds=['QCD',     'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf',     'TT',         'WW',          'WZ',         'ZZ']
    # BGColors=   [rt.kAzure+7,   rt.kRed-4,              rt.kOrange-2,            rt.kGreen+2,  rt.kOrange+7,  rt.kBlue+1,   rt.kMagenta+2]
    # BGTeX=      ['QCD',        'W+JetsToQQ',           'Z+JetsToQQ',             'TTbar'],      'WW',          'WZ',         'ZZ']
    #stackOrder= [4,5,6,2,1,3,0]
    Backgrounds = [
        'QCD'
    ]  # 'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf', 'ZZ']  'TT',         'WW',          'WZ',         'ZZ']
    BGColors = [
        rt.kAzure + 7
    ]  #,              rt.kOrange-2,            rt.kGreen+2],  rt.kOrange+7,  rt.kBlue+1,   rt.kMagenta+2]
    BGTeX = ['QCD']  #

    stackOrder = [0]

    PreSelection = [
        'nocuts', 'common', 'corrections', 'cleaner', 'softdropmassCorr',
        'AK4pfidfilter', 'AK8pfidfilter', 'invMAk8sel', 'detaAk8sel',
        'AK8N2sel'
    ]
    Selection = [
        'preselection', 'softdropAK8sel', 'tau21sel', 'deltaR48', 'VVRegion',
        'AK4N2sel', 'OpSignsel', 'detaAk4sel', 'invMAk4sel_1p0', 'Kin_AK8'
    ]

    cutnames = [
        'cleaner', 'AK8N2sel', 'invMAk8sel', 'detaAk8sel', 'softdropAK8sel',
        'tau21sel', 'AK4cleaner', 'AK4N2sel', 'OpSignsel', 'detaAk4sel',
        'invMAk4sel_1p0'
    ]

    cuts = {
        'cleaner':
        '#splitline{p_{T-AK8} > 200 GeV, |#eta_{AK8}| < 2.5}{p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0}',
        'AK8N2sel': 'N_{AK8} #geq 2',
        'invMAk8sel': 'M_{jj-AK8} > 1050 GeV',
        'detaAk8sel': '|#Delta#eta_{jj-AK8}|<1.3',
        'softdropAK8sel': '65 GeV <M_{SD}< 105 GeV',
        'tau21sel': '0 #leq #tau_{2}/#tau_{1}<0.45',
        # 'AK4cleaner':'p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0',
        'AK4cleaner': '',
        'AK4N2sel': 'N_{AK4} #geq 2',
        'OpSignsel': '#eta_{1-AK4} #eta_{2-AK4} < 0',
        'detaAk4sel': '|#Delta#eta_{jj-AK4}| > 3.0',
        'invMAk4sel_1p0': 'M_{jj-AK4} > 1.0 TeV'
    }

    VV = ('VV' in channels)
    seperate = (not VV)
    if VV:
        #channels=["WPWP","WPWM","WMWM","WPZ","WMZ","ZZ"]
        channels = ["ZZ"]

    plottitle = plotdir + '_' + plot

    lumi = 36.814
    xLabelSize = 18.
    yLabelSize = 18.
    xTitleSize = 20.
    yTitleSize = 22.
    xTitleOffset = 4.
    yTitleOffset = 1.3

    printout = False
    Portrait = True
    cutname = False
    ratio = includeData

    if ('highbin' in plot):
        binning = 'dijetbinning'
    else:
        binning = 'default'

    if (Portrait):
        canvX = 600
        canvY = 600
    else:
        canvX = 900
        canvY = 675

    if (plotdir in PreSelection):
        region = 'PreSelection'
        initPath = ''
        referenceHistPath = 'detaAk8sel/N_pv'
        if (PreSelection.index(plotdir) < 4 and ('softdrop' in plot)):
            return 'SofdropMass not filled yet!'
    else:
        region = 'SignalRegion'
        referenceHistPath = 'tau21sel/N_pv'
    referenceHistPath = plotdir + '/' + plot

    if (initPath == ''):
        path = '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/%s' % region
    else:
        path = initPath
    outputPath = path.replace(
        '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/SignalRegion',
        'plots/')
    if (plotdir in PreSelection):
        CutNumber = PreSelection.index(plotdir)
    else:
        CutNumber = Selection.index(plotdir)
    outputPath = outputPath + '/%02i_%s' % (CutNumber, plotdir) + '/'
    if (printout):
        print('InputPath:', path)
        print('OutputPath:', outputPath)
    #check if OutputPath exists - and if not create it!
    if not os.path.exists(outputPath):
        os.makedirs(outputPath)
    # path='/home/albrec/Master/signal/'
    scaleVV = (scaleSignal != 0)
    VVScale = scaleSignal

    if (UserRange[2] == None or UserRange[3] == None):
        YRangeUser = False
        Ymin = UserRange[2]
        Ymax = UserRange[3]
    else:
        YRangeUser = True
        Ymin = UserRange[2]
        Ymax = UserRange[3]

    if (UserRange[0] == None or UserRange[1] == None):
        XRangeUser = False
        Xmin = UserRange[0]
        Xmax = UserRange[1]
    else:
        XRangeUser = True
        Xmin = UserRange[0]
        Xmax = UserRange[1]

    # YRangeUser=False
    # Ymin=0.11
    # Ymax=9*10**3

    # XRangeUser=False
    # Xmin=0
    # Xmax=6000.

    gROOT.ProcessLine("gErrorIgnoreLevel = 2001;")
    SFiles = []
    for i in range(len(channels)):
        SFiles.append(
            TFile(
                path +
                "/uhh2.AnalysisModuleRunner.MC.MC_aQGC_%sjj_hadronic_2016v3.root"
                % channels[i]))
#uhh2.AnalysisModuleRunner.MC.MC_aQGC_ZZjj_hadronic_2016v3.root
##Open Files to get BackgroundHist:
    BFiles = []
    for i in range(len(Backgrounds)):
        BFiles.append(
            TFile(path +
                  "/uhh2.AnalysisModuleRunner.MC.MC_%s.root" % Backgrounds[i]))

    #Open File to get DataHist:

# DataFile = TFile(path+"/uhh2.AnalysisModuleRunner.Data.DATA.root")

#gROOT.ProcessLine( "gErrorIgnoreLevel = 0;")

    if (includeData == True):
        #calculate QCDscale with Integrals from the following Histogram:
        # referenceHistPath = 'tau21sel/N_AK4'
        # referenceHistPath = 'detaAk8sel/N_pv'
        # referenceHistPath = 'tau21sel/met_pt_over_sumptAK8_2'
        QCDscale = float(DataFile.Get(referenceHistPath).Integral())
        QCDNorm = 1
        for i in range(len(BFiles)):
            if ('QCD' in BFiles[i].GetName()):
                QCDNorm = float(BFiles[i].Get(referenceHistPath).Integral())
            else:
                QCDscale -= float(BFiles[i].Get(referenceHistPath).Integral())
        QCDscale /= QCDNorm
    else:
        QCDscale = 1.0
    if (printout):
        print('using QCDscale:', QCDscale)

    SHists = []
    for i in range(len(channels)):
        SHists.append(SFiles[i].Get(plotdir + '/' + plot))

    BHists = []
    for i in range(len(BFiles)):
        BHists.append(BFiles[i].Get(plotdir + '/' + plot))
        if ('QCD' in BFiles[i].GetName()):
            BHists[-1].Scale(QCDscale)

    #if(includeData):
    #    DataHist=DataFile.Get(plotdir+'/'+plot)

    if (binning == 'dijetbinning'):
        fitbinning = array('d')
        binwidth = 200
        NBins = (14000 / binwidth) - ((1040 / binwidth) + 1)
        NBins = int(NBins)
        for i in range(NBins + 1):
            fitbinning.append(1050 + i * binwidth)

        for i in range(len(channels)):
            SHists[i] = SHists[i].Rebin(NBins, "new binning", fitbinning)
        for i in range(len(Backgrounds)):
            BHists[i] = BHists[i].Rebin(NBins, "new binning", fitbinning)

        if (includeData):
            DataHist = DataHist.Rebin(NBins, "new binning", fitbinning)

    canv = TCanvas(plottitle, plottitle, canvX, canvY)

    yplot = 0.7
    yratio = 0.3
    ymax = 1.0
    xmax = 1.0
    xmin = 0.0
    if (ratio):
        plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot, xmax, ymax)
        ratiopad = TPad("ratiopad", "Ratio", xmin, ymax - yplot - yratio, xmax,
                        ymax - yplot)
    else:
        plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot - yratio, xmax,
                       ymax)

    plotpad.SetTopMargin(0.08)
    plotpad.SetLeftMargin(0.1)
    plotpad.SetRightMargin(0.05)
    plotpad.SetTicks()
    plotpad.Draw()

    if (ratio):
        plotpad.SetBottomMargin(0.016)
        ratiopad.SetTopMargin(0.016)
        ratiopad.SetBottomMargin(0.35)
        ratiopad.SetLeftMargin(0.1)
        ratiopad.SetRightMargin(0.05)
        ratiopad.SetTicks()
        ratiopad.Draw()
    else:
        plotpad.SetBottomMargin(0.1)

    if (logY):
        plotpad.SetLogy()
        canv.SetLogy()
    if ('-logX' in xTitle):
        plotpad.SetLogx()
        if (ratio):
            ratiopad.SetLogx()
        canv.SetLogx()

    drawOptions = "HE"

    stack = THStack(plottitle, plottitle)

    BHist = THStack(plottitle, plottitle)

    # for i in range(len(Backgrounds)):
    for i in stackOrder:
        # BHists[i].SetFillColor(BGColors[i])
        BHists[i].SetLineColor(BGColors[i])
        BHist.Add(BHists[i], 'Hist')

    BHist.SetTitle(plottitle)

    BHistErr = BHists[0].Clone()
    for i in range(1, len(Backgrounds)):
        BHistErr.Add(BHists[i])

    BHistErr.SetFillStyle(3204)
    BHistErr.SetFillColor(rt.kGray + 2)
    BHistErr.SetLineColor(1)

    BGMax = BHist.GetMaximum()
    SIGMax = 0
    #if(VV):       #new
    #    SIGMax=VVsum.GetMaximum()
    #else:
    for i in range(len(channels)):
        tmpmax = SHists[i].GetMaximum()
        if (tmpmax > SIGMax):
            SIGMax = tmpmax
    if (scaleVV):
        SIGMax = SIGMax * VVScale
    if (logY):
        MAX = 0.9 * float(10**(magnitude(max(BGMax, SIGMax)) + 1))
        MIN = float(10**(magnitude(max(BGMax, SIGMax)) - 5))
        MIN += float(10**(magnitude(MIN)))
        legendMIN = math.log(max(BGMax, SIGMax)) / math.log(MAX)
    else:
        MAX = (1.0 / 0.8) * max(BGMax, SIGMax)
        legendMIN = 0.7
        MIN = 0.
    legendMIN = (legendMIN * 0.7) + 0.3 - 0.016

    legend = TLegend(0.5, 0.75, 0.85, 0.89)
    legend.SetFillStyle(0)
    legend.SetTextSize(0.02)
    legend.SetMargin(0.4)
    legend.SetNColumns(2)
    legend.SetColumnSeparation(0.3)

    if (includeData):
        DataHist.SetMarkerStyle(8)
        DataHist.SetLineColor(1)
        DataHist.SetTitle(plottitle)

    if VV:
        for i in range(len(channels)):
            if (i == 0):
                VVsum = SHists[i].Clone()
            else:
                VVsum.Add(SHists[i])
        legentry = 'VVjj'
        if (scaleVV):
            VVsum.Scale(VVScale)
            legentry += ' *%0.f' % VVScale
        VVsum.SetLineColor(1)
        VVsum.SetLineStyle(plotstyle[0][1])
        VVsum.SetLineWidth(2)
        legend.AddEntry(VVsum, legentry)
    else:
        for i in range(len(channels)):
            SHists[i].SetLineColor(plotstyle[i][0])
            SHists[i].SetLineStyle(plotstyle[i][1])
            SHists[i].SetLineWidth(2)
            legentry = "%sjj" % channelTex[channels[i]]
            if (scaleVV):
                SHists[i].Scale(VVScale)
                legentry += ' *%.2E' % VVScale
            legend.AddEntry(SHists[i], legentry)

    for i in stackOrder:
        legend.AddEntry(BHists[i], BGTeX[i], "f")
    legend.AddEntry(BHistErr, "stat. Uncertainty", "f")

    if (includeData):
        legend.AddEntry(DataHist, "Data", "lep")

    canv.SetTitle(plottitle)

    BHistErr.GetYaxis().SetTitle('Events')
    BHistErr.GetYaxis().SetRangeUser(MIN, MAX)
    BHistErr.GetYaxis().SetTitleFont(43)
    BHistErr.GetYaxis().SetTitleSize(yTitleSize)
    BHistErr.GetYaxis().SetTitleOffset(yTitleOffset)
    BHistErr.GetYaxis().SetLabelFont(43)
    BHistErr.GetYaxis().SetLabelSize(yLabelSize)
    if (ratio):
        BHistErr.GetXaxis().SetTitleSize(0.0)
        BHistErr.GetXaxis().SetLabelSize(0.0)
    else:
        BHistErr.GetXaxis().SetTitle(xTitle)
        BHistErr.GetXaxis().SetTitleFont(43)
        BHistErr.GetXaxis().SetTitleSize(xTitleSize)
        # BHistErr.GetXaxis().SetTitleOffset(xTitleOffset)
        BHistErr.GetXaxis().SetTitleOffset(1.2)
        BHistErr.GetXaxis().SetLabelFont(43)
        BHistErr.GetXaxis().SetLabelSize(xLabelSize)
        # BHistErr.GetXaxis().SetTickLength(0.08)
        # BHistErr.GetXaxis().SetNdivisions(506)

    if (YRangeUser):
        BHistErr.GetYaxis().SetRangeUser(Ymin, Ymax)
    if (XRangeUser):
        BHistErr.GetXaxis().SetRangeUser(Xmin, Xmax)

    plotpad.cd()

    BHistErr.Draw("E2")
    BHist.Draw("HistSAME")
    BHistErr.Draw("E2SAME")

    if (VV):
        VVsum.Draw("SAME" + drawOptions)
    elif ('-noSig' not in xTitle):
        for i in range(len(channels)):
            SHists[i].Draw("SAME" + drawOptions)

    if (includeData):
        DataHist.Draw("APE1SAME")

    plotpad.RedrawAxis()
    if (ratio):
        ratiopad.cd()

        if (includeData):
            ratioHist = DataHist.Clone()
        else:
            ratioHist = BHistErr.Clone()
        ratioHist.SetLineColor(rt.kBlack)
        # ratioHist.Sumw2()
        ratioHist.SetStats(0)
        ratioHist.Divide(BHistErr)
        ratioHist.SetMarkerStyle(21)
        ratioHist.SetMarkerSize(0.7)

        #Yaxis
        ratioHist.GetYaxis().SetRangeUser(0.3, 1.7)
        ratioHist.GetYaxis().SetTitle("Data/BG")
        ratioHist.GetYaxis().CenterTitle()
        ratioHist.GetYaxis().SetTitleFont(43)
        ratioHist.GetYaxis().SetTitleSize(yTitleSize)
        ratioHist.GetYaxis().SetTitleOffset(yTitleOffset)
        ratioHist.GetYaxis().SetLabelFont(43)
        ratioHist.GetYaxis().SetLabelSize(yLabelSize)
        ratioHist.GetYaxis().SetNdivisions(506)
        #Xaxis
        ratioHist.GetXaxis().SetTitle(xTitle)
        ratioHist.GetXaxis().SetTitleFont(43)
        ratioHist.GetXaxis().SetTitleSize(xTitleSize)
        ratioHist.GetXaxis().SetTitleOffset(xTitleOffset)
        ratioHist.GetXaxis().SetLabelFont(43)
        ratioHist.GetXaxis().SetLabelSize(xLabelSize)
        ratioHist.GetXaxis().SetTickLength(0.08)
        ratioHist.GetXaxis().SetNdivisions(506)

        # if(YRangeUser):
        #     ratioHist.GetYaxis().SetRangeUser(Ymin,Ymax)
        if (XRangeUser):
            ratioHist.GetXaxis().SetRangeUser(Xmin, Xmax)
            ratioXMin = Xmin
            ratioXMax = Xmax
        else:
            ratioXMin = ratioHist.GetXaxis().GetXmin()
            ratioXMax = ratioHist.GetXaxis().GetXmax()
        ratioHist.Draw("ep")

        zeropercent = TLine(ratioXMin, 1, ratioXMax, 1)
        zeropercent.Draw()
        plus10percent = TLine(ratioXMin, 1.1, ratioXMax, 1.1)
        plus10percent.SetLineStyle(rt.kDashed)
        plus10percent.Draw()
        minus10percent = TLine(ratioXMin, 0.9, ratioXMax, 0.9)
        minus10percent.SetLineStyle(rt.kDashed)
        minus10percent.Draw()

    canv.cd()
    gPad.RedrawAxis()
    legend.Draw()

    latex = TLatex()
    latex.SetNDC(kTRUE)
    latex.SetTextSize(20)
    latex.DrawLatex(0.69, 0.953, "%.2f fb^{-1} (13 TeV)" % lumi)
    latex.DrawLatex(0.1, 0.953, "private work")

    lastcut = 'nocuts'
    for cut in cutnames:
        if cut in plotdir:
            lastcut = cut

    if (not (lastcut == 'nocuts') and cutname):
        # latex.SetTextSize(0.03)
        latex.SetTextSize(15)
        for l in range(cutnames.index(lastcut) + 1):
            latex.DrawLatex(0.12, 0.8 - l * 0.04, cuts[cutnames[l]])

    canv.Update()
    canv.Print(outputPath + '/%s_%s.pdf' % (plotdir, plot))
    #prevents memory leak in Canvas Creation/Deletion
    #see: https://root.cern.ch/root/roottalk/roottalk04/2484.html
    gSystem.ProcessEvents()
    if (ratio):
        del ratiopad
    del plotpad, canv
    # gc.collect()
    return 'done!'
Example #21
0
def main():
    # usage description
    usage = "Example: ./scripts/plotSignificance.py -l logs -f qq --massrange 1200 6000 100"

    # input parameters
    parser = ArgumentParser(description='Script that plots significance for specified mass points',epilog=usage)

    parser.add_argument("-M", "--method", dest="method",
                        choices=['MaxLikelihoodFit'],
                        default='MaxLikelihoodFit',
                        help="Method to calculate upper limits",
                        metavar="METHOD")

    results_group = parser.add_mutually_exclusive_group(required=True)
    results_group.add_argument("-l", "--logs_path", dest="logs_path",
                               help="Path to log files",
                               metavar="LOGS_PATH")
    results_group.add_argument("-r", "--results_file", dest="results_file",
                               help="Path to a file containing results",
                               metavar="RESULTS_FILE")

    parser.add_argument("-f", "--final_state", dest="final_state", required=True,
                        help="Final state (e.g. qq, qg, gg)",
                        metavar="FINAL_STATE")

    parser.add_argument("--postfix", dest="postfix", default='', help="Postfix for the output plot name (default: %(default)s)")

    parser.add_argument("--fileFormat", dest="fileFormat", default='pdf', help="Format of the output plot (default: %(default)s)")

    parser.add_argument("--extraText", dest="extraText", default='Simulation Preliminary', help="Extra text on the plot (default: %(default)s)")

    parser.add_argument("--lumi_sqrtS", dest="lumi_sqrtS", default='1 fb^{-1} (13 TeV)', help="Integrated luminosity and center-of-mass energy (default: %(default)s)")

    parser.add_argument("--printResults", dest="printResults", default=False, action="store_true", help="Print results to the screen")

    mass_group = parser.add_mutually_exclusive_group(required=True)
    mass_group.add_argument("--mass",
                            type=int,
                            nargs = '*',
                            default = 1000,
                            help="Mass can be specified as a single value or a whitespace separated list (default: %(default)i)"
                            )
    mass_group.add_argument("--massrange",
                            type=int,
                            nargs = 3,
                            help="Define a range of masses to be produced. Format: min max step",
                            metavar = ('MIN', 'MAX', 'STEP')
                            )
    mass_group.add_argument("--masslist",
                            help = "List containing mass information"
                            )

    args = parser.parse_args()

    # mass points for which resonance shapes will be produced
    input_masses = []

    if args.massrange != None:
        MIN, MAX, STEP = args.massrange
        input_masses = range(MIN, MAX+STEP, STEP)
    elif args.masslist != None:
        # A mass list was provided
        print "Will create mass list according to", args.masslist
        masslist = __import__(args.masslist.replace(".py",""))
        input_masses = masslist.masses
    else:
        input_masses = args.mass
    # sort masses
    input_masses.sort()

    # arrays holding results
    masses = array('d')
    sig = array('d')
    sig_ex = array('d')
    sig_eyl = array('d')
    sig_eyh = array('d')

    if args.logs_path != None:

        logs_path = os.path.join(os.getcwd(),args.logs_path)

        for mass in input_masses:

            print ">> Reading results for %s resonance with m = %i GeV..."%(args.final_state, int(mass))

            masses.append(mass)

            logName = 'signal_xs_%s_%s_m%i.log'%(args.method,args.final_state,int(mass))

            log_file = open(os.path.join(logs_path,logName),'r')

            # read the log file
            for line in log_file:
                if re.search("^Best fit r:", line):
                  sig.append(float(line.split()[3]))
                  sig_eyl.append(float(line.split()[4].split('/')[0].lstrip('-')))
                  sig_eyh.append(float(line.split()[4].split('/')[1].lstrip('+')))

            sig_ex.append(0.)

            if len(masses) != len(sig):
                print "** WARNING: ** Fit failed for m =", int(mass), "GeV. Setting signal cross section to 0."
                sig.append(0.)
                sig_eyl.append(0.)
                sig_eyh.append(0.)
    else:
        print ">> Importing results..."

        sys.path.insert(0, os.path.dirname(args.results_file))

        results = __import__(os.path.basename(args.results_file).replace(".py",""))

        all_masses = np.array(results.masses)
        indices = []

        # search for indices of input_masses
        for mass in input_masses:
            where = np.where(all_masses==mass)[0]
            if len(where) == 0:
                print "** WARNING: ** Cannot find results for m =", int(mass), "GeV in the provided results file. Skipping this mass point."
            indices.extend( where )

        # sort indices
        indices.sort()

        for i in indices:
            masses.append( results.masses[i] )
            sig.append( results.sig[i] )
            sig_ex.append( results.sig_ex[i] )
            sig_eyl.append( results.sig_eyl[i] )
            sig_eyh.append( results.sig_eyh[i] )


    if args.printResults:
        print "masses =", masses.tolist()
        print "sig =", sig.tolist()
        print "sig_ex =", sig_ex.tolist()
        print "sig_eyl =", sig_eyl.tolist()
        print "sig_eyh =", sig_eyh.tolist()

    # create final arrays
    sig_pos = array('d')
    sig_exl = array('d')
    sig_exh = array('d')

    # fill final arrays
    for i in range(0,len(masses)):
        sig_pos.append(sig[i] if sig[i]>0. else 0.)
        sig_exl.append(sig_ex[i])
        sig_exh.append(sig_ex[i])
        sig_eyl.append(sig_eyl[i] if sig[i]>0. else 0.)
        sig_eyh.append(sig_eyh[i])

    # import ROOT stuff
    from ROOT import kTRUE, kFALSE, gROOT, gStyle, gPad, TGraphAsymmErrors, TCanvas, TLegend
    from ROOT import kGreen, kYellow, kWhite, kRed, kBlue

    gROOT.SetBatch(kTRUE);
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)
    gStyle.SetTitleFont(42, "XYZ")
    gStyle.SetTitleSize(0.06, "XYZ")
    gStyle.SetLabelFont(42, "XYZ")
    gStyle.SetLabelSize(0.05, "XYZ")
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetFrameBorderMode(0)
    gStyle.SetCanvasColor(kWhite)
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)
    gStyle.SetPadLeftMargin(0.15)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadBottomMargin(0.15)
    gROOT.ForceStyle()

    graph_sig = TGraphAsymmErrors(len(masses),masses,sig_pos,sig_exl,sig_exh,sig_eyl,sig_eyh)
    graph_sig.GetXaxis().SetTitle("%s resonance mass [GeV]"%(args.final_state))
    graph_sig.GetYaxis().SetTitle("Signal cross section [pb]")
    graph_sig.GetYaxis().SetTitleOffset(1.2)
    graph_sig.GetYaxis().SetRangeUser(1e-4,2e2)
    graph_sig.SetMarkerStyle(20)
    graph_sig.SetMarkerColor(1)
    graph_sig.SetLineWidth(2)
    graph_sig.SetLineStyle(1)
    graph_sig.SetLineColor(1)

    c = TCanvas("c", "",800,800)
    c.cd()

    graph_sig.Draw("AP")

    # draw the lumi text on the canvas
    CMS_lumi.extraText = args.extraText
    CMS_lumi.lumi_sqrtS = args.lumi_sqrtS # used with iPeriod = 0 (free form)
    iPos = 11
    iPeriod = 0

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)

    gPad.RedrawAxis()

    c.SetLogy()
    c.SetGridx()
    c.SetGridy()
    fileName = 'signal_xs_%s_%s.%s'%(args.method,args.final_state + ( ('_' + args.postfix) if args.postfix != '' else '' ), args.fileFormat.lower())
    c.SaveAs(fileName)
    print "Plot saved to '%s'"%(fileName)
def main():
    # usage description
    usage = "Example: ./scripts/plotSignificance.py -l logs -f qq --massrange 1200 6000 100"
    # input parameters
    parser = ArgumentParser(
        description='Script that plots significance for specified mass points',
        epilog=usage)
    parser.add_argument('analysis', type=str, help='Analysis name')
    parser.add_argument('model', type=str, help='Model name')

    parser.add_argument("-M",
                        "--method",
                        dest="method",
                        choices=['ProfileLikelihood', 'HybridNew', 'theta'],
                        default='ProfileLikelihood',
                        help="Method to calculate upper limits",
                        metavar="METHOD")
    parser.add_argument(
        '--fit_function',
        type=str,
        default="dijet4",
        help="Name of fit function used for background estimate")

    parser.add_argument(
        "--sigRange",
        dest="sigRange",
        type=float,
        default=2.5,
        help="Significance range to plot (default: %(default)f)")

    parser.add_argument(
        "--postfix",
        dest="postfix",
        default='',
        help="Postfix for the output plot name (default: %(default)s)")

    parser.add_argument(
        "--fileFormat",
        dest="fileFormat",
        default='pdf',
        help="Format of the output plot (default: %(default)s)")

    parser.add_argument("--extraText",
                        dest="extraText",
                        default='Preliminary',
                        help="Extra text on the plot (default: %(default)s)")

    parser.add_argument(
        "--lumi_sqrtS",
        dest="lumi_sqrtS",
        default='19.7 fb^{-1} (13 TeV)',
        help=
        "Integrated luminosity and center-of-mass energy (default: %(default)s)"
    )

    parser.add_argument("--printResults",
                        dest="printResults",
                        default=False,
                        action="store_true",
                        help="Print results to the screen")
    parser.add_argument('--fitTrigger',
                        action='store_true',
                        help="Use trigger fit")
    parser.add_argument('--correctTrigger',
                        action='store_true',
                        help="Use trigger correction")
    parser.add_argument('--useMCTrigger',
                        action='store_true',
                        help="Use MC trigger emulation")
    parser.add_argument("--noSyst",
                        action="store_true",
                        help="Make plots for limits without systematics")
    parser.add_argument(
        "--freezeNuisances",
        type=str,
        help="Make plots for limits with frozen nuisance parameters")

    mass_group = parser.add_mutually_exclusive_group(required=True)
    mass_group.add_argument(
        "--mass",
        type=int,
        nargs='*',
        default=1000,
        help=
        "Mass can be specified as a single value or a whitespace separated list (default: %(default)i)"
    )
    mass_group.add_argument(
        "--massrange",
        type=int,
        nargs=3,
        help="Define a range of masses to be produced. Format: min max step",
        metavar=('MIN', 'MAX', 'STEP'))
    mass_group.add_argument("--masslist",
                            help="List containing mass information")

    args = parser.parse_args()

    # mass points for which resonance shapes will be produced
    input_masses = []

    if args.massrange != None:
        MIN, MAX, STEP = args.massrange
        input_masses = range(MIN, MAX + STEP, STEP)
    elif args.masslist != None:
        # A mass list was provided
        print "Will create mass list according to", args.masslist
        masslist = __import__(args.masslist.replace(".py", ""))
        input_masses = masslist.masses
    else:
        input_masses = args.mass
    # sort masses
    input_masses.sort()

    # arrays holding results
    masses = array('d')
    significances = array('d')
    p0_values = array('d')

    for mass in input_masses:
        masses.append(mass)
        #print ">> Reading results for resonance with m = %i GeV..."%(int(mass))
        log_file = open(
            limit_config.get_combine_log_path(
                args.analysis,
                args.model,
                mass,
                args.fit_function,
                args.method,
                what="significance",
                systematics=(not args.noSyst),
                frozen_nps=args.freezeNuisances,
                fitTrigger=args.fitTrigger,
                correctTrigger=args.correctTrigger,
                useMCTrigger=args.useMCTrigger), 'r')

        if args.method == 'theta':
            logName = logName.replace('significance_', '')

        # read the log file
        for line in log_file:
            if args.method == 'theta':
                if re.search("^{'signal': {'Z':", line):
                    significances.append(
                        float(line.split()[-1].lstrip('[').rstrip('}').rstrip(
                            ']')))
            else:
                if re.search("^Significance:", line):
                    significances.append(float(line.split()[1]))
                elif re.search("^Null p-value:", line):
                    p0_values.append(float(line.split()[2]))

        if len(masses) != len(significances):
            print "** ERROR: ** Could not find significance for m =", int(
                mass), "GeV. Aborting."
            sys.exit(1)
        if len(masses) != len(p0_values):
            print "** ERROR: ** Could not find p0 value for m =", int(
                mass), "GeV. Aborting."
            sys.exit(1)
        # Allow only positive fluctuations
        if significances[-1] < 0:
            significances[-1] = 0.

    if args.printResults:
        print "masses =", masses.tolist()
        print "significances =", significances.tolist()
        print "p0_values =", p0_values.tolist()

    # import ROOT stuff
    from ROOT import kTRUE, kFALSE, gROOT, gStyle, gPad, TGraph, TCanvas, TLegend
    from ROOT import kGreen, kYellow, kWhite, kRed, kBlue

    gROOT.SetBatch(kTRUE)
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)
    gStyle.SetTitleFont(42, "XYZ")
    gStyle.SetTitleSize(0.06, "XYZ")
    gStyle.SetLabelFont(42, "XYZ")
    gStyle.SetLabelSize(0.05, "XYZ")
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetFrameBorderMode(0)
    gStyle.SetCanvasColor(kWhite)
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)
    gStyle.SetPadLeftMargin(0.15)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadBottomMargin(0.15)
    gROOT.ForceStyle()

    graph_sig = TGraph(len(masses), masses, significances)
    graph_sig.GetXaxis().SetTitle("Resonance mass [GeV]")
    graph_sig.GetYaxis().SetTitle("p_0")
    graph_sig.GetYaxis().SetTitleOffset(1.2)
    graph_sig.GetYaxis().SetRangeUser(0., args.sigRange)
    graph_sig.SetLineWidth(2)
    graph_sig.SetLineColor(kRed)
    graph_sig.SetMarkerStyle(21)
    graph_sig.SetMarkerSize(1)
    graph_sig.SetMarkerColor(kBlue)

    c = TCanvas("c", "", 800, 800)
    c.cd()

    graph_sig.Draw("ALP")

    # draw the lumi text on the canvas
    CMS_lumi.extraText = args.extraText
    CMS_lumi.lumi_sqrtS = args.lumi_sqrtS  # used with iPeriod = 0 (free form)
    iPos = 11
    iPeriod = 0

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)

    gPad.RedrawAxis()

    c.SetGridx()
    c.SetGridy()
    fileName = limit_config.paths[
        "limit_plots"] + '/significance_%s_%s_%s_%s.%s' % (
            args.method, args.analysis, args.model + args.postfix,
            args.fit_function, args.fileFormat.lower())
    c.SaveAs(fileName)
    #print "Significance plot saved to '%s'"%(fileName)

    graph_p0 = TGraph(len(masses), masses, p0_values)
    graph_p0.GetXaxis().SetTitle("Resonance mass [GeV]")
    graph_p0.GetYaxis().SetTitle("p_{0} (local)")
    graph_p0.GetYaxis().SetTitleOffset(1.2)
    graph_p0.GetYaxis().SetRangeUser(1.e-3, 1.)
    graph_p0.SetLineWidth(2)
    graph_p0.SetLineColor(kRed)
    graph_p0.SetMarkerStyle(21)
    graph_p0.SetMarkerSize(1)
    graph_p0.SetMarkerColor(kBlue)
    c_p0 = TCanvas("c_p0", "", 800, 800)
    c_p0.SetLogy()
    c_p0.cd()

    graph_p0.Draw("ALP")

    # draw the lumi text on the canvas
    # draw the lumi text on the canvas
    CMS_lumi.extraText = args.extraText
    CMS_lumi.lumi_sqrtS = args.lumi_sqrtS  # used with iPeriod = 0 (free form)
    iPos = 11
    iPeriod = 0

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)

    #Root.CMSLabel(0.2, 0.2, "Internal", 1, 0.65)

    gPad.RedrawAxis()

    c_p0.SetGridx()
    c_p0.SetGridy()
    fileName = limit_config.paths["limit_plots"] + '/p0_%s_%s_%s_%s.%s' % (
        args.method, args.analysis, args.model + args.postfix,
        args.fit_function, args.fileFormat.lower())
    c_p0.SaveAs(fileName)
    print "p0 plot saved to '%s'" % (fileName)
Example #23
0
def makePlot(hName, CR, isQCDMC, isData, isLog, isRatio):
    '''
    We first draw stacked histograms then data then unc band.
    The ratio of data and background is drawn next in a separate
    pad.
    '''
    #Divide canvas for the ratio plot
    canvas = TCanvas()
    if isRatio and isData:
        canvas.Divide(1,2)
        canvas.cd(1)
        gPad.SetRightMargin(0.03);
        gPad.SetPad(xPadRange[0],yPadRange[2],xPadRange[1],yPadRange[3]);
        gPad.SetTopMargin(0.09);
        gPad.SetBottomMargin(padGap);
        #gPad.SetTickx(0);
        gPad.RedrawAxis();
    if isLog:
        gPad.SetLogy(True);

    #Get nominal histograms
    #dataHist, bkgHists, qcdMCHist, qcdDDHist = getBaseHists(fileDict, hName, CR)
    dataHist, bkgHists, qcdMCHist = getBaseHists(fileDict, hName, CR)
    hSumOtherBkg = bkgHists[0].Clone("hSumOtherBkg")
    hSumOtherBkg.Reset()
    hAllBkgs = bkgHists
    for bkgHist in bkgHists:
        hColor = Samples[bkgHist.GetName().split("_")[0]][1]
        hSumOtherBkg.Add(bkgHist)
    hSumAllBkg = hSumOtherBkg.Clone("hSumAllBkg")
    if isQCDMC:
        hSumAllBkg.Add(qcdMCHist[0])
        hAllBkgs.append(qcdMCHist[0])
    #else:
    #    hSumAllBkg.Add(qcdDDHist[0])
    #    hAllBkgs.append(qcdDDHist[0])

    #Stack nominal hists
    xTitle = histograms[hName][0]
    yTitle = histograms[hName][1]
    hStack = THStack(hName,hName)
    hForStack = sortHists(hAllBkgs, False)
    for h in hForStack: 
        sampleName = h.GetName().split("_")[0]
        decoHist(h, xTitle, yTitle, Samples[sampleName][1])
        hStack.Add(h)
    hStack.SetMinimum(1.0)
    if isLog:
        hStack.SetMaximum(100*hStack.GetMaximum())
    else: 
        hStack.SetMaximum(1.3*hStack.GetMaximum())
    hStack.Draw("HIST")
    decoHistStack(hStack, xTitle, yTitle)

    #Get histograms for the difference between nominal and syst up/down
    hSumOtherBkgUps, hQCDUps = getSystHists(fileDict, hName, CR, "Up")
    hSumOtherBkgDowns, hQCDDowns = getSystHists(fileDict, hName, CR, "Down")
    hDiffUp = hSumOtherBkg.Clone("hDiffUp")
    hDiffUp.Reset()
    hDiffDown = hSumOtherBkg.Clone("hDiffDown")
    hDiffDown.Reset()
    for hUp in hSumOtherBkgUps:
        hDiff = hUp.Clone("hDiff")
        hDiff.Add(hSumOtherBkg, -1)    
        hDiffUp.Add(hDiff)
        print "hDiffUp = ", hDiffUp.Integral()
    for hDown in hSumOtherBkgDowns:
        hDiff = hSumOtherBkg.Clone("hDiff")
        hDiff.Add(hDown, -1)    
        hDiffDown.Add(hDiff)
    if isQCDMC:
        for hUp in hQCDUps:
            hDiff = hUp.Clone("hDiff")
            hDiff.Add(qcdMCHist[0], -1)    
            hDiffUp.Add(hDiff)
        for hDown in hQCDDowns:
            hDiff = qcdMCHist[0].Clone("hDiff")
            hDiff.Add(hDown, -1)    
            hDiffDown.Add(hDiff)

    #Get unc band for the top plot
    uncGraphTop = getUncBand(hSumAllBkg, hDiffUp, hDiffDown,False)
    uncGraphTop.SetFillColor(2);
    uncGraphTop.SetFillStyle(3001);
    uncGraphTop.Draw(" E2 same ");
    
    #Draw data
    decoHist(dataHist[0], xTitle, yTitle, Samples["Data"][1])
    dataHist[0].SetMarkerStyle(20)
    if isData:
        dataHist[0].Draw("EPsame")

    #Draw legend
    hForLegend = sortHists(hAllBkgs, True)
    plotLegend = getLegend(dataHist, hForLegend, uncGraphTop)
    plotLegend.Draw()

    #Draw CMS, Lumi, channel
    if channel in ["mu", "Mu", "m"]:
        chName = "#mu + jets"
    else:
        chName = "e + jets"
    crName = formatCRString(CR)
    if CR=="":
        chName = "%s, SR"%chName
    else:
        chName = "%s, CR"%chName
    chCRName = "#splitline{#font[42]{%s}}{#font[42]{%s}}"%(chName, crName)
    extraText   = "#splitline{Preliminary}{%s}"%chCRName
    #CMS_lumi(canvas, iPeriod, iPosX, extraText)
    lumi_13TeV = "35.9 fb^{-1}"
    if "16" in year:
        lumi_13TeV = "35.9 fb^{-1} (2016)"
    if "17" in year:
        lumi_13TeV = "41.5 fb^{-1} (2017)"
    if "18" in year:
        lumi_13TeV = "59.7 fb^{-1} (2018)"
    CMS_lumi(lumi_13TeV, canvas, iPeriod, iPosX, extraText)

    #Draw the ratio of data and all background
    if isData and isRatio:
        canvas.cd(2)
        gPad.SetTopMargin(padGap); 
        gPad.SetBottomMargin(0.30); 
        gPad.SetRightMargin(0.03);
        #gPad.SetTickx(0);
        gPad.SetPad(xPadRange[0],yPadRange[0],xPadRange[1],yPadRange[2]);
        gPad.RedrawAxis();
        hRatio = dataHist[0].Clone("hRatio")
        hRatio.Divide(hSumAllBkg)
        decoHistRatio(hRatio, xTitle, "Obs./Exp.", 1)
        hRatio.Draw()
        uncGraphRatio = getUncBand(hSumAllBkg, hDiffUp, hDiffDown,True)
        uncGraphRatio.SetFillColor(2);
        uncGraphRatio.SetFillStyle(3001);
        uncGraphRatio.Draw("E2same");
        baseLine = TF1("baseLine","1", -100, 2000);
        #baseLine.SetLineColor(kRed+1);
        baseLine.SetLineColor(3);
        baseLine.Draw("SAME");
        hRatio.Draw("same")
    #canvas.SaveAs("%s/%s.pdf"%(outPlotFullDir, hName))
    canvas.SaveAs("%s/%s_%s_%s.png"%(outPlotFullDir, hName, year, channel))