jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def make_click_precedence_effect_plot(regex=None):
    if regex is None:
        regex = ("/om2/user/francl/grp-om2/gahlm/dataset_pipeline_test/"
                 "arch_number_*init_0/batch_conditional_precedenceEffectRecords"
                 "_45DegOffset_jitteredStart_jitteredPt5msDelay_expanded_stackedCH*iter100000*")
        pd_dataframe_precedence = make_dataframe(regex,fold_data=True)
        pd_dataframe_precedence = format_click_precedence_effect_dataframe(pd_dataframe_precedence)
        pd_filtered_precedence = pd_dataframe_precedence[(pd_dataframe_precedence['Lead Click Position'].isin([45])) & (pd_dataframe_precedence['Lead Click Level Difference (dB)'].isin([0]))].astype('int32')
        pd_filtered_precedence_arch_mean = pd_filtered_precedence.groupby(['arch_index','delay','Lead Click Level Difference (dB)']).mean().reset_index()
        plt.clf()
        plt.figure()
        sns.lineplot(x="delay",
                     y="predicted_folded",data=pd_filtered_precedence_arch_mean,
                     color='k',err_style='bars',ci=68,lw=1.0)
        format_precedence_effect_graph()
        plt.yticks([-40,-20,0,20,40])
        plt.xticks([0,10,20,30,40,50])
        plt.tight_layout()
        pd_filtered_precedence_arch_mean.to_csv(plots_folder+"/"+"precedence_effect_graph_lineplot_clicks.csv")
        plt.savefig(plots_folder+"/"+"precedence_effect_graph_lineplot_clicks.svg")
//  [python]
def make_zhong_yost_plots(pd_zhong_yost,prefix=""):
    plt.clf()
    pd_zhong_yost_arch_mean = pd_zhong_yost.groupby(["arch_index","num_sources"]).mean().reset_index()
    pd_zhong_yost_stats = pd_zhong_yost_arch_mean.groupby(["num_sources"]).agg([np.mean,'std','sem']).reset_index()
    x_axis = [x for x in range(1,9)]
    y_num_sources = pd_zhong_yost_stats['pred_num_sources']['mean'].tolist()
    y_std_num_sources = pd_zhong_yost_stats['pred_num_sources']['std'].tolist()
    y_prop_corr = pd_zhong_yost_stats['percent_correct_pred']['mean'].tolist()
    y_std_prop_corr = pd_zhong_yost_stats['percent_correct_pred']['std'].tolist()
    plt.plot(pd_zhong_yost_arch_mean["num_sources"],pd_zhong_yost_arch_mean["pred_num_sources"],color='k')
    plt.errorbar(x=x_axis,y=y_num_sources,yerr=y_std_num_sources,lw=0,elinewidth=1,capsize=0,ecolor='k')
    plt.plot([0, 8], [0, 8],ls="--",color='k',lw=0.5)
    plt.xticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    plt.yticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    for i in range(0,10):
        plt.axhline(i,color='k',alpha=0.5)
    plt.ylim(0,8)
    plt.xlim(0,8.5)
    plt.ylabel("Reported Number of Sources",fontsize=10)
    plt.xlabel("Actual Number of Sources",fontsize=10)
    pd_zhong_yost_stats.to_csv(plots_folder+"/"+prefix+"num_sources_vs_pred_num_sources_zhong_yost.csv")
    plt.savefig(plots_folder+"/"+prefix+"num_sources_vs_pred_num_sources_zhong_yost.svg")
    plt.clf()
    plt.plot(pd_zhong_yost_arch_mean["num_sources"],pd_zhong_yost_arch_mean["percent_correct_pred"],color='k')
    plt.errorbar(x=x_axis,y=y_prop_corr,yerr=y_std_prop_corr,lw=0,elinewidth=1,capsize=0,ecolor='k')
    plt.xticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    plt.yticks([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0],fontsize=10)
    for i in [x/10.0 for x in range(0,10)]:
        plt.axhline(i,color='k',alpha=0.5)
    plt.ylim(0,1.0)
    plt.xlim(0,8.5)
    plt.ylabel("Proportion of Correct Responses",fontsize=10)
    plt.xlabel("Actual Number of Sources",fontsize=10)
    pd_zhong_yost_arch_mean.to_csv(plots_folder+"/"+prefix+"num_sources_vs_percent_correct_pred_zhong_yost.csv")
    plt.savefig(plots_folder+"/"+prefix+"num_sources_vs_percent_correct_pred_zhong_yost.svg")
//  [python]
def make_zhong_yost_plots(pd_zhong_yost,prefix=""):
    plt.clf()
    pd_zhong_yost_arch_mean = pd_zhong_yost.groupby(["arch_index","num_sources"]).mean().reset_index()
    pd_zhong_yost_stats = pd_zhong_yost_arch_mean.groupby(["num_sources"]).agg([np.mean,'std','sem']).reset_index()
    x_axis = [x for x in range(1,9)]
    y_num_sources = pd_zhong_yost_stats['pred_num_sources']['mean'].tolist()
    y_std_num_sources = pd_zhong_yost_stats['pred_num_sources']['std'].tolist()
    y_prop_corr = pd_zhong_yost_stats['percent_correct_pred']['mean'].tolist()
    y_std_prop_corr = pd_zhong_yost_stats['percent_correct_pred']['std'].tolist()
    sns.lineplot(data=pd_zhong_yost_arch_mean,x="num_sources",y="pred_num_sources",ci=None,color='k')
    plt.errorbar(x=x_axis,y=y_num_sources,yerr=y_std_num_sources,lw=0,elinewidth=1,capsize=0,ecolor='k')
    plt.plot([0, 8], [0, 8],ls="--",color='k',lw=0.5)
    plt.xticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    plt.yticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    for i in range(0,10):
        plt.axhline(i,color='k',alpha=0.5)
    plt.ylim(0,8)
    plt.xlim(0,8.5)
    plt.ylabel("Reported Number of Sources",fontsize=10)
    plt.xlabel("Actual Number of Sources",fontsize=10)
    pd_zhong_yost_stats.to_csv(plots_folder+"/"+prefix+"num_sources_vs_pred_num_sources_zhong_yost.csv")
    plt.savefig(plots_folder+"/"+prefix+"num_sources_vs_pred_num_sources_zhong_yost.svg")
    plt.clf()
    sns.lineplot(data=pd_zhong_yost_arch_mean,x="num_sources",y="percent_correct_pred",ci=None,color='k')
    plt.errorbar(x=x_axis,y=y_prop_corr,yerr=y_std_prop_corr,lw=0,elinewidth=1,capsize=0,ecolor='k')
    plt.xticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    plt.yticks([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0],fontsize=10)
    for i in [x/10.0 for x in range(0,10)]:
        plt.axhline(i,color='k',alpha=0.5)
    plt.ylim(0,1.0)
    plt.xlim(0,8.5)
    plt.ylabel("Proportion of Correct Responses",fontsize=10)
    plt.xlabel("Actual Number of Sources",fontsize=10)
    pd_zhong_yost_arch_mean.to_csv(plots_folder+"/"+prefix+"num_sources_vs_percent_correct_pred_zhong_yost.csv")
    plt.savefig(plots_folder+"/"+prefix+"num_sources_vs_percent_correct_pred_zhong_yost.svg")
