def compare_by_eta_pu_bins(graphs_list, file_identifier, pu_labels, title, oDir, ylim=None, lowpt_zoom=True): """Compare graphs for each (eta, PU) bin. Parameters ---------- graphs_list : list[list[Contribution]] List of list of contributions, so you can any number of sets of contributions on a graph. file_identifier : str String to be inserted into resultant plot filename. title : str Title to put on plots oDir : str Output directory for plots ylim : list, optional Set y axis range lowpt_zoom : bool, optional Zoom in on low pt range """ for (eta_min, eta_max) in pairwise(binning.eta_bins): rename_dict = dict(eta_min=eta_min, eta_max=eta_max) new_graphs_list = [ setup_new_graphs(g, rename_dict) for g in graphs_list ] if not ylim: ylim = [0.5, 3.5] if eta_min > 2 else [0.5, 4] for i, pu_label in enumerate(pu_labels): rename_dict['pu_label'] = pu_label p = Plot(contributions=[ng[i] for ng in new_graphs_list], what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), ylim=ylim) p.plot() p.save( os.path.join( oDir, "compare_%s_eta_%g_%g_%s.pdf" % (file_identifier, eta_min, eta_max, pu_label))) if lowpt_zoom: # zoom in on low pT p = Plot(contributions=[ng[i] for ng in new_graphs_list], what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), xlim=zoom_pt, ylim=ylim) p.plot() p.save( os.path.join( oDir, "compare_%s_eta_%g_%g_%s_pTzoomed.pdf" % (file_identifier, eta_min, eta_max, pu_label)))
def compare_scenarios_by_pu_eta_bins(eta_bins, pu_labels, graph_lists, title, oDir, ylim=None, lowpt_zoom=False): for eta_min, eta_max in pairwise(eta_bins): for pu_ind, pu_label in enumerate(pu_labels): pu_graphs = [x[pu_ind] for x in graph_lists] # tweak names and colors for i, contr in enumerate(pu_graphs): contr.line_color = colors[i] contr.marker_color = colors[i] contr.obj_name = "eta_%g_%g/resRefRef_%g_%g_diff" % (eta_min, eta_max, eta_min, eta_max) fmt_dict = dict(eta_min=eta_min, eta_max=eta_max, pu_label=pu_label) plt_title = title.format(**fmt_dict) p = Plot(contributions=pu_graphs, what='graph', xtitle=pt_ref_str, ytitle=res_ref_str, title=plt_title, ylim=[0, 0.7], xlim=[0, 500]) p.legend.SetX1(0.4) p.plot() filename = 'compare_fall15_dummyLayer1_newLayer1_withJEC_eta_%g_%g_%s.pdf' % (eta_min, eta_max, pu_label) p.save(os.path.join(oDir, filename)) if lowpt_zoom: p = Plot(contributions=pu_graphs, what='graph', xtitle=pt_ref_str, ytitle=res_ref_str, title=plt_title, ylim=[0, 0.7], xlim=zoom_pt) p.legend.SetX1(0.4) p.plot() filename = 'compare_fall15_dummyLayer1_newLayer1_withJEC_eta_%g_%g_%s_ptZoomed.pdf' % (eta_min, eta_max, pu_label) p.save(os.path.join(oDir, filename))
def do_mc_pt_comparison_plot(dirname_label_pairs, output_filename, qcd_filename, **plot_kwargs): # qcd_files = [cu.open_root_file(os.path.join(dl[0], qgc.QCD_FILENAME)) for dl in dirname_label_pairs] qcd_files = [ cu.open_root_file(os.path.join(dl[0], qgc.QCD_PYTHIA_ONLY_FILENAME)) for dl in dirname_label_pairs ] histname = "Dijet_tighter/pt_jet1" qcd_hists = [cu.get_from_tfile(qf, histname) for qf in qcd_files] N = len(dirname_label_pairs) conts = [ Contribution(qcd_hists[i], label=lab, marker_color=cu.get_colour_seq(i, N), line_color=cu.get_colour_seq(i, N), line_style=(i % 3) + 1, line_width=2, rebin_hist=1, subplot=qcd_hists[0] if i != 0 else None) for i, (d, lab) in enumerate(dirname_label_pairs) ] plot = Plot(conts, what='hist', ytitle="N", subplot_limits=(0.5, 1.5), subplot_type="ratio", subplot_title="* / %s" % (dirname_label_pairs[0][1]), **plot_kwargs) plot.y_padding_max_log = 500 plot.legend.SetY1(0.7) plot.plot("NOSTACK HIST E") plot.set_logx(do_more_labels=False) plot.set_logy(do_more_labels=False) plot.save(output_filename)
def 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)
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_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)
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)
def compare_PU_by_eta_bins(graphs, title, oDir, ylim=None, lowpt_zoom=True): """Plot graph contributions, with a different plot for each eta bin. Parameters ---------- graphs : list[Contribution] List of Contribution objects to be included on any one plot. title : str Title to put on plots oDir : str Output directory for plots ylim : list, optional Set y axis range lowpt_zoom : bool, optional Zoom in on low pt range """ for i, (eta_min, eta_max) in enumerate(pairwise(binning.eta_bins)): rename_dict = dict(eta_min=eta_min, eta_max=eta_max) # make a copy as we have to change the graph names new_graphs = setup_new_graphs(graphs, rename_dict) if not ylim: ylim = [0.5, 3.5] if eta_min > 2 else [0.5, 4] p = Plot(contributions=new_graphs, what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), ylim=ylim) p.plot() p.save( os.path.join(oDir, "compare_PU_eta_%g_%g.pdf" % (eta_min, eta_max))) if lowpt_zoom: # zoom in on low pT p = Plot(contributions=new_graphs, what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), xlim=zoom_pt, ylim=ylim) p.plot() p.save( os.path.join( oDir, "compare_PU_eta_%g_%g_pTzoomed.pdf" % (eta_min, eta_max)))
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 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)
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)
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)
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)
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)
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))
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 compare_eta_by_pu_bins(graphs, pu_labels, title, oDir, ylim=None, lowpt_zoom=True): """Compare eta bins for graphs for a given PU bin. Does central, fowrad, and central+forward. Parameters ---------- graphs : list[Contribution] Contributions corresponding to eta bins (0PU, PU0to10, 15to25, 30to40) title : str Title to put on plots oDir : str Output directory for plots ylim : list, optional Set y axis range lowpt_zoom : bool, optional Zoom in on low pt range """ cu.check_dir_exists_create(oDir) eta_scenarios = [binning.eta_bins_central, binning.eta_bins_forward, binning.eta_bins] eta_scenario_labels = ['central', 'forward', 'all'] for eta_bins, eta_label in izip(eta_scenarios, eta_scenario_labels): for pu_ind, pu_label in enumerate(pu_labels): new_graphs = [] rename_dict = dict(pu_label=pu_label) for eta_ind, (eta_min, eta_max) in enumerate(pairwise(eta_bins)): rename_dict['eta_min'] = eta_min rename_dict['eta_max'] = eta_max contr = deepcopy(graphs[pu_ind]) contr.obj_name = graphs[pu_ind].obj_name.format(**rename_dict) contr.line_color = colors[eta_ind] contr.marker_color = colors[eta_ind] contr.label = "%g < |#eta^{L1}| < %g" % (eta_min, eta_max) new_graphs.append(contr) if not ylim: ylim = [0.5, 4] p = Plot(contributions=new_graphs, what='graph', xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), ylim=ylim) p.plot() p.save(os.path.join(oDir, 'compare_%sEta_%s.pdf' % (eta_label, pu_label))) if lowpt_zoom: p = Plot(contributions=new_graphs, what='graph', xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), xlim=zoom_pt, ylim=ylim) p.plot() p.save(os.path.join(oDir, 'compare_%sEta_%s_pTzoomed.pdf' % (eta_label, pu_label)))
def compare_by_eta_pu_bins(graphs_list, file_identifier, pu_labels, title, oDir, ylim=None, lowpt_zoom=True): """Compare graphs for each (eta, PU) bin. Parameters ---------- graphs_list : list[list[Contribution]] List of list of contributions, so you can any number of sets of contributions on a graph. file_identifier : str String to be inserted into resultant plot filename. title : str Title to put on plots oDir : str Output directory for plots ylim : list, optional Set y axis range lowpt_zoom : bool, optional Zoom in on low pt range """ cu.check_dir_exists_create(oDir) for (eta_min, eta_max) in pairwise(binning.eta_bins): rename_dict = dict(eta_min=eta_min, eta_max=eta_max) eta_min_str = '{:g}'.format(eta_min).replace('.', 'p') eta_max_str = '{:g}'.format(eta_max).replace('.', 'p') new_graphs_list = [setup_new_graphs(g, rename_dict) for g in graphs_list] if not ylim: ylim = [0.5, 3.5] if eta_min > 2 else [0.5, 4] for i, pu_label in enumerate(pu_labels): rename_dict['pu_label'] = pu_label p = Plot(contributions=[ng[i] for ng in new_graphs_list], what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), ylim=ylim) p.plot() p.legend.SetX1(0.5) p.save(os.path.join(oDir, "compare_%s_eta_%s_%s_%s.pdf" % (file_identifier, eta_min_str, eta_max_str, pu_label))) if lowpt_zoom: # zoom in on low pT p = Plot(contributions=[ng[i] for ng in new_graphs_list], what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), xlim=zoom_pt, ylim=ylim) p.plot() p.legend.SetX1(0.5) p.save(os.path.join(oDir, "compare_%s_eta_%s_%s_%s_pTzoomed.pdf" % (file_identifier, eta_min_str, eta_max_str, pu_label)))
def compare_PU_by_eta_bins(graphs, title, oDir, ylim=None, lowpt_zoom=True): """Plot graph contributions, with a different plot for each eta bin. Relies on each Contribution.obj_name in graphs being templated with the variables `eta_min` and `eta_max`. Parameters ---------- graphs : list[Contribution] List of Contribution objects to be included on any one plot. title : str Title to put on plots oDir : str Output directory for plots ylim : list, optional Set y axis range lowpt_zoom : bool, optional Zoom in on low pt range """ cu.check_dir_exists_create(oDir) for i, (eta_min, eta_max) in enumerate(pairwise(binning.eta_bins)): rename_dict = dict(eta_min=eta_min, eta_max=eta_max) eta_min_str = '{:g}'.format(eta_min).replace('.', 'p') eta_max_str = '{:g}'.format(eta_max).replace('.', 'p') # make a copy as we have to change the graph names new_graphs = setup_new_graphs(graphs, rename_dict) if not ylim: ylim = [0.5, 2] if eta_min > 2 else [0.5, 2.5] p = Plot(contributions=new_graphs, what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), ylim=ylim) p.plot() p.save(os.path.join(oDir, "compare_PU_eta_%s_%s.pdf" % (eta_min_str, eta_max_str))) if lowpt_zoom: # zoom in on low pT p = Plot(contributions=new_graphs, what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), xlim=zoom_pt, ylim=ylim) p.plot() p.save(os.path.join(oDir, "compare_PU_eta_%s_%s_pTzoomed.pdf" % (eta_min_str, eta_max_str)))
def compare_PU_by_eta_bins(graphs, title, oDir, ylim=None, lowpt_zoom=True): """Plot graph contributions, with a different plot for each eta bin. Relies on each Contribution.obj_name in graphs being templated with the variables `eta_min` and `eta_max`. Parameters ---------- graphs : list[Contribution] List of Contribution objects to be included on any one plot. title : str Title to put on plots oDir : str Output directory for plots ylim : list, optional Set y axis range lowpt_zoom : bool, optional Zoom in on low pt range """ cu.check_dir_exists_create(oDir) for i, (eta_min, eta_max) in enumerate(pairwise(binning.eta_bins)): rename_dict = dict(eta_min=eta_min, eta_max=eta_max) eta_min_str = '{:g}'.format(eta_min).replace('.', 'p') eta_max_str = '{:g}'.format(eta_max).replace('.', 'p') # make a copy as we have to change the graph names new_graphs = setup_new_graphs(graphs, rename_dict) if not ylim: ylim = [0.5, 3] if eta_min > 2 else [0.5, 3] p = Plot(contributions=new_graphs, what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), ylim=ylim) p.plot() p.save(os.path.join(oDir, "compare_PU_eta_%s_%s.pdf" % (eta_min_str, eta_max_str))) if lowpt_zoom: # zoom in on low pT p = Plot(contributions=new_graphs, what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), xlim=zoom_pt, ylim=ylim) p.plot() p.save(os.path.join(oDir, "compare_PU_eta_%s_%s_pTzoomed.pdf" % (eta_min_str, eta_max_str)))
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)
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)
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 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)
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)))
def do_genht_comparison_plot(dirname_label_pairs, output_filename, **plot_kwargs): """Like do_genht but for multiple samples""" qcd_files = [ cu.open_root_file(os.path.join(dl[0], qgc.QCD_FILENAME)) for dl in dirname_label_pairs ] histname = "Dijet_gen/gen_ht" qcd_hists = [cu.get_from_tfile(qf, histname) for qf in qcd_files] N = len(dirname_label_pairs) conts = [ Contribution(qcd_hists[i], label=lab, marker_color=cu.get_colour_seq(i, N), line_color=cu.get_colour_seq(i, N), line_style=i + 1, line_width=2, subplot=qcd_hists[0] if i != 0 else None) for i, (d, lab) in enumerate(dirname_label_pairs) ] plot = Plot( conts, what='hist', ytitle="N", # subplot_limits=(0.75, 1.25), subplot_type="ratio", subplot_title="* / %s" % (dirname_label_pairs[0][1]), ylim=[1E6, None], **plot_kwargs) plot.y_padding_max_log = 500 plot.legend.SetY1(0.7) plot.subplot_maximum_ceil = 5 plot.plot("NOSTACK HIST E") plot.set_logx(do_more_labels=False) plot.set_logy(do_more_labels=False) plot.save(output_filename)
def do_deltas_plot(graph_contribs, output_filename, bin_labels, title="", xtitle=""): do_legend = len(graph_contribs) > 1 p = Plot(graph_contribs, what="graph", title=title, xtitle=xtitle, ytitle="Separation #Delta", legend=do_legend) if do_legend: p.legend.SetX1(0.7) p.legend.SetY1(0.15) p.legend.SetY2(0.35) p.plot("AP") # p.container.GetXaxis().LabelsOption("h") xax = p.container.GetXaxis() for i, lab in enumerate(bin_labels): bin_ind = xax.FindBin(i) # need this as they don't correspond at all! p.container.GetXaxis().SetBinLabel(bin_ind, lab) p.container.SetMinimum(0) p.save(output_filename)
def compare_PU_by_eta_bins(graphs, title, oDir, ylim=None, lowpt_zoom=True): """Plot graph contributions, with a different plot for each eta bin. Parameters ---------- graphs : list[Contribution] List of Contribution objects to be included on any one plot. title : str Title to put on plots oDir : str Output directory for plots ylim : list, optional Set y axis range lowpt_zoom : bool, optional Zoom in on low pt range """ for i, (eta_min, eta_max) in enumerate(pairwise(binning.eta_bins)): rename_dict = dict(eta_min=eta_min, eta_max=eta_max) # make a copy as we have to change the graph names new_graphs = setup_new_graphs(graphs, rename_dict) if not ylim: ylim = [0.5, 3.5] if eta_min > 2 else [0.5, 4] p = Plot(contributions=new_graphs, what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), ylim=ylim) p.plot() p.save(os.path.join(oDir, "compare_PU_eta_%g_%g.pdf" % (eta_min, eta_max))) if lowpt_zoom: # zoom in on low pT p = Plot(contributions=new_graphs, what="graph", xtitle="<p_{T}^{L1}>", ytitle="Correction value (= 1/response)", title=title.format(**rename_dict), xlim=zoom_pt, ylim=ylim) p.plot() p.save(os.path.join(oDir, "compare_PU_eta_%g_%g_pTzoomed.pdf" % (eta_min, eta_max)))
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)
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)
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)
def compare_flavour_fraction_hists_vs_pt(input_files, hist_names, pt_bins, labels, flav, output_filename, title="", xtitle="p_{T}^{jet} [GeV]", is_preliminary=True): """Plot a specified flavour fraction vs pT for several sources. Each entry in input_files, dirnames, and labels corresponds to one line n_partons can be a str, 'all', '1', etc, or a list of str to include TODO: use this one more often - compare_flavour_fractions_vs_pt() is almost identical but has to deal with npartons """ bin_centers = [0.5 * (x[0] + x[1]) for x in pt_bins] bin_widths = [0.5 * (x[1] - x[0]) for x in pt_bins] contribs = [] info = [ get_flavour_efficiencies(ifile, bins=pt_bins, hist_name=hname) for ifile, hname in zip(input_files, hist_names) ] N = len(bin_centers) colours = [ROOT.kBlack, ROOT.kBlue, ROOT.kRed, ROOT.kGreen + 2] for i, fdict in enumerate(info): if flav in ['u', 'd', 's', 'c', 'b', 't', 'g']: obj = fdict[flav].CreateGraph() else: raise RuntimeError("Robin broke 1-X functionality") obj = ROOT.TGraphErrors( N, np.array(bin_centers), 1. - np.array(fdict[flav.replace("1-", '')]), np.array(bin_widths), np.zeros(N)) if obj.GetN() == 0: continue c = Contribution(obj, label=labels[i], line_color=colours[i], line_width=1, line_style=1, marker_style=20 + i, marker_color=colours[i], marker_size=1, leg_draw_opt="LP") contribs.append(c) flav_str = FLAV_STR_DICT[flav] ytitle = "Fraction of %s %ss" % (flav_str.lower(), get_jet_str('')) p = Plot(contribs, what='graph', xtitle=xtitle, ytitle=ytitle, title=title, xlim=(50, 2000), ylim=(0, 1), has_data=False, is_preliminary=is_preliminary) p.default_canvas_size = (600, 600) try: p.plot("AP") p.main_pad.SetBottomMargin(0.16) p.get_modifier().GetXaxis().SetTitleOffset(1.4) p.get_modifier().GetXaxis().SetTitleSize(.045) p.legend.SetX1(0.56) p.legend.SetY1(0.65) p.legend.SetY2(0.87) p.set_logx(do_more_labels=True, do_exponent=False) p.save(output_filename) except ZeroContributions: pass
def 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