def doPlot(mass, name, nuisance, thetas):
    f = ROOT.TFile.Open("lands_histograms_hplushadronic_m%d.root" % mass)

    h = f.Get(name)
    hUp = f.Get("%s_%dUp" % (name, nuisance))
    hDown = f.Get("%s_%dDown" % (name, nuisance))

    shapes = []
    ll = {}
    for i, theta in enumerate(thetas):
        morphed = doShape(h, hUp, hDown, theta)
        shapes.append(histograms.Histo(morphed, "Theta%d" % i, drawStyle="HIST", legendStyle="l"))
        ll["Theta%d" % i] = "#theta=%.2f (%.1f)" % (theta, _integral(morphed))

    plot = plots.PlotBase(shapes)
    plot.histoMgr.forEachHisto(styles.generator())
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3))
    plot.histoMgr.setHistoLegendLabelMany(ll)
    plot.setLegend(histograms.createLegend())
    
    plot.createFrame("shape_theta_%s_syst%d_m%d" % (name, nuisance, mass))
    plot.frame.GetXaxis().SetTitle("m_{T} (GeV)")
    plot.frame.GetYaxis().SetTitle("Rate")

    plot.draw()

    x = 0.6
    size = 20
    histograms.addText(x, 0.70, "Sample %s" % name, size=size)
    histograms.addText(x, 0.65, "Nuisance %d" % nuisance, size=size)
    histograms.addText(x, 0.60, "m_{H^{+}}=%d GeV" % mass, size=size)        

    plot.save()

    f.Close()
def rtauGen(h, name, rebin=2, ratio=False, defaultStyles=True):
    if defaultStyles:
        h.setDefaultStyles()
        h.histoMgr.forEachHisto(styles.generator())

    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))


    xlabel = "PF E_{T}^{miss} (GeV)"
    ylabel = "Events / %.2f" % h.binWidth()
    if "LeptonsInMt" in name:
        xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})"
        ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth()
    if "NoLeptonsRealTau" in name:
        xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})"
        ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth()
    if "Mass" in name:
        xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})"
        ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth()

        
    kwargs = {"ymin": 0.1, "ymax": 1000}
    if "LeptonsInMt" in name: 
        kwargs = {"ymin": 0., "xmax": 300}
    if "NoLeptonsRealTau" in name: 
        kwargs = {"ymin": 0., "xmax": 300}
    if "Rtau" in name:
        kwargs = {"ymin": 0.0001, "xmax": 1.1}   
        kwargs = {"ymin": 0.1, "xmax": 1.1}     
        h.getPad().SetLogy(True)

#    kwargs["opts"] = {"ymin": 0, "xmax": 14, "ymaxfactor": 1.1}}
    if ratio:
        kwargs["opts2"] = {"ymin": 0.5, "ymax": 1.5}
        kwargs["createRatio"] = True
#    name = name+"_log"

    h.createFrame(name, **kwargs)

#    histograms.addText(0.65, 0.7, "BR(t #rightarrow bH^{#pm})=0.05", 20)
    h.getPad().SetLogy(True)
    
    leg = histograms.createLegend(0.6, 0.75, 0.8, 0.9)
 
    if "LeptonsInMt" in name:
        h.getPad().SetLogy(False)
        leg = histograms.moveLegend(leg, dx=-0.18)
        histograms.addText(0.5, 0.65, "TailKiller cut: Tight", 20)
  
    h.setLegend(leg)
    plots._legendLabels["MetNoJetInHole"] = "Jets outside dead cells"
    plots._legendLabels["MetJetInHole"] = "Jets within dead cells"
    histograms.addText(300, 300, "p_{T}^{jet} > 50 GeV/c", 20)
    kwargs["opts2"] = {"ymin": 0.5, "ymax": 1.5}
    kwargs["createRatio"] = True
#    if ratio:
#        h.createFrameFraction(name, opts=opts, opts2=opts2)
#    h.setLegend(leg)

    common(h, xlabel, ylabel)
