Пример #1
0
def compare():
    """Make all da plots"""

    # New 
    s2_new = '/users/jt15104/local_L1JEC_store/30June2016_QCDFlatFall15PU0to50NzshcalRaw_ak4_ref10to5000_809v70_noJEC_893ca_etaBinsSel16/runCalib_jetMetFitErr/'
    f_PU0to10_new = os.path.join(s2_new, 'totalPairs_L1Ntuple_etaBinsSel16_PU0to10_maxPt1022.root')
    f_PU15to25_new = os.path.join(s2_new, 'totalPairs_L1Ntuple_etaBinsSel16_PU15to25_maxPt1022.root')
    f_PU30to40_new = os.path.join(s2_new, 'totalPairs_L1Ntuple_etaBinsSel16_PU30to40_maxPt1022.root')
    f_PU45to55_new = os.path.join(s2_new, 'totalPairs_L1Ntuple_etaBinsSel16_PU45to55_maxPt1022.root')

    pu_labels = ['PU0to10', 'PU15to25', 'PU30to40']

    # common object name
    corr_eta_graph_name = "l1corr_eta_{eta_min:g}_{eta_max:g}"

    # --------------------------------------------------------------------
    # New Stage 2 curves
    # Plot different PU scenarios for given eta bin
    # --------------------------------------------------------------------
    graphs = [
        Contribution(file_name=f_PU0to10_new, obj_name=corr_eta_graph_name,
                     label="PU: 0 - 10", line_color=colors[1], marker_color=colors[1]),
        Contribution(file_name=f_PU15to25_new, obj_name=corr_eta_graph_name,
                     label="PU: 15 - 25", line_color=colors[2], marker_color=colors[2]),
        Contribution(file_name=f_PU30to40_new, obj_name=corr_eta_graph_name,
                     label="PU: 30 - 40", line_color=colors[3], marker_color=colors[3]),
        Contribution(file_name=f_PU45to55_new, obj_name=corr_eta_graph_name,
                     label="PU: 45 - 55", line_color=colors[4], marker_color=colors[4])
    ]
    title = "Fall15 MC, Stage2, {eta_min:g} < |#eta^{{L1}}| < {eta_max:g}"
    compare_PU_by_eta_bins(graphs, title, os.path.join(s2_new, 'comparePU'), lowpt_zoom=True)
