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()
Esempio n. 2
0
def plotCommon(h, rebin, xlabel, log, opts={}, opts2={}, coverPadOpts={}):
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    #h.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(5))
    #h.histoMgr.getHistos()[0].getRootHisto().SetLineStyle(3)
    ylabel = "A.u. / %.2f" % h.binWidth()
    xlabel = xlabel
    opts_ = {}
    opts_.update(opts)
    coverPadOpts_ = {}
    coverPadOpts_.update(coverPadOpts)
    if log:
        if not "ymaxfactor" in opts_:
            opts_["ymaxfactor"] = 2
        if not "yminfactor" in opts_ and not "ymin" in opts_:
            opts_["yminfactor"] = 1e-4
    if not "ymin" in coverPadOpts_:
        coverPadOpts_["ymin"] = 0.278

    name = "TauEmbeddingTaus_%s" % (h.plotName)
    if log:
        name += "_log"
    h.createFrame(name, createRatio=True, opts=opts_, opts2=opts2, coverPadOpts=coverPadOpts_)
    h.getFrame2().GetYaxis().SetTitle(h.ratioLabel)
    h.getFrame2().GetYaxis().SetTitleSize(27) # Absolute size
    h.getFrame2().GetYaxis().SetTitleOffset(2)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(createLegend())
    if log:
        ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText(x=0.5, y=0.3)
    h.save()
def tauCandPt(h, step="", rebin=1):
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylabel = "Events /%.0f GeV/c" % h.binWidth()   
    xlabel = "p_{T}^{#tau candidate} (GeV/c)"
    opts = {"ymaxfactor": 2}
    
    h.stackMCHistograms()
    h.addMCUncertainty()

    if h.normalizeToOne:
        ylabel = "A.u."
        opts["yminfactor"] = 1e-5
    else:
        opts["ymin"] = 0.001
           

    name = "tauCandidatePtSimulatedEmbedded_%s_log" % step
    h.createFrameFraction(name, opts=opts)
    #h.createFrame(name, opts=opts)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText()
    h.save()
def deltaPhi(h, step="", rebin=5):
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "R_{#tau}"
    ylabel = "Events / %.2f" % h.binWidth()
    opts = {"ymaxfactor": 2}
    
    h.stackMCHistograms()
    h.addMCUncertainty()

    if h.normalizeToOne:
        ylabel = "A.u."
        opts["yminfactor"] = 1e-5
    else:
        opts["ymin"] = 0.001
           

    name = "deltaPhiSimulateEmbedded_%s_log" % step
    h.createFrameFraction(name, opts=opts)
    #h.createFrame(name, opts=opts)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend(0.5, 0.3, 0.7, 0.6))
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText()
    h.save()
Esempio n. 5
0
def vertexCount(h, prefix="", postfix=""):
    xlabel = "Number of vertices"
    ylabel = "Number of events"

    h.stackMCHistograms()
    h.addMCUncertainty()

    h.createFrame(prefix+"vertices"+postfix)
    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+"vertices"+postfix+"_log", ymin=0.1, factor=2)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    ROOT.gPad.SetLogy(True)
    h.setLegend(histograms.createLegend())
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()
Esempio n. 6
0
def drawSave(h, updatePaletteStyle=False):
    h.draw()
    if updatePaletteStyle:
        histograms.updatePaletteStyle(h.histoMgr.getHistos()[0].getRootHisto())
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.save()
Esempio n. 7
0
def tauCandPhi(h, step="", rebin=5):
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "#phi^{#tau candidate}"
    ylabel = "Events / %.1f" % h.binWidth()
    opts = {"ymaxfactor": 2}
    
    h.stackMCHistograms()
    h.addMCUncertainty()
    scaleMCfromWmunu(h)

    
    if h.normalizeToOne:
        ylabel = "A.u."
        opts["yminfactor"] = 1e-5
    else:
        opts["ymin"] = 0.01
           

    name = "tauCandidatePhi_%s_log" % step
    h.createFrameFraction(name, opts=opts)
    #h.createFrame(name, opts=opts)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText()
    h.save()
def transverseMass(h, rebin=5, ratio=False, particle="#tau"):
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "m_{T}(%s, MET) (GeV/c^{2})" % particle
    ylabel = "Events / %.2f GeV/c^{2}" % h.binWidth()
    opts = {"ymaxfactor": 2}
    
    if h.normalizeToOne:
        ylabel = "A.u."
        opts["yminfactor"] = 1e-5
    else:
        opts["ymin"] = 0.001
    opts["xmax"] = 200

    name = prefix+"_"+h.name
    h.createFrame(name, createRatio=ratio, opts=opts)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText()
    h.save()

    name += "_log"
    h.createFrame(name, createRatio=ratio, opts=opts)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText()
    h.save()
Esempio n. 9
0
def jetPt(h, prefix="", rebin=10):
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "Jet p_{T} (GeV/c)"
    ylabel = "Number of jets / %.0f GeV/c" % h.binWidth()

    ptcut = 30
    ymin = 1e-1
    xmax = 400

    h.stackMCHistograms()
    h.addMCUncertainty()

    h.createFrame(prefix+"jet_pt_log", xmax=xmax, ymin=ymin, yfactor=2)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()

    h.createFrame(prefix+"jet_pt_log_cut%d"%ptcut, xmin=ptcut, xmax=xmax, ymin=ymin, yfactor=2)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()
Esempio n. 10
0
def muonPhi(h, prefix="", plotAll=False, rebin=1):
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))

    xlabel = "Muon  #phi"
    ylabel = "Number of muons / %.1f" % h.binWidth()
    h.stackMCHistograms()

    if plotAll:
        h.createFrame(prefix+"muon_phi", yfactor=1.4)
        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_phi_log", yfactor=2, ymin=0.1)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    ROOT.gPad.SetLogy()
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()
Esempio n. 11
0
def selectionFlow(h, name, rebin=1, ratio=False):

    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "Cut"
    ylabel = "Events"
    
        
    #h.stackMCSignalHistograms()
    h.stackMCHistograms()       
    h.addMCUncertainty()
    scaleMCfromWmunu(h)

    njets = 5
    lastSelection = njets
    
    opts = {"xmax": lastSelection, "ymin": 0.1, "ymaxfactor": 2, "nbins": lastSelection}
    opts2 = {"ymin": 0.5, "ymax": 1.5}

    h.createFrame(name, opts=opts, createRatio=ratio, opts2=opts2)
    xaxis = h.getFrame().GetXaxis()
    xaxis.SetBinLabel(1, "Trigger")
    xaxis.SetBinLabel(2, "#tau ID+R_{#tau}")
    xaxis.SetBinLabel(3, "e veto")
    xaxis.SetBinLabel(4, "#mu veto")
    xaxis.SetBinLabel(5, "N_{jets}")
    h.getPad().SetLogy(True)
    h.setLegend(histograms.createLegend())
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.addLuminosityText()
    addMassBRText(x=0.4, y=0.87)
    h.save()    
Esempio n. 12
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 common(h, xlabel, ylabel, cutLine=None, cutBox=None, function=None):
    # 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)

    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.addLuminosityText()
    h.save()
def distComparison(datasets):
    # Create a comparison plot of two distributions (must have the same binning)
    # Set the names of DatasetRootHisto objects in order to be able easily reference them later
    drh1 = datasets.getDataset("Data").getDatasetRootHisto(analysis+"/MET_BaseLineTauId")
    drh1.setName("Base")
    drh1.normalizeToOne()
    drh2 = datasets.getDataset("Data").getDatasetRootHisto(analysis+"/MET_InvertedTauId")
    drh2.setName("Inv")
    drh2.normalizeToOne()
    plot = plots.ComparisonPlot(drh1, drh2)

    # Set the styles
    st1 = styles.getDataStyle().clone()
    st2 = st1.clone()
    st2.append(styles.StyleLine(lineColor=ROOT.kRed))
    plot.histoMgr.forHisto("Base", st1)
    plot.histoMgr.forHisto("Inv", st2)


    # Set the legend labels
    plot.histoMgr.setHistoLegendLabelMany({"Base": "Baseline Tau ID",
                                           "Inv": "Inverted Tau ID"})
    # Set the legend styles
    plot.histoMgr.setHistoLegendStyleAll("L")

    plot.histoMgr.setHistoLegendStyle("Base", "P") # exception to the general rule

    # Set the drawing styles
    plot.histoMgr.setHistoDrawStyleAll("HIST")
    plot.histoMgr.setHistoDrawStyle("Base", "EP") # exception to the general rule

    # Rebin, if necessary
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))

    # Create frame with a ratio pad
    plot.createFrame("METbaseVSinvertedTauID", opts={"ymin":1e-5, "ymaxfactor": 1.5},
                     createRatio=True, opts2={"ymin": -10, "ymax": 50}, # bounds of the ratio plot
                     )

    # Set Y axis of the upper pad to logarithmic
    plot.getPad1().SetLogy(True)

    # Create legend to the default position
    plot.setLegend(histograms.createLegend())

    # Set the X/Y axis labels
    plot.frame.GetXaxis().SetTitle("MET (GeV)")
    plot.frame.GetYaxis().SetTitle("Arbitrary units")

    # Draw the plot
    plot.draw()

    # Add the various texts to 
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    histograms.addLuminosityText(x=None, y=None, lumi=datasets.getDataset("Data").getLuminosity())

    # Save the plot to files
    plot.save()
def common(h, xlabel, ylabel):
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.addLuminosityText()
    h.save()
Esempio n. 16
0
 def _plotLinear(self, h, selection, met):
     h.createFrame(selection+"_"+met+self.postfix, ymax=self.ymax, xmax=self.xmax)
     h.frame.GetXaxis().SetTitle(self.xlabel(met))
     h.frame.GetYaxis().SetTitle(self.ylabel)
     h.setLegend(histograms.createLegend())
     h.draw()
     histograms.addCmsPreliminaryText()
     histograms.addEnergyText()
     h.histoMgr.addLuminosityText()
     h.save()
