示例#1
0
def do_mc_pt_comparison_plot(dirname_label_pairs, output_filename,
                             qcd_filename, **plot_kwargs):
    # qcd_files = [cu.open_root_file(os.path.join(dl[0], qgc.QCD_FILENAME)) for dl in dirname_label_pairs]
    qcd_files = [
        cu.open_root_file(os.path.join(dl[0], qgc.QCD_PYTHIA_ONLY_FILENAME))
        for dl in dirname_label_pairs
    ]
    histname = "Dijet_tighter/pt_jet1"
    qcd_hists = [cu.get_from_tfile(qf, histname) for qf in qcd_files]
    N = len(dirname_label_pairs)
    conts = [
        Contribution(qcd_hists[i],
                     label=lab,
                     marker_color=cu.get_colour_seq(i, N),
                     line_color=cu.get_colour_seq(i, N),
                     line_style=(i % 3) + 1,
                     line_width=2,
                     rebin_hist=1,
                     subplot=qcd_hists[0] if i != 0 else None)
        for i, (d, lab) in enumerate(dirname_label_pairs)
    ]
    plot = Plot(conts,
                what='hist',
                ytitle="N",
                subplot_limits=(0.5, 1.5),
                subplot_type="ratio",
                subplot_title="* / %s" % (dirname_label_pairs[0][1]),
                **plot_kwargs)
    plot.y_padding_max_log = 500
    plot.legend.SetY1(0.7)
    plot.plot("NOSTACK HIST E")
    plot.set_logx(do_more_labels=False)
    plot.set_logy(do_more_labels=False)

    plot.save(output_filename)
def do_jet_pt_rel_error_with_var_cuts(histname, cuts, input_filename, output_filename):
    ROOT.gStyle.SetPalette(palette_1D)
    tf = cu.open_root_file(input_filename)
    h3d = cu.get_from_tfile(tf, histname)
    if h3d.GetEntries() == 0:
        return
    pt_hists = []
    for cut in cuts:
        max_bin = h3d.GetZaxis().FindFixBin(cut)
        # print("cut:", cut, "bin:", max_bin)
        h = h3d.ProjectionY("pt_var_lt_%g" % cut, 0, -1, 0, max_bin, "e")
        h2 = h.Clone()
        h2.Rebin(2)
        if h.GetEntries() > 0:
            h3 = qgp.hist_divide_bin_width(h2)
        # convert bin contents to bin error/bin contents
        for ibin in range(1, h2.GetNbinsX()+1):
            if h3.GetBinContent(ibin) == 0:
                continue
            h3.SetBinContent(ibin, h3.GetBinError(ibin) / h3.GetBinContent(ibin))
            h3.SetBinError(ibin, 0)
        pt_hists.append(h3)

    line_styles = [1, 2, 3]
    n_line_styles = len(line_styles)
    conts = [Contribution(h, label=" < %g" % cut,
                          line_color=cu.get_colour_seq(ind, len(cuts)),
                          line_style=line_styles[ind % n_line_styles],
                          line_width=2,
                          marker_color=cu.get_colour_seq(ind, len(cuts)),
                          subplot=pt_hists[-1])
             for ind, (h, cut) in enumerate(zip(pt_hists, cuts))]

    jet_str = pt_genjet_str if "_vs_pt_genjet_vs_" in histname else pt_str
    weight_str = "(unweighted)" if "unweighted" in histname else "(weighted)"
    ratio_lims = (0.98, 1.02) if "unweighted" in histname else None
    plot = Plot(conts, what='hist',
                title='%s for cuts on %s %s' % (jet_str, get_var_str(histname), weight_str),
                xtitle=None,
                ytitle='Relative error',
                # xlim=None, ylim=None,
                legend=True,
                subplot_type='ratio',
                subplot_title='* / var < %g' % cuts[-1],
                subplot_limits=ratio_lims,
                has_data=False)
    plot.y_padding_max_log = 200
    plot.subplot_maximum_ceil = 2
    plot.subplot_maximum_floor = 1.02
    plot.subplot_minimum_ceil = 0.98
    plot.legend.SetY1(0.7)
    plot.legend.SetY2(0.89)
    plot.legend.SetX1(0.78)
    plot.legend.SetX2(0.88)
    plot.plot("NOSTACK HISTE", "NOSTACK HIST")
    plot.set_logx(True, do_more_labels=True)
    plot.set_logy(True, do_more_labels=False)
    plot.save(output_filename)
示例#3
0
def do_data_mc_plot(dirname, histname, output_filename, **plot_kwargs):
    data_file = cu.open_root_file(os.path.join(dirname, qgc.JETHT_ZB_FILENAME))
    qcd_file = cu.open_root_file(os.path.join(dirname, qgc.QCD_FILENAME))
    qcd_py_file = cu.open_root_file(
        os.path.join(dirname, qgc.QCD_PYTHIA_ONLY_FILENAME))
    qcd_hpp_file = cu.open_root_file(
        os.path.join(dirname, qgc.QCD_HERWIG_FILENAME))

    data_hist = cu.get_from_tfile(data_file, histname)
    qcd_hist = cu.get_from_tfile(qcd_file, histname)
    qcd_py_hist = cu.get_from_tfile(qcd_py_file, histname)
    qcd_hpp_hist = cu.get_from_tfile(qcd_hpp_file, histname)
    conts = [
        Contribution(data_hist,
                     label="Data",
                     line_color=ROOT.kBlack,
                     marker_size=0,
                     marker_color=ROOT.kBlack),
        Contribution(qcd_hist,
                     label="QCD MG+PYTHIA8 MC",
                     line_color=qgc.QCD_COLOUR,
                     subplot=data_hist,
                     marker_size=0,
                     marker_color=qgc.QCD_COLOUR),
        Contribution(qcd_py_hist,
                     label="QCD PYTHIA8 MC",
                     line_color=qgc.QCD_COLOURS[2],
                     subplot=data_hist,
                     marker_size=0,
                     marker_color=qgc.QCD_COLOURS[2]),
        # Contribution(qcd_hpp_hist, label="QCD HERWIG++ MC", line_color=qgc.HERWIGPP_QCD_COLOUR, subplot=data_hist, marker_size=0, marker_color=qgc.HERWIGPP_QCD_COLOUR),
    ]
    plot = Plot(conts,
                what='hist',
                ytitle="N",
                xtitle="p_{T}^{Leading jet} [GeV]",
                subplot_type="ratio",
                subplot_title="Simulation / data",
                ylim=[1E3, None],
                lumi=cu.get_lumi_str(do_dijet=True, do_zpj=False),
                **plot_kwargs)
    plot.y_padding_max_log = 500

    plot.legend.SetX1(0.55)
    plot.legend.SetX2(0.98)
    plot.legend.SetY1(0.7)
    # plot.legend.SetY2(0.88)
    plot.plot("NOSTACK HIST E")
    plot.set_logx(do_more_labels=True, do_exponent=False)
    plot.set_logy(do_more_labels=False)

    plot.save(output_filename)
示例#4
0
def do_genht_plot(dirname, output_filename, **plot_kwargs):
    qcd_file = cu.open_root_file(os.path.join(dirname, qgc.QCD_FILENAME))
    histname = "Dijet_gen/gen_ht"
    qcd_hist = cu.get_from_tfile(qcd_file, histname)
    conts = [Contribution(qcd_hist, label="QCD MC", line_color=ROOT.kRed)]
    plot = Plot(conts, what='hist', ytitle="N", **plot_kwargs)
    plot.y_padding_max_log = 500
    plot.legend.SetY1(0.7)
    plot.plot("NOSTACK HIST E")
    plot.set_logx(do_more_labels=False)
    plot.set_logy(do_more_labels=False)

    plot.save(output_filename)
