Exemplo n.º 1
0
def convertHistToGraph(hist, useGarwood=False):
    alpha = 1 - 0.6827
    graph = TGraphAsymmErrors(hist.GetNbinsX())
    if useGarwood:
        lastEvent = False
        for i in reversed(range(hist.GetNbinsX())):
            N = hist.GetBinContent(i + 1)
            if not lastEvent and N > 0: lastEvent = True
            if lastEvent and N <= 0.: N = 1.e-6
            L = 0 if N == 0 else ROOT.Math.gamma_quantile(alpha / 2, N, 1.)
            U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1)
            graph.SetPoint(i,
                           hist.GetXaxis().GetBinCenter(i + 1),
                           N if not N == 0 else -1.e99)
            graph.SetPointError(i, 0., 0., N - L, U - N)
    else:
        for i in range(hist.GetNbinsX()):
            graph.SetPoint(i,
                           hist.GetXaxis().GetBinCenter(i + 1),
                           hist.GetBinContent(i + 1))
            graph.SetPointError(i,
                                hist.GetXaxis().GetBinWidth(i + 1) / 2.,
                                hist.GetXaxis().GetBinWidth(i + 1) / 2.,
                                hist.GetBinError(i + 1),
                                hist.GetBinError(i + 1))

    graph.SetLineWidth(hist.GetLineWidth())
    graph.SetLineStyle(hist.GetLineStyle())
    graph.SetLineColor(hist.GetLineColor())
    graph.SetMarkerSize(hist.GetMarkerSize())
    graph.SetMarkerStyle(hist.GetMarkerStyle())
    graph.SetMarkerColor(hist.GetMarkerColor())
    graph.SetFillStyle(hist.GetFillStyle())
    graph.SetFillColor(hist.GetFillColor())
    return graph
Exemplo n.º 2
0
def makeResidHist(data, bkg):
    pulls = TGraphAsymmErrors(data.GetN())
    pulls.SetName("Pulls")
    pulls.SetLineWidth(data.GetLineWidth())
    pulls.SetLineStyle(data.GetLineStyle())
    pulls.SetLineColor(data.GetLineColor())
    pulls.SetMarkerSize(data.GetMarkerSize())
    pulls.SetMarkerStyle(data.GetMarkerStyle())
    pulls.SetMarkerColor(data.GetMarkerColor())
    pulls.SetFillStyle(data.GetFillStyle())
    pulls.SetFillColor(data.GetFillColor())

    # Add histograms, calculate Poisson confidence interval on sum value
    for i in range(data.GetN()):
        x = data.GetX()[i]
        dyl = data.GetErrorYlow(i)
        dyh = data.GetErrorYhigh(i)
        yy = data.GetY()[i] - bkg.Interpolate(x)  #bkg.GetBinContent(i+1)
        norm = dyl if yy > 0. else dyh
        if norm == 0.:
            yy, dyh, dyl = 0., 0., 0.
        else:
            yy /= norm
            dyh /= norm
            dyl /= norm
        pulls.SetPoint(i, x, yy)
        pulls.SetPointEYhigh(i, dyh)
        pulls.SetPointEYlow(i, dyl)

    return pulls
Exemplo n.º 3
0
def getGraph(inArr):
    points = inArr[0]
    gr = TGraphAsymmErrors(len(points), array("d", [x[0] for x in points]),
                           array("d", [x[1] for x in points]),
                           array("d", [x[2] for x in points]),
                           array("d", [x[3] for x in points]),
                           array("d", [x[4] for x in points]),
                           array("d", [x[5] for x in points]))
    configurations = inArr[1]
    if len(configurations) != 0:
        gr.SetFillStyle(configurations[0])
    return gr
Exemplo n.º 4
0
def convertHistToGraph(hist):
    graph = TGraphAsymmErrors(hist.GetNbinsX())
    for i in range(hist.GetNbinsX()):
        graph.SetPoint(i,
                       hist.GetXaxis().GetBinCenter(i), hist.GetBinContent(i))
        graph.SetPointError(i,
                            hist.GetXaxis().GetBinWidth(i) / 2.,
                            hist.GetXaxis().GetBinWidth(i) / 2.,
                            hist.GetBinError(i), hist.GetBinError(i))
    graph.SetLineWidth(hist.GetLineWidth())
    graph.SetLineStyle(hist.GetLineStyle())
    graph.SetLineColor(hist.GetLineColor())
    graph.SetMarkerSize(hist.GetMarkerSize())
    graph.SetMarkerStyle(hist.GetMarkerStyle())
    graph.SetMarkerColor(hist.GetMarkerColor())
    graph.SetFillStyle(hist.GetFillStyle())
    graph.SetFillColor(hist.GetFillColor())
    return graph
Exemplo n.º 5
0
def histToGraph(hist, name='', keepErrors=True, poissonErrors=True):
    ## Helper method to convert a histogram to a corresponding graph
    #  @hist           TH1 object
    #  @name           name of the graph (default is name of histogram)
    #  @keepErrors     decide if the y-errors should be propagated to the graph
    #  @poissonErrors  decide if the y-errors should be calculated as Poisson errors
    #  @return graph
    if not name:
        name = 'g%s' % (hist.GetName())
    from ROOT import TGraphAsymmErrors
    nBins = hist.GetNbinsX()
    graph = TGraphAsymmErrors(nBins)
    graph.SetNameTitle(name, hist.GetTitle())
    xAxis = hist.GetXaxis()
    for i in xrange(nBins):
        xVal = xAxis.GetBinCenter(i + 1)
        yVal = hist.GetBinContent(i + 1)
        graph.SetPoint(i, xVal, yVal)
        graph.SetPointEXlow(i, abs(xVal - xAxis.GetBinLowEdge(i + 1)))
        graph.SetPointEXhigh(i, abs(xVal - xAxis.GetBinUpEdge(i + 1)))
        if keepErrors:
            if poissonErrors:
                lo, hi = calculatePoissonErrors(yVal)
                graph.SetPointEYlow(i, lo)
                graph.SetPointEYhigh(i, hi)
            else:
                graph.SetPointEYlow(i, hist.GetBinErrorLow(i + 1))
                graph.SetPointEYhigh(i, hist.GetBinErrorUp(i + 1))
    # copy the style
    graph.SetMarkerStyle(hist.GetMarkerStyle())
    graph.SetMarkerColor(hist.GetMarkerColor())
    graph.SetMarkerSize(hist.GetMarkerSize())
    graph.SetLineStyle(hist.GetLineStyle())
    graph.SetLineColor(hist.GetLineColor())
    graph.SetLineWidth(hist.GetLineWidth())
    graph.SetFillColor(hist.GetFillColor())
    graph.SetFillStyle(hist.GetFillStyle())
    return graph
Exemplo n.º 6
0
def MakeOneHist(histogramName):

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

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

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

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

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

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

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

    colorIndex = 0

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

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

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

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

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

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

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

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

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

        Histogram.SetMarkerStyle(markerStyle)

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

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

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

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

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

    ### Drawing histograms to canvas

    makeRatioPlots = arguments.makeRatioPlots
    makeDiffPlots = arguments.makeDiffPlots

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

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

        Canvas.cd(1)

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

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

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

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

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

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

    if arguments.makeFancy:
        HeaderLabel.Draw()

    #drawing the ratio or difference plot if requested

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

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

    outputFile.cd()
    Canvas.Write()

    if arguments.savePDFs:
        Canvas.SaveAs("efficiency_histograms_pdfs/" + histogramName + ".pdf")
can_scan_SL1_L1.SetGrid()
can_scan_SL1_L1.cd()
##Prepare summary TGraph
graph = TGraphAsymmErrors()
n=0
for a in sorted(threshold_scan):
#for a in sorted(run_parameters):
    ##Fill the TGraph with threshold (x-axis) and rate (y-axis)
    #######graph.SetPoint(n,int(run_parameters[a]['VTHR']),float(run_parameters[a]['RATE_SL1_L1']))
    graph.SetPoint(n,int(a),float(threshold_scan[a]))
    n = n+1
graph.SetMarkerSize(1.)
graph.SetMarkerStyle(21)
graph.SetMarkerColor(862)
graph.SetFillColor(868)
graph.SetFillStyle(3844)
graph.SetLineColor(868)
graph.SetLineWidth(2)
graph.SetLineStyle(2)
graph.GetXaxis().SetTitle("threshold [mV]")
graph.GetYaxis().SetTitleOffset(1.2)
graph.GetYaxis().SetTitle("rate [kHz]")
graph.Draw("APL")
latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.04)
latex.SetTextColor(1)
latex.SetTextFont(42)
latex.SetTextAlign(33)
latex.SetTextSize(0.04)
latex.SetTextFont(62)
Exemplo n.º 8
0
def limit(channel, signal):
    multF = 1.  # in fb
    filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_scalar" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    if (options.mediator == 'SC'):
        filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_scalar" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    elif (options.mediator == 'PS'):
        filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_pseudo" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    else:
        print 'WRONG mediator type'
    mass, val = fillValues(filename)

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

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

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

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

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

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

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

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

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

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

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

    # legend
    top = 0.9
    nitems = 4 + 2

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

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

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

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

    return

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

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

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

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

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


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

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Exemplo n.º 9
0
can_HV_scan_SL1_L1.SetGrid()
can_HV_scan_SL1_L1.cd()
##Prepare summary TGraph
graph_HV_L1 = TGraphAsymmErrors()
n = 0
for a in sorted(HV_scan_L1):
    #for a in sorted(run_parameters):
    ##Fill the TGraph with threshold (x-axis) and rate (y-axis)
    #######graph.SetPoint(n,int(run_parameters[a]['VTHR']),float(run_parameters[a]['RATE_SL1_L1']))
    graph_HV_L1.SetPoint(n, int(a), float(HV_scan_L1[a]))
    n = n + 1
graph_HV_L1.SetMarkerSize(1.)
graph_HV_L1.SetMarkerStyle(21)
graph_HV_L1.SetMarkerColor(418)
graph_HV_L1.SetFillColor(868)
graph_HV_L1.SetFillStyle(3844)
graph_HV_L1.SetLineColor(418 - 1)
graph_HV_L1.SetLineWidth(2)
graph_HV_L1.SetLineStyle(2)
graph_HV_L1.GetXaxis().SetTitle("HV [V]")
graph_HV_L1.GetYaxis().SetTitleOffset(1.2)
graph_HV_L1.GetYaxis().SetTitle("efficiency")
graph_HV_L1.GetYaxis().SetRangeUser(0, 1.01)
graph_HV_L1.Draw("APL")
latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.04)
latex.SetTextColor(1)
latex.SetTextFont(42)
latex.SetTextAlign(33)
latex.SetTextSize(0.04)
Exemplo n.º 10
0
def make1DLimitPlot(xtitle, xvals, obs, exp, exp1plus, exp1minus, exp2plus, exp2minus, theory):
    gStyle.SetOptTitle(0)

    axisTitleSize = 0.041
    axisTitleOffset = 1.2
    axisTitleSizeRatioX   = 0.18
    axisLabelSizeRatioX   = 0.12
    axisTitleOffsetRatioX = 0.94
    axisTitleSizeRatioY   = 0.15
    axisLabelSizeRatioY   = 0.108
    axisTitleOffsetRatioY = 0.32

    leftMargin   = 0.15
    rightMargin  = 0.12
    topMargin    = 0.05
    bottomMargin = 0.14
    bottomMargin2 = 0.22

    #c1 = TCanvas() #'c1', '', 200, 10, 700, 500 )
    c1 = TCanvas( "c1", "c2", 200, 10, 700, 600 )

    c1.SetHighLightColor(2)
    c1.SetFillColor(0)
    c1.SetBorderMode(0)
    c1.SetBorderSize(2)
    c1.SetLeftMargin(leftMargin)
    c1.SetRightMargin(rightMargin)
    c1.SetTopMargin(topMargin)
    c1.SetBottomMargin(bottomMargin)
    c1.SetFrameBorderMode(0)
    c1.SetFrameBorderMode(0)
    c1.SetLogy(1)
    #c1.SetLogx(1)
    c1.SetTickx(1)
    c1.SetTicky(1)
    #c1.SetGridx(True);
    #c1.SetGridy(True);
    if "c#tau" in xtitle:
        c1.SetLogx(1);

    exp2sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
           array('d', [0]), array('d', [0]), array('d', exp2minus), array('d', exp2plus))
    exp2sigma_xsec.Sort()
    exp2sigma_xsec.Draw('A3')
    exp2sigma_xsec.SetFillStyle(1001);
    exp2sigma_xsec.SetFillColor(kOrange);
    exp2sigma_xsec.SetLineColor(kOrange);
    exp2sigma_xsec.GetYaxis().SetRangeUser(0.001,100);
    exp2sigma_xsec.GetXaxis().SetLimits(0.8*min(xvals),1.1*max(xvals));
    #exp2sigma_xsec.GetXaxis().SetTitle('m_{1} [GeV]')
    #exp2sigma_xsec.GetXaxis().SetTitle('c#tau [cm]')
    exp2sigma_xsec.GetXaxis().SetTitle(xtitle)
    exp2sigma_xsec.GetXaxis().SetTitleOffset(axisTitleOffset)
    exp2sigma_xsec.GetYaxis().SetTitle('95% C.L. #sigma(pp #rightarrow #chi_{1} #chi_{1} #mu^{+} #mu^{-}) [pb]')
    exp2sigma_xsec.GetYaxis().SetTitleOffset(axisTitleOffset+0.1)

    exp1sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
            array('d', [0]), array('d', [0]), array('d', exp1minus), array('d', exp1plus))
    exp1sigma_xsec.Sort()
    exp1sigma_xsec.SetFillStyle(1001);
    exp1sigma_xsec.SetFillColor(kGreen+1);
    exp1sigma_xsec.SetLineColor(kGreen+1);
    exp1sigma_xsec.Draw('3 SAME')

    exp_xsec = TGraph(len(xvals), array('d', xvals), array('d', exp))
    exp_xsec.Sort()
    exp_xsec.SetLineWidth(2)
    exp_xsec.SetLineStyle(1)
    exp_xsec.SetLineColor(kRed)
    exp_xsec.Draw('C SAME')

    obs_xsec = TGraph(len(xvals), array('d', xvals), array('d', obs))
    obs_xsec.Sort()
    obs_xsec.SetLineWidth(3)
    obs_xsec.SetLineColor(kBlack)
    obs_xsec.SetMarkerColor(kBlack)
    obs_xsec.SetMarkerStyle(20)
    obs_xsec.SetMarkerSize(1)
    obs_xsec.Draw('PC SAME')

    theory_xsec = TGraph(len(xvals), array('d', xvals), array('d', theory))
    theory_xsec.Sort()
    theory_xsec.SetLineWidth(2)
    theory_xsec.SetLineStyle(8)
    theory_xsec.SetLineColor(kBlue)
    theory_xsec.Draw('C SAME')

    leg = TLegend(0.50,0.70,0.8,0.90);
    leg.SetBorderSize(0);
    leg.SetFillStyle(0);
    leg.AddEntry(theory_xsec, "Theory", "l");
    leg.AddEntry(obs_xsec, "Observed Limit", "pl");
    leg.AddEntry(exp_xsec, "Expected Limit", "l");
    leg.AddEntry(exp1sigma_xsec, "#pm 1 std. dev.", "f");
    leg.AddEntry(exp2sigma_xsec, "#pm 2 std. dev.", "f");
    leg.Draw()

    drawCMSLogo(c1, 13, 122450)

    # TCanvas.Update() draws the frame, after which one can change it
    # c1.Update()
    # c1.Modified()
    # c1.Update()

    c1.RedrawAxis()
    c1.Draw()
    
    wait(True)