Пример #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)
Пример #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)
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)
Пример #5
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)
Пример #6
0
def make_comparison_plot_ingredients(entries,
                                     rebin=1,
                                     normalise_hist=True,
                                     mean_rel_error=1.0,
                                     **plot_kwargs):
    """Make the Plot object for a comparison plot.

    User can then add other elements to the plot.

    Parameters
    ----------
    entries : list[(object, dict)]
        List of ROOT object & it's configuration dict, where the dict is a set of kwargs passed to the Contribution object
    rebin : int, optional
        Rebin factor
    normalise_hist : bool, optional
        Normalise each histogram's integral to unity
    mean_rel_error : float, optional
        Remove contributions that have a mean realtive error more than this value
        mean realtive error = mean of all the error/bin contents
    **plot_kwargs
        Any other kwargs to be passed to the Plot object contructor

    Returns
    -------
    Plot
        Plot object to be modified, plotted, etc

    Raises
    ------
    RuntimeError
        If there are 0 contributions
    """
    conts = [
        Contribution(ent[0],
                     normalise_hist=normalise_hist,
                     rebin_hist=rebin,
                     **ent[1]) for ent in entries
    ]
    # if get_hist_mean_rel_error(ent[0]) < mean_rel_error and ent[0].Integral() > 0]
    do_legend = len(conts) > 1
    if len(conts) == 0:
        raise RuntimeError("0 contributions for this plot")
    do_subplot = any(c.subplot for c in conts)
    if (len(conts) == 1 or not do_subplot) and "subplot_type" in plot_kwargs:
        plot_kwargs['subplot_type'] = None
    p = Plot(conts,
             what="hist",
             ytitle="p.d.f",
             legend=do_legend,
             **plot_kwargs)
    if do_legend:
        p.legend.SetX1(0.5)
        p.legend.SetX2(0.95)
        if len(entries) > 4:
            p.legend.SetY1(0.67)
        else:
            p.legend.SetY1(0.78)
        p.legend.SetY2(0.95)
    return p
    def plot_unfolded_normalised_pt_bin_offset(self, bin_offset_2=0):

        for ibin, (bin_edge_low, bin_edge_high) in enumerate(zip(self.bins[:-1], self.bins[1:])):
            # print(bin_edge_low, bin_edge_high)
            ind2 = ibin+bin_offset_2
            if ind2 < 0:
                # print("...skipping")
                continue

            hbc1_args = dict(ind=ibin, binning_scheme='generator')
            unfolded1_hist_bin_stat_errors = self.hist_bin_chopper1.get_pt_bin_normed_div_bin_width('unfolded_stat_err', **hbc1_args)

            hbc2_args = dict(ind=ind2, binning_scheme='generator')
            unfolded2_hist_bin_stat_errors = self.hist_bin_chopper2.get_pt_bin_normed_div_bin_width('unfolded_stat_err', **hbc2_args)

            entries = [
                Contribution(unfolded1_hist_bin_stat_errors,
                             label="Data (stat. unc.)\n%s" % self.setup1.label,
                             line_color=self.plot_styles['unfolded_stat_colour'],
                             line_width=self.line_width,
                             line_style=1,
                             marker_color=self.plot_styles['unfolded_stat_colour'],
                             marker_style=cu.Marker.get('circle'),
                             marker_size=0.75),
                Contribution(unfolded2_hist_bin_stat_errors,
                             label="Data (stat. unc.)\n%s" % self.setup2.label,
                             line_color=self.plot_styles['unfolded_unreg_colour'],
                             line_width=self.line_width,
                             line_style=1,
                             marker_color=self.plot_styles['unfolded_unreg_colour'],
                             marker_style=cu.Marker.get('square', filled=False),
                             marker_size=0.75,
                             subplot=unfolded1_hist_bin_stat_errors),
            ]
            if not self.check_entries(entries, "plot_unfolded_normalised_pt_bin_offset %d" % (ibin)):
                return

            plot = Plot(entries,
                        ytitle=self.setup1.pt_bin_normalised_differential_label,
                        title=self.get_pt_bin_title(bin_edge_low, bin_edge_high),
                        xlim=qgp.calc_auto_xlim(entries),
                        subplot_limits=(0.8, 1.2),
                        **self.pt_bin_plot_args)
            self._modify_plot(plot)
            plot.subplot_title = "* / %s" % (self.region1['label'])
            plot.plot("NOSTACK E1")
            plot.save("%s/compare_unfolded_%s_bin_%d_divBinWidth.%s" % (self.setup1.output_dir, self.setup1.append, ibin, self.setup1.output_fmt))
Пример #8
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)
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)
Пример #10
0
def plot_ddelta(ddelta_hist, output_filename, xtitle, ytitle, title=""):
    cont = Contribution(ddelta_hist)
    p = Plot([cont],
             what="hist",
             legend=None,
             xtitle=xtitle,
             ytitle=ytitle,
             title=title)
    p.plot("HISTE")
    p.save(output_filename)
Пример #11
0
def do_pt_plot(pythia_dir,
               herwig_dir,
               selection,
               hist_name,
               output_name,
               title=""):
    h_pythia = grab_obj(
        "%s/uhh2.AnalysisModuleRunner.MC.MC_%s_.root" %
        (pythia_dir, selection), hist_name)
    h_herwig = grab_obj(
        "%s/uhh2.AnalysisModuleRunner.MC.MC_%s_.root" %
        (herwig_dir, selection), hist_name)

    c_pythia = Contribution(h_pythia,
                            label="MG+Pythia",
                            line_color=ROOT.kBlue,
                            marker_color=ROOT.kBlue,
                            fill_color=ROOT.kBlue,
                            normalise_hist=True)
    # c_herwig = Contribution(h_herwig, label="Herwig", line_color=ROOT.kRed, normalise_hist=True)
    c_herwig = Contribution(h_herwig,
                            label="Pythia only",
                            line_color=ROOT.kRed,
                            marker_color=ROOT.kRed,
                            fill_color=ROOT.kRed,
                            normalise_hist=True)

    p = Plot([c_pythia, c_herwig],
             what="hist",
             legend=True,
             subplot_type='ratio',
             subplot=c_pythia,
             title=title)
    p.plot("NOSTACK HISTE")
    p.main_pad.SetLogy()
    p.container.SetMinimum(1E-12)
    p.subplot_container.SetMaximum(1.5)
    p.subplot_container.SetMinimum(0)
    p.canvas.Update()
    p.save(output_name)
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)
Пример #13
0
def do_roc_plot(hist_signal, hist_background, output_filename):
    """"Make a single ROC plot"""
    gr = make_roc_graph(hist_signal, hist_background)
    cont = Contribution(gr, marker_style=21)
    p = Plot([cont],
             "graph",
             xtitle="#epsilon_{ g}",
             ytitle="#epsilon_{ q}",
             xlim=[0, 1],
             ylim=[0, 1],
             legend=False)
    p.plot("AL")
    p.save(output_filename)