Esempio n. 17
0
 def _plotLog(self, h, selection, met):
     h.createFrame(selection+"_"+met+"_log"+self.postfix, ymin=0.1, yfactor=2, xmax=self.xmax)
     h.frame.GetXaxis().SetTitle(self.xlabel(met))
     h.frame.GetYaxis().SetTitle(self.ylabel)
     h.setLegend((histograms.createLegend()))
     ROOT.gPad.SetLogy(True)
     h.draw()
     histograms.addCmsPreliminaryText()
     histograms.addEnergyText()
     h.histoMgr.addLuminosityText()
     h.save()
Esempio n. 18
0
def common(h, xlabel, ylabel, addLuminosityText=True, afterDraw=None):
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.draw()
    if afterDraw != None:
        afterDraw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    if addLuminosityText:
        h.addLuminosityText()
    h.save()
Esempio n. 19
0
def vertexCount(h, prefix="", postfix="", ratio=True):
        xlabel = "Number of good vertices"
        ylabel = "Number of events"

        if h.normalizeToOne:
            ylabel = "Arbitrary units."

        h.stackMCHistograms()

        stack = h.histoMgr.getHisto("StackedMC")
        #hsum = stack.getSumRootHisto()
        #total = hsum.Integral(0, hsum.GetNbinsX()+1)
        #for rh in stack.getAllRootHistos():
        #    dataset._normalizeToFactor(rh, 1/total)
        #dataset._normalizeToOne(h.histoMgr.getHisto("Data").getRootHisto())

        h.addMCUncertainty()

        opts = {}
        opts_log = {"ymin": 1e-10, "ymaxfactor": 10, "xmax": 30}
        opts_log.update(opts)

        opts2 = {"ymin": 0.5, "ymax": 3}
        opts2_log = opts2
        #opts2_log = {"ymin": 5e-2, "ymax": 5e2}
        
        h.createFrame(prefix+"vertices"+postfix, opts=opts, createRatio=ratio, opts2=opts2)
        h.frame.GetXaxis().SetTitle(xlabel)
        h.frame.GetYaxis().SetTitle(ylabel)
        h.setLegend(histograms.createLegend())
        h.draw()
        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        #    histograms.addLuminosityText(x=None, y=None, lumi=191.)
        h.histoMgr.addLuminosityText()
        if h.normalizeToOne:
            histograms.addText(0.35, 0.9, "Normalized to unit area", 17)
        h.save()

        h.createFrame(prefix+"vertices"+postfix+"_log", opts=opts_log, createRatio=ratio, opts2=opts2_log)
        h.frame.GetXaxis().SetTitle(xlabel)
        h.frame.GetYaxis().SetTitle(ylabel)
        h.getPad1().SetLogy(True)
        #h.getPad2().SetLogy(True)
        h.setLegend(histograms.createLegend())
        h.draw()
        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        #    histograms.addLuminosityText(x=None, y=None, lumi=191.)
        h.histoMgr.addLuminosityText()
        if h.normalizeToOne:
            histograms.addText(0.35, 0.9, "Normalized to unit area", 17)
        h.save()
Esempio n. 20
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()
Esempio n. 21
0
def muonD0():
    # Muon track ip w.r.t. beam spot
    h = Plot(datasets, lastSelection+"/muon_trackDB")
    h.stackMCHistograms()
    h.createFrame(lastSelection+"_muon_trackdb", xmin=0, xmax=0.2, ymin=0.1)
    h.frame.GetXaxis().SetTitle("Muon track d_{0}(Bsp) (cm)")
    h.frame.GetYaxis().SetTitle("Number of muons")
    h.setLegend(histograms.createLegend())
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()
Esempio n. 22
0
def dataMCExample(datasets):
    # Create data-MC comparison plot, with the default
    # - legend labels (defined in plots._legendLabels)
    # - plot styles (defined in plots._plotStyles, and in styles)
    # - drawing styles ('HIST' for MC, 'EP' for data)
    # - legend styles ('L' for MC, 'P' for data)
    plot = plots.DataMCPlot(datasets, analysis+"/SelectedTau_pT_AfterTauID")

    # Example of how to rebin all histograms in a histogram manager of a plot
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))

    # Stack all MC histograms, except signal
    # The stacked histograms become filled
    plot.stackMCHistograms()

    # Add MC statistical uncertainty band, calculated as a total of
    # the stacked histograms
    plot.addMCUncertainty()

    # Create the cancas and the frame, with a file name of taupt
    #plot.createFrame("taupt")
    # give explicitly some of the boundaries, leave the rest to be the default
    plot.createFrame("taupt", opts={"ymin": 1e-1, "ymaxfactor": 10})
    # give explicitly the x and y axis boundaries
    #plot.createFrame("taupt", opts={"xmin":40, "xmax":100, "ymin":1e-4, "ymaxfactor": 10})

    # Set Y axis to logarithmic
    plot.getPad().SetLogy(True)

    # Create legend to the default position
    plot.setLegend(histograms.createLegend())
    # to a fixed position
    #plot.setLegend(histograms.createLegend(0.7, 0.6, 0.9, 0.9))
    # to the default position, move the legend after that, and change the width and height
    #plot.setLegend(histograms.moveLegend(histograms.createLegend(), dx=0.1, dy=-0.1, dw=0.1, dh=-0.1)

    # Set X/Y axis labels via TAxis
    plot.frame.GetXaxis().SetTitle("Tau p_{T} (GeV/c)")
    plot.frame.GetYaxis().SetTitle("Number of events")

    # Draw the plot
    plot.draw()

    # Add the various texts to 
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    plot.addLuminosityText()

    # Save the plot to files
    plot.save()
Esempio n. 23
0
def dataMCExample(datasets):
    # Create data-MC comparison plot, with the default
    # - legend labels (defined in plots._legendLabels)
    # - plot styles (defined in plots._plotStyles, and in styles)
    # - drawing styles ('HIST' for MC, 'EP' for data)
    # - legend styles ('L' for MC, 'P' for data)
    plot = plots.DataMCPlot(datasets, analysis + "/SelectedTau_pT_AfterTauID")

    # Example of how to rebin all histograms in a histogram manager of a plot
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))

    # Stack all MC histograms, except signal
    # The stacked histograms become filled
    plot.stackMCHistograms()

    # Add MC statistical uncertainty band, calculated as a total of
    # the stacked histograms
    plot.addMCUncertainty()

    # Create the cancas and the frame, with a file name of taupt
    #plot.createFrame("taupt")
    # give explicitly some of the boundaries, leave the rest to be the default
    plot.createFrame("taupt", opts={"ymin": 1e-1, "ymaxfactor": 10})
    # give explicitly the x and y axis boundaries
    #plot.createFrame("taupt", opts={"xmin":40, "xmax":100, "ymin":1e-4, "ymaxfactor": 10})

    # Set Y axis to logarithmic
    plot.getPad().SetLogy(True)

    # Create legend to the default position
    plot.setLegend(histograms.createLegend())
    # to a fixed position
    #plot.setLegend(histograms.createLegend(0.7, 0.6, 0.9, 0.9))
    # to the default position, move the legend after that, and change the width and height
    #plot.setLegend(histograms.moveLegend(histograms.createLegend(), dx=0.1, dy=-0.1, dw=0.1, dh=-0.1)

    # Set X/Y axis labels via TAxis
    plot.frame.GetXaxis().SetTitle("Tau p_{T} (GeV/c)")
    plot.frame.GetYaxis().SetTitle("Number of events")

    # Draw the plot
    plot.draw()

    # Add the various texts to
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    plot.addLuminosityText()

    # Save the plot to files
    plot.save()
Esempio n. 24
0
def jetMultiplicity(h, prefix=""):
    h.stackMCHistograms()
    h.addMCUncertainty()

    h.createFrame(prefix+"njets_log", xmin=3, xmax=10, ymin=0.1, yfactor=2)
    h.frame.GetXaxis().SetTitle("Jet multiplicity")
    h.frame.GetYaxis().SetTitle("Number of events")
    h.setLegend(histograms.createLegend())
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()
Esempio n. 25
0
def transverseMass(plot,name):
    plot.histoMgr.forHisto("EWK", styles.StyleFill(styles.ttStyle))
    plot.stackMCHistograms()
    plot.setLegend(histograms.createLegend(0.7, 0.68, 0.9, 0.93))
    plot.createFrame(name, opts={"ymin": 1e-1, "ymaxfactor": 10})
    # Set Y axis to logarithmic
    plot.getPad().SetLogy(True)
    plot.frame.GetXaxis().SetTitle("MET (GeV)")
    plot.frame.GetYaxis().SetTitle("Events / %.0f GeV" % plot.binWidth())
    plot.draw()
    # Add the various texts to 
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    plot.addLuminosityText()
    plot.save()
Esempio n. 26
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()
Esempio n. 27
0
def plotDataEwkDiff(mT, name):
    data = dataEwkDiff(mT, name)
    data.SetName("Data-EWK")

    # Draw the subtracted plot
    plot = plots.PlotBase([data])
    plot.createFrame(name, opts={"ymin": 1e-1, "ymaxfactor": 10})
    plot.frame.GetXaxis().SetTitle("MET (GeV)")
    plot.frame.GetYaxis().SetTitle("Data - EWK")
    # Set Y axis to logarithmic
    plot.getPad().SetLogy(True)
    plot.draw()
    # Add the various texts to 
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
#    plot.addLuminosityText()
    plot.save()
Esempio n. 28
0
def wTransMass(h, prefix="", rebin=10):
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))
    xlabel = "m_{T}(#mu, MET) (GeV/c)"
    ylabel = "Number of events / %.0f GeV/c^{2}" % h.binWidth()

    h.stackMCHistograms()
    h.addMCUncertainty()

    h.createFrame(prefix+"wtmass_log", ymin=0.1, xmax=350, yfactor=2)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()
