Exemplo n.º 1
0
def drawFilledBox(ieta, iphi, canvas):
    canvas.cd()
    box = TBox(ieta - 0.5, iphi - 0.5, ieta + 0.5, iphi + 0.5)
    box.SetLineColor(ROOT.kBlack)
    box.SetFillStyle(3013)
    box.SetFillColor(ROOT.kBlack)
    box.Draw()
    return box
Exemplo n.º 2
0
def draw(plot, channel='MuMu', plotprefix=None, SetLogy=0):
    # print plot
    Stack.STAT_ERRORS = True
    blindxmin = None
    blindxmax = None
    titles = xtitles
    if channel == 'TauEle':
        titles = xtitles_TauEle
    xtitle = titles.get(plot.varName, None)
    if xtitle is None:
        xtitle = ''
    global can, pad, padr, ratio
    if pad is None:
        can, pad, padr = buildCanvas()
    pad.cd()
    pad.SetLogy(SetLogy)
    plot.DrawStack('HIST')
    h = plot.supportHist
    h.GetXaxis().SetLabelColor(0)
    h.GetXaxis().SetLabelSize(0)
    gevperbin = h.GetXaxis().GetBinWidth(1)
    h.GetYaxis().SetTitle('Events')
    h.GetYaxis().SetTitleOffset(1.4)
    padr.cd()
    ratio = copy.deepcopy(plot)
    ratio.legendOn = False
    ratio.DrawRatioStack('HIST', ymin=0.4, ymax=1.6)
    hr = ratio.stack.totalHist
    # hr.weighted.Fit('pol1')
    hr.GetYaxis().SetNdivisions(4)
    hr.GetYaxis().SetTitle('Exp./Obs.')
    hr.GetYaxis().SetTitleSize(0.1)
    hr.GetYaxis().SetTitleOffset(0.5)
    hr.GetXaxis().SetTitle('{xtitle}'.format(xtitle=xtitle))
    hr.GetXaxis().SetTitleSize(0.13)
    hr.GetXaxis().SetTitleOffset(0.9)
    rls = 0.075
    hr.GetYaxis().SetLabelSize(rls)
    hr.GetXaxis().SetLabelSize(rls)
    hr.GetYaxis().SetRangeUser(0.5, 1.5)
    padr.Update()
    # blinding
    if plot.blindminx:
        pad.cd()
        max = plot.stack.totalHist.GetMaximum()
        box = TBox(plot.blindminx, 0, plot.blindmaxx, max)
        box.SetFillColor(1)
        box.SetFillStyle(3004)
        box.Draw()
        # import pdb; pdb.set_trace()
        keeper.append(box)
    print channel
    if channel == 'MuMu': CMSPrelim(plot, pad, '#mu#mu')
    can.cd()
    if plotprefix == None: plotname = plot.varName
    else: plotname = plotprefix + '_' + plot.varName
    can.SaveAs(plotname + '.png')
    pad.SetLogy(0)
Exemplo n.º 3
0
def draw_box(boxList,xl,xr,yl,yr,opacity=1,color=1,style=1001,lstyle=1,lw=3):
    from ROOT import TBox
    b=TBox(xl,yl,xr,yr)
    b.SetBit(ROOT.kCanDelete)
    b.SetFillStyle(style)
    b.SetFillColorAlpha(color, opacity)
    b.SetLineColor(color)
    b.SetLineWidth(lw)
    b.SetLineStyle(lstyle)
    b.Draw()
    boxList.append(b)
Exemplo n.º 4
0
def drawHoBoxes(canvas):
    canvas.cd()
    boxes = []
    for i in range(1, 6):
        for j in range(1, 6):
            box = TBox(-2.5 + i - 1, -2.5 + j - 1, -2.5 + i, -2.5 + j)
            box.SetFillStyle(0)
            box.SetLineColor(ROOT.kBlack)
            box.SetLineWidth(2)
            box.Draw()
            boxes.append(box)
    return boxes
Exemplo n.º 5
0
def drawHcalBoxesHcalCoords(canvas):
	canvas.cd()
	boxes = []
	for i in range(-15,15):
		for j in range(0,72):
			box = TBox(i,j,(i+1),(j+1))
			box.SetFillStyle(0)
			box.SetLineColor(colorRwthMagenta)
			box.SetLineWidth(2)
			box.Draw()
			boxes.append(box)
	return boxes
Exemplo n.º 6
0
def drawHoBoxes(canvas):
	canvas.cd()
	boxes = []
	for i in range(-1,2):
		for j in range(-1,2):
			box = TBox(i*0.087 - 0.0435,j*0.087 - 0.0435,(i*0.087+0.0435),(j*0.087+0.0435))
			box.SetFillStyle(0)
			box.SetLineColor(colorRwthMagenta)
			box.SetLineWidth(3)
			box.Draw()
			boxes.append(box)
	return boxes
Exemplo n.º 7
0
def drawHoBoxes(canvas):
    canvas.cd()
    boxes = []
    for i in range(1, 8):
        for j in range(1, 8):
            box = TBox(-0.3045 + (i - 1) * 0.087, -0.3045 + (j - 1) * 0.087,
                       -0.3045 + i * 0.087, -0.3045 + j * 0.087)
            box.SetFillStyle(0)
            box.SetLineColor(ROOT.kBlack)
            box.SetLineWidth(2)
            box.Draw()
            boxes.append(box)
    return boxes
Exemplo n.º 8
0
def drawOfficial(plot, doBlind=False, channel='TauMu', plotprefix = None, ymin = 0.1):
    global ocan
    print plot
    Stack.STAT_ERRORS = False
    blindxmin = None
    blindxmax = None
    doBlind = (plot.varName == 'svfitMass') and doBlind
    if doBlind:
        blindxmin = 100
        blindxmax = 160
        plot.Blind(blindxmin, blindxmax, False)
    titles = xtitles
    if channel=='TauEle':
        titles = xtitles_TauEle
    xtitle = titles.get( plot.varName, None )
    if xtitle is None:
        xtitle = ''
    global ocan
    if ocan is None:
        ocan = buildCanvasOfficial()
    ocan.cd()
    plot.DrawStack('HIST', ymin=ymin)
    h = plot.supportHist
    h.GetXaxis().SetTitle('{xtitle}'.format(xtitle=xtitle))
    # blinding
    if plot.blindminx:
        ocan.cd()
        max = plot.stack.totalHist.GetMaximum()
        box = TBox( plot.blindminx, 0,  plot.blindmaxx, max )
        box.SetFillColor(1)
        box.SetFillStyle(3004)
        box.Draw()
        # import pdb; pdb.set_trace()
        keeper.append(box)
    year, lumi, energy = datasetInfo( plot )
    datasetStr = "CMS Preliminary, #sqrt{{s}} = {energy} TeV, L = {lumi:3.2f} fb^{{-1}}".format(energy=energy, lumi=lumi)
    if channel == 'TauMu' : a,b = CMSPrelimOfficial( datasetStr, '#tau_{#mu}#tau_{h}',0.15,0.835)
    elif channel == 'TauEle' : a,b = CMSPrelimOfficial( datasetStr, '#tau_{e}#tau_{h}', 0.15, 0.835)
    a.Draw()
    b.Draw()
    save.extend([a,b])
    ocan.Modified()    
    ocan.Update()    
    ocan.cd()
    if plotprefix == None : plotname = plot.varName
    else : plotname = plotprefix + '_' + plot.varName
    ocan.SaveAs( plotname + '.png')
    ocan.SetLogy()
    ocan.SaveAs( plotname + '_log.png')
    ocan.SetLogy(0)
Exemplo n.º 9
0
def drawBox(x1, y1, x2, y2, t=""):
    box = TBox(x1, y1, x2, y2)
    box.SetFillColor(1)
    box.SetFillStyle(3004)
    box.Draw()
    if not t == "":
        text = TLatex()
        text.SetTextColor(1)
        text.SetTextFont(42)
        text.SetTextAlign(23)
        text.SetTextSize(0.04)
        text.DrawLatex((x1 + x2) / 2., y2 / 1.15, t)
        text.Draw()
    return box
