예제 #1
0
파일: graphUtils.py 프로젝트: namcneal/QY
    def drawGraph(self,g,figDir="",SetLogx=False,SetLogy=False,option='APL'):
        '''
        output graph to file
        '''
        title = g.GetTitle()
        name  = g.GetName()
        if SetLogx: name += '_logx'
        if SetLogy: name += '_logy'

        pdf   = os.path.join( figDir,  name + '.pdf')
    
        xsize,ysize = 1100,850 # landscape style
        noPopUp = True
        if noPopUp : gROOT.ProcessLine("gROOT->SetBatch()")
        canvas = TCanvas(pdf,title,xsize,ysize)

        
        g.Draw(option)

        if SetLogy: canvas.SetLogy(1)
        if SetLogx: canvas.SetLogx(1)
    
        canvas.Draw()
        canvas.SetGrid(1)
        canvas.SetTicks(1)
        canvas.cd()
        canvas.Modified()
        canvas.Update()
        canvas.Print(pdf,'pdf')
        return
예제 #2
0
def main():
    # print "reade ntuple for file ", sys.arg[1]
    # print "read geometry from file ", sys.argv[2]
    # ntuple = HGCalNtuple(sys.argv[1])
    # planes = GeoUtils.read_planes(sys.argv[2])

    # for plane in planes:
    #  print_geo(ntuple, plane)
    print "read geometry from file: ", "fullgeometry_.txt"

    print "reading planes"
    planes = GeoUtils.read_planes("fullgeometry_.txt")

    c = TCanvas()

    mg = TMultiGraph()

    cells = planes[0].cells

    for cell in cells:
        x = array("d", cell.coordinates.vertices[:, 0])
        x.append(x[0])

        y = array("d", cell.coordinates.vertices[:, 1])
        y.append(y[0])

        gi = TGraph(len(x), x, y)
        gi.SetMarkerStyle(1)

        mg.Add(gi, "AL")

    # mg.Draw("AL")
    mg.Draw("A")
    c.Draw()
    c.SaveAs("hex0.png")
예제 #3
0
def drawTopoGeometry(geometry, is2016):

    outfn = "TopoLayout%s.pdf" % ("2016" if is2016 else "2015")

    global box, c, h, leg

    gROOT.Reset()
    gStyle.SetOptStat(0)

    c = TCanvas('c', "MuCTPi to Topo Geometry", 1400, 950)
    c.Draw()

    h = TH2F("h", "Muon Topo Geometry %s" % "2016" if is2016 else "2015", 10,
             -2.6, 2.6, 10, -0.15, 6.4)
    h.SetXTitle("#eta")
    h.SetYTitle("#phi")
    h.Draw()

    box = TBox()
    box.SetFillStyle(0)
    box.SetLineColor(3)

    circle = TArc()

    for colorIndex, MioctID in enumerate(drawOrder):
        MIOCT = geometry.getMIOCT(MioctID)
        color = colorMap[colorIndex % len(colorMap)]
        box.SetLineColor(color)
        box.SetFillColor(color)

        circle.SetLineColor(color)
        circle.SetFillColor(color)

        fillStyle = 3004
        for cellIdx, TopoCell in enumerate(MIOCT.Decode.TopoCells):
            # corner 1
            c1_x = float(TopoCell["etamin"])
            c1_y = float(TopoCell["phimin"])
            # corner 2
            c2_x = float(TopoCell["etamax"])
            c2_y = float(TopoCell["phimax"])
            # center rounded
            c_x = float(TopoCell["ieta"])
            c_y = float(TopoCell["iphi"])

            #print "cell %i : eta [%f - %f], phi [%f - %f]" % (cellIdx, c1_x, c2_x, c1_y, c2_y)

            if fillStyle == 3004:
                fillStyle = 3012
            else:
                fillStyle = 3004
            box.SetFillStyle(fillStyle)
            box.DrawBox(c1_x, c1_y, c2_x, c2_y)
            box.SetFillStyle(0)
            box.DrawBox(c1_x, c1_y, c2_x, c2_y)

            circle.DrawArc(c_x / 10., c_y / 10., 0.02)

    c.Update()
    c.SaveAs(outfn)