Beispiel #3
0
def doPlot(legList, graphList, saveName, **kwargs):

    # Definitions
    hgList = []
    lList = {}

    # For-loop: All TGraphs
    for i, g in enumerate(graphList, 0):
        if opts.boldText:
            gName = legList[i]
        else:
            gName = "#font[42]{%s}" % legList[i]
        hg = histograms.HistoGraph(graphList[i],
                                   gName,
                                   drawStyle="L",
                                   legendStyle="l")
        hgList.append(hg)

    # Create a plot-base object
    Verbose("Creating the plot-base object", True)
    # plot = plots.PlotBase(hgList, saveFormats=[])
    hgList.insert(0, hgList.pop(opts.refIndex))
    plot = plots.ComparisonManyPlot(hgList[0], hgList[1:], saveFormats=[])
    #plot = plots.ComparisonManyPlot(hgList[-1], hgList[:-1], saveFormats=[])

    # Apply histo style
    Verbose("Applying the histogram styles (generator)", True)
    plot.histoMgr.forEachHisto(styles.generator())

    # plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(1.2))
    # plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3))

    def sty(h):
        r = h.getRootHisto()
        r.SetLineWidth(3)
        r.SetMarkerSize(1.2)
        return

    # Apply style and set label
    Verbose("Applying the histogram styles (forEachHisto)", True)
    plot.histoMgr.forEachHisto(sty)
    if opts.plotType != "var":
        plot.setLegendHeader("Sequential Model (Keras)")

    # Draw the plot
    Verbose("Drawing the plot", True)
    plots.drawPlot(plot, saveName, **kwargs)
    if opts.removeLegend:
        plot.removeLegend()

    # Save plots and return
    Verbose("Saving the plot as %s" % (saveName), True)
    SavePlot(plot, opts.saveDir, saveName, opts.saveFormats)

    Verbose(
        "Plots saved under directory %s" %
        (sh_s + aux.convertToURL(opts.saveDir, opts.url) + sh_n), True)
    return
def doPlot2(limits, legendLabels, name):
    graphs = [
        histograms.HistoGraph(limits[0].expectedGraph(), "Expected", drawStyle="L"),
        histograms.HistoGraph(limits[0].expectedBandGraph(sigma=1), "Expected1", drawStyle="F", legendStyle="fl"),
        histograms.HistoGraph(limits[0].expectedBandGraph(sigma=2), "Expected2", drawStyle="F", legendStyle="fl"),
        ]
    graphs[0].getRootHisto().SetLineStyle(1)
    plot = plots.PlotBase(graphs)
    ll = {
        "Expected": None,
        "Expected1": "%s exp. median #pm 1#sigma" % legendLabels[0],
        "Expected2": "%s exp. median #pm 2#sigma" % legendLabels[0],
        }

    stGen = styles.generator()
    for i in xrange(1, len(limits)):
        gr = histograms.HistoGraph(limits[i].expectedGraph(), "Exp%d"%i, drawStyle="L")
        stGen(gr)
        gr.getRootHisto().SetLineWidth(3)
        gr.getRootHisto().SetLineStyle(1)
        plot.histoMgr.insertHisto(len(plot.histoMgr)-2, gr, legendIndex=len(plot.histoMgr))
        ll["Exp%d"%i] = "%s exp. median" % legendLabels[i]

    plot.histoMgr.setHistoLegendLabelMany(ll)

    legend = histograms.moveLegend(histograms.createLegend(0.48, 0.75, 0.85, 0.92), dx=-0.02)
    if len(limits[0].getFinalstates()) > 1:
        legend = histograms.moveLegend(legend, dy=-0.1)
    plot.setLegend(legend)

    plot.createFrame(name+"_limits", opts={"ymin": 0, "ymax": limits[0].getFinalstateYmaxBR()})
    plot.frame.GetXaxis().SetTitle(limit.mHplus())
    plot.frame.GetYaxis().SetTitle(limit.BRlimit)

    plot.draw()

    plot.setLuminosity(limits[0].getLuminosity())
    plot.addStandardTexts(cmsTextPosition="outframe")

    size = 20
    x = 0.2
    histograms.addText(x, 0.88, limit.process, size=size)
    histograms.addText(x, 0.84, limits[0].getFinalstateText(), size=size)
    histograms.addText(x, 0.79, limit.BRassumption, size=size)

    plot.save()