Exemplo n.º 10
0
    def makeTimeVsEtaPlot(self, source, title=""):
        canvas = TCanvas(source)
        if title == "":
            title = source
        hist = TH2D(source, title + ";i#eta;Time / ns;#", 33, -16.5, 16.5, 201,
                    -100.5, 100.5)
        graph = self.fileHandler.getGraph('graphs/timingSupport_' + source)
        fillGraphIn2DHist(graph, hist)
        hist.SetStats(0)
        hist.Draw('colz')
        canvas.Update()
        setupAxes(hist)
        label = self.drawLabel()
        canvas.Update()
        fractionGraph, counterDict = self.printFractionsPerIEta(graph)
        self.debug('Integral of plot %20s: %d' % (source, hist.Integral()))
        medianTofZero = (counterDict[9]['median'] +
                         counterDict[11]['median']) / 2.
        tofFunction = TF1(
            'f',
            '4*sqrt(1+ 1/(tan(2*atan(exp(-x*0.087/2.)))**2))/300000000.*1e9 - 13.3 + [0]',
            -10, 10)
        tofFunction.SetParameter(0, medianTofZero)
        tofFunction.Draw('same')

        ###
        # Draw Boxes for the Intervals
        ###
        intervalBoxes = []
        for index, item in enumerate(counterDict):
            iEta = index - 10
            # Skip iEta 0
            if iEta == 0:
                continue
            box = TBox(iEta - 0.5, item['median'] - 12.5, iEta + 0.5,
                       item['median'] + 12.5)
            box.SetFillStyle(0)
            box.SetLineColor(colorRwthMagenta)
            box.SetLineWidth(2)
            box.Draw()
            intervalBoxes.append(box)

        return canvas, hist, label, fractionGraph, intervalBoxes, tofFunction
Exemplo n.º 11
0
    def plot3x3MatchQualityCodesVsPt(self):
        c = TCanvas('cMatchQC3x3', 'Match QC 3x3', 0, 0, 900, 700)
        c.SetLogz()
        hist = self.fileHandler.getHistogram(
            'qualityCode/L1Muon3x3Match_QcVsPt')
        hist.SetStats(0)
        hist.Scale(1, 'width')
        hist.Draw('colz')
        c.Update()
        setupPalette(hist)
        c.Update()

        label = self.drawLabel()
        c.Update()

        box = TBox(0, 6.5, 180, 7.5)
        box.SetLineColor(3)
        box.SetLineWidth(2)
        box.Draw()

        c.Update()

        return hist, c, label, box
Exemplo n.º 12
0
tpc_xy.SetLineStyle(2)
tpc_xy.SetFillStyle(0)
tpc_xy.SetFillStyle(0)
tpc_xy.SetLineWidth(3)
h_xy.Draw("col")
h_xy.GetYaxis().SetTitleOffset(1.3)

#h_xy_corr.Draw("col")
h_xy_corr.GetYaxis().SetTitleOffset(1.3)
preliminary = TPaveText(0.48, 0.74, 0.81, 0.84, "NDC")
preliminary.SetShadowColor(0)
preliminary.SetBorderSize(0)
preliminary.SetFillStyle(0)
preliminary.AddText("MicroBooNE Preliminary")
#preliminary.Draw()
tpc_xy.Draw()

g_end.Draw("P")
g.Draw("P")
f3.SetLineStyle(1)
f3.Draw("cont2same")

c_spacecharge.Update()
c_spacecharge.SaveAs(output + "/spacecharge_" + algo + ".pdf")
c_yz = TCanvas("c_yz")
h_yz.Draw()
#h_yz_mc.Draw("same")
#h_yz_corr.Draw("same")
h_yz_mc.SetMarkerColor(kRed + 1)
h_yz_corr.SetMarkerColor(kBlue + 1)
c_yz.Update()
Exemplo n.º 13
0
def massrap_matching(blinded):
    c = Canvas("c")
    c.cd()
    c.SetTicks(1,1)
    
    gr = ROOT.TGraphErrors('gr')
    gr.SetName('gr')
    count_20, count_5, count_3, count_2, x, y = 0, 0, 0, 0, ROOT.Double(0), ROOT.Double(0)
    for i, year in enumerate(years): 
        g = getGraph(year)
        n_gr = gr.GetN() if i > 0 else 0
        for j in range(g.GetN()):
            g.GetPoint(j,x,y)
            #print 'm:', x, 'y:', y
            ex = g.GetErrorX(j)
            ey = g.GetErrorY(j)
            gr.SetPoint(n_gr+j,x,y)
            gr.SetPointError(n_gr+j,ex,ey)
            if abs(x) < 20 and abs(y) < 20: count_20 += 1
            if abs(x) < 5 and abs(y) < 5: count_5 += 1
            if abs(x) < 3 and abs(y) < 3: count_3 += 1
            if abs(x) < 2 and abs(y) < 2: count_2 += 1

    print 'Total events:', gr.GetN(), '20sig:', count_20, '5sig:', count_5, '3sig:', count_3, '2sig:', count_2

    gr.SetLineColor(ROOT.kBlack)
    gr.SetTitle('')
    gr.GetXaxis().SetTitle("(m_{pp}-m_{#gamma#gamma})/#sigma(m_{pp}-m_{#gamma#gamma})")
    gr.GetYaxis().SetTitle("(y_{pp} - y_{#gamma#gamma})/#sigma(y_{pp} - y_{#gamma#gamma})")
    gr.GetXaxis().SetLimits(-20,20)
    gr.GetYaxis().SetRangeUser(-20,20)
    gr.SetMarkerSize(0.5)
    gr.SetMarkerStyle(24)
    gr.Draw("AP")

    b3 = TBox(-5, -5, 5, 5)
    b3.SetLineColor(ROOT.kRed)
    b3.SetFillStyle(0)
    #b3.Draw()
    b2 = TBox(-3, -3, 3, 3)
    if not blinded: b2.SetFillStyle(3001) # transparent
    b2.SetFillColor(5)
    b2.SetLineColor(1)
    b2.Draw()
    b1 = TBox(-2, -2, 2, 2)
    if not blinded: b1.SetFillStyle(3001) # transparent
    b1.SetFillColor(3) 
    b1.SetLineColor(1)
    b1.Draw()
    legend = TLegend(0.7,0.8,0.9,0.9)
    legend.AddEntry(b1,"2#sigma matching",'f')
    legend.AddEntry(b2,"3#sigma matching",'f')
    #legend.AddEntry(b3,"5#sigma matching",'l')
    legend.Draw()
    c.Update() 
    pLabel = prelimLabel()
    pLabel.Draw()
    sLabel = selectionLabel("#xi^{#pm}_{#gamma#gamma} #in PPS")
    #sLabel = selectionLabel("Reverse acop. selection")
    sLabel.Draw()
    lLabel = lumiLabel()
    lLabel.Draw()
    s_blind = '_blinded' if blinded else ''
    c.SaveAs("plots/matching/massrap_matching_"+s_years+"_multiRP%s.%s" % (s_blind,extension))
Exemplo n.º 14
0
    def draw(plot,
             do_ratio=True,
             channel='e#mu#mu',
             plot_dir='/plots/',
             plot_name=None,
             SetLogy=0,
             blindxmin=None,
             blindxmax=None,
             unit=None):
        print plot
        Stack.STAT_ERRORS = True

        can = pad = padr = None

        if do_ratio:
            can, pad, padr = HistDrawer.buildCanvas()
        else:
            can = HistDrawer.buildCanvasSingle()

        pad.cd()
        pad.SetLogy(SetLogy)

        plot.DrawStack('HIST', print_norm=plot.name == '_norm_',
                       ymin=0.1)  # magic word to print integrals in legend

        h = plot.supportHist
        h.GetXaxis().SetLabelColor(1)
        # h.GetXaxis().SetLabelSize(1)

        unitsperbin = h.GetXaxis().GetBinWidth(1)
        ytitle = 'Events'
        if unit:
            round_to_n = lambda x, n: round(
                x, -int(floor(log10(abs(x)))) + (n - 1))
            ytitle += round_to_n(unitsperbin, 3)

        h.GetYaxis().SetTitle('Events')
        h.GetYaxis().SetTitleOffset(1.0)
        h.GetXaxis().SetTitleOffset(2.0)

        if do_ratio:
            padr.cd()
            ratio = copy.deepcopy(plot)
            ratio.legendOn = False

        if blindxmin or blindxmax:
            if not blindxmin:
                blindxmin = 0
            if not blindxmax:
                blindxmax = plot.stack.totalHist.GetXaxis().GetXmax()
            if do_ratio:
                ratio.Blind(blindxmin, blindxmax, True)
            plot.Blind(blindxmin, blindxmax, False)

        if do_ratio:
            ratio.DrawDataOverMCMinus1(-0.5, 0.5)
            hr = ratio.dataOverMCHist

            # Gymnastics to get same label sizes etc in ratio and main plot
            ytp_ratio = 2.
            xtp_ratio = 2.

            # hr.GetYaxis().SetNdivisions(4)

            hr.GetYaxis().SetTitleSize(h.GetYaxis().GetTitleSize() * xtp_ratio)
            hr.GetXaxis().SetTitleSize(h.GetXaxis().GetTitleSize() * ytp_ratio)

            hr.GetYaxis().SetTitleOffset(h.GetYaxis().GetTitleOffset() /
                                         xtp_ratio)
            hr.GetXaxis().SetTitleOffset(h.GetXaxis().GetTitleOffset() /
                                         ytp_ratio)

            hr.GetYaxis().SetLabelSize(h.GetYaxis().GetLabelSize() * xtp_ratio)
            hr.GetXaxis().SetLabelSize(h.GetXaxis().GetLabelSize() * ytp_ratio)

            h.GetXaxis().SetLabelColor(0)
            h.GetXaxis().SetLabelSize(0)
            padr.Update()

        # blinding
        if blindxmin or blindxmax:
            pad.cd()
            max = plot.stack.totalHist.GetMaximum()
            box = TBox(blindxmin, 0, blindxmax, max)
            box.SetFillColor(1)
            box.SetFillStyle(3004)
            box.Draw()
            HistDrawer.keeper.append(box)

        HistDrawer.CMSPrelim(plot, pad, channel, legend=plot.legendPos)
        can.cd()

        plotname = plot_dir + '/'
        ensureDir(plot_dir)
        plotname += plot_name if plot_name else plot.name
        can.SaveAs(plotname + '.png')
        can.SaveAs(plotname + '.pdf')
        can.SaveAs(plotname + '.root')

        # Also save with log y
        h.GetYaxis().SetRangeUser(pad.GetUymax() * 5. / 1000000.,
                                  pad.GetUymax() * 5.)
        pad.SetLogy(True)
        can.SaveAs(plotname + '_log.png')
        can.SaveAs(plotname + '_log.pdf')
        pad.SetLogy(0)
