def plot_rsp_Vs_ref(check_file, eta_min, eta_max, normX, logZ, oDir, oFormat="pdf"):
    """Plot response (l1/ref) Vs ref pt"""
    app = "_normX" if normX else ""
    hname = "eta_%g_%g/Histograms/h2d_rsp_gen%s" % (eta_min, eta_max, app)
    fwd_bin = abs(eta_min)>2.9
    if cu.exists_in_file(check_file, hname):
        h2d_rsp_ref_orig = cu.get_from_file(check_file, hname)
    else:
        h2d_rsp_ref_orig = cu.get_from_file(check_file, "eta_%g_%g/Histograms/h2d_rsp_gen" % (eta_min, eta_max))
    if normX:
        h2d_rsp_ref_orig = cu.norm_vertical_bins(h2d_rsp_ref_orig, rescale_peaks=True)
    h2d_rsp_ref = h2d_rsp_ref_orig.Rebin2D(2, 1, "hnew")
    c = generate_canvas()
    if logZ:
        c.SetLogz()
        app += "_log"
    h2d_rsp_ref.SetTitle("%s: %g-%g;%s;%s" % (eta_l1_str, eta_min, eta_max, pt_ref_str, rsp_str))
    if normX:
        h2d_rsp_ref.Draw("COL")
    else:
        h2d_rsp_ref.Draw("COLZ")
    h2d_rsp_ref.SetAxisRange(rsp_min, rsp_max, 'Y')
    if fwd_bin:
        h2d_rsp_ref.SetAxisRange(0, 254, 'X')
    line = ROOT.TLine(0, 1, 1022, 1)
    line.SetLineStyle(2)
    line.SetLineWidth(2)
    line.Draw()
    c.SaveAs("%s/h2d_rsp_ref_%g_%g%s.%s" % (oDir, eta_min, eta_max, app, oFormat))
def plot_rsp_Vs_pt_candle_violin(check_file, eta_min, eta_max, ptVar, oDir, oFormat):
    """Plot response vs pt as a candle plot and violin plot.
    Also puts fitted peak graph on there as well for comparison."""

    hname = "eta_%g_%g/Histograms/h2d_rsp_%s" % (eta_min, eta_max, ptVar)
    if cu.exists_in_file(check_file, hname):
        h2d_rsp_pt_orig = cu.get_from_file(check_file, hname)
    else:
        h2d_rsp_pt_orig = cu.get_from_file(check_file, "eta_%g_%g/Histograms/h2d_rsp_%s" % (eta_min, eta_max, ptVar))
    h2d_rsp_pt = h2d_rsp_pt_orig.Rebin2D(1, 1, "hnew")

    c = generate_canvas()
    ptStr = pt_l1_str if ptVar == 'l1' else pt_ref_str
    h2d_rsp_pt.SetTitle("%s: %g-%g;%s;%s" % (eta_l1_str, eta_min, eta_max, ptStr, rsp_str))
    h2d_rsp_pt.Draw("CANDLE")
    # Draw fitted peaks as well
    gr_name = "eta_{0:g}_{1:g}/gr_rsp_{2}_eta_{0:g}_{1:g}".format(eta_min, eta_max, 'pt' if ptVar == 'l1' else 'ptRef')
    gr = cu.get_from_file(check_file, gr_name)
    gr.SetLineColor(ROOT.kRed)
    gr.SetMarkerColor(ROOT.kRed)
    gr.SetMarkerStyle(21)
    gr.Draw("LP")

    max_pt = 100
    gr.GetXaxis().SetLimits(0, max_pt)
    h2d_rsp_pt.SetAxisRange(0, max_pt, 'X')
    h2d_rsp_pt.SetAxisRange(rsp_min, rsp_max, 'Y')

    line = ROOT.TLine(0, 1, max_pt, 1)
    line.SetLineStyle(2)
    line.SetLineWidth(2)
    line.Draw()
    c.SaveAs("%s/h2d_rsp_%s_%g_%g_box.%s" % (oDir, 'l1' if ptVar == 'l1' else 'ref', eta_min, eta_max, oFormat))

    h2d_rsp_pt.Draw("VIOLIN")
    gr.Draw("LP")
    c.SaveAs("%s/h2d_rsp_%s_%g_%g_violin.%s" % (oDir, 'l1' if ptVar == 'l1' else 'ref', eta_min, eta_max, oFormat))
                dir_append = hist_dir.lower().replace("weight_", "")
                odir = os.path.join(MAINDIR, workdir, "var_jet_pt_weights_%s_%s" % (dir_append, filename.replace("uhh2.AnalysisModuleRunner.MC.MC_", "").replace(".root", "")))
                cu.check_dir_exists_create(odir)

                # do_weight_vs_pt_plot(input_filename=ifile,
                #                      output_filename=os.path.join(odir, "weight_vs_pt.pdf"))

                # do_weight_vs_genjet_pt_plot(input_filename=ifile,
                #                             output_filename=os.path.join(odir, "weight_vs_genjet_pt.pdf"))

                for ind, base_hname in enumerate(histnames):
                    hname = os.path.join(hist_dir, base_hname)
                    
                    tf = cu.open_root_file(ifile)
                    if not cu.exists_in_file(tf, hname):
                        continue

                    do_var_vs_pt_plot(histname=hname,
                                      input_filename=ifile,
                                      output_filename=os.path.join(odir, base_hname.replace("weight_vs_", "") + ".pdf"))

                    # if "_vs_pt_" in hname:
                    #     # skip the _vs_pt_genjet_ since identical, and we collapse that axis anyway
                    #     do_weight_vs_var_plot(histname=hname,
                    #                           input_filename=ifile,
                    #                           output_filename=os.path.join(odir, base_hname.replace("_vs_pt_vs_", "_").replace("_vs_pt_genjet_vs_", "") + ".pdf"))

                    cuts = [10, 9, 8, 7, 6, 5, 4, 3, 2]
                    cuts = [10, 8, 6, 4, 3, 2]
                    cuts = [100, 75, 50, 25, 10, 8, 5, 2]
