Ejemplo n.º 1
0
        if sample == 'data' and region == 'SR':
            continue

        sel = getattr(regions_, region)
        
        
        histograms[0].GetXaxis().SetBinLabel(iregion+1, region)


        print region
        for idx, ver in enumerate(versions):
            evts = get_events(sample, selection=sel, version=ver, scale=False)
            print ver, evts
            histograms[idx].SetBinContent(iregion+1, evts.mean)

            set_style(histograms[idx], msize=1, lwidth=2, color=colors[idx])


    # Plot
    c = ROOT.TCanvas()

    cup   = ROOT.TPad("u", "u", 0., 0.305, 0.99, 1)
    cdown = ROOT.TPad("d", "d", 0., 0.01, 0.99, 0.295)

    cup.SetLogy()
        
    cup.SetFillColor(0);
    cup.SetBorderMode(0);
    cup.SetBorderSize(2);
    cup.SetTicks()
    cup.SetTopMargin   ( 0.1 );
Ejemplo n.º 2
0
        sel = getattr(regions_, region)

        histograms[0].GetXaxis().SetBinLabel(iregion + 1, region)

        print region
        print '-----'
        for idx, ver in enumerate(versions):
            evts = get_events(sample,
                              selection=sel,
                              version=ver,
                              scale=args.scale,
                              lumi='data')
            print ver, evts
            histograms[idx].SetBinContent(iregion + 1, evts.mean)

            set_style(histograms[idx], msize=1, lwidth=2, color=colors[idx])

    # Plot
    c = ROOT.TCanvas()

    cup = ROOT.TPad("u", "u", 0., 0.305, 0.99, 1)
    cdown = ROOT.TPad("d", "d", 0., 0.01, 0.99, 0.295)

    cup.SetLogy()

    cup.SetFillColor(0)
    cup.SetBorderMode(0)
    cup.SetBorderSize(2)
    cup.SetTicks()
    cup.SetTopMargin(0.1)
    cup.SetRightMargin(0.05)
Ejemplo n.º 3
0
    h_yields_norm.SetBinContent(counter, norm_yield)
    h_yields_norm.SetBinError(counter, error / lumi)

    print run, norm_yield

    # avgmu
    htemp = ROOT.TH1D('avgmu_%i' % run, 'avgmu', 50, 0., 50.)
    tree.Project('avgmu_%i' % run, 'avgmu', selection)

    h_avgmu.SetBinContent(counter, htemp.GetMean())

    counter += 1

set_atlas_style()

set_style(h_yields_norm, color=ROOT.kBlack, lwidth=1)
set_style(h_avgmu, color='pink', lwidth=1, alpha=0.5)

c = ROOT.TCanvas('', '', 2400, 600)

c.SetFillColor(0)
c.SetBorderMode(0)
c.SetBorderSize(2)
c.SetTicks(0, 1)
c.SetTickx(0)
c.SetTopMargin(0.03)
c.SetRightMargin(0.02)
c.SetLeftMargin(0.05)
c.SetBottomMargin(0.1)

h_yields_norm.GetYaxis().SetTitle('yield per pb^{-1}')
Ejemplo n.º 4
0
    print run, norm_yield

    # avgmu
    htemp = ROOT.TH1D('avgmu_%i' % run, 'avgmu', 50, 0., 50.)
    tree.Project('avgmu_%i' % run, 'avgmu', selection)

    h_avgmu.SetBinContent(counter, htemp.GetMean())
    

    counter += 1


set_atlas_style()

set_style(h_yields_norm, color=ROOT.kBlack, lwidth=1)
set_style(h_avgmu,   color='pink', lwidth=1, alpha=0.5)

c = ROOT.TCanvas('', '', 2400, 600)

c.SetFillColor(0)
c.SetBorderMode(0)
c.SetBorderSize(2)
c.SetTicks(0,1)
c.SetTickx(0)
c.SetTopMargin  (0.03)
c.SetRightMargin(0.02)
c.SetLeftMargin (0.05)
c.SetBottomMargin  (0.1)

h_yields_norm.GetYaxis().SetTitle('yield per pb^{-1}')
    h_corr.SetMarkerSize(1.1);
elif(num_pars<20):
    h_corr.SetMarkerSize(0.85);
elif(num_pars<40):
    h_corr.SetMarkerSize(0.5);
else:
    h_corr.SetMarkerSize(0.25);

if   num_pars<5:    labelSize = 0.05
elif num_pars<10:   labelSize = 0.04
elif num_pars<20:   labelSize = 0.028
elif num_pars<40:   labelSize = 0.02
else:               labelSize = 0.015