示例#5
0
def do_plot(entries, output_file, hist_name=None, xlim=None, ylim=None, rebin=2, is_data=True, is_ak8=False):
    components = []
    do_unweighted = any(["unweighted" in e.get('hist_name', hist_name) for e in entries])
    for ent in entries:
        if 'tfile' not in ent:
            ent['tfile'] = cu.open_root_file(ent['filename'])
        ent['hist'] = cu.get_from_tfile(ent['tfile'], ent.get('hist_name', hist_name))
        if not do_unweighted and 'scale' in ent:
            ent['hist'].Scale(ent.get('scale', 1))
        components.append(
            Contribution(ent['hist'],
                         fill_color=ent['color'],
                         line_color=ent['color'],
                         marker_color=ent['color'],
                         marker_size=0,
                         line_width=2,
                         label=ent['label'],
                         rebin_hist=rebin
                        )
        )
        # print stats
        print(ent['hist_name'], ent['label'], ent['hist'].Integral())
    title = 'AK8 PUPPI' if is_ak8 else 'AK4 PUPPI'
    plot = Plot(components,
                what='hist',
                has_data=is_data,
                title=title,
                xlim=xlim,
                ylim=ylim,
                xtitle="p_{T}^{jet 1} [GeV]",
                ytitle="Unweighted N" if do_unweighted else 'N')
    # plot.y_padding_min_log = 10 if 'unweighted' in hist_name else 10
    plot.default_canvas_size = (700, 600)
    plot.legend.SetNColumns(2)
    plot.legend.SetX1(0.55)
    plot.legend.SetY1(0.7)
    plot.legend.SetY2(0.88)
    plot.plot("HISTE")
    plot.set_logx()
    plot.set_logy(do_more_labels=False)
    plot.save(output_file)

    # do non-stacked version
    stem, ext = os.path.splitext(output_file)
    plot.plot("HISTE NOSTACK")
    plot.set_logx()
    plot.set_logy(do_more_labels=False)
    plot.save(stem+"_nostack" + ext)
示例#6
0
def do_response_graph(pt_bins, zpj_fits, dj_fits, title, output_filename):
    """Create and plot graph from fit results
    
    Parameters
    ----------
    zpj_fits : TF1
        Description
    dj_fits : TF1
        Description
    output_filename : str
        Description
    """
    gr_zpj = fits_to_graph(pt_bins, zpj_fits)
    gr_qcd = fits_to_graph(pt_bins, dj_fits)
    conts = [
        Contribution(gr_zpj,
                     label=qgc.DY_ZpJ_LABEL,
                     line_color=qgc.DY_COLOUR,
                     marker_color=qgc.DY_COLOUR,
                     marker_style=22),
        Contribution(gr_qcd,
                     label=qgc.QCD_Dijet_LABEL,
                     line_color=qgc.QCD_COLOUR,
                     marker_color=qgc.QCD_COLOUR,
                     marker_style=23)
    ]
    xmin = pt_bins[0][0]
    xmax = pt_bins[-1][1]
    plot = Plot(conts,
                what="graph",
                legend=True,
                xlim=(xmin, xmax),
                title=title,
                xtitle="p_{T}^{GenJet} [GeV]",
                ytitle="Mean fitted response #pm fit error")
    plot.plot("ALP")
    plot.set_logx()
    line_center = ROOT.TLine(xmin, 1, xmax, 1)
    line_center.SetLineStyle(2)
    line_center.Draw("SAME")
    line_upper = ROOT.TLine(xmin, 1.1, xmax, 1.1)
    line_upper.SetLineStyle(2)
    line_upper.Draw("SAME")
    line_lower = ROOT.TLine(xmin, 0.9, xmax, 0.9)
    line_lower.SetLineStyle(2)
    line_lower.Draw("SAME")
    plot.save(output_filename)
示例#7
0
def do_pthat_comparison_plot(dirname_label_pairs, output_filename,
                             **plot_kwargs):
    qcd_files = [
        cu.open_root_file(os.path.join(dl[0], qgc.QCD_PYTHIA_ONLY_FILENAME))
        for dl in dirname_label_pairs
    ]
    histname = "Dijet_gen/ptHat"
    qcd_hists = [cu.get_from_tfile(qf, histname) for qf in qcd_files]
    N = len(dirname_label_pairs)
    pthat_rebin = array('d', [
        15, 30, 50, 80, 120, 170, 300, 470, 600, 800, 1000, 1400, 1800, 2400,
        3200, 5000
    ])
    nbins = len(pthat_rebin) - 1
    qcd_hists = [
        h.Rebin(nbins, cu.get_unique_str(), pthat_rebin) for h in qcd_hists
    ]
    conts = [
        Contribution(qcd_hists[i],
                     label=lab,
                     marker_color=cu.get_colour_seq(i, N),
                     line_color=cu.get_colour_seq(i, N),
                     line_style=i + 1,
                     line_width=2,
                     subplot=qcd_hists[0] if i != 0 else None)
        for i, (d, lab) in enumerate(dirname_label_pairs)
    ]
    plot = Plot(conts,
                what='hist',
                ytitle="N",
                subplot_limits=(0.75, 1.25),
                subplot_type="ratio",
                subplot_title="* / %s" % (dirname_label_pairs[0][1]),
                **plot_kwargs)
    plot.y_padding_max_log = 500
    plot.legend.SetY1(0.7)
    plot.plot("NOSTACK HIST E")
    plot.set_logx(do_more_labels=False)
    plot.set_logy(do_more_labels=False)

    plot.save(output_filename)
示例#8
0
def compare_flavour_fraction_hists_vs_pt_from_contribs(
        contribs,
        flav,
        output_filename,
        title="",
        xtitle="p_{T}^{jet} [GeV]",
        **plot_kwargs):
    """Plot a specified flavour fraction vs pT for several sources.

    TODO: use this one more often - compare_flavour_fractions_vs_pt() is almost identical but has to deal with npartons
    """
    flav_str = FLAV_STR_DICT[flav]
    ytitle = "Fraction of %s %ss" % (flav_str.lower(), get_jet_str(''))
    p = Plot(contribs,
             what='graph',
             xtitle=xtitle,
             ytitle=ytitle,
             title=title,
             xlim=(50, 2000),
             ylim=(0, 1),
             has_data=False,
             **plot_kwargs)
    p.default_canvas_size = (600, 600)
    try:
        p.plot("AP")
        p.main_pad.SetBottomMargin(0.16)
        p.get_modifier().GetXaxis().SetTitleOffset(1.4)
        p.get_modifier().GetXaxis().SetTitleSize(.045)
        p.legend.SetX1(0.56)
        p.legend.SetY1(0.65)
        p.legend.SetY2(0.87)
        if len(contribs) >= 4:
            p.legend.SetY1(0.7)
            p.legend.SetX1(0.5)
            p.legend.SetNColumns(2)
        p.set_logx(do_more_labels=True, do_exponent=False)
        p.save(output_filename)
    except ZeroContributions:
        warnings.warn("No contributions for %s" % output_filename)
示例#9
0
def do_genht_comparison_plot(dirname_label_pairs, output_filename,
                             **plot_kwargs):
    """Like do_genht but for multiple samples"""
    qcd_files = [
        cu.open_root_file(os.path.join(dl[0], qgc.QCD_FILENAME))
        for dl in dirname_label_pairs
    ]
    histname = "Dijet_gen/gen_ht"
    qcd_hists = [cu.get_from_tfile(qf, histname) for qf in qcd_files]
    N = len(dirname_label_pairs)
    conts = [
        Contribution(qcd_hists[i],
                     label=lab,
                     marker_color=cu.get_colour_seq(i, N),
                     line_color=cu.get_colour_seq(i, N),
                     line_style=i + 1,
                     line_width=2,
                     subplot=qcd_hists[0] if i != 0 else None)
        for i, (d, lab) in enumerate(dirname_label_pairs)
    ]
    plot = Plot(
        conts,
        what='hist',
        ytitle="N",
        # subplot_limits=(0.75, 1.25),
        subplot_type="ratio",
        subplot_title="* / %s" % (dirname_label_pairs[0][1]),
        ylim=[1E6, None],
        **plot_kwargs)
    plot.y_padding_max_log = 500
    plot.legend.SetY1(0.7)
    plot.subplot_maximum_ceil = 5
    plot.plot("NOSTACK HIST E")
    plot.set_logx(do_more_labels=False)
    plot.set_logy(do_more_labels=False)

    plot.save(output_filename)
