Пример #1
0
def getPavetext():
    addInfo = TPaveText(0.3010112, 0.2066292, 0.4202143, 0.3523546, "NDC")
    addInfo.SetFillColor(0)
    addInfo.SetLineColor(0)
    addInfo.SetFillStyle(0)
    addInfo.SetBorderSize(0)
    addInfo.SetTextFont(42)
    addInfo.SetTextSize(0.040)
    addInfo.SetTextAlign(12)
    return addInfo
Пример #2
0
def tgs(tgraphs, title):

    tmg = TMultiGraph()
    tle = TLegend(0.6, 0.4, 0.9, 0.8)
    tit = TPaveText(0.2988506, 0.934322, 0.6997126, 1, "nbNDC")

    # Make title
    tit.SetFillColor(0)
    tit.SetFillStyle(0)
    tit.SetLineColor(0)
    tit.AddText(title)

    for i in xrange(len(tgraphs)):
        tgraphs[i].SetLineWidth(2)
        tgraphs[i].SetLineColor(i + 1)

        tmg.Add(tgraphs[i])
        tle.AddEntry(tgraphs[i], tgraphs[i].GetName(), "l")

    return [tmg, tle, tit]
Пример #3
0
def main(options, args):

    from ROOT import gSystem, gROOT, gStyle
    gROOT.SetBatch()
    gSystem.Load("libRooFitCore")

    if options.doWebPage:
        from lip.Tools.rootutils import loadToolsLib, apply_modifs
        loadToolsLib()

    from ROOT import TFile, RooFit, RooArgSet, RooDataHist, RooKeysPdf, RooHistPdf, TCanvas, TLegend, TLatex, TArrow, TPaveText, RooAddPdf, RooArgList
    from ROOT import kWhite, kBlue, kOpenSquare
    if options.doWebPage:
        from ROOT import HtmlHelper, HtmlTag, HtmlTable, HtmlPlot

    rootglobestyle.setTDRStyle()
    gStyle.SetMarkerSize(1.5)
    gStyle.SetTitleYOffset(1.5)

    gStyle.SetPadLeftMargin(0.16)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadBottomMargin(0.13)

    gStyle.SetLabelFont(42, "XYZ")
    gStyle.SetLabelOffset(0.007, "XYZ")
    gStyle.SetLabelSize(0.05, "XYZ")

    gStyle.SetTitleSize(0.06, "XYZ")
    gStyle.SetTitleXOffset(0.9)
    gStyle.SetTitleYOffset(1.24)
    gStyle.SetTitleFont(42, "XYZ")

    ##
    ## Read files
    ##
    options.outdir = "%s_m%1.0f" % (options.outdir, options.mH)
    if options.fp:
        options.outdir += "_fp"

    ncat = options.ncat
    cats = options.cats
    if cats is "":
        categories = ["_cat%d" % i for i in range(0, ncat)]
    else:
        categories = ["_cat%s" % i for i in cats.split(",")]

    if options.mva:
        clables = {
            "_cat0": ("MVA > 0.89", ""),
            "_cat1": ("0.74 #leq MVA", "MVA < 0.89"),
            "_cat2": ("0.545 #leq MVA", "MVA < 0.74"),
            "_cat3": ("0.05 #leq MVA", "MVA < 0.545"),
            "_cat4": ("Di-jet", "Tagged"),
            "_cat5": ("Di-jet", "Tagged"),
            "_combcat": ("All Classes", "Combined")
        }
    else:
        clables = {
            "_cat0": ("max(|#eta|<1.5", "min(R_{9})>0.94"),
            "_cat1": ("max(|#eta|<1.5", "min(R_{9})<0.94"),
            "_cat2": ("max(|#eta|>1.5", "min(R_{9})>0.94"),
            "_cat3": ("max(|#eta|>1.5", "min(R_{9})<0.94"),
            "_cat4": ("Di-jet", "Tagged"),
            "_cat5": ("Di-jet", "Tagged"),
            "_combcat": ("All Classes", "Combined")
        }
    helper = Helper()

    fin = TFile.Open(options.infile)
    helper.files.append(fin)
    ws = fin.Get("cms_hgg_workspace")
    mass = ws.var("CMS_hgg_mass")
    mass.SetTitle("m_{#gamma#gamma}")
    mass.setUnit("GeV")
    mass.setRange(100., 150.)
    mass.setBins(100, "plot")
    mass.setBins(5000)

    print ws

    aset = RooArgSet(mass)

    helper.objs.append(mass)
    helper.objs.append(aset)

    fitopt = (RooFit.Minimizer("Minuit2", ""), RooFit.Minos(False),
              RooFit.SumW2Error(False), RooFit.NumCPU(8))

    if not options.binned and not options.refit:
        finpdf = TFile.Open(options.infilepdf)
        helper.files.append(finpdf)
        wspdf = finpdf.Get("wsig")
    else:
        wspdf = ws

    for c in categories:
        processes = ["ggh", "vbf", "wzh"]
        if options.fp:
            processes = ["vbf", "wzh"]
        ### elif clables[c][0] == "Di-jet":
        ###     processes = [ "vbf", "ggh" ]

        dsname = "sig_mass_m%1.0f%s" % (options.mH, c)
        print dsname
        print ws
        ds = ws.data("sig_%s_mass_m%1.0f%s" %
                     (processes[0], options.mH, c)).Clone(dsname)
        for proc in processes[1:]:
            ds.append(ws.data("sig_%s_mass_m%1.0f%s" % (proc, options.mH, c)))
        helper.dsets.append(ds)

        if options.binned:
            binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname,
                                    aset, ds)
            pdf = RooKeysPdf("pdf_%s_%s" % (dsname, f), "pdf_%s" % dsname,
                             mass, ds)
            plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset,
                                  plot_ds)
            helper.add(binned_ds, binned_ds.GetName())
        else:
            if options.refit:
                if options.refitall and clables[c][0] != "Di-jet":
                    rpdfs = []
                    for proc in processes:
                        for ngaus in range(1, 4):
                            pp = build_pdf(ws, "%s_%s" % (c, proc), ngaus,
                                           ngaus == 3)
                            pp.fitTo(
                                ws.data("sig_%s_mass_m%1.0f%s" %
                                        (proc, options.mH, c)),
                                RooFit.Strategy(0), *fitopt)
                        rpdfs.append(pp)
                    pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c,
                                    RooArgList(*tuple(rpdfs)))
                else:
                    if options.refitall and clables[c][0] == "Di-jet":
                        for ngaus in range(1, 5):
                            pdf = build_pdf(ws, c, ngaus, ngaus == 5)
                            pdf.fitTo(ds, RooFit.Strategy(0), *fitopt)
                    else:
                        for ngaus in range(1, 4):
                            pdf = build_pdf(ws, c, ngaus, ngaus == 3)
                            pdf.fitTo(ds, RooFit.Strategy(0), *fitopt)
            else:
                pdfs = (wspdf.pdf("hggpdfrel%s_%s" % (c, p))
                        for p in processes)
                pdf = RooAddPdf("hggpdfrel%s" % c, "hggpdfrel%s" % c,
                                RooArgList(*pdfs))
            helper.add(pdf, pdf.GetName())
            plot_pdf = pdf.Clone("pdf_%s" % dsname)

        plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset,
                              "plot")
        plot_ds.add(ds)

        cdf = pdf.createCdf(aset)
        hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10.,
                                  options.mH + 10.)
        wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10.,
                                   options.mH + 10.)
        ### hmin, hmax, hm = get_FWHM( points )

        helper.add(plot_ds, plot_ds.GetName())
        helper.add(plot_pdf, plot_pdf.GetName())
        helper.add((wmin, wmax), "eff_sigma%s" % c)
        helper.add((hmin, hmax, hm), "FWHM%s" % c)
        helper.add(ds.sumEntries(),
                   "sumEntries%s" % c)  # signal model integral

        # data integral for PAS tables
        data = ws.data("data_mass%s" % c)
        helper.add(
            data.sumEntries("CMS_hgg_mass>=%1.4f && CMS_hgg_mass<=%1.4f" %
                            (options.mH - 10., options.mH + 10.)),
            "data_sumEntries%s" % c)

        del cdf
        del pdf

    dsname = "sig_mass_m%1.0f_combcat" % options.mH
    print dsname
    combined_ds = helper.dsets[0].Clone(dsname)
    for d in helper.dsets[1:]:
        combined_ds.append(d)

    if options.binned:
        binned_ds = RooDataHist("binned_%s" % dsname, "binned_%s" % dsname,
                                aset, combined_ds)
        pdf = RooKeysPdf("pdf_%s" % (dsname), "pdf_%s" % dsname, mass,
                         combined_ds)
        plot_pdf = RooHistPdf("pdf_%s" % dsname, "pdf_%s" % dsname, aset,
                              plot_ds)
        helper.add(binned_ds, binned_ds.GetName())
    else:
        #### pdf = build_pdf(ws,"_combcat")
        #### pdf.fitTo(combined_ds, RooFit.Strategy(0), *fitopt )
        #### plot_pdf = pdf.Clone( "pdf_%s" % dsname )
        pdf = RooAddPdf(
            "pdf_%s" % dsname, "pdf_%s" % dsname,
            RooArgList(*(helper.histos["hggpdfrel%s" % c]
                         for c in categories)))
        plot_pdf = pdf

    cdf = pdf.createCdf(aset)

    plot_ds = RooDataHist("plot_%s" % dsname, "plot_%s" % dsname, aset, "plot")
    plot_ds.add(combined_ds)

    wmin, wmax = get_eff_sigma(mass, pdf, cdf, options.mH - 10.,
                               options.mH + 10.)
    hmin, hmax, hm = get_FWHM(mass, pdf, cdf, options.mH - 10.,
                              options.mH + 10.)

    helper.add(plot_ds, plot_ds.GetName())
    helper.add(plot_pdf, plot_pdf.GetName())
    helper.add((wmin, wmax), "eff_sigma_combcat")
    helper.add((hmin, hmax, hm), "FWHM_combcat")
    helper.add(plot_ds.sumEntries(), "sumEntries_combcat")

    mass.setRange("higgsrange", options.mH - 25., options.mH + 15.)

    del cdf
    del pdf
    del helper.dsets

    ### label = TLatex(0.1812081,0.8618881,"#scale[0.8]{#splitline{CMS preliminary}{Simulation}}")
    label = TLatex(0.7, 0.86,
                   "#scale[0.65]{#splitline{CMS preliminary}{Simulation}}")
    label.SetNDC(1)

    ##
    ## Make web page with plots
    ##
    if options.doWebPage:
        hth = HtmlHelper(options.outdir)
        hth.navbar().cell(HtmlTag("a")).firstChild().txt("..").set(
            "href", "../?C=M;O=D")
        hth.navbar().cell(HtmlTag("a")).firstChild().txt("home").set(
            "href", "./")

        tab = hth.body().add(HtmlTable())

    ip = 0
    for c in ["_combcat"] + categories:
        ### for c in categories:
        if options.doWebPage and ip % 4 == 0:
            row = tab.row()
        ip = ip + 1

        dsname = "sig_mass_m%1.0f%s" % (options.mH, c)
        canv = TCanvas(dsname, dsname, 600, 600)
        helper.objs.append(canv)

        ### leg = TLegend(0.4345638,0.6835664,0.9362416,0.9178322)
        leg = TLegend(0.2, 0.96, 0.5, 0.55)
        #apply_modifs( leg, [("SetLineColor",kWhite),("SetFillColor",kWhite),("SetFillStyle",0),("SetLineStyle",0)] )

        hplotcompint = mass.frame(RooFit.Bins(250), RooFit.Range("higgsrange"))
        helper.objs.append(hplotcompint)
        helper.objs.append(leg)

        plot_ds = helper.histos["plot_%s" % dsname]
        plot_pdf = helper.histos["pdf_%s" % dsname]
        wmin, wmax = helper.histos["eff_sigma%s" % c]
        hmin, hmax, hm = helper.histos["FWHM%s" % c]
        print hmin, hmax, hm

        style = (RooFit.LineColor(kBlue), RooFit.LineWidth(2),
                 RooFit.FillStyle(0))
        style_seff = (
            RooFit.LineWidth(2),
            RooFit.FillStyle(1001),
            RooFit.VLines(),
            RooFit.LineColor(15),
        )
        style_ds = (RooFit.MarkerStyle(kOpenSquare), )

        plot_ds.plotOn(hplotcompint, RooFit.Invisible())

        plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"),
                        RooFit.Range(wmin, wmax), RooFit.FillColor(19),
                        RooFit.DrawOption("F"), *style_seff)
        seffleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1))
        plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"),
                        RooFit.Range(wmin, wmax), RooFit.LineColor(15),
                        *style_seff)

        plot_pdf.plotOn(hplotcompint, RooFit.NormRange("higgsrange"),
                        RooFit.Range("higgsrange"), *style)
        pdfleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1))

        plot_ds.plotOn(hplotcompint, *style_ds)
        pointsleg = hplotcompint.getObject(int(hplotcompint.numItems() - 1))

        iob = int(hplotcompint.numItems() - 1)
        leg.AddEntry(pointsleg, "Simulation", "pe")
        leg.AddEntry(pdfleg, "Parametric model", "l")
        leg.AddEntry(seffleg,
                     "#sigma_{eff} = %1.2f GeV " % (0.5 * (wmax - wmin)), "fl")

        clabel = TLatex(0.74, 0.65,
                        "#scale[0.65]{#splitline{%s}{%s}}" % clables[c])
        clabel.SetNDC(1)
        helper.objs.append(clabel)

        hm = hplotcompint.GetMaximum() * 0.5 * 0.9
        ### hm = pdfleg.GetMaximum()*0.5
        fwhmarrow = TArrow(hmin, hm, hmax, hm)
        fwhmarrow.SetArrowSize(0.03)
        helper.objs.append(fwhmarrow)
        fwhmlabel = TPaveText(0.20, 0.58, 0.56, 0.48, "brNDC")
        fwhmlabel.SetFillStyle(0)
        fwhmlabel.SetLineColor(kWhite)
        reducedFWHM = (hmax - hmin) / 2.3548200
        fwhmlabel.AddText("FWHM/2.35 = %1.2f GeV" % reducedFWHM)
        helper.objs.append(fwhmlabel)

        hplotcompint.SetTitle("")
        hplotcompint.GetXaxis().SetNoExponent(True)
        hplotcompint.GetXaxis().SetTitle("m_{#gamma#gamma} (GeV)")
        hplotcompint.GetXaxis().SetNdivisions(509)
        ## hplotcompint.GetYaxis().SetTitle("A.U.");
        ## hplotcompint.GetYaxis().SetRangeUser(0.,hplotcompint.GetMaximum()*1.4);
        hplotcompint.Draw()
        leg.Draw("same")
        label.Draw("same")
        clabel.Draw("same")
        fwhmarrow.Draw("<>")
        fwhmlabel.Draw("same")

        plot_ds.sumEntries()

        if options.doWebPage:
            hpl = HtmlPlot(canv, False, "", True, True, True)
            hpl.caption("<i>%s</i>" % canv.GetTitle())
            row.cell(hpl)
        else:
            if os.path.isdir(options.outdir) is False:
                os.mkdir(options.outdir)
            for ext in "C", "png", "pdf":
                canv.SaveAs(
                    os.path.join(options.outdir,
                                 "%s.%s" % (canv.GetName(), ext)))

        if "comb" in c:
            ip = 0

    if options.doWebPage:
        print "Creating pages..."
        hth.dump()

    for f in helper.files:
        f.Close()
    gROOT.Reset()

    from pprint import pprint
    pprint(helper)

    print 'Summary statistics per event class'
    print 'Cat\tSignal\t\tData/GeV (in %3.1f+/-10)\tsigEff\tFWHM/2.35' % options.mH
    sigTotal = 0.
    dataTotal = 0.
    for c in categories:
        sigVal = helper.histos["sumEntries%s" % c]
        datVal = helper.histos["data_sumEntries%s" % c]
        sigTotal += sigVal
        dataTotal += datVal
    for c in categories:
        sigVal = helper.histos["sumEntries%s" % c]
        datVal = helper.histos["data_sumEntries%s" % c]
        effSig = 0.5 * (helper.histos["eff_sigma%s" % c][1] -
                        helper.histos["eff_sigma%s" % c][0])
        fwhm = (helper.histos["FWHM%s" % c][1] -
                helper.histos["FWHM%s" % c][0]) / 2.3548200
        print c, '\t%3.1f (%3.1f%%)\t%3.1f (%3.1f%%)\t\t\t%2.2f\t%2.2f' % (
            sigVal, 100. * sigVal / sigTotal, datVal /
            (10. + 10.), 100. * datVal / dataTotal, effSig, fwhm)

    print "Done."
