def plot_cutflow_hist(hist, output_filename, title='', has_data=False):
    """Plot one cutflow histogram. Normalises so bins are fractions of the first"""
    frac_hist = hist.Clone()
    first_bin = hist.GetBinContent(1)
    for i in range(1, frac_hist.GetNbinsX()+1):
        frac_hist.SetBinContent(i, hist.GetBinContent(i) / first_bin)
        frac_hist.SetBinError(i, hist.GetBinError(i) / first_bin)

    col = ROOT.kBlue
    entry = [Contribution(frac_hist, label='',
                          line_color=col, line_width=2, line_style=1,
                          marker_color=col, marker_size=0.75, marker_style=cu.Marker.get('circle'),
                          normalise_hist=False)]

    hmax = frac_hist.GetMaximum()
    hmin = frac_hist.GetMinimum(0)
    hdiff = hmax-hmin
    ymin = max(0, hmin - (hdiff*0.1))
    ymax = hmax + (hdiff*0.25)

    plot = Plot(entry, 'hist',
                xtitle='',
                ytitle='Fraction',
                title=title,
                ylim=(ymin, ymax),
                legend=False,
                has_data=has_data)
    plot.default_canvas_size = (800, 600)
    plot.plot("NOSTACK HISTE")
    plot.save(output_filename)
Ejemplo n.º 2
0
def draw_folded_hists(hist_mc_folded,
                      hist_mc_reco,
                      hist_data_reco,
                      output_filename,
                      title=""):
    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="Bin number",
                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")
    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)
def do_pf_fraction_plot(hist_map, pt_bins, output_filename):
    """Plot PF particle type fractioin for matches, binned by GenParticle pT"""
    entries = []
    for pt_low, pt_high, mark in zip(pt_bins[:-1], pt_bins[1:],
                                     cu.Marker().cycle()):
        values = {}
        for pf_ind, (pf_name, hist) in hist_map.items():
            ax = hist.GetXaxis()
            binx1 = ax.FindBin(pt_low)
            binx2 = ax.FindBin(pt_high) - 1
            if pt_high == ax.GetBinUpEdge(ax.GetLast()):
                binx2 = ax.GetLast()
            biny1 = 1
            biny2 = hist.GetNbinsY()
            binz1 = 1
            binz2 = hist.GetNbinsZ()
            values[pf_ind] = hist.Integral(
                binx1, binx2, biny1, biny2, binz1,
                binz2)  # integral includes the last bin

        sum_values = sum(values.values())
        fracs = {k: (v / sum_values) for k, v in values.items()}

        h = ROOT.TH1D("h_pt_bin_%gto%g" % (pt_low, pt_high), "", len(values),
                      0, len(values))
        ax = h.GetXaxis()
        for ind, k in enumerate(sorted(fracs.keys()), 1):
            h.SetBinContent(ind, fracs[k])
            h.SetBinError(ind, sqrt(values[k]) / sum_values)
            ax.SetBinLabel(ind, hist_map[k][0])

        c = Contribution(h,
                         label='%g < GenParticle p_{T} < %g GeV' %
                         (pt_low, pt_high),
                         line_width=1,
                         marker_size=0.75,
                         marker_style=mark,
                         normalise_hist=False)
        entries.append(c)

    ROOT.gStyle.SetPalette(55)
    plot = Plot(entries,
                'hist',
                xtitle='PF particle type',
                ytitle='Fraction matched as type',
                ylim=(1E-3, 2),
                has_data=False)
    plot.default_canvas_size = (800, 600)
    plot.plot("NOSTACK PMC PLC HISTE")
    plot.set_logy(do_more_labels=False)
    plot.save(output_filename)
    ROOT.gStyle.SetPalette(ROOT.kViridis)
Ejemplo n.º 4
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)
Ejemplo n.º 5
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)
Ejemplo n.º 6
0
def do_flavour_fraction_vs_eta(input_file,
                               dirname,
                               eta_bins,
                               output_filename,
                               title="",
                               var_prepend="",
                               which_jet="both",
                               append=""):
    """Plot all flavour fractions vs eta for one input file & dirname in the ROOT file"""
    info = get_flavour_efficiencies(
        input_file,
        bins=eta_bins,
        hist_name=get_flavour_hist_name(
            dirname=dirname,
            var_prepend=var_prepend,
            which_jet="both",  # since no jet/jet1/jet2 in hist name
            metric='eta' + append))

    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="y^{%s}" % get_jet_str(''),
        ytitle="Fraction",
        title=title,
        xlim=(eta_bins[0][0], eta_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.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)