Exemplo n.º 15
0
def plot_rocs(plotObjects, kwargs):

    from ROOT import kCyan, kRed, kGreen, kBlue, kBlack, kMagenta, kGray, kWhite, kYellow
    Colors = [kBlue, kRed, kMagenta, kBlack, kCyan, kGreen]
    from RingerCore import StdPair as std_pair
    from util import line, minmax

    dset = kwargs['set']
    ref = kwargs['reference']
    refVal = kwargs['refVal']
    eps = kwargs['eps']
    savename = kwargs['cname'] + '.pdf'

    #Some protection
    if not ('operation' in dset or 'tst' in dset):
        raise ValueError('Option set must be: tst (test) or val (validation)')
    if not ('SP' in ref or 'Pd' in ref or 'Pf' in ref):
        raise ValueError('Option reference must be: SP, Pd or Pf')

    #Create dict to hold all list plots
    curves = dict()
    #list of dicts to dict of lists
    for name in plotObjects.keys():
        curves[name] = plotObjects.tolist(name)

    paintIdx = kwargs['paintListIdx']  # [best, worst]
    paintCurves = [
        std_pair(plotObjects.index_correction(paintIdx[0]), kBlack),
        std_pair(plotObjects.index_correction(paintIdx[1]), kRed)
    ]
    curves['roc'] = curves['roc_' + dset]

    #Start to build all ROOT objects
    from ROOT import TCanvas, gROOT, kTRUE
    gROOT.SetBatch(kTRUE)
    canvas = TCanvas('canvas', 'canvas', 1600, 1300)

    x_limits = [0.00, 0.40]
    y_limits = [0.6, 1.03]

    #create dummy graph
    dummy = curves['roc'][0]
    dummy.SetTitle('Receive Operation Curve')
    dummy.GetXaxis().SetTitle('False Alarm')
    dummy.GetYaxis().SetTitle('Detection')
    dummy.GetHistogram().SetAxisRange(y_limits[0], y_limits[1], 'Y')
    dummy.GetHistogram().SetAxisRange(x_limits[0], x_limits[1], 'X')
    dummy.Draw('AL')

    corredor = None
    target = None
    from ROOT import TBox
    if ref == 'Pf':
        corredor = TBox(refVal - eps, y_limits[0], refVal + eps, y_limits[1])
        target = line(refVal, y_limits[0], refVal, y_limits[1], kBlack, 2, 1,
                      '')
    elif ref == 'Pd':
        corredor = TBox(x_limits[0], refVal - eps, x_limits[1], refVal + eps)
        target = line(x_limits[0], refVal, x_limits[1], refVal, kBlack, 2, 1,
                      '')

    if ref != 'SP':
        corredor.SetFillColor(kYellow - 9)
        corredor.Draw('same')
        target.Draw('same')
        canvas.Modified()
        canvas.Update()

    #Plot curves
    for c in curves['roc']:
        c.SetLineColor(kGray + 1)
        #c.SetMarkerStyle(7)
        #c.SetMarkerColor(kBlue)
        c.SetLineWidth(1)
        c.SetLineStyle(3)
        #c.Draw('PLsame')
        c.Draw('same')

    marker = list()
    #Paint a specifical curve
    for pair in paintCurves:
        curves['roc'][pair.first].SetLineWidth(1)
        curves['roc'][pair.first].SetLineStyle(1)
        #curves['roc'][pair.first].SetMarkerStyle(7)
        #curves['roc'][pair.first].SetMarkerColor(kBlue)
        curves['roc'][pair.first].SetLineColor(pair.second)
        #curves['roc'][pair.first].Draw('PLsame')
        curves['roc'][pair.first].Draw('same')

        if ref == 'SP':
            faVec = curves['roc'][pair.first].GetX()
            detVec = curves['roc'][pair.first].GetY()
            from RingerCore import calcSP
            spVec = [
                calcSP(detVec[i], 1 - faVec[i])
                for i in range(curves['roc'][pair.first].GetN())
            ]
            imax = spVec.index(max(spVec))
            from ROOT import TMarker
            marker.append(TMarker(faVec[imax], detVec[imax], 4))
            marker[-1].SetMarkerColor(pair.second)
            marker[-1].Draw('same')

    #Update Canvas
    canvas.Modified()
    canvas.Update()
    canvas.SaveAs(savename)
    del canvas

    return savename
Exemplo n.º 16
0
    def draw(plot,
             do_ratio=True,
             channel='#mu#tau_{h}',
             plot_dir='plots',
             plot_name=None,
             SetLogy=0,
             blindxmin=None,
             blindxmax=None,
             unit=None):
        print plot
        Stack.STAT_ERRORS = True

        can = pad = padr = None

        if do_ratio:
            can, pad, padr = HistDrawer.buildCanvas()
        else:
            can = HistDrawer.buildCanvasSingle()

        pad.cd()
        pad.SetLogy(SetLogy)
        # print "about to DrawStack"
        # plot.DrawNormalized()
        # plot.DrawNormalizedRatioStack('HIST', ymin=0.1)
        # , dataAsPoisson=True
        plot.DrawStack(
            'HIST',
            print_norm=plot.name == '_norm_',
            ymin=0.1,
            scale_signal='')  # magic word to print integrals in legend

        h = plot.supportHist
        h.GetXaxis().SetLabelColor(1)
        # h.GetXaxis().SetLabelSize(1)

        unitsperbin = h.GetXaxis().GetBinWidth(1)
        ytitle = 'Events'
        if unit:
            round_to_n = lambda x, n: round(
                x, -int(floor(log10(abs(x)))) + (n - 1))
            ytitle += round_to_n(unitsperbin, 3)

        h.GetYaxis().SetTitle('Events')
        # if axis labels and title overlap, change offset here
        h.GetYaxis().SetTitleOffset(1.3)
        h.GetXaxis().SetTitleOffset(2.0)

        if do_ratio:
            padr.cd()
            ratio = copy.deepcopy(plot)
            ratio.legendOn = False

        if blindxmin or blindxmax:
            if not blindxmin:
                blindxmin = 0
            if not blindxmax:
                blindxmax = plot.GetXaxis().GetXmax()
            if do_ratio:
                ratio.Blind(blindxmin, blindxmax, True)
            plot.Blind(blindxmin, blindxmax, False)

        if do_ratio:
            ratio.DrawDataOverMCMinus1(-0.5, 0.5)
            hr = ratio.dataOverMCHist

            # Gymnastics to get same label sizes etc in ratio and main plot
            ytp_ratio = 2.
            xtp_ratio = 2.

            # hr.GetYaxis().SetNdivisions(4)

            hr.GetYaxis().SetTitleSize(h.GetYaxis().GetTitleSize() * xtp_ratio)
            hr.GetXaxis().SetTitleSize(h.GetXaxis().GetTitleSize() * ytp_ratio)

            hr.GetYaxis().SetTitleOffset(h.GetYaxis().GetTitleOffset() /
                                         xtp_ratio)
            hr.GetXaxis().SetTitleOffset(h.GetXaxis().GetTitleOffset() /
                                         ytp_ratio)

            hr.GetYaxis().SetLabelSize(h.GetYaxis().GetLabelSize() * xtp_ratio)
            hr.GetXaxis().SetLabelSize(h.GetXaxis().GetLabelSize() * ytp_ratio)

            h.GetXaxis().SetLabelColor(0)
            h.GetXaxis().SetLabelSize(0)
            padr.Update()

        # blinding
        if blindxmin or blindxmax:
            pad.cd()
            max = plot.stack.totalHist.GetMaximum()
            box = TBox(blindxmin, 0, blindxmax, max)
            box.SetFillColor(1)
            box.SetFillStyle(3004)
            box.Draw()
            HistDrawer.keeper.append(box)

        HistDrawer.CMSPrelim(plot, pad, channel, legend=plot.legendPos)
        can.cd()

        plotname = plot_dir + '/'
        ensureDir(plot_dir)
        plotname += plot_name if plot_name else plot.name
        can.SaveAs(plotname + '.png')
        can.SaveAs(plotname + '.pdf')

        # Also save with log y
        if plot.legendPos == 'right':
            h.GetYaxis().SetRangeUser(0.1001, pad.GetUymax() * 5.)
        else:
            # minimum is set to 2 orders of magnitude lower than maximum
            minRange = pow(10, floor(log10(pad.GetUymax() / 100.)))
            h.GetYaxis().SetRangeUser(minRange + minRange * 1e-4,
                                      pad.GetUymax() * 5.e3)
        pad.SetLogy(True)
        can.SaveAs(plotname + '_log.png')
        can.SaveAs(plotname + '_log.pdf')
        pad.SetLogy(0)
        return ratio