Esempio n. 29
0
def vertexCount(h, prefix="", postfix=""):
        xlabel = "Number of vertices"
        ylabel = "A.u."

        h.stackMCHistograms()

        stack = h.histoMgr.getHisto("StackedMC")
        #hsum = stack.getSumRootHisto()
        #total = hsum.Integral(0, hsum.GetNbinsX()+1)
        #for rh in stack.getAllRootHistos():
        #    dataset._normalizeToFactor(rh, 1/total)
        #dataset._normalizeToOne(h.histoMgr.getHisto("Data").getRootHisto())

        h.addMCUncertainty()

        opts = {"xmax": 16}
        opts_log = {"ymin": 1e-10, "ymaxfactor": 10}
        opts_log.update(opts)
        
        h.createFrame(prefix+"vertices"+postfix, opts=opts)
        h.frame.GetXaxis().SetTitle(xlabel)
        h.frame.GetYaxis().SetTitle(ylabel)
        h.setLegend(histograms.createLegend())
        h.draw()
        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        #    histograms.addLuminosityText(x=None, y=None, lumi=191.)
        h.histoMgr.addLuminosityText()
        h.save()

        h.createFrame(prefix+"vertices"+postfix+"_log", opts=opts_log)
        h.frame.GetXaxis().SetTitle(xlabel)
        h.frame.GetYaxis().SetTitle(ylabel)
        ROOT.gPad.SetLogy(True)
        h.setLegend(histograms.createLegend())
        h.draw()
        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        #    histograms.addLuminosityText(x=None, y=None, lumi=191.)
        h.histoMgr.addLuminosityText()
        h.save()
Esempio n. 30
0
def vertexCount(h, prefix="", postfix=""):
    xlabel = "Number of vertices"
    ylabel = "A.u."

    h.stackMCHistograms()

    stack = h.histoMgr.getHisto("StackedMC")
    #hsum = stack.getSumRootHisto()
    #total = hsum.Integral(0, hsum.GetNbinsX()+1)
    #for rh in stack.getAllRootHistos():
    #    dataset._normalizeToFactor(rh, 1/total)
    #dataset._normalizeToOne(h.histoMgr.getHisto("Data").getRootHisto())

    h.addMCUncertainty()

    opts = {"xmax": 16}
    opts_log = {"ymin": 1e-10, "ymaxfactor": 10}
    opts_log.update(opts)

    h.createFrame(prefix + "vertices" + postfix, opts=opts)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #    histograms.addLuminosityText(x=None, y=None, lumi=191.)
    h.histoMgr.addLuminosityText()
    h.save()

    h.createFrame(prefix + "vertices" + postfix + "_log", opts=opts_log)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    ROOT.gPad.SetLogy(True)
    h.setLegend(histograms.createLegend())
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #    histograms.addLuminosityText(x=None, y=None, lumi=191.)
    h.histoMgr.addLuminosityText()
    h.save()
Esempio n. 31
0
def transverseMass(h, step="", rebin=5, particle="#tau"):
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "m_{T}(%s, MET) (GeV/c^{2})" % particle
    ylabel = "Events / %.2f GeV/c^{2}" % h.binWidth()
    opts = {"ymaxfactor": 2}

    h.stackMCHistograms()
    h.addMCUncertainty()

    if h.normalizeToOne:
        ylabel = "A.u."
        opts["yminfactor"] = 1e-5
    else:
        opts["ymin"] = 0.001
    opts["xmax"] = 200

    name = "transverseMassSimulateEmbedded_%s_log" % step
    h.createFrameFraction(name, opts=opts)
    #h.createFrame(name, opts=opts)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText()
    h.save()

    name = "transverseMassSimulateEmbedded_%s" % step
    h.createFrameFraction(name, opts=opts)
    #h.createFrame(name, opts=opts)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText()
    h.save()
def transverseMass(h, step="", rebin=5, particle="#tau"):
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "m_{T}(%s, MET) (GeV/c^{2})" % particle
    ylabel = "Events / %.2f GeV/c^{2}" % h.binWidth()
    opts = {"ymaxfactor": 2}
    
    h.stackMCHistograms()
    h.addMCUncertainty()

    if h.normalizeToOne:
        ylabel = "A.u."
        opts["yminfactor"] = 1e-5
    else:
        opts["ymin"] = 0.001
    opts["xmax"] = 200

    name = "transverseMassSimulateEmbedded_%s_log" % step
    h.createFrameFraction(name, opts=opts)
    #h.createFrame(name, opts=opts)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText()
    h.save()

    name = "transverseMassSimulateEmbedded_%s" % step
    h.createFrameFraction(name, opts=opts)
    #h.createFrame(name, opts=opts)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText()
    h.save()
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()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    p.addLuminosityText()
    p.save()
def plotCommon(h, rebin, xlabel, log, opts={}, opts2={}, coverPadOpts={}):
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    #h.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(5))
    #h.histoMgr.getHistos()[0].getRootHisto().SetLineStyle(3)
    ylabel = "A.u. / %.2f" % h.binWidth()
    xlabel = xlabel
    opts_ = {}
    opts_.update(opts)
    coverPadOpts_ = {}
    coverPadOpts_.update(coverPadOpts)
    if log:
        if not "ymaxfactor" in opts_:
            opts_["ymaxfactor"] = 2
        if not "yminfactor" in opts_ and not "ymin" in opts_:
            opts_["yminfactor"] = 1e-4
    if not "ymin" in coverPadOpts_:
        coverPadOpts_["ymin"] = 0.278

    name = "TauEmbeddingTaus_%s" % (h.plotName)
    if log:
        name += "_log"
    h.createFrame(name,
                  createRatio=True,
                  opts=opts_,
                  opts2=opts2,
                  coverPadOpts=coverPadOpts_)
    h.getFrame2().GetYaxis().SetTitle(h.ratioLabel)
    h.getFrame2().GetYaxis().SetTitleSize(27)  # Absolute size
    h.getFrame2().GetYaxis().SetTitleOffset(2)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(createLegend())
    if log:
        ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText(x=0.5, y=0.3)
    h.save()
Esempio n. 35
0
    def plotHisto(self,histo,canvasName):
        plot = plots.PlotBase()
        plot.histoMgr.appendHisto(histograms.Histo(histo,histo.GetName()))
        plot.createFrame(canvasName+self.label, opts={"ymin": 0.1, "ymaxfactor": 2.})

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        plot.getPad().SetLogy(True)

        integralValue = int(0.5 + histo.Integral(0,histo.GetNbinsX(),"width"))
        print histo.GetName(),"Integral",histo.Integral(0,histo.GetNbinsX(),"width")
        histograms.addText(0.4,0.7,"Integral = %s ev"% integralValue)

        match = re.search("aseline",histo.GetName())
        if match:
            self.nBaseQCD = integralValue
        match = re.search("nverted",histo.GetName())
        if match:
            self.nInvQCD = integralValue
            
        self.plotIntegral(plot, histo.GetName())
def selectionFlow(h, name, rebin=1, ratio=False):

    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "Cut"
    ylabel = "Events"

    #h.stackMCSignalHistograms()
    h.stackMCHistograms()
    h.addMCUncertainty()
    scaleMCfromWmunu(h)

    njets = 5
    lastSelection = njets

    opts = {
        "xmax": lastSelection,
        "ymin": 0.1,
        "ymaxfactor": 2,
        "nbins": lastSelection
    }
    opts2 = {"ymin": 0.5, "ymax": 1.5}

    h.createFrame(name, opts=opts, createRatio=ratio, opts2=opts2)
    xaxis = h.getFrame().GetXaxis()
    xaxis.SetBinLabel(1, "Trigger")
    xaxis.SetBinLabel(2, "#tau ID+R_{#tau}")
    xaxis.SetBinLabel(3, "e veto")
    xaxis.SetBinLabel(4, "#mu veto")
    xaxis.SetBinLabel(5, "N_{jets}")
    h.getPad().SetLogy(True)
    h.setLegend(histograms.createLegend())
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.addLuminosityText()
    addMassBRText(x=0.4, y=0.87)
    h.save()