예제 #4
0
def plotnorm(h1, h2, h3, fname, particle, swap=False):
    leg = TLegend(0.15, 0.65, 0.50, 0.92, "", "brNDC")
    leg.SetFillStyle(4000)
    # will be transparent
    leg.SetFillColor(0)
    leg.SetTextFont(42)
    leg.SetBorderSize(0)
    leg.AddEntry(0, "MadGraph+Pythia8", "")
    leg.AddEntry(0, "#it{gg}#rightarrow#it{t}#bar{#it{t}} (500k events)", "")
    leg.AddEntry(0, "Truth level for now", "")
    leg.AddEntry(h1, "|SM|^{2}", "ple")
    leg.AddEntry(h2, "|#it{" + particle + "}|^{2} reweighted", "ple")
    leg.AddEntry(h3, "|#it{" + particle + "}|^{2} generated", "ple")
    leg.AddEntry(0, "#it{m}_{#it{" + particle + "}} = 500 GeV", "")
    # leg.AddEntry(0, "in |#it{m}_{#it{t#bar{t}}}-#it{m}_{#it{"+particle+"}}|<100 GeV", "");

    cnv = TCanvas("cnv", "", 600, 600)
    cnv.Draw()
    cnv.SetTicks(1, 1)
    h1.GetYaxis().SetTitle("Norm.")
    h2.GetYaxis().SetTitle("Norm.")
    h3.GetYaxis().SetTitle("Norm.")
    if (swap):
        h2.DrawNormalized()
        h1.DrawNormalized("same")
    else:
        h1.DrawNormalized()
        h2.DrawNormalized("same")
    h3.DrawNormalized("same")
    leg.Draw("same")

    cnv.Update()
    cnv.RedrawAxis()
    cnv.SaveAs(fname)
예제 #5
0
def draw_nice_canvas(name,
                     x=800,
                     y=800,
                     logx=False,
                     logy=False,
                     logz=True,
                     title=None,
                     replace=True):
    global nice_canvases
    if not replace and name in nice_canvases:
        c = nice_canvases[name]
        c.cd()
        if title is not None:
            c.SetTitle(title)
        return c
    if title is None:
        title = name
    c = TCanvas(name, title, x, y)
    c.SetLogx(logx)
    c.SetLogy(logy)
    c.SetLogz(logz)
    c.SetTicky()
    c.SetTickx()
    c.SetLeftMargin(0.15)
    c.SetBottomMargin(0.15)
    c.SetRightMargin(0.05)
    c.SetTopMargin(0.05)
    c.Draw()
    nice_canvases[name] = c
    return c
예제 #6
0
def drawCodeValues(geometry, is2016):

    global h, c

    gROOT.Reset()
    gStyle.SetOptStat(0)

    c = TCanvas('c', "Topo encoding", 1400, 950)
    c.Draw()

    h = TH2F("h", "Muon Topo encoding %i" % (2016 if is2016 else 2015), 8, 0,
             8, 8, 0, 8)
    h.SetXTitle("#eta")
    h.SetYTitle("#phi")
    h.Draw()

    for MioctID in drawOrder:
        #for MioctID in [3,4,5,6,7]:
        MIOCT = geometry.getMIOCT(MioctID)
        for tc in MIOCT.Decode.TopoCells:
            h.Fill(int(tc['etacode'], 16), int(tc['phicode'], 16))

    h.Draw("colz")
    c.Update()
    c.SaveAs("TopoCodes%s.pdf" % "2016" if is2016 else "2015")
예제 #7
0
def draw_canvas_histo(nchannels, xmin, xmax, title, cat_names):
    c = TCanvas("c", "Canvas", 800, 600)
    c.Draw()

    h = TH2F("h", "", 10, xmin, xmax, nchannels, -1, nchannels - 1)
    h.Draw()
    h.SetStats(0)
    h.SetXTitle(title)

    yaxis = h.GetYaxis()
    yaxis.SetLabelSize(fontsize)

    for ibin in range(0, nchannels):
        yaxis.SetBinLabel(nchannels - ibin, cat_names[ibin])

    t = TLatex()
    t.SetNDC()
    t.SetTextFont(42)
    t.SetTextSize(fontsize)
    t.SetTextAlign(11)
    t.DrawLatex(
        0.40, 0.91, "                                          " + lumi +
        " fb^{-1}, #sqrt{s} = 13 TeV")

    return c, h
예제 #8
0
파일: graphUtils.py 프로젝트: namcneal/QY
    def drawFit(self,h,figdir='',SetLogy=False,SetLogx=False,extraName=None):
        '''
        draw histogram with fit parameters
        '''
        name = h.GetName()
        if extraName is not None: name += '_' + extraName
        title = h.GetTitle()
        if SetLogx: name += '_logx'
        if SetLogy: name += '_logy'
        pdf = os.path.join( figdir ,  name + '.pdf' )
        ps  = os.path.join( figdir , name + '.ps' )
        xsize,ysize = 1100,850 # landscape style
        noPopUp = True
        if noPopUp : gROOT.ProcessLine("gROOT->SetBatch()")
        canvas = TCanvas(pdf,title,xsize,ysize)
        
        gStyle.SetOptFit(1111)
        h.Draw()
        if SetLogy: canvas.SetLogy(1)
        if SetLogx: canvas.SetLogx(1)
        
        canvas.Draw()
        canvas.SetGrid(1)
        canvas.SetTicks(1)
        canvas.cd()
        canvas.Modified()
        canvas.Update()
        
        canvas.Print(ps,'Landscape')
        os.system('ps2pdf ' + ps + ' ' + pdf)
        if os.path.exists(pdf): os.system('rm ' + ps)

        return