Exemplo n.º 17
0
		null = TPad("null","",0,0,1,1)
		null.SetFillStyle(0)
		null.SetFrameFillStyle(0)
		null.Draw()
		null.cd()
		null.Range(x1-LM,yf-BM,x2+RM,y2+TM)

		tri=TPolyLine(3,xx,yy)
		tri.SetFillColor(0)
		box1=TBox(-0.2,-0.2,1.05,0)
		box2=TBox(-0.2,-0.2,0,1.05)
		box1.SetFillColor(0)
		box2.SetFillColor(0)
		#p.Draw('atext')
		tri.Draw('f')
		box1.Draw('f')
		box2.Draw('f')
		tri.Draw('f')

		if tipo in ['obs','exp']:
			bm = c.GetBottomMargin()
			lm = c.GetLeftMargin()
			rm = c.GetRightMargin()
			to = c.GetTopMargin()
			x1 = p.GetXaxis().GetXmin()
			yf = p.GetYaxis().GetXmin()
			x2 = p.GetXaxis().GetXmax()
			y2 = p.GetYaxis().GetXmax()

			Xa = (x2-x1)/(1-lm-rm)-(x2-x1)
			Ya = (y2-yf)/(1-bm-to)-(y2-yf)
Exemplo n.º 18
0
    def draw(plot,
             do_ratio=True,
             channel='TauMu',
             plot_dir='plots',
             plot_name=None,
             SetLogy=0,
             mssm=False,
             blindxmin=None,
             blindxmax=None,
             unit=None):
        print plot
        Stack.STAT_ERRORS = True

        can = pad = padr = None

        if do_ratio:
            can, pad, padr = HistDrawer.buildCanvas()
        else:
            can = HistDrawer.buildCanvasSingle()

        pad.cd()
        pad.SetLogy(SetLogy)

        plot.DrawStack('HIST')

        h = plot.supportHist
        h.GetXaxis().SetLabelColor(1)
        # h.GetXaxis().SetLabelSize(1)

        unitsperbin = h.GetXaxis().GetBinWidth(1)
        ytitle = 'Events'
        if unit:
            round_to_n = lambda x, n: round(
                x, -int(floor(log10(abs(x)))) + (n - 1))
            ytitle += round_to_n(unitsperbin, 3)

        h.GetYaxis().SetTitle('Events')
        h.GetYaxis().SetTitleOffset(1.0)
        h.GetXaxis().SetTitleOffset(2.0)

        if do_ratio:
            padr.cd()
            ratio = copy.deepcopy(plot)
            ratio.legendOn = False

        if blindxmin or blindxmax:
            if not blindxmin:
                blindxmin = 0
            if not blindxmax:
                blindxmax = plot.GetXaxis().GetXmax()
            if do_ratio:
                ratio.Blind(blindxmin, blindxmax, True)
            plot.Blind(blindxmin, blindxmax, False)

        if do_ratio:
            ratio.DrawDataOverMCMinus1(-0.5, 0.5)
            hr = ratio.dataOverMCHist

            # ytp_ratio = float(pad.YtoPixel(0.)/padr.YtoPixel(0))
            # print 'YTP ratio', ytp_ratio
            # xtp_ratio = float(pad.XtoPixel(0.)/padr.XtoPixel(0))
            # print 'XTP ratio', xtp_ratio

            ytp_ratio = 2.
            xtp_ratio = 2.

            # hr.GetYaxis().SetNdivisions(4)

            hr.GetYaxis().SetTitleSize(h.GetYaxis().GetTitleSize() * xtp_ratio)
            hr.GetXaxis().SetTitleSize(h.GetXaxis().GetTitleSize() * ytp_ratio)

            hr.GetYaxis().SetTitleOffset(h.GetYaxis().GetTitleOffset() /
                                         xtp_ratio)
            hr.GetXaxis().SetTitleOffset(h.GetXaxis().GetTitleOffset() /
                                         ytp_ratio)

            hr.GetYaxis().SetLabelSize(h.GetYaxis().GetLabelSize() * xtp_ratio)
            hr.GetXaxis().SetLabelSize(h.GetXaxis().GetLabelSize() * ytp_ratio)

            h.GetXaxis().SetLabelColor(0)
            h.GetXaxis().SetLabelSize(0)
            padr.Update()

        # blinding
        if blindxmin or blindxmax:
            pad.cd()
            max = plot.stack.totalHist.GetMaximum()
            box = TBox(blindxmin, 0, blindxmax, max)
            box.SetFillColor(1)
            box.SetFillStyle(3004)
            box.Draw()
            HistDrawer.keeper.append(box)
        print channel
        if channel == 'TauMu':
            HistDrawer.CMSPrelim(plot,
                                 pad,
                                 '#tau_{#mu}#tau_{h}',
                                 legend=plot.legendPos)
        elif channel == 'TauEle':
            HistDrawer.CMSPrelim(plot,
                                 pad,
                                 '#tau_{e}#tau_{h}',
                                 legend=plot.legendPos)
        can.cd()

        plotname = plot_dir + '/'
        ensureDir(plot_dir)
        plotname += plot_name if plot_name else plot.name
        can.SaveAs(plotname + '.png')
        pad.SetLogy(0)
        return ratio
Exemplo n.º 19
0
    ihMinTHalf_y = SensClass.GetTHalf(ihMaxMbb_meV * CLHEP.meV, isotope,
                                      nmeModel, ga) / CLHEP.year
    ihMaxTHalf_y = SensClass.GetTHalf(ihMinMbb_meV * CLHEP.meV, isotope,
                                      nmeModel, ga) / CLHEP.year
    ihMaxMaxTHalf_y = SensClass.GetTHalf(ihMinMinMbb_meV * CLHEP.meV, isotope,
                                         nmeModel, ga) / CLHEP.year
    bInvHierOut = TBox(expMin_ty, ihMinMinTHalf_y, 0.98 * expMax_ty,
                       ihMaxMaxTHalf_y)
    bInvHierIn = TBox(expMin_ty, ihMinTHalf_y, 0.98 * expMax_ty, ihMaxTHalf_y)
    if options.useShellModel: ihText += "(SM"
    else: ihText += "(QRPA"
    ihText += ", g_{A}=" + str(ga) + ")"
    lInvHier = TLatex(2. * expMin_ty, math.sqrt(ihMinTHalf_y * ihMaxTHalf_y),
                      ihText)
bInvHierOut.SetFillColor(TColor.GetColor(0.8, 1.0, 0.8))
bInvHierOut.Draw()
bInvHierIn.SetFillColor(TColor.GetColor(0.7, 0.95, 0.7))
bInvHierIn.Draw()
lInvHier.SetTextAlign(12)
lInvHier.SetTextColor(TColor.GetColor(0.1, 0.4, 0.1))
lInvHier.SetTextSize(0.04)
lInvHier.Draw()