Esempio n. 37
0
def selectionFlow(h, name, rebin=1, ratio=False):

    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = "Cut"
    ylabel = "Events"

    h.stackMCHistograms()
    h.addMCUncertainty()
    scaleMCfromWmunu(h)

    opts = {"xmax": 7, "ymin": 0.01, "ymaxfactor": 2}
    opts2 = {"ymin": 0.5, "ymax": 1.5}

    if ratio:
        h.createFrameFraction(name, opts=opts, opts2=opts2)
    else:
        h.createFrame(name, opts=opts)
    h.getPad().SetLogy(True)
    h.setLegend(histograms.createLegend(0.7, 0.6, 0.9, 0.9))
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    #h.addLuminosityText()
    h.save()
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()
Esempio n. 39
0
    def Save(self, name):

        hObserved = self.CreateGraph("Observed")
        hExpected = self.CreateGraph("Expected")
        hExpected1s = self.CreateGraph("Expected1")
        hExpected1s.SetFillColor(ROOT.kYellow)
        hExpected2s = self.CreateGraph("Expected2")
        hExpected2s.SetFillColor(ROOT.kOrange)

        style = tdrstyle.TDRStyle()

        plot = plots.ComparisonManyPlot(
            histograms.HistoGraph(hObserved, "Observed"), [
                histograms.HistoGraph(hExpected, "Expected"),
                histograms.HistoGraph(hExpected1s, "Expected1"),
                histograms.HistoGraph(hExpected2s, "Expected2")
            ])

        obsStyle = styles.getDataStyle().clone()
        plot.histoMgr.forHisto("Observed", styles.getDataStyle().clone())
        plot.histoMgr.setHistoDrawStyle("Observed", "PL")

        expStyle = styles.getDataStyle().clone()
        expStyle.append(styles.StyleLine(lineStyle=2))
        expStyle.append(styles.StyleLine(lineColor=ROOT.kRed))
        expStyle.append(styles.StyleMarker(markerStyle=ROOT.kFullSquare))
        expStyle.append(styles.StyleMarker(markerColor=ROOT.kRed))
        plot.histoMgr.forHisto("Expected", expStyle)
        plot.histoMgr.setHistoDrawStyle("Expected", "PL")
        plot.histoMgr.setHistoDrawStyle("Expected1", "PL3")
        plot.histoMgr.setHistoDrawStyle("Expected2", "PL3")

        plot.createFrame(name,
                         opts={
                             "xmin": 70.1,
                             "xmax": 169.9,
                             "ymin": 0,
                             "ymax": 0.2
                         })
        plot.frame.GetXaxis().SetTitle(self.xtitle)
        plot.frame.GetYaxis().SetTitle(self.ytitle)

        plot.histoMgr.setHistoLegendStyle("Observed", "PL")
        plot.histoMgr.setHistoLegendStyle("Expected", "PL")
        plot.histoMgr.setHistoLegendStyle("Expected1", "F")
        plot.histoMgr.setHistoLegendStyle("Expected2", "F")

        plot.histoMgr.setHistoLegendLabelMany({
            "Expected":
            "Expected median",
            "Expected1":
            "Expected median #pm1#sigma",
            "Expected2":
            "Expected median #pm2#sigma"
        })
        plot.setLegend(histograms.createLegend(0.55, 0.68, 0.9, 0.93))

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        textSize = 16
        textX = 0.19
        textY = 0.8
        textDY = 0.038
        histograms.addText(textX, textY + 2 * textDY,
                           "t#rightarrowbH^{#pm}, H^{#pm}#rightarrow#tau#nu",
                           textSize)
        histograms.addText(textX, textY + textDY, "Fully hadronic final state",
                           textSize)
        histograms.addText(textX, textY,
                           "BR(H^{#pm}#rightarrow#tau^{#pm} #nu) = 1",
                           textSize)

        plot.draw()
        plot.save()
Esempio n. 40
0
def getEfficiency(postfix, lumi):
    f = ROOT.TFile.Open("tagprobe_output_%s.root" % postfix)

    trig = ""
    if "Mu20" in postfix:
        trig = "HLT_Mu20"
    elif "Mu24" in postfix:
        trig = "HLT_Mu24"
    elif "Mu30" in postfix:
        trig = "HLT_Mu30"
    elif "Mu40" in postfix:
        trig = "HLT_Mu40"

    l = ROOT.TLatex()
    l.SetNDC()
    l.SetTextFont(l.GetTextFont() - 20)  # bold -> normal

    #    cntfit = "cnt"
    cntfit = "fit"

    path = "tnpTree/All/%s_eff_plots" % cntfit
    plot = "pt_PLOT"
    graph = "hxy_%s_eff" % cntfit

    pathPt = "tnpTree/All_pt/%s_eff_plots" % cntfit
    grahpPt = "hxy_%s_eff" % cntfit

    canv = f.Get(path + "/" + plot)
    canv.SetName("TagProbe_%s_%s_%s" % (postfix, plot, graph))
    #    canv.SaveAs(".eps")
    canv.SaveAs(".png")

    eff = canv.FindObject(graph)
    #print eff
    eff_value = eff.GetY()[0]
    eff_plus = eff.GetErrorYhigh(0)
    eff_minus = eff.GetErrorYlow(0)

    canv = f.Get(pathPt + "/" + plot)
    gr = canv.FindObject(graph).Clone()

    name = "TagProbe_Pt100_%s_%s_%s" % (postfix, plot, graph)
    c = ROOT.TCanvas(name, name)
    frame = c.DrawFrame(40, 0, 100, 1.1)
    gr.Draw("EP")
    frame.GetXaxis().SetTitle("Probe muon p_{T} (GeV/c)")
    frame.GetYaxis().SetTitle("Trigger and ID efficiency")
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    histograms.addLuminosityText(None, None, lumi)
    l.DrawLatex(0.2, 0.4, trig)
    c.SaveAs(".png")

    gr = canv.FindObject(graph).Clone()
    name = "TagProbe_Pt400_%s_%s_%s" % (postfix, plot, graph)
    c = ROOT.TCanvas(name, name)
    frame = c.DrawFrame(40, 0, 400, 1.1)
    gr.Draw("EP")
    frame.GetXaxis().SetTitle("Probe muon p_{T} (GeV/c)")
    frame.GetYaxis().SetTitle("Trigger and ID efficiency")
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    histograms.addLuminosityText(None, None, lumi)
    l.DrawLatex(0.2, 0.4, trig)
    c.SaveAs(".png")

    #    if postfix == "Run2011A_Mu40":
    #        eff_plus = 0.006
    #       eff_minus = 0.006

    print "%s overall efficiency %f + %f - %f" % (postfix, eff_value, eff_plus,
                                                  eff_minus)
    return (eff_value, eff_plus, eff_minus)
Esempio n. 41
0
    def plot(self, datasets, an, t="Met"):
        h = Plot(
            datasets,
            an,
            [
                #"Muon,"+t+"_DPhi",
                "Tau," + t + "_DPhi",
                "Muon," + t + "Original_DPhi",
                #"Tau,"+t+"Original_DPhi"
            ])

        ylabel = self.ylabel % h.binWidth()

        h.histoMgr.setHistoLegendLabelMany({
            #"Muon,"+t+"_DPhi": "#Delta#phi(#mu, MET_{#tau})",
            "Muon," + t + "Original_DPhi":
            "#Delta#phi(#mu, MET_{#mu})",
            "Tau," + t + "_DPhi":
            "#Delta#phi(#tau, MET_{#tau})",
            #"Tau,"+t+"Original_DPhi": "#Delta#phi(#tau, MET_{#mu})"
        })
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(self.rebin))
        h.createFrame("MuonTau," + t + "_DPhi")
        h.frame.GetXaxis().SetTitle("#Delta#phi")
        h.frame.GetYaxis().SetTitle(ylabel)
        h.setLegend(createLegend2(y1=0.75))
        drawSave(h)

        style.setWide(True)
        h = Plot(datasets, an, ["Muon," + t + "Original_Tau," + t + "_DPhi"])
        h.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().Rebin2D(self.rebin, self.rebin))
        h.createFrame("MuonTau," + t + "DPhi2D",
                      xmin=-3.5,
                      ymin=-3.5,
                      xmax=3.5,
                      ymax=3.5)
        h.frame.GetXaxis().SetTitle("#Delta#phi(#mu, MET_{#mu})")
        h.frame.GetYaxis().SetTitle("#Delta#phi(#tau, MET_{#tau})")
        h.histoMgr.setHistoDrawStyleAll("COLZ")
        drawSave(h, updatePaletteStyle=True)
        style.setWide(False)

        name = t + "," + t + "Original_DPhi"
        h = Plot(datasets, an, [name])
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(self.rebin))
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetStats(True))
        h.createFrame(name)
        h.frame.GetXaxis().SetTitle("#Delta#phi(MET_{#tau},MET_{#mu}) (rad)")
        h.frame.GetYaxis().SetTitle(self.ylabel)
        drawSave(h)

        #style.setOptStat(1)
        name = t + "," + t + "Original_DEt"
        h = Plot(datasets, an, [name])
        h.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().Rebin(self.rebinMet))
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetStats(True))
        h.createFrame(name, xmin=-100, xmax=200)
        h.frame.GetXaxis().SetTitle("MET_{#tau}-MET_{#mu} (GeV)")
        h.frame.GetYaxis().SetTitle(self.ylabelMet)
        h.draw()
        #ROOT.gPad.Update()
        #box = h.histoMgr.getHistos()[0].FindObject("stats")
        #box.SetOptStat("em")
        #box.SetX1NDC(0.8)
        #box.SetX2NDC(0.92)
        #box.SetY1NDC(0.8)
        #box.SetY2NDC(0.92)
        #box.Draw()
        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        h.save()
        #style.setOptStat(0)

        style.setWide(True)
        name = "Muon," + t + "Original_DPhi_" + name
        h = Plot(datasets, an, [name])
        h.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().Rebin2D(self.rebin, self.rebinMet))
        h.createFrame(name, xmin=-3.5, ymin=-100, xmax=3.5, ymax=200)
        h.frame.GetXaxis().SetTitle("#Delta#phi(#mu, MET_{#mu})")
        h.frame.GetYaxis().SetTitle("MET_{#tau}-MET_{#mu}")
        h.histoMgr.setHistoDrawStyleAll("COLZ")
        drawSave(h, updatePaletteStyle=True)
        style.setWide(False)

        numEventsAll = h.histoMgr.getHistos()[0].getRootHisto().GetEntries()

        h = Plot(datasets, an, [
            "GenWTauNu," + t + "_DPhi",
            "GenWNu," + t + "Original_DPhi",
        ])
        h.histoMgr.setHistoLegendLabelMany({
            "GenWTauNu," + t + "_DPhi":
            "#Delta#phi(#nu_{#mu}+#nu_{#tau}, MET_{#tau})",
            "GenWNu," + t + "Original_DPhi":
            "#Delta#phi(#nu_{#mu}, MET_{#nu})"
        })
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(self.rebin))
        h.createFrame("GenWNu_GenWTauNu_" + t + "_DPhi")
        h.frame.GetXaxis().SetTitle("#Delta#phi")
        h.frame.GetYaxis().SetTitle(self.ylabel)
        h.setLegend(createLegend2())
        drawSave(h)

        numEventsGenMu = h.histoMgr.getHistos()[0].getRootHisto().GetEntries()
        print "%s: N(W->munu) / N(all) = %d/%d = %.1f %%" % (
            an, numEventsGenMu, numEventsAll,
            numEventsGenMu / numEventsAll * 100)

        style.setWide(True)
        h = Plot(datasets, an,
                 ["GenWNu," + t + "Original_GenWTauNu," + t + "_DPhi"])
        h.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().Rebin2D(self.rebin, self.rebin))
        h.createFrame("GenWNu_GenWTauNu_" + t + "_DPhi2D",
                      xmin=-3.5,
                      ymin=-3.5,
                      xmax=3.5,
                      ymax=3.5)
        h.frame.GetXaxis().SetTitle("#Delta#phi(#nu_{#mu}, MET_{#mu})")
        h.frame.GetYaxis().SetTitle(
            "#Delta#phi(#nu_{#mu}+#nu_{#tau}, MET_{#tau})")
        h.histoMgr.setHistoDrawStyleAll("COLZ")
        drawSave(h, updatePaletteStyle=True)
        style.setWide(False)
