def transverseMass(h, name="transverseMass", rebin=2, log=True):
#    name = h.getRootHistoPath()
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))

    xlabel = "m_{T}(#tau jet, MET) (GeV/c^{2})" 
    ylabel = "A.u."

  
#    h.stackMCHistograms()
#    h.addMCUncertainty()
    opts = {"xmax": 200}
#    opts = {"ymin": 0.0001,"xmax": 200, "ymaxfactor": 1.3}
#    opts2 = {"ymin": 0.5, "ymax": 1.5}
#    opts = {"xmax": 200}

    if log:
        name += "_log"
        opts["ymin"] = 1e-4
        opts["ymaxfactor"] = 2

    #h.createFrameFraction(name, opts=opts)
    h.createFrame(name, opts=opts)
    legend = histograms.createLegend()
    if log:
        h.getPad().SetLogy(True)
        histograms.moveLegend(legend, dx=-0.5, dy=-0.3)
    h.setLegend(legend)
        
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
#    h.addLuminosityText()
    h.save()
Exemplo n.º 2
0
def transverseMass(h, prefix="", rebin=1, ratio=False):
    xlabel = "m_{T}(#mu, E_{T}^{miss}) (GeV)"
    ylabel = "Events / %.0f GeV"

    _optsLin  = {}
    _optsLog  = {"ymin": 0.1, "ymaxfactor": 2}
    _opts2 = {"ymin": 0, "ymax": 2}

    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylabel = ylabel % h.binWidth()

    h.stackMCHistograms()
    h.addMCUncertainty()

    h.createFrame(prefix+"mt", opts=_optsLin)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()

    h.createFrame(prefix+"mt_log", createRatio=ratio, opts=_optsLog, opts2=_opts2)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.moveLegend(histograms.createLegend()))
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()
def drawPlotData(h, name, xlabel, ylabel="Events / %.0f GeV/c", rebin=1, log=True, ratio=True, opts={}, opts2={}, moveLegend={}, **kwargs):
    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylab = ylabel
    if "%" in ylabel:
        ylab = ylabel % h.binWidth()

    #scaleNormalization(h)
    #h.stackMCHistograms()

    _opts = {"ymin": 0.01, "ymaxfactor": 2}
    if not log:
        _opts["ymin"] = 0
        _opts["ymaxfactor"] = 1.1
    _opts2 = {"ymin": 0.5, "ymax": 1.5}
    _opts.update(opts)
    _opts2.update(opts2)

    if log:
        name = name + "_log"
    h.createFrame(name, createRatio=ratio, opts=_opts, opts2=_opts2)
    h.getPad().SetLogy(log)
    if ratio:
        h.getFrame2().GetYaxis().SetTitle("Ratio")
    #yaxis = h.getFrame2().GetYaxis()
    #yaxis.SetTitleSize(yaxis.GetTitleSize()*0.7)
    #yaxis.SetTitleOffset(yaxis.GetTitleOffset()*1.5)
    h.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

    common(h, xlabel, ylab, **kwargs)
Exemplo n.º 4
0
def compare(raw, type1, quantity, name):
    rawTh1 = raw.histoMgr.getHisto(name).getRootHisto().Clone("Raw")
    type1Th1 = type1.histoMgr.getHisto(name).getRootHisto().Clone("Type1")

    styles.dataStyle.apply(rawTh1)
    styles.mcStyle.apply(type1Th1)

    plot = plots.ComparisonPlot(
        histograms.Histo(rawTh1, "Raw"),
        histograms.Histo(type1Th1, "Type 1")
        )
    q = " "+quantity
    if quantity == "Et":
        q = ""

    plot.setLegend(histograms.moveLegend(histograms.createLegend(), dh=0.15))
    plot.createFrame("metres_%s_%s" % (name, quantity))
    plot.frame.GetXaxis().SetTitle("MET%s/genMET%s" % (q, q))
    plot.frame.GetYaxis().SetTitle("Events / %.2f" % raw.binWidth())
    plot.draw()
    l = ROOT.TLatex()
    l.SetNDC()
    x = 0.5
    y = 0.7
    dy = 0.05
    l.DrawLatex(x, y, name); y -= dy
    l.SetTextSize(l.GetTextSize()*0.7)
    l.SetTextColor(rawTh1.GetLineColor())
    l.DrawLatex(x, y, "Raw mean %.2f, stddev %.2f" % (rawTh1.GetMean(), rawTh1.GetRMS())); y -= dy
    l.SetTextColor(type1Th1.GetLineColor())
    l.DrawLatex(x, y, "Type 1 mean %.2f, stddev %.2f" % (type1Th1.GetMean(), type1Th1.GetRMS())); y -= dy

    plot.save()
Exemplo n.º 5
0
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)
def doPlot(datasetsEmb, analyses, path, name, text):
    histos = []
    legends = {"Plus": "#tau-jet energy scale variated by +3 %",
               "Minus": "#tau-jet energy scale variated by -3 %"}

    for aname, analysis in analyses:
        (rootHisto, tmp) = datasetsEmb.getHistogram("Data", analysis+"/"+path)
        h = histograms.Histo(rootHisto, aname)
        h.setLegendLabel(legends.get(aname, aname))
        h.setDrawStyle("EP")
        h.setLegendStyle("p")
        histos.append(h)

    p = plots.ComparisonManyPlot(histos[0], histos[1:])
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(20))

    styles.dataStyle(p.histoMgr.getHisto("Baseline"))
    styles.mcStyle(p.histoMgr.getHisto("Plus"))
    styles.mcStyle2(p.histoMgr.getHisto("Minus"))
    p.histoMgr.getHisto("Minus").getRootHisto().SetMarkerSize(2)
    p.setLuminosity(datasetsEmb.getLuminosity())
    p.createFrame(name, createRatio=True, opts2={"ymax": 2}, opts={"ymax": 35})
    yaxis = p.getFrame2().GetYaxis()
    yaxis.SetTitle("Ratio")
    #yaxis.SetTitleSize(yaxis.GetTitleSize()*0.8)
    p.setLegend(histograms.moveLegend(histograms.createLegend()))

    p.appendPlotObject(histograms.PlotText(0.5, 0.55, text, size=20))
    
    p.frame.GetXaxis().SetTitle("m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})")
    p.frame.GetYaxis().SetTitle("Events / 20 GeV/c^{2}")
    p.draw()
    p.addStandardTexts()
    p.save()
def plotEff(h, prefix):
    h.createFrame(prefix+"eff_%s"%h.name)
    h.frame.GetXaxis().SetTitle("Cut on isolation")
    h.frame.GetYaxis().SetTitle(h.ylabel)
    h.setLegend(histograms.moveLegend(histograms.createLegend(), dx=0.55))
    h.draw()
    h.save()
    return
def createTransverseMassPlotInternal(dset, name, postfix, normalizeToOne, nominalSelection, compareSelection, nominalLegend="Nominal", compareLegend="Compare", moveLegend={}):
    datasetName = dset.getName()
    treeDraw = dataset.TreeDraw("tree", varexp="TauMETTransverseMass >>tmp(10,0,200)")

    tdNominal = treeDraw.clone(selection=nominalSelection)#selection="Obj2Type == 3 && LeptonVetoStatus == 0 && (TauIDStatus == 1 || TauIDStatus == 2 || TauIDStatus == 3)") # FIXME
    tdCompare = treeDraw.clone(selection=compareSelection)

    drhNominal = dset.getDatasetRootHisto(tdNominal)
    drhCompare = dset.getDatasetRootHisto(tdCompare)

    integrate = lambda h: h.Integral(0, h.GetNbinsX()+1)
    nNominal = integrate(drhNominal.getHistogram())
    nCompare = integrate(drhCompare.getHistogram())

    if normalizeToOne:
        drhNominal.normalizeToOne()
        drhCompare.normalizeToOne()

    drhNominal.setName("Nominal")
    drhCompare.setName("Compare")

    p = plots.ComparisonPlot(drhNominal, drhCompare)

    p.histoMgr.forEachHisto(styles.generator())
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3))
    p.histoMgr.setHistoLegendLabelMany({
            "Nominal": nominalLegend+ " (%d)" % int(nNominal),
            "Compare": compareLegend+ " (%d)" % int(nCompare)
            })

    pfix = postfix
    if normalizeToOne:
        pfix += "_unit"
    p.createFrame("mt_"+datasetName+"_"+name+"_"+pfix, createRatio=normalizeToOne, invertRatio=True, opts2={"ymin": 0, "ymax": 2})
    p.frame.GetXaxis().SetTitle("Transverse mass (GeV/c^{2})")
    if normalizeToOne:
        p.frame.GetYaxis().SetTitle("Arbitrary units")
    else:
        p.frame.GetYaxis().SetTitle("MC events")
    p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.93, y2=0.80, x1=0.45, x2=0.85), **moveLegend))

    nomErr = p.histoMgr.getHisto("Nominal").getRootHisto().Clone("Nominal_err")
    nomErr.SetFillColor(ROOT.kBlue-7)
    nomErr.SetFillStyle(3004)
    nomErr.SetMarkerSize(0)
    p.prependPlotObject(nomErr, "E2")

    comErr = p.histoMgr.getHisto("Compare").getRootHisto().Clone("Compare_err")
    comErr.SetFillColor(ROOT.kRed-7)
    comErr.SetFillStyle(3013)
    comErr.SetMarkerSize(0)
    p.prependPlotObject(comErr, "E2")

    if normalizeToOne:
        p.appendPlotObject(histograms.PlotText(0.6, 0.75, "Normalized to unit area", size=17))

    p.draw()
    p.save()
Exemplo n.º 9
0
def plotClosure(mt_nom, mt_var, name, optMode):
    style = tdrstyle.TDRStyle() 
    plot = plots.ComparisonPlot(mt_var, mt_nom)
    plot.createFrame(optMode.replace("Opt","mT_Closure_"+ name +"_"), createRatio=True, opts2={"ymin": 0.7, "ymax": 1.3})#0.73,1.27
    #plot.createFrame(optMode.replace("Opt","mT_Closure_"+ name +"_"), createRatio=True, opts2={"ymin": 0.73, "ymax": 1.27}, ratio = True, ratioType = "errorScale")
    plot.frame.GetXaxis().SetTitle("m_{T}(tau,MET), GeV")
    plot.frame.GetYaxis().SetTitle("#LT Events / bin #GT")
    moveLegend={"dx": -0.3,"dy": 0.04}
    plot.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
    histograms.addStandardTexts()
    plot.draw()
    plot.save()
