Ejemplo n.º 1
0
def Compare(w, output, fn1, fn2, bins, var, other_vars= {}, line_pos=None):
    label_vars = []
    for key, val in other_vars.iteritems():
        w.var(key).setVal(val)
        label_vars.append('%s=%g' % (key, val))
    h1 = w.function(fn1).createHistogram(fn1, w.var(var),
            ROOT.RooFit.Binning(*bins),
            ROOT.RooFit.Scaling(False)
        )
    h2 = w.function(fn2).createHistogram(fn2, w.var(var),
            ROOT.RooFit.Binning(*bins),
            ROOT.RooFit.Scaling(False)
        )
    canv = ROOT.TCanvas(output, output)
    pads = plot.TwoPadSplit(0.30, 0.01, 0.01)
    pads[0].cd()
    pads[0].SetGrid(1, 1)
    plot.Set(h1, LineColor=ROOT.kBlack, LineWidth=2)
    plot.Set(h1.GetYaxis(), Title='Efficiency')
    plot.Set(h2, LineColor=ROOT.kRed, LineWidth=2)

    for i in xrange(1, h1.GetNbinsX()+1):
        h1.SetBinError(i, 0.)
    for i in xrange(1, h2.GetNbinsX()+1):
        h2.SetBinError(i, 0.)
    h1.Draw('L')
    h2.Draw('LSAME')
    ratio = h1.Clone()
    ratio.Divide(h2)


    legend = ROOT.TLegend(0.18, 0.82, 0.6, 0.93, '', 'NBNDC')
    legend.AddEntry(h1, fn1, 'L')
    legend.AddEntry(h2, fn2, 'L')
    legend.Draw()
    print plot.GetPadYMax(pads[0])
    plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.25)
    plot.DrawTitle(pads[0], ','.join(label_vars), 1)

    line = ROOT.TLine()
    plot.Set(line, LineColor=12, LineStyle=4, LineWidth=2)
    if line_pos is not None:
        plot.DrawVerticalLine(pads[0], line, line_pos)

    pads[1].cd()
    pads[1].SetGrid(1, 1)
    ratio.Draw('L')
    plot.SetupTwoPadSplitAsRatio(
        pads, plot.GetAxisHist(
            pads[0]), plot.GetAxisHist(pads[1]), 'Ratio', True, 0.91, 1.09)
    if line_pos is not None:
        plot.DrawVerticalLine(pads[1], line, line_pos)
    canv.Print('.pdf')
    canv.Print('.png')
Ejemplo n.º 2
0
def MakeProjections(h2d_list,
                    main_label,
                    ix,
                    color,
                    marker,
                    along='X',
                    sublabels=['total', 'stat', 'syst']):
    res = {}
    attr = 'Projection%s' % along
    if len(h2d_list) >= 2:
        for i in xrange(len(h2d_list)):
            res[sublabels[i]] = getattr(h2d_list[i], attr)(
                '%s_%s_proj%s_%i' % (main_label, sublabels[i], along, ix), ix,
                ix)

        plot.Set(res[sublabels[0]], MarkerSize=0, LineWidth=2, LineColor=color)
        plot.Set(res[sublabels[1]],
                 LineColorAlpha=(color, 0.3),
                 MarkerColor=color,
                 LineWidth=8,
                 MarkerSize=0)
        # plot.Set(res[sublabels[2]], LineColor=color, MarkerColor=color, LineWidth=2, MarkerSize=0.7, MarkerStyle=marker)
        if len(h2d_list) >= 3:
            plot.Set(res[sublabels[2]],
                     FillColorAlpha=(0, 0),
                     LineColor=color,
                     MarkerColor=color,
                     LineWidth=2,
                     MarkerSize=0.0,
                     MarkerStyle=marker)
    else:
        res['stat'] = getattr(h2d_list[0], attr)(
            '%s_stat_proj%s_%i' % (main_label, along, ix), ix, ix)
        plot.Set(res['stat'],
                 LineColor=color,
                 MarkerColor=color,
                 LineWidth=2,
                 MarkerSize=0.7,
                 MarkerStyle=marker)
    return res