Exemplo n.º 11
0
def make_ratioplot(name,
                   ttbar_file=0,
                   qcd_file=0,
                   signal_files=[],
                   histo=0,
                   rebin=1,
                   minx=0,
                   maxx=0,
                   miny=0,
                   maxy=0,
                   logy=False,
                   xtitle='',
                   ytitle='',
                   textsizefactor=1,
                   signal_legend=[],
                   outfile=0,
                   signal_colors=[],
                   signal_zoom=1,
                   qcd_zoom=1,
                   ttbar_zoom=1,
                   ttbar_legend='t#bar{t}',
                   qcd_legend='QCD from MC',
                   dosys=False,
                   docms=True,
                   legendtitle=''):

    ###canvas setting up
    canvas = 0
    canvas = TCanvas(name, '', 0, 0, 600, 600)
    canvas.SetLeftMargin(0.15)
    canvas.SetRightMargin(0.05)
    canvas.SetTopMargin(0.10)
    canvas.SetBottomMargin(0.10)
    charsize = 0.04
    offset = 1.9

    ###latex label
    latex = 0
    latex = TLatex(0.6, 0.7, '13 TeV, 2.69 fb^{-1}')
    latex.SetTextSize(charsize)
    latex.SetNDC(1)
    latex.SetTextFont(42)

    ###legend setting up
    #legend=TLegend(0.0,0.75,0.99,1.04)
    legend = TLegend(0.4, 0.6, 0.94, 0.95)
    legend.SetNColumns(2)
    legend.SetHeader('')
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)

    ###mc stack
    stack = THStack(name + '_stack', '')

    qcd_histo = qcd_file.Get(histo).Clone(name + '_make_plot')
    qcd_histo.Rebin(rebin)
    ttbar_histo = ttbar_file.Get(histo).Clone()
    ttbar_histo.Rebin(rebin)
    ttbar_histo.SetFillColor(kRed - 9)
    ttbar_histo.SetLineColor(kRed - 9)
    ttbar_histo.SetMarkerColor(kRed - 9)
    if ttbar_zoom != 1:
        ttbar_histo.Scale(ttbar_zoom)
    legend.AddEntry(ttbar_histo, ttbar_legend, 'f')
    qcd_histo.SetFillColor(kOrange - 5)
    qcd_histo.SetLineColor(kOrange - 5)
    qcd_histo.SetMarkerColor(kOrange - 5)
    if qcd_zoom != 1:
        qcd_histo.Scale(qcd_zoom)
    legend.AddEntry(qcd_histo, qcd_legend, 'f')

    sum_mc = qcd_histo.Clone(histo + 'tmp')
    sum_mc.Add(ttbar_histo)
    stack.Add(ttbar_histo)
    stack.Add(qcd_histo)

    sum_mc.SetLineColor(kBlack)
    sum_mc.SetFillStyle(0)
    err = TGraphAsymmErrors(sum_mc)
    legend.AddEntry(err, 'Total uncertainty', 'f')

    if legendtitle == '':
        legend.AddEntry(0, "", '')
        legend.AddEntry(0, "g_{RS} #rightarrow t#bar{t} (2pb)", '')
    else:
        legend.AddEntry(0, "", '')
        legend.AddEntry(0, legendtitle, '')

    ###signal setting up
    signal_histos = []
    colors = [
        kBlack, kRed, kOrange, kBlue, kGreen + 3, 44, 45, 46, 47, 48, 49, 50,
        51, 52, 53, 54, 55, 56, 57, 58, 59, 60
    ]
    styles = [
        1, 3, 5, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 1, 1, 1, 1
    ]
    if signal_colors != []:
        colors = signal_colors
    for i in range(len(signal_files)):
        signal_histos.append(signal_files[i].Get(histo).Clone())
        signal_histos[i].SetLineWidth(3)
        signal_histos[i].SetLineStyle(styles[i])
        signal_histos[i].SetLineColor(colors[i])
        signal_histos[i].SetMarkerColor(colors[i])
        signal_histos[i].Rebin(rebin)
        if signal_zoom != 1:
            signal_histos[i].Scale(signal_zoom)
        legend.AddEntry(signal_histos[i], signal_legend[i], 'l')

    ###mc shape line
    ttbar_line = 0
    ttbar_line = ttbar_histo.Clone()
    ttbar_line.SetLineColor(kBlack)
    ttbar_line.SetFillStyle(0)

    ###mc errors
    if dosys:
        sys_diff_qcd = []
        sys_diff_ttbar = []
        for imtt in range(1, ttbar_histo.GetNbinsX() + 1):
            sys_diff_qcd.append([])
            sys_diff_ttbar.append([])

        #adding stat uncertainties <--removed
        # for imtt in range(1,ttbar_histo.GetNbinsX()+1):
        #   sys_diff_ttbar[imtt-1].append(ttbar_histo.GetBinError(imtt))
        #   sys_diff_ttbar[imtt-1].append(-ttbar_histo.GetBinError(imtt))
        #   sys_diff_qcd[imtt-1].append(qcd_histo.GetBinError(imtt))
        #   sys_diff_qcd[imtt-1].append(-qcd_histo.GetBinError(imtt))
        #adding flat uncertainties
        for imtt in range(1, ttbar_histo.GetNbinsX() + 1):
            #ttbar
            for i in [
                    2.4,  #pdf
                    10.0,  #mu
                    3.0,  #xsec
                    6.0,  #toppt
                    1.0,  #lumi
                    3.5,  #jec
                    3.0,  #jer
                    10.0,  #btag
                    #3.0,#trig
                    10.0,  #toptag
                    3.0
            ]:  #pileup
                sys_diff_ttbar[imtt - 1].append(
                    i / 100.0 * ttbar_histo.GetBinContent(imtt))
                sys_diff_ttbar[imtt - 1].append(
                    -i / 100.0 * ttbar_histo.GetBinContent(imtt))
            closureunc = 5.0
            # if '1b' in histo:
            #   closureunc=5.0
            # elif '2b' in histo:
            #   closureunc=10.0
            for i in [
                    2.0,  #modmass
                    closureunc
            ]:  #closure
                sys_diff_qcd[imtt - 1].append(i / 100.0 *
                                              qcd_histo.GetBinContent(imtt))
                sys_diff_qcd[imtt - 1].append(-i / 100.0 *
                                              qcd_histo.GetBinContent(imtt))
            # #3% trigger
            # sys_diff_ttbar[imtt-1].append(0.03*ttbar_histo.GetBinContent(imtt))
            # sys_diff_ttbar[imtt-1].append(-0.03*ttbar_histo.GetBinContent(imtt))
            # #2.7% lumi
            # sys_diff_ttbar[imtt-1].append(0.023*ttbar_histo.GetBinContent(imtt))
            # sys_diff_ttbar[imtt-1].append(-0.023*ttbar_histo.GetBinContent(imtt))
            # #15% ttbar
            # #sys_diff_ttbar[imtt-1].append(0.15*ttbar_histo.GetBinContent(imtt))
            # #sys_diff_ttbar[imtt-1].append(-0.15*ttbar_histo.GetBinContent(imtt))
            # #2.8% QCD
            # sys_diff_qcd[imtt-1].append(0.028*qcd_histo.GetBinContent(imtt))
            # sys_diff_qcd[imtt-1].append(-0.028*qcd_histo.GetBinContent(imtt))
        #combining uncertainties
        sys_tot_ttbar = []
        sys_tot_qcd = []
        sys_tot = []
        sys_global_ttbar = [0.0, 0.0]
        sys_global_qcd = [0.0, 0.0]
        nevt_global = [0.0, 0.0, 0.0]
        for imtt in range(1, ttbar_histo.GetNbinsX() + 1):
            uperr_qcd = 0
            downerr_qcd = 0
            uperr_ttbar = 0
            downerr_ttbar = 0
            for error in sys_diff_ttbar[imtt - 1]:
                if error < 0:
                    downerr_ttbar = downerr_ttbar + error * error
                else:
                    uperr_ttbar = uperr_ttbar + error * error
            for error in sys_diff_qcd[imtt - 1]:
                if error < 0:
                    downerr_qcd = downerr_qcd + error * error
                else:
                    uperr_qcd = uperr_qcd + error * error
            sys_tot_ttbar.append(
                [math.sqrt(downerr_ttbar),
                 math.sqrt(uperr_ttbar)])
            sys_tot_qcd.append([math.sqrt(downerr_qcd), math.sqrt(uperr_qcd)])
            sys_tot.append([
                math.sqrt(downerr_qcd + downerr_ttbar),
                math.sqrt(uperr_qcd + uperr_ttbar)
            ])
            sys_global_qcd[0] = sys_global_qcd[0] + downerr_qcd
            sys_global_qcd[1] = sys_global_qcd[1] + uperr_qcd
            sys_global_ttbar[0] = sys_global_ttbar[0] + downerr_ttbar
            sys_global_ttbar[1] = sys_global_ttbar[1] + uperr_ttbar
            # nevt_global[0]=nevt_global[0]+data_histo.GetBinContent(imtt)
            nevt_global[1] = nevt_global[1] + qcd_histo.GetBinContent(imtt)
            nevt_global[2] = nevt_global[2] + ttbar_histo.GetBinContent(imtt)
            #print 'ttbar+qcd',math.sqrt(uperr_qcd+uperr_ttbar),math.sqrt(downerr_qcd+downerr_ttbar)
            #print 'qcd',math.sqrt(uperr_qcd),math.sqrt(downerr_qcd)
            #print 'ttbar',math.sqrt(uperr_ttbar),math.sqrt(downerr_ttbar)
            err.SetPointEYhigh(imtt - 1, math.sqrt(uperr_qcd + uperr_ttbar))
            err.SetPointEYlow(imtt - 1, math.sqrt(downerr_qcd + downerr_ttbar))
        sys_global = [0.0, 0.0]
        sys_global[0] = math.sqrt(sys_global_qcd[0] + sys_global_ttbar[0])
        sys_global[1] = math.sqrt(sys_global_qcd[1] + sys_global_ttbar[1])
        sys_global_qcd[0] = math.sqrt(sys_global_qcd[0])
        sys_global_qcd[1] = math.sqrt(sys_global_qcd[1])
        sys_global_ttbar[0] = math.sqrt(sys_global_ttbar[0])
        sys_global_ttbar[1] = math.sqrt(sys_global_ttbar[1])
        # print name
        # print "\hline"
        # print "Multijet QCD & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1],sys_global_qcd[1],sys_global_qcd[0])
        # print "SM ttbar & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[2],sys_global_ttbar[1],sys_global_ttbar[0])
        # print "\hline"
        # print "Total background & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1]+nevt_global[2],sys_global[1],sys_global[0])
        # print 'DATA & %.0f' %nevt_global[0]

    err.SetFillStyle(3145)
    err.SetFillColor(kGray + 1)

    ###drawing top
    canvas.cd()
    stack.Draw('hist')
    stack.GetXaxis().SetTitle(ttbar_histo.GetXaxis().GetTitle())
    stack.GetYaxis().SetTitle(ttbar_histo.GetYaxis().GetTitle())
    stack.GetXaxis().SetLabelSize(charsize)
    stack.GetXaxis().SetTitleSize(charsize)
    stack.GetYaxis().SetLabelSize(charsize)
    stack.GetYaxis().SetTitleSize(charsize)
    stack.GetYaxis().SetTitleOffset(offset)
    if minx != 0 or maxx != 0:
        stack.GetXaxis().SetRangeUser(minx, maxx)
    #else:
    #  stack.GetXaxis().SetRangeUser(0,4000)
    if miny != 0 or maxy != 0:
        stack.SetMaximum(maxy)
        stack.SetMinimum(miny)
    else:
        if logy:
            stack.SetMaximum(stack.GetMaximum() * 10)
            stack.SetMinimum(0.2)
        else:
            stack.SetMaximum(stack.GetMaximum() * 2.0)
            stack.SetMinimum(0.001)
    err.Draw('2')
    sum_mc.Draw('samehist')
    if ttbar_file != 0:
        ttbar_line.Draw('samehist')
    for i in signal_histos:
        i.Draw('samehist')
    if logy:
        canvas.SetLogy()
    legend.Draw()

    latex2text = ''
    if 'ldy_0b' in name:
        latex2text = '#Deltay < 1; 0 b tag'
    elif 'ldy_1b' in name:
        latex2text = '#Deltay < 1; 1 b tag'
    elif 'ldy_2b' in name:
        latex2text = '#Deltay < 1; 2 b tag'
    elif 'hdy_0b' in name:
        latex2text = '#Deltay > 1; 0 b tag'
    elif 'hdy_1b' in name:
        latex2text = '#Deltay > 1; 1 b tag'
    elif 'hdy_2b' in name:
        latex2text = '#Deltay > 1; 2 b tag'
    latex2 = TLatex(0.19, 0.7, latex2text)
    latex2.SetTextSize(0.03)
    latex2.SetNDC(1)
    latex2.SetTextFont(42)
    latex2.Draw()

    if docms:
        if '3000' in name:
            CMS_lumi.CMS_lumi(canvas, 3, 11)
        elif '1000' in name:
            CMS_lumi.CMS_lumi(canvas, 2, 11)
        elif '300' in name:
            CMS_lumi.CMS_lumi(canvas, 1, 11)
        elif '36' in name:
            CMS_lumi.CMS_lumi(canvas, 0, 11)

    ###saving
    canvas.SaveAs('pdf/' + name + '.pdf')
    if outfile != 0:
        canvas.Write()