def do_pt_transfer_plot(tdir, plot_dir):
    """Plot ratio between pt bins of the spectrum. Check to make sure xfer factor << drop in pt"""
    plot_dir = os.path.join(plot_dir, tdir.GetName())
    cu.check_dir_exists_create(plot_dir)
    hist_name = "pt_jet_response_binning"
    h = cu.get_from_tfile(tdir, hist_name)
    binning = [
        h.GetXaxis().GetBinLowEdge(bin_ind)
        for bin_ind in range(1,
                             h.GetNbinsX() + 1)
    ]
    hist_factors = ROOT.TH1F(
        "hist_factors" + cu.get_unique_str(),
        ";p_{T}^{Reco} [GeV];Fraction rel to previous bin",
        len(binning) - 1, array('d', binning))
    for bin_ind in range(2, h.GetNbinsX() + 1):
        cont = h.GetBinContent(bin_ind)
        cont_prev = h.GetBinContent(bin_ind - 1)
        if cont == 0 or cont_prev == 0:
            continue
        factor = cont / cont_prev
        hist_factors.SetBinContent(bin_ind, factor)
        hist_factors.SetBinError(bin_ind, 0)

    col_purity = ROOT.kBlack
    conts = [
        Contribution(hist_factors,
                     label="Factor relative to previous bin",
                     line_color=col_purity,
                     marker_color=col_purity),
        # Contribution(hist_purity, label="Purity (gen in right bin)", line_color=col_purity, marker_color=col_purity),
    ]
    xlim = [30, binning[-1]]
    plot = Plot(conts, what='hist', xlim=xlim)
    plot.plot()
    plot.set_logx()
    plot.save(os.path.join(plot_dir, 'pt_migration_factors.%s' % (OUTPUT_FMT)))
示例#11
0
def compare_flavour_fractions_vs_pt(input_files,
                                    dirnames,
                                    pt_bins,
                                    labels,
                                    flav,
                                    output_filename,
                                    title="",
                                    var_prepend="",
                                    which_jet="both",
                                    xtitle="p_{T}^{jet} [GeV]",
                                    n_partons='all',
                                    is_preliminary=True):
    """Plot a specified flavour fraction vs pT for several sources.
    Each entry in input_files, dirnames, and labels corresponds to one line
    n_partons can be a str, 'all', '1', etc, or a list of str to include

    TODO: fix this - bit stupid input format
    """
    bin_centers = [0.5 * (x[0] + x[1]) for x in pt_bins]
    bin_widths = [0.5 * (x[1] - x[0]) for x in pt_bins]

    if isinstance(n_partons, str):
        n_partons = [n_partons]

    contribs = []
    for n_parton_ind, n_parton in enumerate(n_partons):
        metric = 'pt'
        if n_parton.lower() != 'all':
            metric = 'pt_npartons_%s' % n_parton
        info = [
            get_flavour_efficiencies(
                ifile,
                bins=pt_bins,
                hist_name=get_flavour_hist_name(
                    dirname=dname,
                    var_prepend=var_prepend,
                    which_jet=(which_jet if "Dijet" in dname else "both"),
                    metric=metric))
            for ifile, dname in zip(input_files, dirnames)
        ]
        N = len(bin_centers)

        colours = [ROOT.kBlack, ROOT.kBlue, ROOT.kRed, ROOT.kGreen + 2]

        for i, fdict in enumerate(info):
            if flav in ['u', 'd', 's', 'c', 'b', 't', 'g']:
                obj = fdict[flav].CreateGraph()
            else:
                raise RuntimeError("Robin broke 1-X functionality")
                obj = ROOT.TGraphErrors(
                    N, np.array(bin_centers),
                    1. - np.array(fdict[flav.replace("1-", '')]),
                    np.array(bin_widths), np.zeros(N))
            if obj.GetN() == 0:
                continue
            n_parton_str = "" if n_parton == "all" else " (%s-parton)" % n_parton
            c = Contribution(obj,
                             label="%s%s" % (labels[i], n_parton_str),
                             line_color=colours[i] + n_parton_ind,
                             line_width=1,
                             line_style=n_parton_ind + 1,
                             marker_style=20 + i,
                             marker_color=colours[i] + n_parton_ind,
                             marker_size=1,
                             leg_draw_opt="LP")
            contribs.append(c)

    flav_str = FLAV_STR_DICT[flav]
    ytitle = "Fraction of %s %ss" % (flav_str.lower(), get_jet_str(''))
    p = Plot(contribs,
             what='graph',
             xtitle=xtitle,
             ytitle=ytitle,
             title=title,
             xlim=(pt_bins[0][0], pt_bins[-1][1]),
             ylim=(0, 1),
             has_data=False,
             is_preliminary=is_preliminary)
    p.default_canvas_size = (600, 600)
    try:
        p.plot("AP")
        p.main_pad.SetBottomMargin(0.16)
        p.get_modifier().GetXaxis().SetTitleOffset(1.4)
        p.get_modifier().GetXaxis().SetTitleSize(.045)
        p.legend.SetX1(0.56)
        p.legend.SetY1(0.65)
        p.legend.SetY2(0.87)
        p.set_logx(do_more_labels=True, do_exponent=False)
        p.save(output_filename)
    except ZeroContributions:
        pass
示例#12
0
def do_zerobias_per_run_comparison_plot(dirname_label_pairs,
                                        output_dir,
                                        append="",
                                        title="",
                                        **plot_kwargs):
    runs = [
        (qgc.ZEROBIAS_RUNB_FILENAME, 'B'),
        (qgc.ZEROBIAS_RUNC_FILENAME, 'C'),
        (qgc.ZEROBIAS_RUND_FILENAME, 'D'),
        (qgc.ZEROBIAS_RUNE_FILENAME, 'E'),
        (qgc.ZEROBIAS_RUNF_FILENAME, 'F'),
        (qgc.ZEROBIAS_RUNG_FILENAME, 'G'),
        (qgc.ZEROBIAS_RUNH_FILENAME, 'H'),
    ]
    zb_entry = {
        'label': 'HLT_ZeroBias',
        'color': ROOT.kMagenta - 9,
        # 'scale': 35918219492.947 / 29048.362
        'scale': 1
    }

    for filename, run_period in runs:
        zb_root_files = [
            cu.open_root_file(os.path.join(dl[0], filename))
            for dl in dirname_label_pairs
        ]

        # PT JET 1
        zb_hist_names = [
            "Dijet_jet_hist_0/pt_1", "Dijet_jet_hist_unweighted_0/pt_1"
        ][1:]
        N = len(dirname_label_pairs)
        rebin = 2
        for zb_name in zb_hist_names:
            # add zeero bias ones
            this_data_entries = [
                Contribution(
                    cu.get_from_tfile(zb_root_files[i], zb_name),
                    label=zb_entry['label'] + " Run %s: " % run_period + l,
                    marker_color=zb_entry['color'],
                    line_color=zb_entry['color'],
                    line_style=1 + i,
                    rebin_hist=rebin,
                ) for i, (d, l) in enumerate(dirname_label_pairs)
            ]
            for c in this_data_entries[1:]:
                c.subplot = this_data_entries[0].obj

            plot = Plot(
                this_data_entries,
                what='hist',
                title=title,
                xtitle="p_{T}^{jet 1} [GeV]",
                ytitle="N",
                xlim=[30, 1000],
                ylim=[1E3, None],
                # ylim=[10, 1E8] if 'unweighted' in ht_name else [1, 1E12],
                subplot_type='ratio',
                subplot_title='* / %s' % dirname_label_pairs[0][1],
                **plot_kwargs)
            plot.subplot_maximum_ceil = 10
            plot.default_canvas_size = (800, 600)
            plot.y_padding_max_log = 500
            plot.legend.SetY1(0.7)
            plot.legend.SetY2(0.88)
            plot.legend.SetX1(0.5)
            plot.legend.SetNColumns(2)
            plot.plot("NOSTACK HISTE")
            plot.set_logx(do_more_labels=False)
            plot.set_logy(do_more_labels=False)
            output_filename = "%s/DataJetHTZB-pt_jet1%s_Run%s%s.pdf" % (
                output_dir, "_unweighted" if 'unweighted' in zb_name else "",
                run_period, append)
            plot.save(output_filename)

        # ETA JET 1
        zb_hist_names = ["Dijet_jet_hist_unweighted_0/eta_1"]

        N = len(dirname_label_pairs)
        rebin = 2
        for zb_name in zb_hist_names:
            # add zero bias ones
            this_data_entries = [
                Contribution(
                    cu.get_from_tfile(zb_root_files[i], zb_name),
                    label=zb_entry['label'] + " Run %s: " % run_period + l,
                    marker_color=zb_entry['color'],
                    line_color=zb_entry['color'],
                    line_style=1 + i,
                    rebin_hist=rebin,
                ) for i, (d, l) in enumerate(dirname_label_pairs)
            ]
            for c in this_data_entries[1:]:
                c.subplot = this_data_entries[0].obj

            # plot zb
            plot = Plot(
                this_data_entries,
                what='hist',
                title=title,
                xtitle="y^{jet 1}",
                ytitle="N",
                subplot_type='ratio',
                subplot_title='* / %s' % dirname_label_pairs[0][1],
                # subplot_limits=(0, 5),
                **plot_kwargs)
            plot.subplot_maximum_ceil = 5
            plot.default_canvas_size = (800, 600)
            plot.y_padding_max_log = 500
            plot.legend.SetY1(0.7)
            plot.legend.SetY2(0.88)
            plot.legend.SetX1(0.5)
            plot.legend.SetNColumns(2)
            plot.plot("NOSTACK HISTE")
            output_filename = "%s/DataZB-eta_jet1%s_Run%s%s.pdf" % (
                output_dir, "_unweighted" if 'unweighted' in zb_name else "",
                run_period, append)
            plot.save(output_filename)