if drawKKDC:
    hvkkTHalfLo_y = (2.23 - 3. * 0.31) * 1e25
    hvkkTHalfHi_y = (2.23 + 3. * 0.44) * 1e25
    hvkkMbbLo_meV = SensClass.GetMbb(hvkkTHalfHi_y * CLHEP.year, isotope,
                                     nmeModel, ga) / (1.e-3 * CLHEP.eV)
    hvkkMbbHi_meV = SensClass.GetMbb(hvkkTHalfLo_y * CLHEP.year, isotope,
                                     nmeModel, ga) / (1.e-3 * CLHEP.eV)
    hvkkBox = TBox(expMin_ty, hvkkMbbLo_meV, 0.98 * expMax_ty, hvkkMbbHi_meV)
Exemplo n.º 20
0
def oneDim_matching(blinded):
    c1 = Canvas("c1")
    c2 = Canvas("c2")

    h_mass = ROOT.TH1F('h_mass', '', 40, -20, 20)
    h_rap = ROOT.TH1F('h_rap', '', 40, -20, 20)
    x, y = ROOT.Double(0), ROOT.Double(0)
    for i, year in enumerate(years):
        g = getGraph(year)
        for j in range(g.GetN()):
            g.GetPoint(j,x,y)
            ex = g.GetErrorX(j)
            ey = g.GetErrorY(j)
            h_mass.Fill(x)
            h_rap.Fill(y)

    c1.cd()
    c1.SetTicks(1,1)
    h_mass.GetXaxis().SetTitle('(m_{pp}-m_{#gamma#gamma})/#sigma(m_{pp}-m_{#gamma#gamma}}')
    h_mass.GetYaxis().SetTitle('Events')
    h_mass.SetMarkerStyle(24)
    h_mass.SetLineColor( ROOT.kBlack )
    h_mass.Sumw2()
    min, max = h_mass.GetMinimum(), h_mass.GetMaximum()+3
    h_mass.SetMaximum(max)
    h_mass.Draw('p')
    '''
    l1 = TLine(-2,h_mass.GetMinimum(),-2,max)
    l1.SetLineColor( ROOT.kRed+1 )
    l1.SetLineStyle(2)
    l1.SetLineWidth(2)
    l2 = TLine(2,h_mass.GetMinimum(),2,max)
    l2.SetLineColor( ROOT.kRed+1 )
    l2.SetLineStyle(2)
    l2.SetLineWidth(2)
    l3 = TLine(-3,h_mass.GetMinimum(),-3,max)
    l3.SetLineColor( ROOT.kRed+1 )
    l3.SetLineStyle(1)
    l3.SetLineWidth(2)
    l4 = TLine(3,h_mass.GetMinimum(),3,max)
    l4.SetLineColor( ROOT.kRed+1 )
    l4.SetLineStyle(1)
    l4.SetLineWidth(2)
    '''
    b2 = TBox(-3, min, 3, max-0.05)
    if not blinded: b2.SetFillStyle(3001) # transparent
    b2.SetFillColor(5)
    b2.SetLineColor(1)
    b2.Draw()
    b1 = TBox(-2, min, 2, max-0.05)
    if not blinded: b1.SetFillStyle(3001) # transparent
    b1.SetFillColor(3)
    b1.SetLineColor(1)
    b1.Draw()
    pLabel, sLabel, lLabel = prelimLabel(), selectionLabel("#xi^{#pm}_{#gamma#gamma} #in PPS"), lumiLabel()
    pLabel.Draw(), sLabel.Draw(), lLabel.Draw()
    legend = TLegend(0.7,0.8,0.9,0.9)
    legend.AddEntry(b1,"2#sigma matching",'f')
    legend.AddEntry(b2,"3#sigma matching",'f')
    legend.Draw()
    c1.SaveAs('plots/matching/h_mass_1d.%s' % extension)
    c2.cd()
    c2.SetTicks(1,1)
    h_rap.GetXaxis().SetTitle('(y_{pp}-y_{#gamma#gamma})/#sigma(y_{pp}-y_{#gamma#gamma}}')
    h_rap.GetYaxis().SetTitle('Events')
    h_rap.SetMarkerStyle(24)
    h_rap.SetLineColor( ROOT.kBlack )
    h_rap.Sumw2()
    h_rap.SetMaximum(max)
    h_rap.Draw('p')
    b2.Draw()
    b1.Draw()
    pLabel, sLabel, lLabel = prelimLabel(), selectionLabel("#xi^{#pm}_{#gamma#gamma} #in PPS"), lumiLabel()
    pLabel.Draw(), sLabel.Draw(), lLabel.Draw()
    legend = TLegend(0.7,0.8,0.9,0.9)
    legend.AddEntry(b1,"2#sigma matching",'f')
    legend.AddEntry(b2,"3#sigma matching",'f')
    legend.Draw()
    c2.SaveAs('plots/matching/h_rap_1d.%s' % extension)
Exemplo n.º 21
0
def pullsVertical(fileName):

    content = filterPullFile(fileName)
    nbins, off = len(content), 0.10

    b_pulls = TH1F("b_pulls", ";;Pulls", nbins, 0. - off, nbins - off)
    s_pulls = TH1F("s_pulls", ";;Pulls", nbins, 0. + off, nbins + off)  #

    for i, s in enumerate(content):
        l = s.split()
        b_pulls.GetXaxis().SetBinLabel(i + 1, l[0])
        s_pulls.GetXaxis().SetBinLabel(i + 1, l[0])
        b_pulls.SetBinContent(i + 1, float(l[1]))
        b_pulls.SetBinError(i + 1, float(l[2]))
        s_pulls.SetBinContent(i + 1, float(l[3]))
        s_pulls.SetBinError(i + 1, float(l[4]))

    b_pulls.SetFillStyle(3005)
    b_pulls.SetFillColor(923)
    b_pulls.SetLineColor(923)
    b_pulls.SetLineWidth(1)
    b_pulls.SetMarkerStyle(20)
    b_pulls.SetMarkerSize(1.25)

    s_pulls.SetLineColor(602)
    s_pulls.SetMarkerColor(602)
    s_pulls.SetMarkerStyle(24)  #24
    s_pulls.SetLineWidth(1)

    b_pulls.GetYaxis().SetRangeUser(-2.5, 2.5)

    # Graphs
    h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins)
    B_pulls = TGraphAsymmErrors(nbins)
    S_pulls = TGraphAsymmErrors(nbins)

    boxes = []

    canvas = TCanvas("canvas", "Pulls", 600, 150 + nbins * 10)  #nbins*20)
    canvas.cd()
    canvas.SetGrid(0, 1)
    canvas.GetPad(0).SetTopMargin(0.01)
    canvas.GetPad(0).SetRightMargin(0.01)
    canvas.GetPad(0).SetBottomMargin(0.05)
    canvas.GetPad(0).SetLeftMargin(0.25)  #(0.25)#(0.065)
    canvas.GetPad(0).SetTicks(1, 1)

    for i, s in enumerate(content):
        l = s.split()
        if "1034h" in l[0]: l[0] = "CMS_PDF_13TeV"
        h_pulls.GetYaxis().SetBinLabel(i + 1, l[0].replace('CMS2016_', ''))  #C
        #y1 = gStyle.GetPadBottomMargin()
        #y2 = 1. - gStyle.GetPadTopMargin()
        #h = (y2 - y1) / float(nbins)
        #y1 = y1 + float(i) * h
        #y2 = y1 + h
        #box = TPaveText(0, y1, 1, y2, 'NDC')
        #box.SetFillColor(0)
        #box.SetTextSize(0.02)
        #box.SetBorderSize(0)
        #box.SetTextAlign(12)
        #box.SetMargin(0.005)
        #if i % 2 == 0:
        #    box.SetFillColor(18)
        #box.Draw()
        #boxes.append(box)
        B_pulls.SetPoint(i + 1, float(l[1]), float(i + 1) - 0.3)  #C
        B_pulls.SetPointError(i + 1, float(l[2]), float(l[2]), 0., 0.)  #C

    for i, s in enumerate(content):
        l = s.split()
        S_pulls.SetPoint(i + 1, float(l[3]), float(i + 1) - 0.7)  #C
        S_pulls.SetPointError(i + 1, float(l[4]), float(l[4]), 0., 0.)  #C

    h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta")
    h_pulls.GetXaxis().SetLabelOffset(-0.01)
    h_pulls.GetXaxis().SetTitleOffset(.6)
    h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0)

    B_pulls.SetFillColor(1)
    B_pulls.SetLineColor(1)
    B_pulls.SetLineStyle(1)
    B_pulls.SetLineWidth(2)
    B_pulls.SetMarkerColor(1)
    B_pulls.SetMarkerStyle(20)
    B_pulls.SetMarkerSize(1)  #(0.75)

    S_pulls.SetFillColor(629)
    S_pulls.SetLineColor(629)
    S_pulls.SetMarkerColor(629)
    S_pulls.SetLineWidth(2)
    S_pulls.SetMarkerStyle(20)
    S_pulls.SetMarkerSize(1)

    box1 = TBox(-1., 0., 1., nbins)
    box1.SetFillStyle(3001)
    #box1.SetFillStyle(0)
    box1.SetFillColor(417)
    box1.SetLineWidth(2)
    box1.SetLineStyle(2)
    box1.SetLineColor(417)

    box2 = TBox(-2., 0., 2., nbins)
    box2.SetFillStyle(3001)
    #box2.SetFillStyle(0)
    box2.SetFillColor(800)
    box2.SetLineWidth(2)
    box2.SetLineStyle(2)
    box2.SetLineColor(800)

    leg = TLegend(0.1, -0.05, 0.7, 0.08)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    leg.SetNColumns(2)
    leg.AddEntry(B_pulls, "B-only fit", "lp")
    leg.AddEntry(S_pulls, "S+B fit", "lp")
    if text: leg.AddEntry(0, text, "")

    h_pulls.Draw("")
    box2.Draw()
    box1.Draw()
    B_pulls.Draw("P6SAME")
    S_pulls.Draw("P6SAME")
    leg.Draw()

    #    drawCMS(35867, "Preliminary")
    #    drawAnalysis("VH")
    #    drawRegion(outName)

    canvas.Print(outName + ".png")
    canvas.Print(outName + ".pdf")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Exemplo n.º 22