Exemplo n.º 10
0
def doPlot(datasets, analyses, path, name, rootFile=None, rootHistoName=None):
    histos = []
    legends = {"Plus": "#tau-jet energy scale variated by +3 %",
               "Minus": "#tau-jet energy scale variated by -3 %"}

    for aname, analysis in analyses:
        p = None
        if isinstance(path, basestring):
            p = plots.DataMCPlot(datasets, analysis+"/"+path)
        else:
            p = plots.DataMCPlot(datasets, path.clone(tree=analysis+"/tree"))

        if normalize:
            tauEmbedding.scaleNormalization(p)
        
        h = p.histoMgr.getHisto("Data")
        h.setName(aname)
        h.setLegendLabel(legends.get(aname, aname))
        histos.append(h)

    p = plots.ComparisonManyPlot(histos[0], histos[1:])
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(20))
    if rootFile:
        baseline = histos[0].getRootHisto().Clone("EWKtau_"+rootHistoName)
        baseline.SetDirectory(rootFile)
        baseline.Write()

        plus = histos[1].getRootHisto().Clone("EWKtau_JESUp_"+rootHistoName)
        plus.SetDirectory(rootFile)
        plus.Write()

        minus = histos[2].getRootHisto().Clone("EWKtau_JESDown_"+rootHistoName)
        minus.SetDirectory(rootFile)
        minus.Write()

    styles.mcStyle(p.histoMgr.getHisto("Plus"))
    styles.mcStyle2(p.histoMgr.getHisto("Minus"))
    p.histoMgr.getHisto("Minus").getRootHisto().SetMarkerSize(2)
    p.setLuminosity(datasets.getDataset("Data").getLuminosity())
    p.createFrame(name, createRatio=True, opts2={"ymax": 2}, opts={"ymax": 40})
    yaxis = p.getFrame2().GetYaxis()
    yaxis.SetTitle("Ratio")
    #yaxis.SetTitleSize(yaxis.GetTitleSize()*0.8)
    p.setLegend(histograms.moveLegend(histograms.createLegend()))
    
    p.frame.GetXaxis().SetTitle("m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})")
    p.frame.GetYaxis().SetTitle("Events / 20 GeV/c^{2}")
    p.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    p.addLuminosityText()
    p.save()
Exemplo n.º 11
0
def plotRoc(h, prefix, postfix="", log=False, opts={}, zoom_opts={}, moveLegend={}):
    args = {"ymin": 0, "ymax": 1.1, "xmin": 0, "xmax": 1.1}
    name = prefix+"isolation_%s"%h.name + postfix
    if log:
        name += "_log"
        args["ymin"] = 1e-3
    args.update(opts)

    h.createFrame(name, **args)
    h.frame.GetXaxis().SetTitle("Non-QCD efficiency")
    h.frame.GetYaxis().SetTitle(h.ylabel)
    if log:
        ROOT.gPad.SetLogy(True)
    h.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
    h.draw()
    h.save()
def drawPlot(h, name, xlabel, ylabel="Events / %.0f GeV/c", rebin=1, log=True, addMCUncertainty=True, ratio=True, opts={}, opts2={}, moveLegend={}, normalize=True, cutLine=None, cutBox=None, function=None):
    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylab = ylabel
    if "%" in ylabel:
        ylab = ylabel % h.binWidth()

    if normalize:
        tauEmbedding.scaleNormalization(h)
    h.stackMCHistograms()
    if addMCUncertainty:
        h.addMCUncertainty()

    _opts = {"ymin": 0.01, "ymaxfactor": 2}
    if not log:
        _opts["ymin"] = 0
        _opts["ymaxfactor"] = 2
    _opts2 = {"ymin": 0.5, "ymax": 1.5}
    _opts.update(opts)
    _opts2.update(opts2)

    if log:
        name = name + "_log"
    h.createFrame(name, createRatio=ratio, opts=_opts, opts2=_opts2)
    h.getPad().SetLogy(log)
    h.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

    # Add cut line and/or box
    if cutLine != None:
        lst = cutLine
        if not isinstance(lst, list):
            lst = [lst]

        for line in lst:
            h.addCutBoxAndLine(line, box=False, line=True)
    if cutBox != None:
        lst = cutBox
        if not isinstance(lst, list):
            lst = [lst]

        for box in lst:
            h.addCutBoxAndLine(**box)

    if function != None:
        function(h)

    common(h, xlabel, ylab)
Exemplo n.º 13
0
def drawPlot(h, name, xlabel, ylabel="Events / %.0f GeV/c", rebin=1, log=True, addMCUncertainty=True, ratio=False, opts={}, opts2={}, moveLegend={}, textFunction=None, cutLine=None, cutBox=None):
    if cutLine != None and cutBox != None:
        raise Exception("Both cutLine and cutBox were given, only either one can exist")

    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylab = ylabel
    if "%" in ylabel:
        ylab = ylabel % h.binWidth()

    scaleMCfromWmunu(h)
    h.stackMCHistograms()
    if addMCUncertainty:
        h.addMCUncertainty()

    _opts = {"ymin": 0.01, "ymaxfactor": 2}
    if not log:
        _opts["ymin"] = 0
        _opts["ymaxfactor"] = 1.1
    _opts2 = {"ymin": 0.5, "ymax": 1.5}
    _opts.update(opts)
    _opts2.update(opts2)

    #if log:
    #    name = name + "_log"
    h.createFrame(name, createRatio=ratio, opts=_opts, opts2=_opts2)
    if log:
        h.getPad().SetLogy(log)
    h.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

    # Add cut line and/or box
    if cutLine != None:
        lst = cutLine
        if not isinstance(lst, list):
            lst = [lst]

        for line in lst:
            h.addCutBoxAndLine(line, box=False, line=True)
    if cutBox != None:
        lst = cutBox
        if not isinstance(lst, list):
            lst = [lst]

        for box in lst:
            h.addCutBoxAndLine(**box)

    common(h, xlabel, ylab, textFunction=textFunction)
Exemplo n.º 14
0
def muonPt(h, prefix="", rebin=1, ratio=False, cutBox=None):
    xlabel = "Muon p_{T} (GeV/c)"
    ylabel = "Events / %.0f GeV/c"
    #ylabel = "Number of events / 5.0 GeV/c"

    _optsLin  = {}
    _optsLog  = {"ymin": 0.1, "ymaxfactor": 2}
    _opts2 = {"ymin": 0, "ymax": 2}

    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylabel = ylabel % h.binWidth()

    h.stackMCHistograms()
    h.addMCUncertainty()

#    tmp = h.histoMgr.getHisto("Data").getRootHisto()
#    dataEvents = tmp.Integral(0, tmp.GetNbinsX()+1)
#    tmp = h.histoMgr.getHisto("StackedMC").getSumRootHisto()
#    mcEvents = tmp.Integral(0, tmp.GetNbinsX()+1)
#    print "Muon pt Data/MC = %f/%f = %f" % (dataEvents, mcEvents, dataEvents/mcEvents)

    h.createFrame(prefix+"muon_pt", opts=_optsLin)
    if cutBox != None:
        h.addCutBoxAndLine(**cutBox)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()

    h.createFrame(prefix+"muon_pt_log", createRatio=ratio, opts=_optsLog, opts2=_opts2)
    if cutBox != None:
        h.addCutBoxAndLine(**cutBox)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.moveLegend(histograms.createLegend()))
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()
Exemplo n.º 15
0
def plotMet(h, name, xlabel, rebin=1, ratio=False, opts={}, opts2={}):
    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))

    ylabel = "Events / %.0f GeV" % h.binWidth()

    h.stackMCHistograms(stackSignal=False)
    h.addMCUncertainty()

    opts_ = {"ymin": 1e-2, "ymaxfactor": 2} #10}
    opts_.update(opts)

    #h.createFrameFraction(name, opts=opts)
    h.createFrame(name+"_"+runs, opts=opts_, createRatio=ratio, opts2=opts2)
    ROOT.gPad.SetLogy(True)
    h.setLegend(histograms.moveLegend(histograms.createLegend())) #, dx=-0.12))
    h.appendPlotObject(histograms.PlotText(0.42, 0.89, "Runs %s"%runs, size=17))
    common(h, xlabel, ylabel)
Exemplo n.º 16
0
def plotTurnOnData(datasets, name, pathAll, pathPassed1, pathPassed2, dataText1, dataText2, rebin=1, ratio=False):
    dataLabel1 = "Data: "+dataText1
    dataLabel2 = "Data: "+dataText2

    dataset = datasets.getDataset("Data")
    all = dataset.getDatasetRootHisto(pathAll).getHistogram()
    passed1 = dataset.getDatasetRootHisto(pathPassed1).getHistogram()
    passed2 = dataset.getDatasetRootHisto(pathPassed2).getHistogram()

    data_eff_gr1 = ROOT.TGraphAsymmErrors(passed1, all, "cp") # 0.683 cl is default
    data_eff_gr2 = ROOT.TGraphAsymmErrors(passed2, all, "cp") # 0.683 cl is default

    p = plots.ComparisonPlot(
        histograms.HistoGraph(data_eff_gr1, "Data1", "p", "P"),
        histograms.HistoGraph(data_eff_gr2, "Data2", "p", "P")
        )
    p.histoMgr.forEachHisto(styles.generator2(styles.StyleMarker(markerSizes=[1.0, 2.0]), [styles.dataStyle, styles.mcStyle2]))
    p.histoMgr.setHistoLegendLabelMany({
            "Data1": dataLabel1,
            "Data2": dataLabel2,
            })
    p.setLuminosity(dataset.getLuminosity())

    opts = {"ymin": 0.0, "ymax": 1.1}
    #opts2 = {"ymin": 0.5, "ymax": 1.5}
    opts2 = {"ymin": 0.8, "ymax": 1.2}

    name = "calomet_turnon_"+runs+"_data_"+name
    p.createFrame(name, createRatio=ratio, invertRatio=True, opts=opts, opts2=opts2)
    if ratio:
        p.getFrame2().GetYaxis().SetTitle("Ratio")

    p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.95, y2=0.85),
                                      #dx=-0.55, dy=-0.05
                                      dx=-0.44, dy=-0.58
                                      ))

    common(p, "Uncorrected PF E_{T}^{miss} (GeV)", "Efficiency")