Exemplo n.º 12
0
def make1DLimitPlot(xtitle, xvals, obs, exp, exp1plus, exp1minus, exp2plus,
                    exp2minus, theory, alphaD, xvar):
    gStyle.SetOptTitle(0)

    axisTitleSize = 0.041
    axisTitleOffset = 1.2
    axisTitleSizeRatioX = 0.18
    axisLabelSizeRatioX = 0.12
    axisTitleOffsetRatioX = 0.94
    axisTitleSizeRatioY = 0.15
    axisLabelSizeRatioY = 0.108
    axisTitleOffsetRatioY = 0.32

    leftMargin = 0.15
    rightMargin = 0.12
    topMargin = 0.05
    bottomMargin = 0.14
    bottomMargin2 = 0.22

    #c1 = TCanvas() #'c1', '', 200, 10, 700, 500 )
    c1 = TCanvas("c1", "c2", 200, 10, 700, 600)

    c1.SetHighLightColor(2)
    c1.SetFillColor(0)
    c1.SetBorderMode(0)
    c1.SetBorderSize(2)
    c1.SetLeftMargin(leftMargin)
    c1.SetRightMargin(rightMargin)
    c1.SetTopMargin(topMargin)
    c1.SetBottomMargin(bottomMargin)
    c1.SetFrameBorderMode(0)
    c1.SetFrameBorderMode(0)
    c1.SetLogy(1)
    #c1.SetLogx(1)
    c1.SetTickx(1)
    c1.SetTicky(1)
    #c1.SetGridx(True);
    #c1.SetGridy(True);
    if "c#tau" in xtitle:
        c1.SetLogx(1)

    exp2sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
           array('d', [0]), array('d', [0]), array('d', exp2minus), array('d', exp2plus))
    exp2sigma_xsec.Sort()
    exp2sigma_xsec.Draw('A3')
    exp2sigma_xsec.SetFillStyle(1001)
    exp2sigma_xsec.SetFillColor(kOrange)
    exp2sigma_xsec.SetLineColor(kOrange)
    exp2sigma_xsec.GetYaxis().SetRangeUser(1e-4, 1e3)
    if xvar == 'mass':
        exp2sigma_xsec.GetXaxis().SetLimits(1, 80)
    elif xvar == 'ctau':
        exp2sigma_xsec.GetXaxis().SetLimits(0.1, 100)
    else:
        exp2sigma_xsec.GetXaxis().SetLimits(0.8 * min(xvals), 1.1 * max(xvals))
    #exp2sigma_xsec.GetXaxis().SetTitle('m_{1} [GeV]')
    #exp2sigma_xsec.GetXaxis().SetTitle('c#tau [cm]')
    exp2sigma_xsec.GetXaxis().SetTitle(xtitle)
    exp2sigma_xsec.GetXaxis().SetTitleOffset(axisTitleOffset)
    exp2sigma_xsec.GetYaxis().SetTitle(
        "#sigma_{95% CL} Br(A' #rightarrow #mu#mu) [pb]")
    exp2sigma_xsec.GetYaxis().SetTitleOffset(axisTitleOffset + 0.1)

    exp1sigma_xsec = TGraphAsymmErrors(len(xvals), array('d', xvals), array('d', exp), \
            array('d', [0]), array('d', [0]), array('d', exp1minus), array('d', exp1plus))
    exp1sigma_xsec.Sort()
    exp1sigma_xsec.SetFillStyle(1001)
    exp1sigma_xsec.SetFillColor(kGreen + 1)
    exp1sigma_xsec.SetLineColor(kGreen + 1)
    exp1sigma_xsec.Draw('3 SAME')

    exp_xsec = TGraph(len(xvals), array('d', xvals), array('d', exp))
    exp_xsec.Sort()
    exp_xsec.SetLineWidth(2)
    exp_xsec.SetLineStyle(1)
    exp_xsec.SetLineColor(kRed)
    exp_xsec.Draw('C SAME')

    obs_xsec = TGraph(len(xvals), array('d', xvals), array('d', obs))
    obs_xsec.Sort()
    obs_xsec.SetLineWidth(3)
    obs_xsec.SetLineColor(kBlack)
    obs_xsec.SetMarkerColor(kBlack)
    obs_xsec.SetMarkerStyle(20)
    obs_xsec.SetMarkerSize(1)
    obs_xsec.Draw('PC SAME')

    theory_xsec = TGraph(len(xvals), array('d', xvals), array('d', theory))
    theory_xsec.Sort()
    theory_xsec.SetLineWidth(2)
    theory_xsec.SetLineStyle(8)
    theory_xsec.SetLineColor(kBlue)
    theory_xsec.Draw('C SAME')

    leg = TLegend(0.50, 0.70, 0.8, 0.90)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.AddEntry(theory_xsec, "Theory", "l")
    leg.AddEntry(obs_xsec, "Observed Limit", "pl")
    leg.AddEntry(exp_xsec, "Expected Limit", "l")
    leg.AddEntry(exp1sigma_xsec, "#pm 1 std. dev.", "f")
    leg.AddEntry(exp2sigma_xsec, "#pm 2 std. dev.", "f")
    leg.Draw()

    drawCMSLogo(c1, 13, 122450)

    if alphaD != '':
        aDtext = TLatex()
        #baseSize = 25
        aDtext.SetNDC()
        aDtext.SetTextAngle(0)
        aDtext.SetTextColor(1)
        #aDtext.SetTextFont(61)
        #aDtext.SetTextAlign(11)
        aDtext.SetTextSize(0.0375)
        aDtext.DrawLatex(0.7, 0.9, "#alpha_{D} = " + alphaD)

    # TCanvas.Update() draws the frame, after which one can change it
    # c1.Update()
    # c1.Modified()
    # c1.Update()

    c1.RedrawAxis()
    c1.Draw()

    wait(True)
Exemplo n.º 13
0
    total = ggxsec[0] + vbfxsec[0]
    errUp = math.sqrt(pow(ggxsec[1], 2) + pow(vbfxsec[1], 2))
    errDown = math.sqrt(pow(ggxsec[2], 2) + pow(vbfxsec[2], 2))
    totalGr.SetPoint(ipt, imass[0], total)
    totalGr.SetPointError(ipt, 0, 0, errUp, errDown)

    ipt = ipt + 1

c = ROOT.TCanvas("c", "c", 600, 600)

totalGr.SetName("total")
totalGr.SetTitle("gg+VBF")
totalGr.SetMarkerStyle(20)
totalGr.SetMarkerColor(1)
totalGr.SetFillColor(0)
totalGr.SetFillStyle(0)
totalGr.Draw("ae1p")
totalGr.GetXaxis().SetTitle("Higgs mass [GeV/c^{2}]")
totalGr.GetYaxis().SetTitle("Cross section [pb]")

glugluGr.SetName("gg")
glugluGr.SetTitle("gg")
glugluGr.SetMarkerStyle(21)
glugluGr.SetMarkerColor(2)
glugluGr.SetFillColor(0)
glugluGr.SetFillStyle(0)
glugluGr.Draw("e1p")

vbfGr.SetName("vbf")
vbfGr.SetTitle("VBF")
vbfGr.SetMarkerStyle(22)
Exemplo n.º 14
0
def limit():
    method = ''
    channel = "bb"
    if INCLUDEACC:
        particleP = "X"
    else:
        particleP = "Z'"
    particle = 'b#bar{b}'
    multF = ZPTOBB
    THEORY = ['A1', 'B3']
    if INCLUDEACC: THEORY.append('SSM')
 
    suffix = "_"+BTAGGING
    if ISMC: suffix += "_MC"
    if SY: suffix += "_comb"
    #if method=="cls": suffix="_CLs"
    if INCLUDEACC: suffix+="_acc"

    if SY:
        filename = "./combine/limits/" + BTAGGING + "/combined_run2/"+ YEAR + "_M%d.txt"
    else:
        filename = "./combine/limits/" + BTAGGING + "/"+ YEAR + "_M%d.txt"
    if CATEGORY!="":
        if SY:
            filename = filename.replace(BTAGGING + "/combined_run2/", BTAGGING + "/single_category/combined_run2/"+CATEGORY+"_")
        else:
            filename = filename.replace(BTAGGING + "/", BTAGGING + "/single_category/"+CATEGORY+"_")
        suffix += "_"+CATEGORY
    if ISMC: filename = filename.replace(".txt", "_MC.txt")
    mass, val = fillValues(filename)

    #print "mass =",mass
    #print "val =", val

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

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

        if INCLUDEACC:
            acc_factor = ACCEPTANCE[m]
        else:
            acc_factor = 1.

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


    for t in THEORY:
        Theory[t] = TGraphAsymmErrors()
        Xs_dict = HVT[t]['Z']['XS'] if t!='SSM' else SSM['Z']
        for m in sorted(Xs_dict.keys()):
            if INCLUDEACC and t!='SSM':
                acc_factor = ACCEPTANCE[m]
            else:
                acc_factor = 1.
            if m < SIGNALS[0] or m > SIGNALS[-1]: continue
            #if m < mass[0] or m > mass[-1]: continue
            #if t!= 'SSM' and m>4500: continue ## I don't have the higher mass xs
            if m>4500: continue
            XsZ, XsZ_Up, XsZ_Down = 0., 0., 0.
            if t!='SSM':
                XsZ = 1000.*HVT[t]['Z']['XS'][m]*SSM["BrZ"][m] #assuming the same BR as the SSM Z' one
                XsZ_Up = XsZ*(1.+math.hypot(HVT[t]['Z']['QCD'][m][0]-1., HVT[t]['Z']['PDF'][m][0]-1.))
                XsZ_Down = XsZ*(1.-math.hypot(1.-HVT[t]['Z']['QCD'][m][0], 1.-HVT[t]['Z']['PDF'][m][0]))
            else:
                XsZ = 1000.*SSM['Z'][m]*SSM["BrZ"][m]
                XsZ_Up = XsZ*(1.+math.hypot(HVT['A1']['Z']['QCD'][m][0]-1., HVT['A1']['Z']['PDF'][m][0]-1.))
                XsZ_Down = XsZ*(1.-math.hypot(1.-HVT['A1']['Z']['QCD'][m][0], 1.-HVT['A1']['Z']['PDF'][m][0]))
     
            n = Theory[t].GetN()
            Theory[t].SetPoint(n, m, XsZ*acc_factor)
            Theory[t].SetPointError(n, 0., 0., (XsZ-XsZ_Down)*acc_factor, (XsZ_Up-XsZ)*acc_factor)

            Theory[t].SetLineColor(theoryLineColor[t])
            Theory[t].SetFillColor(theoryFillColor[t])
            Theory[t].SetFillStyle(theoryFillStyle[t])
            Theory[t].SetLineWidth(2)
            #Theory[t].SetLineStyle(7)


    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp1s.SetFillColor(417) #kGreen+1
    Exp1s.SetLineColor(417) #kGreen+1
    Exp2s.SetFillColor(800) #kOrange
    Exp2s.SetLineColor(800) #kOrange
    Exp2s.GetXaxis().SetTitle("m_{"+particleP+"} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize()*1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle("#sigma("+particleP+") #bf{#it{#Beta}}("+particleP+" #rightarrow "+particle+"){} (fb)".format(" #times #Alpha" if INCLUDEACC else ""))
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

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

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

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



    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.050)
    Exp2s.GetYaxis().SetTitleSize(0.050)
    Exp2s.GetXaxis().SetLabelSize(0.045)
    Exp2s.GetYaxis().SetLabelSize(0.045)
    Exp2s.GetXaxis().SetTitleOffset(0.90)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    if INCLUDEACC:
        Exp2s.GetYaxis().SetRangeUser(0.05, 5.e3)
    else:
        Exp2s.GetYaxis().SetRangeUser(0.1, 5.e3)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    #Exp2s.GetXaxis().SetRangeUser(mass[0], min(mass[-1], MAXIMUM[channel] if channel in MAXIMUM else 1.e6))
    Exp2s.GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1])
    #drawAnalysis(channel)
    drawAnalysis("")
    #drawRegion(channel, True)
    drawRegion("", True)
    #drawCMS(LUMI, "Simulation Preliminary") #Preliminary
    if CATEGORY=="": 
        #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
        drawCMS(LUMI, "", suppressCMS=True)
    else:
         #drawCMS(LUMI, "Work in Progress, "+CAT_LABELS[CATEGORY], suppressCMS=True)       
         drawCMS(LUMI, CAT_LABELS[CATEGORY], suppressCMS=True)       

    # legend
    top = 0.9
    nitems = 4 + len(THEORY)

    leg = TLegend(0.55, top-nitems*0.3/5., 0.98, top)
    #leg = TLegend(0.45, top-nitems*0.3/5., 0.98, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0) #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected", "l")
    leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    for t in THEORY: leg.AddEntry(Theory[t], theoryLabel[t], "fl")
    leg.Draw()
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.045)
    latex.SetTextFont(42)
    #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h")

    leg2 = TLegend(0.12, 0.225-2*0.25/5., 0.65, 0.225)
    leg2.SetBorderSize(0)
    leg2.SetFillStyle(0) #1001
    leg2.SetFillColor(0)
    c1.GetPad(0).RedrawAxis()

    leg2.Draw()
    if not options.blind: Obs0s.Draw("SAME, L")
    c1.GetPad(0).Update()

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

    c1.Print("combine/plotsLimit/ExclusionLimits/"+YEAR+suffix+".png")
    c1.Print("combine/plotsLimit/ExclusionLimits/"+YEAR+suffix+".pdf")
    if 'ah' in channel or 'sl' in channel:
        c1.Print("combine/plotsLimit/ExclusionLimits/"+YEAR+suffix+".C")
        c1.Print("combine/plotsLimit/ExclusionLimits/"+YEAR+suffix+".root")

    for t in THEORY:
        print "Model", t, ":",
        for m in range(mass[0], mass[-1], 1):
            if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == (Theory[t].Eval(m+1) > Obs0s.Eval(m+1)): print m,
        print ""

    return ##FIXME


    # ---------- Significance ----------
    c2 = TCanvas("c2", "Significance", 800, 600)
    c2.cd()
    c2.GetPad(0).SetTopMargin(0.06)
    c2.GetPad(0).SetRightMargin(0.05)
    c2.GetPad(0).SetTicks(1, 1)
    c2.GetPad(0).SetGridx()
    c2.GetPad(0).SetGridy()
    Sign.GetYaxis().SetRangeUser(0., 5.)
    Sign.Draw("AL3")
    #drawCMS(LUMI, "Preliminary")
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c2.Print("combine/plotsLimit/Significance/"+YEAR+suffix+".png")
    c2.Print("combine/plotsLimit/Significance/"+YEAR+suffix+".pdf")