Beispiel #5
0
def doPlot(mass, name, nuisance, thetas):
    f = ROOT.TFile.Open("lands_histograms_hplushadronic_m%d.root" % mass)

    h = f.Get(name)
    hUp = f.Get("%s_%dUp" % (name, nuisance))
    hDown = f.Get("%s_%dDown" % (name, nuisance))

    shapes = []
    ll = {}
    for i, theta in enumerate(thetas):
        morphed = doShape(h, hUp, hDown, theta)
        shapes.append(
            histograms.Histo(morphed,
                             "Theta%d" % i,
                             drawStyle="HIST",
                             legendStyle="l"))
        ll["Theta%d" % i] = "#theta=%.2f (%.1f)" % (theta, _integral(morphed))

    plot = plots.PlotBase(shapes)
    plot.histoMgr.forEachHisto(styles.generator())
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3))
    plot.histoMgr.setHistoLegendLabelMany(ll)
    plot.setLegend(histograms.createLegend())

    plot.createFrame("shape_theta_%s_syst%d_m%d" % (name, nuisance, mass))
    plot.frame.GetXaxis().SetTitle("m_{T} (GeV)")
    plot.frame.GetYaxis().SetTitle("Rate")

    plot.draw()

    x = 0.6
    size = 20
    histograms.addText(x, 0.70, "Sample %s" % name, size=size)
    histograms.addText(x, 0.65, "Nuisance %d" % nuisance, size=size)
    histograms.addText(x, 0.60, "m_{H^{+}}=%d GeV" % mass, size=size)

    plot.save()

    f.Close()
def doLimitError(limits, unblindedStatus):
    expRelErrors = []
    expLabels    = {}
    obsRelErrors = []
    obsLabels    = {}

    order = [0, 1, -1, 2, -2]
    expErrors = [limits.expectedErrorGraph(sigma=s) for s in order]
    if expErrors[0] != None:
        exps = [limits.expectedGraph(sigma=s) for s in order]
        expRelErrors = [(limit.divideGraph(expErrors[i], exps[i]), "ExpRelErr%d"%i) for i in xrange(len(exps))]
        expLabels = {
            "ExpRelErr0": "Expected median",
            "ExpRelErr1": "Expected +1#sigma",
            "ExpRelErr2": "Expected -1#sigma",
            "ExpRelErr3": "Expected +2#sigma",
            "ExpRelErr4": "Expected -2#sigma",
            }

    if unblindedStatus:
        obsErr = limits.observedErrorGraph()
        if obsErr != None:
            obs = limits.observedGraph()
            if obs != None:
                obsRelErrors = [(limit.divideGraph(obsErr, obs), "ObsRelErr")]
                obsLabels = {"ObsRelErr": "Observed"}

    if len(expRelErrors) == 0 and len(obsRelErrors) == 0:
        return

    # Create the plot
    plot = plots.PlotBase()
    if len(expRelErrors) > 0:
        plot.histoMgr.extendHistos([histograms.HistoGraph(x[0], x[1], drawStyle="PL", legendStyle="lp") for x in expRelErrors])
        plot.histoMgr.forEachHisto(styles.generator())
        def sty(h):
            r = h.getRootHisto()
            r.SetLineStyle(1)
            r.SetLineWidth(3)
            r.SetMarkerSize(1.4)
        plot.histoMgr.forEachHisto(sty)
        plot.histoMgr.setHistoLegendLabelMany(expLabels)
    if unblindedStatus:
        if len(obsRelErrors) > 0:
            obsRelErrors[0][0].SetMarkerSize(1.4)
            obsRelErrors[0][0].SetMarkerStyle(25)
            plot.histoMgr.insertHisto(0, histograms.HistoGraph(obsRelErrors[0][0], obsRelErrors[0][1], drawStyle="PL", legendStyle="lp"))
            plot.histoMgr.setHistoLegendLabelMany(obsLabels)

    plot.setLegend(histograms.moveLegend(histograms.createLegend(0.48, 0.75, 0.85, 0.92), dx=0.1, dy=-0.1))
 
    if len(limits.mass) == 1:
        plot.createFrame("limitsBrRelativeUncertainty", opts={"xmin": limits.mass[0]-5.0, "xmax": limits.mass[0]+5.0,  "ymin": 0, "ymaxfactor": 1.5})
    else:
        plot.createFrame("limitsBrRelativeUncertainty", opts={"ymin": 0, "ymaxfactor": 1.5})
    plot.frame.GetXaxis().SetTitle(limit.mHplus())
    plot.frame.GetYaxis().SetTitle("Uncertainty/limit")

    plot.draw()

    plot.setLuminosity(limits.getLuminosity())
    plot.addStandardTexts()

    size = 20
    x = 0.2
    histograms.addText(x, 0.88, limit.process, size=size)
    histograms.addText(x, 0.84, limits.getFinalstateText(), size=size)
    histograms.addText(x, 0.79, limit.BRassumption, size=size)

    size = 22
    x = 0.55
    histograms.addText(x, 0.88, "Toy MC relative", size=size)
    histograms.addText(x, 0.84, "statistical uncertainty", size=size)

    plot.save()