//  [python]
def make_zhong_yost_human_plots():
    pd_num_sources,pd_pred_locs = get_zhong_yost_human_data()
    plt.clf()
    pd_num_sources_line = pd_num_sources.loc[:,"Num Sources"]
    pd_num_sources_top = pd_num_sources.loc[:,"Top Error Bar"]
    pd_num_sources_bottom = pd_num_sources.loc[:,"Bottom Error Bar"]
    pd_pred_locs_line = pd_pred_locs.loc[:,"Correct Responses"]
    pd_pred_locs_top = pd_pred_locs.loc[:,"Top Error Bar"]
    pd_pred_locs_bottom = pd_pred_locs.loc[:,"Bottom Error Bar"]
    errorbar_vector_num_sources =np.array([abs(pd_num_sources_top["Y"]-pd_num_sources_line["Y"]),
                                  abs(pd_num_sources_bottom["Y"]-pd_num_sources_line["Y"])])
    errorbar_vector_pred_locs =np.array([abs(pd_pred_locs_top["Y"]-pd_pred_locs_line["Y"]),
                                  abs(pd_pred_locs_bottom["Y"]-pd_pred_locs_line["Y"])])
    plt.plot(pd_num_sources_line["X"],pd_num_sources_line["Y"],color='k')
    plt.errorbar(x=pd_num_sources_line["X"],y=pd_num_sources_line["Y"],yerr=errorbar_vector_num_sources,
                 lw=0,elinewidth=1,capsize=0,ecolor='k')
    plt.plot([0, 8], [0, 8],ls="--",color='k',lw=0.5)
    plt.xticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    plt.yticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    for i in range(0,10):
        plt.axhline(i,color='k',alpha=0.5)
    plt.ylim(0,8)
    plt.xlim(0,8.5)
    plt.ylabel("Reported Number of Sources",fontsize=10)
    plt.xlabel("Actual Number of Sources",fontsize=10)
    plt.savefig(plots_folder+"/zhong_yost_num_sources_human_results.svg")
    plt.clf()
    plt.plot(pd_pred_locs_line["X"],pd_pred_locs_line["Y"],color='k')
    plt.errorbar(x=pd_pred_locs_line["X"],y=pd_pred_locs_line["Y"],yerr=errorbar_vector_pred_locs,
                 lw=0,elinewidth=1,capsize=0,ecolor='k')
    plt.xticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    plt.yticks([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0],fontsize=10)
    for i in [x/10.0 for x in range(0,10)]:
        plt.axhline(i,color='k',alpha=0.5)
    plt.ylim(0,1.0)
    plt.xlim(0,8.5)
    plt.ylabel("Proportion of Correct Responses",fontsize=10)
    plt.xlabel("Actual Number of Sources",fontsize=10)
    plt.savefig(plots_folder+"/zhong_yost_correct_pred_locs_human_results.svg")
//  [python]
def make_zhong_yost_human_plots():
    pd_num_sources,pd_pred_locs = get_zhong_yost_human_data()
    plt.clf()
    pd_num_sources_line = pd_num_sources.loc[:,"Num Sources"]
    pd_num_sources_top = pd_num_sources.loc[:,"Top Error Bar"]
    pd_num_sources_bottom = pd_num_sources.loc[:,"Bottom Error Bar"]
    pd_pred_locs_line = pd_pred_locs.loc[:,"Correct Responses"]
    pd_pred_locs_top = pd_pred_locs.loc[:,"Top Error Bar"]
    pd_pred_locs_bottom = pd_pred_locs.loc[:,"Bottom Error Bar"]
    errorbar_vector_num_sources =np.array([abs(pd_num_sources_top["Y"]-pd_num_sources_line["Y"]),
                                  abs(pd_num_sources_bottom["Y"]-pd_num_sources_line["Y"])])
    errorbar_vector_pred_locs =np.array([abs(pd_pred_locs_top["Y"]-pd_pred_locs_line["Y"]),
                                  abs(pd_pred_locs_bottom["Y"]-pd_pred_locs_line["Y"])])
    sns.lineplot(data=pd_num_sources_line,x="X",y="Y",ci=None,color='k')
    plt.errorbar(x=pd_num_sources_line["X"],y=pd_num_sources_line["Y"],yerr=errorbar_vector_num_sources,
                 lw=0,elinewidth=1,capsize=0,ecolor='k')
    plt.plot([0, 8], [0, 8],ls="--",color='k',lw=0.5)
    plt.xticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    plt.yticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    for i in range(0,10):
        plt.axhline(i,color='k',alpha=0.5)
    plt.ylim(0,8)
    plt.xlim(0,8.5)
    plt.ylabel("Reported Number of Sources",fontsize=10)
    plt.xlabel("Actual Number of Sources",fontsize=10)
    plt.savefig(plots_folder+"/zhong_yost_num_sources_human_results.svg")
    plt.clf()
    sns.lineplot(data=pd_pred_locs_line,x="X",y="Y",ci=None,color='k')
    plt.errorbar(x=pd_pred_locs_line["X"],y=pd_pred_locs_line["Y"],yerr=errorbar_vector_pred_locs,
                 lw=0,elinewidth=1,capsize=0,ecolor='k')
    plt.xticks([0,1,2,3,4,5,6,7,8],fontsize=10)
    plt.yticks([0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0],fontsize=10)
    for i in [x/10.0 for x in range(0,10)]:
        plt.axhline(i,color='k',alpha=0.5)
    plt.ylim(0,1.0)
    plt.xlim(0,8.5)
    plt.ylabel("Proportion of Correct Responses",fontsize=10)
    plt.xlabel("Actual Number of Sources",fontsize=10)
    plt.savefig(plots_folder+"/zhong_yost_correct_pred_locs_human_results.svg")
//  [python]
def make_precedence_effect_plot_networks(regex=None,filter_lead_pos_list=[-45]):
    if regex is None:
       regex = ("/om2/user/francl/grp-om2/gahlm/dataset_pipeline_test/"
                "arch_number_*init_0/batch_conditional_*precedence*"
                "45Deg0DegOffset*pinknoise*5degStep*iter100000*")
    pd_dataframe_precedence = make_dataframe(regex,fold_data=True)
    pdb.set_trace()
    pd_dataframe_precedence = format_precedence_effect_dataframe(pd_dataframe_precedence)
    pd_filtered_precedence = pd_dataframe_precedence[(pd_dataframe_precedence['Lead Click Position'].isin(filter_lead_pos_list)) &\
                            (pd_dataframe_precedence['Lead Click Level Difference (dB)'].isin([0]))].astype('int32')
    pd_filtered_precedence_arch_mean = pd_filtered_precedence.groupby(['arch_index','delay','Lead Click Level Difference (dB)'])\
    .mean().reset_index()
    plt.clf()
    sns.pointplot(x="delay",y="predicted_folded",data=pd_filtered_precedence_arch_mean,ci=68)
    format_precedence_effect_graph()
    return pd_filtered_precedence_arch_mean