#    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".root")
#    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".C")

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

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

    #drawCMS(LUMI, "Preliminary")
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c3.Print("combine/plotsLimit/pValue/"+YEAR+suffix+".png")
    c3.Print("combine/plotsLimit/pValue/"+YEAR+suffix+".pdf")
#    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".root")
#    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".C")

    # --------- Best Fit ----------
    c4 = TCanvas("c4", "Best Fit", 800, 600)
    c4.cd()
    c4.GetPad(0).SetTopMargin(0.06)
    c4.GetPad(0).SetRightMargin(0.05)
    c4.GetPad(0).SetTicks(1, 1)
    c4.GetPad(0).SetGridx()
    c4.GetPad(0).SetGridy()
    Best.Draw("AL3")
    #drawCMS(LUMI, "Preliminary")
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c4.Print("combine/plotsLimit/BestFit/"+YEAR+suffix+".png")
    c4.Print("combine/plotsLimit/BestFit/"+YEAR+suffix+".pdf")
#    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".root")
#    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".C")

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

    if 'ah' in channel:
        outFile = TFile("bands.root", "RECREATE")
        outFile.cd()
        pVal.Write("graph")
        Best.Write("best")
        outFile.Close()
Exemplo n.º 15
0
class plotTogether:
    tfiles = {}
    lgx = 0.65
    lgy = 0.4

    def __init__(self):
        self.unctitle = ''
        self.MCplots = []
        self.DAplots = []
        self.NOplots = []
        self.Otherplots = []
        self.DIVplots = []
        self.Canvases = []
        self.Pads = []
        self.unc = False
        ROOT.gStyle.SetOptFit(0)
        ROOT.gStyle.SetOptStat(0)
        ROOT.gStyle.SetPadTickX(0)
        ROOT.gStyle.SetPadTickY(0)
        ROOT.gStyle.SetOptStat(0)
        ROOT.gStyle.SetOptStat(0)

        ROOT.gStyle.SetPadTopMargin(0.05)
        ROOT.gStyle.SetPadRightMargin(0.05)
        ROOT.gStyle.SetPadBottomMargin(0.15)
        ROOT.gStyle.SetPadLeftMargin(0.15)

        ROOT.gStyle.SetLabelFont(43, "x")
        ROOT.gStyle.SetLabelFont(43, "y")
        ROOT.gStyle.SetLabelFont(43, "z")
        ROOT.gStyle.SetLabelOffset(0.01, "x")
        ROOT.gStyle.SetLabelOffset(0.01, "y")
        ROOT.gStyle.SetLabelOffset(0.01, "z")
        ROOT.gStyle.SetLabelSize(25, "x")
        ROOT.gStyle.SetLabelSize(25, "y")
        ROOT.gStyle.SetLabelSize(25, "z")
        ROOT.gStyle.SetTitleFont(43, "x")
        ROOT.gStyle.SetTitleFont(43, "y")
        ROOT.gStyle.SetTitleFont(43, "z")
        ROOT.gStyle.SetTitleOffset(1.2, "x")
        ROOT.gStyle.SetTitleOffset(1.5, "y")
        ROOT.gStyle.SetTitleOffset(1.1, "z")
        ROOT.gStyle.SetTitleSize(30, "x")
        ROOT.gStyle.SetTitleSize(30, "y")
        ROOT.gStyle.SetTitleSize(30, "z")

    def legend(self, legtitle):
        xpos = 1. - ROOT.gPad.GetRightMargin()
        ypos = 1. - ROOT.gPad.GetTopMargin()
        #self.lg = TLegend(0.55, 0.4, xpos-0.02, ypos-0.02)
        self.lg = TLegend(self.lgx, self.lgy, xpos - 0.02, ypos - 0.02)
        if len(legtitle) != 0:
            self.lg.SetHeader(legtitle)
        self.lg.SetFillColor(0)
        self.lg.SetFillStyle(0)
        self.lg.SetLineColor(0)
        self.lg.SetLineStyle(0)
        self.lg.SetBorderSize(0)
        self.lg.SetShadowColor(0)
        self.lg.SetTextFont(42)
        self.lg.SetTextSize(0.07)

    njetstr = sys.argv[3][0] + ' jets' if '6' not in sys.argv[
        3] and 'up' not in sys.argv[3] else '#geq' + sys.argv[3][0] + ' jets'

    def setchannel(self, title='e/#mu+jets, ' + njetstr):
        #def setchannel(self, title = 'e/#mu+jets, %s jets' %njets[0]):
        #def setchannel(self, title = 'e/#mu+jets, #geq%s jets' %njets[0]):
        #def setchannel(self, title = 'e/#mu+jets, #geq%s jets in SB' %njets[0]):
        #def setchannel(self, title = 'l+jets'):
        xpos = 1. - ROOT.gPad.GetRightMargin()
        ypos = 1. - ROOT.gPad.GetTopMargin()
        lxtitle = TLatex(0., 0., 'Z')
        lxtitle.SetNDC(True)
        lxtitle.SetTextFont(63)
        lxtitle.SetTextSize(25)
        lxtitle.SetTextAlign(13)
        lxtitle.DrawLatex(0.35, ypos - 0.03, title)

    def cmstext(self, add=''):
        xpos = ROOT.gPad.GetLeftMargin()
        ypos = 1. - ROOT.gPad.GetTopMargin()
        self.lx = TLatex(0., 0., 'Z')
        self.lx.SetNDC(True)
        self.lx.SetTextFont(62)
        self.lx.SetTextSize(0.07)
        self.lx.SetTextAlign(13)
        self.lx.DrawLatex(xpos + 0.04, ypos - 0.03, 'CMS')
        self.lx2 = TLatex(0., 0., 'Z')
        self.lx2.SetNDC(True)
        self.lx2.SetTextFont(52)
        self.lx2.SetTextSize(0.05)
        self.lx2.SetTextAlign(13)
        self.lx2.DrawLatex(xpos + 0.04, ypos - 0.10, 'Preliminary')

    def settitle(self, title):
        xpos = 1. - ROOT.gPad.GetRightMargin()
        ypos = 1. - ROOT.gPad.GetTopMargin()
        self.lxtitle = TLatex(0., 0., 'Z')
        self.lxtitle.SetNDC(True)
        self.lxtitle.SetTextFont(42)
        self.lxtitle.SetTextSize(0.07)
        self.lxtitle.SetTextAlign(31)
        self.lxtitle.DrawLatex(xpos, ypos + 0.02, title)

    def printLatexYieldTable(self, fname='yield_table.tex'):
        ''' This function will print a table based on how the addMCplot and addDAplot functions were called.
	        It will sum over all files that have no title, and assing them to the previous title. So for example:
	           plot[p].addMCplot(DYfile, p, 'V+Jets', DYscale, ROOT.kGreen+2, projection = pro)
	           plot[p].addMCplot(Wfile, p, '', Wscale, ROOT.kGreen+2, projection = pro)
	        will create a category 'V+Jets' that includes DY and W+jets events stored in DYfile and Wfile.
	        A call to this function should be added just after a call to drawAddWithRatio for that particular histogram, and then, for example:
	           can = plot[p].drawAddWithRatio( .......
	           if (p == "RECO/all_njets"):
	                 plot[p].printLatexYieldTable('totyield_table.tex'
	        '''
        MCtot = 0.
        MCtot_err = 0.
        category_yield = []
        category_err = []
        category_title = []
        cat_yield = 0.
        cat_err = 0.
        for index, hist in enumerate(self.MCplots):
            if hist.GetTitle() != '':
                category_title.append(hist.GetTitle())
                cat_yield = 0.
                cat_err = 0.
            err = ROOT.Double(0)
            # Make sure you run this over a histogram with known under- and overflows!
            # For example number of jets, or MET, anything that hasn't been initialized to -9
            events = hist.IntegralAndError(0, hist.GetNbinsX() + 1, err)
            #events = hist.Integral()
            cat_yield += events
            cat_err = math.sqrt(cat_err * cat_err + err * err)
            if len(self.MCplots
                   ) == index + 1 or self.MCplots[index + 1].GetTitle() != '':
                category_yield.append(cat_yield)
                category_err.append(cat_err)
            MCtot += events
            MCtot_err = math.sqrt(MCtot_err * MCtot_err + err * err)

    # Ready to print the numbers, first open the latex file:
        latexfile = open(fname, "w")
        latexfile.write(
            "\\begin{tabular}{l|r@{$\\pm$}l} \\hline \n")  # r@{$\pm$}l
        latexfile.write("%-12s & %20s \\\\ \\hline \n" %
                        ('Source', '\multicolumn{2}{c}{Yield}'))
        for i in range(len(category_title)):
            print "%-12s %5.1f +- %4.1f" % (category_title[i],
                                            category_yield[i], category_err[i])
            latexfile.write(
                "%-12s & %5.1f & %4.1f \\\\ \n" %
                (category_title[i], category_yield[i], category_err[i]))

        print "%-12s %5.1f +- %4.1f" % ('BKG SUM ', MCtot, MCtot_err)
        latexfile.write("%-12s & %5.1f & %4.1f\\\\ \\hline \n" %
                        ('BKG SUM ', MCtot, MCtot_err))

        DAtot = 0.
        for hist in self.DAplots:
            DAtot += hist.Integral()
        print "%-12s %5i" % ('Data ', DAtot)
        latexfile.write("%-12s & \multicolumn{2}{c}{%5i} \\\\ \n" %
                        ('Data ', DAtot))
        latexfile.write("\\end{tabular} \n")
        latexfile.close()
        print "Wrote LaTeX table with yields in: ", fname
        print "The errors are obtained from ROOT::TH1::IntegralAndError() and added in quadrature per category"
        return [DAtot, MCtot, MCtot_err]

    def addMCplot(self,
                  filename,
                  histpath,
                  title,
                  scale,
                  color,
                  projection=''):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
            print "little fox", self.tfiles[filename], histpath
        if projection == 'Y':
            self.MCplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.MCplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        else:
            self.MCplots.append(TH1D(self.tfiles[filename].Get(histpath)))
            print "fox"
        self.MCplots[-1].SetFillColor(color)
        self.MCplots[-1].SetLineColor(color)
        #self.MCplots[-1].Scale(scale, 'width')
        self.MCplots[-1].Scale(scale)
        self.MCplots[-1].SetTitle(title)

    def setUncTitle(self, unctitle):
        self.unctitle = unctitle

    def addUncerHist(self,
                     fcentral,
                     datascale,
                     datascaledw,
                     datascaleup,
                     ferrdown,
                     ferrup,
                     hist,
                     scaleUnc,
                     projection='',
                     Norm=False,
                     AsymmetricError=False):
        if self.unc == False:
            self.herr = TH1D(self.DAplots[-1])
            self.herr.Reset()
            self.herr.SetName('err')
            if AsymmetricError:
                self.herrup = TH1D(self.DAplots[-1])
                self.herrup.Reset()
                self.herrup.SetName('errup')
                self.herrdw = TH1D(self.DAplots[-1])
                self.herrdw.Reset()
                self.herrdw.SetName('errdw')
            self.unc = True
        if fcentral not in self.tfiles:
            self.tfiles[fcentral] = TFile(fcentral, 'read')
        if ferrdown not in self.tfiles:
            self.tfiles[ferrdown] = TFile(ferrdown, 'read')
        if ferrup not in self.tfiles:
            self.tfiles[ferrup] = TFile(ferrup, 'read')

        hcen = self.tfiles[fcentral].Get(hist)
        hdown = self.tfiles[ferrdown].Get(hist)
        hup = self.tfiles[ferrup].Get(hist)
        print "normalization precheck:", hcen.Integral(), hdown.Integral(
        ), hup.Integral(), datascale, datascaleup, datascaledw
        if Norm and (hup.Integral() != 0. and hdown.Integral() != 0.):
            hcen.Scale(datascale)
            hup.Scale(datascaleup)
            hdown.Scale(datascaledw)
            hup.Scale(hcen.Integral() / hup.Integral())
            hdown.Scale(hcen.Integral() / hdown.Integral())
        else:
            hcen.Scale(datascale)
            hup.Scale(datascaleup)
            hdown.Scale(datascaledw)
        print "normalization check:", hcen.Integral(), hdown.Integral(
        ), hup.Integral()
        if projection == 'Y':
            hcen = TH1D(hcen.ProjectionY())
            hdown = TH1D(hdown.ProjectionY())
            hup = TH1D(hup.ProjectionY())
        if projection == 'X':
            hcen = TH1D(hcen.ProjectionX())
            hdown = TH1D(hdown.ProjectionX())
            hup = TH1D(hup.ProjectionX())

        self.cumaddhist = []
        self.cumaddhist.append(TH1D(self.MCplots[0]))
        for hist in self.MCplots[1:]:
            self.cumaddhist.append(TH1D(self.cumaddhist[-1]))
            self.cumaddhist[-1].Add(hist)

        for b in range(1, 1 + self.herr.GetNbinsX()):
            cen = hcen.GetBinContent(b)
            tot = self.cumaddhist[-1].GetBinContent(b)
            if cen == 0 or tot == 0:
                continue
            up = hup.GetBinContent(b)
            down = hdown.GetBinContent(b)
            old = self.herr.GetBinContent(b)

            errA = (up - cen) * scaleUnc / cen
            errB = (down - cen) * scaleUnc / cen
            err = (abs(errA) + abs(errB)) / 2.
            #err = max(abs(errA), abs(errB))
            compWeight = cen / tot

            self.herr.SetBinContent(b,
                                    math.sqrt(old**2 + err**2 * compWeight**2))
            #self.herr.SetBinContent(b, math.sqrt(old**2 + err**2))
            #print scaleUnc

            if AsymmetricError:
                old = self.herrup.GetBinContent(b)
                self.herrup.SetBinContent(
                    b, math.sqrt(old**2 + errA**2 * compWeight**2))
                old = self.herrdw.GetBinContent(b)
                self.herrdw.SetBinContent(
                    b, math.sqrt(old**2 + errB**2 * compWeight**2))

        #Those are important !!!
        hcen.Scale(1 / datascale)
        hup.Scale(1 / datascaleup)
        hdown.Scale(1 / datascaledw)
        if Norm and (hup.Integral() != 0 and hdown.Integral() != 0):
            hup.Scale(1 / (hcen.Integral() / hup.Integral()))
            hdown.Scale(1 / (hcen.Integral() / hdown.Integral()))

    def addUncerVal(self, val):
        if self.unc == False:
            self.herr = TH1D(self.DAplots[-1])
            self.herr.Reset()
            self.herr.SetName('err')
            self.unc = True
        for b in range(1, 1 + self.herr.GetNbinsX()):
            old = self.herr.GetBinContent(b)
            self.herr.SetBinContent(b, math.sqrt(old**2 + val**2))

    def addUncerValBins(self, valist):
        if self.unc == False:
            self.herr = TH1D(self.DAplots[-1])
            self.herr.Reset()
            self.herr.SetName('err')
            self.unc = True
        for b in range(len(valist)):
            old = self.herr.GetBinContent(b + 4)
            print old, valist[b], math.sqrt(old**2 + valist[b]**2), b + 1
            self.herr.SetBinContent(b + 4, math.sqrt(old**2 + valist[b]**2))

    #def addDAplot(self, filename, histpath, title, projection = '', scale = 1.):#close box
    def addDAplot(self, filename, histpath, title, scale, projection=''):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
        if projection == 'Y':
            self.DAplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.DAplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        else:
            self.DAplots.append(TH1D(self.tfiles[filename].Get(histpath)))
        self.DAplots[-1].SetTitle(title)
        self.DAplots[-1].Scale(scale)
        #self.DAplots[-1].Scale(1., 'width')
        self.DAplots[-1].Scale(1.)  #//close box

    def addOtherplot(self,
                     filename,
                     histpath,
                     title,
                     scale,
                     color,
                     style=1,
                     projection=''):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
        if projection == 'Y':
            self.Otherplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.Otherplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        else:
            self.Otherplots.append(TH1D(self.tfiles[filename].Get(histpath)))
        #self.NOplots[-1].SetFillColor(color)
        self.Otherplots[-1].SetLineColor(color)
        self.Otherplots[-1].SetLineStyle(style)
        self.Otherplots[-1].SetTitle(title)
        self.Otherplots[-1].Scale(scale)

    def addNormplot(self, filename, histpath, title, color, projection=''):
        if filename not in self.tfiles:
            self.tfiles[filename] = TFile(filename, 'read')
        if projection == 'Y':
            self.NOplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionY()))
        elif projection == 'X':
            self.NOplots.append(
                TH1D(self.tfiles[filename].Get(histpath).ProjectionX()))
        else:
            self.NOplots.append(TH1D(self.tfiles[filename].Get(histpath)))
        #self.NOplots[-1].SetFillColor(color)
        self.NOplots[-1].SetLineColor(color)
        self.NOplots[-1].SetTitle(title)

    def drawAddWithRatio(self,
                         options='hist',
                         rebin=1,
                         legtitle='',
                         title='',
                         ratio=False,
                         rangemin=0.,
                         rangemax=0.,
                         printbinwidth=True,
                         xtitle='',
                         ytitle='',
                         logy=False,
                         xlabels=[],
                         AsymmetricError=False):
        self.cumaddhist = []
        self.cumaddhist.append(TH1D(self.MCplots[0]))
        for hist in self.MCplots[1:]:
            self.cumaddhist.append(TH1D(self.cumaddhist[-1]))
            self.cumaddhist[-1].Add(hist)
            self.cumaddhist[-1].SetFillColor(hist.GetFillColor())
            self.cumaddhist[-1].SetLineColor(hist.GetLineColor())
            self.cumaddhist[-1].SetTitle(hist.GetTitle())

        totalevents = 0.
        for hist in self.MCplots:
            if rangemin != rangemax:
                hist.GetXaxis().SetRangeUser(rangemin, rangemax)
            totalevents += hist.Integral()
        print 'Total MC events: ', totalevents
        totalevents = 0.
        for hist in self.DAplots:
            if rangemin != rangemax:
                hist.GetXaxis().SetRangeUser(rangemin, rangemax)
            totalevents += hist.Integral()
        print 'Total DA events: ', totalevents
        mymax = 0.
        self.Canvases.append(
            TCanvas('CanvasAdd_' + self.cumaddhist[-1].GetName(),
                    'CanvasAdd_' + self.cumaddhist[-1].GetName(), 800, 600))
        if ratio == True:
            split = 0.3
            spaceleft = 0.15
            spaceright = 0.05
            self.Pads.append(TPad("histpad", "histpad", 0, split, 1., 1.))
            self.Pads[-1].SetTopMargin(0.05)
            self.Pads[-1].SetBottomMargin(0.022)
            self.Pads[-1].SetLeftMargin(spaceleft)
            self.Pads[-1].SetRightMargin(spaceright)
            self.Pads[-1].Draw()
            self.Canvases[-1].cd()
            self.Pads.append(TPad("divpad", "divpad", 0, 0, 1., split))
            self.Pads[-1].SetTopMargin(0.0)
            self.Pads[-1].SetBottomMargin(0.4)
            self.Pads[-1].SetLeftMargin(spaceleft)
            self.Pads[-1].SetRightMargin(spaceright)
            self.Pads[-1].Draw()
            self.Pads[-2].cd()

        if len(title) > 0:
            ROOT.gPad.SetTopMargin(0.1)
        self.legend(legtitle)
        if len(xlabels) != 0:
            b = 0
            for label in xlabels:
                b += 1
                self.cumaddhist[-1].GetXaxis().SetBinLabel(b, label)
        if ratio == True:
            self.cumaddhist[-1].GetXaxis().SetTitleOffset(5.)
            self.cumaddhist[-1].GetXaxis().SetLabelOffset(5.)

        xList, yList = array('d'), array('d')
        errleftList, errightList = array('d'), array('d')
        errupList, errdwList = array('d'), array('d')
        relupList, reldwList = array('d'), array('d')

        for hist in reversed(self.cumaddhist):
            hist.Rebin(rebin)
            hist.Draw(options)

            mymax = max(mymax, hist.GetMaximum())
            if rangemin != 0 or rangemax != 0:
                hist.GetXaxis().SetRangeUser(rangemin, rangemax)
            if 'same' not in options:
                if self.unc:
                    self.herr.Rebin(rebin)
                    self.herr.Scale(1. / rebin)
                    self.errprint = TH1D(hist)
                    self.errprint.SetName('errprint')
                    for b in range(1, self.errprint.GetNbinsX() + 1):
                        self.errprint.SetBinError(
                            b,
                            self.herr.GetBinContent(b) * hist.GetBinContent(b))

                    self.errprint.SetFillColor(1)
                    self.errprint.SetLineColor(1)
                    self.errprint.SetLineWidth(0)
                    self.errprint.SetFillStyle(3354)
                    #self.errprint.SetFillStyle(3344)
                    self.errprint.Draw('E2same')  #//close box

                    if AsymmetricError:
                        self.herrup.Rebin(rebin)
                        self.herrup.Scale(1. / rebin)
                        self.herrdw.Rebin(rebin)
                        self.herrdw.Scale(1. / rebin)
                        #self.DAplots[0].Rebin(rebin)

                        for b in range(1, 1 + self.herr.GetNbinsX()):
                            xList.append(self.cumaddhist[-1].GetBinCenter(b))
                            yList.append(self.cumaddhist[-1].GetBinContent(b))
                            #yList.append(self.DAplots[0].GetBinContent(b))
                            errleftList.append(self.cumaddhist[-1].GetXaxis(
                            ).GetBinCenter(b) - self.cumaddhist[-1].GetXaxis().
                                               GetBinLowEdge(b))
                            errightList.append(
                                self.cumaddhist[-1].GetXaxis().GetBinUpEdge(
                                    b) -
                                self.cumaddhist[-1].GetXaxis().GetBinCenter(b))
                            #errupList.append(self.herrup.GetBinContent(b)*self.cumaddhist[-1].GetBinContent(b))
                            #errdwList.append(self.herrdw.GetBinContent(b)*self.cumaddhist[-1].GetBinContent(b))
                            errupList.append(
                                self.herrup.GetBinContent(b) *
                                self.DAplots[0].GetBinContent(b))
                            errdwList.append(
                                self.herrdw.GetBinContent(b) *
                                self.DAplots[0].GetBinContent(b))
                            relupList.append(self.herrup.GetBinContent(b))
                            reldwList.append(self.herrdw.GetBinContent(b))

                        self.gerr = TGraphAsymmErrors(len(xList), xList, yList,
                                                      errleftList, errightList,
                                                      errdwList, errupList)
                        self.gerr.SetName('gerr')

                        self.gerr.SetFillColor(1)
                        self.gerr.SetLineColor(1)
                        self.gerr.SetLineWidth(0)
                        self.gerr.SetFillStyle(3354)
                        self.gerr.Draw('E2same')  #//close box
                    #else:
                    #self.errprint.Draw('E2same')#//close box

                units = re.findall('\[.*\]', hist.GetXaxis().GetTitle())
                unit = ''
                if len(units) == 1:
                    unit = units[0][1:-1]
                if ytitle == '':
                    if len(hist.GetYaxis().GetTitle()) == 0:
                        ytitle = 'Events'
                    else:
                        ytitle = hist.GetYaxis().GetTitle()
                        #ytitle = ytitle.lower()
                if printbinwidth == True:
                    hist.GetYaxis().SetTitle(
                        ytitle +
                        ' / {0:g}'.format(hist.GetXaxis().GetBinWidth(1)) +
                        ' ' + unit)
                else:
                    hist.GetYaxis().SetTitle(ytitle)
                if (xtitle != ''):
                    hist.GetXaxis().SetTitle(xtitle)
                options += ' same'
        #if not AsymmetricError:
        #	self.errprint.Draw('E2same')#//close box

        for np in self.NOplots:
            np.Rebin(rebin)
            np.Scale(self.DAplots[0].Integral() / np.Integral())
            np.SetLineWidth(2)
            np.Draw('sameE0')  #//close box
            mymax = max(mymax, np.GetMaximum())
        for op in self.Otherplots:
            op.Rebin(rebin)
            op.SetLineWidth(2)
            op.Draw('sameE0')  #//close box
            mymax = max(mymax, op.GetMaximum())
        if len(self.DAplots) == 1:
            self.DAplots[0].Rebin(rebin)
            self.DAplots[0].SetMarkerStyle(20)
            self.DAplots[0].SetMarkerSize(1.1)
            self.DAplots[0].SetLineWidth(2)
            self.DAplots[0].Draw('E1X0same')
            mymax = max(mymax, self.DAplots[0].GetMaximum())
        if len(self.DAplots) == 1:
            self.lg.AddEntry(self.DAplots[0], self.DAplots[0].GetTitle(), 'p')
        for hist in reversed(self.cumaddhist):
            if len(hist.GetTitle()) != 0:
                self.lg.AddEntry(hist, hist.GetTitle(), 'f')
        for np in self.NOplots:
            self.lg.AddEntry(np, np.GetTitle() + ' (Scaled)', 'l')
        for op in self.Otherplots:
            self.lg.AddEntry(op, op.GetTitle(), 'l')
        if len(self.unctitle) != 0:
            self.lg.AddEntry(self.errprint, self.unctitle, 'f')
        self.lg.Draw()
        self.settitle(title)
        self.setchannel()
        self.cmstext()
        if logy == False:
            self.cumaddhist[-1].GetYaxis().SetRangeUser(0, mymax * 1.5)
        if logy == True:
            self.cumaddhist[-1].GetYaxis().SetRangeUser(10, mymax * 50)
            self.Pads[-2].SetLogy(True)

        self.Pads[-2].RedrawAxis()
        if ratio == True:
            self.Pads[-1].cd()
            self.Pads[-1].SetGridy()
            self.DIVplots.append(TH1D(self.DAplots[0]))
            if (xtitle != ''):
                self.DIVplots[-1].GetXaxis().SetTitle(xtitle)
            #self.DIVplots[-1].Divide(self.cumaddhist[-1])
            printList = []
            for b in range(1, self.DIVplots[-1].GetNbinsX() + 1):
                if (self.cumaddhist[-1].GetBinContent(b) > 0.):
                    divval = self.DIVplots[-1].GetBinContent(
                        b) / self.cumaddhist[-1].GetBinContent(b)
                    divvalerr = self.DIVplots[-1].GetBinError(
                        b) / self.cumaddhist[-1].GetBinContent(b)
                    printList.append(divval)
                    self.DIVplots[-1].SetBinContent(b, divval)
                    #self.DIVplots[-1].SetBinError(b, divvalerr)
                    self.DIVplots[-1].SetBinError(
                        b,
                        math.sqrt(divvalerr**2 +
                                  (self.cumaddhist[-1].GetBinError(b) /
                                   self.cumaddhist[-1].GetBinContent(b))**2))
                else:
                    printList.append(0)
                    self.DIVplots[-1].SetBinContent(b, 0.)
                    self.DIVplots[-1].SetBinError(b, 0.)
            print printList
            self.DIVplots[-1].SetMarkerSize(1.1)
            if len(xlabels) != 0:
                b = 0
                for label in xlabels:
                    b += 1
                    self.DIVplots[-1].GetXaxis().SetBinLabel(b, label)
            self.DIVplots[-1].Draw('E1X0same')
            self.DIVplots[-1].GetXaxis().SetTitleOffset(3)
            self.DIVplots[-1].GetYaxis().SetTitle('#frac{Data}{MC}')
            self.DIVplots[-1].GetYaxis().SetTitleOffset(1.3)
            self.DIVplots[-1].GetYaxis().SetRangeUser(0.5, 1.5)
            self.DIVplots[-1].GetYaxis().SetNdivisions(105)
            if rangemin != 0 or rangemax != 0:
                self.DIVplots[-1].GetXaxis().SetRangeUser(rangemin, rangemax)
            if self.unc:
                self.errprintratio = TH1D(self.herr)
                for b in range(1, self.errprintratio.GetNbinsX() + 1):
                    self.errprintratio.SetBinError(b,
                                                   self.herr.GetBinContent(b))
                    self.errprintratio.SetBinContent(b, 1.)
                self.errprintratio.SetFillColor(1)
                #self.errprintratio.SetFillStyle(3002)
                self.errprintratio.SetFillStyle(3354)
                #self.errprintratio.Draw('E2same')#//close box

                if AsymmetricError:
                    self.gerratio = TGraphAsymmErrors(
                        len(xList), xList, array('d', [1] * len(xList)),
                        errleftList, errightList, reldwList, relupList)
                    self.gerratio.SetFillColor(1)
                    self.gerratio.SetFillStyle(3354)
                    self.gerratio.Draw('E2same')
                else:
                    self.errprintratio.Draw('E2same')  #//close box

            self.DIVplots[-1].Draw('E1X0same')
        self.Pads[-1].RedrawAxis()

        return (self.Canvases[-1])