示例#13
0
def do_jetht_trigger_comparison_plot(dirname_label_pairs,
                                     output_dir,
                                     append="",
                                     title="",
                                     **plot_kwargs):
    # Unweighted pt, showing contributions from different triggers
    # Have to add in ZB manually
    zb_entry = {
        'label': 'HLT_ZeroBias',
        'color': ROOT.kMagenta - 9,
        # 'scale': 35918219492.947 / 29048.362
        'scale': 1
    }

    jet_ht_entries = [
        {
            'ind': '0',
            'label': "PFJet40",
            'color': ROOT.kRed,
        },
        {
            'ind': '1',
            'label': "PFJet60",
            'color': ROOT.kBlue,
        },
        {
            'ind': '2',
            'label': "PFJet80",
            'color': ROOT.kGreen + 2,
        },
        {
            'ind': '3',
            'label': "PFJet140",
            'color': ROOT.kViolet + 5,
        },
        {
            'ind': '4',
            'label': "PFJet200",
            'color': ROOT.kOrange,
        },
        {
            'ind': '5',
            'label': "PFJet260",
            'color': ROOT.kTeal,
        },
        {
            'ind': '6',
            'label': "PFJet320",
            'color': ROOT.kViolet,
        },
        {
            'ind': '7',
            'label': "PFJet400",
            'color': ROOT.kOrange - 6
        },
        {
            'ind': '8',
            'label': "PFJet450",
            'color': ROOT.kAzure + 1,
        },
    ]

    # PT JET 1
    zb_hist_names = [
        "Dijet_jet_hist_0/pt_1", "Dijet_jet_hist_unweighted_0/pt_1"
    ]
    jet_ht_hist_names = [
        "Dijet_jet_hist_{ind}/pt_1", "Dijet_jet_hist_unweighted_{ind}/pt_1"
    ]

    zb_root_files = [
        cu.open_root_file(os.path.join(dl[0], qgc.ZB_FILENAME))
        for dl in dirname_label_pairs
    ]
    jetht_root_files = [
        cu.open_root_file(os.path.join(dl[0], qgc.JETHT_FILENAME))
        for dl in dirname_label_pairs
    ]
    N = len(dirname_label_pairs)
    rebin = 2
    for zb_name, ht_name in zip(zb_hist_names, jet_ht_hist_names):
        # add zeero bias ones
        this_data_entries = [
            Contribution(
                cu.get_from_tfile(zb_root_files[i], zb_name),
                label=zb_entry['label'] + ": " + l,
                marker_color=zb_entry['color'],
                line_color=zb_entry['color'],
                line_style=1 + i,
                rebin_hist=rebin,
            ) for i, (d, l) in enumerate(dirname_label_pairs)
        ]
        for c in this_data_entries[1:]:
            c.subplot = this_data_entries[0].obj

        # # add jet ht ones
        for ent in jet_ht_entries:
            histname = ht_name.format(ind=ent['ind'])
            new_entries = [
                Contribution(
                    cu.get_from_tfile(jetht_root_files[i], histname),
                    label=ent['label'] + ": " + l,
                    marker_color=ent['color'],
                    line_color=ent['color'],
                    line_style=1 + i,
                    rebin_hist=rebin,
                ) for i, (d, l) in enumerate(dirname_label_pairs)
            ]
            for c in new_entries[1:]:
                c.subplot = new_entries[0].obj

            this_data_entries.extend(new_entries)

        plot = Plot(
            this_data_entries,
            what='hist',
            title=title,
            ytitle="N",
            xtitle="p_{T}^{jet 1} [GeV]",
            xlim=[30, 1000],
            ylim=[1E3, None],
            # ylim=[10, 1E8] if 'unweighted' in ht_name else [1, 1E12],
            subplot_type='ratio',
            subplot_title='* / %s' % dirname_label_pairs[0][1],
            **plot_kwargs)
        plot.default_canvas_size = (800, 600)
        plot.subplot_maximum_ceil = 10
        plot.y_padding_max_log = 500
        plot.legend.SetY1(0.7)
        plot.legend.SetY2(0.88)
        plot.legend.SetX1(0.5)
        plot.legend.SetNColumns(2)
        plot.plot("NOSTACK HISTE")
        plot.set_logx(do_more_labels=False)
        plot.set_logy(do_more_labels=False)
        output_filename = "%s/DataJetHTZB-pt_jet1%s%s.pdf" % (
            output_dir, "_unweighted" if 'unweighted' in zb_name else "",
            append)
        plot.save(output_filename)

    # ETA JET 1
    zb_hist_names = ["Dijet_jet_hist_unweighted_0/eta_1"]
    jet_ht_hist_names = ["Dijet_jet_hist_unweighted_{ind}/eta_1"]

    zb_root_files = [
        cu.open_root_file(os.path.join(dl[0], qgc.ZB_FILENAME))
        for dl in dirname_label_pairs
    ]
    jetht_root_files = [
        cu.open_root_file(os.path.join(dl[0], qgc.JETHT_FILENAME))
        for dl in dirname_label_pairs
    ]
    N = len(dirname_label_pairs)
    rebin = 2
    for zb_name, ht_name in zip(zb_hist_names, jet_ht_hist_names):
        # add zero bias ones
        this_data_entries = [
            Contribution(
                cu.get_from_tfile(zb_root_files[i], zb_name),
                label=zb_entry['label'] + ": " + l,
                marker_color=zb_entry['color'],
                line_color=zb_entry['color'],
                line_style=1 + i,
                rebin_hist=rebin,
            ) for i, (d, l) in enumerate(dirname_label_pairs)
        ]
        for c in this_data_entries[1:]:
            c.subplot = this_data_entries[0].obj

        # plot zb
        plot = Plot(
            this_data_entries,
            what='hist',
            title=title,
            xtitle="y^{jet 1}",
            ytitle="N",
            subplot_type='ratio',
            subplot_title='* / %s' % dirname_label_pairs[0][1],
            # subplot_limits=(0, 5),
            **plot_kwargs)
        plot.subplot_maximum_ceil = 5
        plot.default_canvas_size = (800, 600)
        plot.y_padding_max_log = 500
        plot.legend.SetY1(0.7)
        plot.legend.SetY2(0.88)
        plot.legend.SetX1(0.5)
        plot.legend.SetNColumns(2)
        plot.plot("NOSTACK HISTE")
        output_filename = "%s/DataZB-eta_jet1%s%s.pdf" % (
            output_dir, "_unweighted" if 'unweighted' in zb_name else "",
            append)
        plot.save(output_filename)

        # add jet ht ones
        for ent in jet_ht_entries:
            histname = ht_name.format(ind=ent['ind'])
            this_data_entries = [
                Contribution(
                    cu.get_from_tfile(jetht_root_files[i], histname),
                    label=ent['label'] + ": " + l,
                    marker_color=ent['color'],
                    line_color=ent['color'],
                    line_style=1 + i,
                    rebin_hist=rebin,
                ) for i, (d, l) in enumerate(dirname_label_pairs)
            ]
            for c in this_data_entries[1:]:
                c.subplot = this_data_entries[0].obj

            plot = Plot(
                this_data_entries,
                what='hist',
                title=title,
                xtitle="y^{jet 1}",
                ytitle="N",
                # xlim=[30, 1000],
                # ylim=[10, 1E8] if 'unweighted' in ht_name else [1, 1E12],
                subplot_type='ratio',
                subplot_title='* / %s' % dirname_label_pairs[0][1],
                **plot_kwargs)
            plot.default_canvas_size = (800, 600)
            plot.y_padding_max_log = 500
            plot.legend.SetY1(0.7)
            plot.legend.SetY2(0.88)
            plot.legend.SetX1(0.5)
            plot.legend.SetNColumns(2)
            plot.plot("NOSTACK HISTE")
            output_filename = "%s/DataJetHTZB-%s_eta_jet1%s%s.pdf" % (
                output_dir, ent['label'],
                "_unweighted" if 'unweighted' in zb_name else "", append)
            plot.save(output_filename)