def main(in_args):
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--input",
        help=
        "Input ROOT file with response & resolution hists (from jet_response_fitter_x)",
        required=True)
    parser.add_argument("--outputDir",
                        help="Output directory for plots",
                        default=os.getcwd())
    parser.add_argument("--title", help="Title string for plots", default="")
    parser.add_argument("--sampleName",
                        help="Sample name string for plots",
                        default="")
    parser.add_argument("--plotN",
                        help="Plot grpah of N vs pT that goes into the median",
                        action='store_true')
    parser.add_argument(
        "--plotRMS",
        help="Plot graph of raw RMS vs pT that goes into memdian",
        action='store_true')
    args = parser.parse_args(in_args)

    cu.check_dir_exists_create(args.outputDir)

    lw = 2
    entry_dicts = [
        {
            "flav": "RelRsp",
            "label": "All",
            "colour": ROOT.kBlack,
            "marker_style": ROOT.kFullCircle,
            "line_style": 2,
            "line_width": lw,
            "marker_size": 1.2
        },
        {
            "flav": "ud_RelRsp",
            "label": "ud",
            "colour": ROOT.kRed,
            "marker_style": ROOT.kFullSquare,
            "line_style": 1,
            "line_width": lw,
            "marker_size": 1.2
        },
        {
            "flav": "s_RelRsp",
            "label": "s",
            "colour": ROOT.kBlue,
            "marker_style": ROOT.kFullTriangleUp,
            "line_style": 1,
            "line_width": lw,
            "marker_size": 1.4
        },
        {
            "flav": "c_RelRsp",
            "label": "c",
            "colour": ROOT.kGreen + 2,
            "marker_style": ROOT.kFullTriangleDown,
            "line_style": 1,
            "line_width": lw,
            "marker_size": 1.4
        },
        {
            "flav": "b_RelRsp",
            "label": "b",
            "colour": ROOT.kOrange - 3,
            "marker_style": ROOT.kFullDiamond,
            "line_style": 1,
            "line_width": lw,
            "marker_size": 1.6
        },
        {
            "flav": "g_RelRsp",
            "label": "g",
            "colour": ROOT.kAzure + 1,
            "marker_style": 29,
            "line_style": 1,
            "line_width": lw,
            "marker_size": 1.8
        },
    ]

    # Loop through all different ak4pfchs, etc
    input_tfile = cu.open_root_file(args.input)
    dirs = cu.get_list_of_element_names(input_tfile)
    for mydir in dirs[:1]:
        jec_text = ROOT.TPaveText(0.14, 0.91, 0.2, 0.92, "NDC")
        jec_text.AddText(args.title)
        jec_text.SetTextAlign(ROOT.kHAlignLeft + ROOT.kVAlignBottom)
        jec_text.SetTextFont(42)
        jec_text.SetTextSize(FONT_SIZE)
        jec_text.SetBorderSize(0)
        jec_text.SetFillStyle(0)

        dir_text = ROOT.TPaveText(0.17, 0.72, 0.2, 0.73, "NDC")
        dir_label = mydir.upper().replace("PFCHS", " PF CHS").replace(
            "PUPPI", " PUPPI").replace("L1L2L3",
                                       " + L1L2L3").replace("L1", " + L1")
        dir_text.AddText(dir_label)
        dir_text.SetTextAlign(ROOT.kHAlignLeft + ROOT.kVAlignBottom)
        dir_text.SetTextFont(42)
        dir_text.SetTextSize(FONT_SIZE)
        dir_text.SetBorderSize(0)
        dir_text.SetFillStyle(0)

        sample_text = ROOT.TPaveText(0.91, 0.91, 0.97, 0.92, "NDC")
        sample_text.AddText(args.sampleName + " 13 TeV")
        sample_text.SetTextFont(42)
        sample_text.SetTextSize(FONT_SIZE)
        sample_text.SetTextAlign(ROOT.kHAlignRight + ROOT.kVAlignBottom)
        sample_text.SetBorderSize(0)
        sample_text.SetFillStyle(0)
        sample_text.Draw()

        other_elements = [jec_text, dir_text, sample_text]

        plot_dir = os.path.join(args.outputDir, mydir)
        cu.check_dir_exists_create(plot_dir)

        obj_list = cu.get_list_of_objects_in_dir(args.input, mydir)

        # Do separate dir for each eta bin, then separate plot for each pt bin
        common_eta_bins = cu.sort_human(cu.get_common_eta_bins(obj_list))
        common_pt_bins = cu.sort_human(cu.get_common_pt_bins(obj_list))
        print("Doing eta bins", common_eta_bins)
        print("Doing pt bins", common_pt_bins)

        for eta_bin in common_eta_bins[:]:
            this_plot_dir = os.path.join(plot_dir, eta_bin)
            cu.check_dir_exists_create(this_plot_dir)

            all_pt_entries = []
            for pt_bin in common_pt_bins:
                entries = []
                if not cu.exists_in_file(
                        input_tfile, "%s/%s_%s_%s" %
                    (mydir, entry_dicts[0]['flav'], eta_bin, pt_bin)):
                    continue
                for fdict in entry_dicts:
                    entry = deepcopy(fdict)
                    # entry["hist"] = cu.grab_obj_from_file(args.input, "%s/%s_%s_%s" % (mydir, fdict['flav'], eta_bin, pt_bin))
                    entry["hist"] = cu.get_from_tfile(
                        input_tfile, "%s/%s_%s_%s" %
                        (mydir, fdict['flav'], eta_bin, pt_bin))
                    entry["hist"].Rebin(int(entry["hist"].GetNbinsX() / 200))
                    entry["line_color"] = fdict['colour']
                    entry["marker_color"] = fdict['colour']
                    entries.append(entry)
                bin_title = eta_bin.replace("to", " < |#eta| < ").replace(
                    "JetEta", "")
                bin_title += "\n"
                bin_title += pt_bin.replace("to", " < p^{Gen}_{T} < ").replace(
                    "RefPt", "")
                bin_title += " GeV"
                norm_entries = deepcopy(entries)
                do_comparison_hist(
                    entries,
                    bin_title=bin_title,
                    xlimits=(0, 2),
                    xtitle="Response (p_{T}^{Reco} / p_{T}^{Gen})",
                    ytitle="N",
                    other_elements=other_elements,
                    normalise=False,
                    output_filename=os.path.join(
                        this_plot_dir, "rsp_vs_pt_%s.pdf" % (pt_bin)))

                all_pt_entries.append(deepcopy(entries))
                do_comparison_hist(
                    norm_entries,
                    bin_title=bin_title,
                    xlimits=(0, 2),
                    xtitle="Response (p_{T}^{Reco} / p_{T}^{Gen})",
                    ytitle="p.d.f",
                    other_elements=other_elements,
                    normalise=True,
                    draw_fits=False,
                    output_filename=os.path.join(
                        this_plot_dir, "rsp_vs_pt_%s_normed.pdf" % (pt_bin)))

            this_dir_text = dir_text.Clone()
            this_dir_text.SetY1(0.76)
            this_dir_text.SetY2(0.77)
            bin_title = eta_bin.replace("to",
                                        " < |#eta| < ").replace("JetEta", "")
            do_flavour_fraction_graph(
                all_pt_entries,
                common_pt_bins,
                title=bin_title,
                xtitle="p^{Gen}_{T} [GeV]",
                ytitle="Flavour fraction",
                other_elements=[jec_text, this_dir_text, sample_text],
                add_unknown=False,
                logx=True,
                logy=True,
                output_filename=os.path.join(
                    plot_dir, "flav_frac_vs_pt_%s.pdf" % (eta_bin)))

            if args.plotN:
                do_plot_N_graph(
                    all_pt_entries,
                    common_pt_bins,
                    title=bin_title,
                    which="GetEffectiveEntries",
                    xtitle="p^{Gen}_{T} [GeV]",
                    other_elements=[jec_text, this_dir_text, sample_text],
                    logx=True,
                    logy=True,
                    output_filename=os.path.join(
                        plot_dir, "Neff_vs_pt_%s.pdf" % (eta_bin)))

            if args.plotRMS:
                do_plot_RMS_graph(
                    all_pt_entries,
                    common_pt_bins,
                    title=bin_title,
                    xtitle="p^{Gen}_{T} [GeV]",
                    other_elements=[jec_text, this_dir_text, sample_text],
                    logx=True,
                    logy=True,
                    output_filename=os.path.join(
                        plot_dir, "RMS_vs_pt_%s.pdf" % (eta_bin)))

    return 0