def doPlotsWTauMu(datasetsEmb, name, btag=True):
    
    if btag:
        selection = And(metCut, bTaggingCut, deltaPhi130Cut)
        treeDraw = dataset.TreeDraw(analysisEmb+"/tree", weight="weightPileup*weightTrigger*weightBTagging")
    else:
        selection = And(metCut, deltaPhi130Cut)
        treeDraw = dataset.TreeDraw(analysisEmb+"/tree", weight="weightPileup*weightTrigger")
    tdMt = treeDraw.clone(varexp="sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,400)")

    (hall, tmp) = datasetsEmb.getHistogram(name, tdMt.clone(selection=selection))
    (hpure, tmp) = datasetsEmb.getHistogram(name, tdMt.clone(selection=And(selection, "abs(temuon_mother_pdgid) == 24")))

    tdEff = tdMt.clone(weight="", varexp=tdMt.varexp.replace("tmp", "tmpeff"))
    heff = datasetsEmb.getEfficiency(name, tdEff.clone(selection=And(selection, "abs(temuon_mother_pdgid) == 24")), tdEff.clone(selection=selection))

    hall.SetName("All")
    hpure.SetName("Pure")

    nall = hall.Integral(0, hall.GetNbinsX())
    npure = hpure.Integral(0, hall.GetNbinsX())

    print {True: "Btagging", False: "NoBTag"}[btag], npure/nall, (1-npure/nall)*100

    p = plots.ComparisonPlot(hall, hpure)
    p.histoMgr.setHistoLegendLabelMany({
            "All": "All muons",
            "Pure": "W#rightarrow#mu"
            })
    p.histoMgr.forEachHisto(styles.generator())
    if btag:
        fname = "transverseMass_4AfterDeltaPhi160_wtaumu_"+name
    else:
        fname = "transverseMass_4AfterDeltaPhi160NoBTag_wtaumu_"+name

    hallErr = hall.Clone("AllError")
    hallErr.SetFillColor(ROOT.kBlue-7)
    hallErr.SetFillStyle(3004)
    hallErr.SetMarkerSize(0)
    p.prependPlotObject(hallErr, "E2")

    hpureErr = hpure.Clone("PureErr")
    hpureErr.SetFillColor(ROOT.kRed-7)
    hpureErr.SetFillStyle(3005)
    hpureErr.SetMarkerSize(0)
    p.prependPlotObject(hpureErr, "E2")

    p.createFrame(fname, createRatio=True, opts2={"ymin": 0.9, "ymax": 1.05})
    styles.getDataStyle().apply(heff)
    p.setRatios([heff])
    xmin = p.frame.GetXaxis().GetXmin()
    xmax = p.frame.GetXaxis().GetXmax()
    val = 1-0.038479
    l = ROOT.TLine(xmin, val, xmax, val)
    l.SetLineWidth(2)
    l.SetLineColor(ROOT.kBlue)
    l.SetLineStyle(4)
    p.prependPlotObjectToRatio(l)
    p.appendPlotObjectToRatio(histograms.PlotText(0.65, 0.61, "1-0.038", size=18, color=ROOT.kBlue))
    p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction")

    p.setLegend(histograms.moveLegend(histograms.createLegend()))
    tmp = hpureErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    tmp.SetLineColor(ROOT.kWhite)
    p.legend.AddEntry(tmp, "Stat. unc.", "F")

    p.frame.GetXaxis().SetTitle("m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})")
    p.frame.GetYaxis().SetTitle("Events / %.0f GeV/c^{2}" % p.binWidth())
    p.appendPlotObject(histograms.PlotText(0.5, 0.9, plots._legendLabels.get(name, name), size=18))
    p.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    p.save()
def doPlots(table):
    nrows = table.getNrows()
    function = ROOT.TF1("fitFunction", "[0]")
    function.SetParameter(0, 0)
    f2 = ROOT.TF1("fitG", "gaus")
    f2.SetLineColor(ROOT.kRed)
    f2.SetLineWidth(2)

    binning = {
        "Data": (8, 60, 100),
        "Diboson": (8, 0, 2),
        "DYJetsToLL": (8, 1, 5),
        "EWKMCsum": (8, 40, 120),
        "SingleTop": (8, 3, 6),
        "TTJets": (10, 25, 35),
        "W3Jets": (10, 6, 11),
        "WJets": (14, 10, 80),
    }
    if onlyWjets:
        binning["WJets"] = (24, 10, 90)
    if not normalize:
        binning["Data"] = (10, 70, 120)
        binning["EWKMCsum"] = (6, 60, 120)
        binning["SingleTop"] = (8, 4, 6)
        binning["TTJets"] = (10, 32, 42)
        binning["W3Jets"] = (12, 6, 12)
        if onlyWjets:
            binning["WJets"] = (10, 20, 60)
    if mcEvents:
        binning["TTJets"] = (12, 320, 440)
        binning["WJets"] = (24, 30, 90)

    for icol in xrange(table.getNcolumns()):
        name = table.getColumnNames()[icol]
        label = plots._legendLabels.get(name, name)
        if name != "Data":
            label += " MC"
        h = ROOT.TH1F(name, name, nrows, 0, nrows)
        h2 = ROOT.TH1F(name + "_dist", name, *(binning.get(name,
                                                           (10, 0, 100))))
        mean = dataset.Count(0, 0)
        for irow in xrange(nrows):
            count = table.getCount(irow, icol)
            h.SetBinContent(irow + 1, count.value())
            h.SetBinError(irow + 1, count.uncertainty())
            h2.Fill(count.value())
            mean.add(count)
        mean = dataset.Count(mean.value() / nrows, mean.uncertainty() / nrows)

        h.Fit("fitFunction")

        value = function.GetParameter(0)
        error = function.GetParError(0)

        # function.SetParameters(1., 40., 1.);
        # function.SetParLimits(0, 0.0, 1.0);
        # fitResult = graph.Fit(function, "NRSE+EX0");
        # print "Fit status", fitResult.Status()
        # #fitResult.Print("V");
        # #fitResult.GetCovarianceMatrix().Print();
        # function.SetLineColor(graph.GetMarkerColor());
        # function.SetLineWidth(2);
        function.Draw("same")
        ROOT.gPad.Update()
        stat = h.FindObject("stats")
        if stat:
            stat.SetX1NDC(0.2)
            stat.SetX2NDC(0.44)
            stat.SetY1NDC(0.2)
            stat.SetY2NDC(0.3)
            stat.SetTextColor(ROOT.kRed)
            stat.SetLineColor(ROOT.kRed)
        # return (function, fitResult)

        styles.dataStyle.apply(h)
        p = plots.PlotBase([h])
        p.histoMgr.setHistoDrawStyle(name, "EP")
        p.createFrame("fluctuation_" + name,
                      opts={
                          "ymin": 0,
                          "ymaxfactor": 1.2,
                          "nbins": nrows
                      })
        p.frame.GetXaxis().SetTitle("Embedding trial number")
        ylabel = "MC"
        if name == "Data":
            ylabel = "Data"
        ylabel += " events"
        p.frame.GetYaxis().SetTitle(ylabel)
        for irow in xrange(nrows):
            p.frame.GetXaxis().SetBinLabel(irow + 1, "%d" % (irow + 1))

        xmin = p.frame.GetXaxis().GetXmin()
        xmax = p.frame.GetXaxis().GetXmax()

        leg = histograms.moveLegend(histograms.createLegend(),
                                    dx=-0.05,
                                    dy=-0.6,
                                    dh=-0.15)
        leg.AddEntry(h, "Trial values", "P")

        def createLine(val, st=1, col=ROOT.kRed):
            l = ROOT.TLine(xmin, val, xmax, val)
            l.SetLineWidth(2)
            l.SetLineStyle(st)
            l.SetLineColor(col)
            return l

        fv = createLine(value)
        leg.AddEntry(fv, "Fitted value", "L")
        p.appendPlotObject(fv)
        # fe = createLine(value+error, ROOT.kDashed)
        # leg.AddEntry(fe, "Fit uncertainty", "L")
        # p.appendPlotObject(fe)
        # p.appendPlotObject(createLine(value-error, ROOT.kDashed))
        v = createLine(mean.value(), col=ROOT.kBlue)
        leg.AddEntry(v, "Mean", "L")
        p.appendPlotObject(v)
        ve = createLine(mean.value() + mean.uncertainty(),
                        st=ROOT.kDashed,
                        col=ROOT.kBlue)
        leg.AddEntry(ve, "Mean uncertainty", "L")
        p.appendPlotObject(ve)
        p.appendPlotObject(
            createLine(mean.value() - mean.uncertainty(),
                       st=ROOT.kDashed,
                       col=ROOT.kBlue))

        p.legend = leg

        p.appendPlotObject(histograms.PlotText(0.5, 0.2, label, size=20))
        p.draw()
        if name == "Data":
            p.setLuminosity(lumi)
        p.addStandardTexts()
        p.save()

        ###############

        f2.SetParameter(1, value)
        h2.Fit("fitG")
        #        f2.Draw("same")
        ROOT.gPad.Update()
        stat = h2.FindObject("stats")
        if stat:
            stat.SetX1NDC(0.62)
            stat.SetX2NDC(0.9)
            stat.SetY1NDC(0.7)
            stat.SetY2NDC(0.85)
            stat.SetTextColor(ROOT.kRed)
            stat.SetLineColor(ROOT.kRed)

        styles.dataStyle.apply(h2)
        p = plots.PlotBase([h2])
        p.histoMgr.setHistoDrawStyle(name + "_dist", "HIST")
        p.createFrame("fluctuation_" + name + "_dist",
                      opts={
                          "ymin": 0,
                          "ymaxfactor": 1.4,
                          "nbins": nrows
                      })
        p.frame.GetXaxis().SetTitle(ylabel)
        p.frame.GetYaxis().SetTitle("Occurrances")

        ymin = p.frame.GetYaxis().GetXmin()
        ymax = p.frame.GetYaxis().GetXmax()

        leg = histograms.moveLegend(histograms.createLegend(),
                                    dx=-0.07,
                                    dy=-0.25,
                                    dh=-0.15)
        leg.AddEntry(h2, "Trials", "F")
        leg.AddEntry(f2, "Gaussian fit", "L")

        def createLine2(val, st=1):
            l = ROOT.TLine(val, ymin, val, ymax)
            l.SetLineWidth(1)
            l.SetLineColor(ROOT.kBlue)
            l.SetLineStyle(st)
            return l

        p.appendPlotObject(h2, "FUNC")
        p.appendPlotObject(stat)
        p.appendPlotObject(histograms.PlotText(0.75, 0.88, label, size=20))
        # fv = createLine2(value)
        # leg.AddEntry(fv, "Fit of values", "L")
        # p.appendPlotObject(fv)
        # fe = createLine2(value+error, ROOT.kDashed)
        # leg.AddEntry(fe, "Fit of values unc.", "L")
        # p.appendPlotObject(fe)
        # p.appendPlotObject(createLine2(value-error, ROOT.kDashed))
        p.legend = leg

        p.draw()

        p.addStandardTexts()
        p.save()