def doPlot(mass, mu, mul=None):
    f = openFile(mass)
    tree_obs = f.Get("TESTED_R%s"%mu)
    if not tree_obs:
        print "Did not find TESTED_R%s TTree in file %s" % (mu, f.GetName())
        listMu(mass, f)
        f.Close()
        return

    tree_sb = f.Get("SAMPLING_SB_TESTED_R%s" % mu)
    if not tree_sb:
        raise Exception("Did not find SAMPLING_SB_TESTED_R%s from file %s" % (mu, f.GetName()))
    tree_b = f.Get("SAMPLING_B_TESTED_R%s" % mu)
    if not tree_b:
        raise Exception("Did not find SAMPLING_B_TESTED_R%s from file %s" % (mu, f.GetName()))

    xmin = min(tree_sb.GetMinimum("brT"), tree_b.GetMinimum("brT"))
    xmax = max(tree_sb.GetMaximum("brT"), tree_b.GetMaximum("brT"))
    obsval = tree_obs.GetMinimum("brT")

    # Get the distributions
    tree_sb.Draw("brT >>hsb(%d, %f, %f)" % (nbins, xmin, xmax), "", "goff")
    h_sb = tree_sb.GetHistogram()
    tree_b.Draw("brT >>hb(%d, %f, %f)" % (nbins, xmin, xmax), "", "goff")
    h_b = tree_b.GetHistogram()

    # Set obsval to bin boundary
    obsval_bin = obsval
    for bin in xrange(0, h_sb.GetNbinsX()+1):
        edge = h_sb.GetBinLowEdge(bin)
        if obsval > edge:
            obsval_bin = edge

    # Normalize the distributions to unit area
    dataset._normalizeToOne(h_sb)
    dataset._normalizeToOne(h_b)

    plot = plots.PlotBase([
            histograms.Histo(h_b, "B"),
            histograms.Histo(h_sb, "SB")
            ])
    mulegend = mul
    if mul == None:
        mulegend = mu
    plot.histoMgr.setHistoLegendLabelMany({
            "B":  "f(#tilde{q}_{#mu=%s} | #mu=0, #hat{#bf{#theta}}_{0}^{obs})" % mulegend,
            "SB": "f(#tilde{q}_{#mu=%s} | #mu=%s, #hat{#bf{#theta}}_{#mu=%s}^{obs})" % (mulegend, mulegend, mulegend),
            })
    plot.setLegend(histograms.moveLegend(histograms.createLegend(0.6, 0.8, 0.9, 0.9), dy=0.02, dx=-0.05))
    plot.histoMgr.forEachHisto(styles.generator())

    fname = "teststat_m%s_mu%s" % (mass, mu)
    plot.createFrame(fname.replace(".", "_"), opts={"ymin": 1e-6, "ymaxfactor": 2})
    plot.frame.GetXaxis().SetTitle("Test statistic #tilde{q}_{#mu}")
    plot.frame.GetYaxis().SetTitle("Arbitrary units")
    plot.getPad().SetLogy(True)

    area_sb = h_sb.Clone("AreaSB")
    area_sb.SetFillColor(area_sb.GetLineColor())
    area_sb.SetFillStyle(3005)
    area_sb.SetLineWidth(0)

    area_b = h_b.Clone("AreaB")
    area_b.SetFillColor(area_b.GetLineColor())
    area_b.SetFillStyle(3004)
    area_b.SetLineWidth(0)
    for bin in xrange(0, area_sb.GetNbinsX()+1):
        if area_sb.GetBinLowEdge(bin) < obsval_bin:
            area_sb.SetBinContent(bin, 0)
        if area_b.GetBinLowEdge(bin) >= obsval_bin:
            area_b.SetBinContent(bin, 0)

    plot.appendPlotObject(area_b, "HIST ][")
    plot.appendPlotObject(area_sb, "HIST ][")

    plot.addCutBoxAndLine(box=False, cutValue=obsval_bin)


    plot.draw()

    size = 26
    histograms.addText(0.35, 0.4, "CL_{s+b}", size=size)
    histograms.addText(0.18, 0.4, "1-CL_{b}", size=size)

    size = 20