Пример #14
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)
Пример #15
0
def print_hist_comparison(entries, plots_kwargs, output_filename):
    """Print multiple hists on canvas, no rescaling, no stacking

    entries: list[(object, kwargs for Contribution)]
    """
    conts = [Contribution(e[0], **e[1]) for e in entries]
    logy = plots_kwargs.get('logy', False)
    if "logy" in plots_kwargs:
        del plots_kwargs['logy']
    plot = Plot(conts, what="hist", **plots_kwargs)
    plot.plot("HISTE NOSTACK")
    if logy:
        plot.set_logy()
    plot.save(output_filename)
Пример #16
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)
Пример #17
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)
Пример #18
0
def do_roc_plot(eff_dict, output_filename):
    """Turn dict of efficiencies into ROC plot

    Parameters
    ----------
    eff_dict : TYPE
        Description
    output_filename : TYPE
        Description
    """
    signal_effs = [0] * len(eff_dict.values()[0])
    bkg_effs = [0] * len(eff_dict.values()[0])
    for k, v in eff_dict.iteritems():
        if k.replace("Dijet_Presel_",
                     "").lstrip("_unknown_").lstrip("_q").startswith("g"):
            print(k)
            for ind, eff in enumerate(v):
                signal_effs[ind] += eff
        else:
            for ind, eff in enumerate(v):
                bkg_effs[ind] += eff
    # divide by totals
    for ind, (s, b) in enumerate(zip(signal_effs, bkg_effs)):
        total = s + b
        signal_effs[ind] /= total
        bkg_effs[ind] /= total
    print(signal_effs)
    print(bkg_effs)

    gr = ROOT.TGraph(len(signal_effs), array('d', bkg_effs),
                     array('d', signal_effs))
    cont = Contribution(gr, marker_style=21)
    p = Plot([cont],
             "graph",
             xtitle="fraction jet2!=g",
             ytitle="fraction jet2=g",
             xlim=[0, 1],
             ylim=[0, 1],
             legend=False)
    p.plot("AP")
    p.save(output_filename)
Пример #19
0
def create_contibutions_compare_vs_pt(input_files, hist_names, pt_bins, labels,
                                      flav, **contrib_kwargs):
    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 = cycle([
        ROOT.kBlack, ROOT.kBlue, ROOT.kRed, ROOT.kGreen + 2, ROOT.kOrange - 3,
        ROOT.kViolet + 6
    ])

    for i, (fdict, label, col) in enumerate(zip(info, labels, colours)):
        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=label,
                         line_color=col,
                         line_width=1,
                         line_style=1,
                         marker_style=20 + i,
                         marker_color=col,
                         marker_size=1,
                         leg_draw_opt="LP",
                         **contrib_kwargs)
        contribs.append(c)
    return contribs
Пример #20
0
def plot_corrections(corrections_graph, xtitle, title, output_filename):
    # print(x_values)
    # print(corrections)
    conts = [
        Contribution(corrections_graph,
                     label="Correction",
                     line_color=ROOT.kRed,
                     marker_color=ROOT.kRed,
                     line_width=2,
                     marker_size=1,
                     marker_style=20,
                     fit_match_style=False)
    ]
    # plot = Plot(conts, what='graph', xtitle=xtitle, ytitle="Correction", title=title, has_data=False, ylim=[0, 2.5])
    plot = Plot(conts,
                what='both',
                xtitle=xtitle,
                ytitle="Correction",
                title=title,
                has_data=False,
                ylim=[0, 2.5])
    plot.plot("ALP")
    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)))