예제 #9
0
def foo():
    c = TCanvas()
    c.Divide(2, 2, 0, 0)
    c.SetCanvasSize(1000, 800)

    leg = TLegend(.65, .90, 1, 1)
    leg.SetHeader("Centrality", "C")
    leg.SetNColumns(3)
    leg.SetTextSize(0.03)

    for i, key in enumerate(('Ro', 'Rs', 'Rl', 'RoRs'), 1):
        pad = c.cd(i)
        #     pad.SetTopMargin(0)
        #     pad.SetBottomMargin(0)
        #     pad.SetLeftMargin(0.17)
        if i == 4 or i == 3:
            pad.SetBottomMargin(0.18)
    #     if i in (1, 3):
        pad.SetLeftMargin(0.17)
        #     elif i == 1:
        #         pad.SetTopMargin(0.0)

        if i == 3:
            yrange = 0.1, 9.5
        elif i == 4:
            yrange = 0.7, 1.3
        else:
            yrange = 0.1, 7.9

        for g, graph in enumerate(kisiel_graphs[key]):
            graph.GetXaxis().SetRangeUser(0.0, 1.0)
            if g == 0:
                graph.GetYaxis().SetRangeUser(*yrange)
                graph.GetYaxis().SetTitleSize(.07)
                graph.GetYaxis().SetTitleOffset(0.69)
                graph.GetYaxis().CenterTitle()
                if i == 4:
                    graph.GetYaxis().SetNdivisions(404)
                elif i == 3:
                    graph.GetYaxis().SetNdivisions(405)
                if i == 4:
                    graph.GetXaxis().SetTitleSize(0.07)
                    graph.GetXaxis().SetLabelSize(0.07)
    #                 graph.Set

                graph.Draw('AP')
            else:
                graph.Draw('SAME P')

            if i == 1:
                leg.AddEntry(graph, cent_names[g], 'P')

        for g, graph in enumerate(kubera_graphs[key]):
            graph.Draw('P')

    c.cd(0)
    leg.Draw()
    c.Draw()
예제 #10
0
def draw(pattern):
    '''Draw all histograms with a key matching pattern in separate canvases'''
    for hist in hists:
        name = hist.GetName()
        if fnmatch.fnmatch(name, pattern):
            can = TCanvas(name, name, cx, cy)
            canvases.append(can)
            can.Draw()
            hist.Draw()
예제 #11
0
def plot2d(h,
           nsmooth,
           fname,
           drawopt,
           nameX,
           mX,
           hR=0,
           minz=+1.e11,
           maxz=-1.e11,
           phi=-50,
           theta=25,
           dologx=False,
           dology=True,
           dologz=False):
    for i in range(0, nsmooth):
        h.Smooth()
    c = TCanvas("c" + h.GetName(), "c" + h.GetName(), 1000, 600)
    c.cd()
    c.Draw()
    c.SetTopMargin(0.1)

    if (dologx): c.SetLogx()
    if (dology): c.SetLogy()
    if (dologz): c.SetLogz()

    if (minz < +1.e10): h.SetMinimum(minz)
    if (maxz > -1.e10): h.SetMaximum(maxz)

    if (hR):
        h.Divide(hR)
        h.Scale(100)
        h.GetZaxis().SetTitle("(SM+#it{" + nameX + "})/SM-1 [%]")
        h.GetZaxis().SetTitleOffset(-0.1)

    # h.GetYaxis().SetLimits(0.,10.)
    # ymin = 0.
    # ymax = 10.
    # nPrimitiveBins = 10
    # nBins = nPrimitiveBins*int(ymax-ymin)
    # h.GetYaxis().Set(nBins,ymin,ymax)

    # h.GetYaxis().SetNdivisions((Int_t)(10.*16),kFALSE)
    # h.RebinY(5)

    h.SetTitleOffset(0.5)
    if (("SURF" in drawopt) or ("LEGO" in drawopt)):
        c.SetPhi(phi)
        c.SetTheta(theta)
        h.GetZaxis().SetTitleOffset(1.10)
        h.GetXaxis().SetTitleOffset(1.60)
        h.GetYaxis().SetTitleOffset(1.30)
    h.Draw(drawopt)
    c.Modified()
    c.Update()
    c.SaveAs(fname)
    c.SaveAs(fname.replace(".pdf", ".root"))