h_corr.GetXaxis().SetLabelSize(labelSize)
h_corr.GetYaxis().SetLabelSize(labelSize)
h_corr.GetXaxis().LabelsOption("v")

h_corr.SetContour(999)
h_corr.GetZaxis().SetRangeUser(-1, 1)
h_corr.GetZaxis().SetLabelSize(labelSize)
h_corr.GetZaxis().SetLabelOffset(0.01)

set_style(h_corr)

h_corr.Draw("colz");
h_corr.Draw("textsame");

c_corr.SaveAs(args.output)

Ejemplo n.º 6
0
def do_plot(plotname,
            variable,
            data={}, bkg={}, signal={},
            do_bkg_total=True,
            do_ratio=True,
            region_name='',
            ratio_type='',
            normalize=False,
            do_fit=False,
            logy=True,
            big_label=False,
            extensions=['pdf',],
            region_line=None,
            atlas_label='',
            data_label=''):

    if data is None:
        data = {}
    if signal is None:
        signal = {}
    if bkg is None:
        bkg = {}


    conf = get_plotconf(variable)

    xtitle, ytitle, legpos = conf['xtitle'], conf['ytitle'], conf['legpos']

    if not logy:
        logy = False
    else:
        logy = conf['logy']

    logx = conf['logx']

    can = ROOT.TCanvas('', '', 800, 800)
    can.cd()

    margin_l = 0.11
    margin_r = 0.03
    margin_b = 0.35
    margin_t = 0.05

    can.SetBottomMargin(margin_b)
    can.SetTopMargin(margin_t)
    can.SetLeftMargin(margin_l)
    can.SetRightMargin(margin_r)

    def calc_size(pad):
        pad_width  = pad.XtoPixel(pad.GetX2())
        pad_height = pad.YtoPixel(pad.GetY1())

        if pad_width < pad_height:
            tsize = 28.6 / pad_width
        else:
            tsize = 28.6 / pad_height
        return tsize

    if do_ratio:

        cup   = ROOT.TPad("u", "u", 0., 0.305, 0.99, 1)
        cdown = ROOT.TPad("d", "d", 0., 0.01, 0.99, 0.295)
        # cup.SetRightMargin(0.05)
        # cup.SetBottomMargin(0.005)
        # cup.SetLeftMargin(0.12)
        cup.SetTickx()
        cup.SetTicky()
        cdown.SetTickx()
        cdown.SetTicky()
        # cdown.SetRightMargin(0.05)
        # cdown.SetTopMargin(0.0054)
        # cdown.SetLeftMargin(0.12)
        # cdown.SetBottomMargin(cdown.GetBottomMargin()*1.1)

        cup.SetBottomMargin(0.005)
        cup.SetRightMargin (margin_r)
        cup.SetLeftMargin  (margin_l)
        cup.SetTopMargin   (margin_t)

        cdown.SetTickx()
        cdown.SetTicky()
        cdown.SetTopMargin   (0.0054)
        cdown.SetRightMargin (margin_r)
        cdown.SetLeftMargin  (margin_l)
        cdown.SetBottomMargin(margin_b)

        cup.Draw()
        cdown.Draw()

        if logy:
            cup.SetLogy()
        if logx:
            cup.SetLogx()
            cdown.SetLogx()

        cup.SetTopMargin(0.08)
        cdown.SetBottomMargin(0.35)

        up_size = calc_size(cup)
        dn_size = calc_size(cdown)

    else:
        if logy:
            can.SetLogy()
        if logx:
            can.SetLogx()

        can.SetTicks(1, 1)
        can.SetLeftMargin(0.12)
        can.SetBottomMargin(0.1)
        can.SetRightMargin(0.04)
        can.SetTopMargin(0.04)

        up_size = calc_size(can)
        dn_size = calc_size(can)


    if big_label:
        up_size *= 1.2
        dn_size *= 1.2

    # configure histograms
    if data:
        set_style(data, msize=1, lwidth=2, color=ROOT.kBlack)

    if bkg:
        for name, hist in bkg.iteritems():
            set_style(hist, color=colors_dict[name], fill=True)
            hist.SetLineWidth(1)
            hist.SetLineColor(ROOT.kBlack)

    if signal:
        for sig, hist in signal.iteritems():
            set_style(hist, msize=1.2, lwidth=2, lstyle=2, color=colors_dict[sig])

    # bkg stack
    if bkg:
        sm_stack = ROOT.THStack()

        def _compare(a, b):
            amax = a.GetMaximum()
            bmax = b.GetMaximum()
            return cmp(int(amax), int(bmax))

        for hist in sorted(bkg.itervalues(), _compare):
            sm_stack.Add(hist)


        # Total background
        sm_total = None
        sm_totalerr = None
        sm_total_style = 3354
        sm_total_color = ROOT.kGray+3

        sm_stat_color = ROOT.kGray+1
        sm_syst_color = ROOT.kGray+3

        sm_total = sm_stack.GetStack().Last().Clone('sm_total')
        sm_total_stat = sm_total.Clone()

        if sm_total is not None:
            sm_total.SetLineWidth(2)
            sm_total.SetLineColor(sm_total_color)
            sm_total.SetFillColor(0)
            sm_total.SetMarkerSize(0)

            sm_total_stat.SetFillColor(sm_total_color)
            sm_total_stat.SetLineColor(sm_total_color)
            sm_total_stat.SetFillStyle(sm_total_style)
            sm_total_stat.SetLineWidth(2)
            sm_total_stat.SetMarkerSize(0)


    # we don't want to plot signals in Control Regions
    if 'CR' in region_name:
        signal = {}

    if do_ratio:
        cup.cd()

    # first histogram to configure (ROOT de mierda)
    if bkg:
        sm_stack.Draw('hist')
        chist = sm_stack
    elif data:
        chist = data
    else:
        for name, hist in signal.iteritems():
            break
        chist = signal[name]

    if conf['xmin'] is not None and conf['xmax'] is not None:
        chist.GetXaxis().SetRangeUser(conf['xmin'], conf['xmax'])

    if chist.GetXaxis().GetXmax() < 5.:
        chist.GetXaxis().SetNdivisions(512)
    else:
        chist.GetXaxis().SetNdivisions(508)

    if do_ratio:
        cup.RedrawAxis()
    else:
        can.RedrawAxis()

    if logy:
        chist.SetMinimum(0.015)

        ymax = chist.GetMaximum()
        if 'dphi' in variable:
            chist.SetMaximum(ymax*100)
        else:
            chist.SetMaximum(ymax*100)
    else:
        if data:
            ymax = max(chist.GetMaximum(), data.GetMaximum())
        elif signal:
            tmpmax = chist.GetMaximum()
            for hsig in signal.itervalues():
                tmpmax = max(tmpmax, hsig.GetMaximum())
            ymax = tmpmax
        else:
            ymax = chist.GetMaximum()

        chist.SetMaximum(ymax*1.4)


    if big_label:
        y_offset = 1.1
        x_offset = 1.
    else:
        y_offset = 0.9
        x_offset = 1.

    # x-axis
    if do_ratio:
        chist.GetXaxis().SetLabelSize(0.)
        chist.GetXaxis().SetTitleSize(0.)
    else:
        chist.GetXaxis().SetTitle(xtitle)
        chist.GetXaxis().SetTitleOffset(x_offset)
        chist.GetXaxis().SetLabelSize(up_size)
        chist.GetXaxis().SetTitleSize(up_size)

    # y-axis
    if 'BIN' in ytitle:
        if bkg:
            width = sm_total.GetBinWidth(1)
        else:
            width = chist.GetBinWidth(1)

        if width > 10:
            ytitle = ytitle.replace('BIN', '{:.0f}'.format(width))
        else:
            ytitle = ytitle.replace('BIN', '{:.2f}'.format(width))

    chist.GetYaxis().SetTitle(ytitle)
    chist.GetYaxis().SetLabelSize(up_size)
    chist.GetYaxis().SetTitleSize(up_size)
    chist.GetYaxis().SetTitleOffset(y_offset)



    if data:
        g_data = make_poisson_cl_errors(data)

        g_data.SetMarkerStyle(20)
        g_data.SetMarkerSize(1.2)
        g_data.SetLineWidth(2)
        g_data.SetLineColor(ROOT.kBlack)
        g_data.SetMarkerColor(ROOT.kBlack)

        g_data.Draw('P0Z')

    if bkg and sm_total is not None:
        sm_total.Draw("histsame")
        sm_total_stat.Draw("E2same][")

    for h in signal.itervalues():
        h.Draw('histsame')

    if data:
        g_data.Draw('P0Z')

    if do_ratio:
        cup.RedrawAxis()
    else:
        can.RedrawAxis()

    # legend
    legxmin, legxmax = 0.6, 0.88
    legymin, legymax = 0.6, 0.88
    if do_ratio:
        legymin = 0.64
        legymax = 0.88

        if legpos == 'left' or legpos == 'top':
            legxmin = 0.13
            legxmax = 0.57
        elif legpos == 'right':
            legxmin = 0.50
            legxmax = 0.94
    else:
        legymin = 0.80
        legymax = 0.92

        if legpos == 'left' or legpos == 'top':
            legxmin = 0.15
            legxmax = 0.53
        elif legpos == 'right':
            legxmin = 0.65
            legxmax = 0.92

    legend1 = ROOT.TLegend(legxmin, legymin, legxmax, legymax)
    legend1.SetFillColor(0)
    legend1.SetBorderSize(0)
    legend1.SetNColumns(2)
    legend1.SetTextFont(42)
    legend1.SetTextSize(legend1.GetTextSize()*0.8)
    if signal:
        if legpos == 'top':
            if data:
                legend2 = ROOT.TLegend(legxmax+0.02, legymin+0.1, legxmax+0.39, legymax)
            else:
                legend2 = ROOT.TLegend(legxmax+0.02, legymin, legxmax+0.39, legymax)
        else:
            if data:
                legend2 = ROOT.TLegend(legxmin-0.01, legymin-.15, legxmax-0.01, legymin -.01)
            else:
                legend2 = ROOT.TLegend(legxmin-0.01, legymin-.20, legxmax-0.01, legymin -.01)

        legend2.SetFillColor(0)
        legend2.SetBorderSize(0)
        legend2.SetTextFont(42)
        legend2.SetTextSize(legend1.GetTextSize())

    if bkg:
        for name, hist in bkg.iteritems():
            legend1.AddEntry(hist, labels_dict[name], 'f')

        if do_bkg_total and sm_total is not None:
            legend1.AddEntry(sm_total_stat, "SM Total", 'lf')

    if data:
        legend1.AddEntry(g_data, labels_dict['data'], 'ep')

    if signal:
        for name, hist in signal.iteritems():
            legend2.AddEntry(hist, labels_dict[name], 'f')

    legend1.Draw()
    if signal:
        legend2.Draw()

    # ATLAS/data labels
    if data:
        text = data_label
        t = ROOT.TLatex(0, 0, text)
        t.SetNDC()
        t.SetTextFont(42)
        t.SetTextSize(0.045)
        t.SetTextColor(ROOT.kBlack)

        if legpos == 'top' and signal:
            t.DrawLatex(0.58, 0.66, data_label)
        else:
            if legpos == 'right':
                t.DrawLatex(0.15, 0.76, data_label)
            else:
                t.DrawLatex(0.60, 0.76, data_label)

    # Region line
    # if region_line is not None:

        # xline = float(region_line)

    # l = ROOT.TLine(200, 0.01, 200, data.GetMaximum())
    # l.SetLineWidth(2)
    # l.SetLineStyle(2)
    # l.Draw()

    # l2 = ROOT.TArrow(200, data.GetMaximum(), 240, data.GetMaximum())
    # l2.SetLineWidth(2)
    # l2.SetLineStyle(2)
    # l2.Draw()


    ratio_ylabel_size = dn_size
    ratio_ytitle_size = dn_size

    ratio_xlabel_size = dn_size
    ratio_xtitle_size = dn_size

    if do_ratio and data and bkg and ratio_type == 'significance':

        ratio = data.Clone()

        cdown.cd()
        ratio.SetTitle('')
        ratio.SetStats(0)
        ratio.SetMarkerStyle(20)
        ratio.SetMarkerSize(1)
        ratio.SetLineWidth(2)
        ratio.SetLineColor(ROOT.kBlack)
        ratio.SetMarkerColor(ROOT.kBlack)
        ratio.SetFillColor(ROOT.kGray)

        # x axis
        ratio.GetXaxis().SetTitle(xtitle)
        if conf.xmin is not None and conf.xmax is not None:
            ratio.GetXaxis().SetRangeUser(conf.xmin, conf.xmax)
        ratio.GetXaxis().SetLabelSize(ratio_xlabel_size)
        ratio.GetXaxis().SetTitleSize(ratio_xtitle_size)
        ratio.GetXaxis().SetTitleOffset(x_offset)
        ratio.GetXaxis().SetLabelOffset(0.03)
        ratio.GetXaxis().SetTickLength(0.06)

        if ratio.GetXaxis().GetXmax() < 5.:
            ratio.GetXaxis().SetNdivisions(512)
        else:
            ratio.GetXaxis().SetNdivisions(508)

        # y axis
        ratio.GetYaxis().SetTitle('Significance')
        ratio.GetYaxis().SetLabelSize(ratio_ylabel_size)
        ratio.GetYaxis().SetTitleSize(ratio_ytitle_size)
        ratio.GetYaxis().SetRangeUser(-5, 5)
        ratio.GetYaxis().SetNdivisions(504)
        ratio.GetYaxis().SetTitleOffset(0.5)
        ratio.GetYaxis().SetLabelOffset(0.01)

        for bx in xrange(ratio.GetNbinsX()):

            obs = data.GetBinContent(bx+1)

            if model is None:
                exp = sm_total.GetBinContent(bx+1)
            else:
                x = ratio.GetBinCenter(bx+1)
                if x < model.GetXmin() or x > model.GetXmax():
                    exp = obs
                else:
                    exp = model.Eval(x)

            z = poisson_significance(obs, exp)
            ratio.SetBinContent(bx+1, z)

        ratio.Draw('e0')

        firstbin = ratio.GetXaxis().GetFirst()
        lastbin  = ratio.GetXaxis().GetLast()
        xmax     = ratio.GetXaxis().GetBinUpEdge(lastbin)
        xmin     = ratio.GetXaxis().GetBinLowEdge(firstbin)

        lines = [None, None, None]

        lines[0] = ROOT.TLine(xmin,  0., xmax,  0.)
        lines[1] = ROOT.TLine(xmin, -3., xmax, -3.)
        lines[2] = ROOT.TLine(xmin,  3., xmax,  3.)

        lines[0].SetLineWidth(1)
        lines[0].SetLineStyle(2)
        lines[1].SetLineStyle(3)
        lines[2].SetLineStyle(3)

        lines[0].Draw()
        lines[1].Draw()
        lines[2].Draw()
        ratio.Draw('e0 same')

        ratio.GetYaxis().SetLabelSize(0.)

        x = xmin - ratio.GetBinWidth(1)
        t = ROOT.TLatex()
        t.SetTextSize(0.12)
        t.SetTextAlign(32)
        t.SetTextAngle(0);

        y = ratio.GetYaxis().GetBinCenter(3)
        t.DrawLatex(x, y+0.5, '3')

        y = ratio.GetYaxis().GetBinCenter(-3)
        t.DrawLatex(x, y+0.5, '-3')


    elif do_ratio and data and bkg:

        ratio = g_data.Clone()
        for b in xrange(ratio.GetN()):
            x = ROOT.Double(0.)
            y = ROOT.Double(0.)
            ratio.GetPoint(b, x, y)

            sm_y = sm_total.GetBinContent(sm_total.FindBin(x))

            exl = ratio.GetErrorXlow(b)
            exh = ratio.GetErrorXhigh(b)

            eyl = ratio.GetErrorYlow(b)
            eyh = ratio.GetErrorYhigh(b)

            try:
                ratio_y   = y/sm_y
                ratio_eyl = eyl/sm_y
                ratio_eyh = eyh/sm_y
            except:
                ratio_y   = 0.
                ratio_eyl = 0.
                ratio_eyh = 0.

            ratio.SetPoint(b, x, ratio_y)
            ratio.SetPointError(b, exl, exh, ratio_eyl, ratio_eyh)

        # remove the point from the plot if zero
        # for b in xrange(ratio.GetNbinsX()):
        #     if ratio.GetBinContent(b+1) < 0.00001:
        #         ratio.SetBinContent(b+1, -1)

        #ratio = make_poisson_cl_errors(ratio)
        set_style(ratio, msize=1, lwidth=2, color=ROOT.kBlack)

        cdown.cd()
        if conf['xmin'] is not None and conf['xmax'] is not None:
            frame = cdown.DrawFrame(conf['xmin'], 0., conf['xmax'], 2.2)
        else:
            frame = cdown.DrawFrame(chist.GetXaxis().GetXmin(), 0., chist.GetXaxis().GetXmax(), 2.2)

        ratio.SetTitle('')
        ratio.SetMarkerStyle(20)
        ratio.SetMarkerSize(1)
        ratio.SetLineWidth(2)
        ratio.SetLineColor(ROOT.kBlack)
        ratio.SetMarkerColor(ROOT.kBlack)

        # x axis
        frame.GetXaxis().SetTitle(xtitle)
        frame.GetXaxis().SetLabelSize(ratio_xlabel_size)
        frame.GetXaxis().SetTitleSize(ratio_xtitle_size)
        frame.GetXaxis().SetTitleOffset(1.1)
        frame.GetXaxis().SetLabelOffset(0.03)
        frame.GetXaxis().SetTickLength(0.06)

        if conf['xmin'] is not None and conf['xmax'] is not None:
            ratio.GetXaxis().SetRangeUser(conf['xmin'], conf['xmax'])

        if frame.GetXaxis().GetXmax() < 5.:
            frame.GetXaxis().SetNdivisions(512)
        else:
            frame.GetXaxis().SetNdivisions(508)

        # y axis
        frame.GetYaxis().SetTitle('Data / SM')
        frame.GetYaxis().CenterTitle()
        frame.GetYaxis().SetLabelSize(ratio_ylabel_size)
        frame.GetYaxis().SetTitleSize(ratio_ytitle_size)
        frame.GetYaxis().SetRangeUser(0, 2.2)
        frame.GetYaxis().SetNdivisions(504)
        frame.GetYaxis().SetTitleOffset(0.35)
        frame.GetYaxis().SetLabelOffset(0.01)

        err_band_stat = ROOT.TGraphAsymmErrors(sm_total.GetNbinsX())

        for b in xrange(1,sm_total.GetNbinsX()+1):

            x    = sm_total.GetBinCenter(b)
            xerr = 0.5*sm_total.GetBinWidth(b)

            sm_y = sm_total.GetBinContent(b)

            sm_stat_high = sm_total_stat.GetBinError(b)
            sm_stat_low  = sm_total_stat.GetBinError(b)

            try:
                stat_low  = sm_stat_low/sm_y
            except ZeroDivisionError:
                stat_low = 0.0

            try:
                stat_high = sm_stat_high/sm_y
            except ZeroDivisionError:
                stat_high = 0.0

            err_band_stat.SetPoint(b-1, x, 1.)
            err_band_stat.SetPointError(b-1, xerr, xerr, stat_low, stat_high)


        err_band_stat.SetLineWidth(2)
        err_band_stat.SetMarkerSize(0)
        err_band_stat.SetFillStyle(sm_total_style)
        err_band_stat.SetLineColor(sm_total_color)
        err_band_stat.SetFillColor(sm_total_color)

        if conf['xmin'] is not None and conf['xmax'] is not None:
            xmin, xmax = conf['xmin'], conf['xmax']
        else:
            firstbin = hist.GetXaxis().GetFirst()
            lastbin  = hist.GetXaxis().GetLast()
            xmax     = hist.GetXaxis().GetBinUpEdge(lastbin)
            xmin     = hist.GetXaxis().GetBinLowEdge(firstbin)

        draw_ratio_lines(xmin, xmax)
        err_band_stat.Draw('P2same')
        ratio.Draw('P0Z')


    # S/B significance as a function of cut in plotted variable
    elif do_ratio and signal and bkg:
        cdown.cd()

        names = []
        ratio_z = []
        for name in signal.iterkeys():
            names.append(name)
            ratio_z.append(histogram_equal_to(sm_total))

        # remove the point from the plot if zero
        max_bins = ratio_z[0].GetNbinsX()
        for bx in xrange(1, max_bins+1):

            imin = bx
            imax = max_bins

            b = sm_total.Integral(imin, imax)

            for i, name in enumerate(names):

                s = signal[name].Integral(imin, imax)

                z = get_significance(s, b, 0.3)

                ratio_z[i].SetBinContent(bx, z)

        for i, name in enumerate(names):
            set_style(ratio_z[i], msize=1.2, lwidth=2, lstyle=2, color=colors_dict[name])


        # x-axis
        ratio_z[0].GetXaxis().SetTitle(xtitle)
        if conf.xmin is not None and conf.xmax is not None:
            ratio_z[0].GetXaxis().SetRangeUser(conf.xmin, conf.xmax)
        ratio_z[0].GetXaxis().SetLabelSize(ratio_xlabel_size)
        ratio_z[0].GetXaxis().SetTitleSize(ratio_xtitle_size)
        ratio_z[0].GetXaxis().SetTitleOffset(x_offset)
        ratio_z[0].GetXaxis().SetLabelOffset(0.03)
        ratio_z[0].GetXaxis().SetTickLength(0.06)

        # if ratio_z[0].GetXaxis().GetXmax() < 5.:
        #     ratio_z[0].GetXaxis().SetNdivisions(512)
        # else:
        #     ratio_z[0].GetXaxis().SetNdivisions(508)

        # y-axis
        cdown.SetGridy()
        ratio_z[0].GetYaxis().SetTitle('Significance')
        ratio_z[0].GetYaxis().SetLabelSize(ratio_ylabel_size)
        ratio_z[0].GetYaxis().SetTitleSize(ratio_ytitle_size)
        ratio_z[0].GetYaxis().SetNdivisions(508)
        ratio_z[0].GetYaxis().SetTitleOffset(y_offset*0.4)
        ratio_z[0].GetYaxis().SetLabelOffset(0.01)

        zmax = 0
        for ratio in ratio_z:
            if ratio.GetMaximum() > zmax:
                zmax = ratio.GetMaximum()

        ratio_z[0].GetYaxis().SetRangeUser(0, zmax+0.5)
        ratio_z[0].Draw()
        for ratio in ratio_z[1:]:
            ratio.Draw('same')


    # Save plot
    output_name = fix_output_name(plotname)
    for ext in extensions:
        can.SaveAs(output_name+'.'+ext)