Exemplo n.º 19
0
def drawPlot(h,
             name,
             xlabel,
             ylabel="Events / %.0f GeV/c",
             rebin=1,
             log=True,
             addMCUncertainty=True,
             ratio=False,
             opts={},
             opts2={},
             moveLegend={},
             textFunction=None,
             cutLine=None,
             cutBox=None):
    if cutLine != None and cutBox != None:
        raise Exception(
            "Both cutLine and cutBox were given, only either one can exist")

    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylab = ylabel
    if "%" in ylabel:
        ylab = ylabel % h.binWidth()

    scaleMCfromWmunu(h)
    #    h.stackMCSignalHistograms()

    h.stackMCHistograms(stackSignal=True)  #stackSignal=True)
    #    h.stackMCHistograms()

    if addMCUncertainty:
        h.addMCUncertainty()

    _opts = {"ymin": 0.01, "ymaxfactor": 2}
    if not log:
        _opts["ymin"] = 0
        _opts["ymaxfactor"] = 1.1
##    _opts2 = {"ymin": 0.5, "ymax": 1.5}
    _opts2 = {"ymin": 0.0, "ymax": 2.0}
    _opts.update(opts)
    _opts2.update(opts2)

    #if log:
    #    name = name + "_log"
    h.createFrame(name, createRatio=ratio, opts=_opts, opts2=_opts2)
    if log:
        h.getPad().SetLogy(log)
    h.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

    # Add cut line and/or box
    if cutLine != None:
        lst = cutLine
        if not isinstance(lst, list):
            lst = [lst]

        for line in lst:
            h.addCutBoxAndLine(line, box=False, line=True)
    if cutBox != None:
        lst = cutBox
        if not isinstance(lst, list):
            lst = [lst]

        for box in lst:
            h.addCutBoxAndLine(**box)

    common(h, xlabel, ylab, textFunction=textFunction)
def drawPlot(h, name, xlabel, ylabel="Events / %.0f GeV/c", rebin=1, log=True, ratio=True, opts={}, opts2={}, moveLegend={}, cutLine=None, cutBox=None, function=None):
    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylab = ylabel
    if "%" in ylabel:
        ylab = ylabel % h.binWidth()

    #scaleNormalization(h)
    #h.stackMCHistograms()

    embErr = h.histoMgr.getHisto("Embedded").getRootHisto().Clone("Embedded_err")
    sigErr = h.histoMgr.getHisto("Normal").getRootHisto().Clone("Normal_err")

    embErr.SetFillColor(ROOT.kBlue-7)
    embErr.SetFillStyle(3004)
    embErr.SetMarkerSize(0)
    sigErr.SetFillColor(ROOT.kRed-7)
    sigErr.SetMarkerSize(0)
    sigErr.SetFillStyle(3005)

    h.prependPlotObject(sigErr, "E2")
    h.prependPlotObject(embErr, "E2")

    _opts = {"ymin": 0.01, "ymaxfactor": 2}
    if not log:
        _opts["ymin"] = 0
        _opts["ymaxfactor"] = 1.1
    _opts2 = {"ymin": 0.5, "ymax": 1.5}
    _opts.update(opts)
    _opts2.update(opts2)

    if log:
        name = name + "_log"
    h.createFrame(name, createRatio=ratio, opts=_opts, opts2=_opts2)
    h.getPad().SetLogy(log)
    if ratio:
        h.getFrame2().GetYaxis().SetTitle("Ratio")
    #yaxis = h.getFrame2().GetYaxis()
    #yaxis.SetTitleSize(yaxis.GetTitleSize()*0.7)
    #yaxis.SetTitleOffset(yaxis.GetTitleOffset()*1.5)
    h.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
    tmp = embErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    tmp.SetLineColor(ROOT.kWhite)
    h.legend.AddEntry(tmp, "Stat. unc.", "F")

    # Add cut line and/or box
    if cutLine != None:
        lst = cutLine
        if not isinstance(lst, list):
            lst = [lst]

        for line in lst:
            h.addCutBoxAndLine(line, box=False, line=True)
    if cutBox != None:
        lst = cutBox
        if not isinstance(lst, list):
            lst = [lst]

        for box in lst:
            h.addCutBoxAndLine(**box)

    if function != None:
        function(h)

    common(h, xlabel, ylab)
Exemplo n.º 21
0
def main(argv):

    dirs = []
    if len(sys.argv) < 2:
	usage()

    dirs.append(sys.argv[1])

    QCDInvertedNormalization = sort(QCDInvertedNormalizationFactors.QCDInvertedNormalization)

    analysis = "signalAnalysisInvertedTau"
    optModes = []
    optModes.append("OptQCDTailKillerZeroPlus")
    optModes.append("OptQCDTailKillerLoosePlus") 
    optModes.append("OptQCDTailKillerMediumPlus") 
    optModes.append("OptQCDTailKillerTightPlus") 
    optModes.append("OptQCDTailKillerVeryTightPlus")
                    
    plot = plots.PlotBase()
    color = 1
    for optMode in optModes:
        datasets = dataset.getDatasetsFromMulticrabDirs(dirs,dataEra=dataEra,  searchMode=searchMode, analysisName=analysis, optimizationMode=optMode)
        datasets.updateNAllEventsToPUWeighted()
        datasets.loadLuminosities()

        plots.mergeRenameReorderForDataMC(datasets)

        histonames = datasets.getDataset("Data").getDirectoryContent(HISTONAME)

        bins = []
        for histoname in histonames:
            binname = histoname.replace(HISTONAME,"")
            if not binname == "Inclusive":
                bins.append(binname)


        for i,bin in enumerate(bins):
            mtplot = plots.DataMCPlot(datasets, HISTONAME+"/"+HISTONAME+bin)
            if i == 0:
                mt = mtplot.histoMgr.getHisto("Data").getRootHisto().Clone(HISTONAME+"/"+HISTONAME+bin)
                legendName = optMode.replace("OptQCDTailKiller","R_{BB} ")
                legendName = legendName.replace("Plus","")
                mt.SetName(legendName)
                mt.SetLineColor(color)
                mt.Scale(QCDInvertedNormalization[i])
                color += 1
                if color == 5:
                    color += 1
            else:
                h = mtplot.histoMgr.getHisto("Data").getRootHisto().Clone(HISTONAME+"/"+HISTONAME+bin)
                h.Scale(QCDInvertedNormalization[i])
                mt.Add(h)
 
        plot.histoMgr.appendHisto(histograms.Histo(mt,mt.GetName()))

    style = tdrstyle.TDRStyle()

    plot.createFrame("mt")
    moveLegend={"dx": -0.15,"dy": 0.}
    plot.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

    plot.setLuminosity(datasets.getDataset("Data").getLuminosity())
    plot.addStandardTexts()

    plot.draw()
    plot.save()
def drawPlot(h,
             name,
             xlabel,
             ylabel="Events / %.0f GeV/c",
             rebin=1,
             log=True,
             addMCUncertainty=True,
             ratio=True,
             opts={},
             opts2={},
             moveLegend={},
             normalize=True,
             cutLine=None,
             cutBox=None,
             function=None):
    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylab = ylabel
    if "%" in ylabel:
        ylab = ylabel % h.binWidth()

    if normalize:
        tauEmbedding.scaleNormalization(h)
    h.stackMCHistograms()
    if addMCUncertainty:
        h.addMCUncertainty()

    _opts = {"ymin": 0.01, "ymaxfactor": 2}
    if not log:
        _opts["ymin"] = 0
        _opts["ymaxfactor"] = 2
    _opts2 = {"ymin": 0.5, "ymax": 1.5}
    _opts.update(opts)
    _opts2.update(opts2)

    if log:
        name = name + "_log"
    h.createFrame(name, createRatio=ratio, opts=_opts, opts2=_opts2)
    h.getPad().SetLogy(log)
    h.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

    # Add cut line and/or box
    if cutLine != None:
        lst = cutLine
        if not isinstance(lst, list):
            lst = [lst]

        for line in lst:
            h.addCutBoxAndLine(line, box=False, line=True)
    if cutBox != None:
        lst = cutBox
        if not isinstance(lst, list):
            lst = [lst]

        for box in lst:
            h.addCutBoxAndLine(**box)

    if function != None:
        function(h)

    common(h, xlabel, ylab)
