def compare_ml_std(case_ml,
                   ana_type_ml,
                   period_number,
                   filepath_std,
                   scale_std=None,
                   map_std_bins=None,
                   mult_bin=None,
                   ml_histo_names=None,
                   std_histo_names=None,
                   suffix=""):

    with open("data/database_ml_parameters_%s.yml" % case_ml,
              'r') as param_config:
        data_param = yaml.load(param_config, Loader=yaml.FullLoader)
    if period_number < 0:
        filepath_ml = data_param[case_ml]["analysis"][ana_type_ml]["data"][
            "resultsallp"]
    else:
        filepath_ml = data_param[case_ml]["analysis"][ana_type_ml]["data"][
            "results"][period_number]

    # Get pt spectrum files
    if mult_bin is None:
        mult_bin = 0
    path_ml = f"{filepath_ml}/finalcross{case_ml}{ana_type_ml}mult{mult_bin}.root"
    if not os.path.exists(path_ml):
        FILES_NOT_FOUND.append(path_ml)
        return

    file_ml = TFile.Open(path_ml, "READ")
    file_std = TFile.Open(filepath_std, "READ")

    # Collect histo names to quickly loop later
    histo_names = [
        "hDirectMCpt", "hFeedDownMCpt", "hDirectMCptMax", "hDirectMCptMin",
        "hFeedDownMCptMax", "hFeedDownMCptMin", "hDirectEffpt",
        "hFeedDownEffpt", "hRECpt", "histoYieldCorr", "histoYieldCorrMax",
        "histoYieldCorrMin", "histoSigmaCorr", "histoSigmaCorrMax",
        "histoSigmaCorrMin"
    ]
    if ml_histo_names is None:
        ml_histo_names = histo_names
    if std_histo_names is None:
        std_histo_names = histo_names

    for hn_ml, hn_std in zip(ml_histo_names, std_histo_names):
        histo_ml = file_ml.Get(hn_ml)
        histo_std_tmp = file_std.Get(hn_std)
        histo_std = None

        if not histo_ml:
            print(f"Could not find histogram {hn_ml}, continue...")
            continue
        if not histo_std_tmp:
            print(f"Could not find histogram {hn_std}, continue...")
            continue

        if "MC" not in hn_ml and map_std_bins is not None:
            histo_std = histo_ml.Clone("std_rebin")
            histo_std.Reset("ICESM")

            contents = [0] * histo_ml.GetNbinsX()
            errors = [0] * histo_ml.GetNbinsX()

            for ml_bin, std_bins in map_std_bins:
                for b in std_bins:
                    contents[ml_bin-1] += histo_std_tmp.GetBinWidth(b) * \
                            histo_std_tmp.GetBinContent(b) / histo_ml.GetBinWidth(ml_bin)
                    errors[ml_bin - 1] += histo_std_tmp.GetBinError(
                        b) * histo_std_tmp.GetBinError(b)

            for b in range(histo_std.GetNbinsX()):
                histo_std.SetBinContent(b + 1, contents[b])
                histo_std.SetBinError(b + 1, sqrt(errors[b]))

        else:
            histo_std = histo_std_tmp.Clone("std_cloned")
        if scale_std is not None:
            histo_std.Scale(scale_std)

        folder_plots = data_param[case_ml]["analysis"]["dir_general_plots"]
        if not os.path.exists(folder_plots):
            print("creating folder ", folder_plots)
            os.makedirs(folder_plots)


        save_path = \
                f"{folder_plots}/{hn_ml}_ml_std_mult_{mult_bin}_period_{period_number}{suffix}.eps"

        plot_histograms([histo_std, histo_ml], True, True, ["STD", "ML"],
                        histo_ml.GetTitle(), "#it{p}_{T} (GeV/#it{c}",
                        histo_ml.GetYaxis().GetTitle(), "ML / STD", save_path)