//  [python]
def make_precedence_effect_plot_networks(regex=None,filter_lead_pos_list=[-45]):
    if regex is None:
       regex = ("/om2/user/francl/grp-om2/gahlm/dataset_pipeline_test/"
                "arch_number_*init_0/batch_conditional_*precedence*"
                "45Deg0DegOffset*pinknoise*5degStep*iter100000*")
    pd_dataframe_precedence = make_dataframe(regex,fold_data=True)
    pdb.set_trace()
    pd_dataframe_precedence = format_precedence_effect_dataframe(pd_dataframe_precedence)
    pd_filtered_precedence = pd_dataframe_precedence[(pd_dataframe_precedence['Lead Click Position'].isin(filter_lead_pos_list)) &\
                            (pd_dataframe_precedence['Lead Click Level Difference (dB)'].isin([0]))].astype('int32')
    pd_filtered_precedence_arch_mean = pd_filtered_precedence.groupby(['arch_index','delay','Lead Click Level Difference (dB)'])\
    .mean().reset_index()
    plt.clf()
    sns.lineplot(x="delay",y="predicted_folded",data=pd_filtered_precedence_arch_mean,err_style='bars',ci=68)
    format_precedence_effect_graph()
    return pd_filtered_precedence_arch_mean
//  [python]
def make_kulkarni_network_prediction_plots(regex=None):
    if regex is None:
        regex = ("/om2/user/francl/grp-om2/gahlm/dataset_pipeline_test/arch_number_*_init_0"
                 "/batch_conditional_broadbandNoiseRecords_convolved_smooth*"
                 "HRIR_direct_stackedCH_upsampled_iter100000.npy")
    np_data_array_dictionary_smoothed_hrtf = make_dataframe(regex,fold_data=False,elevation_predictions=True)
    pd_dataframe_smoothed_hrtf_filtered = get_error_smoothed_hrtf(np_data_array_dictionary_smoothed_hrtf)
    model_order = np.sort(pd_dataframe_smoothed_hrtf_filtered["smooth_factor"].unique())[::-1] 
    pd_smoothed_arch_mean = pd_dataframe_smoothed_hrtf_filtered.groupby(["azim","elev","smooth_factor","arch_index"]).mean().reset_index()
    plt.clf()
    sns.tsplot(x="azim",y="predicted_azim",hue="smooth_factor",
                 data=pd_smoothed_arch_mean[pd_smoothed_arch_mean['elev'].isin([0])],ci=68,
                 hue_order=model_order,legend='full',palette=sns.color_palette("colorblind",n_colors=9))
    plt.xticks([-75,-50,-25,0,25,50,75],fontsize=10,rotation=75)
    plt.yticks([-75,-50,-25,0,25,50,75],fontsize=10)
    plt.ylabel("Judged Azim",fontsize=10)
    plt.xlabel("Azim",fontsize=10)
    plt.savefig(plots_folder+"/azim_vs_predicted_by_smooth_factor_with_legend.png",dpi=400)
    
    plt.tight_layout()
    plt.gca().get_legend().remove()
    plt.savefig(plots_folder+"/azim_vs_predicted_by_smooth_factor.svg")
    plt.clf()
    sns.tsplot(x="elev",y="predicted_elev",hue="smooth_factor",
                 data=pd_smoothed_arch_mean,legend=False,ci=68,
                 hue_order=model_order,palette=sns.color_palette("colorblind",n_colors=9))
    plt.xticks([0,10,20,30,40,50,60],fontsize=10,rotation=75)
    plt.yticks([0,10,20,30,40,50,60],fontsize=10)
    plt.ylabel("Judged Elev",fontsize=10)
    plt.xlabel("Elev",fontsize=10)
    plt.tight_layout()
    pd_smoothed_arch_mean.to_csv(plots_folder+"/elev_vs_predicted_by_smooth_factor.csv")
    plt.savefig(plots_folder+"/elev_vs_predicted_by_smooth_factor.svg")
//  [python]
def make_kulkarni_network_prediction_plots(regex=None):
    if regex is None:
        regex = ("/om2/user/francl/grp-om2/gahlm/dataset_pipeline_test/arch_number_*_init_0"
                 "/batch_conditional_broadbandNoiseRecords_convolved_smooth*"
                 "HRIR_direct_stackedCH_upsampled_iter100000.npy")
    np_data_array_dictionary_smoothed_hrtf = make_dataframe(regex,fold_data=False,elevation_predictions=True)
    pd_dataframe_smoothed_hrtf_filtered = get_error_smoothed_hrtf(np_data_array_dictionary_smoothed_hrtf)
    model_order = np.sort(pd_dataframe_smoothed_hrtf_filtered["smooth_factor"].unique())[::-1] 
    pd_smoothed_arch_mean = pd_dataframe_smoothed_hrtf_filtered.groupby(["azim","elev","smooth_factor","arch_index"]).mean().reset_index()
    plt.clf()
    sns.lineplot(x="azim",y="predicted_azim",hue="smooth_factor",
                 data=pd_smoothed_arch_mean[pd_smoothed_arch_mean['elev'].isin([0])],ci=68,
                 hue_order=model_order,legend='full',palette=sns.color_palette("colorblind",n_colors=9))
    plt.xticks([-75,-50,-25,0,25,50,75],fontsize=10,rotation=75)
    plt.yticks([-75,-50,-25,0,25,50,75],fontsize=10)
    plt.ylabel("Judged Azim",fontsize=10)
    plt.xlabel("Azim",fontsize=10)
    plt.savefig(plots_folder+"/azim_vs_predicted_by_smooth_factor_with_legend.png",dpi=400)
    
    plt.tight_layout()
    plt.gca().get_legend().remove()
    plt.savefig(plots_folder+"/azim_vs_predicted_by_smooth_factor.svg")
    plt.clf()
    sns.lineplot(x="elev",y="predicted_elev",hue="smooth_factor",
                 data=pd_smoothed_arch_mean,legend=False,ci=68,
                 hue_order=model_order,palette=sns.color_palette("colorblind",n_colors=9))
    plt.xticks([0,10,20,30,40,50,60],fontsize=10,rotation=75)
    plt.yticks([0,10,20,30,40,50,60],fontsize=10)
    plt.ylabel("Judged Elev",fontsize=10)
    plt.xlabel("Elev",fontsize=10)
    plt.tight_layout()
    pd_smoothed_arch_mean.to_csv(plots_folder+"/elev_vs_predicted_by_smooth_factor.csv")
    plt.savefig(plots_folder+"/elev_vs_predicted_by_smooth_factor.svg")