Ejemplo n.º 7
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)
Ejemplo n.º 8
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
Ejemplo n.º 9
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
Ejemplo n.º 10
0
def make_plot(entries,
              output_filename,
              plot_kwargs,
              projection_axis='x',
              start_val=None,
              end_val=None,
              is_pdgid_plot=False,
              logy=False):
    """Make a plot from entries. Each one is a projection of a 2D plot.
    
    Parameters
    ----------
    entries : list[dict]
        List of plot entries. Each is represented by a dict
    output_filename : str
        Filename for output plot
    plot_kwargs : dict
        kwargs for Plot constructor
    projection_axis : str, optional
        Axis to use for projection. If None, must be specified in entry.
    start_val : None, optional
        If set, use this to make 1D projection plot. Cuts on X axis. 
        Otherwise should be set per entry.
    end_val : None, optional
        If set, use this to make 1D projection plot. Cuts on X axis. 
        Otherwise should be set per entry.
    is_pdgid_plot : bool, optional
        True if for PDGIDs (sets special size & binning)
    logy : bool, optional
        Description
    
    Raises
    ------
    RuntimeError
        Description
    """
    conts = []
    if not is_pdgid_plot:
        for ent in entries:
            h2d = cu.get_from_tfile(
                ent['file'],
                "ak4pfchsl1/" + ent['histname'] + "_JetEta0to0.783")
            start_val = ent.get('start_val', start_val)
            end_val = ent.get('end_val', end_val)
            if start_val is None or end_val is None:
                raise RuntimeError("Expected start_val and end_val")
            hist = cu.get_projection_plot(
                h2d, start_val, end_val,
                ent.get('projection_axis', projection_axis))
            if hist.GetEntries() == 0:
                ent['used'] = False
                continue
            contrib = Contribution(hist,
                                   label=ent['label'],
                                   line_width=lw,
                                   line_color=ent['colour'],
                                   line_style=ent.get('line_style', 1),
                                   marker_size=ent.get('marker_size', 0),
                                   marker_color=ent['colour'],
                                   marker_style=ent.get('marker_style', 1),
                                   normalise_hist=True,
                                   rebin_hist=ent.get('rebin', None))
            conts.append(contrib)
            ent['used'] = True

    else:
        # For PDGID plots, we want a different canvas aspect ratio, and only to include bins
        # with non-0 contents. We also relabel bins.
        custom_bins = []
        for ent in entries:
            h2d = cu.get_from_tfile(
                ent['file'],
                "ak4pfchsl1/" + ent['histname'] + "_JetEta0to0.783")
            start_val = ent.get('start_val', start_val)
            end_val = ent.get('end_val', end_val)
            if not start_val or not end_val:
                raise RuntimeError("Expected start_val and end_val")
            hist = cu.get_projection_plot(
                h2d, start_val, end_val,
                ent.get('projection_axis', projection_axis))
            ax = hist.GetXaxis()
            bins = dict()
            for i in range(1, hist.GetNbinsX() + 1):
                value = ax.GetBinLowEdge(i)
                cont = hist.GetBinContent(i)
                err = hist.GetBinError(i)
                if cont > 0:
                    bins[value] = [cont, err]
                    # print(custom_bins[-1])

            custom_bins.append(bins)

        nbins = max([len(d) for d in custom_bins])
        first_keys = set(custom_bins[0].keys())
        for cb in custom_bins[1:]:
            first_keys = first_keys.union(set(cb.keys()))
        all_keys = sorted(list(first_keys))
        print(all_keys)

        for cbin, ent in zip(custom_bins, entries):
            h = ROOT.TH1D(cu.get_unique_str(), ";PDGID;N", nbins, 0, nbins)
            for ind, k in enumerate(all_keys, 1):
                content, error = cbin.get(k, [0, 0])
                h.SetBinContent(ind, content)
                h.SetBinError(ind, error)
            ax = h.GetXaxis()
            for i in range(1, nbins + 1):
                # ax.SetBinLabel(i, str(int(all_keys[i-1])))
                pdgid = int(all_keys[i - 1])
                ax.SetBinLabel(i, PDGID_STR.get(pdgid, str(pdgid)))
            h.LabelsOption("v")
            contrib = Contribution(h,
                                   label=ent['label'],
                                   line_width=lw,
                                   line_color=ent['colour'],
                                   line_style=ent.get('line_style', 1),
                                   marker_size=ent.get('marker_size', 0),
                                   marker_color=ent['colour'],
                                   marker_style=ent.get('marker_style', 1),
                                   normalise_hist=True,
                                   rebin_hist=ent.get('rebin', None))
            conts.append(contrib)
            ent['used'] = True

    entries = [e for e in entries if e['used']]
    for ind, ent in enumerate(entries):
        if not ent['used']:
            continue
        if ent.get('subplot_ind', -1) >= 0:
            conts[ind].subplot = conts[ent['subplot_ind']].obj

    plot = Plot(conts,
                what="hist",
                ytitle="p.d.f.",
                has_data=False,
                **plot_kwargs)
    if is_pdgid_plot and conts[0].obj.GetNbinsX() > 10:
        plot.default_canvas_size = (800, 800)
    else:
        plot.default_canvas_size = (450, 600)
    plot.legend.SetX1(0.5)
    plot.legend.SetX2(0.97)
    if len(entries) > 4:
        plot.legend.SetY1(0.7)
        plot.legend.SetNColumns(2)
    else:
        plot.legend.SetY1(0.75)
    plot.legend.SetY2(0.9)
    plot.plot("HISTE NOSTACK")
    if logy:
        plot.set_logy()
    plot.save(output_filename)