Exemplo n.º 16
0
def main():

    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-i", "--inputfile", dest="inputfile")
    parser.add_option("-N", "--multiplicity", dest="N", type="int", default=3)
    parser.add_option("-x", "--exclusive", action="store_true",\
          dest="isExclusive", default=False)
    parser.add_option("-l", "--label", dest="label", type="string", default="")
    parser.add_option("-z",
                      "--zeyneplabel",
                      action="store_true",
                      dest="zeynep",
                      default=True)
    (options, args) = parser.parse_args()

    N = options.N
    isExclusive = options.isExclusive
    label_text = options.label

    zeynep = options.zeynep

    if isExclusive and not (N == 2 or N == 3):
        parser.error("Exclusive plot only for N =2 or 3")

    import configurations as config
    from ROOT import TFile, TCanvas, THStack, TLegend, TPaveText, gStyle, TPad, TH1F, TGraphAsymmErrors, TMath
    from ModelParser import ModelKey

    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadBottomMargin(0.20)

    gStyle.SetErrorX(0.)

    suffix = ""
    if not isExclusive:
        suffix = "up"

    sm_files = []
    for model in config.sm_models:
        f = TFile("%s/%s.root" % (config.sm_dir, model), "READ")
        sm_files.append(f)

    bh_weights = []
    bh_files = []
    from BHXsec import BHXsec
    xsec = BHXsec()
    for model in config.bh_showcase:
        f = TFile("%s/%s.root" % (config.bh_dir, model), "READ")
        bh_files.append(f)
        h = f.Get("plotsNoCut/ST")
        nEvents = h.GetEntries()
        bh_weights.append(
            xsec.get(model) / nEvents * config.integrated_luminosity)

    c = TCanvas("ST_Mul%d%s" % (N, suffix), "ST_Mul%d%s" % (N, suffix), 500,
                600)
    hs = THStack()
    hs1 = THStack()

    infile = TFile(options.inputfile, "READ")
    hBkg = infile.Get("Background_N%d%s" % (N, suffix))
    #hnewBkg = infile.Get("histoTemplateN3_0")
    hnewBkg = infile.Get("ReferenceTemplateN3_0")
    gBkg = infile.Get("BackgroundGraph_N%d%s" % (N, suffix))
    hData = infile.Get("Data_N%d%s" % (N, suffix))
    hBkg = infile.Get("Background_N%d%s" % (N, suffix))
    hBkg.SetMarkerSize(0)
    hBkg_ = hBkg.Clone("BkgLine")
    hBkg.SetFillColor(33)
    hBkg.SetLineColor(33)
    hBkg_.SetLineWidth(3)
    hBkg_.SetLineColor(862)

    hs.Add(hBkg, "e3")
    hnewBkg.SetLineWidth(3)
    hnewBkg.Scale(10 * 3.407)
    hs.Add(hnewBkg, "l")

    legend = TLegend(0.2826613, 0.4819492, 0.6094355,
                     0.9416102)  # - only for N >= 2 and 3
    #legend = TLegend(0.3026613,0.5519492,0.6094355,0.9416102) # was 0.4919...zeynep

    #legend = TLegend(0.3526613,0.5519492,0.6094355,0.9416102) # was 0.4919...

    #legend.SetTextSize(0.041); #was 0.02966102
    legend.SetTextSize(0.037)
    legend.SetTextFont(42)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    if isExclusive:
        legend.SetHeader("Multiplicity N = %d" % N)
    else:
        legend.SetHeader("Multiplicity N #geq %d" % N)
    legend.AddEntry(hData, "Data", "lep")
    #legend.AddEntry(hnewBkg, "N=3 Fit Rescaled","l")
    legend.AddEntry(hBkg_, "Background", "l")
    legend.AddEntry(hBkg, "Uncertainty", "f")

    legend_sm = TLegend(0.6471774, 0.7069492, 0.8508065, 0.8471186)
    #   legend_sm = TLegend(0.6271774,0.7369492,0.8308065,0.8771186)
    #   legend_sm.SetTextSize(0.037);
    legend_sm.SetTextSize(0.037)

    legend_sm.SetTextFont(42)
    legend_sm.SetFillColor(0)
    legend_sm.SetLineColor(0)

    for i, f in enumerate(bh_files):
        h = f.Get("plotsN%d%s/ST" % (N, suffix))
        h.Rebin(config.rebin)
        h.Scale(bh_weights[i])

        # Add background
        for ibin in range(h.GetNbinsX()):
            h.SetBinContent(ibin+1,\
                  h.GetBinContent(ibin+1)\
                  + hBkg.GetBinContent(ibin+1))

            h.SetLineWidth(3)
            #h.SetLineColor(i+2)
            h.SetLineStyle(i + 2)

            #if i == 0:
            #h.SetLineColor(814)
            if i == 0:
                h.SetLineStyle(5)
                h.SetLineColor(899)
            if i == 1:
                h.SetLineStyle(9)
                h.SetLineColor(4)
            if i == 2:
                h.SetLineStyle(3)
                h.SetLineColor(614)

        hs.Add(h, "hist")
        model = ModelKey(config.bh_showcase[i])
        bh_legend = "M_{D} = %.1f TeV, M_{BH}^{ min} = %.1f TeV, n = %d" % (\
              model.parameter["MD"],
              model.parameter["M"],
              model.parameter["n"])
        if i == 3:
            bh_legend = "M_{D} = 3.0 TeV, M_{QBH}^{ min} = 4.0 TeV, n = 4"

        legend.AddEntry(h, bh_legend, "l")