//  [python]
def make_van_opstal_human_plots():
    pd_van_opstal_human = pd.read_pickle("/om/user/francl/pd_van_opstal_human_data_extracted.pkl")
    df_x,df_y = collapse_van_opstal_data_human(pd_van_opstal_human)
    df_x = format_van_opstal_human_dataframes(df_x)  
    df_y = format_van_opstal_human_dataframes(df_y)  
    plt.clf()
    sns.pointplot(x='Azimuth (Degrees)',y='Judged Azimuth (Degrees)',hue="Ears Used",
                join=True,ci=None,scale=1,lw=4,ms=10,
                data=df_x.query('Reference == False'),palette=reversed(sns.color_palette
                                                                      (n_colors=2)))
    format_van_opstal_azim()
    plt.savefig(plots_folder+"/"+"van_opstal_human_data_azimuth_before_after_pointplot_individual_subjects.png")
    plt.clf()
    sns.pointplot(x='Elevation (Degrees)',y='Judged Elevation (Degrees)',hue="Ears Used",
                join=True,ci=None,scale=1,lw=4,ms=10,
                data=df_x.query('Reference == False'),palette=reversed(sns.color_palette
                                                                      (n_colors=2)))
    format_van_opstal_elevation()
    plt.savefig(plots_folder+"/"+"van_opstal_human_data_elevation_before_after_pointplot_individual_subjects.png")
//  [python]
def make_van_opstal_human_plots():
    pd_van_opstal_human = pd.read_pickle("/om/user/francl/pd_van_opstal_human_data_extracted.pkl")
    df_x,df_y = collapse_van_opstal_data_human(pd_van_opstal_human)
    df_x = format_van_opstal_human_dataframes(df_x)  
    df_y = format_van_opstal_human_dataframes(df_y)  
    plt.clf()
    sns.lineplot(x='Azimuth (Degrees)',y='Judged Azimuth (Degrees)',hue="Ears Used",
                units="Condition",estimator=None, lw=4,ms=10,
                data=df_x.query('Reference == False'),style="Ears Used",
                markers=["o","o"],dashes=False,palette=reversed(sns.color_palette
                                                                      (n_colors=2)))
    format_van_opstal_azim()
    plt.savefig(plots_folder+"/"+"van_opstal_human_data_azimuth_before_after_pointplot_individual_subjects.png")
    plt.clf()
    sns.lineplot(x='Elevation (Degrees)',y='Judged Elevation (Degrees)',hue="Ears Used",
                estimator=None, lw=4,ms=10,
                data=df_x.query('Reference == False'),style="Ears Used",
                markers=["o","o"],dashes=False,palette=reversed(sns.color_palette
                                                                      (n_colors=2)))
    format_van_opstal_elevation()
    plt.savefig(plots_folder+"/"+"van_opstal_human_data_elevation_before_after_pointplot_individual_subjects.png")
//  [python]
def plot_losses(
    log_fname: str,
    out_fname: Optional[str] = None,
    simple: bool = False,
    pattern: Optional[str] = None,
):
    """
    Plot the validation loss values from a log file. Spuports multiple
    validation losses if present in log file. Plots per epoch, and if multiple
    values are record for an epoch, plot the median.
    """

    def keyfunc(x: str) -> tuple:
        """
        Validation first, then train
        """
        ordering = ["test", "val", "train"]
        if "_" in x:
            x_split, x_val = x.split("_", maxsplit=1)
            x_retval = tuple([ordering.index(x_split), x_val])
        else:
            x_retval = (len(ordering), x)
        assert len(x_retval) == 2
        return x_retval

    if simple:
        assert pattern is None
        pattern = re.compile(r"_loss$")
    if isinstance(pattern, str):
        pattern = re.compile(pattern)

    fig, ax = plt.subplots(dpi=300)

    df = pd.read_csv(log_fname)
    cols = df.columns.to_list()
    cols = sorted(cols, key=keyfunc)
    for colname in df.columns:
        if "loss" not in colname:
            continue
        if pattern is not None:
            if not pattern.search(colname):
                continue
        vals = df.loc[:, ["epoch", colname]]
        vals.dropna(axis="index", how="any", inplace=True)
        plt.plot(vals["epoch"], vals[colname], label=colname, alpha=0.5)
    ax.legend(loc="upper right")
    ax.set(xlabel="Epoch", ylabel="Loss", title="Loss over epochs")

    if out_fname is not None:
        fig.savefig(out_fname, bbox_inches="tight")
    return fig
//  [python]
def plot_losses(
    log_fname: str,
    out_fname: Optional[str] = None,
    simple: bool = False,
    pattern: Optional[str] = None,
):
    """
    Plot the validation loss values from a log file. Spuports multiple
    validation losses if present in log file. Plots per epoch, and if multiple
    values are record for an epoch, plot the median.
    """

    def keyfunc(x: str) -> tuple:
        """
        Validation first, then train
        """
        ordering = ["test", "val", "train"]
        if "_" in x:
            x_split, x_val = x.split("_", maxsplit=1)
            x_retval = tuple([ordering.index(x_split), x_val])
        else:
            x_retval = (len(ordering), x)
        assert len(x_retval) == 2
        return x_retval

    if simple:
        assert pattern is None
        pattern = re.compile(r"_loss$")
    if isinstance(pattern, str):
        pattern = re.compile(pattern)

    fig, ax = plt.subplots(dpi=300)

    df = pd.read_csv(log_fname)
    cols = df.columns.to_list()
    cols = sorted(cols, key=keyfunc)
    for colname in df.columns:
        if "loss" not in colname:
            continue
        if pattern is not None:
            if not pattern.search(colname):
                continue
        vals = df.loc[:, ["epoch", colname]]
        vals.dropna(axis="index", how="any", inplace=True)
        sns.lineplot(x="epoch", y=colname, data=vals, ax=ax, label=colname, alpha=0.5)
    ax.legend(loc="upper right")
    ax.set(xlabel="Epoch", ylabel="Loss", title="Loss over epochs")

    if out_fname is not None:
        fig.savefig(out_fname, bbox_inches="tight")
    return fig
//  [python]
def lineplot_message_length(msgs, your_name, target_name, path_to_save):
    sns.set(style="whitegrid")

    (x, y_total), (xticks, xticks_labels, xlabel) = _get_plot_data(msgs), _get_xticks(msgs)

    y_your = [avg([len(msg.text) for msg in period if msg.author == your_name]) for period in y_total]
    y_target = [avg([len(msg.text) for msg in period if msg.author == target_name]) for period in y_total]

    plt.fill_between(x, y_your, alpha=0.3)
    ax = plt.plot(x, y_your, color="denim blue", linewidth=2.5, label=your_name)
    plt.fill_between(x, y_target, alpha=0.3)
    plt.plot(x, y_target, linewidth=2.5, label=target_name)

    ax = plt.gca()
    ax.set(xlabel=xlabel, ylabel="average message length (characters)")
    ax.set_xticklabels(xticks_labels)

    ax.tick_params(axis='x', bottom=True, color="#A9A9A9")
    plt.xticks(xticks, rotation=65)
    ax.margins(x=0, y=0)

    # plt.tight_layout()
    fig = plt.gcf()
    fig.set_size_inches(13, 7)

    fig.savefig(os.path.join(path_to_save, lineplot_message_length.__name__ + ".png"), dpi=500)
    # plt.show()
    plt.close("all")
    log_line(f"{lineplot_message_length.__name__} was created.")