def drawPlot(h, name, xlabel, ylabel="Events / %.0f GeV/c", rebin=1, log=True, ratio=True, opts={}, opts2={}, moveLegend={}, **kwargs):
    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylab = ylabel
    if "%" in ylabel:
        ylab = ylabel % h.binWidth()

    #scaleNormalization(h)
    #h.stackMCHistograms()

    sigErr = h.histoMgr.getHisto("Normal").getRootHisto().Clone("Normal_err")
    sigErr.SetFillColor(ROOT.kRed-7)
    sigErr.SetMarkerSize(0)
    sigErr.SetFillStyle(3005)
    h.prependPlotObject(sigErr, "E2")
    if h.histoMgr.hasHisto("Embedded"):
        embErr = h.histoMgr.getHisto("Embedded").getRootHisto().Clone("Embedded_err")
        embErr.SetFillColor(ROOT.kBlue-7)
        embErr.SetFillStyle(3004)
        embErr.SetMarkerSize(0)
        h.prependPlotObject(embErr, "E2")

    if hasattr(h, "embeddingVariation"):
        h.prependPlotObject(h.embeddingVariation, "[]")
    if hasattr(h, "embeddingDataVariation"):
        h.prependPlotObject(h.embeddingDataVariation, "[]")


    _opts = {"ymin": 0.01, "ymaxfactor": 2}
    if not log:
        _opts["ymin"] = 0
        _opts["ymaxfactor"] = 1.1
    _opts2 = {"ymin": 0.5, "ymax": 1.5}
    _opts.update(opts)
    _opts2.update(opts2)

    if log:
        name = name + "_log"
    h.createFrame(name, createRatio=ratio, opts=_opts, opts2=_opts2)
    h.getPad().SetLogy(log)
    if ratio:
        h.getFrame2().GetYaxis().SetTitle("Ratio")
        # Very, very ugly hack
        if h.histoMgr.hasHisto("EmbeddedData"):
            if h.ratios[1].getName() != "Embedded":
                raise Exception("Assumption failed")
            h.ratios[1].setDrawStyle("PE2")
            rh = h.ratios[1].getRootHisto()
            rh.SetFillColor(ROOT.kBlue-7)
            rh.SetFillStyle(3004)
            # err = h.ratios[1].getRootHisto().Clone("Embedded_ratio_err")
            # err.SetFillColor(ROOT.kBlue-7)
            # err.SetFillStyle(3004)
            # err.SetMarkerSize(0)
            # h.prependPlotObjectToRatio(err, "E2")

    #yaxis = h.getFrame2().GetYaxis()
    #yaxis.SetTitleSize(yaxis.GetTitleSize()*0.7)
    #yaxis.SetTitleOffset(yaxis.GetTitleOffset()*1.5)
    h.setLegend(histograms.moveLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend)))
    tmp = sigErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    #tmp.SetFillStyle(sigErr.GetFillStyle()); tmp.SetFillColor(sigErr.GetFillColor())
    tmp.SetLineColor(ROOT.kWhite)
    h.legend.AddEntry(tmp, "Stat. unc.", "F")

    x = h.legend.GetX1()
    y = h.legend.GetY1()
    x += 0.05; y -= 0.03
    if hasattr(h, "embeddingDataVariation"):
        histograms.addText(x, y, "[  ]", size=17, color=h.embeddingDataVariation.GetMarkerColor()); x += 0.05
        histograms.addText(x, y, "Embedded data min/max", size=17); y-= 0.03
    if hasattr(h, "embeddingVariation"):
        histograms.addText(x, y, "[  ]", size=17, color=h.embeddingVariation.GetMarkerColor()); x += 0.05
        histograms.addText(x, y, "Embedded MC min/max", size=17); y-= 0.03

    #if hasattr(h, "embeddingDataVariation"):
    #    h.legend.AddEntry(h.embeddingDataVariation, "Embedded data min/max", "p")
    #if hasattr(h, "embeddingVariation"):
    #    h.legend.AddEntry(h.embeddingVariation, "Embedded MC min/max", "p")

    common(h, xlabel, ylab, **kwargs)
Exemplo n.º 24
0
def plotTurnOn(datasets, pathAll, pathPassed, commonText, dataText=None, mcText=None, rebin=1, ratio=False):
    dataLabel = "Data"
    mcLabel = "Simulation"
    if dataText != None and mcText == None:
        raise Exception("mcText must not be None when dataText is not")
    if dataText == None and mcText != None:
        raise Exception("dataText must not be None when mcText is not")
#    if dataText != None:
#        dataLabel += ": "+dataText
#        mcLabel += ": "+mcText

    mc_effs = []
    data_eff_gr = None
    binWidth = None
    luminosity = 0
    for dataset in datasets.getAllDatasets():
        all = dataset.getDatasetRootHisto(pathAll).getHistogram()
        passed = dataset.getDatasetRootHisto(pathPassed).getHistogram()

        if rebin > 1:
            all.Rebin(rebin)
            passed.Rebin(rebin)
        binWidth = all.GetBinWidth(1)

        if dataset.isMC() and not "TTTo" in dataset.getName():
        #if dataset.isMC() and not "TTTo" in dataset.getName() and not "QCD" in dataset.getName():
        #if dataset.isMC() and "QCD" in dataset.getName():
            mc_effs.append(HistoEff(all, passed, dataset))

        elif dataset.isData():
            data_eff_gr = ROOT.TGraphAsymmErrors(passed, all, "cp") # 0.683 cl is default
            luminosity += dataset.getLuminosity()

    mc_eff_gr = combineHistoEffs(mc_effs)

    p = plots.ComparisonPlot(
        histograms.HistoGraph(data_eff_gr, "Data", "p", "P"),
        histograms.HistoGraph(mc_eff_gr, "Simulation", "p", "P")
        )
    p.histoMgr.forEachHisto(styles.generator2(styles.StyleMarker(markerSizes=[1.0, 1.5]), plotStyles))
    p.histoMgr.setHistoLegendLabelMany({
            "Data": dataLabel,
            "Simulation": mcLabel,
            })
    p.setLuminosity(luminosity)
    #p.addGraph(data_eff_gr, "Data")
    #p.addGraph(mc_eff_gr, "Simulation")
    #p.finalize()

    opts = {"ymin": 0.0, "ymax": 1.1}
    #opts2 = {"ymin": 0.5, "ymax": 1.5}
    opts2 = {"ymin": 0.7, "ymax": 1.3}

    name = "calomet_turnon_"+runs
    if not mcDataDefinition:
        name += "_McSummer11"
    if caloMetNoHF:
        name += "_caloMetNoHF"
    
    p.createFrame(name, createRatio=ratio, opts=opts, opts2=opts2)
    if ratio:
        p.getFrame2().GetYaxis().SetTitle("Data / MC")
        p.cf.canvas.cd(2)
        p.line1 = plots._createRatioLine(p.cf.frame.getXmin(), p.cf.frame.getXmax(), 0.9)
        p.line2 = plots._createRatioLine(p.cf.frame.getXmin(), p.cf.frame.getXmax(), 1.1)
        p.line1.SetLineColor(ROOT.kBlue)
        p.line2.SetLineColor(ROOT.kBlue)
        p.line1.Draw("L")
        p.line2.Draw("L")
        p.cf.canvas.cd(1)

    p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.95, y2=0.85),
                                      #dx=-0.55, dy=-0.05
                                      #dx=-0.44, dy=-0.58
                                      dx=-0.3, dy=-0.4
                                      ))

    x = 0.25
    y = 0.3
    dy = 0.035
    mcColor = mc_eff_gr.GetMarkerColor()
    size = 17
    p.appendPlotObject(histograms.PlotText(x, y, "Data (runs %s):"%runs, size=size)); y -= dy
    p.appendPlotObject(histograms.PlotText(x, y, dataText, size=size)); y -= dy

    y -= 0.01
    p.appendPlotObject(histograms.PlotText(x, y, "Simulation:", size=size, color=mcColor)); y -= dy
    p.appendPlotObject(histograms.PlotText(x, y, mcText, size=size, color=mcColor)); y -= dy
                       


    def text():
        l = ROOT.TLatex()
        l.SetNDC()
#        l.SetTextFont(l.GetTextFont()-20) # bold -> normal
        l.SetTextSize(l.GetTextSize()*0.65)
        #l.DrawLatex(0.35, 0.4, commonText)
        l.DrawLatex(0.48, 0.32, commonText)
    textFunction = text
    if dataText != None:
        textFunction = None
    #common(p, "PF E_{T}^{miss} (GeV)", "Efficiency / %.0f GeV"%binWidth, afterDraw=textFunction)
    common(p, "Uncorrected PF E_{T}^{miss} (GeV)", "Efficiency", afterDraw=textFunction)
Exemplo n.º 25
0
def doPlotsWTauMu(datasets, name):
    selection = And(muonSelection, muonVeto, electronVeto, jetSelection)
    td = treeDraw.clone(varexp="muons_p4.Pt() >> tmp(40,0,400)")

    ds = datasets.getDataset(name)
    # Take first unweighted histograms for the fraction plot
    drh_all = ds.getDatasetRootHisto(td.clone(selection=selection, weight=""))
    drh_pure = ds.getDatasetRootHisto(td.clone(selection=And(selection, "abs(muons_mother_pdgid) == 24"), weight=""))
    hallUn = drh_all.getHistogram()
    hpureUn = drh_pure.getHistogram()

    # Then the correctly weighted for the main plot
    drh_all = ds.getDatasetRootHisto(td.clone(selection=selection))
    drh_pure = ds.getDatasetRootHisto(td.clone(selection=And(selection, "abs(muons_mother_pdgid) == 24")))
    lumi = datasets.getDataset("Data").getLuminosity()
    drh_all.normalizeToLuminosity(lumi)
    drh_pure.normalizeToLuminosity(lumi)
    hall = drh_all.getHistogram()
    hpure = drh_pure.getHistogram()

    hall.SetName("All")
    hpure.SetName("Pure")

    p = plots.ComparisonPlot(hall, hpure)
    p.histoMgr.setHistoLegendLabelMany({
            "All": "All muons",
            "Pure": "W#rightarrow#tau#rightarrow#mu"
#            "Pure": "W#rightarrow#mu"
            })
    p.histoMgr.forEachHisto(styles.generator())

    hallErr = hall.Clone("AllError")
    hallErr.SetFillColor(ROOT.kBlue-7)
    hallErr.SetFillStyle(3004)
    hallErr.SetMarkerSize(0)
    p.prependPlotObject(hallErr, "E2")

    hpureErr = hpure.Clone("PureErr")
    hpureErr.SetFillColor(ROOT.kRed-7)
    hpureErr.SetFillStyle(3005)
    hpureErr.SetMarkerSize(0)
    p.prependPlotObject(hpureErr, "E2")

    p.createFrame("muonPt_wtaumu_"+name, createRatio=True, opts={"ymin": 1e-1, "ymaxfactor": 2}, opts2={"ymin": 0.9, "ymax": 1.05}
                  )
    p.setRatios([plots._createRatio(hpureUn, hallUn, "", isBinomial=True)])
    xmin = p.frame.GetXaxis().GetXmin()
    xmax = p.frame.GetXaxis().GetXmax()
    val = 1-0.038479
    l = ROOT.TLine(xmin, val, xmax, val)
    l.SetLineWidth(2)
    l.SetLineColor(ROOT.kBlue)
    l.SetLineStyle(4)
    p.prependPlotObjectToRatio(l)
    #p.appendPlotObjectToRatio(histograms.PlotText(0.18, 0.61, "1-0.038", size=18, color=ROOT.kBlue))
    p.appendPlotObjectToRatio(histograms.PlotText(0.18, 0.61, "0.038", size=18, color=ROOT.kBlue))
    p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction")

    p.getPad().SetLogy(True)
    p.setLegend(histograms.moveLegend(histograms.createLegend()))
    tmp = hpureErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    tmp.SetLineColor(ROOT.kWhite)
    p.legend.AddEntry(tmp, "Stat. unc.", "F")

    p.frame.GetXaxis().SetTitle("Muon p_{T} (GeV/c)")
    p.frame.GetYaxis().SetTitle("Events / %.0f GeV/c" % p.binWidth())
    p.appendPlotObject(histograms.PlotText(0.5, 0.9, plots._legendLabels.get(name, name), size=18))

    p.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    p.save()