def do_jet_pt_with_var_cuts(histname, cuts, input_filename, output_filename):
    ROOT.gStyle.SetPalette(palette_1D)
    total = len(cuts) - 1 + .1 # slight offset to not hit the maximum or minimum
    # if len(cuts) <= 3:
        # ROOT.gStyle.SetPalette(ROOT.kCool)
        # num_colours = ROOT.TColor.GetPalette().fN - 1
        # print('num_colours:', num_colours)
        # for index in range(len(cuts)):
        #     print(num_colours, index, len(cuts), index / len(cuts), num_colours * index / total)
        #     print(index, ROOT.TColor.GetColorPalette(int(num_colours * 1. * index / total)))
    tf = cu.open_root_file(input_filename)
    h3d = cu.get_from_tfile(tf, histname)
    if h3d.GetEntries() == 0:
        return
    pt_hists = []
    for cut in cuts:
        max_bin = h3d.GetZaxis().FindFixBin(cut)
        # print("cut:", cut, "bin:", max_bin)
        h = h3d.ProjectionY("pt_var_lt_%g" % cut, 0, -1, 0, max_bin, "e")
        h2 = h.Clone()
        h2.Rebin(2)
        if h.GetEntries() > 0:
            h3 = qgp.hist_divide_bin_width(h2)
        pt_hists.append(h3)

    line_styles = [1, 2, 3]
    if len(cuts) <= 3:
        line_styles = [1]
    n_line_styles = len(line_styles)
    ref_ind = 0
    conts = [Contribution(h, label=" < %g" % cut,
                          line_color=cu.get_colour_seq(ind, total),
                          line_style=line_styles[ind % n_line_styles],
                          line_width=2,
                          marker_color=cu.get_colour_seq(ind, total),
                          subplot=pt_hists[ref_ind] if ind != ref_ind else None)
             for ind, (h, cut) in enumerate(zip(pt_hists, cuts))]

    jet_str = pt_genjet_str if "_vs_pt_genjet_vs_" in histname else pt_str
    weight_str = "(unweighted)" if "unweighted" in histname else "(weighted)"
    ratio_lims = (0.5, 2.5)
    ratio_lims = (0.5, 1.1)
    plot = Plot(conts, what='hist',
                title='%s for cuts on %s %s' % (jet_str, get_var_str(histname), weight_str),
                xtitle=None,
                ytitle='N',
                # xlim=None, ylim=None,
                legend=True,
                subplot_type='ratio',
                subplot_title='* / var < %g' % cuts[ref_ind],
                subplot_limits=ratio_lims,
                has_data=False)
    plot.y_padding_max_log = 200
    plot.subplot_maximum_ceil = 4
    plot.subplot_maximum_floor = 1.02
    plot.subplot_minimum_ceil = 0.98
    plot.legend.SetY1(0.7)
    plot.legend.SetY2(0.89)
    plot.legend.SetX1(0.78)
    plot.legend.SetX2(0.88)
    plot.plot("NOSTACK HISTE", "NOSTACK HIST")
    plot.set_logx(True, do_more_labels=True)
    plot.set_logy(True, do_more_labels=False)
    plot.save(output_filename)
def do_1D_plot(hists,
               output_filename,
               components_styles_dicts=None,
               draw_opts="NOSTACK HISTE",
               do_ratio=True,
               logx=False,
               logy=False,
               normalise_hists=True,
               title=""):

    if (len(hists) != len(components_styles_dicts)):
        raise RuntimeError("# hists != # components_styles_dicts (%d vs %d)" %
                           (len(hists), len(components_styles_dicts)))

    hists = [h.Clone(h.GetName() + str(uuid1())) for h in hists]
    contributions = [
        Contribution(hist, normalise_hist=normalise_hists, **csd)
        for hist, csd in zip(hists, components_styles_dicts)
    ]

    if len(contributions) == 0:
        return

    # Ignore if all empty objs
    total_entries = sum(c.obj.GetEntries() for c in contributions)
    if total_entries == 0:
        print("WARNING: all plots have 0 entries")
        return

    min_val = min([h.GetMinimum(0) for h in hists])
    max_val = max([h.GetMaximum() for h in hists])
    # print("Auto y limits:", min_val, max_val)
    if logy:
        ylim = [0.5 * min_val, 50 * max_val]
    else:
        # ylim = [0.5*min_val, 1.5*max_val]
        ylim = [0, 1.5 * max_val]

    # Auto calc x limits to avoid lots of empty bins
    high_bin = max([find_largest_filled_bin(h)[0] for h in hists])
    low_bin = min([find_first_filled_bin(h)[0] for h in hists])
    xlim = [
        hists[0].GetBinLowEdge(low_bin - 1),
        hists[0].GetBinLowEdge(high_bin + 2)
    ]

    p = Plot(
        contributions,
        what='hist',
        ytitle="p.d.f." if normalise_hists else "N",
        title=title,
        xlim=xlim,
        ylim=ylim,
        subplot_type="ratio" if do_ratio else None,
        subplot_title="Herwig / PY8",
        subplot=contributions[0],
        subplot_limits=(0.5, 1.5),
    )
    # p.legend.SetX1(0.55)
    # # p.legend.SetX2(0.95)
    # p.legend.SetY1(0.7)
    # p.legend.SetY2(0.85)
    p.legend.SetX1(0.5)
    p.legend.SetX2(0.97)
    if len(contributions) > 4:
        p.legend.SetY1(0.6)
    else:
        p.legend.SetY1(0.7)
    p.legend.SetY2(0.9)
    p.plot(draw_opts)

    if logy:
        p.set_logy()
    if logx:
        p.set_logx()

    p.save(output_filename)