#    x = obsval_bin/(plot.frame.GetXaxis().GetXmax() - plot.frame.GetXaxis().GetXmin())+0.02
    x = (obsval_bin - plot.getPad().GetX1()) / (plot.getPad().GetX2() - plot.getPad().GetX1())
    x += 0.01
    histograms.addText(x, 0.88, "Observed", size=size)
    histograms.addText(x, 0.85, "value", size=size)

    histograms.addText(0.62, 0.78, "m_{H^{+}} = %s %s" % (mass, limit.massUnit()), size=size)

#    size = 20
#    x = 0.2
#    histograms.addText(x, 0.88, brlimit.process, size=size)
#    histograms.addText(x, 0.84, brlimit._finalstateLabels["taujets"], size=size)
#    histograms.addText(x, 0.79, brlimit.BRassumption, size=size)

    plot.save()

    f.Close()
Beispiel #8
0
def doLimitError(limits, unblindedStatus):
    expRelErrors = []
    expLabels = {}
    obsRelErrors = []
    obsLabels = {}

    order = [0, 1, -1, 2, -2]
    expErrors = [limits.expectedErrorGraph(sigma=s) for s in order]
    if expErrors[0] != None:
        exps = [limits.expectedGraph(sigma=s) for s in order]
        expRelErrors = [(limit.divideGraph(expErrors[i],
                                           exps[i]), "ExpRelErr%d" % i)
                        for i in xrange(len(exps))]
        expLabels = {
            "ExpRelErr0": "Expected median",
            "ExpRelErr1": "Expected +1#sigma",
            "ExpRelErr2": "Expected -1#sigma",
            "ExpRelErr3": "Expected +2#sigma",
            "ExpRelErr4": "Expected -2#sigma",
        }

    if unblindedStatus:
        obsErr = limits.observedErrorGraph()
        if obsErr != None:
            obs = limits.observedGraph()
            if obs != None:
                obsRelErrors = [(limit.divideGraph(obsErr, obs), "ObsRelErr")]
                obsLabels = {"ObsRelErr": "Observed"}

    if len(expRelErrors) == 0 and len(obsRelErrors) == 0:
        return

    # Create the plot
    plot = plots.PlotBase()
    if len(expRelErrors) > 0:
        plot.histoMgr.extendHistos([
            histograms.HistoGraph(x[0], x[1], drawStyle="PL", legendStyle="lp")
            for x in expRelErrors
        ])
        plot.histoMgr.forEachHisto(styles.generator())

        def sty(h):
            r = h.getRootHisto()
            r.SetLineStyle(1)
            r.SetLineWidth(3)
            r.SetMarkerSize(1.4)

        plot.histoMgr.forEachHisto(sty)
        plot.histoMgr.setHistoLegendLabelMany(expLabels)
    if unblindedStatus:
        if len(obsRelErrors) > 0:
            obsRelErrors[0][0].SetMarkerSize(1.4)
            obsRelErrors[0][0].SetMarkerStyle(25)
            plot.histoMgr.insertHisto(
                0,
                histograms.HistoGraph(obsRelErrors[0][0],
                                      obsRelErrors[0][1],
                                      drawStyle="PL",
                                      legendStyle="lp"))
            plot.histoMgr.setHistoLegendLabelMany(obsLabels)

    plot.setLegend(
        histograms.moveLegend(histograms.createLegend(0.48, 0.75, 0.85, 0.92),
                              dx=0.1,
                              dy=-0.1))

    if len(limits.mass) == 1:
        plot.createFrame("limitsBrRelativeUncertainty",
                         opts={
                             "xmin": limits.mass[0] - 5.0,
                             "xmax": limits.mass[0] + 5.0,
                             "ymin": 0,
                             "ymaxfactor": 1.5
                         })
    else:
        plot.createFrame("limitsBrRelativeUncertainty",
                         opts={
                             "ymin": 0,
                             "ymaxfactor": 1.5
                         })
    plot.frame.GetXaxis().SetTitle(limit.mHplus())
    plot.frame.GetYaxis().SetTitle("Uncertainty/limit")

    plot.draw()

    plot.setLuminosity(limits.getLuminosity())
    plot.addStandardTexts()

    size = 20
    x = 0.2
    histograms.addText(x, 0.88, limit.process, size=size)
    histograms.addText(x, 0.84, limits.getFinalstateText(), size=size)
    histograms.addText(x, 0.79, limit.BRassumption, size=size)

    size = 22
    x = 0.55
    histograms.addText(x, 0.88, "Toy MC relative", size=size)
    histograms.addText(x, 0.84, "statistical uncertainty", size=size)

    plot.save()