Ejemplo n.º 3
0
def MakeMultiHistPlot(name, outdir, hists, cfg, layout, ratios=None):
    js_workaround = False
    copyhists = {}
    for hname, h in hists.iteritems():
        if len(cfg['rebinvar']):
            copyhists[hname] = VariableRebin(h, cfg['rebinvar'])
        else:
            copyhists[hname] = h.Clone()
        if cfg['norm_to'] > 0.:
            copyhists[hname].Scale(cfg['norm_to'] /
                                   copyhists[hname].Integral())
        if cfg['divwidth']:
            copyhists[hname].Scale(1., 'width')

    hists = copyhists

    # Canvas and pads
    if cfg['pads'] is not None:
        pads = cfg['pads']
    elif cfg['ratio'] or cfg['fraction']:
        canv = ROOT.TCanvas(name, name)
        if cfg['purity']:
            pads = plot.MultiRatioSplit([0.27, 0.13], [0.005, 0.005],
                                        [0.005, 0.005])
        else:
            # if js_workaround:
            #     upper = ROOT.TPad('upper', 'upper', 0., cfg['ratio_pad_frac'], 1., 1.)
            #     upper.SetBottomMargin(0.01)
            #     # upper.SetFillStyle(4000)
            #     upper.Draw()
            #     lower = ROOT.TPad('lower', 'lower', 0., 0., 1., cfg['ratio_pad_frac'])
            #     lower.SetTopMargin(0.01)
            #     # lower.SetFillStyle(4000)
            #     lower.Draw()
            #     upper.cd()
            #     pads = [upper, lower]
            # else:
            #     pads = plot.TwoPadSplit(cfg['ratio_pad_frac'], 0.01, 0.01)
            pads = plot.TwoPadSplit(cfg['ratio_pad_frac'], 0.01, 0.01)

    else:
        canv = ROOT.TCanvas(name, name)
        pads = plot.OnePad()

    # Allow the user to skip specifying a list of entries for a given plot element.
    # If it's not been specified then we will add it manually
    for info in layout:
        if 'entries' not in info:
            info['entries'] = [info['name']]
        for opt in cfg['global_hist_opts']:
            if opt not in info:
                info[opt] = cfg['global_hist_opts'][opt]

    h_data = None
    if cfg['type'] == 'datamc':
        # Get the data and create axis hist
        h_data = hists[cfg['data_name']]
    else:
        h_data = hists[layout[0]['entries'][0]]

    if isinstance(h_data, ROOT.TH2):
        print 'TH2: aborting!'
        return

    h_axes = [h_data.Clone() for x in pads]
    for h in h_axes:
        h.SetTitle("")
        if len(cfg['x_range']):
            h.GetXaxis().SetRangeUser(*cfg['x_range'])
        h.Reset()

    build_h_tot = True
    h_tot = None
    if 'TotalProcs' in hists:
        h_tot = hists['TotalProcs']
        build_h_tot = False
    if cfg['type'] != 'datamc':
        build_h_tot = False

    if isinstance(cfg['x_title'], list) or isinstance(cfg['x_title'], tuple):
        x_title = cfg['x_title'][0]
        units = cfg['x_title'][1]
    else:
        x_title = cfg['x_title']
        units = ''

    if x_title == '' and h_data.GetXaxis().GetTitle() != '':
        x_title = h_data.GetXaxis().GetTitle()

    if ':' in x_title:
        units = x_title.split(':')[1]
        x_title = x_title.split(':')[0]

    if cfg['logy']:
        pads[0].SetLogy()
        h_axes[0].SetMinimum(cfg['logy_min'])

    rpad_idx = len(pads) - 1

    if cfg['ratio'] or cfg['fraction']:
        plot.StandardAxes(h_axes[rpad_idx].GetXaxis(), h_axes[0].GetYaxis(),
                          x_title, units)
    else:
        plot.StandardAxes(h_axes[0].GetXaxis(), h_axes[0].GetYaxis(), x_title,
                          units)
    h_axes[0].Draw()

    # A dict to keep track of the hists
    h_store = {}
    p_store = {}

    legend = ROOT.TLegend(*(cfg['legend_pos'] + ['', 'NBNDC']))
    stack = ROOT.THStack()
    purity_stack = ROOT.THStack()

    curr_auto_colour = 0
    for info in layout:
        hist = hists[info['entries'][0]]
        if 'color' in info:
            col = info['color']
        else:
            col = AUTO_COLOURS[curr_auto_colour]
            if curr_auto_colour == (len(AUTO_COLOURS) - 1):
                curr_auto_colour = 0
            else:
                curr_auto_colour += 1
        # col = info['color']
        if isinstance(col, list):
            col = ROOT.TColor.GetColor(*col)
        # print info['line_width']
        if cfg['type'] == 'multihist':
            plot.Set(hist,
                     FillColor=col,
                     MarkerColor=col,
                     LineColor=col,
                     Title=info['legend'],
                     MarkerSize=info['marker_size'],
                     LineWidth=info['line_width'])
        else:
            plot.Set(hist,
                     FillColor=col,
                     MarkerColor=col,
                     Title=info['legend'],
                     MarkerSize=info['marker_size'],
                     LineWidth=info['line_width'])
        if len(info['entries']) > 1:
            for other in info['entries'][1:]:
                hist.Add(hists[other])
        h_store[info['name']] = hist
        p_store[info['name']] = hist.Clone()
        if build_h_tot:
            if h_tot is None:
                h_tot = hist.Clone()
            else:
                h_tot.Add(hist)
        if cfg['type'] == 'datamc':
            stack.Add(hist)
        else:
            hist.Draw('SAME%s' % info['draw_opts'])

    # h_tot_purity = h_tot.Clone()
    for info in layout:
        p_store[info['name']].Divide(h_tot)
        purity_stack.Add(p_store[info['name']])

    if cfg['type'] == 'datamc':
        h_tot.SetFillColor(plot.CreateTransparentColor(12, 0.3))
        h_tot.SetMarkerSize(0)
        legend.AddEntry(h_data, 'Observed', 'PL')

    # Build overlays
    for info in cfg['overlays']:
        hist = None
        input_list = []
        if isinstance(info['entries'], str):
            input_list = list(all_input_hists)
        else:
            input_list = list(info['entries'])
        updated_list = []
        for xh in input_list:
            if xh + info['hist_postfix'] in hists:
                updated_list.append(xh + info['hist_postfix'])
            else:
                updated_list.append(xh)
        print updated_list
        hist = HistSum(hists, updated_list)
        col = info['color']
        if isinstance(col, list):
            col = ROOT.TColor.GetColor(*col)
        plot.Set(hist,
                 LineColor=col,
                 LineWidth=1,
                 MarkerSize=0,
                 Title=info['legend'])
        for ib in xrange(1, hist.GetNbinsX() + 1):
            hist.SetBinError(ib, 1E-7)
        h_store[info['name']] = hist

    if cfg['type'] == 'datamc':
        for ele in reversed(layout):
            legend.AddEntry(h_store[ele['name']], ele['legend'],
                            ele['legend_opts'])
    else:
        for ele in layout:
            leg_extra = ''
            if cfg['legend_show_yields']:
                leg_extra = ' (%.1f)' % h_store[ele['name']].Integral(
                    'width' if cfg['divwidth'] else '')
            legend.AddEntry(h_store[ele['name']], ele['legend'] + leg_extra,
                            ele['legend_opts'])

    if cfg['type'] == 'datamc':
        bkg_uncert_label = 'Stat. Uncertainty'
        if not build_h_tot:
            bkg_uncert_label = 'Uncertainty'
        legend.AddEntry(h_tot, bkg_uncert_label, 'F')

        stack.Draw('HISTSAME')
        h_tot.Draw("E2SAME")

        for info in cfg['overlays']:
            h_store[info['name']].Draw('HISTSAME')

        if not cfg['hide_data']:
            h_data.Draw('E0SAME')

    for info in cfg['overlays']:
        legend.AddEntry(h_store[info['name']], info['legend'], 'L')

    plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35)
    legend.Draw()
    # if cfg['legend_padding'] > 0.:
    #     plot.FixBoxPadding(pads[0], legend, cfg['legend_padding'])

    # Do the ratio plot
    r_store = {}
    r_data = None
    r_tot = None
    if cfg['ratio'] or cfg['fraction']:
        pads[rpad_idx].cd()
        pads[rpad_idx].SetGrid(0, 1)
        h_axes[rpad_idx].Draw()

        if cfg['type'] == 'datamc' and cfg['ratio']:
            r_data = plot.MakeRatioHist(h_data, h_tot, True, False)
            r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False)
            r_tot.Draw('E2SAME')
            for info in cfg['overlays']:
                r_store[info['name']] = plot.MakeRatioHist(
                    h_store[info['name']], h_tot, False, False)
                r_store[info['name']].Draw('SAME')
            if not cfg['hide_data']:
                r_data.Draw('SAME')

        if cfg['type'] == 'datamc' and cfg['fraction']:
            r_frac = plot.MakeRatioHist(h_tot, h_data, True, True)
            r_frac.Draw('SAME')
            plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                         plot.GetAxisHist(pads[rpad_idx]),
                                         'Exp/Obs', True, 0.0, 0.5)

        if ratios is not None:
            for info in ratios:
                if 'type' in info and info['type'] == 'binomial':
                    rhist = h_store[info['num']].Clone()
                    rhist.Divide(h_store[info['num']], h_store[info['den']],
                                 1., 1., "B")
                elif 'type' in info and info['type'] == 'noerror':
                    rhist = plot.MakeRatioHist(h_store[info['num']],
                                               h_store[info['den']], True,
                                               False)
                else:
                    rhist = plot.MakeRatioHist(h_store[info['num']],
                                               h_store[info['den']], True,
                                               True)
                r_store['%s_%s' % (info['num'], info['den'])] = rhist
                rhist.Draw('SAMEE0')

        plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                     plot.GetAxisHist(pads[rpad_idx]),
                                     cfg['ratio_y_title'], True,
                                     *(cfg['ratio_y_range']))
        if js_workaround:
            # This makes the ticks way too large
            plot.GetAxisHist(pads[rpad_idx]).GetYaxis().SetTickLength(
                ROOT.gStyle.GetTickLength())

    if cfg['purity']:
        pads[1].cd()
        h_axes[1].Draw()
        plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                     plot.GetAxisHist(pads[1]), 'f', True, 0,
                                     1)
        plot.Set(h_axes[1].GetXaxis(), TitleSize=0, LabelSize=0)
        plot.Set(h_axes[1].GetYaxis(), Ndivisions=(502, False))
        purity_stack.Draw('HISTSAME')
        # purity_stack.Print()
        h_axes[1].SetMinimum(0)
        h_axes[1].SetMaximum(1)
        pads[1].RedrawAxis()

    # Go back and tidy up the axes and frame
    pads[0].cd()
    if not js_workaround:
        pads[0].GetFrame().Draw()
        pads[0].RedrawAxis()

    # CMS logo
    plot.DrawCMSLogo(pads[0], cfg['main_logo'], cfg['sub_logo'], 11, 0.045,
                     0.05, 1.0, '', 1.0)
    plot.DrawTitle(pads[0], cfg['top_title_left'], 1)
    if cfg['auto_top_title_right']:
        title_right = h_data.GetTitle()
        if title_right.startswith('lumi:'):
            plot.DrawTitle(pads[0], title_right.replace('lumi:', ''), 3)

    latex = ROOT.TLatex()
    plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03)
    # latex.DrawLatex(0.20, 0.75, args.title)
    # plot.DrawTitle(pads[0], args.title, 1)

    # ... and we're done
    if cfg['pads'] is None:
        canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] +
                   '.png')
        canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] +
                   '.pdf')
        # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.root')
        # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.svg')
        # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.json')

    outobjs = {}
    outobjs['axes'] = h_axes
    outobjs['hists'] = hists
    outobjs['stack'] = stack
    outobjs['purity_stack'] = purity_stack
    outobjs['h_tot'] = h_tot
    outobjs['legend'] = legend
    outobjs['r_store'] = r_store
    outobjs['p_store'] = p_store
    outobjs['r_data'] = r_data
    outobjs['r_tot'] = r_tot
    return outobjs
Ejemplo n.º 4
0
ROOT.PyConfig.IgnoreCommandLineOptions = True
ROOT.gROOT.SetBatch(ROOT.kTRUE)
plot.ModTDRStyle()
ROOT.gStyle.SetNdivisions(510, 'XYZ')  # probably looks better

canv = ROOT.TCanvas(args.output, args.output)

if args.ratio_to is not None:
    pads = plot.TwoPadSplit(0.30, 0.01, 0.01)
else:
    pads = plot.OnePad()

# Set the style options of the pads
for padx in pads:
    # Use tick marks on oppsite axis edges
    plot.Set(padx, Tickx=1, Ticky=1, Logx=args.logx)
    if args.pad_style is not None:
        settings = {
            x.split('=')[0]: eval(x.split('=')[1])
            for x in args.pad_style.split(',')
        }
        print 'Applying style options to the TPad(s):'
        print settings
        plot.Set(padx, **settings)