def compare_ml_std_ratio(case_ml_1,
                         case_ml_2,
                         ana_type_ml,
                         period_number,
                         filepath_std_1,
                         filepath_std_2,
                         scale_std_1=None,
                         scale_std_2=None,
                         map_std_bins=None,
                         mult_bin=None,
                         ml_histo_names=None,
                         std_histo_names_1=None,
                         std_histo_names_2=None,
                         suffix=""):

    with open("data/database_ml_parameters_%s.yml" % case_ml_1,
              'r') as param_config:
        data_param_1 = yaml.load(param_config, Loader=yaml.FullLoader)
    with open("data/database_ml_parameters_%s.yml" % case_ml_2,
              'r') as param_config:
        data_param_2 = yaml.load(param_config, Loader=yaml.FullLoader)
    if period_number < 0:
        filepath_ml_1 = data_param_1[case_ml_1]["analysis"][ana_type_ml][
            "data"]["resultsallp"]
        filepath_ml_2 = data_param_2[case_ml_2]["analysis"][ana_type_ml][
            "data"]["resultsallp"]
    else:
        filepath_ml_1 = \
                data_param_1[case_ml_1]["analysis"][ana_type_ml]["data"]["results"][period_number]
        filepath_ml_2 = \
                data_param_2[case_ml_2]["analysis"][ana_type_ml]["data"]["results"][period_number]

    name_1 = data_param_1[case_ml_1]["analysis"][ana_type_ml]["latexnamemeson"]
    name_2 = data_param_2[case_ml_2]["analysis"][ana_type_ml]["latexnamemeson"]
    # Get pt spectrum files
    if mult_bin is None:
        mult_bin = 0
    path_ml_1 = f"{filepath_ml_1}/finalcross{case_ml_1}{ana_type_ml}mult{mult_bin}.root"
    path_ml_2 = f"{filepath_ml_2}/finalcross{case_ml_2}{ana_type_ml}mult{mult_bin}.root"
    if not os.path.exists(path_ml_1):
        FILES_NOT_FOUND.append(path_ml_1)
        return
    if not os.path.exists(path_ml_2):
        FILES_NOT_FOUND.append(path_ml_2)
        return

    file_ml_1 = TFile.Open(path_ml_1, "READ")
    file_ml_2 = TFile.Open(path_ml_2, "READ")
    file_std_1 = TFile.Open(filepath_std_1, "READ")
    file_std_2 = TFile.Open(filepath_std_2, "READ")

    # Collect histo names to quickly loop later
    histo_names = [
        "hDirectMCpt", "hFeedDownMCpt", "hDirectMCptMax", "hDirectMCptMin",
        "hFeedDownMCptMax", "hFeedDownMCptMin", "hDirectEffpt",
        "hFeedDownEffpt", "hRECpt", "histoYieldCorr", "histoYieldCorrMax",
        "histoYieldCorrMin", "histoSigmaCorr", "histoSigmaCorrMax",
        "histoSigmaCorrMin"
    ]

    if ml_histo_names is None:
        ml_histo_names = histo_names
    if std_histo_names_1 is None:
        std_histo_names_1 = histo_names
    if std_histo_names_2 is None:
        std_histo_names_2 = histo_names

    for hn_ml, hn_std_1, hn_std_2 in zip(ml_histo_names, std_histo_names_1,
                                         std_histo_names_2):
        histo_ml_1 = file_ml_1.Get(hn_ml)
        histo_ml_2 = file_ml_2.Get(hn_ml)
        histo_std_tmp_1 = file_std_1.Get(hn_std_1)
        histo_std_tmp_2 = file_std_2.Get(hn_std_2)
        histo_std_1 = None
        histo_std_2 = None

        if not histo_ml_1:
            print(f"Could not find histogram {hn_ml}, continue...")
            continue
        if not histo_ml_2:
            print(f"Could not find histogram {hn_ml}, continue...")
            continue
        if not histo_std_tmp_1:
            print(f"Could not find histogram {hn_std_1}, continue...")
            continue
        if not histo_std_tmp_2:
            print(f"Could not find histogram {hn_std_2}, continue...")
            continue

        if "MC" not in hn_ml and map_std_bins is not None:
            histo_std_1 = histo_ml_1.Clone("std_rebin_1")
            histo_std_1.Reset("ICESM")
            histo_std_2 = histo_ml_2.Clone("std_rebin_2")
            histo_std_2.Reset("ICESM")

            contents = [0] * histo_ml_1.GetNbinsX()
            errors = [0] * histo_ml_1.GetNbinsX()

            for ml_bin, std_bins in map_std_bins:
                for b in std_bins:
                    contents[
                        ml_bin -
                        1] += histo_std_tmp_1.GetBinContent(b) / len(std_bins)
                    errors[ml_bin-1] += \
                            histo_std_tmp_1.GetBinError(b) * histo_std_tmp_1.GetBinError(b)

            for b in range(histo_std_1.GetNbinsX()):
                histo_std_1.SetBinContent(b + 1, contents[b])
                histo_std_1.SetBinError(b + 1, sqrt(errors[b]))

            contents = [0] * histo_ml_2.GetNbinsX()
            errors = [0] * histo_ml_2.GetNbinsX()

            for ml_bin, std_bins in map_std_bins:
                for b in std_bins:
                    contents[
                        ml_bin -
                        1] += histo_std_tmp_2.GetBinContent(b) / len(std_bins)
                    errors[ml_bin-1] += \
                            histo_std_tmp_2.GetBinError(b) * histo_std_tmp_2.GetBinError(b)

            for b in range(histo_std_2.GetNbinsX()):
                histo_std_2.SetBinContent(b + 1, contents[b])
                histo_std_2.SetBinError(b + 1, sqrt(errors[b]))

        else:
            histo_std_1 = histo_std_tmp_1.Clone("std_cloned_1")
            histo_std_2 = histo_std_tmp_2.Clone("std_cloned_2")

        if scale_std_1 is not None:
            histo_std_1.Scale(scale_std_1)
        if scale_std_2 is not None:
            histo_std_2.Scale(scale_std_2)

        histo_ratio_ml = histo_ml_1.Clone("{histo_ml_1.GetName()}_ratio")
        histo_ratio_ml.Divide(histo_ml_2)
        histo_ratio_std = histo_std_1.Clone("{histo_std_1.GetName()}_ratio")
        histo_ratio_std.Divide(histo_std_2)

        folder_plots = data_param_1[case_ml_1]["analysis"]["dir_general_plots"]
        if not os.path.exists(folder_plots):
            print("creating folder ", folder_plots)
            os.makedirs(folder_plots)

        save_path = f"{folder_plots}/ratio_{case_ml_1}_{case_ml_2}_{hn_ml}_ml_std_mult_" \
                    f"{mult_bin}_period_{period_number}{suffix}.eps"

        plot_histograms([histo_ratio_std, histo_ratio_ml], True, True,
                        ["STD", "ML"], "Ratio", "#it{p}_{T} (GeV/#it{c}",
                        f"{name_1} / {name_2}", "ML / STD", save_path)

        folder_plots = data_param_2[case_ml_2]["analysis"]["dir_general_plots"]
        if not os.path.exists(folder_plots):
            print("creating folder ", folder_plots)
            os.makedirs(folder_plots)

        save_path = f"{folder_plots}/ratio_{case_ml_1}_{case_ml_2}_{hn_ml}_ml_std_mult_" \
                    f"{mult_bin}_period_{period_number}{suffix}.eps"

        plot_histograms([histo_ratio_std, histo_ratio_ml], True, True,
                        ["STD", "ML"], "Ratio", "#it{p}_{T} (GeV/#it{c}",
                        f"{name_1} / {name_2}", "ML / STD", save_path)