0
    def makeCombinedEtaPlot(self, tight=False):
        hist = self.makeL1TimeVsEtaPlot(('tight_' if tight else '') +
                                        'dtOnly_bxidVsEta')[2]
        countsInL1 = []
        for x in np.arange(-.95, 1.05, 0.1):
            totalCounter = 0
            zeroCount = 0
            for y in range(-2, 3):
                totalCounter += hist.GetBinContent(hist.FindBin(x, y))
                if y == 0:
                    zeroCount = hist.GetBinContent(hist.FindBin(x, y))
            countsInL1.append({
                'total': totalCounter,
                'zero': zeroCount,
                'eta': x
            })

        #Graph for results
        graph1 = TEfficiency(hist.GetName(), "", 8, -9.195, -.5)
        graph2 = TEfficiency(hist.GetName(), "", 8, .5, 9.195)

        for item in countsInL1:
            if item['total'] == 0:
                continue
            print item['total'], item['zero'], item['eta']
            if item['eta'] < 0:
                graph1.SetTotalEvents(
                    graph1.FindFixBin(-0.5 + item['eta'] / 0.087),
                    int(item['total']))
                graph1.SetPassedEvents(
                    graph1.FindFixBin(-0.5 + item['eta'] / 0.087),
                    int(item['zero']))
            else:
                graph2.SetTotalEvents(
                    graph2.FindFixBin(0.5 + item['eta'] / 0.087),
                    int(item['total']))
                graph2.SetPassedEvents(
                    graph2.FindFixBin(0.5 + item['eta'] / 0.087),
                    int(item['zero']))

        histHo = None
        if tight:
            histHo = self.plotTightHoTimeVsEta()[3][1]
        else:
            histHo = self.plotHoTimeVsEta()[3][1]

        histHo.SetTitle(('Tight ' if tight else '') + 'Unmatched DT + HO')

        canvas = TCanvas(
            'combinedPlot' + ('Tight ' if tight else '') + hist.GetName(),
            'combinedPlot')
        canvas.cd().SetTopMargin(.15)
        histHo.Draw('ap')
        canvas.Update()
        canvas.cd().SetTicks(0, 0)

        histHo.SetMarkerStyle(2)
        histHo.SetLineColor(colorRwthDarkBlue)
        histHo.SetMarkerColor(colorRwthDarkBlue)
        histHo.GetPaintedGraph().GetXaxis().SetRangeUser(-12, 12)
        histHo.GetPaintedGraph().GetXaxis().SetLabelColor(colorRwthDarkBlue)
        histHo.GetPaintedGraph().GetXaxis().SetTitleColor(colorRwthDarkBlue)
        histHo.GetPaintedGraph().GetXaxis().SetAxisColor(colorRwthDarkBlue)
        yMax = gPad.GetFrame().GetY2()
        yMin = gPad.GetFrame().GetY1()

        #Print average Fraction excluding iEta +/-2
        x = Double(0)
        y = Double(0)
        mean = 0
        var = 0
        for i in range(0, histHo.GetPaintedGraph().GetN()):
            histHo.GetPaintedGraph().GetPoint(i, x, y)
            if abs(x) == 2:
                continue
            mean += y
            var += histHo.GetPaintedGraph().GetErrorY(
                i) * histHo.GetPaintedGraph().GetErrorY(i)

        mean /= histHo.GetPaintedGraph().GetN() - 2
        sigma = sqrt(var / (histHo.GetPaintedGraph().GetN() - 2))

        self.debug(
            "Average fraction excluding iEta +/- 2 %s: %5.2f%% +/- %5.2f%%" %
            ('[Tight]' if tight else '', mean * 100, sigma * 100))

        nTotal = 0
        nPassed = 0
        for item in countsInL1:
            if fabs(item['eta']) == 2 or fabs(item['eta'] == 0):
                continue
            nTotal += item['total']
            nPassed += item['zero']

        #Print again with ClopperPearson uncertainty, the counts are for L1!!!
        mean = nPassed / nTotal * 100
        sigmaPlus = TEfficiency.ClopperPearson(int(nTotal), int(nPassed), .68,
                                               1) * 100 - mean
        sigmaMinus = mean - TEfficiency.ClopperPearson(
            int(nTotal), int(nPassed), .68, 0) * 100
        #self.debug("Average fraction excluding iEta +/- 2 %s with Clop.Pear.: %5.2f%% +%5.2f%% -%5.2f%%"
        #		% ('[Tight]' if tight else '',mean,sigmaPlus,sigmaMinus))

        #Left axis part
        f1 = TF1("f1", "x", -0.87, 0)
        A1 = TGaxis(-10, yMax, -0.5, yMax, "f1", 010, "-")
        A1.SetLineColor(colorRwthRot)
        A1.SetLabelColor(colorRwthRot)
        A1.Draw()

        #Right axis part
        f2 = TF1("f2", "x", 0, 0.87)
        A2 = TGaxis(0.5, yMax, 10, yMax, "f2", 010, "-")
        A2.SetLineColor(colorRwthRot)
        A2.SetLabelColor(colorRwthRot)
        A2.Draw()

        #Box for shading out 0
        box = TBox(-.5, yMin, 0.5, yMax)
        box.SetLineColor(colorRwthDarkGray)
        box.SetFillColor(colorRwthDarkGray)
        box.SetFillStyle(3013)
        box.Draw('same')

        #Left L1 eta
        graph1.SetMarkerColor(colorRwthRot)
        graph1.SetLineColor(colorRwthRot)
        graph1.SetMarkerStyle(20)
        graph1.Draw('same,p')

        #Right L1Eta
        graph2.SetMarkerColor(colorRwthRot)
        graph2.SetLineColor(colorRwthRot)
        graph2.SetMarkerStyle(20)
        graph2.Draw('same,p')

        #Label for extra axis
        axisLabel = TPaveText(0.83, 0.85, 0.89, 0.9, "NDC")
        axisLabel.AddText('#eta_{L1}')
        axisLabel.SetBorderSize(0)
        axisLabel.SetFillStyle(0)
        axisLabel.SetTextColor(colorRwthRot)
        axisLabel.SetTextSize(0.05)
        axisLabel.Draw()

        #Legend
        legend = getLegend(x1=0.1, y1=0.1, x2=0.4, y2=.35)
        legend.AddEntry(histHo, 'HO #in #pm12.5 ns', 'pe')
        legend.AddEntry(graph1, ('Tight ' if tight else '') + 'L1 BXID = 0',
                        'pe')
        legend.Draw()

        canvas.Update()
        self.storeCanvas(canvas,
                         "combinedFractionL1AndHo" +
                         ('Tight' if tight else ''),
                         drawMark=False)

        return histHo, graph1, canvas, A1, f1, A2, f2, box, graph2, axisLabel, legend
                           pars.varRanges[pars.var[0]][2])