//  [python]
def lineplot_message_length(msgs, your_name, target_name, path_to_save):
    sns.set(style="whitegrid")

    (x, y_total), (xticks, xticks_labels, xlabel) = _get_plot_data(msgs), _get_xticks(msgs)

    y_your = [avg([len(msg.text) for msg in period if msg.author == your_name]) for period in y_total]
    y_target = [avg([len(msg.text) for msg in period if msg.author == target_name]) for period in y_total]

    plt.fill_between(x, y_your, alpha=0.3)
    ax = sns.lineplot(x=x, y=y_your, palette="denim blue", linewidth=2.5, label=your_name)
    plt.fill_between(x, y_target, alpha=0.3)
    sns.lineplot(x=x, y=y_target, linewidth=2.5, label=target_name)

    ax.set(xlabel=xlabel, ylabel="average message length (characters)")
    ax.set_xticklabels(xticks_labels)

    ax.tick_params(axis='x', bottom=True, color="#A9A9A9")
    plt.xticks(xticks, rotation=65)
    ax.margins(x=0, y=0)

    # plt.tight_layout()
    fig = plt.gcf()
    fig.set_size_inches(13, 7)

    fig.savefig(os.path.join(path_to_save, lineplot_message_length.__name__ + ".png"), dpi=500)
    # plt.show()
    plt.close("all")
    log_line(f"{lineplot_message_length.__name__} was created.")
//  [python]
def lineplot_messages(msgs, your_name, target_name, path_to_save):
    sns.set(style="whitegrid")

    (x, y_total), (xticks, xticks_labels, xlabel) = _get_plot_data(msgs), _get_xticks(msgs)

    y_your = [len([msg for msg in period if msg.author == your_name]) for period in y_total]
    y_target = [len([msg for msg in period if msg.author == target_name]) for period in y_total]

    plt.fill_between(x, y_your, alpha=0.3)
    ax = plt.plot(x, y_your, color="denim blue", linewidth=2.5, label=your_name)
    plt.fill_between(x, y_target, alpha=0.3)
    plt.plot(x, y_target, linewidth=2.5, label=target_name)

    ax = plt.gca()
    ax.set(xlabel=xlabel, ylabel="messages")
    ax.set_xticklabels(xticks_labels)

    ax.tick_params(axis='x', bottom=True, color="#A9A9A9")
    plt.xticks(xticks, rotation=65)
    ax.margins(x=0, y=0)

    # plt.tight_layout()
    fig = plt.gcf()
    fig.set_size_inches(13, 7)

    fig.savefig(os.path.join(path_to_save, lineplot_messages.__name__ + ".png"), dpi=500)
    # plt.show()
    plt.close("all")
    log_line(f"{lineplot_messages.__name__} was created.")
//  [python]
def lineplot_messages(msgs, your_name, target_name, path_to_save):
    sns.set(style="whitegrid")

    (x, y_total), (xticks, xticks_labels, xlabel) = _get_plot_data(msgs), _get_xticks(msgs)

    y_your = [len([msg for msg in period if msg.author == your_name]) for period in y_total]
    y_target = [len([msg for msg in period if msg.author == target_name]) for period in y_total]

    plt.fill_between(x, y_your, alpha=0.3)
    ax = sns.lineplot(x=x, y=y_your, palette="denim blue", linewidth=2.5, label=your_name)
    plt.fill_between(x, y_target, alpha=0.3)
    sns.lineplot(x=x, y=y_target, linewidth=2.5, label=target_name)

    ax.set(xlabel=xlabel, ylabel="messages")
    ax.set_xticklabels(xticks_labels)

    ax.tick_params(axis='x', bottom=True, color="#A9A9A9")
    plt.xticks(xticks, rotation=65)
    ax.margins(x=0, y=0)

    # plt.tight_layout()
    fig = plt.gcf()
    fig.set_size_inches(13, 7)

    fig.savefig(os.path.join(path_to_save, lineplot_messages.__name__ + ".png"), dpi=500)
    # plt.show()
    plt.close("all")
    log_line(f"{lineplot_messages.__name__} was created.")
//  [python]
def plot(dataframe_path):
    # DTU experiment plot
    save_path = os.path.dirname(dataframe_path)
    total_df = pandas.read_csv(dataframe_path)

    fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True)
    sb.pointplot(
        data=total_df,
        x="Reference Image Number",
        y="PSNR",
        hue="Planning Type",
        linewidth=PLOT_LINE_WIDTH,
        ax=ax1,
        ci="sd",
        palette=["C2", "C0", "C3"],
        join=True,
    )

    ax1.set_ylabel("PSNR", fontsize=PLOT_FONT_SIZE)
    ax1.set_xlabel("Number of collected images", fontsize=PLOT_FONT_SIZE)
    ax1.yaxis.set_major_formatter(FormatStrFormatter("%.1f"))
    ax1.yaxis.set_major_locator(MaxNLocator(nbins=4))
    ax1.tick_params(axis="both", labelsize=PLOT_TICKS_SIZE)

    handles, labels = ax1.get_legend_handles_labels()
    order = [2, 0, 1]
    ax1.legend(
        [handles[idx] for idx in order],
        [labels[idx] for idx in order],
        loc="lower right",
        fontsize=PLOT_LEGEND_SIZE,
        frameon=False,
    )

    sb.pointplot(
        data=total_df,
        x="Reference Image Number",
        y="SSIM",
        hue="Planning Type",
        linewidth=PLOT_LINE_WIDTH,
        ax=ax2,
        ci="sd",
        palette=["C2", "C0", "C3"],
        join=True,
    )
    ax2.set_xlabel("Number of collected images", fontsize=PLOT_FONT_SIZE)
    ax2.set_ylabel("SSIM", fontsize=PLOT_FONT_SIZE)
    ax2.yaxis.set_major_formatter(FormatStrFormatter("%.2f"))
    ax2.yaxis.set_major_locator(MaxNLocator(nbins=4))
    ax2.get_legend().remove()
    ax2.tick_params(axis="both", labelsize=PLOT_TICKS_SIZE)

    plt.xticks([2, 3, 4, 5, 6, 7, 8, 9])
    plt.savefig(f"{save_path}/plot_results.svg", bbox_inches="tight")
    plt.clf()