#      qbh_legend = "M_{D} = 4.0 TeV, M_{QBH}^{ min} = 5.0 TeV, n = 5"

#      legend.AddEntry(h, qbh_legend, "l")

#if isExclusive:
    zeynep = True
    if zeynep:
        for i, f in enumerate(sm_files):
            h = f.Get("plotsN%d%s/ST" % (N, suffix))
            h.Rebin(config.rebin)
            h.Scale(config.integrated_luminosity)
            h.SetFillColor(config.sm_colors[i])
            h.SetLineColor(config.sm_colors[i])
            hs1.Add(h, "hist")
            legend_sm.AddEntry(h, config.sm_models[i], "f")

    #hs.Add(hData, "e")

    hs.Draw("nostack")
    hs1.Draw("same")

    c.SetLogy(1)
    hs.GetXaxis().SetTitle("S_{T} (GeV)")
    hs.GetYaxis().SetTitle(hData.GetYaxis().GetTitle())
    hs.GetYaxis().SetTitleOffset(1.25)

    hs.GetYaxis().SetTitleSize(0.04)
    hs.GetYaxis().SetLabelSize(0.04)
    hs.GetXaxis().SetTitleSize(0.01)
    hs.GetXaxis().SetLabelSize(0.01)

    ibin = 0
    #if isExclusive:
    #   hs.GetXaxis().SetRangeUser(config.fit_range[0], config.maxST)
    #   ibin = hData.FindBin(config.fit_range[0])
    #else:
    #   hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST)
    #   ibin = hData.FindBin(config.norm_range[0])

    if isExclusive:
        hs.GetXaxis().SetRangeUser(1800, config.maxST)
        ibin = hData.FindBin(1800)
    else:
        hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST)
        ibin = hData.FindBin(config.norm_range[0])

    from Styles import formatUncertainty
    formatUncertainty(gBkg)
    gBkg.Draw("LX")
    hData.Draw("sameex0")

    hs.SetMinimum(5e-1)
    if isExclusive:
        hs.SetMaximum(1e7)