예제 #12
0
def drawAppMVAOutputPlots(region, method, isMC):

    MCstr = ""
    if isMC:
        MCstr = "BsMC12"
    Region = region[:1].upper() + region[
        1:]  #capitalize first letter for retrieving file names
    HistName = "ApplicationOutput" + MCstr + Region + method
    CvsName = "canvasMVA_" + MCstr + method + region
    canvas = TCanvas(CvsName, CvsName)
    stackBDT = THStack(HistName, HistName)
    histos = []
    appFiles = []
    canvas.Draw()

    # note: TMVApp file name structure: "TMVApp"+Region+method+sample+".root"
    #                             "BsMC12TMVApp"+Region+method+sample+".root"
    appFile = TFile(MCstr + "TMVApp" + Region + method + ".root")
    histo = appFile.Get("MVA_" + method).Clone(HistName)
    histo.Scale(1 / histo.GetEntries())
    stackBDT.Add(histo)

    for sample in range(3):
        appFiles.append(
            TFile(MCstr + "TMVApp" + Region + method + str(sample) + ".root"))
        histos.append(appFiles[sample].Get("MVA_" + method).Clone("HistName" +
                                                                  str(sample)))
        histos[sample].SetLineColor(2 * sample)
        histos[sample].Scale(1 / histos[sample].GetEntries())
        stackBDT.Add(histos[sample])

    stackBDT.Draw("nostack")
    if isMC:
        applicationBDTLegend = TLegend(0.2, 0.7, 0.5, 0.9, "", "brNDC")
        #applicationBDTLegend.SetHeader("Bs MC "+region.split("BsMC")[1])
        applicationBDTLegend.SetHeader("Bs MC " + Region)
    else:
        applicationBDTLegend = TLegend(0.55, 0.7, 0.85, 0.9, "", "brNDC")
        applicationBDTLegend.SetHeader(Region)

    applicationBDTLegend.AddEntry(histo, "Full sample", "l")
    applicationBDTLegend.AddEntry(histos[0],
                                  "Trained on 0, tested on 1, applied on 2",
                                  "l")
    applicationBDTLegend.AddEntry(histos[1],
                                  "Trained on 1, tested on 2, applied on 0",
                                  "l")
    applicationBDTLegend.AddEntry(histos[2],
                                  "Trained on 2, tested on 0, applied on 1",
                                  "l")
    applicationBDTLegend.Draw("same")
    applicationBDTLegend.SetFillColor(0)
    applicationBDTLegend.SetLineColor(0)
    canvas.SaveAs(figuresDir + "Application" + method + "Output_" + MCstr +
                  region + ".pdf")
예제 #13
0
    def plotNSamples(cls, npatterns, etBins, etaBins, outname='nPatterns.pdf'):
        """Plot number of samples per bin"""
        logger = Logger.getModuleLogger("PlotNSamples")
        from ROOT import TCanvas, gROOT, kTRUE, kFALSE, TH2I, TText
        gROOT.SetBatch(kTRUE)
        c1 = TCanvas("plot_patterns_signal", "a", 0, 0, 800, 400)
        c1.Draw()
        shape = [len(etBins) - 1, len(etaBins) - 1]
        histo1 = TH2I(
            "text_stats",
            "#color[4]{Signal}/#color[2]{Background} available statistics",
            shape[0], 0, shape[0], shape[1], 0, shape[1])
        #histo1 = TH2I("text_stats", "Signal/Background available statistics", shape[0], 0, shape[0], shape[1], 0, shape[1])
        histo1.SetStats(kFALSE)
        histo1.Draw("TEXT")
        histo1.SetXTitle("E_{T}")
        histo1.SetYTitle("#eta")
        histo1.GetXaxis().SetTitleSize(0.04)
        histo1.GetYaxis().SetTitleSize(0.04)
        histo1.GetXaxis().SetLabelSize(0.04)
        histo1.GetYaxis().SetLabelSize(0.04)
        histo1.GetXaxis().SetTickSize(0)
        histo1.GetYaxis().SetTickSize(0)
        ttest = TText()
        ttest.SetTextAlign(22)
        for etBin in range(shape[0]):
            for etaBin in range(shape[1]):
                key = 'et%d_eta%d' % (etBin, etaBin)
                ttest.SetTextColor(4)
                ttest.DrawText(.5 + etBin, .75 + etaBin,
                               's: ' + str(npatterns['sgnPattern_' + key]))

                ttest.SetTextColor(2)
                ttest.DrawText(.5 + etBin, .25 + etaBin,
                               'b: ' + str(npatterns['bkgPattern_' + key]))

                try:
                    histo1.GetYaxis().SetBinLabel(
                        etaBin + 1, '#bf{%d} : %.2f->%.2f' %
                        (etaBin, etaBins[etaBin], etaBins[etaBin + 1]))
                except Exception:
                    logger.error("Couldn't retrieve eta bin %d bounderies.",
                                 etaBin)
                    histo1.GetYaxis().SetBinLabel(etaBin + 1, str(etaBin))
                try:
                    histo1.GetXaxis().SetBinLabel(
                        etBin + 1, '#bf{%d} : %d->%d [GeV]' %
                        (etBin, etBins[etBin], etBins[etBin + 1]))
                except Exception:
                    logger.error("Couldn't retrieve et bin %d bounderies.",
                                 etBin)
                    histo1.GetXaxis().SetBinLabel(etBin + 1, str(etaBin))
        c1.SetGrid()
        c1.Update()
        c1.SaveAs(outname)