Esempio n. 42
0
    def fitData(self, histo):

        parInvQCD = self.parInvQCD
        parMCEWK = self.parMCEWK
        nInvQCD = self.nInvQCD
        nFitInvQCD = self.nFitInvQCD
        nMCEWK = self.nMCEWK

        class FitFunction:
            def __call__(self, x, par):
                return par[0] * (
                    par[1] * QCDFunction(x, parInvQCD, 1 / nFitInvQCD) +
                    (1 - par[1]) * EWKFunction(x, parMCEWK, 1 / nMCEWK))

        class QCDOnly:
            def __call__(self, x, par):
                return par[0] * par[1] * QCDFunction(x, parInvQCD,
                                                     1 / nFitInvQCD)

        rangeMin = histo.GetXaxis().GetXmin()
        rangeMax = histo.GetXaxis().GetXmax()
        numberOfParameters = 2

        print "Fit range ", rangeMin, " - ", rangeMax

        theFit = TF1("theFit", FitFunction(), rangeMin, rangeMax,
                     numberOfParameters)

        plot = plots.PlotBase()
        plot.histoMgr.appendHisto(histograms.Histo(histo, histo.GetName()))
        plot.createFrame("combinedfit" + self.label,
                         opts={
                             "ymin": 1e-5,
                             "ymaxfactor": 2.
                         })

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        print "data events ", histo.Integral(0, histo.GetNbinsX())

        histo.Fit(theFit, "R")

        theFit.SetRange(histo.GetXaxis().GetXmin(), histo.GetXaxis().GetXmax())
        theFit.SetLineStyle(2)
        theFit.Draw("same")

        par = theFit.GetParameters()

        qcdOnly = TF1("qcdOnly", QCDOnly(), rangeMin, rangeMax,
                      numberOfParameters)
        qcdOnly.FixParameter(0, par[0])
        qcdOnly.FixParameter(1, par[1])
        qcdOnly.SetLineStyle(2)
        qcdOnly.Draw("same")

        histograms.addText(0.35, 0.8, "Data, Baseline TauID")
        histograms.addText(0.4, 0.3, "QCD", 15)

        plot.histoMgr.appendHisto(histograms.Histo(qcdOnly, "qcdOnly"))

        plot.getPad().SetLogy(True)

        plot.draw()
        plot.save()

        fitPars = "fit parameters "
        i = 0
        while i < numberOfParameters:
            fitPars = fitPars + " " + str(par[i])
            i = i + 1
        print fitPars
        nBaseQCD = par[0]
        self.QCDfraction = par[1]
        if len(self.label) > 0:
            print "Bin ", self.label
        print "Integral     ", nBaseQCD
        print "QCD fraction ", self.QCDfraction

        return theFit
Esempio n. 43
0
def muonIso(h, prefix="", q="reliso", plotAll=False, ratio=False, printFraction=False, rebin=5, opts={}, opts2={}):
    #dist2pass(h.histoMgr.getHisto("QCD_Pt20_MuEnriched").getRootHisto())

    passed = PlotPassed(h)
    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    xlabel = {"sumIsoRel": "Muon rel. iso",
              "sumIsoRelFull": "Muon rel. iso",
              "pfSumIsoRel": "Muon PF rel. iso",
              "pfSumIsoRelFull": "Muon PF rel. iso",
              "tauTightIso": "N(PFCand) in iso annulus",
              "tauTightSc015Iso": "N(PFCand) in iso annulus",
              "tauTightSc02Iso": "N(PFCand) in iso annulus",
              "tauTightIc04Iso": "N(PFCand) in iso annulus",
              "tauTightIc04ChargedIso": "N(PFChargedCand) in iso annulus",
              "tauTightIc04GammaIso": "N(PFGammaCand) in iso annulus",
              "tauTightIc04SumPtIso": "#Sigma p_{T} in iso annulus (GeV/c)",
              "tauTightIc04MaxPtIso": "max(p_{T}) in iso annulus (GeV/c)",
              "tauTightSc015Ic04Iso": "N(PFCand) in iso annulus",
              "tauTightSc02Ic04Iso": "N(PFCand) in iso annulus",
              "tauMediumIso": "Tau-like medium occupancy",
              "tauLooseIso": "Tau-like loose occupancy",
              "tauVLooseIso": "Tau-like vloose occupancy",
              }[q]
    bw = h.binWidth()
    if bw < 1:
        ylabel = "Number of muons / %.3f" % bw
#    elif int(bw) == 1:
#        ylabel = "Number of muons"
    else:
        ylabel = "Number of muons / %.0f" % bw
    
    h.stackMCHistograms()

    if plotAll:
        h.createFrame(prefix+"muon_"+q, createRatio=ratio)
        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()

    _opts = {"ymin": 1e-2, "ymaxfactor": 10}
    _opts.update(opts)
    _opts2 = {"ymin": 0, "ymax": 2}
    _opts2.update(opts2)

    h.createFrame(prefix+"muon_%s_log" % q, createRatio=ratio, opts=_opts, opts2=_opts2)
    h.frame.GetXaxis().SetTitle(xlabel)
    h.frame.GetYaxis().SetTitle(ylabel)
    h.setLegend(histograms.createLegend())
    ROOT.gPad.SetLogy(True)
    h.draw()
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    h.histoMgr.addLuminosityText()
    h.save()

    passed.createFrame(prefix+"muon_%s_log_passed" % q, ymin=10, ymaxfactor=10)
    passed.frame.GetXaxis().SetTitle("Cut on "+xlabel)
    passed.frame.GetYaxis().SetTitle("Passed events")
    ROOT.gPad.SetLogy(True)
    passed.draw()
    passed.save()

    if printFraction:
        print "----------------------------------------"
        print "quantity %s" % q
        passed.printFractions(21)
        passed.printFractions(31)
        passed.printFractions(101)
        print "----------------------------------------"

    qcdFraction = PlotIso([passed], q)
    qcdFraction.createFrame(prefix+"muon_%s_qcdfraction" % q)
    qcdFraction.frame.GetXaxis().SetTitle("Cut on "+xlabel)
    qcdFraction.frame.GetYaxis().SetTitle("Fraction of QCD")
    qcdFraction.draw()
    qcdFraction.save()

    return passed
Esempio n. 44
0
    def fitQCD(self, origHisto):

        histo = origHisto.Clone("histo")

        rangeMin = histo.GetXaxis().GetXmin()
        rangeMax = histo.GetXaxis().GetXmax()

        numberOfParameters = 8

        print "Fit range ", rangeMin, " - ", rangeMax

        class FitFunction:
            def __call__(self, x, par):
                return QCDFunction(x, par, 1)

        theFit = TF1('theFit', FitFunction(), rangeMin, rangeMax,
                     numberOfParameters)

        theFit.SetParLimits(0, 1, 20)
        theFit.SetParLimits(1, 20, 40)
        theFit.SetParLimits(2, 10, 25)

        theFit.SetParLimits(3, 1, 10)
        theFit.SetParLimits(4, 0, 150)
        theFit.SetParLimits(5, 10, 100)

        theFit.SetParLimits(6, 0.0001, 1)
        theFit.SetParLimits(7, 0.001, 0.05)

        if self.label == "Baseline":
            rangeMax = 240

        if self.label == "7080":
            theFit.SetParLimits(5, 10, 100)

#	if self.label == "100120":
#	    theFit.SetParLimits(0,1,20)
#	    theFit.SetParLimits(2,1,25)
#	    theFit.SetParLimits(3,0.1,20)

        if self.label == "120150":
            theFit.SetParLimits(0, 1, 20)
            theFit.SetParLimits(3, 0.1, 5)

        gStyle.SetOptFit(0)

        plot = plots.PlotBase()
        plot.histoMgr.appendHisto(histograms.Histo(histo, histo.GetName()))
        plot.createFrame("qcdfit" + self.label,
                         opts={
                             "ymin": 1e-5,
                             "ymaxfactor": 2.
                         })

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        self.normInvQCD = histo.Integral(0, histo.GetNbinsX())

        histo.Scale(1 / self.normInvQCD)
        histo.Fit(theFit, "LR")

        theFit.SetRange(histo.GetXaxis().GetXmin(), histo.GetXaxis().GetXmax())
        theFit.SetLineStyle(2)
        theFit.Draw("same")

        histograms.addText(0.4, 0.8, "Inverted TauID")

        plot.histoMgr.appendHisto(histograms.Histo(theFit, "Fit"))

        plot.getPad().SetLogy(True)

        plot.draw()
        plot.save()

        self.parInvQCD = theFit.GetParameters()

        fitPars = "fit parameters "
        i = 0
        while i < numberOfParameters:
            fitPars = fitPars + " " + str(self.parInvQCD[i])
            i = i + 1
        print fitPars
        self.nFitInvQCD = theFit.Integral(0, 1000, self.parInvQCD)
        print "Integral ", self.normInvQCD * self.nFitInvQCD