Ejemplo n.º 7
0
def do_pull_plot(output_name, h_obs, h_exp, h_bkg_dict, atlas_label='', data_label='', max_pull=3.0, plot_significance=False):

    g_obs = make_poisson_cl_errors(h_obs)

    ## bkg stack
    stack = ROOT.THStack("stack", "stack")

    def _compare(a, b):
        amax = a.GetMaximum()
        bmax = b.GetMaximum()
        return cmp(int(amax), int(bmax))

    for hist in sorted(h_bkg_dict.itervalues(), _compare):
        stack.Add(hist)

    h_bkg_total = h_exp.Clone()

    # Compute uncertainties and pulls
    pulls = []
    for b in xrange(1, h_obs.GetNbinsX()+1):

        n_obs = h_obs.GetBinContent(b)
        n_exp = h_exp.GetBinContent(b)

        exp_syst = h_exp.GetBinError(b)

        exp_stat = 0
        exp_stat_up = 0
        exp_stat_dn = 0
        if n_exp > 0:
            exp_stat = ROOT.TMath.Sqrt(n_exp)
            exp_stat_up, exp_stat_dn = get_poisson_error(n_exp)

        exp_total = 0
        exp_total_up = 0
        exp_total_dn = 0

        exp_total    = ROOT.TMath.Sqrt(exp_stat*exp_stat + exp_syst*exp_syst)
        exp_total_up = ROOT.TMath.Sqrt(exp_stat_up*exp_stat_up + exp_syst*exp_syst)
        exp_total_dn = ROOT.TMath.Sqrt(exp_stat_dn*exp_stat_dn + exp_syst*exp_syst)

        if plot_significance:
            pvalue = pvalue_poisson_error(int(n_obs), n_exp, exp_syst*exp_syst)

            if pvalue < 0.5:
                pull = pvalue_to_significance(pvalue, (n_obs > n_exp))
            else:
                pull = 0.0001

        else:
            pull = 0
            if (n_obs - n_exp) > 0 and exp_total_up != 0:
                pull = (n_obs - n_exp)/exp_total_up
            if (n_obs - n_exp) <= 0 and exp_total_dn != 0:
                pull = (n_obs - n_exp)/exp_total_dn

            if -0.02 < pull < 0:
                pull = -0.02 ###ATT: ugly
            if 0 < pull < 0.02:
                pull = 0.02 ###ATT: ugly

            if n_obs < 0.0001:
                pull = 0.


        pulls.append(pull)


    ROOT.gStyle.SetOptStat(0000)


    # Plot
    c = ROOT.TCanvas("c",'', 1200, 600);

    c.SetFrameFillColor(ROOT.kWhite)

    cup   = ROOT.TPad("u", "u", 0., 0.305, 0.99, 1)
    cdown = ROOT.TPad("d", "d", 0., 0.01, 0.99, 0.295)

    cup.SetLogy()

    cup.SetFillColor(0)
    cup.SetBorderMode(0)
    cup.SetBorderSize(2)
    cup.SetTicks()
    cup.SetTopMargin    (0.1)
    cup.SetRightMargin  (0.02)
    cup.SetBottomMargin (0.0025)
    cup.SetLeftMargin   (0.08)
    cup.SetFrameBorderMode(0)
    cup.SetFrameBorderMode(0)
    cup.Draw()

    cdown.SetGridx()
    cdown.SetGridy()

    cdown.SetFillColor(0)
    cdown.SetBorderMode(0)
    cdown.SetBorderSize(2)
    cdown.SetTickx(1)
    cdown.SetTicky(1)
    cdown.SetTopMargin   (0.003)
    cdown.SetRightMargin (0.02)
    cdown.SetBottomMargin(0.22)
    cdown.SetLeftMargin  (0.08)
    cdown.Draw()

    cup.cd()

    for sam, h in h_bkg_dict.iteritems():
        set_style(h, color=colors_dict[sam], fill=True)
        h.SetLineWidth(1)
        h.SetLineColor(ROOT.kBlack)


    # Total background
    sm_total_style = 3354
    sm_total_color = ROOT.kGray+3

    h_exp.SetLineWidth(2)
    h_exp.SetLineColor(sm_total_color)
    h_exp.SetFillColor(0)
    h_exp.SetMarkerSize(0)

    h_bkg_total.SetFillColor(sm_total_color)
    h_bkg_total.SetLineColor(sm_total_color)
    h_bkg_total.SetFillStyle(sm_total_style)
    h_bkg_total.SetLineWidth(2)
    h_bkg_total.SetMarkerSize(0)

    set_style(g_obs, msize=1, lwidth=2, color=ROOT.kBlack)
    set_style(h_obs, msize=1, lwidth=2, color=ROOT.kBlack)

    h_obs.SetMaximum(1000*h_obs.GetMaximum())
    h_obs.SetMinimum(0.05)

    h_obs.GetYaxis().SetTitle("Number of events")
    h_obs.GetYaxis().SetTitleSize(0.06)
    h_obs.GetYaxis().SetTitleOffset(0.65)
    h_obs.GetXaxis().SetLabelSize(0.00)
    h_obs.GetYaxis().SetLabelSize(0.05)

    h_obs.Draw('p')
    stack.Draw("histsame")
    g_obs.Draw("P0Z")
    h_exp.Draw("histsame")
    h_bkg_total.Draw("E2same][")
    g_obs.Draw("P0Z")


    legymin = 0.53
    legymax = 0.85

    legxmin = 0.65
    legxmax = 0.94

    legend1 = ROOT.TLegend(legxmin, legymin, legxmax, legymax)
    legend1.SetFillColor(0)
    legend1.SetBorderSize(0)
    legend1.SetNColumns(2)
    legend1.SetTextFont(42)
    legend1.SetTextSize(legend1.GetTextSize()*0.8)

    for name, hist in h_bkg_dict.iteritems():
        legend1.AddEntry(hist, labels_dict[name], 'f')

    legend1.AddEntry(h_bkg_total, "SM Total", 'f')
    legend1.AddEntry(g_obs, 'Data', 'pl')

    t = ROOT.TLatex(0, 0, data_label)
    t.SetNDC()
    t.SetTextFont(42)
    t.SetTextSize(0.05)
    t.SetTextColor(ROOT.kBlack)

    if atlas_label:
        t.DrawLatex(0.15, 0.80, atlas_label)
    if data_label:
        t.DrawLatex(0.15, 0.72, data_label)

    legend1.Draw()
    cup.RedrawAxis()

    # Down plot (pulls)
    cdown.cd()

    frame = ROOT.TH2F("frame", "", len(pulls), 0., len(pulls), 8, -4., 4.);
    frame.GetYaxis().SetTitleSize(0.10)
    frame.GetYaxis().CenterTitle()
    frame.GetYaxis().SetTitleOffset(0.35)
    frame.GetYaxis().SetRangeUser(-max_pull, max_pull)
    frame.GetXaxis().SetLabelOffset(0.03)
    frame.GetXaxis().SetLabelSize(0.12)
    frame.GetYaxis().SetLabelSize(0.12)
    frame.GetYaxis().SetNdivisions(4)
    if plot_significance:
        frame.SetYTitle("Significance")
    else:
        frame.SetYTitle("(n_{#lower[-0.3]{obs}} - n_{exp}) / #sigma_{tot}")

    # global style settings
    ROOT.gPad.SetTicks();
    frame.SetLabelFont(42, "X");
    frame.SetTitleFont(42, "X");
    frame.SetLabelFont(42, "Y");
    frame.SetTitleFont(42, "Y");

    for b in xrange(1, h_obs.GetNbinsX()+1):
        label = h_obs.GetXaxis().GetBinLabel(b)
        frame.GetXaxis().SetBinLabel(b, label)

    frame.GetXaxis().SetLabelSize(0.15)
    frame.Draw()

    l1 = ROOT.TLine(0, -1., len(pulls), -1.)
    l2 = ROOT.TLine(0,  1., len(pulls),  1.)

    ROOT.SetOwnership(l1, False)
    ROOT.SetOwnership(l2, False)

    l1.SetLineStyle(3)
    l2.SetLineStyle(3)

    l1.Draw()
    l2.Draw()

    allp = []
    for counter, pull in enumerate(pulls):

        color = ROOT.TColor.GetColor('#80807a')

        if pull > 0.:
            miny = -0.02
        else:
            miny = 0.02

        if pull > max_pull:
            pull = max_pull-0.05
        elif pull < -max_pull:
            pull = -max_pull+0.05

        box = ROOT.TBox(0.1+counter, miny, 0.9+counter, pull)
        box.SetFillColor(color)
        box.SetLineColor(color)
        box.Draw()

        allp.append(box)

    c.SaveAs(output_name)