Beispiel #9
0
def doPlotSigmaBands(limits, legendLabels, saveName, _opts={}):

    # Define graphs to be used
    graphs = [
        histograms.HistoGraph(limits[0].expectedGraph(),
                              "Expected",
                              drawStyle="L"),
        histograms.HistoGraph(limits[0].expectedBandGraph(sigma=1),
                              "Expected1",
                              drawStyle="F",
                              legendStyle="fl"),
        histograms.HistoGraph(limits[0].expectedBandGraph(sigma=2),
                              "Expected2",
                              drawStyle="F",
                              legendStyle="fl"),
    ]

    # Set line style
    graphs[0].getRootHisto().SetLineStyle(ROOT.kSolid)

    # Create plot base object
    plot = plots.PlotBase(graphs)
    ll = {
        "Expected": None,
        "Expected1": "%s #pm 1#sigma" % legendLabels[0],
        "Expected2": "%s #pm 2#sigma" % legendLabels[0],
        #"Expected1": "%s exp. median #pm 1#sigma" % legendLabels[0],
        #"Expected2": "%s exp. median #pm 2#sigma" % legendLabels[0],
    }

    stGen = styles.generator()
    nLimits = len(limits)

    # For-loop: All limits
    for i in xrange(1, nLimits):
        name = "Exp%d" % i
        gr = histograms.HistoGraph(limits[i].expectedGraph(),
                                   name,
                                   drawStyle="L")
        stGen(gr)
        gr.getRootHisto().SetLineWidth(3)
        gr.getRootHisto().SetLineStyle(1)
        plot.histoMgr.insertHisto(len(plot.histoMgr) - 2,
                                  gr,
                                  legendIndex=len(plot.histoMgr))
        ll[name] = "%s" % legendLabels[i]  # "%s exp. median" % legendLabels[i]

    # Set histo labels
    plot.histoMgr.setHistoLegendLabelMany(ll)

    # Create & set legend
    nGraphs = len(graphs)

    # If sigma bands are drawn each legend entry is plotted twice. Correct this in the count
    if "Sigma1" in name or "Sigma2" in name:
        nGraphs = nGraphs / 2.0
    legend = getLegend(nGraphs + 4, limit, xPosLeg)
    plot.setLegend(legend)

    # Determine save name, minimum and maximum of y-axis
    ymin, ymax, saveName = getYMinMaxAndName(limits, saveName)
    if _opts.yMin == -1:
        _opts.yMin = ymin
    if _opts.yMax == -1:
        _opts.yMax = ymax

    # Create the frame and set axes titles
    plot.createFrame(saveName, opts={"ymin": _opts.yMin, "ymax": _opts.yMax})

    # Add cut line?
    if _opts.cutLine != 999.9:
        kwargs = {"greaterThan": True}
        plot.addCutBoxAndLine(cutValue=_opts.cutLine,
                              fillColor=ROOT.kRed,
                              box=False,
                              line=True,
                              **kwargs)
    if opts.cutLineY != 999.9:
        kwargs = {
            "greaterThan": True,
            "mainCanvas": True,
            "ratioCanvas": False
        }
        plot.addCutBoxAndLineY(cutValue=_opts.cutLineY,
                               fillColor=ROOT.kRed,
                               box=False,
                               line=True,
                               **kwargs)

    # Set axes titles
    plot.frame.GetXaxis().SetTitle(limit.mHplus())
    plot.frame.GetYaxis().SetTitle(limit.BRlimit)

    # Enable/Disable logscale for axes
    ROOT.gPad.SetLogy(_opts.logY)
    ROOT.gPad.SetLogx(_opts.logX)

    # Draw the plot with standard texts
    plot.draw()
    plot.addStandardTexts(cmsTextPosition="outframe")
    plot.setLuminosity(limits[0].getLuminosity())
    addPhysicsText(histograms, limit, x=xPosText)

    # Save the plots & return
    SavePlot(plot, _opts.saveDir, saveName, [".png"])  #, ".pdf"])
    return