Esempio n. 45
0
    def cutefficiency(self, histo1, histo2):

        h1 = histo1.Clone("h1")
        h2 = histo2.Clone("h2")

        h1.Scale(1 / h1.GetMaximum())
        h2.Scale(1 / h2.GetMaximum())

        # check that no bin has negative value, negative values possible after subtracting EWK from data
        iBin = 1
        nBins = h1.GetNbinsX()
        while iBin < nBins:
            value1 = h1.GetBinContent(iBin)
            value2 = h2.GetBinContent(iBin)

            if value1 < 0:
                h1.SetBinContent(iBin, 0)

            if value2 < 0:
                h2.SetBinContent(iBin, 0)

            iBin = iBin + 1

        h1cut = h1.Clone("h1cut")
        h1cut.Reset()
        h1cut.GetYaxis().SetTitle("Efficiency")
        h1cut.GetXaxis().SetTitle("PF MET cut (GeV)")

        h2cut = h2.Clone("h2cut")
        h2cut.Reset()
        h2cut.SetLineColor(2)

        integralError = ROOT.Double(0.0)
        integralValue = h1.IntegralAndError(1, h1cut.GetNbinsX(),
                                            integralError)

        h1_integral = h1.Integral(0, h1.GetNbinsX())
        h2_integral = h2.Integral(0, h2.GetNbinsX())

        iBin = 1
        nBins = h1cut.GetNbinsX()
        while iBin < nBins:
            error = ROOT.Double(0.0)
            selected1 = h1.IntegralAndError(iBin, nBins, error)
            if selected1 > 0:
                error = error / selected1
            else:
                error = integralError / integralValue
            efficiency1 = selected1 / h1_integral
            h1cut.SetBinContent(iBin, efficiency1)
            if self.errorBars:
                h1cut.SetBinError(iBin, error)

            error = ROOT.Double(0.0)
            selected2 = h2.IntegralAndError(iBin, nBins, error)
            if selected2 > 0:
                error = error / selected2
            else:
                error = integralError / integralValue
            efficiency2 = selected2 / h2_integral
            h2cut.SetBinContent(iBin, efficiency2)
            if self.errorBars:
                h2cut.SetBinError(iBin, error)

            iBin = iBin + 1

        plot = plots.ComparisonPlot(
            histograms.Histo(h1cut, "Inv"),
            histograms.Histo(h2cut, "Base"),
        )
        # Set the styles
        st1 = styles.getDataStyle().clone()
        st2 = st1.clone()
        st2.append(styles.StyleLine(lineColor=ROOT.kRed))
        st2.append(styles.StyleMarker(markerColor=ROOT.kRed))
        plot.histoMgr.forHisto("Base", st1)
        plot.histoMgr.forHisto("Inv", st2)

        # Set the legend labels
        plot.histoMgr.setHistoLegendLabelMany({
            "Inv": h1.GetTitle(),
            "Base": h2.GetTitle()
        })
        # Set the legend styles
        #plot.histoMgr.setHistoLegendStyleAll("L")
        plot.histoMgr.setHistoLegendStyleAll("P")

        # Set the drawing styles
        #plot.histoMgr.setHistoDrawStyleAll("HIST")
        plot.histoMgr.setHistoDrawStyleAll("EP")

        # Create frame with a ratio pad
        plot.createFrame(
            "cuteff" + self.label,
            opts={
                "ymin": 1e-5,
                "ymaxfactor": 2
            },
            createRatio=True,
            opts2={
                "ymin": 0,
                "ymax": 2
            },  # bounds of the ratio plot
        )

        # Set Y axis of the upper pad to logarithmic
        plot.getPad().SetLogy(True)

        plot.setLegend(histograms.createLegend(0.4, 0.82, 0.9, 0.93))

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        plot.draw()
        plot.save()

        ######

        hError = h1cut.Clone("hError")
        hError.Divide(h2cut)

        iBin = 1
        nBins = hError.GetNbinsX()
        while iBin < nBins:
            hError.SetBinContent(iBin, abs(hError.GetBinContent(iBin) - 1))
            iBin = iBin + 1

        hError.GetYaxis().SetTitle(
            "abs( (#varepsilon^{Inverted} - #varepsilon^{Baseline})/#varepsilon^{Baseline} )"
        )
        hError.GetXaxis().SetTitle("PF MET cut (GeV)")

        plot2 = plots.PlotBase()
        plot2.histoMgr.appendHisto(histograms.Histo(hError,
                                                    "ShapeUncertainty"))
        plot2.histoMgr.forHisto("ShapeUncertainty", st1)
        plot2.histoMgr.setHistoDrawStyleAll("EP")
        #        plot2.createFrame("shapeUncertainty"+self.label, opts={"ymin":-1, "ymax": 1})
        plot2.createFrame("shapeUncertainty" + self.label,
                          opts={
                              "ymin": -0.1,
                              "ymax": 1.1
                          })

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        rangeMin = hError.GetXaxis().GetXmin()
        rangeMax = hError.GetXaxis().GetXmax()
        #	rangeMax = 80
        rangeMax = 120
        #	rangeMax = 380

        numberOfParameters = 2

        class FitFunction:
            def __call__(self, x, par):
                #                return Linear(x,par)
                return ErrorFunction(x, par)

        theFit = TF1('theFit', FitFunction(), rangeMin, rangeMax,
                     numberOfParameters)
        theFit.SetParLimits(0, 0.01, 0.03)
        theFit.SetParLimits(1, 50, 150)

        #	theFit.FixParameter(0,0.02)
        #	theFit.FixParameter(1,100)

        hError.Fit(theFit, "LRN")
        print "Error MET > 40", theFit.Eval(40)
        print "Error MET > 50", theFit.Eval(50)
        print "Error MET > 70", theFit.Eval(70)

        plot2.histoMgr.appendHisto(histograms.Histo(theFit, "Fit"))

        plot2.draw()
        plot2.save()
Esempio n. 46
0
    def comparison(self, histo1, histo2, norm=1):

        h1 = histo1.Clone("h1")
        h2 = histo2.Clone("h2")
        if norm == 1:
            h1.Scale(1 / h1.GetMaximum())
            h2.Scale(1 / h2.GetMaximum())

        # check that no bin has negative value, negative values possible after subtracting EWK from data
        iBin = 1
        nBins = h1.GetNbinsX()
        while iBin < nBins:
            value1 = h1.GetBinContent(iBin)
            value2 = h2.GetBinContent(iBin)

            if value1 < 0:
                h1.SetBinContent(iBin, 0)

            if value2 < 0:
                h2.SetBinContent(iBin, 0)

            iBin = iBin + 1

        if norm > 0:
            h1.GetYaxis().SetTitle("Arbitrary units")

        plot = plots.ComparisonPlot(
            histograms.Histo(h1, "Inv"),
            histograms.Histo(h2, "Base"),
        )
        # Set the styles
        st1 = styles.getDataStyle().clone()
        st2 = st1.clone()
        st2.append(styles.StyleMarker(markerColor=ROOT.kRed))
        plot.histoMgr.forHisto("Base", st1)
        plot.histoMgr.forHisto("Inv", st2)

        # Set the legend labels
        plot.histoMgr.setHistoLegendLabelMany({
            "Inv": h1.GetTitle(),
            "Base": h2.GetTitle()
        })
        # Set the legend styles
        plot.histoMgr.setHistoLegendStyleAll("P")

        # Set the drawing styles
        plot.histoMgr.setHistoDrawStyleAll("EP")

        # Create frame with a ratio pad
        plot.createFrame(
            "comparison" + self.label,
            opts={
                "ymin": 1e-5,
                "ymaxfactor": 2
            },
            createRatio=True,
            opts2={
                "ymin": 0,
                "ymax": 2
            },  # bounds of the ratio plot
        )

        # Set Y axis of the upper pad to logarithmic
        plot.getPad1().SetLogy(True)

        plot.setLegend(histograms.createLegend(0.4, 0.82, 0.9, 0.93))

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        plot.draw()
        plot.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()
Esempio n. 48
0
def distComparison(datasets):
    # Create a comparison plot of two distributions (must have the same binning)
    # Set the names of DatasetRootHisto objects in order to be able easily reference them later
    drh1 = datasets.getDataset("Data").getDatasetRootHisto(
        analysis + "/MET_BaseLineTauId")
    drh1.setName("Base")
    drh1.normalizeToOne()
    drh2 = datasets.getDataset("Data").getDatasetRootHisto(
        analysis + "/MET_InvertedTauId")
    drh2.setName("Inv")
    drh2.normalizeToOne()
    plot = plots.ComparisonPlot(drh1, drh2)

    # Set the styles
    st1 = styles.getDataStyle().clone()
    st2 = st1.clone()
    st2.append(styles.StyleLine(lineColor=ROOT.kRed))
    plot.histoMgr.forHisto("Base", st1)
    plot.histoMgr.forHisto("Inv", st2)

    # Set the legend labels
    plot.histoMgr.setHistoLegendLabelMany({
        "Base": "Baseline Tau ID",
        "Inv": "Inverted Tau ID"
    })
    # Set the legend styles
    plot.histoMgr.setHistoLegendStyleAll("L")

    plot.histoMgr.setHistoLegendStyle("Base",
                                      "P")  # exception to the general rule

    # Set the drawing styles
    plot.histoMgr.setHistoDrawStyleAll("HIST")
    plot.histoMgr.setHistoDrawStyle("Base",
                                    "EP")  # exception to the general rule

    # Rebin, if necessary
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))

    # Create frame with a ratio pad
    plot.createFrame(
        "METbaseVSinvertedTauID",
        opts={
            "ymin": 1e-5,
            "ymaxfactor": 1.5
        },
        createRatio=True,
        opts2={
            "ymin": -10,
            "ymax": 50
        },  # bounds of the ratio plot
    )

    # Set Y axis of the upper pad to logarithmic
    plot.getPad1().SetLogy(True)

    # Create legend to the default position
    plot.setLegend(histograms.createLegend())

    # Set the X/Y axis labels
    plot.frame.GetXaxis().SetTitle("MET (GeV)")
    plot.frame.GetYaxis().SetTitle("Arbitrary units")

    # Draw the plot
    plot.draw()

    # Add the various texts to
    histograms.addCmsPreliminaryText()
    histograms.addEnergyText()
    histograms.addLuminosityText(
        x=None, y=None, lumi=datasets.getDataset("Data").getLuminosity())

    # Save the plot to files
    plot.save()