Ejemplo n.º 11
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)
Ejemplo n.º 12
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)
Ejemplo n.º 13
0
def draw_projection_comparison(h_orig,
                               h_projection,
                               title,
                               xtitle,
                               output_filename,
                               print_bin_comparison=True):
    """Draw 2 hists, h_orig the original, and h_projection the projection of a 2D hist"""

    # Check integrals
    int_orig = h_orig.Integral()
    int_proj = h_projection.Integral()
    if abs(int_orig - int_proj) / int_orig > 0.01:
        print("draw_projection_comparison: different integrals: %f vs %f" %
              (int_orig, int_proj))

    # Check bin-by-bin
    if print_bin_comparison:
        for i in range(1, h_orig.GetNbinsX() + 1):
            value_orig = h_orig.GetBinContent(i)
            value_proj = h_projection.GetBinContent(i)
            if value_orig == 0 and value_proj == 0:
                continue
            rel_diff = abs((value_orig - value_proj) /
                           max(abs(value_orig), abs(value_proj)))
            if rel_diff > 1E-3:
                print(
                    "draw_projection_comparison: bin %s has different contents: %f vs %f (rel diff %f)"
                    % (i, value_orig, value_proj, rel_diff))

    entries = [
        Contribution(h_orig,
                     label="1D hist",
                     line_color=ROOT.kBlue,
                     line_width=1,
                     marker_color=ROOT.kBlue,
                     marker_size=0,
                     normalise_hist=False),
        Contribution(h_projection,
                     label="Response map projection",
                     line_color=ROOT.kRed,
                     line_width=1,
                     marker_color=ROOT.kRed,
                     marker_size=0,
                     normalise_hist=False,
                     subplot=h_orig),
    ]
    plot = Plot(entries,
                what='hist',
                title=title,
                xtitle=xtitle,
                ytitle="N",
                subplot_type='ratio',
                subplot_title='Projection / 1D',
                subplot_limits=(0.999, 1.001))
    plot.default_canvas_size = (800, 600)
    plot.plot("NOSTACK HIST")
    plot.main_pad.SetLogy(1)
    ymax = max(h.GetMaximum() for h in [h_orig, h_projection])
    plot.container.SetMaximum(ymax * 10)
    # plot.container.SetMinimum(1E-8)
    plot.legend.SetY1NDC(0.77)
    plot.legend.SetX2NDC(0.85)
    plot.save(output_filename)