示例#3
0
def plot_hfspectrum_years_ratios(case_1, case_2, ana_type, mult_bins=None):

    with open("data/database_ml_parameters_%s.yml" % case_1,
              'r') as param_config:
        data_param_1 = yaml.load(param_config, Loader=yaml.FullLoader)

    with open("data/database_ml_parameters_%s.yml" % case_2,
              'r') as param_config:
        data_param_2 = yaml.load(param_config, Loader=yaml.FullLoader)

    folder_plots_1 = data_param_1[case_1]["analysis"]["dir_general_plots"]
    folder_plots_2 = data_param_2[case_2]["analysis"]["dir_general_plots"]
    folder_plots_1 = folder_plots_1 + "/comp_years"
    folder_plots_2 = folder_plots_2 + "/comp_years"
    if not os.path.exists(folder_plots_1):
        print("creating folder ", folder_plots_1)
        os.makedirs(folder_plots_1)
    if not os.path.exists(folder_plots_2):
        print("creating folder ", folder_plots_2)
        os.makedirs(folder_plots_2)

    use_period = data_param_1[case_1]["analysis"][ana_type]["useperiod"]
    latexbin2var = data_param_1[case_1]["analysis"][ana_type]["latexbin2var"]
    result_paths_1 = [data_param_1[case_1]["analysis"][ana_type]["data"]["results"][i] \
            for i in range(len(use_period)) if use_period[i]]
    result_paths_1.insert(
        0, data_param_1[case_1]["analysis"][ana_type]["data"]["resultsallp"])

    result_paths_2 = [data_param_2[case_2]["analysis"][ana_type]["data"]["results"][i] \
            for i in range(len(use_period)) if use_period[i]]
    result_paths_2.insert(
        0, data_param_2[case_2]["analysis"][ana_type]["data"]["resultsallp"])

    # Assume same in all particle cases
    periods = [data_param_1[case_1]["multi"]["data"]["period"][i] \
            for i in range(len(use_period)) if use_period[i]]
    periods.insert(0, "merged")

    binsmin = data_param_1[case_1]["analysis"][ana_type]["sel_binmin2"]
    binsmax = data_param_1[case_1]["analysis"][ana_type]["sel_binmax2"]

    name_1 = data_param_1[case_1]["analysis"][ana_type]["latexnamemeson"]
    name_2 = data_param_2[case_2]["analysis"][ana_type]["latexnamemeson"]

    #br_1 = data_param_1[case_1]["ml"]["opt"]["BR"]
    #br_2 = data_param_2[case_2]["ml"]["opt"]["BR"]
    #sigmav0_1 = data_param_1[case_1]["analysis"]["sigmav0"]
    #sigmav0_2 = data_param_2[case_2]["analysis"]["sigmav0"]

    if mult_bins is None:
        mult_bins = range(len(binsmin))
    files_mult_1 = []
    files_mult_2 = []
    periods_string = "_".join(periods)
    for imult in mult_bins:
        files_years_1 = []
        files_years_2 = []
        for folder_1, folder_2 in zip(result_paths_1, result_paths_2):
            path_1 = f"{folder_1}/finalcross{case_1}{ana_type}mult{imult}.root"
            path_2 = f"{folder_2}/finalcross{case_2}{ana_type}mult{imult}.root"
            if not os.path.exists(path_1) or not os.path.exists(path_2):
                FILES_NOT_FOUND.append(f"{path_1} or {path_2}")
                continue
            files_years_1.append(path_1)
            files_years_2.append(path_2)

        files_mult_1.append(files_years_1)
        files_mult_2.append(files_years_2)

        histos = []
        legend_titles = []
        for period, path_1, path_2 in zip(periods, files_years_1,
                                          files_years_2):
            file_1 = TFile.Open(path_1, "READ")
            file_2 = TFile.Open(path_2, "READ")
            hyield_1 = file_1.Get("histoSigmaCorr")
            hyield_1.SetDirectory(0)
            hyield_2 = file_2.Get("histoSigmaCorr")
            hyield_2.SetDirectory(0)
            #hyield_1.Scale(1./(br_1 * sigmav0_1 * 1e12))
            #hyield_2.Scale(1./(br_2 * sigmav0_2 * 1e12))
            hyield_ratio = hyield_1.Clone(
                f"{case_1}_{case_2}_ratio_{period}_{imult}")
            hyield_ratio.Divide(hyield_2)
            histos.append(hyield_ratio)

            l_string = f"{binsmin[imult]:.1f} #leq {latexbin2var} < {binsmax[imult]:.1f} "\
                       f"({ana_type}), {period}"
            legend_titles.append(l_string)

        if not histos:
            continue

        sub_folder = os.path.join(folder_plots_1, "ratios", ana_type)
        if not os.path.exists(sub_folder):
            os.makedirs(sub_folder)

        save_path = f"{sub_folder}/{histos[0].GetName()}_combined_{periods_string}_{imult}.eps"
        y_label = f"{histos[0].GetYaxis().GetTitle()} {name_1} / {name_2}"

        plot_histograms(histos, True, True, legend_titles,
                        histos[0].GetTitle(), "#it{p}_{T} (GeV/#it{c})",
                        y_label, "year / merged", save_path)