#     hs.SetMaximum(hData.GetBinContent(ibin) * 40)
    else:
        #hs.SetMaximum(1e8)
        hs.SetMaximum(hData.GetBinContent(ibin) *
                      20)  # or 1e7 for N>=3 and use 4 models

    legend.Draw("plain")
    #if isExclusive:
    if zeynep:
        legend_sm.Draw("plain")

    if isExclusive:
        cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC")
    else:
        cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC")
    cmslabel.AddText(config.cmsTitle)
    #cmslabel.AddText(config.cmsSubtitle)
    cmslabel.SetFillColor(0)
    cmslabel.SetTextSize(0.041)
    cmslabel.Draw("plain")

    label = TPaveText(0.8891129, 0.8644068, 0.9435484, 0.9258475, "brNDC")
    label.SetFillColor(0)
    #label.SetTextSize(0.0529661);
    label.SetTextSize(0.0529661)
    label.AddText(label_text)
    label.Draw("plain")

    c.RedrawAxis()

    #Divide

    ibin = hData.FindBin(config.norm_range[0])
    #print ibin

    fbin = hData.FindBin(config.maxST)
    #print fbin

    hData.Sumw2()
    hBkg_.Sumw2()

    Pull = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100)
    Pull2 = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100)

    Ratio = hData.Clone()
    Ratio.Add(hBkg_, -1)
    #Ratio.Divide(hBkg_)

    Band = TGraphAsymmErrors(fbin - ibin + 1)

    for i in range(ibin - 1, fbin + 1):
        i += 1
        if hData.GetBinContent(i) != 0:
            value = hData.GetBinContent(i) + (hBkg_.GetBinError(i) *
                                              hBkg_.GetBinError(i))
            #print Ratio.GetBinError(i),  value**(0.5)
            #print i-19,i,(i)*100, hData.GetBinContent(i) , hBkg_.GetBinContent(i),hData.GetBinContent(i) - hBkg_.GetBinContent(i)
            Pull.SetBinContent(
                i - 19, (hData.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                Ratio.GetBinError(i))
            #print Ratio.GetBinError(i), abs(Ratio.GetBinContent(i))*0.05
            #Pull.SetBinContent(i-19,(hData.GetBinContent(i) - hBkg_.GetBinContent(i))/ Ratio.GetBinError(i))
            #Pull.SetBinContent(i-19,(hData.GetBinContent(i) / hBkg_.GetBinContent(i)))
            Pull.SetBinError(i - 19, Ratio.GetBinError(i))
            #Pull.SetBinError(i-19,hData.GetBinError(i)/gBkg.GetErrorY(i))
            if (hBkg_.GetBinContent(i) * 0.05 > hBkg_.GetBinError(i)):
                #print "bin error too small changing the error to: ", hBkg_.GetBinContent(i)*0.05
                Pull2.SetBinContent(
                    i - 19,
                    (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                    (hBkg_.GetBinContent(i) * 0.05))
            else:
                Pull2.SetBinContent(
                    i - 19,
                    (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                    hBkg_.GetBinError(i))
            #print hBkg_.GetBinError(i), hBkg_.GetBinContent(i)*0.05
            #print i, " Pull2: ", Pull2.GetBinContent(i-19), "hnewBkg.GetBinContent(i-1): " , hnewBkg.GetBinContent(i-1), "hBkg_.GetBinContent(i): ", hBkg_.GetBinContent(i)
        else:
            Pull.SetBinContent(i - 19, 0)
            Pull2.SetBinContent(
                i - 19,
                (hnewBkg.GetBinContent(i - 1) - hBkg_.GetBinContent(i)) /
                hBkg_.GetBinError(i))

        Band.SetPoint(i, hBkg_.GetBinCenter(i), 1.0)
        #print hBkg_.GetBinContent(i), hBkg_.GetBinError(i)
        up = abs(1. - ((hBkg_.GetBinContent(i) + hBkg_.GetBinError(i)) /
                       hBkg_.GetBinContent(i)))
        down = abs(1. - ((hBkg_.GetBinContent(i) - hBkg_.GetBinError(i)) /
                         hBkg_.GetBinContent(i)))
        Band.SetPointError(i, 0., 0., down, up)

    #Band.Print()
    pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)

    pad.SetTopMargin(0.799999)
    pad.SetRightMargin(0.05)
    pad.SetBottomMargin(0.09)

    pad.SetFillColor(0)
    #pad.SetGridy(1)
    pad.SetFillStyle(0)
    pad.Draw("same")
    pad.cd(0)

    Ratio.SetMarkerStyle(20)
    Pull.SetMarkerStyle(20)
    Pull.SetLineColor(1)
    Pull.SetMarkerSize(0.9)
    #Pull.SetMaximum(3)
    #Pull.SetMinimum(-1)

    Pull.SetMaximum(2.5)
    Pull.SetMinimum(-2.5)
    Pull.GetYaxis().SetNdivisions(5, 1)

    Pull.GetXaxis().SetTitle('S_{T} (GeV)')
    Pull.GetXaxis().SetLabelSize(0.04)

    Pull.GetYaxis().SetTitleOffset(1.05)
    Pull.GetYaxis().SetLabelSize(0.02)
    Pull.GetYaxis().SetTitleSize(0.025)
    Pull.GetYaxis().CenterTitle(1)

    Pull.GetYaxis().SetTitle('#sigma(Data-Bkg)')

    Pull.SetFillColor(2)
    Pull.Draw("HIST")
    Pull2.SetLineColor(862)
    Pull2.SetLineWidth(3)
    Pull2.SetLineStyle(2)
    #Pull2.Draw("SAME")
    formatUncertainty(Band)
    Band.SetFillStyle(3001)

    # Band.Draw("le3")
    # Pull.Draw("ex0same")
    pad.RedrawAxis()

    gStyle.SetOptStat(0)

    #block1 =TPaveText(0.370,0.84,0.351,0.86,"brNDC"); # for N>=2 and >=3 only
    #block1 =TPaveText(0.361,0.85,0.377,0.87,"brNDC");
    #block1 =TPaveText(0.333,0.88,0.354,0.85,"brNDC") #for n = 2 only

    block1 = TPaveText(0.331, 0.82, 0.357, 0.85, "brNDC")
    #FOR n=3 only
    block1.SetFillColor(0)
    block1.Draw("plain")

    #block2 =TPaveText(0.305,0.84,0.333,0.86,"brNDC"); # for N>=2 and >=3 only
    #block2 =TPaveText(0.395,0.85,0.41,0.87,"brNDC");
    #block2 =TPaveText(0.296,0.88,0.316,0.85,"brNDC"); for n =2 only

    block2 = TPaveText(0.295, 0.82, 0.317, 0.85, "brNDC")
    #FOR n=3 only
    block2.SetFillColor(0)
    block2.Draw("plain")

    if isExclusive:
        c.Print("ST_Mul%d.pdf" % N)
        c.Print("ST_Mul%d.png" % N)
    else:
        c.Print("ST_Mul%dup.pdf" % N)
        c.Print("ST_Mul%dup.png" % N)
    c.Update()

    raw_input("Press Enter to continue...")
Exemplo n.º 17
0
def limit():
    method = ''
    channel = "bb"
    particleP = "Z'"
    particle = channel
    multF = ZPTOBB
    THEORY = ['A1', 'B3']

    suffix = "_" + BTAGGING
    if ISMC: suffix += "_MC"
    if SY: suffix += "_comb"
    #if method=="cls": suffix="_CLs"

    if SY:
        filename = "./combine/limits/MANtag_study/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt"
    else:
        filename = "./combine/limits/MANtag_study/" + BTAGGING + "/" + YEAR + "_M%d.txt"
    if CATEGORY != "":
        filename = filename.replace(
            BTAGGING + "/", BTAGGING + "/single_category/" + CATEGORY + "_")
        suffix += "_" + CATEGORY
    if ISMC: filename = filename.replace(".txt", "_MC.txt")
    mass, val = fillValues(filename)

    #print "mass =",mass
    #print "val =", val

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

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

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

    for t in THEORY:
        Theory[t] = TGraphAsymmErrors()
        addXZH = True
        for m in sorted(HVT[t]['W']['XS'].keys()):
            if m < mass[0] or m > mass[-1]: continue
            if m > 4500:
                continue  ## for now because I don't have the higher mass xs FIXME
            XsZ, XsZ_Up, XsZ_Down = 0., 0., 0.
            if addXZH:
                XsZ = 1000. * HVT[t]['Z']['XS'][
                    m] * 0.12  #temporary BR value set to 0.12 FIXME
                XsZ_Up = XsZ * (1. + math.hypot(HVT[t]['Z']['QCD'][m][0] - 1.,
                                                HVT[t]['Z']['PDF'][m][0] - 1.))
                XsZ_Down = XsZ * (1. -
                                  math.hypot(1. - HVT[t]['Z']['QCD'][m][0],
                                             1. - HVT[t]['Z']['PDF'][m][0]))

            n = Theory[t].GetN()
            Theory[t].SetPoint(n, m, XsZ)
            Theory[t].SetPointError(n, 0., 0., (XsZ - XsZ_Down),
                                    (XsZ_Up - XsZ))

            Theory[t].SetLineColor(theoryLineColor[t])
            Theory[t].SetFillColor(theoryFillColor[t])
            Theory[t].SetFillStyle(theoryFillStyle[t])
            Theory[t].SetLineWidth(2)
            #Theory[t].SetLineStyle(7)

    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp1s.SetFillColor(417)  #kGreen+1
    Exp1s.SetLineColor(417)  #kGreen+1
    Exp2s.SetFillColor(800)  #kOrange
    Exp2s.SetLineColor(800)  #kOrange
    Exp2s.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle("#sigma(" + particleP + ") #bf{#it{#Beta}}(" +
                              particleP + " #rightarrow " + particle +
                              ") (fb)")
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

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

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

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

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.050)
    Exp2s.GetYaxis().SetTitleSize(0.050)
    Exp2s.GetXaxis().SetLabelSize(0.045)
    Exp2s.GetYaxis().SetLabelSize(0.045)
    Exp2s.GetXaxis().SetTitleOffset(0.90)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetRangeUser(0.1, 5.e3)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    #Exp2s.GetXaxis().SetRangeUser(mass[0], min(mass[-1], MAXIMUM[channel] if channel in MAXIMUM else 1.e6))
    Exp2s.GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1])
    #drawAnalysis(channel)
    drawAnalysis("")
    #drawRegion(channel, True)
    drawRegion("", True)
    #drawCMS(LUMI, "Simulation Preliminary") #Preliminary
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)

    # legend
    top = 0.9
    nitems = 4 + len(THEORY)

    leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.98, top)
    #leg = TLegend(0.45, top-nitems*0.3/5., 0.98, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected", "l")
    leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    for t in THEORY:
        leg.AddEntry(Theory[t], theoryLabel[t], "fl")
    leg.Draw()
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.045)
    latex.SetTextFont(42)
    #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h")

    leg2 = TLegend(0.12, 0.225 - 2 * 0.25 / 5., 0.65, 0.225)
    leg2.SetBorderSize(0)
    leg2.SetFillStyle(0)  #1001
    leg2.SetFillColor(0)
    c1.GetPad(0).RedrawAxis()

    leg2.Draw()
    if not options.blind: Obs0s.Draw("SAME, L")
    c1.GetPad(0).Update()

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

    c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR +
             suffix + ".png")
    c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR +
             suffix + ".pdf")
    if 'ah' in channel or 'sl' in channel:
        c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR +
                 suffix + ".C")
        c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR +
                 suffix + ".root")

    for t in THEORY:
        print "Model", t, ":",
        for m in range(mass[0], mass[-1], 1):
            if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == (
                    Theory[t].Eval(m + 1) > Obs0s.Eval(m + 1)):
                print m,
        print ""

    return
Exemplo n.º 18
0
] * len(brazil_data))
rms = array("d", list(map(itemgetter(2), brazil_data)))
rms2 = array("d", [2 * r for r in rms])
low_2sigma = array("d", list(map(itemgetter(3), brazil_data)))
low_1sigma = array("d", list(map(itemgetter(4), brazil_data)))
high_1sigma = array("d", list(map(itemgetter(5), brazil_data)))
high_2sigma = array("d", list(map(itemgetter(6), brazil_data)))

mg = TMultiGraph()
#mg.SetTitle(title)
mg.SetTitle(job_id)

brazil_yellow = TGraphAsymmErrors(len(brazil_data), x, mean, xerr, xerr,
                                  low_2sigma, high_2sigma)
brazil_yellow.SetFillColor(5)
brazil_yellow.SetFillStyle(1001)
brazil_yellow.SetLineColor(3)
brazil_yellow.SetLineWidth(10)
brazil_yellow.SetMarkerColor(3)

brazil_green = TGraphAsymmErrors(len(brazil_data), x, mean, xerr, xerr,
                                 low_1sigma, high_1sigma)
brazil_green.SetFillColor(3)
brazil_green.SetFillStyle(1001)
brazil_green.SetLineColor(3)
brazil_green.SetLineWidth(3)