예제 #14
0
    def compareGraphs(self, name, gCompare):
        '''
        Create pdf file that compares graphs created from same raw data
        Plot raw data(points+line) and either points or lines as defined by dict gCompare
        Two panels are created.
        Top panel shows full ordinate range.
        Lower panel concentrates on baseline.
        '''
        graw = self.findGraph(name)
        title = 'Comparison' + graw.GetTitle()
        purename = name.replace('raw', '')
        pdf = self.figDir + 'compare_' + purename + '.pdf'

        xsize, ysize = 1100, 850
        noPopUp = True
        if noPopUp: gROOT.ProcessLine("gROOT->SetBatch()")
        canvas = TCanvas(pdf, title, xsize, ysize)
        canvas.Divide(1, 2)
        x, y = self.getGraphContent(graw)
        xmi, xma = min(x), max(x)
        #print 'compareGraphs:graw.GetName(),x[0],x[1],x[-1],len(x),y[0],y[1],y[-1],len(y)',graw.GetName(),x[0],x[1],x[-1],len(x),y[0],y[1],y[-1],len(y)
        abit = (xma - xmi) / 40.
        xmi -= abit
        xma += abit
        ymi, yma = 1.e20, -1.e20
        options = {1: "ALP", 2: "LP"}
        for i in [1, 2]:

            canvas.cd(i)
            if ymi < yma:
                abit = (yma - ymi)
                yma += abit
                ymi -= abit / 10.
                #print 'compareGraphs: graw',graw.GetName(),'xmi,xma,ymi,yma',xmi,xma,ymi,yma
                canvas.DrawFrame(xmi, ymi, xma, yma)
            graw.Draw(options[i])
            for g in gCompare:
                g.Draw(gCompare[g])
                x, y = self.getGraphContent(g)
                ylo = min(y)
                yhi = max(y)
                if ylo < ymi: ymi = ylo
                if yma < yhi: yma = yhi

            canvas.Draw()
            canvas.SetGrid(1)
            canvas.SetTicks(1)
            canvas.cd()
            canvas.Modified()
            canvas.Update()
        canvas.Print(pdf, 'pdf')

        return
 def displayWeights(self, bins, weights):
     gWeights = TGraph(len(bins), bins, weights)
     c1 = TCanvas("c1", "c1", 1000, 750)
     gWeights.GetXaxis().SetTitle("PileUp")
     gWeights.GetYaxis().SetTitle("Weight")
     gWeights.SetLineWidth(2)
     gWeights.SetMarkerColor(kBlue)
     gWeights.SetMarkerSize(1.0)
     gWeights.SetMarkerStyle(22)
     gWeights.Draw("AP")
     c1.Draw()
     raw_input()
    def getWeights(self, MCtree, year):
        fData = TFile('data_pileup_{0:d}.root'.format(year))
        hData = fData.Get('pileup')
        print("hData={0:s}".format(str(hData)))
        binWidth = hData.GetBinWidth(1)
        xMin = hData.GetBinLowEdge(1)
        nBins = hData.GetNbinsX()
        xMax = xMin + nBins * binWidth
        bins = np.linspace(xMin + 0.5 * binWidth, xMax - 0.5 * binWidth, nBins)
        print("nBins={0:d} binWidth={1:f} xMin={2:f} xMax={3:f}".format(
            nBins, binWidth, xMin, xMax))
        hMC = TH1D("hMC", "hMC", nBins, xMin, xMax)
        nentries = MCtree.GetEntries()
        print("Number of entries in MCtree={0:d}".format(nentries))
        print("Entering pileup loop")
        import time
        tStart = time.time()
        for i, e in enumerate(MCtree):
            hMC.Fill(e.Pileup_nPU)
            #if i > 10000 : break
        print("After pileup loop:  time={0:.1f}".format(time.time() - tStart))

        nData = hData.GetSumOfWeights()
        pData = np.array(hData)[1:-1] / nData
        print("sum of pData={0:f}".format(np.sum(pData)))
        nMC = hMC.GetSumOfWeights()
        pMC = np.array(hMC)[1:-1]
        pMC /= nMC
        pMC = np.maximum(1.e-5 * np.ones_like(pMC), pMC)
        print("sum of pMC={0:f}".format(np.sum(pMC)))
        weights = np.divide(pData, pMC)

        if False:
            gData = TGraph(len(bins), bins, pData)
            gData.GetXaxis().SetTitle("PileUp")
            gData.SetMarkerColor(kRed)
            gData.SetMarkerSize(1.0)
            gData.SetMarkerStyle(21)
            gMC = TGraph(len(bins), bins, pMC)
            c1 = TCanvas("c1", "c1", 1000, 750)
            gData.Draw('AP')
            gMC.SetMarkerColor(kBlue)
            gMC.SetMarkerSize(1.0)
            gMC.SetMarkerStyle(22)
            gMC.Draw('P')
            legend = TLegend(0.6, 0.8, 0.80, 0.90)
            legend.AddEntry(gData, "Data")
            legend.AddEntry(gMC, "MC")
            legend.Draw()
            c1.Draw()
            raw_input()

        return bins, weights