graphs = []
graph_sets = []

legend = plot.PositionedLegend(0.45, 0.10, 3, 0.015)
plot.Set(legend, NColumns=2)
Ejemplo n.º 5
0

chain = ROOT.TChain(args.tree)
for f in files:
    chain.Add('%s.root' % f)


res = chain.MultiDraw([(args.var, '(%s)' % args.selection), (args.var, 'wt_nlo_pt*(%s)' % args.selection)])


canv = ROOT.TCanvas(args.output, args.output)
pads = plot.TwoPadSplit(0.30, 0.01, 0.01)

legend = ROOT.TLegend(0.50, 0.75, 0.93, 0.93, '', 'NBNDC')

plot.Set(res[0], LineColor=ROOT.kBlack, LineWidth=3)
plot.Set(res[1], LineColor=ROOT.kRed, LineWidth=3)
legend.AddEntry(res[0], 'Unweighted', 'L')
legend.AddEntry(res[1], 'Weighted', 'L')
res[0].Draw('HISTESAME')
res[1].Draw('HISTESAME')

plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.40)

delta_acc = Rate(res[1]) / Rate(res[0])
legend.SetHeader('Rel. Acc.: %.3f #pm %.3f' % (delta_acc.n, delta_acc.s))
legend.Draw()

axis = plot.GetAxisHist(pads[0])
plot.Set(axis.GetXaxis(), Title=args.x_title)
plot.Set(axis.GetYaxis(), Title='a.u.')
Ejemplo n.º 6
0
hframe = ROOT.TH2F("hframe", "hframe", 6, xmin, xmax, N + 1, 0, N + 1)

relabel = {}
if args.labels is not None:
    labels = args.labels.split(',')
    for l in labels:
        relabel[int(l.split('=')[0])] = l.split('=')[1]

for i, info in enumerate(drawlist):
    hframe.GetYaxis().SetBinLabel(i + 1, Translate(info['Name'], translate))
    if i in relabel:
        hframe.GetYaxis().SetBinLabel(i + 1, relabel[i])

hframe.GetYaxis().LabelsOption('v')
plot.Set(hframe.GetYaxis(), LabelSize=0.05)
plot.Set(hframe.GetXaxis(), Title=args.x_title)

hframe.Draw()

for vline in args.vlines:
    xlines = vline.split(':')[0].split(',')
    linestyle = ParseDictArgs(vline.split(':')[1])
    line = ROOT.TLine()
    plot.Set(line, **linestyle)
    for x in xlines:
        line.DrawLine(float(x), 0., float(x), float(N))

for hline in args.hlines:
    ylines = hline.split(':')[0].split(',')
    linestyle = ParseDictArgs(hline.split(':')[1])
Ejemplo n.º 7
0
    h_axes[0].Draw()

    # A dict to keep track of the hists
    h_store = {}

    layout = LAYOUTS[args.channel]

    stack = ROOT.THStack()
    legend = ROOT.TLegend(0.67, 0.86 - 0.04*len(layout), 0.90, 0.91, '', 'NBNDC')

    # h_tot = None

    for ele in layout:
        info = ele[1]
        hist = Getter(file, '%s/%s' % (target, info['entries'][0]), True)
        plot.Set(hist, FillColor=info['color'], Title=info['legend'])
        if len(info['entries']) > 1:
            for other in info['entries'][1:]:
                hist.Add(Getter(file, '%s/%s' % (target, other), True))
        h_store[ele[0]] = hist
        if build_h_tot:
            if h_tot is None:
                h_tot = hist.Clone()
            else:
                h_tot.Add(hist)
        stack.Add(hist)

    h_tot.SetFillColor(plot.CreateTransparentColor(12, 0.3))
    h_tot.SetMarkerSize(0)

    legend.AddEntry(h_data, 'Observed', 'PL')
Ejemplo n.º 8
0
 def PlotTestStat(self, result, name, opts, poi_vals):
     null_vals = [
         x * -2.
         for x in result.GetNullDistribution().GetSamplingDistribution()
     ]
     alt_vals = [
         x * -2.
         for x in result.GetAltDistribution().GetSamplingDistribution()
     ]
     if len(null_vals) == 0 or len(alt_vals) == 0:
         print '>> Errror in PlotTestStat for %s, null and/or alt distributions are empty'
         return
     plot.ModTDRStyle()
     canv = ROOT.TCanvas(name, name)
     pad = plot.OnePad()[0]
     min_val = min(min(alt_vals), min(null_vals))
     max_val = max(max(alt_vals), max(null_vals))
     min_plot_range = min_val - 0.05 * (max_val - min_val)
     if opts['one_sided']:
         min_plot_range = 0.
         pad.SetLogy(True)
     max_plot_range = max_val + 0.05 * (max_val - min_val)
     hist_null = ROOT.TH1F('null', 'null', 40, min_plot_range,
                           max_plot_range)
     hist_alt = ROOT.TH1F('alt', 'alt', 40, min_plot_range, max_plot_range)
     for val in null_vals:
         hist_null.Fill(val)
     for val in alt_vals:
         hist_alt.Fill(val)
     hist_alt.SetLineColor(ROOT.TColor.GetColor(4, 4, 255))
     hist_alt.SetFillColor(
         plot.CreateTransparentColor(ROOT.TColor.GetColor(4, 4, 255), 0.4))
     hist_alt.GetXaxis().SetTitle('-2 #times ln(^{}L_{%s}/^{}L_{%s})' %
                                  (opts['alt_label'], opts['null_label']))
     hist_alt.GetYaxis().SetTitle('Pseudo-experiments')
     hist_alt.Draw()
     hist_null.SetLineColor(ROOT.TColor.GetColor(252, 86, 11))
     hist_null.SetFillColor(
         plot.CreateTransparentColor(ROOT.TColor.GetColor(254, 195, 40),
                                     0.4))
     hist_null.Draw('SAME')
     val_obs = result.GetTestStatisticData() * -2.
     obs = ROOT.TArrow(val_obs, 0, val_obs,
                       hist_alt.GetMaximum() * 0.3, 0.05, '<-|')
     obs.SetLineColor(ROOT.kRed)
     obs.SetLineWidth(3)
     obs.Draw()
     plot.FixTopRange(pad, plot.GetPadYMax(pad), 0.25)
     leg = plot.PositionedLegend(0.22, 0.2, 3, 0.02)
     leg.AddEntry(hist_alt, opts['alt_label'], 'F')
     leg.AddEntry(hist_null, opts['null_label'], 'F')
     leg.AddEntry(obs, 'Observed', 'L')
     leg.Draw()
     plot.DrawCMSLogo(pad, 'CMS', opts['cms_subtitle'], 0, 0.15, 0.035, 1.2)
     pt_l = ROOT.TPaveText(0.23, 0.75, 0.33, 0.9, 'NDCNB')
     pt_l.AddText('Model:')
     pt_l.AddText('Toys:')
     pt_l.AddText('CLs+b:')
     pt_l.AddText('CLb:')
     pt_l.AddText('CLs:')
     plot.Set(pt_l, TextAlign=11, TextFont=62, BorderSize=0)
     pt_l.Draw()
     pt_r = ROOT.TPaveText(0.33, 0.75, 0.63, 0.9, 'NDCNB')
     pt_r.AddText('%s [%s = %.1f, %s = %.1f]' %
                  (opts['model_label'], opts['poi_labels'][0], poi_vals[0],
                   opts['poi_labels'][1], poi_vals[1]))
     pt_r.AddText(
         '%i (%s) + %i (%s)' %
         (result.GetNullDistribution().GetSize(), opts['null_label'],
          result.GetAltDistribution().GetSize(), opts['alt_label']))
     pt_r.AddText('%.3f #pm %.3f' %
                  (result.CLsplusb(), result.CLsplusbError()))
     pt_r.AddText('%.3f #pm %.3f' % (result.CLb(), result.CLbError()))
     pt_r.AddText('%.3f #pm %.3f' % (result.CLs(), result.CLsError()))
     plot.Set(pt_r, TextAlign=11, TextFont=42, BorderSize=0)
     pt_r.Draw()
     pad.GetFrame().Draw()
     pad.RedrawAxis()
     for fmt in opts['formats']:
         canv.SaveAs(fmt)