//  [python]
def plot(dataframe_path):
    # DTU experiment plot
    save_path = os.path.dirname(dataframe_path)
    total_df = pandas.read_csv(dataframe_path)

    fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True)
    sb.lineplot(
        total_df,
        x="Reference Image Number",
        y="PSNR",
        hue="Planning Type",
        linewidth=PLOT_LINE_WIDTH,
        ax=ax1,
        errorbar=("sd", 1),
        palette=["C2", "C0", "C3"],
    )

    ax1.set_ylabel("PSNR", fontsize=PLOT_FONT_SIZE)
    ax1.set_xlabel("Number of collected images", fontsize=PLOT_FONT_SIZE)
    ax1.yaxis.set_major_formatter(FormatStrFormatter("%.1f"))
    ax1.yaxis.set_major_locator(MaxNLocator(nbins=4))
    ax1.tick_params(axis="both", labelsize=PLOT_TICKS_SIZE)

    handles, labels = ax1.get_legend_handles_labels()
    order = [2, 0, 1]
    ax1.legend(
        [handles[idx] for idx in order],
        [labels[idx] for idx in order],
        loc="lower right",
        fontsize=PLOT_LEGEND_SIZE,
        frameon=False,
    )

    sb.lineplot(
        total_df,
        x="Reference Image Number",
        y="SSIM",
        hue="Planning Type",
        linewidth=PLOT_LINE_WIDTH,
        ax=ax2,
        errorbar=("sd", 1),
        palette=["C2", "C0", "C3"],
    )
    ax2.set_xlabel("Number of collected images", fontsize=PLOT_FONT_SIZE)
    ax2.set_ylabel("SSIM", fontsize=PLOT_FONT_SIZE)
    ax2.yaxis.set_major_formatter(FormatStrFormatter("%.2f"))
    ax2.yaxis.set_major_locator(MaxNLocator(nbins=4))
    ax2.get_legend().remove()
    ax2.tick_params(axis="both", labelsize=PLOT_TICKS_SIZE)

    plt.xticks([2, 3, 4, 5, 6, 7, 8, 9])
    plt.savefig(f"{save_path}/plot_results.svg", bbox_inches="tight")
    plt.clf()
//  [python]
def ablation2(backend):
  sep = f"<!--{backend}-->"
  raw = open("../../report.md").read().split(sep)
  data = parse_table2(raw[1])
  data = pd.DataFrame(data)
  print(data)
  g = sns.FacetGrid(
    data,
    col="Method",
    hue="Metric",
    height=3,
    aspect=1.6,
    sharex=False,
    sharey=False,
  )

  def mapping(x, y, y2, **kwargs):
    plot = sns.pointplot(x=x, y=y, **kwargs)
    sns.pointplot(x=x, y=y2, **kwargs)
    plot.xaxis.set_major_formatter(ticker.EngFormatter())

  g.map(
    mapping,
    "Problem Size",
    "Time per Op (ns)",
    "Cache Miss per Op",
    marker="o",
  )

  g.set_axis_labels("Problem Size", "TpO (ns) and CMpO")
  g.add_legend(bbox_to_anchor=(0.52, 1.02), ncol=7)

  g.savefig(f"{backend}0.png")
//  [python]
def ablation2(backend):
  sep = f"<!--{backend}-->"
  raw = open("../../report.md").read().split(sep)
  data = parse_table2(raw[1])
  data = pd.DataFrame(data)
  print(data)
  g = sns.FacetGrid(
    data,
    col="Method",
    hue="Metric",
    height=3,
    aspect=1.6,
    sharex=False,
    sharey=False,
  )

  def mapping(x, y, y2, **kwargs):
    plot = sns.lineplot(x=x, y=y, **kwargs)
    sns.lineplot(x=x, y=y2, **kwargs)
    plot.xaxis.set_major_formatter(ticker.EngFormatter())

  g.map(
    mapping,
    "Problem Size",
    "Time per Op (ns)",
    "Cache Miss per Op",
    marker="o",
  )

  g.set_axis_labels("Problem Size", "TpO (ns) and CMpO")
  g.add_legend(bbox_to_anchor=(0.52, 1.02), ncol=7)

  g.savefig(f"{backend}0.png")
//  [python]
def precision_reall_f1_report(precision, recall, thresholds, 
                              plot=True, 
                              figsize=(12,8),
                              font_scale=2,
                              linewidth=2):
    reports = pd.DataFrame()
    reports['precision'] = precision[0:-1]
    reports['recall'] = recall[0:-1]
    reports['threshold'] = thresholds
    reports['f1'] = 2 * reports['precision'] * reports['recall'] / (reports['precision'] + reports['recall'])
    
    results = []
    for i, row in reports.iterrows():
        for metric in ['precision', 'recall', 'f1']:
            results.append({'threshold': row['threshold'],
                            'metric': metric,
                            'value': row[metric]})
    
    df = pd.DataFrame(results)
    # Plot
    if plot:
        plt.figure(figsize=figsize)

        rc={'font.weight' : 'bold',
            'axes.linewidth' : linewidth,
            'axes.edgecolor' : 'k'}
        sns.set(style='whitegrid', font_scale=font_scale, rc=rc) 
        
        ax = sns.tsplot(data=df, time="threshold", value="value", unit="metric", 
                          condition='metric', linewidth=linewidth)
        ax.set_xlabel('threshold', fontweight='bold')
        ax.set_ylabel('value', fontweight='bold')
        
    return reports
//  [python]
def precision_reall_f1_report(precision, recall, thresholds, 
                              plot=True, 
                              figsize=(12,8),
                              font_scale=2,
                              linewidth=2):
    reports = pd.DataFrame()
    reports['precision'] = precision[0:-1]
    reports['recall'] = recall[0:-1]
    reports['threshold'] = thresholds
    reports['f1'] = 2 * reports['precision'] * reports['recall'] / (reports['precision'] + reports['recall'])
    
    results = []
    for i, row in reports.iterrows():
        for metric in ['precision', 'recall', 'f1']:
            results.append({'threshold': row['threshold'],
                            'metric': metric,
                            'value': row[metric]})
    
    df = pd.DataFrame(results)
    # Plot
    if plot:
        plt.figure(figsize=figsize)

        rc={'font.weight' : 'bold',
            'axes.linewidth' : linewidth,
            'axes.edgecolor' : 'k'}
        sns.set(style='whitegrid', font_scale=font_scale, rc=rc) 
        
        ax = sns.lineplot(data=df, x="threshold", y="value", hue="metric", 
                          style='metric', linewidth=linewidth)
        ax.set_xlabel('threshold', fontweight='bold')
        ax.set_ylabel('value', fontweight='bold')
        
    return reports