pull1.GetXaxis().SetTitle(fitter.ws.var(vName1).getTitle(True).Data())
pull1.GetYaxis().SetTitle("pull (#sigma)")

blinder = plot1.findObject('TBox')
blinder2 = None
if blinder:
    blinder2 = TBox(pars.exclude[pars.var[0]][0],
                    pull1.GetYaxis().GetXmin(), pars.exclude[pars.var[0]][1],
                    pull1.GetYaxis().GetXmax())
    blinder2.SetFillColor(kBlack)
    blinder2.SetFillStyle(1001)

if blinder2:
    #blinder2.Print()
    blinder2.Draw()

cp1.Update()

if opts.toyOut:
    outFile = open(opts.toyOut, 'a', 1)
    fitter.ws.loadSnapshot("genPars")

    line = '%s %.6g %.6g %.6g '
    outFile.write('nll %f covQual %i edm %.4g ' %
                  (fr.minNll(), fr.covQual(), fr.edm()))
    outFile.write('chi2Prob %f ' % (TMath.Prob(chi2, ndf)))
    for cycle in range(0, fr.numStatusHistory()):
        outFile.write(
            '%s %i ' %
            (fr.statusLabelHistory(cycle), fr.statusCodeHistory(cycle)))
Exemplo n.º 24
0
def draw(plot,
         doBlind=True,
         channel='TauMu',
         plotprefix=None,
         SetLogy=0,
         mssm=False):
    print plot
    Stack.STAT_ERRORS = True
    blindxmin = None
    blindxmax = None
    if doBlind:
        if plot.varName == 'svfitMass':
            blindxmin = 100
            if mssm:
                blindxmax = 1000.
            else:
                blindxmax = 160
        elif plot.varName == 'visMass':
            blindxmin = 70
            blindxmax = 100
    titles = xtitles
    if channel == 'TauEle':
        titles = xtitles_TauEle
    xtitle = titles.get(plot.varName, None)
    if xtitle is None:
        xtitle = ''
    global can, pad, padr, ratio
    #if pad is None:
    if not pad:
        can, pad, padr = buildCanvas()
    pad.cd()
    pad.SetLogy(SetLogy)
    plot.DrawStack('HIST')
    h = plot.supportHist
    h.GetXaxis().SetLabelColor(1)
    h.GetXaxis().SetLabelSize(1)
    gevperbin = h.GetXaxis().GetBinWidth(1)
    h.GetYaxis().SetTitle('Events')
    h.GetYaxis().SetTitleOffset(1.4)
    padr.cd()
    ratio = copy.deepcopy(plot)
    ratio.legendOn = False
    if doBlind:
        ratio.Blind(blindxmin, blindxmax, True)
        plot.Blind(blindxmin, blindxmax, False)
    ratio.DrawDataOverMCMinus1(-0.2, 0.2)
    hr = ratio.dataOverMCHist
    hr.GetYaxis().SetNdivisions(4)
    hr.GetYaxis().SetTitleSize(0.1)
    hr.GetYaxis().SetTitleOffset(0.7)
    hr.GetXaxis().SetTitle('{xtitle}'.format(xtitle=xtitle))
    hr.GetXaxis().SetTitleSize(0.13)
    hr.GetXaxis().SetTitleOffset(0.9)
    rls = 0.1
    hr.GetYaxis().SetLabelSize(rls)
    hr.GetXaxis().SetLabelSize(rls)
    h.GetXaxis().SetLabelColor(0)
    h.GetXaxis().SetLabelSize(0)
    padr.Update()
    # blinding
    if doBlind:
        pad.cd()
        max = plot.stack.totalHist.GetMaximum()
        box = TBox(blindxmin, 0, blindxmax, max)
        box.SetFillColor(1)
        box.SetFillStyle(3004)
        box.Draw()
        # import pdb; pdb.set_trace()
        keeper.append(box)
    print channel
    if channel == 'TauMu': CMSPrelim(plot, pad, '#tau_{#mu}#tau_{h}')
    elif channel == 'TauEle': CMSPrelim(plot, pad, '#tau_{e}#tau_{h}')
    can.cd()
    if plotprefix == None: plotname = plot.varName
    else: plotname = plotprefix + '_' + plot.varName
    can.SaveAs(plotname + '.png')
    pad.SetLogy(0)
    return ratio
Exemplo n.º 25
0
    def draw(plot,
             do_ratio=True,
             channel='e#mu#mu',
             plot_dir='/plots/',
             plot_name=None,
             SetLogy=0,
             blindxmin=None,
             blindxmax=None,
             unit=None,
             server='starseeker',
             region='DY',
             channel_dir='mmm',
             dataset='2017'):
        print(plot)
        Stack.STAT_ERRORS = True

        can = pad = padr = None

        if do_ratio:
            can, pad, padr = HistDrawer.buildCanvas()
            pad.cd()
            pad.SetLogy(SetLogy)
        else:
            can = HistDrawer.buildCanvasSingle()
            pad = can
            pad.cd()
            pad.SetLogy(SetLogy)

        # plot.DrawStack('HIST', print_norm=plot.name=='_norm_', ymin=0.1) # magic word to print integrals in legend
        plot.DrawStack('HIST', print_norm=('_norm_' in plot.name),
                       ymin=0.1)  # magic word to print integrals in legend

        h = plot.supportHist
        h.GetXaxis().SetLabelColor(1)
        # h.GetXaxis().SetLabelSize(1)

        unitsperbin = h.GetXaxis().GetBinWidth(1)
        ytitle = 'Events'
        if unit:
            round_to_n = lambda x, n: round(
                x, -int(floor(log10(abs(x)))) + (n - 1))
            ytitle += round_to_n(unitsperbin, 3)

        h.GetYaxis().SetTitle('Events')
        h.GetYaxis().SetTitleOffset(1.4)
        h.GetXaxis().SetTitleOffset(2.0)

        if do_ratio:
            padr.cd()
            ratio = copy.deepcopy(plot)
            ratio.legendOn = True
            ratio.STAT_ERRORS = True

        if blindxmin or blindxmax:
            if not blindxmin:
                blindxmin = 0
            if not blindxmax:
                blindxmax = plot.stack.totalHist.GetXaxis().GetXmax()
            if do_ratio:
                ratio.Blind(blindxmin, blindxmax, True)
            plot.Blind(blindxmin, blindxmax, False)

        if do_ratio:
            # ratio.DrawDataOverMCMinus1(-0.5, 0.5)
            ratio.DrawDataOverMCMinus1(-0.9, 0.9)
            hr = ratio.dataOverMCHist

            # Gymnastics to get same label sizes etc in ratio and main plot
            ytp_ratio = 2.
            xtp_ratio = 2.

            # hr.GetYaxis().SetNdivisions(4)

            hr.GetYaxis().SetTitleSize(h.GetYaxis().GetTitleSize() * xtp_ratio)
            hr.GetXaxis().SetTitleSize(h.GetXaxis().GetTitleSize() * ytp_ratio)

            hr.GetYaxis().SetTitleOffset(h.GetYaxis().GetTitleOffset() /
                                         xtp_ratio)
            hr.GetXaxis().SetTitleOffset(h.GetXaxis().GetTitleOffset() /
                                         ytp_ratio)

            hr.GetYaxis().SetLabelSize(h.GetYaxis().GetLabelSize() * xtp_ratio)
            hr.GetXaxis().SetLabelSize(h.GetXaxis().GetLabelSize() * ytp_ratio)

            h.GetXaxis().SetLabelColor(0)
            h.GetXaxis().SetLabelSize(0)
            padr.Update()

        # blinding
        if blindxmin or blindxmax:
            pad.cd()
            max = plot.stack.totalHist.GetMaximum()
            box = TBox(blindxmin, 0, blindxmax, max)
            box.SetFillColor(1)
            box.SetFillStyle(3004)
            box.Draw()
            HistDrawer.keeper.append(box)

        HistDrawer.CMSPrelim(plot, pad, channel, legend=plot.legendPos)
        can.cd()

        gErrorIgnoreLevel = kWarning
        h.GetYaxis().SetRangeUser(0, pad.GetUymax() * 1.)
        plotname = plot_name if plot_name else plot.name

        if ('dz' in plotname) or ('logx' in plotname):
            pad.SetLogx(True)
            try:
                padr.SetLogx(True)
            except:
                pass

        if not os.path.exists(plot_dir + '/pdf/'):
            os.mkdir(plot_dir + '/pdf/')
            os.mkdir(plot_dir + '/pdf/linear/')
            os.mkdir(plot_dir + '/pdf/log/')
        if not os.path.exists(plot_dir + '/root/'):
            os.mkdir(plot_dir + '/root/')
            os.mkdir(plot_dir + '/root/linear/')
            os.mkdir(plot_dir + '/root/log')
        if not os.path.exists(plot_dir + '/png/'):
            os.mkdir(plot_dir + '/png/')
            os.mkdir(plot_dir + '/png/linear/')
            os.mkdir(plot_dir + '/png/log/')
        if not os.path.exists(plot_dir + '/datacards/'):
            os.mkdir(plot_dir + '/datacards/')
        can.SaveAs(plot_dir + '/pdf/linear/' + plotname + '.pdf')
        can.SaveAs(plot_dir + '/root/linear/' + plotname + '.root')
        can.SaveAs(plot_dir + '/png/linear/' + plotname + '.png')

        if server == "starseeker":
            if dataset == '2017':
                t3_dir = '/home/dehuazhu/t3work/3_figures/1_DataMC/FinalStates/' + channel_dir + '/' + region.name
            if dataset == '2018':
                t3_dir = '/home/dehuazhu/t3work/3_figures/1_DataMC/FinalStates/2018/' + channel_dir + '/' + region.name
            can.SaveAs(t3_dir + '/pdf/linear/' + plotname + '.pdf')
            can.SaveAs(t3_dir + '/root/linear/' + plotname + '.root')
            can.SaveAs(t3_dir + '/png/linear/' + plotname + '.png')

        # Also save with log y
        h.GetYaxis().SetRangeUser(pad.GetUymax() * 5. / 1000000.,
                                  pad.GetUymax() * 1000.)
        pad.SetLogy(True)
        can.SaveAs(plot_dir + '/png/log/' + plotname + '_log.png')
        can.SaveAs(plot_dir + '/root/log/' + plotname + '_log.root')
        can.SaveAs(plot_dir + '/pdf/log/' + plotname + '_log.pdf')
        if server == "starseeker":
            can.SaveAs(t3_dir + '/pdf/log/' + plotname + '_log.pdf')
            can.SaveAs(t3_dir + '/root/log/' + plotname + '_log.root')
            can.SaveAs(t3_dir + '/png/log/' + plotname + '_log.png')
        pad.SetLogy(0)
        # if 'dz' in plotname:
        if ('dz' in plotname) or ('logx' in plotname):
            pad.SetLogx(False)
            try:
                padr.SetLogx(False)
            except:
                pass