Ejemplo n.º 9
0
                              ROOT.RooFit.LineColor(ROOT.kBlue),
                              ROOT.RooFit.Name("AllPass"))
    wsp.pdf("passing").plotOn(xframe,
                              ROOT.RooFit.Slice(wsp.cat('cat'), "pass"),
                              ROOT.RooFit.Components('backgroundPass'),
                              ROOT.RooFit.LineStyle(ROOT.kDashed),
                              ROOT.RooFit.LineColor(ROOT.kBlue),
                              ROOT.RooFit.Name("BkgPass"))
    '''
    pads[0].cd()
    xframe.Draw()

    axis = plot.GetAxisHist(pads[0])
    #plot.Set(axis.GetXaxis().SetTitle('m_{tag-probe} (GeV)'))
    if args.particle == 'e':
        plot.Set(axis.GetXaxis().SetTitle('p_{t}(e) (GeV)'))
    else:
        plot.Set(axis.GetXaxis().SetTitle('p_{t}(#mu) (GeV)'))
    plot.Set(axis.GetYaxis().SetTitle('Events / %g GeV' % width))
    #plot.DrawTitle(pads[0], 'Pass Region', 1)
    plot.DrawTitle(pads[0], args.title, 1)

    latex.SetTextSize(0.035)
    #latex.DrawLatex(0.5, 0.89, args.title)
    #latex.DrawLatex(0.5, 0.84, 'p_{T}: [%g, %g] GeV #eta: [%g, %g]' % (b[2], b[3], b[4], b[5]))
    font = latex.GetTextFont()
    latex.DrawLatex(0.2, 0.9, 'pass region')
    latex.SetTextFont(42)
    #latex.DrawLatex(0.63, 0.75, '#chi^{2} = %.2f' % (xframe.chiSquare("AllPass", "DataPass", nparams)))
    latex.DrawLatex(
        0.63, 0.7, '#varepsilon = %.4f #pm %.4f' %
Ejemplo n.º 10
0
    relative_exp_graph.SetMarkerColor(ROOT.kRed)
    relative_exp_graph.SetLineStyle(1)
    relative_exp_graph.Draw("PL")
    if not args.expected_only:
        relative_obs_graph.SetLineColor(ROOT.kBlue)
        relative_obs_graph.SetMarkerColor(ROOT.kBlue)
        relative_obs_graph.SetLineWidth(3)
        relative_obs_graph.SetLineStyle(2)
        relative_obs_graph.SetMarkerStyle(20)
        relative_obs_graph.Draw("PL")

pads[0].cd()
h_top = axis.Clone()
#necessary in case chosen range surrounds 0 which will cause axis to contain a horizontal line at 0
h_top.GetYaxis().SetRangeUser(0.001, 100)
plot.Set(h_top.GetXaxis(), LabelSize=0, TitleSize=0, TickLength=0)
plot.Set(h_top.GetYaxis(), LabelSize=0, TitleSize=0, TickLength=0)
h_top.Draw()

legend = plot.PositionedLegend(0.5 if args.relative or args.absolute else 0.4,
                               0.11, 3, 0.015)
plot.Set(legend, NColumns=1, Header='#bf{%.0f%% CL Excluded:}' % 95)
if not (args.relative or args.absolute):
    for i in range(len(files)):
        legend.AddEntry(exp_graph_list[i], labels[i], "PL")
elif args.relative:
    legend.SetTextSize(0.025)
    legend.AddEntry(
        relative_exp_graph, "Exp 2*|" + labels[0] + "-" + labels[1] + "|/(" +
        labels[0] + "+" + labels[1] + ")", "PL")
    if not args.expected_only:
Ejemplo n.º 11
0
h_axis.Draw()

pads[0].SetLogy(args.logy)
pads[0].SetLogx(args.logx)
pads[0].SetTickx()
pads[0].SetTicky()
# h_proto.GetXaxis().SetRangeUser(130,400)
# h_proto.GetYaxis().SetRangeUser(1,20)

fillstyle = 'FSAME'

# Now we draw the actual contours
for i, gr in enumerate(contours95['obs']):
    plot.Set(gr,
             FillColor=ROOT.kBlue - 10,
             LineColor=ROOT.kBlack,
             LineWidth=2,
             FillStyle=1001)
    gr.Draw(fillstyle)
    gr.Draw("LSAME")
for i, gr in enumerate(contours68['obs']):
    plot.Set(gr,
             FillColor=ROOT.kBlue - 8,
             LineColor=ROOT.kBlack,
             LineWidth=2,
             FillStyle=1001)
    gr.Draw(fillstyle)
    gr.Draw("LSAME")

# We just want the top pad to look like a box, so set all the text and tick
# sizes to zero
Ejemplo n.º 12
0
def MakePlot(name, outdir, hists, cfg, layouts):
    copyhists = {}
    for hname, h in hists.iteritems():
        if len(cfg['rebinvar']):
            copyhists[hname] = VariableRebin(h, cfg['rebinvar'])
        else:
            copyhists[hname] = h.Clone()
        if cfg['divwidth']:
            copyhists[hname].Scale(1., 'width')

    hists = copyhists

    # Canvas and pads
    canv = ROOT.TCanvas(name, name)
    if cfg['ratio'] or cfg['fraction']:
        pads = plot.TwoPadSplit(0.27, 0.01, 0.01)
    else:
        pads = plot.OnePad()

    # Get the data and create axis hist
    h_data = hists[cfg['data_name']]
    # h_data = Getter(file, '%s/data_obs' % target, True)
    if isinstance(h_data, ROOT.TH2):
        print 'TH2: aborting!'
        return

    h_axes = [h_data.Clone() for x in pads]
    for h in h_axes:
        if len(cfg['x_range']):
            h.GetXaxis().SetRangeUser(*cfg['x_range'])
        h.Reset()

    build_h_tot = True
    h_tot = None
    if 'TotalProcs' in hists:
        h_tot = hists['TotalProcs']
        build_h_tot = False

    x_title = cfg['x_title'][0]
    units = cfg['x_title'][1]

    if x_title == '' and h_data.GetXaxis().GetTitle() != '':
        x_title = h_data.GetXaxis().GetTitle()

    if ':' in x_title:
        units = x_title.split(':')[1]
        x_title = x_title.split(':')[0]

    if cfg['logy']:
        pads[0].SetLogy()
        h_axes[0].SetMinimum(0.001)

    if cfg['ratio'] or cfg['fraction']:
        plot.StandardAxes(h_axes[1].GetXaxis(), h_axes[0].GetYaxis(), x_title,
                          units)
    else:
        plot.StandardAxes(h_axes[0].GetXaxis(), h_axes[0].GetYaxis(), x_title,
                          units)
    h_axes[0].Draw()

    # A dict to keep track of the hists
    h_store = {}

    layout = layouts[cfg['layout']]

    stack = ROOT.THStack()
    legend = ROOT.TLegend(*(cfg['legend_pos'] + ['', 'NBNDC']))

    for info in layout:
        hist = hists[info['entries'][0]]
        col = info['color']
        if isinstance(col, list):
            col = ROOT.TColor.GetColor(*col)
        plot.Set(hist, FillColor=col, Title=info['legend'])
        if len(info['entries']) > 1:
            for other in info['entries'][1:]:
                hist.Add(hists[other])
        h_store[info['name']] = hist
        if build_h_tot:
            if h_tot is None:
                h_tot = hist.Clone()
            else:
                h_tot.Add(hist)
        stack.Add(hist)

    h_tot.SetFillColor(plot.CreateTransparentColor(12, 0.3))
    h_tot.SetMarkerSize(0)

    legend.AddEntry(h_data, 'Observed', 'PL')
    for ele in reversed(layout):
        legend.AddEntry(h_store[ele['name']], '', 'F')
    bkg_uncert_label = 'Stat. Uncertainty'
    if not build_h_tot:
        bkg_uncert_label = 'Uncertainty'
    legend.AddEntry(h_tot, bkg_uncert_label, 'F')

    stack.Draw('HISTSAME')
    h_tot.Draw("E2SAME")
    if not cfg['hide_data']:
        h_data.Draw('E0SAME')

    plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35)
    legend.Draw()
    if cfg['legend_padding'] > 0.:
        print h_axes[0].GetMinimum(), h_axes[0].GetMaximum()
        if not h_axes[0].GetMaximum() == 0.:
            plot.FixBoxPadding(pads[0], legend, cfg['legend_padding'])

    # Do the ratio plot
    if cfg['ratio'] or cfg['fraction']:
        pads[1].cd()
        pads[1].SetGrid(0, 1)
        h_axes[1].Draw()

        if cfg['ratio']:
            r_data = plot.MakeRatioHist(h_data, h_tot, True, False)
            r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False)
            r_tot.Draw('E2SAME')
            if not cfg['hide_data']:
                r_data.Draw('SAME')

            plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                         plot.GetAxisHist(pads[1]), 'Obs/Exp',
                                         True, 0.61, 1.69)
        if cfg['fraction']:
            r_frac = plot.MakeRatioHist(h_tot, h_data, True, True)
            r_frac.Draw('SAME')
            plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                         plot.GetAxisHist(pads[1]), 'Exp/Obs',
                                         True, 0.0, 0.5)

    # Go back and tidy up the axes and frame
    pads[0].cd()
    pads[0].GetFrame().Draw()
    pads[0].RedrawAxis()

    # CMS logo
    plot.DrawCMSLogo(pads[0], cfg['main_logo'], cfg['sub_logo'], 11, 0.045,
                     0.05, 1.0, '', 1.0)
    plot.DrawTitle(pads[0], cfg['top_title_left'], 1)
    if cfg['auto_top_title_right']:
        title_right = h_data.GetTitle()
        if title_right.startswith('lumi:'):
            plot.DrawTitle(pads[0], title_right.replace('lumi:', ''), 3)
    else:
        plot.DrawTitle(pads[0], cfg['top_title_right'], 3)

    latex = ROOT.TLatex()
    plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03)
    latex.DrawLatex(0.20, 0.75, args.title)
    # plot.DrawTitle(pads[0], args.title, 1)

    # ... and we're done
    canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.png')
    canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.pdf')
Ejemplo n.º 13
0
node = TDirToNode(file, startdir=args.path)

print node.d.keys()

canv = ROOT.TCanvas('test', 'test')
pads = plot.OnePad()

h_nom = node[args.procs]
h_hi = node[args.procs + '_' + args.systs + 'Up']
h_lo = node[args.procs + '_' + args.systs + 'Down']

r_nom = plot.MakeRatioHist(h_nom, h_nom, True, False)
r_hi = plot.MakeRatioHist(h_hi, h_nom, False, False)
r_lo = plot.MakeRatioHist(h_lo, h_nom, False, False)

plot.Set(r_nom, LineColor=1, LineWidth=2)
plot.Set(r_hi, LineColor=2, LineWidth=2)
plot.Set(r_lo, LineColor=4, LineWidth=2)

r_nom.Draw('HISTE')
r_hi.Draw('HISTSAME')
r_lo.Draw('HISTSAME')

r_nom.SetMinimum(0.9)
r_nom.SetMaximum(1.1)

canv.Print('test.pdf')
# made_dirs = set()

# for path, subnode in node.ListNodes(withObjects=True):
#     print path
Ejemplo n.º 14
0
def SummaryPlots(cfg):
    h_ref = cfg['h_ref'].Clone()
    main_label = cfg['main_label']
    ref_axis = h_ref.GetYaxis() if cfg['proj'] == 'X' else h_ref.GetXaxis()
    for ix in xrange(1, ref_axis.GetNbins() + 1):
        bin_label = '%s #in [%g, %g]' % (cfg['y_label'],
                                         ref_axis.GetBinLowEdge(ix),
                                         ref_axis.GetBinUpEdge(ix))
        canv = ROOT.TCanvas('%s_%s_%i' % (main_label, cfg['proj'], ix),
                            '%s_%s_%i' % (main_label, cfg['proj'], ix))
        pads = plot.TwoPadSplit(cfg.get('ratio_split', 0.4), 0.01, 0.01)
        pads[0].cd()

        text = ROOT.TPaveText(0.17, 0.84, 0.6, 0.93, 'NDC')
        legend = ROOT.TLegend(0.6, 0.75, 0.94, 0.93, '', 'NDC')
        data_hists = MakeProjections(cfg['data'],
                                     '%s_data' % main_label,
                                     ix,
                                     color=cfg.get('data_colour', 4),
                                     marker=21,
                                     along=cfg['proj'])
        mc_hists = MakeProjections(cfg['mc'],
                                   '%s_mc' % main_label,
                                   ix,
                                   color=cfg.get('mc_colour', 2),
                                   marker=20,
                                   along=cfg['proj'])
        ratio_hists = MakeProjections(cfg['ratio'],
                                      '%s_ratio' % main_label,
                                      ix,
                                      color=cfg.get('ratio_colour', 1),
                                      marker=21,
                                      along=cfg['proj'])

        if 'total' in data_hists:
            data_hists['total'].Draw('E2SAME')
        if 'syst' in data_hists:
            data_hists['syst'].Draw('E0X0SAME')
        if 'stat' in data_hists:
            data_hists['stat'].Draw('E1X0SAME')
        if 'stat' in mc_hists:
            mc_hists['stat'].Draw('E1X0PSAME')

        if 'syst' in data_hists:
            legend.AddEntry(data_hists['stat'], 'Data', 'P')
            legend.AddEntry(data_hists['stat'], '  Statistical', 'E')
            legend.AddEntry(data_hists['syst'], '  Systematic', 'E')
            legend.AddEntry(data_hists['total'], '  Total', 'F')
            legend.AddEntry(mc_hists['stat'], 'Simulation', 'P')
            legend.AddEntry(mc_hists['stat'], '  Statistical', 'E')
        else:
            legend.AddEntry(data_hists['stat'], 'Data', 'PE')
            legend.AddEntry(mc_hists['stat'], 'Simulation', 'PE')

        axis = plot.GetAxisHist(pads[0])
        plot.Set(axis, Minimum=cfg['y_range'][0], Maximum=cfg['y_range'][1])

        plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.40)

        axis.GetYaxis().SetTitle('Efficiency')

        pads[1].cd()

        if 'total' in ratio_hists:
            ratio_hists['total'].Draw('E2SAME')
        if 'syst' in ratio_hists:
            ratio_hists['syst'].Draw('E0X0SAME')
        if 'stat' in ratio_hists:
            ratio_hists['stat'].Draw('E1X0SAME')
        plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]),
                                     plot.GetAxisHist(pads[1]), 'Data/Sim',
                                     True, cfg['ratio_range'][0],
                                     cfg['ratio_range'][1])
        r_axis = plot.GetAxisHist(pads[1])

        if cfg['logx']:
            pads[1].SetLogx(True)
            r_axis.GetXaxis().SetMoreLogLabels(True)
            r_axis.GetXaxis().SetNoExponent(True)
        r_axis.GetXaxis().SetTitle(cfg['x_axis_title'])
        r_axis.GetXaxis().SetTitleOffset(ROOT.gStyle.GetTitleXOffset())
        pads[1].SetGrid(1, 1)
        pads[1].RedrawAxis('g')

        pads[0].cd()
        legend.Draw()
        text.AddText(cfg['main_text'])
        text.AddText(bin_label)
        text.SetTextAlign(13)
        text.SetBorderSize(0)
        text.Draw()
        pads[0].SetGrid(1, 1)
        if cfg['logx']:
            pads[0].SetLogx(True)
        canv.Print('.png')
        canv.Print('.pdf')
Ejemplo n.º 15
0
def SummaryPlotsPhotonFakes(cfg):
    h_ref = cfg['h_ref'].Clone()
    main_label = cfg['main_label']
    ref_axis = h_ref.GetYaxis() if cfg['proj'] == 'X' else h_ref.GetXaxis()
    for ix in xrange(1, ref_axis.GetNbins() + 1):
        bin_label = '%s #in [%g, %g]' % (cfg['y_label'],
                                         ref_axis.GetBinLowEdge(ix),
                                         ref_axis.GetBinUpEdge(ix))
        canv = ROOT.TCanvas('%s_%s_%i' % (main_label, cfg['proj'], ix),
                            '%s_%s_%i' % (main_label, cfg['proj'], ix))
        pads = plot.OnePad()
        pads[0].cd()

        text = ROOT.TPaveText(0.17, 0.84, 0.6, 0.93, 'NDC')
        legend = ROOT.TLegend(0.6, 0.75, 0.94, 0.93, '', 'NDC')
        data_hists = MakeProjections(cfg['data'],
                                     '%s_data' % main_label,
                                     ix,
                                     color=cfg.get('data_colour', 4),
                                     marker=21,
                                     along=cfg['proj'],
                                     sublabels=cfg['data_labels'])
        # mc_hists = MakeProjections(cfg['mc'], '%s_mc' % main_label, ix, color=cfg.get('mc_colour', 2), marker=20, along=cfg['proj'])
        # ratio_hists = MakeProjections(cfg['ratio'], '%s_ratio' % main_label, ix, color=cfg.get('ratio_colour', 1), marker=21, along=cfg['proj'])

        if 'const_syst' in data_hists:
            data_hists['total_err'] = data_hists['total'].Clone()
            plot.Set(data_hists['total_err'],
                     FillColorAlpha=(data_hists['total_err'].GetLineColor(),
                                     0.3),
                     MarkerColor=data_hists['total_err'].GetLineColor(),
                     LineWidth=0,
                     MarkerSize=0)
            plot.Set(data_hists['bkg_syst'],
                     FillColorAlpha=(0, 0),
                     LineColor=2,
                     LineWidth=2,
                     MarkerSize=0)
            plot.Set(data_hists['const_syst'],
                     FillColorAlpha=(0, 0),
                     LineColor=1,
                     LineWidth=2,
                     MarkerSize=0)
            plot.Set(data_hists['stat'],
                     FillColorAlpha=(0, 0),
                     LineColor=4,
                     LineWidth=2,
                     LineStyle=2)
            for h in ['stat', 'const_syst', 'bkg_syst']:
                data_hists[h + '_hi'] = data_hists[h].Clone()
                data_hists[h + '_lo'] = data_hists[h].Clone()
            for ib in xrange(1, data_hists['const_syst'].GetNbinsX() + 1):
                for h in ['stat', 'const_syst', 'bkg_syst']:
                    data_hists[h + '_hi'].SetBinContent(
                        ib, data_hists[h].GetBinContent(ib) +
                        data_hists[h].GetBinError(ib))
                    data_hists[h + '_lo'].SetBinContent(
                        ib, data_hists[h].GetBinContent(ib) -
                        data_hists[h].GetBinError(ib))
                    data_hists[h + '_hi'].SetBinError(ib, 1E-6)
                    data_hists[h + '_lo'].SetBinError(ib, 1E-6)
                data_hists['total'].SetBinError(ib, 1E-6)
                data_hists['total'].SetBinError(ib, 1E-6)

            data_hists['total'].Draw('ESAME')
            data_hists['total_err'].Draw('E2SAME')
            data_hists['const_syst_hi'].Draw('ESAME')
            data_hists['const_syst_lo'].Draw('ESAME')
            data_hists['bkg_syst_hi'].Draw('ESAME')
            data_hists['bkg_syst_lo'].Draw('ESAME')
            data_hists['stat_hi'].Draw('ESAME')
            data_hists['stat_lo'].Draw('ESAME')

            legend.AddEntry(data_hists['total'], 'Data', 'L')
            legend.AddEntry(data_hists['stat'], '  Statistical', 'L')
            legend.AddEntry(data_hists['const_syst'], '  Non-closure syst.',
                            'L')
            legend.AddEntry(data_hists['bkg_syst'],
                            '  Prompt subtraction syst.', 'L')
            legend.AddEntry(data_hists['total_err'], '  Total', 'F')
            # legend.AddEntry(mc_hists['stat'], 'Simulation', 'P')
            # legend.AddEntry(mc_hists['stat'], '  Statistical', 'E')
        elif 'mc' in data_hists:
            plot.Set(data_hists['mc'], LineColor=13, LineWidth=2, MarkerSize=0)
            plot.Set(data_hists['mc_true'],
                     LineColor=9,
                     LineWidth=2,
                     MarkerSize=0)
            data_hists['mc_err'] = data_hists['mc'].Clone()
            plot.Set(data_hists['mc_err'],
                     FillColorAlpha=(data_hists['mc_err'].GetLineColor(), 0.3),
                     LineWidth=0,
                     MarkerSize=0)
            data_hists['mc_true_err'] = data_hists['mc_true'].Clone()
            plot.Set(data_hists['mc_true_err'],
                     FillColorAlpha=(data_hists['mc_true_err'].GetLineColor(),
                                     0.3),
                     LineWidth=0,
                     MarkerSize=0)
            for ib in xrange(1, data_hists['mc'].GetNbinsX() + 1):
                data_hists['mc'].SetBinError(ib, 1E-6)
                data_hists['mc_true'].SetBinError(ib, 1E-6)

            data_hists['mc'].Draw('ESAME')
            data_hists['mc_err'].Draw('E2SAME')
            data_hists['mc_true'].Draw('ESAME')
            data_hists['mc_true_err'].Draw('E2SAME')

            legend.AddEntry(data_hists['mc'], 'Simulation - fit', 'LF')
            legend.AddEntry(data_hists['mc_true'], 'Simulation - truth', 'LF')
            # legend.AddEntry(mc_hists['stat'], 'Simulation', 'PE')

        axis = plot.GetAxisHist(pads[0])
        plot.Set(axis, Minimum=cfg['y_range'][0], Maximum=cfg['y_range'][1])

        plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.40)

        axis.GetYaxis().SetTitle('#sigma_{i#etai#eta} extrapolation')
        axis.GetXaxis().SetTitle(cfg['x_axis_title'])

        pads[0].cd()
        legend.Draw()
        text.AddText(cfg['main_text'])
        text.AddText(bin_label)
        text.SetTextAlign(13)
        text.SetBorderSize(0)
        text.Draw()
        pads[0].SetGrid(1, 1)
        if cfg['logx']:
            pads[0].SetLogx(True)
        canv.Print('.png')
        canv.Print('.pdf')
Ejemplo n.º 16
0
    axis.GetXaxis().SetLabelSize(0.040)
axis.Draw()

for i in range(len(files)):
    graph_list[i].SetLineColor(colourlist[i])
    graph_list[i].SetLineWidth(3)
    graph_list[i].SetMarkerStyle(20)
    graph_list[i].SetMarkerColor(colourlist[i])
    graph_list[i].SetLineStyle(2)
    graph_list[i].Draw("PL")

pads[0].cd()
h_top = axis.Clone()
#necessary in case chosen range surrounds 0 which will cause axis to contain a horizontal line at 0
h_top.GetYaxis().SetRangeUser(0.001, 100)
plot.Set(h_top.GetXaxis(), LabelSize=0, TitleSize=0, TickLength=0)
plot.Set(h_top.GetYaxis(), LabelSize=0, TitleSize=0, TickLength=0)
h_top.Draw()

legend = plot.PositionedLegend(0.4, 0.11, 3, 0.015)
plot.Set(legend, NColumns=1, Header='')
for i in range(len(files)):
    legend.AddEntry(graph_list[i], labels[i], "PL")

legend.Draw()

#plot.DrawCMSLogo(pads[0], 'CMS', args.cms_sub, 11, 0.045, 0.15, 1.0, '', 1.0)
plot.DrawTitle(pads[0], '%s' % args.title, 3)
plot.FixOverlay()

pads[1].cd()
Ejemplo n.º 17
0
    npu_hist.SetBinContent(i + 1, avgpu_per_run[run])
    npu_hist.SetBinError(i + 1, 0)
    npu_hist.GetXaxis().SetBinLabel(i + 1, str(run))

canv = ROOT.TCanvas(args.output, args.output)
pads = plot.MultiRatioSplit([0.4, 0.2], [0.01, 0.01], [0.01, 0.01])

bad_trigger = ROOT.TBox()
bad_trigger.SetFillColorAlpha(ROOT.kRed, 0.3)

some_presc_l1 = ROOT.TBox()
some_presc_l1.SetFillColorAlpha(ROOT.kYellow, 0.3)

boxes = []
pads[0].cd()
plot.Set(pads[0], Grid=(0, 1), Tickx=1, Ticky=1)
plot.Set(yield_hist,
         LineWidth=2,
         MarkerSize=2,
         LineColor=ROOT.kRed,
         MarkerColor=ROOT.kRed)
plot.Set(yield_hist.GetXaxis(), Title='', LabelSize=0)
plot.Set(yield_hist.GetYaxis(), Title='Yield / pb^{-1}')
yield_hist.Draw('P0')
plot.FixBothRanges(pads[0],
                   plot.GetAxisHist(pads[0]).GetMinimum(), 0.05,
                   plot.GetAxisHist(pads[0]).GetMaximum(), 0.05)
for i, run in enumerate(runs):
    if not prescale_ok[str(run)]:
        boxes.append(
            bad_trigger.DrawBox(float(i),
Ejemplo n.º 18
0
        h_resp.GetXaxis().SetBinLabel(ib + 1, label)
        h_resp.GetYaxis().SetBinLabel(ib + 1, label)

h_resp.GetXaxis().LabelsOption('v')

canv = ROOT.TCanvas(args.output, args.output)
pads = plot.OnePad()

ROOT.gStyle.SetTextFont(42)
h_resp.Draw('COLZ')

latex = ROOT.TLatex()

if args.selection == 'eft_region':
    x_offset = -2.5
    plot.Set(latex, TextSize=0.02, TextAlign=22)
    latex.DrawLatex(1, x_offset, '[150, 200]')
    latex.DrawLatex(4, x_offset, '[200, 300]')
    latex.DrawLatex(7, x_offset, '[300, 500]')
    latex.DrawLatex(10, x_offset, '[500, 800]')
    latex.DrawLatex(13, x_offset, '[800, 1200]')
    # latex.DrawLatex(16, x_offset, '[850, 1200]')

    plot.Set(latex, TextAngle=90)

    y_offset = -2.4
    latex.DrawLatex(y_offset, 1, '[150, 200]')
    latex.DrawLatex(y_offset, 4, '[200, 300]')
    latex.DrawLatex(y_offset, 7, '[300, 500]')
    latex.DrawLatex(y_offset, 10, '[500, 800]')
    latex.DrawLatex(y_offset, 13, '[800, 1200]')
Ejemplo n.º 19
0
h_axes[0].SetMinimum(1E-9)

# A dict to keep track of the hists
legend = ROOT.TLegend(0.67, 0.86 - 0.04 * 3, 0.90, 0.91, '', 'NBNDC')

legend.AddEntry(h_LO_inc, 'LO inclusive', 'L')
# legend.AddEntry(h_sm, 'SM', 'L')
# legend.AddEntry(h_th, 'Reference', 'L')
legend.AddEntry(h_NLO_inc, 'NLO inclusive', 'L')
# legend.AddEntry(h_LO_130, 'LO 130', 'L')
# legend.AddEntry(h_LO_inc_cut_130, 'LO inc., 130 cut', 'L')
# legend.AddEntry(h_LO_500, 'LO 500', 'L')

# plot.Set(h_sm, LineColor=2, LineWidth=2, MarkerColor=2)
# plot.Set(h_th, LineColor=4, LineWidth=2, MarkerColor=4)
plot.Set(h_LO_inc, LineColor=1, LineWidth=2, MarkerColor=1, MarkerSize=0.5)
plot.Set(h_NLO_inc,
         LineColor=ROOT.kGreen - 3,
         LineWidth=1,
         MarkerColor=ROOT.kGreen - 3,
         MarkerSize=0.5)
# plot.Set(h_LO_130, LineColor=9, LineWidth=1)
# plot.Set(h_LO_inc_cut_130, LineColor=2, LineWidth=2)
# plot.Set(h_LO_500, LineColor=28, LineWidth=1)

h_LO_inc.Draw('HISTSAMEE')
# h_sm.Draw('HISTSAMEE')
# h_th.Draw('HISTSAMEE')
h_NLO_inc.Draw('HISTSAMEE')
# h_LO_130.Draw('HISTSAME')
# h_LO_inc_cut_130.Draw('HISTSAME')
Ejemplo n.º 20
0
        text = ROOT.TPaveText(0.55, 0.37, 0.9, 0.50, 'NDC')
        legend = ROOT.TLegend(0.18, 0.37, 0.5, 0.50, '', 'NDC')
    else:
        text = ROOT.TPaveText(0.55, 0.67, 0.9, 0.80, 'NDC')
        legend = ROOT.TLegend(0.18, 0.67, 0.5, 0.80, '', 'NDC')

    for j, src in enumerate(args.input):
        splitsrc = src.split(':')
        slice = hists[j].ProjectionX('%s_projx_%i' % (hists[j].GetName(), j),
                                     i, i)
        if len(splitsrc) >= 3:
            settings = {
                x.split('=')[0]: eval(x.split('=')[1])
                for x in splitsrc[2].split(',')
            }
            plot.Set(slice, **settings)
        slice.Draw('SAME')
        legend.AddEntry(slice)
        slices.append(slice)
    axis = plot.GetAxisHist(pads[0])
    axis.GetYaxis().SetTitle('Efficiency')
    axis.GetXaxis().SetTitle(args.x_title)
    axis.SetMinimum(float(args.y_range.split(',')[0]))
    axis.SetMaximum(float(args.y_range.split(',')[1]))
    pads[0].SetGrid(1, 1)
    pads[0].SetLogx(True)
    latex.SetTextSize(0.04)

    text.AddText(args.title)
    text.AddText(bin_label)
    text.SetTextAlign(13)
Ejemplo n.º 21
0
    xframe = wsp.var("m_ll").frame(ROOT.RooFit.Title("Passing"))
    width = (wsp.var("m_ll").getMax() -
             wsp.var("m_ll").getMin()) / splitData.At(1).numEntries()
    splitData.At(1).plotOn(xframe)
    wsp.pdf("passing").plotOn(xframe,
                              ROOT.RooFit.Slice(wsp.cat('cat'), "pass"),
                              ROOT.RooFit.LineColor(ROOT.kBlue))
    wsp.pdf("passing").plotOn(xframe,
                              ROOT.RooFit.Slice(wsp.cat('cat'), "pass"),
                              ROOT.RooFit.Components('backgroundPass'),
                              ROOT.RooFit.LineStyle(ROOT.kDashed),
                              ROOT.RooFit.LineColor(ROOT.kBlue))
    pads[0].cd()
    xframe.Draw()
    axis = plot.GetAxisHist(pads[0])
    plot.Set(axis.GetXaxis().SetTitle('m_{tag-probe} (GeV)'))
    plot.Set(axis.GetYaxis().SetTitle('Events / %g GeV' % width))
    plot.DrawTitle(pads[0], 'Pass Region', 1)
    latex.SetTextSize(0.03)
    latex.DrawLatex(0.5, 0.89, args.title)
    latex.DrawLatex(
        0.5, 0.84,
        'p_{T}: [%g, %g] GeV #eta: [%g, %g]' % (b[2], b[3], b[4], b[5]))
    latex.SetTextFont(42)
    latex.DrawLatex(
        0.5, 0.79, '#varepsilon = %.4f #pm %.4f' %
        (wsp.var('efficiency').getVal(), wsp.var('efficiency').getError()))

    xframe2 = wsp.var("m_ll").frame(ROOT.RooFit.Title("Failing"))
    splitData.At(0).plotOn(xframe2)
    wsp.pdf("failing").plotOn(xframe2,
Ejemplo n.º 22
0
ROOT.PyConfig.IgnoreCommandLineOptions = True
ROOT.gROOT.SetBatch(ROOT.kTRUE)
plot.ModTDRStyle()
ROOT.gStyle.SetNdivisions(510, 'XYZ') # probably looks better

canv = ROOT.TCanvas(args.output, args.output)

if args.ratio_to is not None:
    pads = plot.TwoPadSplit(0.30, 0.01, 0.01)
else:
    pads = plot.OnePad()

# Set the style options of the pads
for padx in pads:
    # Use tick marks on oppsite axis edges
    plot.Set(padx, Tickx=1, Ticky=1, Logx=args.logx)
    if args.pad_style is not None:
        settings = {x.split('=')[0]: eval(x.split('=')[1]) for x in args.pad_style.split(',')}
        print 'Applying style options to the TPad(s):'
        print settings
        plot.Set(padx, **settings)

graphs = []
graph_sets = []

if args.higgs_bg or args.higgs_injected:
    legend = plot.PositionedLegend(0.4, 0.25, 3, 0.015)
else:
    legend = plot.PositionedLegend(0.3, 0.2, 3, 0.015)
#legend = plot.PositionedLegend(0.45, 0.10, 3, 0.015)
#plot.Set(legend, NColumns=2)
Ejemplo n.º 23
0
    'Unconstrained': 39,
    'Unrecognised': 2
}
color_hists = {}
color_group_hists = {}

if args.color_groups is not None:
    color_groups = {
        x.split('=')[0]: int(x.split('=')[1]) for x in args.color_groups.split(',')
    }

seen_types = set()

for name, col in colors.iteritems():
    color_hists[name] = ROOT.TH1F()
    plot.Set(color_hists[name], FillColor=col, Title=name)

if args.color_groups is not None:
    for name, col in color_groups.iteritems():
        color_group_hists[name] = ROOT.TH1F()
        plot.Set(color_group_hists[name], FillColor=col, Title=name)

for page in xrange(n):
    #canv = ROOT.TCanvas(args.output, args.output)
    canv = ROOT.TCanvas(args.output, args.output, canvasW, canvasH)
    n_params = len(data['params'][show * page:show * (page + 1)])
    pdata = data['params'][show * page:show * (page + 1)]
    print '>> Doing page %i, have %i parameters' % (page, n_params)

    boxes = []
    for i in xrange(n_params):
Ejemplo n.º 24
0

scenario = OrderedDict()

scenario["mt_tot"] = "m_{T}^{tot}"
scenario["lowmass"] = "m_{#tau#tau} vs p_{T}^{#tau#tau}"

colour = {
    "mt_tot": 4,
    "lowmass": 4,
}

for proc in ['gg', 'bb']:

    c = ROOT.TCanvas('c', 'c', 700, 700)
    plot.Set(c, Tickx=1, Ticky=1)
    c.SetLogy()
    c.SetLogx()

    limit_dict = {}
    first_pass = True
    for key, val in scenario.items():

        # change so in bin center

        limit_dict[key] = {}

        limit_dict[key]["p_value"] = ROOT.TGraph()
        limit_dict[key]["significance"] = ROOT.TGraph()

        i = 1
Ejemplo n.º 25
0
if len(other_scans) > 0:
    if min(mins) < main_scan['graph'].GetX()[0]:
        new_min = min(mins) - (main_scan['graph'].GetX()[0] - new_min)
    if max(maxs) > main_scan['graph'].GetX()[main_scan['graph'].GetN() - 1]:
        new_max = max(maxs) + (
            new_max - main_scan['graph'].GetX()[main_scan['graph'].GetN() - 1])
    axishist.GetXaxis().SetLimits(new_min, new_max)

if args.x_range is not None:
    axishist.GetXaxis().SetLimits(float(args.x_range.split(',')[0]),
                                  float(args.x_range.split(',')[1]))

if args.vertical_line is not None:
    vline = ROOT.TLine()
    plot.Set(vline, LineColor=16, LineWidth=1, LineStyle=7)
    plot.DrawVerticalLine(pads[0], vline, args.vertical_line)

if args.breakdown and args.envelope:
    for other in new_others:
        other['graph'].Draw('SAME')

for other in other_scans:
    if args.breakdown is not None:
        other['graph'].SetMarkerSize(0.4)
    if args.pub:
        other['graph'].SetMarkerSize(0.0)
    other['graph'].Draw('SAME')

line = ROOT.TLine()
for i, yval in enumerate(yvals):
Ejemplo n.º 26
0
    'Unconstrained': 39,
    'Unrecognised': 2
}
color_hists = {}
color_group_hists = {}

if args.color_groups is not None:
    color_groups = {
        x.split('=')[0]: int(x.split('=')[1]) for x in args.color_groups.split(',')
    }

seen_types = set()

for name, col in colors.iteritems():
    color_hists[name] = ROOT.TH1F()
    plot.Set(color_hists[name], FillColor=col, Title=name)

if args.color_groups is not None:
    for name, col in color_groups.iteritems():
        color_group_hists[name] = ROOT.TH1F()
        plot.Set(color_group_hists[name], FillColor=col, Title=name)

for page in xrange(n):
    canv = ROOT.TCanvas(args.output, args.output)
    n_params = len(data['params'][show * page:show * (page + 1)])
    pdata = data['params'][show * page:show * (page + 1)]
    print '>> Doing page %i, have %i parameters' % (page, n_params)

    boxes = []
    for i in xrange(n_params):
        y1 = ROOT.gStyle.GetPadBottomMargin()
Ejemplo n.º 27
0
 y2 = []
 q = array('d', [0.68, 0.95, 0.997])
 res = array('d', [0, 0, 0])
 for ib, cutoff in enumerate(arr_x):
     hists[year]['wg_M_scan']['WG-NLO']['cut_%i' % cutoff].GetQuantiles(
         3, res, q)
     y0.append(res[0])
     y1.append(res[1])
     y2.append(res[2])
 gr0 = ROOT.TGraph(len(arr_x), arr_x, array('d', y0))
 gr1 = ROOT.TGraph(len(arr_x), arr_x, array('d', y1))
 gr2 = ROOT.TGraph(len(arr_x), arr_x, array('d', y2))
 canv = ROOT.TCanvas('wg_M_cutoff_quantiles_%s' % year,
                     'wg_M_cutoff_quantiles_%s' % year)
 pads = plot.OnePad()
 plot.Set(gr0, LineWidth=2, LineColor=1, MarkerColor=1)
 plot.Set(gr1, LineWidth=2, LineColor=2, MarkerColor=2)
 plot.Set(gr2, LineWidth=2, LineColor=4, MarkerColor=4)
 gr0.Print()
 gr0.Draw('ALP')
 gr1.Draw('LPSAME')
 gr2.Draw('LPSAME')
 axis = plot.GetAxisHist(pads[0])
 axis.SetMaximum(4000)
 axis.GetXaxis().SetTitle('p_{T}^{#gamma} cut-off [GeV]')
 axis.GetYaxis().SetTitle('M_{W#gamma} [GeV]')
 legend = plot.PositionedLegend(0.30, 0.20, 3, 0.015)
 legend.AddEntry(gr0, '68% quantile')
 legend.AddEntry(gr1, '95% quantile')
 legend.AddEntry(gr2, '99.7% quantile')
 legend.Draw()
Ejemplo n.º 28
0
filename, folder = args.input.split(':')
file = ROOT.TFile(filename)

doIsoDensity = False
doDeltaBeta = False
doSfFit = True
## The isolation density summary plots

if doIsoDensity:
    for var, label in [('nt', 'Iso #gamma'), ('po', 'Signal #gamma')]:
        canv = ROOT.TCanvas(output + "_%s_isodensity" % var,
                            output + "_%s_isodensity" % var)
        pads = plot.TwoPadSplit(0.27, 0.01, 0.01)
        axis = ROOT.TH1F('axis', '', 5, 0, 0.5)
        axisr = ROOT.TH1F('axisr', '', 5, 0, 0.5)
        plot.Set(axis.GetXaxis(), Title='#DeltaR from #vec{#tau}_{charged}')
        plot.Set(axis.GetYaxis(), Title='%s energy density (GeV)' % label)
        hists_data = []
        hists_mc = []
        axis.Draw()
        graph_data = ROOT.TGraphAsymmErrors(5)
        graph_mc = ROOT.TGraphAsymmErrors(5)
        graph_ratio = ROOT.TGraphAsymmErrors(5)
        for i in xrange(5):
            hists_data.append(
                Getter(
                    file, '%s/%s_density_0p%i_0p%i/data_obs' %
                    (folder, var, i, i + 1)))
            hists_mc.append(
                Getter(file, '%s/%s_density_0p%i_0p%i/ZTT' %
                       (folder, var, i, i + 1)))
Ejemplo n.º 29
0
pads[1].SetLogy(args.logy)
pads[1].SetLogx(args.logx)
pads[1].SetTickx()
pads[1].SetTicky()
# h_proto.GetXaxis().SetRangeUser(130,400)
# h_proto.GetYaxis().SetRangeUser(1,20)

fillstyle = 'FSAME'
if args.hist is not None:
    fillstyle = 'LSAME'

# Now we draw the actual contours
if 'exp-2' in contours and 'exp+2' in contours:
    for i, gr in enumerate(contours['exp-2']):
        plot.Set(gr, LineColor=0, FillColor=ROOT.kGray + 0, FillStyle=1001)
        if args.hist is not None:
            plot.Set(gr, LineColor=ROOT.kGray + 0, LineWidth=2)
        gr.Draw(fillstyle)
if 'exp-1' in contours and 'exp+1' in contours:
    for i, gr in enumerate(contours['exp-1']):
        plot.Set(gr, LineColor=0, FillColor=ROOT.kGray + 1, FillStyle=1001)
        if args.hist is not None:
            plot.Set(gr, LineColor=ROOT.kGray + 1, LineWidth=2)
        gr.Draw(fillstyle)
    fill_col = ROOT.kGray + 0
    # If we're only drawing the 1 sigma contours then we should fill with
    # white here instead
    if 'exp-2' not in contours and 'exp+2' not in contours:
        fill_col = ROOT.kWhite
    for i, gr in enumerate(contours['exp+1']):
Ejemplo n.º 30
0
                                   array('d', ey_stat_lo),
                                   array('d', ey_stat_hi)))
        obs_graphs_syst.append(
            ROOT.TGraphAsymmErrors(len(x_vals), array('d', x_vals),
                                   array('d', y_vals), array('d', ex_syst_lo),
                                   array('d', ex_syst_hi),
                                   array('d', ey_syst_lo),
                                   array('d', ey_syst_hi)))

h_axes = [h.Clone() for h in ref_hists_1D]
r_h_axes = [h.Clone() for h in ref_hists_1D]

legend = ROOT.TLegend(*(settings[args.selection]['legend'] + ['', 'NBNDC']))

h_obs = ROOT.TH1F('h_obs', '', 1, 0, 1)
plot.Set(h_obs, LineWidth=2)

latex = ROOT.TLatex()
latex.SetTextFont(62)
latex.SetTextSize(0.03)
latex.SetTextAlign(22)
# latex.SetTextColor(14)
h_matrix = None
h_matrix_fill = None

h_store = {}

for i, h in enumerate(h_axes):
    print i
    hr = r_h_axes[i]
    h.Reset()