Пример #4
0
    def Draw(self,
             histos,
             myfile,
             scales,
             ref,
             irelhisto,
             mode,
             output_path,
             preview=False):

        from ROOT import TH1
        from ROOT import TH1F
        from ROOT import THStack
        from ROOT import TLegend
        from ROOT import TPaveText  #RJ
        from ROOT import TCanvas
        from ROOT import TASImage
        from ROOT import TAttImage
        from ROOT import TPad
        from ROOT import TFile  #RJ

        # Creating a canvas
        PlotFlow.counter = PlotFlow.counter + 1
        canvas = TCanvas("tempo" + str(PlotFlow.counter), "")

        # Loop over datasets and histos
        for ind in range(0, len(histos)):
            # Scaling
            histos[ind].Scale(scales[ind])

        # Stacking or superimposing histos ?
        stackmode = False
        if ref.stack==StackingMethodType.STACK or \
           ( ref.stack==StackingMethodType.AUTO and \
             self.main.stack==StackingMethodType.STACK ):
            stackmode = True

        # Setting AUTO settings
        if len(histos) == 1:
            histos[0].SetLineColor(9)
            if stackmode:
                histos[0].SetFillColor(9)
                histos[0].SetFillStyle(3004)
        elif len(histos) == 2:
            histos[0].SetLineColor(9)
            histos[1].SetLineColor(46)
            if stackmode:
                histos[0].SetFillColor(9)
                histos[0].SetFillStyle(3004)
                histos[1].SetFillColor(46)
                histos[1].SetFillStyle(3005)
        elif len(histos) == 3:
            histos[0].SetLineColor(9)
            histos[1].SetLineColor(46)
            histos[2].SetLineColor(8)
            if stackmode:
                histos[0].SetFillColor(9)
                histos[0].SetFillStyle(3004)
                histos[1].SetFillColor(46)
                histos[1].SetFillStyle(3005)
                histos[2].SetFillColor(8)
                histos[2].SetFillStyle(3006)
        elif len(histos) == 4:
            histos[0].SetLineColor(9)
            histos[1].SetLineColor(46)
            histos[2].SetLineColor(8)
            histos[3].SetLineColor(4)
            if stackmode:
                histos[0].SetFillColor(9)
                histos[0].SetFillStyle(3004)
                histos[1].SetFillColor(46)
                histos[1].SetFillStyle(3005)
                histos[2].SetFillColor(8)
                histos[2].SetFillStyle(3006)
                histos[3].SetFillColor(4)
                histos[3].SetFillStyle(3007)
        elif len(histos) == 5:
            histos[0].SetLineColor(9)
            histos[1].SetLineColor(46)
            histos[2].SetLineColor(8)
            histos[3].SetLineColor(4)
            histos[4].SetLineColor(6)
            if stackmode:
                histos[0].SetFillColor(9)
                histos[0].SetFillStyle(3004)
                histos[1].SetFillColor(46)
                histos[1].SetFillStyle(3005)
                histos[2].SetFillColor(8)
                histos[2].SetFillStyle(3006)
                histos[3].SetFillColor(4)
                histos[3].SetFillStyle(3007)
                histos[4].SetFillColor(6)
                histos[4].SetFillStyle(3013)
        elif len(histos) == 6:
            histos[0].SetLineColor(9)
            histos[1].SetLineColor(46)
            histos[2].SetLineColor(8)
            histos[3].SetLineColor(4)
            histos[4].SetLineColor(6)
            histos[5].SetLineColor(2)
            if stackmode:
                histos[0].SetFillColor(9)
                histos[0].SetFillStyle(3004)
                histos[1].SetFillColor(46)
                histos[1].SetFillStyle(3005)
                histos[2].SetFillColor(8)
                histos[2].SetFillStyle(3006)
                histos[3].SetFillColor(4)
                histos[3].SetFillStyle(3007)
                histos[4].SetFillColor(6)
                histos[4].SetFillStyle(3013)
                histos[5].SetFillColor(2)
                histos[5].SetFillStyle(3017)
        elif len(histos) == 7:
            histos[0].SetLineColor(9)
            histos[1].SetLineColor(46)
            histos[2].SetLineColor(8)
            histos[3].SetLineColor(4)
            histos[4].SetLineColor(6)
            histos[5].SetLineColor(2)
            histos[6].SetLineColor(7)
            if stackmode:
                histos[0].SetFillColor(9)
                histos[0].SetFillStyle(3004)
                histos[1].SetFillColor(46)
                histos[1].SetFillStyle(3005)
                histos[2].SetFillColor(8)
                histos[2].SetFillStyle(3006)
                histos[3].SetFillColor(4)
                histos[3].SetFillStyle(3007)
                histos[4].SetFillColor(6)
                histos[4].SetFillStyle(3013)
                histos[5].SetFillColor(2)
                histos[5].SetFillStyle(3017)
                histos[6].SetFillColor(7)
                histos[6].SetFillStyle(3022)
        elif len(histos) == 8:
            histos[0].SetLineColor(9)
            histos[1].SetLineColor(46)
            histos[2].SetLineColor(8)
            histos[3].SetLineColor(4)
            histos[4].SetLineColor(6)
            histos[5].SetLineColor(2)
            histos[6].SetLineColor(7)
            histos[7].SetLineColor(3)
            if stackmode:
                histos[0].SetFillColor(9)
                histos[0].SetFillStyle(3004)
                histos[1].SetFillColor(46)
                histos[1].SetFillStyle(3005)
                histos[2].SetFillColor(8)
                histos[2].SetFillStyle(3006)
                histos[3].SetFillColor(4)
                histos[3].SetFillStyle(3007)
                histos[4].SetFillColor(6)
                histos[4].SetFillStyle(3013)
                histos[5].SetFillColor(2)
                histos[5].SetFillStyle(3017)
                histos[6].SetFillColor(7)
                histos[6].SetFillStyle(3022)
                histos[7].SetFillColor(3)
                histos[7].SetFillStyle(3315)
        elif len(histos) == 9:
            histos[0].SetLineColor(9)
            histos[1].SetLineColor(46)
            histos[2].SetLineColor(8)
            histos[3].SetLineColor(4)
            histos[4].SetLineColor(6)
            histos[5].SetLineColor(2)
            histos[6].SetLineColor(7)
            histos[7].SetLineColor(3)
            histos[8].SetLineColor(42)
            if stackmode:
                histos[0].SetFillColor(9)
                histos[0].SetFillStyle(3004)
                histos[1].SetFillColor(46)
                histos[1].SetFillStyle(3005)
                histos[2].SetFillColor(8)
                histos[2].SetFillStyle(3006)
                histos[3].SetFillColor(4)
                histos[3].SetFillStyle(3007)
                histos[4].SetFillColor(6)
                histos[4].SetFillStyle(3013)
                histos[5].SetFillColor(2)
                histos[5].SetFillStyle(3017)
                histos[6].SetFillColor(7)
                histos[6].SetFillStyle(3022)
                histos[7].SetFillColor(3)
                histos[7].SetFillStyle(3315)
                histos[8].SetFillColor(42)
                histos[8].SetFillStyle(3351)
        elif len(histos) == 10:
            histos[0].SetLineColor(9)
            histos[1].SetLineColor(46)
            histos[2].SetLineColor(8)
            histos[3].SetLineColor(4)
            histos[4].SetLineColor(6)
            histos[5].SetLineColor(2)
            histos[6].SetLineColor(7)
            histos[7].SetLineColor(3)
            histos[8].SetLineColor(42)
            histos[9].SetLineColor(48)
            if stackmode:
                histos[0].SetFillColor(9)
                histos[0].SetFillStyle(3004)
                histos[1].SetFillColor(46)
                histos[1].SetFillStyle(3005)
                histos[2].SetFillColor(8)
                histos[2].SetFillStyle(3006)
                histos[3].SetFillColor(4)
                histos[3].SetFillStyle(3007)
                histos[4].SetFillColor(6)
                histos[4].SetFillStyle(3013)
                histos[5].SetFillColor(2)
                histos[5].SetFillStyle(3017)
                histos[6].SetFillColor(7)
                histos[6].SetFillStyle(3022)
                histos[7].SetFillColor(3)
                histos[7].SetFillStyle(3315)
                histos[8].SetFillColor(42)
                histos[8].SetFillStyle(3351)
                histos[9].SetFillColor(48)
                histos[9].SetFillStyle(3481)
        else:
            histos[ind].SetLineColor(self.color)
            self.color += 1

        # Setting USER color
        for ind in range(0, len(histos)):

            # linecolor
            if self.main.datasets[ind].linecolor != ColorType.AUTO:
                histos[ind].SetLineColor(ColorType.convert2root( \
                self.main.datasets[ind].linecolor,\
                self.main.datasets[ind].lineshade))

            # lineStyle
            histos[ind].SetLineStyle(LineStyleType.convert2code( \
                self.main.datasets[ind].linestyle))

            # linewidth
            histos[ind].SetLineWidth(self.main.datasets[ind].linewidth)

            # background color
            if self.main.datasets[ind].backcolor != ColorType.AUTO:
                histos[ind].SetFillColor(ColorType.convert2root( \
                self.main.datasets[ind].backcolor,\
                self.main.datasets[ind].backshade))

            # background color
            if self.main.datasets[ind].backstyle != BackStyleType.AUTO:
                histos[ind].SetFillStyle(BackStyleType.convert2code( \
                self.main.datasets[ind].backstyle))

        # Creating and filling the stack; computing the total number of events
        stack = THStack("mystack", "")
        ntot = 0
        for item in histos:
            ntot += item.Integral()
            stack.Add(item)

        # Drawing
        if stackmode:
            stack.Draw()
        else:
            stack.Draw("nostack")

        # Setting Y axis label
        axis_titleY = ref.GetYaxis()

        # Scale to one ?
        scale2one = False
        if ref.stack==StackingMethodType.NORMALIZE2ONE or \
           (self.main.stack==StackingMethodType.NORMALIZE2ONE and \
           ref.stack==StackingMethodType.AUTO):
            scale2one = True

        if scale2one:
            axis_titleY += " ( scaled to one )"
        elif self.main.normalize == NormalizeType.LUMI or \
           self.main.normalize == NormalizeType.LUMI_WEIGHT:
            axis_titleY += " ( L_{int} = " + str(self.main.lumi) + " fb^{-1} )"
        elif self.main.normalize == NormalizeType.NONE:
            axis_titleY += " (not normalized)"

        if ref.titleY != "":
            axis_titleY = PlotFlow.NiceTitle(ref.titleY)

        stack.GetYaxis().SetTitle(axis_titleY)
        if (len(axis_titleY) > 35):
            stack.GetYaxis().SetTitleSize(0.04)
        else:
            stack.GetYaxis().SetTitleSize(0.06)
        stack.GetYaxis().SetTitleFont(42)
        stack.GetYaxis().SetLabelSize(0.04)

        # Setting X axis label
        if ref.titleX == "":
            axis_titleX = ref.GetXaxis()
        else:
            axis_titleX = PlotFlow.NiceTitle(ref.titleX)

        # Setting X axis label
        stack.GetXaxis().SetTitle(axis_titleX)
        stack.GetXaxis().SetTitleSize(0.06)
        stack.GetXaxis().SetTitleFont(42)
        stack.GetXaxis().SetLabelSize(0.04)

        # Setting Log scale
        if ref.logX and ntot != 0:
            canvas.SetLogx()
        if ref.logY and ntot != 0:
            canvas.SetLogy()

        #RJ
        T = TPaveText(0.1, 0.995, 0.5, 0.95, 'NDC')
        T.AddText('#bf{CMS} Simulation')
        T.SetTextFont(42)
        T.Draw("same")
        T.SetBorderSize(0)
        T.SetFillColor(0)
        T.SetFillStyle(0)
        T.SetLineColor(0)
        T.SetTextAlign(22)

        # Save all hists -- R.J. Wang
        # Loop over datasets and histos
        for ind in range(0, len(histos)):
            if not myfile.GetListOfKeys().Contains(
                    PlotFlow.NiceTitle(self.main.datasets[ind].title)):
                myfile.mkdir(PlotFlow.NiceTitle(self.main.datasets[ind].title))
            myfile.cd(PlotFlow.NiceTitle(self.main.datasets[ind].title))
            newhistosNAME = axis_titleX
            newhistosNAME = newhistosNAME.replace('(GeV/c^{2})', '')
            newhistosNAME = newhistosNAME.replace('(GeV/c)', '')
            newhistosNAME = newhistosNAME.replace(' ', '')
            newhistosNAME = newhistosNAME.replace('+', '')
            newhistosNAME = newhistosNAME.replace('-', '')
            newhistosNAME = newhistosNAME.replace('[', '')
            newhistosNAME = newhistosNAME.replace(']', '')
            newhistosNAME = newhistosNAME.replace('#it', '')
            newhistosNAME = newhistosNAME.replace('#slashET', 'MET')
            newhistosNAME = newhistosNAME.replace('(GeV)', '')
            newhistosNAME = newhistosNAME.replace('{', '')
            newhistosNAME = newhistosNAME.replace('}', '')
            newhistosNAME = newhistosNAME.replace('~', '')
            newhistosNAME = newhistosNAME.replace('_', '')
            #print newhistosNAME
            histos[ind].SetName(newhistosNAME)
            histos[ind].SetTitle(newhistosNAME)
            histos[ind].GetXaxis().SetTitle(axis_titleX)
            histos[ind].Write()

        # Displaying a legend
        if len(self.main.datasets) > 1:
            ymin_legend = .95 - .035 * len(histos)
            if ymin_legend < 0.1:
                ymin_legend = 0.1
            ymin_legend = 0.8
            legend = TLegend(.65, ymin_legend, .95, .93)
            legend.SetNColumns(3)
            #legend.SetTextSize(0.05);
            legend.SetTextFont(42)
            for ind in range(0, len(histos)):
                legend.AddEntry(
                    histos[ind],
                    PlotFlow.NiceTitle(self.main.datasets[ind].title), "L")
            legend.SetFillColor(0)
            legend.SetFillStyle(0)
            legend.SetLineColor(0)
            legend.Draw("same")

        if not preview:

            # Put the MA5 logo
            #            logo = TASImage.Open(self.main.ma5dir+\
            #                              "/madanalysis/input/logo.eps")
            #            if not logo.IsValid():
            #                logging.warning("file called '"+self.main.ma5dir+\
            #                                "/madanalysis/input/logo.eps' " +\
            #                                "is not found")
            #            else:
            #                logo.SetConstRatio(0)
            #                logo.SetImageQuality(TAttImage.kImgBest)
            #                logo.Vectorize(256)
            #                w = logo.GetWidth()
            #                h = logo.GetHeight()
            #                logo.Scale(int(w*0.2),int(h*0.2))
            #                mypad = TPad("i1", "i1", 0.75, 0.9, 0.85, 1)
            #                mypad.Draw()
            #                mypad.cd()
            #                logo.Draw()

            #            # Save the canvas in the report format
            #            canvas.Update()
            #
            #            thepicture = TASImage.Create()
            #            thepicture.FromPad(canvas)
            #            thepicture.SetConstRatio(0)
            #            thepicture.SetImageQuality(TAttImage.kImgBest)
            #            thepicture.WriteImage(output_path+"/selection_"+str(irelhisto)+\
            #                                  "."+ReportFormatType.convert2filetype(mode))
            canvas.SaveAs(output_path+"/selection_"+str(irelhisto)+\
                          "."+ReportFormatType.convert2filetype(mode))

            # Save the canvas in the C format
            canvas.SaveAs(output_path + "/selection_" + str(irelhisto) + ".C")

            # Save the canvas in the pdf format
            canvas.SaveAs(output_path + "/selection_" + str(irelhisto) +
                          ".pdf")

        else:
            # break
            answer = raw_input("Press enter to continue : ")