Exemplo n.º 26
0
def pullsVertical_noBonly(fileName):

    content = filterPullFile(fileName)
    nbins, off = len(content), 0.10

    # Graphs
    h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins)
    S_pulls = TGraphAsymmErrors(nbins)

    boxes = []

    canvas = TCanvas("canvas", "Pulls", 720, 300 + nbins * 18)  #nbins*20)
    canvas.cd()
    canvas.SetGrid(0, 1)
    canvas.SetTopMargin(0.01)
    canvas.SetRightMargin(0.01)
    canvas.SetBottomMargin(0.10)
    canvas.SetLeftMargin(0.40)
    canvas.SetTicks(1, 1)

    for i, s in enumerate(content):
        l = s.split()
        h_pulls.GetYaxis().SetBinLabel(i + 1, l[0])
        S_pulls.SetPoint(i, float(l[3]), float(i + 1) - 0.5)
        S_pulls.SetPointError(i, float(l[4]), float(l[4]), 0., 0.)

    h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta")
    h_pulls.GetXaxis().SetLabelOffset(0.0)
    h_pulls.GetXaxis().SetTitleOffset(0.8)
    h_pulls.GetXaxis().SetLabelSize(0.045)
    h_pulls.GetXaxis().SetTitleSize(0.050)
    h_pulls.GetYaxis().SetLabelSize(0.046)
    h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0)

    S_pulls.SetFillColor(kBlack)
    S_pulls.SetLineColor(kBlack)
    S_pulls.SetMarkerColor(kBlack)
    S_pulls.SetLineWidth(2)
    S_pulls.SetMarkerStyle(20)
    S_pulls.SetMarkerSize(1)

    box1 = TBox(-1., 0., 1., nbins)
    #box1.SetFillStyle(3001) # 3001 checkered
    #box1.SetFillStyle(0)
    box1.SetFillColor(kGreen + 1)  # 417
    box1.SetLineWidth(2)
    box1.SetLineStyle(2)
    box1.SetLineColor(kGreen + 1)  # 417

    box2 = TBox(-2., 0., 2., nbins)
    #box2.SetFillStyle(3001) # 3001 checkered
    #box2.SetFillStyle(0)
    box2.SetFillColor(kOrange)  # 800
    box2.SetLineWidth(2)
    box2.SetLineStyle(2)
    box2.SetLineColor(kOrange)  # 800

    leg = TLegend(0.01, 0.01, 0.3, 0.15)
    leg.SetTextSize(0.05)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    #leg.SetNColumns(2)
    leg.AddEntry(S_pulls, "S+B fit", "lp")
    if text: leg.AddEntry(0, text, "")

    h_pulls.Draw("")
    box2.Draw()
    box1.Draw()
    S_pulls.Draw("P6SAME")
    leg.Draw()
    canvas.RedrawAxis()

    canvas.Print(outName + ".png")
    canvas.Print(outName + ".pdf")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Exemplo n.º 27
0
def xi_matching(sector):
    c = Canvas("c")
    c.cd()
    c.SetTicks(1,1)

    gr = ROOT.TGraphErrors('gr')
    gr_m = ROOT.TGraphErrors('gr_m')
    gr.SetName('gr')
    gr_m.SetName('gr_m')
    x, y = ROOT.Double(0), ROOT.Double(0)
    for i, year in enumerate(years):

        g = getGraph(year,'xi'+sector)
        n_grm = gr_m.GetN() if i > 0 else 0
        n_gr = gr.GetN() if i > 0 else 0
        for j in range(g.GetN()):
            g.GetPoint(j,x,y)
            ex = g.GetErrorX(j) # FIXME?
            ey = g.GetErrorY(j)
            diff = abs(y-x)
            if diff < 0.003:
            #if diff < 0.02 * x: # only using relative PPS xi error
                gr_m.SetPoint(n_grm+j,x,y) 
                gr_m.SetPointError(n_grm+j,ex,ey)
            else:
                gr.SetPoint(n_gr+j,x,y) 
                gr.SetPointError(n_gr+j,ex,ey)
 

    gr.SetMarkerSize(0.6)
    gr.SetMarkerStyle(24)
    gr_m.SetMarkerSize(0.6)
    gr_m.SetMarkerStyle(24) 
    gr_m.SetMarkerColor(ROOT.kRed)
    gr_multi = ROOT.TMultiGraph('gr_multi','')
    gr_multi.Add(gr,'AP')
    gr_multi.Add(gr_m,'AP')
    c.SetGrid()
    min, max = 0.0001, 0.25
    c.DrawFrame(min,min,max,max)
    gr_multi.Draw()
    gr_multi.GetXaxis().SetTitleOffset(1.3)
    gr_multi.GetYaxis().SetTitleOffset(1.3)
    if sector == 'm':
        gr_multi.GetXaxis().SetTitle("#xi(p)"+"^{-}")
        gr_multi.GetYaxis().SetTitle("#xi(#gamma#gamma)"+"^{-}")
    elif sector == 'p':
        gr_multi.GetXaxis().SetTitle("#xi(p)"+"^{+}")
        gr_multi.GetYaxis().SetTitle("#xi(#gamma#gamma)"+"^{+}")
    
    # Draw y = x line
    l = TLine(min, min, max, max)
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    l.Draw()

    # Draw shaded region for no acceptance
    b = TBox(min, min, 0.015, max)
    b.SetFillStyle(3001)
    b.SetFillColor(ROOT.kGray)
    b.SetLineColor(1)
    b.Draw()

    # Make legend
    legend = TLegend(0.65,0.45,0.8,0.6)
    legend.SetBorderSize(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.038)
    legend.AddEntry(b,"No acceptance",'f')
    legend.AddEntry(gr,"Not matching",'p')
    legend.AddEntry(gr_m,"Matching at 2#sigma",'p')
    legend.Draw()

    pLabel, sLabel, lLabel = prelimLabel(), selectionLabel("Tight #xi selection"), lumiLabel()
    pLabel.Draw(), sLabel.Draw(), lLabel.Draw()
    #c.SaveAs("plots/matching/xi"+sector+"_matching_"+s_years+".pdf")
    c.SaveAs("plots/matching/xi%s_matching_%s.%s" % (sector,s_years,extension))