def results(histos_central, systematics, title, legend_titles, x_label,
            y_label, save_path, ratio, **kwargs):

    if len(histos_central) != len(systematics):
        print(f"Number of systematics {len(systematics)} differs from number of " \
              f"histograms {len(histos_central)}")
        return

    if len(histos_central) != len(legend_titles):
        print(f"Number of legend titles {len(legend_titles)} differs from number of " \
              f"histograms {len(histos_central)}")
        return

    colors = kwargs.get("colors",
                        [kRed - i for i in range(len(histos_central))])
    if len(histos_central) != len(colors):
        print(f"Number of colors {len(colors)} differs from number of " \
              f"histograms {len(histos_central)}")
        return

    colors = colors * 2
    markerstyles = [1] * len(histos_central) + [20] * len(histos_central)
    draw_options = ["E2"] * len(histos_central) + [""] * len(histos_central)
    legend_titles = [None] * len(histos_central) + legend_titles

    if ratio is False:
        plot_histograms([*systematics, *histos_central],
                        True, [False, False, [1e-8, 1]],
                        legend_titles,
                        title,
                        x_label,
                        y_label,
                        "",
                        save_path,
                        linesytles=[1],
                        markerstyles=markerstyles,
                        colors=colors,
                        linewidths=[1],
                        draw_options=draw_options,
                        fillstyles=[0])
    elif ratio is True:
        plot_histograms([*systematics, *histos_central],
                        True, [False, True, [0.01, 100]],
                        legend_titles,
                        title,
                        x_label,
                        y_label,
                        "",
                        save_path,
                        linesytles=[1],
                        markerstyles=markerstyles,
                        colors=colors,
                        linewidths=[1],
                        draw_options=draw_options,
                        fillstyles=[0])
    else:
        plot_histograms([*systematics, *histos_central],
                        False, [False, True, [0, 0.3]],
                        legend_titles,
                        title,
                        x_label,
                        y_label,
                        "",
                        save_path,
                        linesytles=[1],
                        markerstyles=markerstyles,
                        colors=colors,
                        linewidths=[1],
                        draw_options=draw_options,
                        fillstyles=[0])