def do_1D_plot(hists, output_filename, components_styles_dicts=None,
               draw_opts="NOSTACK HISTE", do_ratio=True, logx=False, logy=False,
               normalise_hists=True, title=""):

    if (len(hists) != len(components_styles_dicts)):
        raise RuntimeError("# hists != # components_styles_dicts (%d vs %d)" % (len(hists), len(components_styles_dicts)))

    hists = [h.Clone(cu.get_unique_str()) for h in hists]
    contributions = [Contribution(hist, 
                                  normalise_hist=normalise_hists, 
                                  label=csd.get('label', 'x'), 
                                  **csd.get('style', {}))
                     for hist, csd in zip(hists, components_styles_dicts)]

    if len(contributions) == 0:
        return

    # Ignore if all empty objs
    total_entries = sum(c.obj.GetEntries() for c in contributions)
    if total_entries == 0:
        print("WARNING: all plots have 0 entries")
        return

    min_val = min([h.GetMinimum(0) for h in hists])
    max_val = max([h.GetMaximum() for h in hists])
    # print("Auto y limits:", min_val, max_val)
    if logy:
        ylim = [0.5*min_val, 50*max_val]
    else:
        # ylim = [0.5*min_val, 1.5*max_val]
        ylim = [0, 1.5*max_val]

    # Auto calc x limits to avoid lots of empty bins
    high_bin = max([find_largest_filled_bin(h)[0] for h in hists])
    low_bin = min([find_first_filled_bin(h)[0] for h in hists])
    xlim = [hists[0].GetBinLowEdge(low_bin-1), hists[0].GetBinLowEdge(high_bin+2)]

    subplot_title = "* / %s" % contributions[0].label
    if len(contributions[0].label) > 10:
        # need padding to centralise it
        padding = ' ' * int(len(contributions[0].label)/2)
        subplot_title = "#splitline{%s* /%s}{%s}" % (padding, padding, contributions[0].label)

    p = Plot(contributions, what='hist',
             ytitle="#DeltaN/N" if normalise_hists else "N",
             title=title,
             xlim=xlim,
             ylim=ylim,
             subplot_type="ratio" if do_ratio else None,
             subplot_title=subplot_title,
             subplot=contributions[0],
             # subplot_limits=(0.5, 1.5),
             # subplot_limits=(0, 2) if logy else (0.5, 1.5),
             subplot_limits=(0, 2.5) if logy else (0.5, 1.5),
             )
    # p.legend.SetX1(0.55)
    # # p.legend.SetX2(0.95)
    # p.legend.SetY1(0.7)
    # p.legend.SetY2(0.85)
    p.legend.SetX1(0.5)
    p.legend.SetX2(0.97)
    if len(contributions) > 4:
        p.legend.SetY1(0.6)
    else:
        p.legend.SetY1(0.7)
    p.legend.SetY2(0.9)
    p.plot(draw_opts)

    if logy:
        p.set_logy(do_more_labels=False)
    if logx:
        p.set_logx(do_more_labels=False)

    # p.save(os.path.join(output_dir, obj_name+".%s" % (OUTPUT_FMT)))
    p.save(output_filename)
示例#17
0
def draw_folded_hists_physical(hist_mc_folded,
                               hist_mc_reco,
                               hist_data_reco,
                               output_filename,
                               title="",
                               xtitle="",
                               logx=False,
                               logy=False):
    entries = []

    if hist_mc_folded:
        entries.append(
            Contribution(hist_mc_folded,
                         label="Folded MC [detector-level]",
                         line_color=ROOT.kGreen + 2,
                         line_width=1,
                         marker_color=ROOT.kGreen + 2,
                         marker_size=0,
                         normalise_hist=False,
                         subplot=hist_data_reco), )

    if hist_mc_reco:
        entries.append(
            Contribution(hist_mc_reco,
                         label="Reco MC [detector-level]",
                         line_color=ROOT.kAzure + 2,
                         line_width=1,
                         line_style=2,
                         marker_color=ROOT.kAzure + 2,
                         marker_size=0,
                         normalise_hist=False,
                         subplot=hist_data_reco), )

    if hist_data_reco:
        entries.append(
            Contribution(hist_data_reco,
                         label="Reco Data [detector-level]",
                         line_color=ROOT.kRed,
                         line_width=0,
                         marker_color=ROOT.kRed,
                         marker_size=0.6,
                         marker_style=20,
                         normalise_hist=False), )

    plot = Plot(entries,
                what='hist',
                title=title,
                xtitle=xtitle,
                ytitle="N",
                subplot_type='ratio',
                subplot_title='MC/Data',
                subplot_limits=(0.25, 1.75))
    plot.default_canvas_size = (800, 600)
    plot.plot("NOSTACK HISTE")
    if logx:
        plot.set_logx(True)
    if logy:
        plot.main_pad.SetLogy(1)
    ymax = max(h.GetMaximum()
               for h in [hist_mc_folded, hist_mc_reco, hist_data_reco] if h)
    plot.container.SetMaximum(ymax * 100)
    plot.container.SetMinimum(1)
    plot.legend.SetY1NDC(0.77)
    plot.legend.SetX2NDC(0.85)
    plot.save(output_filename)
示例#18
0
def do_flavour_fraction_vs_pt(input_file,
                              hist_name,
                              pt_bins,
                              output_filename,
                              title=""):
    """Plot all flavour fractions vs PT for one input file & hist_name in the ROOT file"""
    info = get_flavour_efficiencies(input_file,
                                    bins=pt_bins,
                                    hist_name=hist_name)

    leg_draw_opt = "LP"
    plot_u = Contribution(info['u'].CreateGraph(),
                          label="Up",
                          line_color=ROOT.kRed,
                          marker_color=ROOT.kRed,
                          marker_style=20,
                          leg_draw_opt=leg_draw_opt)
    plot_d = Contribution(info['d'].CreateGraph(),
                          label="Down",
                          line_color=ROOT.kBlue,
                          marker_color=ROOT.kBlue,
                          marker_style=21,
                          leg_draw_opt=leg_draw_opt)
    plot_s = Contribution(info['s'].CreateGraph(),
                          label="Strange",
                          line_color=ROOT.kBlack,
                          marker_color=ROOT.kBlack,
                          marker_style=22,
                          leg_draw_opt=leg_draw_opt)
    plot_c = Contribution(info['c'].CreateGraph(),
                          label="Charm",
                          line_color=ROOT.kGreen + 2,
                          marker_color=ROOT.kGreen + 2,
                          marker_style=23,
                          leg_draw_opt=leg_draw_opt)
    plot_b = Contribution(info['b'].CreateGraph(),
                          label="Bottom",
                          line_color=ROOT.kOrange - 3,
                          marker_color=ROOT.kOrange - 3,
                          marker_style=33,
                          leg_draw_opt=leg_draw_opt)
    plot_g = Contribution(info['g'].CreateGraph(),
                          label="Gluon",
                          line_color=ROOT.kViolet,
                          marker_color=ROOT.kViolet,
                          marker_style=29,
                          leg_draw_opt=leg_draw_opt)
    plot_unknown = Contribution(info['unknown'].CreateGraph(),
                                label="Unknown",
                                line_color=ROOT.kGray + 1,
                                marker_color=ROOT.kGray + 1,
                                marker_style=26,
                                leg_draw_opt=leg_draw_opt)

    p_flav = Plot(
        [plot_d, plot_u, plot_s, plot_c, plot_b, plot_g, plot_unknown],
        what='graph',
        xtitle="p_{T}^{%s} [GeV]" % get_jet_str(''),
        ytitle="Fraction",
        title=title,
        xlim=(pt_bins[0][0], pt_bins[-1][1]),
        ylim=[0, 1],
        has_data=False)
    p_flav.default_canvas_size = (600, 600)
    p_flav.plot("AP")
    p_flav.main_pad.SetBottomMargin(0.16)
    p_flav.get_modifier().GetXaxis().SetTitleOffset(1.4)
    p_flav.get_modifier().GetXaxis().SetTitleSize(.045)
    p_flav.set_logx(do_more_labels=True, do_exponent=False)
    p_flav.legend.SetX1(0.55)
    p_flav.legend.SetY1(0.72)
    p_flav.legend.SetY2(0.85)
    p_flav.legend.SetNColumns(2)
    p_flav.save(output_filename)