Esempio n. 49
0
    def Save(self, name):

        if len(self.histogramsNotFound) > 0:
            for name in self.histogramsNotFound:
                print "Histo", name, "not found"
            self.histogramsNotFound = []
            return

        hObserved = self.histograms[self.FindHistoIndex(
            self.dataHistos[0].name)].Clone("Data")
        hObserved.Reset()
        for histo in self.dataHistos:
            hObserved.Add(self.histograms[self.FindHistoIndex(histo.label)])
        print "    Data:    ", hObserved.Integral(
            0, hObserved.GetNbinsX()), "events"
        hEstimatedEWKfake = self.histograms[self.FindHistoIndex(
            "EWKfake")].Clone("hEstimatedEWKfake")
        print "    EWKfake: ", hEstimatedEWKfake.Integral(
            0, hEstimatedEWKfake.GetNbinsX()), "events"
        hEstimatedEWK = self.histograms[self.FindHistoIndex("EWK")].Clone(
            "hEstimatedEWK")
        print "    EWK:     ", hEstimatedEWK.Integral(
            0, hEstimatedEWK.GetNbinsX()), "events"
        hEstimatedEWK.Add(hEstimatedEWKfake)
        hEstimatedQCD = self.histograms[self.FindHistoIndex("QCD")].Clone(
            "hEstimatedQCD")
        print "    QCD:     ", hEstimatedQCD.Integral(
            0, hEstimatedQCD.GetNbinsX()), "events"
        hEstimatedQCD.Add(hEstimatedEWK)
        hUncertainty = hEstimatedQCD.Clone("BackgrUncertainty")
        hUncertainty.SetFillColor(1)
        hUncertainty.SetFillStyle(3354)
        hUncertainty.SetLineColor(0)
        hUncertainty.SetLineStyle(0)
        hUncertainty.SetLineWidth(0)
        hUncertainty.SetMarkerColor(0)
        hUncertainty.SetMarkerSize(0)
        hSignal = self.histograms[self.FindHistoIndex("Signal")].Clone(
            "hSignal")
        print "    Signal:  ", hSignal.Integral(0,
                                                hSignal.GetNbinsX()), "events"
        hSignal.Add(hEstimatedQCD)

        style = tdrstyle.TDRStyle()

        plot = plots.ComparisonManyPlot(histograms.Histo(hObserved, "Data"), [
            histograms.Histo(hUncertainty, "Backgr.Uncertainty"),
            histograms.Histo(hEstimatedEWKfake, "EWKfake"),
            histograms.Histo(hEstimatedEWK, "EWK"),
            histograms.Histo(hEstimatedQCD, "QCD"),
            histograms.Histo(hSignal, "Signal")
        ])

        plot.histoMgr.forHisto("Data", styles.getDataStyle())

        plot.histoMgr.forHisto("EWK", styles.getEWKStyle())
        plot.histoMgr.forHisto("EWKfake", styles.getEWKFakeStyle())
        plot.histoMgr.forHisto("QCD", styles.getQCDStyle())
        plot.histoMgr.forHisto("Signal", styles.getSignalStyle())
        plot.histoMgr.forHisto("Backgr.Uncertainty", styles.getErrorStyle())

        plot.histoMgr.setHistoDrawStyleAll("HIST")
        plot.histoMgr.setHistoDrawStyle("Data", "EP")
        plot.histoMgr.setHistoDrawStyle("Backgr.Uncertainty", "E2")

        plot.histoMgr.setHistoLegendStyleAll("F")
        plot.histoMgr.setHistoLegendStyle("Data", "P")
        plot.histoMgr.setHistoLegendStyle("Signal", "L")

        plot.createFrame(name, opts={"ymin": 0, "ymaxfactor": 1.2})
        plot.frame.GetXaxis().SetTitle(self.xtitle)
        plot.frame.GetYaxis().SetTitle(self.ytitle)

        plot.histoMgr.reorderLegend(
            ["Data", "Signal", "QCD", "EWK", "EWKfake", "Backgr.Uncertainty"])
        self.setLegendLabels(plot)
        plot.setLegend(histograms.createLegend(0.55, 0.68, 0.9, 0.93))

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        plot.draw()
        plot.save()