def doPlot2(limits, legendLabels, name):
    graphs = [
        histograms.HistoGraph(limits[0].expectedGraph(),
                              "Expected",
                              drawStyle="L"),
        histograms.HistoGraph(limits[0].expectedBandGraph(sigma=1),
                              "Expected1",
                              drawStyle="F",
                              legendStyle="fl"),
        histograms.HistoGraph(limits[0].expectedBandGraph(sigma=2),
                              "Expected2",
                              drawStyle="F",
                              legendStyle="fl"),
    ]
    graphs[0].getRootHisto().SetLineStyle(1)
    plot = plots.PlotBase(graphs)
    ll = {
        "Expected": None,
        "Expected1": "%s exp. median #pm 1#sigma" % legendLabels[0],
        "Expected2": "%s exp. median #pm 2#sigma" % legendLabels[0],
    }

    stGen = styles.generator()
    for i in xrange(1, len(limits)):
        gr = histograms.HistoGraph(limits[i].expectedGraph(),
                                   "Exp%d" % i,
                                   drawStyle="L")
        stGen(gr)
        gr.getRootHisto().SetLineWidth(3)
        gr.getRootHisto().SetLineStyle(1)
        plot.histoMgr.insertHisto(len(plot.histoMgr) - 2,
                                  gr,
                                  legendIndex=len(plot.histoMgr))
        ll["Exp%d" % i] = "%s exp. median" % legendLabels[i]

    plot.histoMgr.setHistoLegendLabelMany(ll)

    legend = histograms.moveLegend(histograms.createLegend(
        0.48, 0.75, 0.85, 0.92),
                                   dx=-0.02)
    if len(limits[0].getFinalstates()) > 1:
        legend = histograms.moveLegend(legend, dy=-0.1)
    plot.setLegend(legend)

    plot.createFrame(name + "_limits",
                     opts={
                         "ymin": 0,
                         "ymax": limits[0].getFinalstateYmaxBR()
                     })
    plot.frame.GetXaxis().SetTitle(limit.mHplus())
    plot.frame.GetYaxis().SetTitle(limit.BRlimit)

    plot.draw()

    plot.setLuminosity(limits[0].getLuminosity())
    plot.addStandardTexts(cmsTextPosition="outframe")

    size = 20
    x = 0.2
    histograms.addText(x, 0.88, limit.process, size=size)
    histograms.addText(x, 0.84, limits[0].getFinalstateText(), size=size)
    histograms.addText(x, 0.79, limit.BRassumption, size=size)

    plot.save()