示例#19
0
def compare_flavour_fraction_hists_vs_pt(input_files,
                                         hist_names,
                                         pt_bins,
                                         labels,
                                         flav,
                                         output_filename,
                                         title="",
                                         xtitle="p_{T}^{jet} [GeV]",
                                         is_preliminary=True):
    """Plot a specified flavour fraction vs pT for several sources.
    Each entry in input_files, dirnames, and labels corresponds to one line
    n_partons can be a str, 'all', '1', etc, or a list of str to include

    TODO: use this one more often - compare_flavour_fractions_vs_pt() is almost identical but has to deal with npartons
    """
    bin_centers = [0.5 * (x[0] + x[1]) for x in pt_bins]
    bin_widths = [0.5 * (x[1] - x[0]) for x in pt_bins]

    contribs = []
    info = [
        get_flavour_efficiencies(ifile, bins=pt_bins, hist_name=hname)
        for ifile, hname in zip(input_files, hist_names)
    ]
    N = len(bin_centers)

    colours = [ROOT.kBlack, ROOT.kBlue, ROOT.kRed, ROOT.kGreen + 2]

    for i, fdict in enumerate(info):
        if flav in ['u', 'd', 's', 'c', 'b', 't', 'g']:
            obj = fdict[flav].CreateGraph()
        else:
            raise RuntimeError("Robin broke 1-X functionality")
            obj = ROOT.TGraphErrors(
                N, np.array(bin_centers),
                1. - np.array(fdict[flav.replace("1-", '')]),
                np.array(bin_widths), np.zeros(N))
        if obj.GetN() == 0:
            continue
        c = Contribution(obj,
                         label=labels[i],
                         line_color=colours[i],
                         line_width=1,
                         line_style=1,
                         marker_style=20 + i,
                         marker_color=colours[i],
                         marker_size=1,
                         leg_draw_opt="LP")
        contribs.append(c)

    flav_str = FLAV_STR_DICT[flav]
    ytitle = "Fraction of %s %ss" % (flav_str.lower(), get_jet_str(''))
    p = Plot(contribs,
             what='graph',
             xtitle=xtitle,
             ytitle=ytitle,
             title=title,
             xlim=(50, 2000),
             ylim=(0, 1),
             has_data=False,
             is_preliminary=is_preliminary)
    p.default_canvas_size = (600, 600)
    try:
        p.plot("AP")
        p.main_pad.SetBottomMargin(0.16)
        p.get_modifier().GetXaxis().SetTitleOffset(1.4)
        p.get_modifier().GetXaxis().SetTitleSize(.045)
        p.legend.SetX1(0.56)
        p.legend.SetY1(0.65)
        p.legend.SetY2(0.87)
        p.set_logx(do_more_labels=True, do_exponent=False)
        p.save(output_filename)
    except ZeroContributions:
        pass
def make_resolution_plots(h2d,
                          xlabel,
                          output_filename,
                          do_fit=True,
                          do_rms=True,
                          quantiles=None,
                          log_var=False,
                          save_response_hists=False):
    """Make graph of resolution vs variables.

    Also optionally save all input histograms to file.
    """
    one_sigma = 0.682689
    quantiles = quantiles or [0.5 * (1 - one_sigma), 1 - 0.5 * (1 - one_sigma)]
    ax = h2d.GetXaxis()
    bin_edges = [ax.GetBinLowEdge(i) for i in range(1, ax.GetNbins() + 1)]

    bin_centers, sigmas, sigmas_unc = [], [], []
    rel_sigmas, rel_sigmas_unc = [], []
    # bin_centers = [ax.GetBinCenter(i) for i in range(1, ax.GetNbins()+1)]

    for var_min, var_max in zip(bin_edges[:-1], bin_edges[1:]):
        h_projection = qgg.get_projection_plot(h2d,
                                               var_min,
                                               var_max,
                                               cut_axis='x')
        if h_projection.GetEffectiveEntries() < 20:
            continue
        # h_projection.Rebin(rebin)
        h_projection.Scale(1. / h_projection.Integral())

        bin_centers.append(0.5 * (var_max + var_min))
        if do_fit:
            do_gaus_fit(h_projection)
            fit = h_projection.GetFunction("gausFit")
            # label += "\n"
            # label += fit_results_to_str(fit)
            # bin_centers.append(fit.GetParameter(1))
            sigmas.append(fit.GetParameter(2))
            rel_sigmas.append(fit.GetParameter(2) / bin_centers[-1])
            sigmas_unc.append(fit.GetParError(2))
            rel_sigmas_unc.append(fit.GetParError(2) / bin_centers[-1])
        else:
            if do_rms:
                sigmas.append(sqrt(h_projection.GetRMS()))
                rel_sigmas.append(
                    sqrt(h_projection.GetRMS()) / bin_centers[-1])
                sigmas_unc.append(sqrt(h_projection.GetRMSError()))
                rel_sigmas_unc.append(
                    sqrt(h_projection.GetRMSError()) / bin_centers[-1])
            elif quantiles:
                if len(quantiles) != 2:
                    raise RuntimeError("Need 2 quantiles")
                q = array('d', quantiles)
                results = array('d', [0.] * len(quantiles))
                h_projection.GetQuantiles(len(quantiles), results, q)
                sigmas.append(results[1] - results[0])
                sigmas_unc.append(0)
                rel_sigmas.append((results[1] - results[0]) / bin_centers[-1])
                rel_sigmas_unc.append(0)
            else:
                raise RuntimeError(
                    "Need either do_fit, do_rms, or 2-tuple in quantiles")

        if save_response_hists:
            xlabel = h_projection.GetXaxis().GetTitle()
            cont = Contribution(h_projection,
                                label="GEN: %g-%g" % (var_min, var_max))
            p = Plot([cont], what='hist')
            p.plot('HISTE')
            rsp_filename = os.path.abspath(
                output_filename.replace(
                    ".%s" % OUTPUT_FMT,
                    "_hist%gto%g.%s" % (var_min, var_max, OUTPUT_FMT)))
            rsp_dir = os.path.dirname(rsp_filename)
            rsp_file = os.path.basename(rsp_filename)
            p.save(os.path.join(rsp_dir, "responseHists", rsp_file))

    gr = ROOT.TGraphErrors(len(bin_centers), array('d', bin_centers),
                           array('d', sigmas),
                           array('d', [0] * len(bin_centers)),
                           array('d', sigmas_unc))
    gr_cont = Contribution(gr, label="")
    ylabel = ""
    if do_fit:
        ylabel = "Fit #sigma"
    elif do_rms:
        ylabel = "#sqrt{RMS}"
    elif quantiles:
        ylabel = "Central %g" % one_sigma
    plot = Plot([gr_cont],
                what='graph',
                xtitle=xlabel,
                ytitle=ylabel,
                xlim=[bin_edges[0], bin_edges[-1]],
                ylim=[0, max(sigmas) * 1.2],
                legend=False)
    plot.plot()
    if log_var:
        plot.set_logx()
    plot.save(output_filename)

    gr_rel = ROOT.TGraphErrors(len(bin_centers), array('d', bin_centers),
                               array('d', rel_sigmas),
                               array('d', [0] * len(bin_centers)),
                               array('d', rel_sigmas_unc))
    gr_rel_cont = Contribution(gr_rel, label="")
    ylabel = "Relative %s" % ylabel
    plot = Plot([gr_rel_cont],
                what='graph',
                xtitle=xlabel,
                ytitle=ylabel,
                xlim=[bin_edges[0], bin_edges[-1]],
                ylim=[min(rel_sigmas) / 1.2,
                      max(rel_sigmas) * 1.2],
                legend=False)
    plot.plot()
    plot.set_logy()
    if log_var:
        plot.set_logx()
    plot.save(
        output_filename.replace(".%s" % OUTPUT_FMT,
                                "_relative.%s" % OUTPUT_FMT))

    return gr, gr_rel