def drawPlot(h,
             name,
             xlabel,
             ylabel="Events / %.0f GeV/c",
             rebin=1,
             log=True,
             ratio=True,
             opts={},
             opts2={},
             moveLegend={},
             **kwargs):
    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylab = ylabel
    if "%" in ylabel:
        ylab = ylabel % h.binWidth()

    #scaleNormalization(h)
    #h.stackMCHistograms()

    sigErr = h.histoMgr.getHisto("Normal").getRootHisto().Clone("Normal_err")
    sigErr.SetFillColor(ROOT.kRed - 7)
    sigErr.SetMarkerSize(0)
    sigErr.SetFillStyle(3005)
    h.prependPlotObject(sigErr, "E2")
    if h.histoMgr.hasHisto("Embedded"):
        embErr = h.histoMgr.getHisto("Embedded").getRootHisto().Clone(
            "Embedded_err")
        embErr.SetFillColor(ROOT.kBlue - 7)
        embErr.SetFillStyle(3004)
        embErr.SetMarkerSize(0)
        h.prependPlotObject(embErr, "E2")

    if hasattr(h, "embeddingVariation"):
        h.prependPlotObject(h.embeddingVariation, "[]")
    if hasattr(h, "embeddingDataVariation"):
        h.prependPlotObject(h.embeddingDataVariation, "[]")

    _opts = {"ymin": 0.01, "ymaxfactor": 2}
    if not log:
        _opts["ymin"] = 0
        _opts["ymaxfactor"] = 1.1
    _opts2 = {"ymin": 0.5, "ymax": 1.5}
    _opts.update(opts)
    _opts2.update(opts2)

    if log:
        name = name + "_log"
    h.createFrame(name, createRatio=ratio, opts=_opts, opts2=_opts2)
    h.getPad().SetLogy(log)
    if ratio:
        h.getFrame2().GetYaxis().SetTitle("Ratio")
        # Very, very ugly hack
        if h.histoMgr.hasHisto("EmbeddedData"):
            if h.ratios[1].getName() != "Embedded":
                raise Exception("Assumption failed")
            h.ratios[1].setDrawStyle("PE2")
            rh = h.ratios[1].getRootHisto()
            rh.SetFillColor(ROOT.kBlue - 7)
            rh.SetFillStyle(3004)
            # err = h.ratios[1].getRootHisto().Clone("Embedded_ratio_err")
            # err.SetFillColor(ROOT.kBlue-7)
            # err.SetFillStyle(3004)
            # err.SetMarkerSize(0)
            # h.prependPlotObjectToRatio(err, "E2")

    #yaxis = h.getFrame2().GetYaxis()
    #yaxis.SetTitleSize(yaxis.GetTitleSize()*0.7)
    #yaxis.SetTitleOffset(yaxis.GetTitleOffset()*1.5)
    h.setLegend(
        histograms.moveLegend(
            histograms.moveLegend(histograms.createLegend(), **moveLegend)))
    tmp = sigErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    #tmp.SetFillStyle(sigErr.GetFillStyle()); tmp.SetFillColor(sigErr.GetFillColor())
    tmp.SetLineColor(ROOT.kWhite)
    h.legend.AddEntry(tmp, "Stat. unc.", "F")

    x = h.legend.GetX1()
    y = h.legend.GetY1()
    x += 0.05
    y -= 0.03
    if hasattr(h, "embeddingDataVariation"):
        histograms.addText(x,
                           y,
                           "[  ]",
                           size=17,
                           color=h.embeddingDataVariation.GetMarkerColor())
        x += 0.05
        histograms.addText(x, y, "Embedded data min/max", size=17)
        y -= 0.03
    if hasattr(h, "embeddingVariation"):
        histograms.addText(x,
                           y,
                           "[  ]",
                           size=17,
                           color=h.embeddingVariation.GetMarkerColor())
        x += 0.05
        histograms.addText(x, y, "Embedded MC min/max", size=17)
        y -= 0.03

    #if hasattr(h, "embeddingDataVariation"):
    #    h.legend.AddEntry(h.embeddingDataVariation, "Embedded data min/max", "p")
    #if hasattr(h, "embeddingVariation"):
    #    h.legend.AddEntry(h.embeddingVariation, "Embedded MC min/max", "p")

    common(h, xlabel, ylab, **kwargs)
def drawPlot(h,
             name,
             xlabel,
             ylabel="Events / %.0f GeV/c",
             rebin=1,
             log=True,
             ratio=True,
             opts={},
             opts2={},
             moveLegend={},
             cutLine=None,
             cutBox=None,
             function=None):
    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylab = ylabel
    if "%" in ylabel:
        ylab = ylabel % h.binWidth()

    #scaleNormalization(h)
    #h.stackMCHistograms()

    embErr = h.histoMgr.getHisto("Embedded").getRootHisto().Clone(
        "Embedded_err")
    sigErr = h.histoMgr.getHisto("Normal").getRootHisto().Clone("Normal_err")

    embErr.SetFillColor(ROOT.kBlue - 7)
    embErr.SetFillStyle(3004)
    embErr.SetMarkerSize(0)
    sigErr.SetFillColor(ROOT.kRed - 7)
    sigErr.SetMarkerSize(0)
    sigErr.SetFillStyle(3005)

    h.prependPlotObject(sigErr, "E2")
    h.prependPlotObject(embErr, "E2")

    _opts = {"ymin": 0.01, "ymaxfactor": 2}
    if not log:
        _opts["ymin"] = 0
        _opts["ymaxfactor"] = 1.1
    _opts2 = {"ymin": 0.5, "ymax": 1.5}
    _opts.update(opts)
    _opts2.update(opts2)

    if log:
        name = name + "_log"
    h.createFrame(name, createRatio=ratio, opts=_opts, opts2=_opts2)
    h.getPad().SetLogy(log)
    if ratio:
        h.getFrame2().GetYaxis().SetTitle("Ratio")
    #yaxis = h.getFrame2().GetYaxis()
    #yaxis.SetTitleSize(yaxis.GetTitleSize()*0.7)
    #yaxis.SetTitleOffset(yaxis.GetTitleOffset()*1.5)
    h.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
    tmp = embErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    tmp.SetLineColor(ROOT.kWhite)
    h.legend.AddEntry(tmp, "Stat. unc.", "F")

    # Add cut line and/or box
    if cutLine != None:
        lst = cutLine
        if not isinstance(lst, list):
            lst = [lst]

        for line in lst:
            h.addCutBoxAndLine(line, box=False, line=True)
    if cutBox != None:
        lst = cutBox
        if not isinstance(lst, list):
            lst = [lst]

        for box in lst:
            h.addCutBoxAndLine(**box)

    if function != None:
        function(h)

    common(h, xlabel, ylab)