Пример #5
0
        pp.append(vkp)

    vprime.append([pp, binss[1]])

c1 = TCanvas()
c1.cd()
tg = TGraph()

for x in xrange(0, len(vprime)):
    mean = n.mean(vprime[x][0])
    tg.SetPoint(x, vprime[x][1],
                n.sqrt(n.var(vprime[x][0]) * (len(vprime[x][0]) - 1)))
    print str(x) + " " + str(vprime[x][1]) + " " + str(
        n.sqrt(n.var(vprime[x][0]) * (len(vprime[x][0]) - 1)))
    #tg.SetPoint(x,vprime[x][1],mean)

tg.SetLineWidth(2)
title = TPaveText(0.549569, 0.8241525, 0.950431, 0.8983051, "nbNDC")
title.SetFillColor(0)
title.SetFillStyle(0)
title.SetLineColor(0)
title.AddText("Pot. E.")

tg.GetYaxis().SetTitle("#hat{#sigma}_{jack}")
tg.GetXaxis().SetTitle("b - Bin size")
tg.GetYaxis().SetTitleOffset(1.10)
tg.GetXaxis().CenterTitle()
tg.GetYaxis().CenterTitle()

tg.Draw("AL")
Пример #6
0
eff2.SetMarkerStyle(21);

eff1.SetLineColor(kBlack);
eff2.SetLineColor(kBlack);