//  [python]
def plot_results(results_df, output_dir):
  """Plots metrics and saves plots as png files."""
  pylab.figure()
  method_name_mapping = {
      'AR': 'pure_AR',
      'ARMA_RLS': 'ARMA_iter',
      'LDS_GIBBS': 'LDS_MLE',
      'kshape': 'k-Shape',
      'PCA': 'PCA',
      # 'dtw_km': 'DTW',
      'ARMA_MLE': 'ARMA_MLE',
      # 'raw_output': 'raw_outputs'
  }
  results_df['inv_sqrt_seq_len'] = results_df.seq_len.apply(
      lambda x: round(1.0 / np.sqrt(x), 3))
  results_df['method'] = results_df.method.map(method_name_mapping)
  mean_df = results_df.groupby(['seq_len', 'method']).mean().reset_index()
  sns.pointplot(x='seq_len', y='failed_convg', data=mean_df, hue='method')
  output = six.StringIO()
  pylab.savefig(output, format='png')
  image = output.getvalue()
  with open(output_dir + '/' + 'convergence_failure_ratio.png', 'w+') as f:
    f.write(image)

  for metric_name in ['l2_a_error', 'l2_r_error', 't_secs']:
    pylab.figure()
    g = sns.pointplot(
        x='seq_len',
        y=metric_name,
        data=results_df,
        hue='method',
        scale=0.5,
        estimator=np.mean,
        err_style='bars',
        capsize=.1)
    output = six.StringIO()
    pylab.savefig(output, format='png')
    image = output.getvalue()
    with open(output_dir + '/' + metric_name + '.png', 'w+') as f:
      f.write(image)

  for metric_name in ['l2_a_error', 'l2_r_error', 't_secs']:
    pylab.figure()
    g = sns.pointplot(
        x='inv_sqrt_seq_len',
        y=metric_name,
        data=results_df,
        hue='method',
        scale=0.5,
        estimator=np.mean,
        err_style='bars',
        capsize=.1)
    g.set_xlim(g.get_xlim()[::-1])
    # g.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))
    output = six.StringIO()
    pylab.savefig(output, format='png')
    image = output.getvalue()
    with open(output_dir + '/' + metric_name + '_sqrt.png', 'w+') as f:
      f.write(image)
//  [python]
def plot_results(results_df, output_dir):
  """Plots metrics and saves plots as png files."""
  pylab.figure()
  method_name_mapping = {
      'AR': 'pure_AR',
      'ARMA_RLS': 'ARMA_iter',
      'LDS_GIBBS': 'LDS_MLE',
      'kshape': 'k-Shape',
      'PCA': 'PCA',
      # 'dtw_km': 'DTW',
      'ARMA_MLE': 'ARMA_MLE',
      # 'raw_output': 'raw_outputs'
  }
  results_df['inv_sqrt_seq_len'] = results_df.seq_len.apply(
      lambda x: round(1.0 / np.sqrt(x), 3))
  results_df['method'] = results_df.method.map(method_name_mapping)
  mean_df = results_df.groupby(['seq_len', 'method']).mean().reset_index()
  sns.lineplot(x='seq_len', y='failed_convg', data=mean_df, hue='method')
  output = six.StringIO()
  pylab.savefig(output, format='png')
  image = output.getvalue()
  with open(output_dir + '/' + 'convergence_failure_ratio.png', 'w+') as f:
    f.write(image)

  for metric_name in ['l2_a_error', 'l2_r_error', 't_secs']:
    pylab.figure()
    g = sns.pointplot(
        x='seq_len',
        y=metric_name,
        data=results_df,
        hue='method',
        scale=0.5,
        estimator=np.mean,
        err_style='bars',
        capsize=.1)
    output = six.StringIO()
    pylab.savefig(output, format='png')
    image = output.getvalue()
    with open(output_dir + '/' + metric_name + '.png', 'w+') as f:
      f.write(image)

  for metric_name in ['l2_a_error', 'l2_r_error', 't_secs']:
    pylab.figure()
    g = sns.pointplot(
        x='inv_sqrt_seq_len',
        y=metric_name,
        data=results_df,
        hue='method',
        scale=0.5,
        estimator=np.mean,
        err_style='bars',
        capsize=.1)
    g.set_xlim(g.get_xlim()[::-1])
    # g.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))
    output = six.StringIO()
    pylab.savefig(output, format='png')
    image = output.getvalue()
    with open(output_dir + '/' + metric_name + '_sqrt.png', 'w+') as f:
      f.write(image)
//  [python]
def plot_RMSD_vs_position(reference_pdb, all_pdbs):
    all_models = []
    all_results = []
    for model_pdb in list(all_pdbs):
        curr_rmsd, curr_distances = _calculate_RMSD(reference_pdb, model_pdb)
        model_name = model_pdb.parent.name
        all_results += [curr_distances]
        all_models.append(model_name)
    all_results = pd.DataFrame(np.array(all_results).T, columns=all_models)
    # TODO Fix:
    fig, axs = plt.subplots(1, figsize=(10, 4.8))
    for col in all_results.columns:
        axs.plot(all_results.index, all_results[col])
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
    fig.tight_layout()
    plt.show()

    return
//  [python]
def plot_RMSD_vs_position(reference_pdb, all_pdbs):
    all_models = []
    all_results = []
    for model_pdb in list(all_pdbs):
        curr_rmsd, curr_distances = _calculate_RMSD(reference_pdb, model_pdb)
        model_name = model_pdb.parent.name
        all_results += [curr_distances]
        all_models.append(model_name)
    all_results = pd.DataFrame(np.array(all_results).T, columns=all_models)
    # TODO Fix:
    fig, axs = plt.subplots(1, figsize=(10, 4.8))
    sns.lineplot(data=all_results, ax=axs)
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
    fig.tight_layout()
    plt.show()

    return
//  [python]
def plot_packingdensity_vs_position(all_pdbs):
    all_models = []
    all_results = []
    for model_pdb in list(all_pdbs):
        curr_packdensity = extract_packdensity_from_ampal(model_pdb)
        model_name = model_pdb.parent.name
        all_results += curr_packdensity
        all_models.append(model_name)

    all_results = pd.DataFrame(np.array(all_results).T, columns=all_models)
    # TODO Fix:
    fig, axs = plt.subplots(1, figsize=(10, 4.8))
    g = sns.tsplot(data=all_results, ax=axs)
    g.set(ylim=(0, 100))

    axs.yaxis.get_major_formatter().set_scientific(False)
    axs.xaxis.get_major_formatter().set_scientific(False)
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
    plt.title("Packing Density")
    fig.tight_layout()
    plt.show()
    return
//  [python]
def plot_packingdensity_vs_position(all_pdbs):
    all_models = []
    all_results = []
    for model_pdb in list(all_pdbs):
        curr_packdensity = extract_packdensity_from_ampal(model_pdb)
        model_name = model_pdb.parent.name
        all_results += curr_packdensity
        all_models.append(model_name)

    all_results = pd.DataFrame(np.array(all_results).T, columns=all_models)
    # TODO Fix:
    fig, axs = plt.subplots(1, figsize=(10, 4.8))
    g = sns.lineplot(data=all_results, ax=axs)
    g.set(ylim=(0, 100))

    axs.yaxis.get_major_formatter().set_scientific(False)
    axs.xaxis.get_major_formatter().set_scientific(False)
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
    plt.title("Packing Density")
    fig.tight_layout()
    plt.show()
    return