def doPlots(table, onlyWjets, mcEvents, normalize, lumi):
    nrows = table.getNrows()
    function = ROOT.TF1("fitFunction", "[0]") 
    function.SetParameter(0, 0)
    f2 = ROOT.TF1("fitG", "gaus")
    f2.SetLineColor(ROOT.kRed)
    f2.SetLineWidth(2)

    binning = {
        "Data": (8, 60, 100),
        "Diboson": (8, 0, 2),
        "DYJetsToLL": (8, 1, 5),
        "EWKMCsum": (8, 40, 120),
        "SingleTop": (8, 3, 6),
        "TTJets": (10, 25, 35),
        "W3Jets": (10, 6, 11),
        "WJets": (14, 10, 80),
        }
    if onlyWjets:
        binning["WJets"] = (24, 10, 90)
    if not normalize:
        binning["Data"] = (10, 70, 120)
        binning["EWKMCsum"] = (6, 60, 120)
        binning["SingleTop"] = (8, 4, 6)
        binning["TTJets"] = (10, 32, 42)
        binning["W3Jets"] = (12, 6, 12)
        if onlyWjets:
            binning["WJets"] = (10, 20, 60)
    if mcEvents:
        binning["TTJets"] = (12, 320, 440)
        binning["WJets"] = (24, 30, 90)

    for icol in xrange(table.getNcolumns()):
        name = table.getColumnNames()[icol]
        label = plots._legendLabels.get(name, name)
        if name != "Data":
            label += " simulation"
        h = ROOT.TH1F(name, name, nrows, 0, nrows)
        h2 = ROOT.TH1F(name+"_dist", name, *(binning.get(name, (10, 0, 100))))
        mean = dataset.Count(0, 0)
        for irow in xrange(nrows):
            count = table.getCount(irow, icol)
            h.SetBinContent(irow+1, count.value())
            h.SetBinError(irow+1, count.uncertainty())
            h2.Fill(count.value())
            mean.add(count)
        mean = dataset.Count(mean.value()/nrows, mean.uncertainty()/nrows)

        h.Fit("fitFunction")

        value = function.GetParameter(0)
        error = function.GetParError(0)

        # function.SetParameters(1., 40., 1.);
        # function.SetParLimits(0, 0.0, 1.0);
        # fitResult = graph.Fit(function, "NRSE+EX0");
        # print "Fit status", fitResult.Status()
        # #fitResult.Print("V");
        # #fitResult.GetCovarianceMatrix().Print();
        # function.SetLineColor(graph.GetMarkerColor());
        # function.SetLineWidth(2);
        function.Draw("same")
        ROOT.gPad.Update()
        stat = h.FindObject("stats")
        if stat:
            stat.SetX1NDC(0.2)
            stat.SetX2NDC(0.44)
            stat.SetY1NDC(0.2)
            stat.SetY2NDC(0.3)
            stat.SetTextColor(ROOT.kRed)
            stat.SetLineColor(ROOT.kRed)
        # return (function, fitResult)

        styles.dataStyle.apply(h)
        p = plots.PlotBase([h])
        p.histoMgr.setHistoDrawStyle(name, "EP")
        p.createFrame("fluctuation_"+name, opts={"ymin": 0, "ymaxfactor": 1.2, "nbins": nrows})
        p.frame.GetXaxis().SetTitle("Embedding trial number")
        ylabel = "Simulation"
        if name == "Data":
            ylabel = "Data"
        ylabel += " events"
        p.frame.GetYaxis().SetTitle(ylabel)
        step = 1
        start = 0
        if onlyWjets:
            start = 4
            step = 5
        for irow in xrange(start, nrows, step):
            p.frame.GetXaxis().SetBinLabel(irow+1, "%d"%(irow+1))

        xmin = p.frame.GetXaxis().GetXmin()
        xmax = p.frame.GetXaxis().GetXmax()

        leg = histograms.moveLegend(histograms.createLegend(), dx=-0.07, dy=-0.6, dh=-0.15)
        leg.AddEntry(h, "Trial values", "P")

        def createLine(val, st=1, col=ROOT.kRed):
            l = ROOT.TLine(xmin, val, xmax, val)
            l.SetLineWidth(2)
            l.SetLineStyle(st)
            l.SetLineColor(col)
            return l

        fv = createLine(value)
        leg.AddEntry(fv, "Fitted value", "L")
        p.appendPlotObject(fv)
        # fe = createLine(value+error, ROOT.kDashed)
        # leg.AddEntry(fe, "Fit uncertainty", "L")
        # p.appendPlotObject(fe)
        # p.appendPlotObject(createLine(value-error, ROOT.kDashed))
        v = createLine(mean.value(), col=ROOT.kBlue)
        leg.AddEntry(v, "Mean", "L")
        p.appendPlotObject(v)
        ve = createLine(mean.value()+mean.uncertainty(), st=ROOT.kDashed, col=ROOT.kBlue)
        leg.AddEntry(ve, "Mean uncertainty", "L")
        p.appendPlotObject(ve)
        p.appendPlotObject(createLine(mean.value()-mean.uncertainty(), st=ROOT.kDashed, col=ROOT.kBlue))

        p.legend = leg

        p.appendPlotObject(histograms.PlotText(0.65, 0.33, label, size=20))
        p.draw()
        if name != "Data":
            histograms.addCmsPreliminaryText(text="Simulation")
        histograms.addEnergyText()
        histograms.addLuminosityText(None, None, lumi)
        p.save()

        ###############

        f2.SetParameter(1, value)
        h2.Fit("fitG")
#        f2.Draw("same")
        ROOT.gPad.Update()
        stat = h2.FindObject("stats")
        if stat:
            stat.SetX1NDC(0.62)
            stat.SetX2NDC(0.9)
            stat.SetY1NDC(0.7)
            stat.SetY2NDC(0.85)
            stat.SetTextColor(ROOT.kRed)
            stat.SetLineColor(ROOT.kRed)

        styles.dataStyle.apply(h2)
        p = plots.PlotBase([h2])
        p.histoMgr.setHistoDrawStyle(name+"_dist", "HIST")
        p.createFrame("fluctuation_"+name+"_dist", opts={"ymin": 0, "ymaxfactor": 1.4, "nbins": nrows})
        p.frame.GetXaxis().SetTitle(ylabel)
        p.frame.GetYaxis().SetTitle("Occurrances")

        ymin = p.frame.GetYaxis().GetXmin()
        ymax = p.frame.GetYaxis().GetXmax()

        leg = histograms.moveLegend(histograms.createLegend(), dx=-0.07, dy=-0.25, dh=-0.15)
        leg.AddEntry(h2, "Trials", "F")
        leg.AddEntry(f2, "Gaussian fit", "L")

        def createLine2(val, st=1):
            l = ROOT.TLine(val, ymin, val, ymax)
            l.SetLineWidth(1)
            l.SetLineColor(ROOT.kBlue)
            l.SetLineStyle(st)
            return l

        p.appendPlotObject(h2, "FUNC")
        p.appendPlotObject(stat)
        p.appendPlotObject(histograms.PlotText(0.65, 0.88, label, size=20))
        # fv = createLine2(value)
        # leg.AddEntry(fv, "Fit of values", "L")
        # p.appendPlotObject(fv)
        # fe = createLine2(value+error, ROOT.kDashed)
        # leg.AddEntry(fe, "Fit of values unc.", "L")
        # p.appendPlotObject(fe)
        # p.appendPlotObject(createLine2(value-error, ROOT.kDashed))
        p.legend = leg

        p.draw()

        if name != "Data":
            histograms.addCmsPreliminaryText(text="Simulation")
        histograms.addEnergyText()
        histograms.addLuminosityText(None, None, lumi)
        p.save()
def doPlotsWTauMu(datasetsEmb, name, btag=True):

    if btag:
        selection = And(metCut, bTaggingCut, deltaPhi130Cut)
        treeDraw = dataset.TreeDraw(
            analysisEmb + "/tree",
            weight="weightPileup*weightTrigger*weightBTagging")
    else:
        selection = And(metCut, deltaPhi130Cut)
        treeDraw = dataset.TreeDraw(analysisEmb + "/tree",
                                    weight="weightPileup*weightTrigger")
    tdMt = treeDraw.clone(
        varexp=
        "sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,400)"
    )

    (hall, tmp) = datasetsEmb.getHistogram(name,
                                           tdMt.clone(selection=selection))
    (hpure, tmp) = datasetsEmb.getHistogram(
        name,
        tdMt.clone(selection=And(selection, "abs(temuon_mother_pdgid) == 24")))

    tdEff = tdMt.clone(weight="", varexp=tdMt.varexp.replace("tmp", "tmpeff"))
    heff = datasetsEmb.getEfficiency(
        name,
        tdEff.clone(
            selection=And(selection, "abs(temuon_mother_pdgid) == 24")),
        tdEff.clone(selection=selection))

    hall.SetName("All")
    hpure.SetName("Pure")

    nall = hall.Integral(0, hall.GetNbinsX())
    npure = hpure.Integral(0, hall.GetNbinsX())

    print {
        True: "Btagging",
        False: "NoBTag"
    }[btag], npure / nall, (1 - npure / nall) * 100

    p = plots.ComparisonPlot(hall, hpure)
    p.histoMgr.setHistoLegendLabelMany({
        "All": "All muons",
        "Pure": "W#rightarrow#mu"
    })
    p.histoMgr.forEachHisto(styles.generator())
    if btag:
        fname = "transverseMass_4AfterDeltaPhi160_wtaumu_" + name
    else:
        fname = "transverseMass_4AfterDeltaPhi160NoBTag_wtaumu_" + name

    hallErr = hall.Clone("AllError")
    hallErr.SetFillColor(ROOT.kBlue - 7)
    hallErr.SetFillStyle(3004)
    hallErr.SetMarkerSize(0)
    p.prependPlotObject(hallErr, "E2")

    hpureErr = hpure.Clone("PureErr")
    hpureErr.SetFillColor(ROOT.kRed - 7)
    hpureErr.SetFillStyle(3005)
    hpureErr.SetMarkerSize(0)
    p.prependPlotObject(hpureErr, "E2")

    p.createFrame(fname, createRatio=True, opts2={"ymin": 0.9, "ymax": 1.05})
    styles.getDataStyle().apply(heff)
    p.setRatios([heff])
    xmin = p.frame.GetXaxis().GetXmin()
    xmax = p.frame.GetXaxis().GetXmax()
    val = 1 - 0.038479
    l = ROOT.TLine(xmin, val, xmax, val)
    l.SetLineWidth(2)
    l.SetLineColor(ROOT.kBlue)
    l.SetLineStyle(4)
    p.prependPlotObjectToRatio(l)
    p.appendPlotObjectToRatio(
        histograms.PlotText(0.65, 0.61, "1-0.038", size=18, color=ROOT.kBlue))
    p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction")

    p.setLegend(histograms.moveLegend(histograms.createLegend()))
    tmp = hpureErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    tmp.SetLineColor(ROOT.kWhite)
    p.legend.AddEntry(tmp, "Stat. unc.", "F")

    p.frame.GetXaxis().SetTitle("m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})")
    p.frame.GetYaxis().SetTitle("Events / %.0f GeV/c^{2}" % p.binWidth())
    p.appendPlotObject(
        histograms.PlotText(0.5,
                            0.9,
                            plots._legendLabels.get(name, name),
                            size=18))
    p.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    p.save()