Пример #22
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)
Пример #23
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)
Пример #24
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)
Пример #25
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
Пример #26
0
def do_pt_min_delta_plots(sources,
                          plot_dir="deltas_ptmin",
                          zpj_dirname="ZPlusJets_QG",
                          dj_dirname="Dijet_QG",
                          var_list=None,
                          var_prepend="",
                          flavour_tag=False,
                          save_component_hists=False,
                          ofmt="pdf"):
    """Do plots comparing power of different ptMin cuts"""
    var_list = var_list or COMMON_VARS
    ptmin_bins = [50, 100, 200, 400, 800][:-1]
    zpj_flav = "q" if flavour_tag else ""
    dj_flav = "g" if flavour_tag else ""
    output_append = "_flavMatched" if flavour_tag else ""
    for ang in var_list:
        v = "%s%s_vs_pt" % (var_prepend, ang.var)
        graph_contribs, bin_labels = [], []

        for source_ind, source in enumerate(sources):
            deltas, components = [], []
            # for the component comparison plot
            colours = [
                ROOT.kBlue, ROOT.kRed, ROOT.kGreen + 2, ROOT.kOrange - 3,
                ROOT.kMagenta, ROOT.kAzure + 1
            ]

            for pt_min, this_colour in zip(ptmin_bins, colours):
                h2d_dyj = grab_obj(
                    os.path.join(source['root_dir'], qgc.DY_FILENAME),
                    "%s_ptMin_%d/%s%s" % (source.get(
                        'zpj_dirname', zpj_dirname), pt_min, zpj_flav, v))
                h2d_qcd = grab_obj(
                    os.path.join(source['root_dir'],
                                 qgc.QCD_FILENAME), "%s_ptMin_%d/%s%s" %
                    (source.get('dj_dirname', dj_dirname), pt_min, dj_flav, v))
                start_val, end_val = 80, 2000
                h_dy = get_projection_plot(h2d_dyj, start_val, end_val)
                if (h_dy.Integral() > 0):
                    h_dy.Scale(1. / (h_dy.GetBinWidth(1) * h_dy.Integral()))

                h_qcd = get_projection_plot(h2d_qcd, start_val, end_val)
                if (h_qcd.Integral() > 0):
                    h_qcd.Scale(1. / (h_qcd.GetBinWidth(1) * h_qcd.Integral()))

                ddelta_hist = get_ddelta_plot(h_dy, h_qcd)

                c = Contribution(ddelta_hist,
                                 line_width=1,
                                 marker_color=this_colour,
                                 line_color=this_colour,
                                 fill_color=this_colour,
                                 label="p_{T}^{Min} = %d GeV" % pt_min,
                                 rebin_hist=1)
                components.append(c)

                deltas.append(calculate_delta(ddelta_hist))

                if source_ind == 0:
                    bin_labels.append("%d" % pt_min)

                if save_component_hists:
                    # need to clone here otherwise the colour will be set inside
                    # plot_delta, which in turn will nullify whatever colours we chose above.
                    plot_ddelta(
                        ddelta_hist.Clone(ROOT.TUUID().AsString()),
                        "%s/delta_ptmin_components/%s_ddelta_ptMin_%d%s.%s" %
                        (plot_dir, ang.var, pt_min, output_append, ofmt),
                        xtitle=ang.name + " (" + ang.lambda_str + ")",
                        ytitle="d#Delta/d" + ang.lambda_str)

            if save_component_hists:
                # plot all differential distributions for this pt bin on one plot
                p = Plot(components,
                         what="hist",
                         xtitle=ang.name,
                         ytitle="p.d.f")
                p.plot("NOSTACK HISTE")
                p.save(
                    "%s/delta_ptmin_components/%s_ddelta_ptMin_comparison%s.%s"
                    % (plot_dir, ang.var, output_append, ofmt))

            gr = construct_deltas_graph(deltas)
            gr.SetName(source.get("label", ""))
            if 'style' in source and 'line_width' not in source['style']:
                source['style']['line_width'] = 2
            c = Contribution(gr,
                             label=source.get("label", "").lstrip(", "),
                             marker_style=0,
                             **source.get("style", {}))
            graph_contribs.append(c)

        do_deltas_plot(graph_contribs,
                       "%s/ptMins_%s%s.%s" %
                       (plot_dir, ang.var, output_append, ofmt),
                       bin_labels=bin_labels,
                       title="%s [%s]" % (ang.name, ang.lambda_str),
                       xtitle="p_{T}^{min} [GeV]")
Пример #27
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
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)
Пример #29
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_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)