예제 #17
0
def export(info, args, npull=15):
    from ROOT import TFile, gROOT, gStyle, TPad, TCanvas
    from math import ceil
    gROOT.SetStyle("Plain")
    gStyle.SetOptFit(1)
    gStyle.SetOptStat(0)
    gROOT.SetBatch(1)

    # outdir = outdir_base % info.year
    # outvar = '%s/%s/' % (outdir,info.variable)
    # if not os.path.isdir(outvar): os.mkdir(outvar)
    # outsys = '%s/%s' % (outvar,info.sysdir)
    # if not os.path.isdir(outsys): os.mkdir(outsys)

    # outname = 'pulls_%s.pdf' % info.variable
    # output = '%s/%s' % (outsys,outname)
    output = "pulls.pdf"
    pulls = TFile.Open(args.g)
    canvas = pulls.Get("nuisances")
    objlist = canvas.GetListOfPrimitives()
    prefit = objlist.At(0).Clone()
    fit_bg = objlist.At(2).Clone()
    fit_bs = objlist.At(3).Clone()
    legend = objlist.At(6).Clone()

    prefit.GetYaxis().SetRangeUser(-4, 4)

    legend.SetX1(0.76)
    legend.SetX2(0.99)

    npages = int(ceil(float(prefit.GetNbinsX()) / npull))
    for page in range(npages):
        canvas = TCanvas()
        canvas.SetBottomMargin(0.15)
        canvas.SetRightMargin(0.25)
        canvas.SetGridx()
        canvas.Draw()
        xlo = page * npull + 1
        xhi = page * npull + npull
        if xhi > prefit.GetNbinsX(): xhi = prefit.GetNbinsX()
        prefit.GetXaxis().SetRange(xlo, xhi)

        prefit.Draw("E2")
        prefit.Draw("histsame")
        fit_bg.Draw("EPsame")
        fit_bs.Draw("EPsame")
        legend.Draw()

        if page == 0: canvas.SaveAs(output + "(")
        elif page + 1 == npages: canvas.SaveAs(output + ")")
        else: canvas.SaveAs(output)
예제 #18
0
 def buildCanvas(self):
     can = TCanvas('can_{num}'.format(num=self.__class__.CAN_NUM),
                   self.name, 600, 600)
     self.__class__.CAN_NUM += 1
     can.cd()
     can.Draw()
     sep = 0.35
     pad = TPad('pad', '', 0.01, sep, 0.99, 0.99)
     pad.SetBottomMargin(0.04)
     padr = TPad('padr', '', 0.01, 0.01, 0.99, sep + 0.02)
     padr.SetTopMargin(0.04)
     padr.SetBottomMargin(0.3)
     padr.SetGridy()
     return can, pad, padr
예제 #19
0
def buildCanvas():
    global can, pad, padr
    can = TCanvas('can','',800,800)
    can.cd()
    can.Draw()
    sep = 0.35
    pad = TPad('pad','',0.01,sep,0.99, 0.99)
    pad.SetBottomMargin(0.04)
    padr = TPad('padr','',0.01, 0.01, 0.99, sep)
    padr.SetTopMargin(0.04)
    padr.SetBottomMargin(0.3)
    pad.Draw()
    padr.Draw()
    return can, pad, padr
예제 #20
0
 def DrawGraphs(self, options=None):
     for hist in self.graphs:
         name = hist.GetName()
         canvas = TCanvas(name, name)
         canvas.Draw()
         if hist.GetLogY(): gPad.SetLogy(1)
         if options: hist.SetOption(options)
         hist.Draw()
         for ext in self.GetExtensions():
             canvas.SaveAs("%s/%s%s" %
                           (self.GetOutputDir(), canvas.GetTitle(), ext))
         canvas.Write()
         canvas.Clear()
         canvas.Close()
     return
예제 #21
0
 def Draw(self, option_=None):
     name = self.hist.GetName()
     canvas = TCanvas(name, name)
     canvas.Draw()
     if self.hist.GetLogY(): gPad.SetLogy(1)
     if option_: option = option_
     else: option = self.options
     self.h().Draw(option)
     self.h().SetTitle("")
     self.h().GetXaxis().SetTitle(self.GetXaxis())
     self.h().GetYaxis().SetTitle(self.GetYaxis())
     if self.hist.GetLegend():
         self.hist.GetLegend().Draw()
     for ext in self.hist.GetExtensions():
         canvas.SaveAs("%s/%s%s" %
                       (self.hist.GetOutputDir(), canvas.GetTitle(), ext))
     canvas.Write()
     canvas.Clear()
     canvas.Close()