def doPlots(mainTable, xvalues, signalDatasets, signalPostfix, consequtive=True):
    allName = "All events"
    cuts = [
        "Trigger and HLT_MET cut",
        "primary vertex",
        "taus == 1",
        "trigger scale factor",
        "electron veto",
        "muon veto",
        "njets",
        "MET",
        "btagging",
        "btagging scale factor",
        "deltaPhiTauMET<160",
        ]

    xerrs = [0]*len(xvalues)
    yvalues = {}
    yerrs = {}
    for cut in cuts:
        yvalues[cut] = []
        yerrs[cut] = []
    for name in signalDatasets:
        column = mainTable.getColumn(name=name)

        # Get the counts (returned objects are of type dataset.Count,
        # and have both value and uncertainty
        allCount = column.getCount(column.getRowNames().index("All events"))
        prevCount = allCount

        for cut in cuts:
            cutCount = column.getCount(column.getRowNames().index(cut))
            eff = cutCount.clone()
            if consequtive:  
                eff.divide(prevCount)
                prevCount = cutCount
            else:
                eff.divide(allCount) # N(cut) / N(all)
        
            yvalues[cut].append(eff.value())
            yerrs[cut].append(eff.uncertainty())

    def createErrors(cutname):
        gr = ROOT.TGraphErrors(len(xvalues), array.array("d", xvalues), array.array("d", yvalues[cutname]),
                               array.array("d", xerrs), array.array("d", yerrs[cutname]))
        gr.SetMarkerStyle(24)
        gr.SetMarkerColor(2)
        gr.SetMarkerSize(2)
        gr.SetLineStyle(1)
        gr.SetLineWidth(4)
        return gr

    def setStyle(gr, lc, ls, ms):
        gr.SetLineColor(lc)
        gr.SetLineStyle(ls)
        gr.SetMarkerColor(lc)
        gr.SetMarkerStyle(ms)

    gtrig = createErrors("Trigger and HLT_MET cut")
    setStyle(gtrig, lc=38, ls=8, ms=20)

    #gtau = createErrors("trigger scale factor")
    gtau = createErrors("taus == 1")
    setStyle(gtau, lc=2, ls=3, ms=21)

    gveto = createErrors("muon veto")
    setStyle(gveto, lc=1, ls=5, ms=22)

    gjets = createErrors("njets")
    setStyle(gjets, lc=4, ls=1, ms=23)

    gmet = createErrors("MET")
    setStyle(gmet, lc=2, ls=2, ms=24)

    gbtag = createErrors("btagging")
    setStyle(gbtag, lc=1, ls=6, ms=24)

    gdphi = createErrors("deltaPhiTauMET<160")
    setStyle(gdphi, lc=9, ls=3, ms=25)
                        
    glist = [gtrig, gtau, gveto, gjets, gmet, gbtag, gdphi]
    
    #opts = {"xmin": 75, "xmax": 165, "ymin": 0.001}
    opts = {"xmin": 75, "xmax": 165, "ymin": 7e-4, "ymax": 2e-1}
    name = "SignalEfficiency"
    if consequtive:
        opts.update({"ymin": 2.5e-2, "ymax": 1.15})
        name += "Conseq"
    name += "_"+signalPostfix

    canvasFrame = histograms.CanvasFrame([histograms.HistoGraph(g, "", "") for g in glist], name, **opts)
    canvasFrame.frame.GetYaxis().SetTitle("Selection efficiency")
    canvasFrame.frame.GetXaxis().SetTitle("m_{H^{+}} (GeV/c^{2})")
    canvasFrame.canvas.SetLogy(True)
    canvasFrame.frame.Draw()

    for gr in glist:
        gr.Draw("PL same")
    
    histograms.addEnergyText()
    histograms.addCmsPreliminaryText(text="Simulation")

    legend = histograms.createLegend(x1=0.5, y1=0.5, x2=0.85, y2=0.75)
    legend = histograms.moveLegend(legend, dx=-0.3, dy=-0.04)
    if not consequtive and signalPostfix == "HH":
        legend = histograms.moveLegend(legend, dy=0.05)

    legend.AddEntry(gtrig,"Trigger", "lp"); 
#    legend.AddEntry(gtau, "#tau-jet identification", "lp"); 
    legend.AddEntry(gtau, "#tau_{h} identification", "lp"); 
    legend.AddEntry(gveto ,"lepton vetoes", "lp"); 
    legend.AddEntry(gjets ,"3 jets", "lp"); 
    legend.AddEntry(gmet,"E_{T}^{miss}", "lp")
    legend.AddEntry(gbtag,"b tagging", "lp")
#    legend.AddEntry(gdphi,"#Delta#phi(#tau, E_{T}^{miss})<160^{o} ", "lp")
    legend.AddEntry(gdphi,"#Delta#phi(#tau_{h}, E_{T}^{miss})<160^{o} ", "lp")
    legend.Draw()

    process = {    
        "HW": "t#bar{t} #rightarrow W^{+}bH^{-}#bar{b}",
        "HH": "t#bar{t} #rightarrow H^{+}bH^{-}#bar{b}"
        }[signalPostfix]

    histograms.addText(x=legend.GetX1()+0.02, y=legend.GetY2()+0.01,
                       text=process, size=17)

    canvasFrame.canvas.SaveAs(".png")
    canvasFrame.canvas.SaveAs(".C")
    canvasFrame.canvas.SaveAs(".eps")
Exemplo n.º 31
0
def doPlotsWTauMu(datasets,
                  name,
                  datasetName,
                  ntupleCache,
                  selectorName,
                  unweighted,
                  fitFunction,
                  rebin=None):
    ds = datasets.getDataset(datasetName)

    # Take first unweighted histograms for the fraction plot
    drh_all = ds.getDatasetRootHisto(
        ntupleCache.histogram("selectedMuonPt_AfterJetSelection" + unweighted,
                              selectorName))
    drh_pure = ds.getDatasetRootHisto(
        ntupleCache.histogram(
            "selectedMuonPt_AfterJetSelection_MuFromW" + unweighted,
            selectorName))

    def Rebin(th1, div=False):
        if rebin is None:
            return th1
        else:
            h = th1.Rebin(
                len(rebin) - 1, th1.GetName(), array.array("d", rebin))
            if div:
                h.Scale(1, "width")
            return h

    def createTEfficiency(drhAll, drhPure):
        hallUn = Rebin(drhAll.getHistogram())
        hpureUn = Rebin(drhPure.getHistogram())
        teff = ROOT.TEfficiency(hpureUn, hallUn)
        teff.SetDirectory(0)
        teff.SetWeight(drhAll.getDataset().getCrossSection())
        return teff

    teffs = drh_all.forEach(createTEfficiency, drh_pure)
    #coll = ROOT.TList()
    #for o in teffs:
    #    coll.AddLast(o)
    #ratio = ROOT.TEfficiency.Combine(coll)
    ratio = teffs[0]
    for e in teffs[1:]:
        ratio.Add(e)
    styles.getDataStyle().apply(ratio)
    ratio.SetName(datasetName)

    ROOT.gStyle.SetStatY(0.99)
    ROOT.gStyle.SetStatX(0.52)
    ROOT.gStyle.SetStatW(0.18)
    ROOT.gStyle.SetStatH(0.23)

    expFit = ROOT.TF1("purityFit", [
        "1/(1+[0]*exp(-[1]*x))",
        "1-[0]*exp(-[1]*x)",
        "1-([0]/(x^[1]))",
    ][fitFunction], aux.th1Xmin(ratio.GetPassedHistogram()),
                      aux.th1Xmax(ratio.GetPassedHistogram()))
    expFit.SetParameter(0, 0.05)
    ratio.Fit(expFit, "N")
    expFit.SetLineColor(ROOT.kRed)
    expFit.SetLineWidth(2)
    #    expFit = None

    # Then the correctly weighted for the main plot
    drh_all = ds.getDatasetRootHisto(
        ntupleCache.histogram("selectedMuonPt_AfterJetSelection",
                              selectorName))
    drh_pure = ds.getDatasetRootHisto(
        ntupleCache.histogram("selectedMuonPt_AfterJetSelection_MuFromW",
                              selectorName))
    if mcOnly:
        lumi = mcLuminosity
    else:
        lumi = datasets.getDataset("Data").getLuminosity()
    drh_all.normalizeToLuminosity(lumi)
    drh_pure.normalizeToLuminosity(lumi)
    hall = Rebin(drh_all.getHistogram(), div=True)
    hpure = Rebin(drh_pure.getHistogram(), div=True)

    hall.SetName("All")
    hpure.SetName("Pure")

    p = plots.ComparisonPlot(hall, hpure)
    p.setLuminosity(lumi)
    p.setEnergy(ds.getEnergy())
    p.histoMgr.setHistoLegendLabelMany({
        "All": "All muons",
        #            "Pure": "W#rightarrow#tau#rightarrow#mu"
        "Pure": "W#rightarrow#mu"
    })
    p.histoMgr.forEachHisto(styles.generator())

    hallErr = hall.Clone("AllError")
    hallErr.SetFillColor(ROOT.kBlue - 7)
    hallErr.SetFillStyle(3004)
    hallErr.SetMarkerSize(0)
    p.prependPlotObject(hallErr, "E2")

    hpureErr = hpure.Clone("PureErr")
    hpureErr.SetFillColor(ROOT.kRed - 7)
    hpureErr.SetFillStyle(3005)
    hpureErr.SetMarkerSize(0)
    p.prependPlotObject(hpureErr, "E2")

    p.createFrame(era + "_" + name +
                  "_selectedMuonPt_AFterJetSelection_MuFromW_%s_fit%d" %
                  (datasetName, fitFunction) + unweighted,
                  createRatio=True,
                  opts={
                      "ymin": 1e-1,
                      "ymaxfactor": 2
                  },
                  opts2={
                      "ymin": 0.9,
                      "ymax": 1.05
                  })
    p.setRatios([ratio])
    xmin = p.frame.GetXaxis().GetXmin()
    xmax = p.frame.GetXaxis().GetXmax()
    val = 1 - 0.038479
    l = ROOT.TLine(xmin, val, xmax, val)
    l.SetLineWidth(2)
    l.SetLineColor(ROOT.kBlue)
    l.SetLineStyle(4)
    p.prependPlotObjectToRatio(l)
    #p.appendPlotObjectToRatio(histograms.PlotText(0.18, 0.61, "1-0.038", size=18, color=ROOT.kBlue))
    p.appendPlotObjectToRatio(
        histograms.PlotText(0.18, 0.61, "0.038", size=18, color=ROOT.kBlue))
    if expFit is not None:
        p.appendPlotObjectToRatio(expFit)
    p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction")

    p.getPad().SetLogy(True)
    p.setLegend(histograms.moveLegend(histograms.createLegend()))
    tmp = hpureErr.Clone("tmp")
    tmp.SetFillColor(ROOT.kBlack)
    tmp.SetFillStyle(3013)
    tmp.SetLineColor(ROOT.kWhite)
    p.legend.AddEntry(tmp, "Stat. unc.", "F")

    p.frame.GetXaxis().SetTitle("Muon p_{T} (GeV/c)")
    p.frame.GetYaxis().SetTitle("Events / #Deltap_{T} %.0f-%.0f GeV/c" %
                                (min(p.binWidths()), max(p.binWidths())))
    p.appendPlotObject(
        histograms.PlotText(0.5,
                            0.9,
                            plots._legendLabels.get(datasetName, datasetName),
                            size=18))

    p.draw()
    p.addStandardTexts()
    p.save()

    # Clear list of functions
    ratio.GetListOfFunctions().Delete()

    return (ratio, expFit)