//  [python]
def plot_occ_aggregated_blocks_result():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/occ_agg_blocks_res.csv")

    sns.pointplot(y="value", x="block_num", hue="modell", data=df)

    plt.title('Aggregált blokkokal mért eredmény Balabit adathalmazon', fontsize=30)
    plt.ylabel('Átlag AUC', fontsize=30)
    plt.xlabel('Aggregált blokkok száma', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks(fontsize=28)
    plt.legend(fontsize=28, loc='lower right')
    plt.show()
//  [python]
def plot_occ_aggregated_blocks_result():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/occ_agg_blocks_res.csv")

    sns.lineplot(y="value", x="block_num", hue="modell", data=df)

    plt.title('Aggregált blokkokal mért eredmény Balabit adathalmazon', fontsize=30)
    plt.ylabel('Átlag AUC', fontsize=30)
    plt.xlabel('Aggregált blokkok száma', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks(fontsize=28)
    plt.legend(fontsize=28, loc='lower right')
    plt.show()
//  [python]
def plot_af2IDDT_vs_position(all_pdbs):
    all_models = []
    all_results = []
    for model_pdb in list(all_pdbs):
        curr_b_factors = extract_bfactor_from_ampal(model_pdb)
        model_name = model_pdb.parent.name
        all_results += curr_b_factors
        all_models.append(model_name)

    all_results = pd.DataFrame(np.array(all_results).T, columns=all_models)
    # TODO Fix:
    fig, axs = plt.subplots(1, figsize=(10, 4.8))
    g = sns.tsplot(data=all_results, ax=axs)
    g.set(ylim=(0, 100))

    axs.yaxis.get_major_formatter().set_scientific(False)
    axs.xaxis.get_major_formatter().set_scientific(False)
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
    fig.tight_layout()
    plt.show()
    return
//  [python]
def plot_af2IDDT_vs_position(all_pdbs):
    all_models = []
    all_results = []
    for model_pdb in list(all_pdbs):
        curr_b_factors = extract_bfactor_from_ampal(model_pdb)
        model_name = model_pdb.parent.name
        all_results += curr_b_factors
        all_models.append(model_name)

    all_results = pd.DataFrame(np.array(all_results).T, columns=all_models)
    # TODO Fix:
    fig, axs = plt.subplots(1, figsize=(10, 4.8))
    g = sns.lineplot(data=all_results, ax=axs)
    g.set(ylim=(0, 100))

    axs.yaxis.get_major_formatter().set_scientific(False)
    axs.xaxis.get_major_formatter().set_scientific(False)
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
    fig.tight_layout()
    plt.show()
    return
//  [python]
def plot_binary_classification_aggregated_blocks_result():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/binary_classification_agg_blocks_res.csv")

    sns.pointplot(y="value", x="block_num", hue="modell", data=df, join=True)

    plt.title('Aggregált blokkokal mért eredmény Balabit adathalmazon', fontsize=30)
    plt.ylabel('Átlag AUC', fontsize=30)
    plt.xlabel('Aggregált blokkok száma', fontsize=30)
    plt.xticks([1, 2, 3, 4, 5], fontsize=28)
    plt.yticks(fontsize=28)
    plt.legend(fontsize=28, loc='center right')
    plt.show()
//  [python]
def plot_binary_classification_aggregated_blocks_result():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/binary_classification_agg_blocks_res.csv")

    sns.lineplot(y="value", x="block_num", hue="modell", data=df)

    plt.title('Aggregált blokkokal mért eredmény Balabit adathalmazon', fontsize=30)
    plt.ylabel('Átlag AUC', fontsize=30)
    plt.xlabel('Aggregált blokkok száma', fontsize=30)
    plt.xticks([1, 2, 3, 4, 5], fontsize=28)
    plt.yticks(fontsize=28)
    plt.legend(fontsize=28, loc='center right')
    plt.show()
//  [python]
def plot_occ_sapimouse_aggregated_blocks_result():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/occ_agg_blocks_res_sapimouse.csv")

    sns.tsplot(y="value", x="block_num", hue="modell", data=df)

    plt.title('Aggregált blokkokal mért eredmény SapiMouse adathalmazon', fontsize=30)
    plt.ylabel('Átlag AUC', fontsize=30)
    plt.xlabel('Aggregált blokkok száma', fontsize=30)
    plt.xticks([1, 2, 3, 4, 5], fontsize=28)
    plt.xticks(fontsize=28)
    plt.yticks(fontsize=28)
    plt.legend(fontsize=28, loc='lower right')
    plt.show()
//  [python]
def plot_occ_sapimouse_aggregated_blocks_result():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/occ_agg_blocks_res_sapimouse.csv")

    sns.lineplot(y="value", x="block_num", hue="modell", data=df)

    plt.title('Aggregált blokkokal mért eredmény SapiMouse adathalmazon', fontsize=30)
    plt.ylabel('Átlag AUC', fontsize=30)
    plt.xlabel('Aggregált blokkok száma', fontsize=30)
    plt.xticks([1, 2, 3, 4, 5], fontsize=28)
    plt.xticks(fontsize=28)
    plt.yticks(fontsize=28)
    plt.legend(fontsize=28, loc='lower right')
    plt.show()
//  [python]
def plot_signal(signal, figsize=(6, 0.5), **kwargs):
    ax = sns.lineplot(data=signal, lw=0.1, **kwargs)
    ax.set_axis_off()
    ax.margins(0)
    plt.gcf().set_size_inches(*figsize)
    plt.show()
//  [python]
def plot(figname, palette=None):
    df = pd.read_csv(f"{figname}.csv")
    df["accuracy"] = df["accuracy"] * 100
    df["time"] = df["time"] / 60
    fig, ax = plt.subplots(figsize=figsize)
    ax.set_ylabel("Accuracy", fontsize=16)
    g = sns.tsplot(
        data=df,
        time="time",
        value="accuracy",
        unit="run",
        ax=ax,
        condition="run",
        markers=["o", "v"],
        palette=palette,
    )
    plt.ylim((40, 80))
    ax.yaxis.set_major_formatter(mpl.ticker.PercentFormatter(decimals=0))
    plt.grid(axis="y")
    plt.xlabel("Time (min)", fontsize=16)
    plt.legend(fontsize=13)
    plt.tight_layout()
    filename = figname + ".pdf"
    print(filename)
    plt.savefig(filename, bbox_inches="tight")
//  [python]
def plot(figname, palette=None):
    df = pd.read_csv(f"{figname}.csv")
    df["accuracy"] = df["accuracy"] * 100
    df["time"] = df["time"] / 60
    fig, ax = plt.subplots(figsize=figsize)
    ax.set_ylabel("Accuracy", fontsize=16)
    g = sns.lineplot(
        data=df,
        x="time",
        y="accuracy",
        hue="run",
        ax=ax,
        style="run",
        markers=["o", "v"],
        palette=palette,
    )
    plt.ylim((40, 80))
    ax.yaxis.set_major_formatter(mpl.ticker.PercentFormatter(decimals=0))
    plt.grid(axis="y")
    plt.xlabel("Time (min)", fontsize=16)
    plt.legend(fontsize=13)
    plt.tight_layout()
    filename = figname + ".pdf"
    print(filename)
    plt.savefig(filename, bbox_inches="tight")