예제 #22
0
def plotWidth(dwdictX, fname, nameX, mX, cuts):
    sorted_dwdictX = SortedDict(dwdictX)
    n = len(sorted_dwdictX) - 1
    x = array('d', sorted_dwdictX.keys())
    y = array('d', sorted_dwdictX.values())
    gwX = TGraph(n, x, y)
    gwX.SetName("gwX")
    gwX.SetTitle("")
    gwX.GetXaxis().SetTitle("tan#beta")
    gwX.GetYaxis().SetTitle("#Gamma_{#it{" + nameX + "}}/#it{m}_{#it{" +
                            nameX + "}} [%]")
    gwX.SetLineColor(ROOT.kBlack)
    gwX.SetMarkerColor(ROOT.kBlack)
    gwX.SetMarkerStyle(20)
    gwX.SetMarkerSize(0.5)

    ptxt = TPaveText(0.62, 0.70, 0.87, 0.87, "NDC")
    ptxt.SetFillStyle(4000)  #will be transparent
    ptxt.SetFillColor(0)
    ptxt.SetTextFont(42)
    ptxt.SetBorderSize(0)
    ptxt.AddText("sin(#beta-#alpha)=1")
    ptxt.AddText("#it{m}_{#it{" + nameX + "}}=" + str(mX) + " GeV")

    c = TCanvas("c", "c", 600, 600)
    c.cd()
    c.SetLogx()
    c.SetLogy()
    c.SetGridx()
    c.SetGridy()
    c.SetTicks(1, 1)
    c.Draw()
    # gwX.Draw("p")
    gwX.Draw()
    ptxt.Draw("same")
    c.Modified()
    c.Update()
    c.SaveAs(fname)
예제 #23
0
    def drawGraph(self, g):
        '''
        output graph to file
        '''
        title = g.GetTitle()
        name = g.GetName()
        pdf = self.figDir + name + '.pdf'

        xsize, ysize = 1100, 850  # landscape style
        noPopUp = True
        if noPopUp: gROOT.ProcessLine("gROOT->SetBatch()")
        canvas = TCanvas(pdf, title, xsize, ysize)

        g.Draw()

        canvas.Draw()
        canvas.SetGrid(1)
        canvas.SetTicks(1)
        canvas.cd()
        canvas.Modified()
        canvas.Update()
        canvas.Print(pdf, 'pdf')
        return
예제 #24
0
def comp_two_w_ratio(h1, h2):
    c = TCanvas()
    c.Draw()
    c.Divide(1, 2)
    h1.SetLineColor(ROOT.kBlue)
    h1.SetMarkerColor(ROOT.kBlue)
    h2.SetLineColor(ROOT.kRed)
    h2.SetMarkerColor(ROOT.kRed)
    c.cd(1)
    h1.Draw("ehist")
    h2.Draw("ehistsame")
    lg = TLegend(0.4, 0.5, 0.9, 0.9)
    lg.AddEntry(h1, h1.GetName(), "lp")
    lg.AddEntry(h2, h2.GetName(), "lp")
    lg.Draw()
    #gPad.SetLogy()
    c.cd(2)
    h_ratio = h1.Clone("h_ratio")
    h_ratio.Divide(h2)
    h_ratio.Draw()
    h_ratio.GetYaxis().SetRangeUser(0.5, 1.5)
    c.Print("tmp.pdf")
    return
예제 #25
0
def drawIValues(geometry, is2016):

    global h, c

    gROOT.Reset()
    gStyle.SetOptStat(0)

    c = TCanvas('c', "Topo encoding", 1400, 950)
    c.Draw()

    h = TH2F("h", "Muon Topo encoding %i" % (2016 if is2016 else 2015), 48,
             -24, 24, 64, 0, 64)
    h.SetXTitle("#eta_{index}")
    h.SetYTitle("#phi_{index}")
    h.Draw()

    for MioctID in drawOrder:
        MIOCT = geometry.getMIOCT(MioctID)
        for tc in MIOCT.Decode.TopoCells:
            h.Fill(int(tc['ieta']) + 0.5, int(tc['iphi']) + 0.5)

    h.Draw("colz")
    c.Update()
    c.SaveAs("TopoCellCenters%s.pdf" % "2016" if is2016 else "2015")
예제 #26
0
    def dedx(self, c=None, **opts):
        from ROOT import TCanvas
        from ROOT import kRed

        color = opts.get('color', kRed)
        title = opts.get('title', "TPC dE/dx ")

        if c is None:
            c = TCanvas()

        plot = PlotData(c)

        track_tdir = self.analysis.Get(f'Tracks')
        dEdX = track_tdir.Get("pass/dEdX")
        dEdX_fail = track_tdir.Get("fail/dEdX")

        plot.p = dEdX
        plot.f = dEdX_fail

        # c.SetLogz()
        #         dEdX.Rebin2D(2,2)
        dEdX_fail.Rebin2D(2, 2)

        dEdX_fail.SetTitle(title)

        dEdX.SetStats(0)
        dEdX_fail.SetStats(0)

        dEdX_fail.Draw()

        dEdX.Draw(' same')
        dEdX.SetMarkerColor(color)

        c.Draw()

        return plot