Esempio n. 50
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()
Esempio n. 51
0
def main():
    # Read the datasets
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.loadLuminosities()

    plots.mergeRenameReorderForDataMC(datasets)

    # Remove signals other than M120
    ###    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
    ###    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    # Set the signal cross sections to a given BR(t->H), BR(h->taunu)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)

    # Set the signal cross sections to a value from MSSM
    #    xsect.setHplusCrossSectionsToMSSM(datasets, tanbeta=20, mu=200)

    ###    plots.mergeWHandHH(datasets) # merging of WH and HH signals must be done after setting the cross section

    style = tdrstyle.TDRStyle()

    eventCounter = counter.EventCounter(datasets, counters=counters)
    eventCounter.normalizeMCByCrossSection()
    mainTable = eventCounter.getMainCounterTable()

    signalDatasets = [
        "TTToHplusBWB_M80",
        "TTToHplusBWB_M90",
        "TTToHplusBWB_M100",
        "TTToHplusBWB_M120",
        "TTToHplusBWB_M140",
        "TTToHplusBWB_M150",
        "TTToHplusBWB_M155",
        "TTToHplusBWB_M160",
    ]
    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"
    ]

    xvalues = [80, 90, 100, 120, 140, 150, 155, 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"))

        for cut in cuts:
            cutCount = column.getCount(column.getRowNames().index(cut))
            eff = cutCount.clone()
            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(0.9)
        gr.SetLineStyle(1)
        gr.SetLineWidth(2)
        return gr

    gtrig = createErrors("Trigger and HLT_MET cut")
    gtrig.SetLineColor(38)
    gtrig.SetMarkerColor(38)
    gtrig.SetLineStyle(2)
    gtau = createErrors("taus == 1")
    gtau.SetLineColor(2)
    gtau.SetMarkerColor(2)
    gtau.SetLineStyle(3)
    #gtau = createErrors("trigger scale factor")
    gveto = createErrors("muon veto")
    gveto.SetLineColor(1)
    gveto.SetMarkerColor(1)
    gveto.SetLineStyle(4)
    gjets = createErrors("njets")
    gjets.SetLineColor(4)
    gjets.SetMarkerColor(4)
    gjets.SetLineStyle(1)
    gmet = createErrors("MET")
    gmet.SetLineColor(2)
    gmet.SetMarkerColor(2)
    gmet.SetLineStyle(5)
    gbtag = createErrors("btagging")
    gbtag.SetLineColor(1)
    gbtag.SetMarkerColor(1)
    gbtag.SetLineStyle(6)
    #gtau = createErrors("trigger scale factor")

    glist = [gtrig, gtau, gveto, gjets, gmet, gbtag]

    opts = {"xmin": 75, "xmax": 165, "ymin": 0.001}
    canvasFrame = histograms.CanvasFrame(
        [histograms.HistoGraph(g, "", "") for g in glist], "SignalEfficiency",
        **opts)
    canvasFrame.frame.GetYaxis().SetTitle("Selection efficiency")
    canvasFrame.frame.GetXaxis().SetTitle("m_{H^{#pm}} (GeV/c^{2})")
    canvasFrame.canvas.SetLogy(True)
    canvasFrame.frame.Draw()

    for gr in glist:
        gr.Draw("PC same")

    histograms.addEnergyText()
    histograms.addCmsPreliminaryText()

    legend = histograms.createLegend(x1=0.5, y1=0.53, x2=0.85, y2=0.75)

    legend.AddEntry(gtrig, "Trigger", "l")
    legend.AddEntry(gtau, "#tau identification", "l")
    legend.AddEntry(gveto, "lepton vetoes", "l")
    legend.AddEntry(gjets, "3 jets", "l")
    legend.AddEntry(gmet, "MET ", "l")
    legend.AddEntry(gbtag, "b tagging ", "l")
    legend.Draw()

    canvasFrame.canvas.SaveAs(".png")
    canvasFrame.canvas.SaveAs(".C")
    canvasFrame.canvas.SaveAs(".eps")
Esempio n. 52
0
    def fitEWK(self, histo, options="R"):

        rangeMin = histo.GetXaxis().GetXmin()
        rangeMax = histo.GetXaxis().GetXmax()
        #	rangeMin = 120
        #	rangeMax = 120

        numberOfParameters = 4

        print "Fit range ", rangeMin, " - ", rangeMax

        class FitFunction:
            def __call__(self, x, par):
                return EWKFunction(x, par, 1, 1)
#		return SumFunction(x,par)
#	        return TestFunction(x,par,1)

        class PlotFunction:
            def __call__(self, x, par):
                return EWKFunction(x, par, 0)

        theFit = TF1('theFit', FitFunction(), rangeMin, rangeMax,
                     numberOfParameters)
        thePlot = TF1('thePlot', PlotFunction(), rangeMin, rangeMax,
                      numberOfParameters)

        theFit.SetParLimits(0, 5, 30)
        theFit.SetParLimits(1, 90, 120)
        theFit.SetParLimits(2, 30, 50)
        theFit.SetParLimits(3, 0.001, 1)

        if self.label == "4050":
            theFit.SetParLimits(0, 5, 20)
            theFit.SetParLimits(1, 90, 120)
            theFit.SetParLimits(2, 30, 50)
            theFit.SetParLimits(3, 0.001, 1)

        if self.label == "5060":
            theFit.SetParLimits(0, 5, 20)
            theFit.SetParLimits(1, 90, 120)
            theFit.SetParLimits(2, 20, 50)
            theFit.SetParLimits(3, 0.001, 1)

        if self.label == "6070":
            theFit.SetParLimits(0, 5, 50)
            theFit.SetParLimits(1, 90, 150)
            theFit.SetParLimits(2, 20, 50)
            theFit.SetParLimits(3, 0.001, 1)

        if self.label == "7080":
            theFit.SetParLimits(0, 5, 60)
            theFit.SetParLimits(1, 90, 200)
            theFit.SetParLimits(2, 20, 100)
            theFit.SetParLimits(3, 0.001, 1)

        if self.label == "80100":
            theFit.SetParLimits(0, 5, 50)
            theFit.SetParLimits(1, 50, 170)
            theFit.SetParLimits(2, 20, 60)
            theFit.SetParLimits(3, 0.001, 1)

        if self.label == "100120":
            theFit.SetParLimits(0, 5, 50)
            theFit.SetParLimits(1, 90, 170)
            theFit.SetParLimits(2, 20, 60)
            theFit.SetParLimits(3, 0.001, 1)

        if self.label == "120150":
            theFit.SetParLimits(0, 5, 50)
            theFit.SetParLimits(1, 60, 170)
            theFit.SetParLimits(2, 10, 100)
            theFit.SetParLimits(3, 0.001, 1)

        if self.label == "150":
            theFit.SetParLimits(0, 5, 50)
            theFit.SetParLimits(1, 70, 170)
            theFit.SetParLimits(2, 20, 100)
            theFit.SetParLimits(3, 0.001, 1)

        plot = plots.PlotBase()
        plot.histoMgr.appendHisto(histograms.Histo(histo, histo.GetName()))
        plot.createFrame("ewkfit" + self.label,
                         opts={
                             "ymin": 1e-5,
                             "ymaxfactor": 2.
                         })

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        self.normEWK = histo.Integral(0, histo.GetNbinsX())

        histo.Scale(1 / self.normEWK)

        histo.Fit(theFit, options)

        theFit.SetRange(histo.GetXaxis().GetXmin(), histo.GetXaxis().GetXmax())
        theFit.SetLineStyle(2)
        theFit.Draw("same")

        self.parMCEWK = theFit.GetParameters()

        fitPars = "fit parameters "

        i = 0
        while i < numberOfParameters:
            fitPars = fitPars + " " + str(self.parMCEWK[i])
            thePlot.SetParameter(i, theFit.GetParameter(i))
            i = i + 1
        thePlot.Draw("same")

        histograms.addText(0.2, 0.2, "EWK MC, baseline TauID")

        plot.histoMgr.appendHisto(histograms.Histo(theFit, "Fit"))

        plot.getPad().SetLogy(True)

        plot.draw()
        plot.save()

        self.parMCEWK = theFit.GetParameters()

        print fitPars
        self.nMCEWK = theFit.Integral(0, 1000, self.parMCEWK)
        print "Integral ", self.normEWK * self.nMCEWK
h.addMCUncertainty()

# Create canvas and frame for only the distributions
h.createFrame("taupt_new")
h.frame.GetXaxis().SetTitle("#tau p_T (GeV/c)")
h.frame.GetYaxis().SetTitle("#tau cands / 1 GeV/c")

# Create legend
h.setLegend(histograms.createLegend())

# Draw the histograms and the legend
h.draw()

# Add the necessary pieces of text
histograms.addCmsPreliminaryText()
histograms.addEnergyText()
h.addLuminosityText()

# Save to .png, .eps and .C file
h.save()

#  counters = "qcdMeasurementMethod2Part1Counters/weighted"
# Same, but create two pads, one for the distributions and another for
# the data/MC
h = plots.DataMCPlot(
    datasets,
    "qcdMeasurementMethod2Part1Counters/TauSelection_all_tau_candidates_pt")
h.stackMCHistograms()
h.addMCUncertainty()
h.createFrameFraction("taupt_new2", )
Esempio n. 54
0
def doCounters(datasets):
    eventCounter = counter.EventCounter(datasets)

    eventCounter.normalizeMCByLuminosity()
    #    eventCounter.normalizeMCToLuminosity(73)
    print "============================================================"
    print "Main counter (MC normalized by collision data luminosity)"
    print eventCounter.getMainCounterTable().format()

    # Set the signal cross sections to a value from MSSM
    #    xsect.setHplusCrossSectionsToMSSM(datasets, tanbeta=20, mu=200)

    ###    plots.mergeWHandHH(datasets) # merging of WH and HH signals must be done after setting the cross section

    style = tdrstyle.TDRStyle()

    eventCounter = counter.EventCounter(datasets, counters=counters)
    eventCounter.normalizeMCByCrossSection()
    mainTable = eventCounter.getMainCounterTable()

    signalDatasets = [
        "TTToHplusBWB_M80",
        "TTToHplusBWB_M90",
        "TTToHplusBWB_M100",
        "TTToHplusBWB_M120",
        "TTToHplusBWB_M140",
        "TTToHplusBWB_M150",
        "TTToHplusBWB_M155",
        "TTToHplusBWB_M160",
    ]
    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"
    ]

    xvalues = [80, 90, 100, 120, 140, 150, 155, 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"))

        for cut in cuts:
            cutCount = column.getCount(column.getRowNames().index(cut))
            if column.getRowNames().index(cut) == 1:  ## trigger
                allCount = column.getCount(
                    column.getRowNames().index("All events"))

            if column.getRowNames().index(cut) == 4:  ## tau id
                allCount = column.getCount(
                    column.getRowNames().index("Trigger and HLT_MET cut"))

            if column.getRowNames().index(cut) == 7:  ## electron veto
                allCount = column.getCount(
                    column.getRowNames().index("taus == 1"))

            if column.getRowNames().index(cut) == 8:  ## muon veto
                ## muon veto for lepton veto
                allCount = column.getCount(
                    column.getRowNames().index("taus == 1"))
#                allCount = column.getCount(column.getRowNames().index("electron veto"))

            if column.getRowNames().index(cut) == 9:  ## njets
                allCount = column.getCount(
                    column.getRowNames().index("muon veto"))

            if column.getRowNames().index(cut) == 10:  ## MET
                allCount = column.getCount(column.getRowNames().index("njets"))

            if column.getRowNames().index(cut) == 11:  ## btagging
                allCount = column.getCount(column.getRowNames().index("MET"))

            eff = cutCount.clone()
            eff.divide(allCount)  # N(cut) / N(all)
            #            print "cutCount ",cutCount.value(),"allCount  ",allCount.value()

            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(0.9)
        gr.SetLineStyle(1)
        gr.SetLineWidth(2)
        return gr

    gtrig = createErrors("Trigger and HLT_MET cut")
    gtrig.SetLineColor(38)
    gtrig.SetMarkerColor(38)
    gtrig.SetLineStyle(8)
    gtrig.SetLineWidth(4)
    gtau = createErrors("taus == 1")
    gtau.SetLineColor(2)
    gtau.SetMarkerColor(2)
    gtau.SetLineStyle(3)
    gtau.SetLineWidth(4)
    #gtau = createErrors("trigger scale factor")
    gveto = createErrors("muon veto")
    gveto.SetLineColor(1)
    gveto.SetMarkerColor(1)
    gveto.SetLineStyle(5)
    gveto.SetLineWidth(4)
    gjets = createErrors("njets")
    gjets.SetLineColor(4)
    gjets.SetMarkerColor(4)
    gjets.SetLineStyle(1)
    gjets.SetLineWidth(4)
    gmet = createErrors("MET")
    gmet.SetLineColor(2)
    gmet.SetMarkerColor(2)
    gmet.SetLineStyle(2)
    gmet.SetLineWidth(4)
    gbtag = createErrors("btagging")
    gbtag.SetLineColor(1)
    gbtag.SetMarkerColor(1)
    gbtag.SetLineStyle(6)
    gbtag.SetLineWidth(4)
    #gtau = createErrors("trigger scale factor")

    glist = [gtrig, gtau, gveto, gjets, gmet, gbtag]

    opts = {"xmin": 75, "xmax": 165, "ymin": 0.03}
    canvasFrame = histograms.CanvasFrame(
        [histograms.HistoGraph(g, "", "") for g in glist],
        "SignalEfficiencyConseq", **opts)
    canvasFrame.frame.GetYaxis().SetTitle("Selection efficiency")
    canvasFrame.frame.GetXaxis().SetTitle("m_{H^{#pm}} (GeV/c^{2})")
    canvasFrame.canvas.SetLogy(True)
    canvasFrame.frame.Draw()

    for gr in glist:
        gr.Draw("PC same")

    histograms.addEnergyText()
    histograms.addCmsPreliminaryText()

    legend = histograms.createLegend(x1=0.5, y1=0.53, x2=0.85, y2=0.75)

    legend.AddEntry(gtrig, "Trigger", "l")
    legend.AddEntry(gtau, "#tau identification", "l")
    legend.AddEntry(gveto, "lepton vetoes", "l")
    legend.AddEntry(gjets, "3 jets", "l")
    legend.AddEntry(gmet, "MET ", "l")
    legend.AddEntry(gbtag, "b tagging ", "l")
    legend.Draw()

    canvasFrame.canvas.SaveAs(".png")
    canvasFrame.canvas.SaveAs(".C")
    canvasFrame.canvas.SaveAs(".eps")