Beispiel #11
0
def doPlot(mass, mu, mul=None):
    f = openFile(mass)
    tree_obs = f.Get("TESTED_R%s" % mu)
    if not tree_obs:
        print "Did not find TESTED_R%s TTree in file %s" % (mu, f.GetName())
        listMu(mass, f)
        f.Close()
        return

    tree_sb = f.Get("SAMPLING_SB_TESTED_R%s" % mu)
    if not tree_sb:
        raise Exception("Did not find SAMPLING_SB_TESTED_R%s from file %s" %
                        (mu, f.GetName()))
    tree_b = f.Get("SAMPLING_B_TESTED_R%s" % mu)
    if not tree_b:
        raise Exception("Did not find SAMPLING_B_TESTED_R%s from file %s" %
                        (mu, f.GetName()))

    xmin = min(tree_sb.GetMinimum("brT"), tree_b.GetMinimum("brT"))
    xmax = max(tree_sb.GetMaximum("brT"), tree_b.GetMaximum("brT"))
    obsval = tree_obs.GetMinimum("brT")

    # Get the distributions
    tree_sb.Draw("brT >>hsb(%d, %f, %f)" % (nbins, xmin, xmax), "", "goff")
    h_sb = tree_sb.GetHistogram()
    tree_b.Draw("brT >>hb(%d, %f, %f)" % (nbins, xmin, xmax), "", "goff")
    h_b = tree_b.GetHistogram()

    # Set obsval to bin boundary
    obsval_bin = obsval
    for bin in xrange(0, h_sb.GetNbinsX() + 1):
        edge = h_sb.GetBinLowEdge(bin)
        if obsval > edge:
            obsval_bin = edge

    # Normalize the distributions to unit area
    dataset._normalizeToOne(h_sb)
    dataset._normalizeToOne(h_b)

    plot = plots.PlotBase(
        [histograms.Histo(h_b, "B"),
         histograms.Histo(h_sb, "SB")])
    mulegend = mul
    if mul == None:
        mulegend = mu
    plot.histoMgr.setHistoLegendLabelMany({
        "B":
        "f(#tilde{q}_{#mu=%s} | #mu=0, #hat{#bf{#theta}}_{0}^{obs})" %
        mulegend,
        "SB":
        "f(#tilde{q}_{#mu=%s} | #mu=%s, #hat{#bf{#theta}}_{#mu=%s}^{obs})" %
        (mulegend, mulegend, mulegend),
    })
    plot.setLegend(
        histograms.moveLegend(histograms.createLegend(0.6, 0.8, 0.9, 0.9),
                              dy=0.02,
                              dx=-0.05))
    plot.histoMgr.forEachHisto(styles.generator())

    fname = "teststat_m%s_mu%s" % (mass, mu)
    plot.createFrame(fname.replace(".", "_"),
                     opts={
                         "ymin": 1e-6,
                         "ymaxfactor": 2
                     })
    plot.frame.GetXaxis().SetTitle("Test statistic #tilde{q}_{#mu}")
    plot.frame.GetYaxis().SetTitle("Arbitrary units")
    plot.getPad().SetLogy(True)

    area_sb = h_sb.Clone("AreaSB")
    area_sb.SetFillColor(area_sb.GetLineColor())
    area_sb.SetFillStyle(3005)
    area_sb.SetLineWidth(0)

    area_b = h_b.Clone("AreaB")
    area_b.SetFillColor(area_b.GetLineColor())
    area_b.SetFillStyle(3004)
    area_b.SetLineWidth(0)
    for bin in xrange(0, area_sb.GetNbinsX() + 1):
        if area_sb.GetBinLowEdge(bin) < obsval_bin:
            area_sb.SetBinContent(bin, 0)
        if area_b.GetBinLowEdge(bin) >= obsval_bin:
            area_b.SetBinContent(bin, 0)

    plot.appendPlotObject(area_b, "HIST ][")
    plot.appendPlotObject(area_sb, "HIST ][")

    plot.addCutBoxAndLine(box=False, cutValue=obsval_bin)

    plot.draw()

    size = 26
    histograms.addText(0.35, 0.4, "CL_{s+b}", size=size)
    histograms.addText(0.18, 0.4, "1-CL_{b}", size=size)

    size = 20
    #    x = obsval_bin/(plot.frame.GetXaxis().GetXmax() - plot.frame.GetXaxis().GetXmin())+0.02
    x = (obsval_bin - plot.getPad().GetX1()) / (plot.getPad().GetX2() -
                                                plot.getPad().GetX1())
    x += 0.01
    histograms.addText(x, 0.88, "Observed", size=size)
    histograms.addText(x, 0.85, "value", size=size)

    histograms.addText(0.62,
                       0.78,
                       "m_{H^{+}} = %s %s" % (mass, limit.massUnit()),
                       size=size)

    #    size = 20
    #    x = 0.2
    #    histograms.addText(x, 0.88, brlimit.process, size=size)
    #    histograms.addText(x, 0.84, brlimit._finalstateLabels["taujets"], size=size)
    #    histograms.addText(x, 0.79, brlimit.BRassumption, size=size)

    plot.save()

    f.Close()