prob1.SetFillColor(4);
prob1.SetLineColor(4);
prob1.SetMarkerColor(4);

prob2.SetFillColor(4);
prob2.SetLineColor(4);
prob2.SetMarkerColor(4);

pt = TPaveText(51.37856,0.5654967,190.8217,0.6623778,"br")
pt.SetFillColor(0)
pt.SetLineColor(0)
pt.SetTextAlign(13)
pt.SetTextFont(42)
pt.AddText("CMS Preliminary Simulation")
pt.AddText("<PU> = 19")
pt.Draw("same")

c1 = TCanvas("vtxProbPt","vtxProbPt")
eff1.SetTitle("Vertex efficiency;p_{T}(#gamma #gamma) (GeV);Fraction | z_{reco} - z_{true} | < 10 mm")
prob1.SetTitle("Average vertex probability;p_{T}(#gamma #gamma) (GeV);Fraction | z_{reco} - z_{true} | < 10 mm")
eff1.GetYaxis().SetRangeUser(0.5, 1.1)
eff1.GetXaxis().SetTitleOffset(1.1);
eff1.GetYaxis().SetTitleOffset(1.2);

eff1.Draw("e0")
prob1.Draw("e3 same")
Пример #7
0
class Plotter(object):

    _ihist = count(0)

    def buildCanvas(self):
        can = self.can
        pad = self.pad
        padr = self.padr
        if not all([can, pad, padr]):
            can = self.can = TCanvas('can' + self.comps[0].var, '', 800,
                                     800) if not can else can
            can.Divide(1, 2, 0.0, 0.0)

            pad = self.pad = can.GetPad(1) if not pad else pad
            padr = self.padr = can.GetPad(2) if not padr else padr

            #Set Y axes Log scale
            if self.set_log_y:
                pad.SetLogy()

            # Set Pad sizes
            pad.SetPad(0.0, 0.32, 1., 1.0)
            padr.SetPad(0.0, 0.00, 1., 0.34)

            pad.SetTopMargin(0.08)
            pad.SetLeftMargin(0.16)
            pad.SetBottomMargin(0.03)
            pad.SetRightMargin(0.05)

            padr.SetBottomMargin(0.35)
            padr.SetLeftMargin(0.16)
            padr.SetRightMargin(0.05)

        can.cd()
        import locale
        locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
        can.Draw()
        pad.Draw()
        padr.Draw()

    def __init__(self, comps, lumi, channel):
        self.can = None
        self.pad = None
        self.padr = None
        self.comps = comps
        self.channel = channel
        for comp in self.comps:
            set_style(comp, self.channel)
        self.lumi = lumi

    def _project(self, comp, var, cut, *bins):
        # hist_name = '{}_{}'.format(comp.name, self._ihist.next())
        hist_name = comp.name
        hist = TH1F(hist_name, '', *bins)
        if comp.tree != None:
            comp.tree.Project(hist.GetName(), var, cut)
        print hist_name
        return hist

    def _prepare_plot(self,
                      xtitle,
                      NormalizeToBinWidth=False,
                      channel='default'):
        plot = DataMCPlot('CHANGEME', histPref[channel])
        for comp in self.comps:
            hist = comp.histogram
            hist.SetStats(0)
            plot.AddHistogram(comp.name,
                              hist,
                              NormalizeToBinWidth=NormalizeToBinWidth)
        return plot

    def draw(self,
             xtitle,
             ytitle,
             makecanvas=True,
             sys_error_hist=None,
             category=None,
             channel_str=None,
             set_log_x=False,
             set_log_y=True,
             x_range=None,
             y_range=None,
             blind=True,
             NormalizeToBinWidth=False,
             ratio_range_var=.6):
        self.plot = self._prepare_plot(xtitle,
                                       NormalizeToBinWidth=NormalizeToBinWidth,
                                       channel=self.channel)
        self.set_log_y = set_log_y
        if makecanvas:
            self.buildCanvas()
            self.pad.cd()
        self.plot.DrawStack()
        if sys_error_hist:
            self.sys_error_hist = sys_error_hist
            self.sys_error_hist.SetFillColor(15)
            self.sys_error_hist.SetFillStyle(3002)
            self.sys_error_hist.SetMarkerStyle(0)
            if NormalizeToBinWidth:
                for i in range(1, self.sys_error_hist.GetNbinsX() + 1):
                    self.sys_error_hist.SetBinContent(
                        i,
                        self.sys_error_hist.GetBinContent(i) /
                        self.sys_error_hist.GetBinWidth(i))
                    self.sys_error_hist.SetBinError(
                        i,
                        self.sys_error_hist.GetBinError(i) /
                        self.sys_error_hist.GetBinWidth(i))
            self.sys_error_hist.Draw('e2 same')

        Xaxis = self.plot.supportHist.GetXaxis()
        Yaxis = self.plot.supportHist.GetYaxis()

        if xtitle == 'mt_tot':
            xtitle = 'm_{#rm T}^{#rm tot} #text{ (GeV)}'

        Xaxis.SetTitle(xtitle)
        Yaxis.SetTitle(ytitle)

        if category and not channel_str:
            _string = category
        elif category and channel_str:
            _string = '{} # #rm {} '.format(channel_str, category)
        elif channel_str and not category:
            _string = channel_str
        else:
            _string = None

        if _string:
            self.category = TPaveText(.15, .93, .40, .98, "NDC")
            self.category.SetFillColor(0)
            self.category.SetFillStyle(0)
            self.category.SetLineColor(0)
            self.category.AddText(_string)
            self.category.Draw("same")

        self.lumibox = TPaveText(.80, .93, .95, .98, "NDC")
        self.lumibox.SetFillColor(0)
        self.lumibox.SetFillStyle(0)
        self.lumibox.SetLineColor(0)
        self.lumibox.AddText("#SI{41.5}{fb^{-1}}")
        self.lumibox.Draw("same")

        if xtitle == 'm_{#rm T}^{#rm tot} #text{ (GeV)}':
            if x_range is None:
                Xaxis.SetRangeUser(0, 900)
            ymax = max(
                self.plot.supportHist.weighted.GetBinContent(
                    self.plot.supportHist.weighted.GetMaximumBin()),
                self.plot.BGHist().weighted.GetBinContent(
                    self.plot.BGHist().weighted.GetMaximumBin()))
            Yaxis.SetRangeUser(0.0001, ymax * 1.3)
            if blind:
                self.plot.Blind(130, 4000, False)
        else:
            ymax = max(
                self.plot.supportHist.weighted.GetBinContent(
                    self.plot.supportHist.weighted.GetMaximumBin()),
                self.plot.BGHist().weighted.GetBinContent(
                    self.plot.BGHist().weighted.GetMaximumBin()))
            Yaxis.SetRangeUser(0.01, ymax * 1000)

        if x_range is not None:
            Xaxis.SetRangeUser(x_range[0], x_range[1])

        if y_range is not None:
            Yaxis.SetRangeUser(y_range[0], y_range[1])

        if makecanvas:
            self.padr.cd()
        self.ratioplot = copy.deepcopy(self.plot)
        self.ratioplot.DrawDataOverMCMinus1(-ratio_range_var, ratio_range_var)
        if sys_error_hist:
            self.sys_error_hist_rel = copy.copy(self.sys_error_hist)
            for b in range(self.sys_error_hist.GetNbinsX()):
                self.sys_error_hist_rel.SetBinContent(b + 1, 1)
                if abs(self.sys_error_hist.GetBinContent(
                        b + 1)) < 1e-4 and abs(
                            self.sys_error_hist.GetBinError(b + 1)) < 1e-4:
                    rel_bin_error = 1  # really?
                else:
                    rel_bin_error = self.sys_error_hist.GetBinError(
                        b + 1) / self.sys_error_hist.GetBinContent(b + 1)
                self.sys_error_hist_rel.SetBinError(b + 1, rel_bin_error)
            self.sys_error_hist_rel.Draw('e2 same')
        ratioXaxis = self.ratioplot.dataOverMCHist.GetXaxis()
        ratioYaxis = self.ratioplot.dataOverMCHist.GetYaxis()
        ratioXaxis.SetTitleSize(0.12)
        ratioYaxis.SetTitleSize(0.08)
        ratioYaxis.SetTitleOffset(0.5)
        ratioXaxis.SetLabelSize(0.08)
        ratioYaxis.SetLabelSize(0.08)
        Xaxis.SetLabelColor(0)
        Xaxis.SetLabelSize(0)

        ratioXaxis.SetMoreLogLabels()
        ratioXaxis.SetNoExponent()

        if set_log_x:
            self.pad.SetLogx()
            self.padr.SetLogx()

        if makecanvas:
            self.padr.Update()
            self.can.cd()
            gPad.Update()

    def write(self, fname):
        self.can.SaveAs(fname)
        if '.tex' in fname:
            import os
            os.system("sed -i 's|mark=|mark=*|g' " + fname)
            os.system("sed -i 's|pattern=dots|pattern=crosshatch dots|g' " +
                      fname)

    def print_info(self, detector, xmin=None, ymin=None):
        lumitext = ''
        lumi = self.lumi
        if lumi > 1e18:
            lumi = int(self.lumi / 1e18 * 10.) / 10.
            lumitext = '{lumi} ab^{{-1}}'.format(lumi=lumi)
        elif lumi > 1e15:
            lumi = int(self.lumi / 1e15 * 10.) / 10.
            lumitext = '{lumi} fb^{{-1}}'.format(lumi=lumi)
        elif lumi > 1e12:
            lumi = int(self.lumi / 1e12 * 10.) / 10.
            lumitext = '{lumi} pb^{{-1}}'.format(lumi=lumi)
        if not xmin:
            xmin = 0.62
        if not ymin:
            ymin = 0.8
        xmax, ymax = xmin + 0.288, ymin + 0.12
        self.pave = TPaveText(xmin, ymin, xmax, ymax, 'ndc')
        self.pave.AddText(detector)
        self.pave.AddText(lumitext)
        self.pave.SetTextSizePixels(28)
        self.pave.SetTextAlign(11)
        self.pave.SetBorderSize(0)
        self.pave.SetFillColor(0)
        self.pave.SetFillStyle(0)
        self.pave.Draw()