mg.Add(brazil_yellow)
mg.Add(brazil_green)
mg.Draw("a3")
Exemplo n.º 19
0
def limit(method, channel):
    particle = channel[1:2]
    particleP = particle + "'" if channel.startswith('X') else channel[0]
    THEORY = ['A1', 'B3'] if channel.startswith('X') else []

    suffix = ""
    if method == "hvt": suffix = "_HVT"
    if method == "cls": suffix = "_CLs"
    if method == "monoH": suffix = "_monoH"

    filename = "./combine/" + method + "/" + channel + "_M%d.txt"
    mass, val = fillValues(filename)

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

    for i, m in enumerate(mass):
        if not m in val:
            print "Key Error:", m, "not in value map"
            continue
        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0])
        Exp0s.SetPoint(n, m, val[m][3])
        Exp1s.SetPoint(n, m, val[m][3])
        Exp1s.SetPointError(n, 0., 0., val[m][3] - val[m][2],
                            val[m][4] - val[m][3])
        Exp2s.SetPoint(n, m, val[m][3])
        Exp2s.SetPointError(n, 0., 0., val[m][3] - val[m][1],
                            val[m][5] - val[m][3])
        if len(val[m]) > 6: Sign.SetPoint(n, m, val[m][6])
        if len(val[m]) > 7: pVal.SetPoint(n, m, val[m][7])
        if len(val[m]) > 8: Best.SetPoint(n, m, val[m][8])
        if len(val[m]) > 10:
            Best.SetPointError(n, 0., 0., abs(val[m][9]), val[m][10])

    for t in THEORY:
        Theory[t] = TGraphAsymmErrors()
        for m in sorted(HVT[t]['Z']['XS'].keys()):
            if m < mass[0] or m > mass[-1]: continue
            XsW, XsW_Up, XsW_Down, XsZ, XsZ_Up, XsZ_Down = 0., 0., 0., 0., 0., 0.
            XsZ = 1000. * HVT[t]['Z']['XS'][m] * HVT[t]['Z']['BR'][m]
            XsZ_Up = XsZ * (1. + math.hypot(HVT[t]['Z']['QCD'][m][0] - 1.,
                                            HVT[t]['Z']['PDF'][m][0] - 1.))
            XsZ_Down = XsZ * (1. - math.hypot(1. - HVT[t]['Z']['QCD'][m][0],
                                              1. - HVT[t]['Z']['PDF'][m][0]))

            n = Theory[t].GetN()
            Theory[t].SetPoint(n, m, XsW + XsZ)
            Theory[t].SetPointError(n, 0., 0.,
                                    (XsW - XsW_Down) + (XsZ - XsZ_Down),
                                    (XsW_Up - XsW) + (XsZ_Up - XsZ))

            Theory[t].SetLineColor(theoryLineColor[t])
            Theory[t].SetFillColor(theoryFillColor[t])
            Theory[t].SetFillStyle(theoryFillStyle[t])
            Theory[t].SetLineWidth(2)
            #Theory[t].SetLineStyle(7)

    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp1s.SetFillColor(417)  #kGreen+1
    Exp1s.SetLineColor(417)  #kGreen+1
    Exp2s.SetFillColor(800)  #kOrange
    Exp2s.SetLineColor(800)  #kOrange
    Exp2s.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle("#sigma(" + particleP + ") #bf{#it{#Beta}}(" +
                              particleP + " #rightarrow " + particle +
                              "h) (fb)")
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

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

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

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

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.050)
    Exp2s.GetYaxis().SetTitleSize(0.050)
    Exp2s.GetXaxis().SetLabelSize(0.045)
    Exp2s.GetYaxis().SetLabelSize(0.045)
    Exp2s.GetXaxis().SetTitleOffset(0.90)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetRangeUser(0.01, 5.e3)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    Exp2s.GetXaxis().SetRangeUser(
        mass[0], min(mass[-1],
                     MAXIMUM[channel] if channel in MAXIMUM else 1.e6))
    drawAnalysis(channel)
    drawRegion(channel, True)
    drawCMS(LUMI, YEAR, "Preliminary")  #Preliminary

    # legend
    top = 0.9
    nitems = 4 + len(THEORY)

    leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.98, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected", "l")
    leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    for t in THEORY:
        leg.AddEntry(Theory[t], theoryLabel[t], "fl")
    leg.Draw()
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.045)
    latex.SetTextFont(42)
    #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h")

    leg2 = TLegend(0.12, 0.225 - 2 * 0.25 / 5., 0.65, 0.225)
    leg2.SetBorderSize(0)
    leg2.SetFillStyle(0)  #1001
    leg2.SetFillColor(0)
    c1.GetPad(0).RedrawAxis()
    """
    if True and channel.endswith('sl'):
        mass, val = fillValues("./combine/alpha/X"+particle+"Hbonly_M%d.txt")
        Exp, Obs = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(mass):
            if not m in val: continue
            Exp.SetPoint(Exp.GetN(), m, val[m][3])
            Obs.SetPoint(Obs.GetN(), m, val[m][0])
        Exp.SetLineWidth(3)
        Exp.SetLineColor(602) #602
        Exp.SetLineStyle(5)
        Obs.SetLineWidth(3)
        Obs.SetLineColor(602)
        Exp.Draw("SAME, L")
        Obs.Draw("SAME, L")
        
        mass15, val15 = fillValues("./combine/Vh_2015/X"+particle+"h_M%d.txt")
        Exp15, Obs15 = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(mass15):
            if not m in val: continue
            Exp15.SetPoint(Exp15.GetN(), m, val15[m][3]*multF*Theory['B3'].GetY()[i]*(0.625 if particle=='V' and m>3000 else 1.))
            Obs15.SetPoint(Obs15.GetN(), m, val15[m][0]*multF*Theory['B3'].GetY()[i]*(0.625 if particle=='V' and m>3000 else 1.))
        Exp15.SetLineWidth(3)
        Exp15.SetLineColor(856) #602
        Exp15.SetLineStyle(6)
        Obs15.SetLineWidth(3)
        Obs15.SetLineColor(856)
        Exp15.Draw("SAME, L")
        #Obs15.Draw("SAME, L")
        
        leg2.AddEntry(Exp, "1+2 b-tag", "l")
    """
    if True and channel == 'AZh':
        massLL, valLL = fillValues("./combine/AZh/AZhll_M%d.txt")
        ExpLL, ObsLL = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massLL):
            if not m in val: continue
            ExpLL.SetPoint(ExpLL.GetN(), m, valLL[m][3] * multF)
            ObsLL.SetPoint(ObsLL.GetN(), m, valLL[m][0] * multF)
        ExpLL.SetLineWidth(3)
        ExpLL.SetLineColor(833)  #602
        ExpLL.SetLineStyle(5)
        ObsLL.SetLineWidth(3)
        ObsLL.SetLineColor(833)
        ExpLL.Draw("SAME, L")
        #ObsLL.Draw("SAME, L")

        massNN, valNN = fillValues("./combine/AZh/AZhnn_M%d.txt")
        ExpNN, ObsNN = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massNN):
            if not m in val: continue
            ExpNN.SetPoint(ExpNN.GetN(), m, valNN[m][3] * multF)
            ObsNN.SetPoint(ObsNN.GetN(), m, valNN[m][0] * multF)
        ExpNN.SetLineWidth(3)
        ExpNN.SetLineColor(855)  #602
        ExpNN.SetLineStyle(6)
        ObsNN.SetLineWidth(3)
        ObsNN.SetLineColor(855)
        ExpNN.Draw("SAME, L")
        #ObsNN.Draw("SAME, L")

        leg2.AddEntry(ExpLL,
                      "Expected, A #rightarrow Zh #rightarrow llb#bar{b}", "l")
        leg2.AddEntry(ExpNN,
                      "Expected, A #rightarrow Zh #rightarrow #nu#nub#bar{b}",
                      "l")

    if method == 'combo':
        massAH, valAH = fillValues("./combine/dijet/X" + particle +
                                   "Hah_M%d.txt")
        ExpAH = TGraphAsymmErrors()
        for i, m in enumerate(massAH):
            if not m in val: continue
            ExpAH.SetPoint(ExpAH.GetN(), m, valAH[m][3] * multF)
        ExpAH.SetLineWidth(2)
        ExpAH.SetLineColor(602)  #602
        ExpAH.SetLineStyle(4)
        ExpAH.Draw("SAME, L")

        massSL, valSL = fillValues("./combine/alpha/X" + particle +
                                   "Hsl_M%d.txt")
        ExpSL = TGraphAsymmErrors()
        for i, m in enumerate(massSL):
            if not m in val: continue
            ExpSL.SetPoint(ExpSL.GetN(), m, valSL[m][3] * multF)
        ExpSL.SetLineWidth(3)
        ExpSL.SetLineColor(860 - 9)  #602
        ExpSL.SetLineStyle(7)
        ExpSL.Draw("SAME, L")

        leg2.AddEntry(ExpAH, "B2G-17-002", "l")
        leg2.AddEntry(ExpSL, "B2G-17-004", "l")

    leg2.Draw()
    if not options.blind: Obs0s.Draw("SAME, L")
    c1.GetPad(0).Update()

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

    c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".png")
    c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".pdf")
    if 'ah' in channel or 'sl' in channel:
        c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".C")
        c1.Print("plotsLimit/Exclusion/" + channel + suffix + ".root")

    for t in THEORY:
        print "Model", t, ":",
        for m in range(mass[0], mass[-1], 1):
            if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == (
                    Theory[t].Eval(m + 1) > Obs0s.Eval(m + 1)):
                print m,
        print ""

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

    #if not 'ah' in channel and not 'sl' in channel: return

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

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

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

    drawCMS(LUMI, YEAR, "Preliminary")
    drawAnalysis(channel[1:3])
    c3.Print("plotsLimit/pValue/" + channel + suffix + ".png")
    c3.Print("plotsLimit/pValue/" + channel + suffix + ".pdf")
    #    c3.Print("plotsLimit/pValue/"+channel+suffix+".root")
    #    c3.Print("plotsLimit/pValue/"+channel+suffix+".C")

    # --------- Best Fit ----------
    c4 = TCanvas("c4", "Best Fit", 800, 600)
    c4.cd()
    c4.GetPad(0).SetTopMargin(0.06)
    c4.GetPad(0).SetRightMargin(0.05)
    c4.GetPad(0).SetTicks(1, 1)
    c4.GetPad(0).SetGridx()
    c4.GetPad(0).SetGridy()
    Best.Draw("AL3")
    drawCMS(LUMI, YEAR, "Preliminary")
    drawAnalysis(channel[1:3])
    c4.Print("plotsLimit/BestFit/" + channel + suffix + ".png")
    c4.Print("plotsLimit/BestFit/" + channel + suffix + ".pdf")
    #    c4.Print("plotsLimit/BestFit/"+channel+suffix+".root")
    #    c4.Print("plotsLimit/BestFit/"+channel+suffix+".C")

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

    if 'ah' in channel:
        outFile = TFile("bands.root", "RECREATE")
        outFile.cd()
        pVal.Write("graph")
        Best.Write("best")
        outFile.Close()
Exemplo n.º 20
0
def make_plot(name, ttbar_file, qcd_file, signal_files, histo, histo_qcd='',rebin=1,minx=0,maxx=0,miny=0,maxy=0,logy=False):
  c=TCanvas(name,'',600,600)
  c.SetLeftMargin(0.15)#
  c.SetRightMargin(0.05)#
  c.SetBottomMargin(0.1)
  c.SetTopMargin(0.25)
  latex=TLatex(0.65,0.70,'13 TeV, 20 fb^{-1} ')
  latex.SetNDC(1)
  latex.SetTextFont(42)
  legend=TLegend(0.0,0.75,0.99,1.04)
  legend.SetHeader('')
  #legend.SetTextSize(0.03)
  legend.SetBorderSize(0)
  legend.SetTextFont(42)
  legend.SetLineColor(1)
  legend.SetLineStyle(1)
  legend.SetLineWidth(1)
  legend.SetFillColor(0)
  legend.SetFillStyle(0)
  stack=THStack(name+'_stack','')
  ttbar_histo=ttbar_file.Get(histo)
  ttbar_histo.Rebin(rebin)
  if histo_qcd=='':
    qcd_histo=qcd_file.Get(histo)
  else:
    qcd_histo=qcd_file.Get(histo_qcd)
  qcd_histo.Rebin(rebin)
  signal_histos=[]
  colors=[28,9,8]
  for i in range(len(signal_files)):
    signal_histos.append(signal_files[i].Get(histo))
    signal_histos[i].SetLineWidth(3)
    signal_histos[i].SetLineStyle(1)
    signal_histos[i].SetLineColor(colors[i])
    signal_histos[i].Rebin(rebin)
  ttbar_histo.SetFillColor(kRed)
  qcd_histo.SetFillColor(kYellow)
  ttbar_histo.SetLineColor(kRed)
  qcd_histo.SetLineColor(kYellow)
  ttbar_histo.SetMarkerColor(kRed)
  qcd_histo.SetMarkerColor(kYellow)
  legend.AddEntry(ttbar_histo,'t#bar{t}','f')
  legend.AddEntry(qcd_histo,'QCD from background estimate','f')
  legend.AddEntry(signal_histos[0],"Z' 1 TeV 1pb",'l')
  legend.AddEntry(signal_histos[1],"Z' 2 TeV 1pb",'l')
  legend.AddEntry(signal_histos[2] ,"Z' 3 TeV 1pb",'l')
  stack.Add(ttbar_histo)
  stack.Add(qcd_histo)
  errors=ttbar_histo.Clone(histo+'tmp')
  errors.Add(qcd_histo)
  err=TGraphAsymmErrors(errors)
  stack.Draw('hist')
  stack.GetXaxis().SetRangeUser(0,4000)
  err.SetFillStyle(3145)
  err.SetFillColor(kGray)
  errors.SetLineColor(kBlack)
  errors.SetFillStyle(0)
  errors.Draw('samehist')
  err.Draw('2')
  #summc.Draw('samehist')
  #stack.SetMinimum(0.1)
  #stack.SetMaximum(stack.GetMaximum()*1.2)
  stack.GetXaxis().SetTitle("m_{t#bar{t}} [GeV]")
  stack.GetYaxis().SetTitle('Events')
  charsize=0.05
  stack.GetYaxis().SetLabelSize(charsize)
  stack.GetYaxis().SetTitleSize(charsize)
  stack.GetYaxis().SetTitleOffset(1.6)
  stack.GetXaxis().SetLabelSize(charsize)
  stack.GetXaxis().SetTitleSize(charsize)
  stack.GetXaxis().SetTitleOffset(0.95)
  #stack.SetMinimum(0.001)
  if logy:
    c.SetLogy()
  if maxx!=0 or minx!=0:
    stack.GetXaxis().SetRangeUser(minx,maxx)
  if maxy!=0 or miny!=0:
    stack.SetMinimum(miny)
    stack.SetMaximum(maxy)
  signal_histos[0].Draw('samehist')
  signal_histos[1].Draw('samehist')
  signal_histos[2].Draw('samehist')
  legend.Draw()
  latex.Draw()
  c.SaveAs('pdf/'+name+'.pdf')