示例#21
0
def do_projection_plots(in_file, plot_dir, do_fit=True, skip_dirs=None):
    hist_name = "pt_jet_response"
    tfile = cu.open_root_file(in_file)
    dirs = cu.get_list_of_element_names(tfile)

    for mydir in dirs:
        if skip_dirs and mydir in skip_dirs:
            continue

        if hist_name not in cu.get_list_of_element_names(tfile.Get(mydir)):
            continue

        print("Doing", mydir)

        h2d = cu.grab_obj_from_file(in_file, "%s/%s" % (mydir, hist_name))

        ax = h2d.GetXaxis()
        bin_edges = [ax.GetBinLowEdge(i) for i in range(1, ax.GetNbins() + 2)]

        bin_centers, sigmas, sigmas_unc = [], [], []

        for pt_min, pt_max in zip(bin_edges[:-1], bin_edges[1:]):
            obj = qgg.get_projection_plot(h2d, pt_min, pt_max, cut_axis='x')
            if obj.GetEffectiveEntries() < 20:
                continue
            # obj.Rebin(rebin)
            obj.Scale(1. / obj.Integral())

            label = "%s < p_{T}^{Gen} < %s GeV" % (str(pt_min), str(pt_max))
            if do_fit:
                do_gaus_fit(obj)
                fit = obj.GetFunction("gausFit")
                label += "\n"
                label += fit_results_to_str(fit)
                # bin_centers.append(fit.GetParameter(1))
                bin_centers.append(0.5 * (pt_max + pt_min))
                sigmas.append(fit.GetParameter(2))
                sigmas_unc.append(fit.GetParError(2))

            # output_filename = os.path.join(plot_dir, "%s_%s_ptGen%sto%s.%s" % (mydir, hist_name, str(pt_min), str(pt_max), OUTPUT_FMT))

            # cont = Contribution(obj, label=label)
            # delta = pt_max - pt_min
            # # xlim = (pt_min - 10*delta, pt_max + 10*delta)
            # xlim = (obj.GetMean()-3*obj.GetRMS(), obj.GetMean()+3*obj.GetRMS())
            # ylim = (0, obj.GetMaximum()*1.1)
            # plot = Plot([cont], what='hist',
            #             xtitle="p_{T}^{Reco} [GeV]", xlim=xlim, ylim=ylim)
            # plot.plot()  # don't use histe as it wont draw the fit
            # plot.save(output_filename)

        gr = ROOT.TGraphErrors(len(bin_centers), array('d', bin_centers),
                               array('d', sigmas),
                               array('d', [0] * len(bin_centers)),
                               array('d', sigmas_unc))
        factor = 0.2
        gr_ideal = ROOT.TGraphErrors(
            len(bin_centers), array('d', bin_centers),
            array('d', [factor * pt for pt in bin_centers]),
            array('d', [0] * len(bin_centers)),
            array('d', [0] * len(bin_centers)))
        gr_cont = Contribution(gr, label='Measured')
        gr_ideal_cont = Contribution(gr_ideal,
                                     label=str(factor) + '*p_{T}',
                                     line_color=ROOT.kBlue,
                                     marker_color=ROOT.kBlue)
        plot = Plot([gr_cont, gr_ideal_cont],
                    what='graph',
                    xtitle="p_{T}^{Reco}",
                    ytitle="#sigma [GeV]",
                    ylim=[0, 100],
                    xlim=[10, 4000])
        plot.plot()
        plot.set_logx()
        output_filename = os.path.join(
            plot_dir, "%s_%s_sigma_plot.%s" % (mydir, hist_name, OUTPUT_FMT))
        plot.save(output_filename)
def do_comparison_graph(entries, output_filename, bin_title="", xtitle="", ytitle="",
                        other_elements=None, logx=False, logy=False,
                        do_line=True, xlimits=None, ylimits=None,
                        y_limit_protection=None, draw_fits=True, 
                        do_ratio=True, ratio_limits=None):
    """Draw several graphs on one canvas and save to file
    
    Parameters
    ----------
    entries : [dict]
        List of entries to plot. Each is represented by a dict, with the graph,
        label, and various other style options to be applied.
    output_filename : str
        Name of output plot file
    bin_title : str
        Bin title e.g. x < pT < y
    xtitle : str
        X axis label
    ytitle : str
        y axis label
    other_elements : [TObject], optional
        Other elements to Draw on the canvas
    logx : bool, optional
        Log x axis
    logy : bool, optional
        Log y axis
    do_line : bool, optional
        Do horizontal line at 1
    xlimits : (min, max), optional
        Set hard x limits
    ylimits : (min, max), optional
        Set hard y limits
    y_limit_protection : (y_min, y_max), optional
        Set minimum and maximum y values in the event of a huge stat error or weird point
    draw_fits : bool, optional
        Draw fitted functions or not
    do_ratio : bool, optional
        Add ratio subplot
    
    """

    plot = Plot(entries, what='graph', 
                title=None, xtitle=xtitle, ytitle=ytitle,
                xlim=xlimits, ylim=ylimits,
                legend=True,
                subplot=entries[0] if do_ratio else None, subplot_type="ratio",
                subplot_title="Ratio to All")

    # replace legend with our own for now
    delta = 0.12
    middle = 0.77
    plot.legend = ROOT.TLegend(middle-delta, 0.75, middle+delta, 0.88)
    plot.legend.SetBorderSize(0)
    plot.legend.SetFillStyle(0)
    plot.legend.SetNColumns(2)
    plot.legend.SetTextAlign(ROOT.kHAlignCenter + ROOT.kVAlignCenter)

    plot.plot()
    if logx:
        plot.set_logx()
    if logy:
        plot.set_logy()

    plot.main_pad.cd()
    if not ylimits:
        plot.container.GetHistogram().SetMaximum(plot.container.GetYaxis().GetXmax() * 1.05)

    # Protection in case y limits are dominated by large stat error
    if y_limit_protection and len(y_limit_protection) == 2:
        y_min, y_max = plot.container.GetYaxis().GetXmin(), plot.container.GetYaxis().GetXmax()
        y_lim_lower, y_lim_upper = y_limit_protection
        if y_max > y_lim_upper:
            plot.container.GetHistogram().SetMaximum(y_lim_upper)
        if y_min < y_lim_lower:
            plot.container.GetHistogram().SetMinimum(y_lim_lower)

    # add protection for subplot
    if not ratio_limits:
        low_lim = 0.8
        upper_lim = 1.2
        y_min, y_max = plot.subplot_container.GetYaxis().GetXmin(), plot.subplot_container.GetYaxis().GetXmax()
        plot.subplot_container.GetYaxis().SetRangeUser(max(low_lim, y_min), min(y_max, upper_lim))  # set limits doesn't work for y axis
    elif len(ratio_limits) == 2:
        plot.subplot_container.GetYaxis().SetRangeUser(*ratio_limits)  # set limits doesn't work for y axis

    plot.subplot_pad.Update()
    plot.canvas.Update()

    # if do_line:
    #     y_min, y_max = plot.container.GetYaxis().GetXmin(), plot.container.GetYaxis().GetXmax()
    #     if y_min < 1 and y_max > 1:
    #         x_min, x_max = plot.container.GetXaxis().GetXmin(), plot.container.GetXaxis().GetXmax()
    #         line = ROOT.TLine(x_min, 1, x_max, 1)
    #         line.SetLineStyle(2)
    #         line.SetLineColor(ROOT.kGray+2)
    #         line.Draw()

    plot.canvas.cd()

    cms_text = ROOT.TPaveText(0.17, 0.84, 0.2, 0.85, "NDC")
    cms_text.AddText("CMS Simulation")
    cms_text.SetTextFont(62)
    cms_text.SetTextAlign(ROOT.kHAlignLeft + ROOT.kVAlignBottom)
    cms_text.SetTextSize(FONT_SIZE)
    cms_text.SetBorderSize(0)
    cms_text.SetFillStyle(0)
    cms_text.Draw()

    bin_text = ROOT.TPaveText(0.17, 0.8, 0.2, 0.81, "NDC")
    bin_text.AddText(bin_title)
    bin_text.SetTextFont(42)
    bin_text.SetTextSize(FONT_SIZE)
    bin_text.SetTextAlign(ROOT.kHAlignLeft + ROOT.kVAlignBottom)
    bin_text.SetBorderSize(0)
    bin_text.SetFillStyle(0)
    bin_text.Draw()

    if other_elements:
        for ele in other_elements:
            ele.Draw()

    plot.save(output_filename)