def draw_canvas_histo(nchannels, xmin, xmax, title, cat_names, channelID):
    c = TCanvas("c", "Canvas", 800, 600)
    c.Draw()

    h = TH2F("h", "", 10, xmin, xmax, 3 * nchannels, 0, 3 * nchannels)
    h.Draw()
    h.SetStats(0)
    h.SetXTitle(title)

    yaxis = h.GetYaxis()
    yaxis.SetLabelSize(0.05)

    for ibin in range(0, nchannels):
        yaxis.SetBinLabel(3 * nchannels - 1 - 3 * ibin, cat_names[ibin])

    pub = TLatex()
    pub.SetNDC()
    pub.SetTextFont(42)
    pub.SetTextSize(0.045)
    pub.SetTextAlign(11)
    pub.DrawLatex(gStyle.GetPadLeftMargin(), 0.92,
                  "#scale[1.2]{#bf{CMS}} #it{Preliminary}")

    lumi = TLatex()
    lumi.SetNDC()
    lumi.SetTextFont(42)
    lumi.SetTextSize(0.035)
    lumi.SetTextAlign(31)
    if channelID is "DL":
        lumi.DrawLatex(1 - gStyle.GetPadRightMargin(), 0.92,
                       "11.4 - 12.9 fb^{-1} (13 TeV)")
    elif channelID is "SL":
        lumi.DrawLatex(1 - gStyle.GetPadRightMargin(), 0.92,
                       "12.9 fb^{-1} (13 TeV)")

    return c, h
예제 #28
0
def draw_canvas_histo(xmin, xmax, title):
    c = TCanvas("c", "Canvas", 600, 600)
    c.Draw()

    h = TH2F("h", "", 10, xmin, xmax, nchannels, -1, nchannels - 1 + 0.001)
    h.Draw()
    h.SetStats(0)
    h.SetXTitle(title)

    yaxis = h.GetYaxis()
    yaxis.SetLabelSize(1.5 * fontsize)
    yaxis.SetBinLabel(3, "Dilepton")
    yaxis.SetBinLabel(2, "Lepton+jets")
    yaxis.SetBinLabel(1, "Combined")

    t = TLatex()
    t.SetNDC()
    t.SetTextFont(42)
    t.SetTextSize(fontsize)
    t.SetTextAlign(11)
    t.DrawLatex(0.22, 0.91,
                "CMS preliminary, " + lumi + " fb^{-1}, #sqrt{s} = 13 TeV")

    return c, h
        legend.SetFillColor(0)
        legend.SetHeader(myDir[idir], "L")
        TGaxis.SetMaxDigits(3)

        c = TCanvas('c', '', W, H)
        c.SetFillColor(0)
        c.SetBorderMode(0)
        c.SetFrameFillStyle(0)
        c.SetFrameBorderMode(0)
        c.SetLeftMargin(L / W)
        c.SetRightMargin(R / W)
        c.SetTopMargin(T / H)
        c.SetBottomMargin(B / H)
        c.SetTickx(0)
        c.SetTicky(0)
        c.Draw()
        c.cd()

        pad1 = TPad("zxc_p1", "zxc_p1", 0, padRatio - padOverlap, 1, 1)
        pad2 = TPad("qwe_p2", "qwe_p2", 0, 0, 1, padRatio + padOverlap)
        pad1.SetLeftMargin(L / W)
        pad1.SetRightMargin(R / W)
        pad1.SetTopMargin(T / H / (1 - padRatio + padOverlap))
        pad1.SetBottomMargin(
            (padOverlap + padGap) / (1 - padRatio + padOverlap))
        pad1.SetFillColor(0)
        pad1.SetBorderMode(0)
        pad1.SetFrameFillStyle(0)
        pad1.SetFrameBorderMode(0)
        pad1.SetTickx(0)
        pad1.SetTicky(0)
예제 #30
0
parser.add_argument("--zmax",
                    dest="zmax",
                    type=float,
                    help="zmax",
                    default=None)

parser.add_argument("--text", dest="text", help="text", default=None)
parser.add_argument("--xlabel", dest="xlabel", help="xlabel", default=None)
parser.add_argument("--ylabel", dest="ylabel", help="ylabel", default=None)

args = parser.parse_args()

if not args.show: ROOT.gROOT.SetBatch(True)

ca = TCanvas("ca", "ca", 800, 600)
ca.Draw()

eras = ["A", "B", "C", "D", ""]
labels = ["2018A", "2018B", "2018C", "2018D", "2018ABCD"]

color = [ROOT.kBlack, ROOT.kRed, ROOT.kGreen, ROOT.kBlue, ROOT.kOrange]

eragraph = {}
for i, era in enumerate(eras):
    infile = TFile.Open("plots/" + args.tag + "/outPlot_2018" + era + ".root")
    h2d = infile.Get(args.name)
    h2d.SetTitle("")
    if args.add:
        h2d_add = infile.Get(args.add)
        h2d.Add(h2d_add)
        del h2d_add