示例#5
0
                    comment = "(empty)"
                l_string = f"{binsmin[imult]:.1f} #leq {latexbin2var} < {binsmax[imult]:.1f} "\
                           f"({ana_type}), {period} {comment}"
                legend_titles.append(l_string)

            if not histos:
                continue

            sub_folder = os.path.join(folder_plots, ana_type)
            if not os.path.exists(sub_folder):
                os.makedirs(sub_folder)
            save_path = f"{sub_folder}/{hn}_combined_{periods_string}_{imult}.eps"

            label_y = f"{histos[0].GetYaxis().GetTitle()} {name}"
            plot_histograms(histos, True, True, legend_titles,
                            histos[0].GetTitle(), "#it{p}_{T} (GeV/#it{c})",
                            label_y, "year / merged", save_path)


#####################################

gROOT.SetBatch(True)

plot_hfspectrum_years("LcpK0spp", "MBvspt_ntrkl")
#plot_hfspectrum_years("LcpK0spp", "MBvspt_v0m")
plot_hfspectrum_years("LcpK0spp", "MBvspt_perc")
#plot_hfspectrum_years("LcpK0spp", "V0mvspt")
#plot_hfspectrum_years("LcpK0spp", "V0mvspt_perc_v0m")
plot_hfspectrum_years("LcpK0spp", "SPDvspt")

plot_hfspectrum_years("D0pp", "MBvspt_ntrkl")