jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def visualize(
            self,
            results,
            x_tile,
            y_tile,
            x_axis,
            y_axis,
            lines,
            results_id=None,
            filename='BarChartVisualizer',
            **kwargs
    ):
        """
        Create a tiled visualization of experiment results.

        :param results: pd.DataFrame of results, loaded from results .csv file.
        :param x_tile: string name of DataFrame column to vary over the x axis of the grid of line graphs
        :param y_tile: string name of DataFrame column to vary over the y axis of the grid of line graphs
        :param x_axis: string name of DataFrame column to plot on the x axis within each individual line graph
        :param y_axis: string name of DataFrame column to plot on the y axis within each individual line graph
        :param lines: string name or list of DataFrame column string names displayed as separate lines within each graph.
                      Providing multiple values means that each unique combination of values will be displayed as a single line.
        :param results_id: string name of folder to save resulting visual in, relative to the root of the results directory
        :param filename: filename (excluding filetype) to use when saving visualization.  Value is relative to folder specified by results_id.
        """
        sns.set(style="ticks", color_codes=True)

        if isinstance(lines, (tuple, list)):
            for col in lines:
                results[col] = results[col].astype(str)
            results['key'] = results[lines].apply(lambda x: ','.join(x), axis=1)
        g = sns.FacetGrid(results, row=y_tile, col=x_tile, hue='key',
                        sharex=True, sharey=False)
        g.map(sns.barplot, x_axis, y_axis)
        g.add_legend()
        for ax in g.axes.flatten():
            ax.set_ylabel('')
            ax.set_xlabel('')
        filename = os.path.join(RESULTS_DIRECTORY, results_id, "{}.png".format(filename))
        plt.savefig(filename, bbox_inches='tight')
//  [python]
def visualize(
            self,
            results,
            x_tile,
            y_tile,
            x_axis,
            y_axis,
            lines,
            results_id=None,
            filename='BarChartVisualizer',
            **kwargs
    ):
        """
        Create a tiled visualization of experiment results.

        :param results: pd.DataFrame of results, loaded from results .csv file.
        :param x_tile: string name of DataFrame column to vary over the x axis of the grid of line graphs
        :param y_tile: string name of DataFrame column to vary over the y axis of the grid of line graphs
        :param x_axis: string name of DataFrame column to plot on the x axis within each individual line graph
        :param y_axis: string name of DataFrame column to plot on the y axis within each individual line graph
        :param lines: string name or list of DataFrame column string names displayed as separate lines within each graph.
                      Providing multiple values means that each unique combination of values will be displayed as a single line.
        :param results_id: string name of folder to save resulting visual in, relative to the root of the results directory
        :param filename: filename (excluding filetype) to use when saving visualization.  Value is relative to folder specified by results_id.
        """
        sns.set(style="ticks", color_codes=True)

        if isinstance(lines, (tuple, list)):
            for col in lines:
                results[col] = results[col].astype(str)
            results['key'] = results[lines].apply(lambda x: ','.join(x), axis=1)
        g = sns.catplot(x=x_axis, y=y_axis, row=y_tile, col=x_tile, hue='key',
                        data=results, kind='bar', legend_out = True, margin_titles=True,
                        sharex=True, sharey=False)
        for ax in g.axes.flatten():
            ax.set_ylabel('')
            ax.set_xlabel('')
        filename = os.path.join(RESULTS_DIRECTORY, results_id, "{}.png".format(filename))
        plt.savefig(filename, bbox_inches='tight')
//  [python]
def plot_umi_match_fraction(umi, r1_match, r2_match, suffix=""):
    print(f"# {time.asctime()} - Plotting fraction of correct barcodes.")

    d = pd.DataFrame(
        [[umi.loc[r1_match].sum(), umi.sum()], [umi.loc[r2_match].sum(), umi.sum()]],
        index=["correct", "total"],
        columns=["r1", "r2"],
    )
    d.loc["fraction of exact match", :] = d.loc["correct"] / d.loc["total"]

    g = sns.factorplot(
        data=d.reset_index().melt(id_vars="index"),
        x="variable",
        y="value",
        col="index",
        sharey=False,
        kind="bar",
        size=3,
        aspect=1,
    )
    g.savefig(
        args.output_prefix + f"umi_matching.barplot.{suffix}.svg".replace("..", "."),
        dpi=300,
        bbox_inches="tight",
    )
//  [python]
def plot_umi_match_fraction(umi, r1_match, r2_match, suffix=""):
    print(f"# {time.asctime()} - Plotting fraction of correct barcodes.")

    d = pd.DataFrame(
        [[umi.loc[r1_match].sum(), umi.sum()], [umi.loc[r2_match].sum(), umi.sum()]],
        index=["correct", "total"],
        columns=["r1", "r2"],
    )
    d.loc["fraction of exact match", :] = d.loc["correct"] / d.loc["total"]

    grid = sns.catplot(
        data=d.reset_index().melt(id_vars="index"),
        x="variable",
        y="value",
        col="index",
        sharey=False,
        kind="bar",
        height=3,
        aspect=1,
    )
    grid.fig.savefig(
        args.output_prefix + f"umi_matching.barplot.{suffix}.svg".replace("..", "."),
        dpi=300,
        bbox_inches="tight",
    )
//  [python]
def plot_categoty_inside(self, x_category, y_category, col_wrap=6,
                             kind='count',figsize=(10,6), dpi=80):
        """
        绘制某一字段内各个类别在另一个类别上的数据统计显示
        
        x_category：类别型字段
        y_category：类别型字段
        col_wrap：每一行显示的小图个数
        kind：显示的类型，‘counts’,'box','violin'等
        figsize：（x,y）代表图显示的x和y坐标。
        """
        
        plt.figure(figsize=figsize, dpi=dpi)
        g = sns.factorplot(x=x_category, col=y_category, 
                        col_wrap=col_wrap, data=self.data,
                        kind=kind, size=4, aspect=1, 
                        palette='tab20')
#         plt.title(y_category + ' VS ' + x_category, loc='center')
        plt.show()
//  [python]
def plot_categoty_inside(self, x_category, y_category, col_wrap=6,
                             kind='count',figsize=(10,6), dpi=80):
        """
        绘制某一字段内各个类别在另一个类别上的数据统计显示
        
        x_category：类别型字段
        y_category：类别型字段
        col_wrap：每一行显示的小图个数
        kind：显示的类型，‘counts’,'box','violin'等
        figsize：（x,y）代表图显示的x和y坐标。
        """
        
        plt.figure(figsize=figsize, dpi=dpi)
        g = sns.catplot(x=x_category, col=y_category, 
                        col_wrap=col_wrap, data=self.data,
                        kind=kind, height=4, aspect=1, 
                        palette='tab20')
#         plt.title(y_category + ' VS ' + x_category, loc='center')
        plt.show()
//  [python]
fig = plt.figure()
instrs = pd.read_csv("graphs/l2b-fig8.csv")
instrs['Compiler'] = instrs['compiler'].map(
        dict(zip(["seccomp","jitsynth"],
            ["libseccomp","JitSynth"])))
instrs['Benchmark'] = instrs['benchmark']
g = sns.factorplot(x="Benchmark", y="instructions", hue="Compiler", data=instrs, kind="bar", aspect=1.6, legend_out=False)
//  [python]
fig = plt.figure()
instrs = pd.read_csv("graphs/l2b-fig8.csv")
instrs['Compiler'] = instrs['compiler'].map(
        dict(zip(["seccomp","jitsynth"],
            ["libseccomp","JitSynth"])))
instrs['Benchmark'] = instrs['benchmark']
g = sns.catplot(x="Benchmark", y="instructions", hue="Compiler", data=instrs, kind="bar", aspect=1.6, legend_out=False)
//  [python]
def gms_box_plots(metrics_table, output_fig=None):
    if isinstance(metrics_table, pd.DataFrame):
        pass
    elif isinstance(metrics_table, str):
        metrics_table = pd.read_csv(metrics_table)
    elif isinstance(metrics_table, list):
        metrics_table = pd.concat([pd.read_csv(mt) for mt in metrics_table], ignore_index=True)
    else:
        ValueError("Pass metrics_table as DataFrame or path to CSV")

    metrics_table = preparing_data_for_plotting(metrics_table)

    facetgrid = sns.FacetGrid(
        data=metrics_table,
        col='Mannings N',
        row='Metric',
        hue='Magnitude',
        margin_titles=False,
        sharex=False,
        sharey=False,
        despine=True,
        height=2.75,
        aspect=1,
    )

    facetgrid.map(
        sns.violinplot,
        'Model',
        'Metric Value',
        inner='quartile',
        split=True,
        order=['FR', 'MS', 'GMS'],
        cut=2,
        scale='width',
        linewidth=1.5,
        saturation=0.55,
    )

    facetgrid.map(
        sns.regplot,
        'model_integer_encodings',
        'Metric Value',
        scatter=False,
        ci=None,
        robust=True,
        color='darkgreen',
        truncate=False,
        line_kws={'linewidth': 2},
        label='Trend Line',
    )

    # facetgrid.fig.set_size_inches(10,15)

    # legend
    handles, labels = facetgrid.axes[0, 0].get_legend_handles_labels()
    facetgrid.fig.legend(
        loc='lower left', ncol=3, bbox_to_anchor=(0.22, -0.06), handles=handles, labels=labels
    )

    # xlabel
    plt.annotate('Model', xy=(0.52, 0.054), xycoords='figure fraction')

    # override axes params
    facetgrid = set_axes(facetgrid)

    facetgrid.fig.subplots_adjust(wspace=0, hspace=0.1)

    # set margins to tight
    # plt.tight_layout()

    # set rlm metrics
    metrics_table = robust_linear_model(metrics_table)
    facetgrid = annotate_rlm(facetgrid, metrics_table)

    # set text sizes
    facetgrid = set_text_sizes(facetgrid)

    if output_fig is not None:
        plt.savefig(output_fig, dpi=300, format='jpg', bbox_inches='tight')

    plt.show()
//  [python]
def gms_box_plots(metrics_table, output_fig=None):
    if isinstance(metrics_table, pd.DataFrame):
        pass
    elif isinstance(metrics_table, str):
        metrics_table = pd.read_csv(metrics_table)
    elif isinstance(metrics_table, list):
        metrics_table = pd.concat([pd.read_csv(mt) for mt in metrics_table], ignore_index=True)
    else:
        ValueError("Pass metrics_table as DataFrame or path to CSV")

    metrics_table = preparing_data_for_plotting(metrics_table)

    facetgrid = sns.catplot(
        data=metrics_table,
        x='Model',
        y='Metric Value',
        hue='Magnitude',
        inner='quartile',
        split=True,
        order=['FR', 'MS', 'GMS'],
        cut=2,
        kind='violin',
        col='Mannings N',
        row='Metric',
        margin_titles=False,
        sharex=False,
        sharey=False,
        despine=True,
        scale='width',
        height=2.75,
        aspect=1,
        linewidth=1.5,
        legend=False,
        saturation=0.55,
    )

    facetgrid.map_dataframe(
        sns.regplot,
        data=metrics_table,
        x='model_integer_encodings',
        y='Metric Value',
        scatter=False,
        ci=None,
        robust=True,
        color='darkgreen',
        truncate=False,
        line_kws={'linewidth': 2},
        label='Trend Line',
    )

    # facetgrid.fig.set_size_inches(10,15)

    # legend
    handles, labels = facetgrid.axes[0, 0].get_legend_handles_labels()
    facetgrid.fig.legend(
        loc='lower left', ncol=3, bbox_to_anchor=(0.22, -0.06), handles=handles, labels=labels
    )

    # xlabel
    plt.annotate('Model', xy=(0.52, 0.054), xycoords='figure fraction')

    # override axes params
    facetgrid = set_axes(facetgrid)

    facetgrid.fig.subplots_adjust(wspace=0, hspace=0.1)

    # set margins to tight
    # plt.tight_layout()

    # set rlm metrics
    metrics_table = robust_linear_model(metrics_table)
    facetgrid = annotate_rlm(facetgrid, metrics_table)

    # set text sizes
    facetgrid = set_text_sizes(facetgrid)

    if output_fig is not None:
        plt.savefig(output_fig, dpi=300, format='jpg', bbox_inches='tight')

    plt.show()
//  [python]
def fig_2c():
    pd_dataframe_folded = make_dataframe(("/om2/user/francl/grp-om2/gahlm/dataset_pipeline_test/"
                                          "arch_number_[0-9][0,1,3-9][0-9]*init_0/"
                                          "batch_conditional_*binaural_recorded_testset"
                                          "_4078_main_kemar_0elev_*iter100000*"),
                                         fold_data=True,recenter_folded_data=False)
    format_binaural_test_set_frontback_folded(pd_dataframe_folded)
    rgb_cmap = get_grayscale_colormap()
    plt.clf()
    sns.violinplot(x="Actual Position (Degrees)",
                data=pd_dataframe_folded.astype('int32'),palette=rgb_cmap)
    format_binarural_test_folded_graph()
    plt.tight_layout()
    pd_dataframe_folded.to_csv(plots_folder+"/"+("binaural_recorded_4078_main_kemar_full_spec_folded"
                                                  "_violinplot_quartile_grayscale_front_limited.csv"))
    plt.savefig(plots_folder+"/"+("binaural_recorded_4078_main_kemar_full_spec_folded"
                                  "_violinplot_quartile_grayscale_front_limited.svg"))
//  [python]
def fig_2c():
    pd_dataframe_folded = make_dataframe(("/om2/user/francl/grp-om2/gahlm/dataset_pipeline_test/"
                                          "arch_number_[0-9][0,1,3-9][0-9]*init_0/"
                                          "batch_conditional_*binaural_recorded_testset"
                                          "_4078_main_kemar_0elev_*iter100000*"),
                                         fold_data=True,recenter_folded_data=False)
    format_binaural_test_set_frontback_folded(pd_dataframe_folded)
    rgb_cmap = get_grayscale_colormap()
    plt.clf()
    sns.catplot(kind="violin",x="Actual Position (Degrees)",
                data=pd_dataframe_folded.astype('int32'),palette=rgb_cmap)
    format_binarural_test_folded_graph()
    plt.tight_layout()
    pd_dataframe_folded.to_csv(plots_folder+"/"+("binaural_recorded_4078_main_kemar_full_spec_folded"
                                                  "_violinplot_quartile_grayscale_front_limited.csv"))
    plt.savefig(plots_folder+"/"+("binaural_recorded_4078_main_kemar_full_spec_folded"
                                  "_violinplot_quartile_grayscale_front_limited.svg"))
//  [python]
def fig_2d():
    pd_dataframe_folded = make_dataframe(("/om2/user/francl/grp-om2/gahlm/dataset_pipeline_test/"
                                          "arch_number_[0-9][0,1,3-9][0-9]*init_0/"
                                          "batch_conditional_*binaural_recorded_testset"
                                          "_4078_main_kemar_0elev_*iter100000*"),
                                         fold_data=True,recenter_folded_data=False)
    format_binaural_test_set(pd_dataframe_folded)
    rgb_cmap = get_grayscale_colormap()
    plt.clf()
    sns.violinplot(x="azim_centered",
                y="predicted_centered", inner='quartile',
                data=pd_dataframe_folded.astype('int32'),palette=rgb_cmap)
    plt.yticks([-180,-150,-120,-90,-60,-30,0,30,60,90,120,150,180])
    plt.ylim(-190,190)
    plt.tight_layout()
    pd_dataframe_folded.to_csv(plots_folder+"/"+("binaural_recorded_4078_main_kemar_full_spec_folded"
                                                 "_violinplot_quartile_grayscale_centered.csv"))
    plt.savefig(plots_folder+"/"+("binaural_recorded_4078_main_kemar_full_spec_folded"
                                  "_violinplot_quartile_grayscale_centered.svg"))
//  [python]
def fig_2d():
    pd_dataframe_folded = make_dataframe(("/om2/user/francl/grp-om2/gahlm/dataset_pipeline_test/"
                                          "arch_number_[0-9][0,1,3-9][0-9]*init_0/"
                                          "batch_conditional_*binaural_recorded_testset"
                                          "_4078_main_kemar_0elev_*iter100000*"),
                                         fold_data=True,recenter_folded_data=False)
    format_binaural_test_set(pd_dataframe_folded)
    rgb_cmap = get_grayscale_colormap()
    plt.clf()
    sns.catplot(kind="violin",x="azim_centered",
                y="predicted_centered", height=8,
                aspect=1.45,inner='quartile',
                data=pd_dataframe_folded.astype('int32'),palette=rgb_cmap)
    plt.yticks([-180,-150,-120,-90,-60,-30,0,30,60,90,120,150,180])
    plt.ylim(-190,190)
    plt.tight_layout()
    pd_dataframe_folded.to_csv(plots_folder+"/"+("binaural_recorded_4078_main_kemar_full_spec_folded"
                                                 "_violinplot_quartile_grayscale_centered.csv"))
    plt.savefig(plots_folder+"/"+("binaural_recorded_4078_main_kemar_full_spec_folded"
                                  "_violinplot_quartile_grayscale_centered.svg"))
//  [python]
def plot(metric: str, data: pd.DataFrame):
    """
    Creates a single plot for a specific metric.
    
    Args:
        metric (str): ''WER' or 'EMD'
    """
    # Create the actual dataframe.
    df = pd.DataFrame(data=data[metric])

    # Plot the histogram.
    sns.set(style="ticks", palette="pastel")
    fig, ax = plt.subplots(1, 1, figsize=(10, 5))
    sns.boxplot(
        data=df,
        y="lr",
        x="values",
        hue="group",
        orient="h",
        palette=sns.color_palette(["#88C3E7"], n_colors=1),
    )
    sns.despine(offset=10, trim=True)
    plt.savefig(f"results/boxplot_{metric}.eps")
//  [python]
def plot(metric: str, data: pd.DataFrame):
    """
    Creates a single plot for a specific metric.
    
    Args:
        metric (str): ''WER' or 'EMD'
    """
    # Create the actual dataframe.
    df = pd.DataFrame(data=data[metric])

    # Plot the histogram.
    sns.set(style="ticks", palette="pastel")
    fig, ax = plt.subplots(1, 1, figsize=(10, 5))
    sns.catplot(
        data=df,
        y="lr",
        x="values",
        col="group",
        kind="box",
        orient="h",
        height=2,
        aspect=4,
        palette=sns.color_palette(["#88C3E7"], n_colors=1),
    )
    sns.despine(offset=10, trim=True)
    plt.savefig(f"results/boxplot_{metric}.eps")
//  [python]
def Plot_Performance(df,dir_results,metrics=None):
    subdir = 'Performance'
    if not os.path.exists(os.path.join(dir_results,subdir)):
        os.makedirs(os.path.join(dir_results,subdir))

    if metrics is None:
        metrics = np.unique(df['Metric'].tolist())

    types = np.unique(df['Classes'].tolist())
    for m in metrics:
        for t in types:
            df_temp = df[(df['Classes']==t) & (df['Metric']==m)]
            sns.pointplot(data=df_temp,x='k',y='Value',hue='Algorithm',capsize=0.2)
            plt.title(t,fontsize=24)
            plt.ylabel(m)
            plt.subplots_adjust(top=0.9)
            plt.xticks(rotation=90,fontsize=12)
            plt.yticks(fontsize=12)
            plt.xlabel('k',fontsize=18)
            plt.ylabel(m,fontsize=18)
            plt.subplots_adjust(bottom=0.15)
            plt.savefig(os.path.join(dir_results,subdir,m+'_'+t+'.eps'))
            plt.close()
//  [python]
def Plot_Performance(df,dir_results,metrics=None):
    subdir = 'Performance'
    if not os.path.exists(os.path.join(dir_results,subdir)):
        os.makedirs(os.path.join(dir_results,subdir))

    if metrics is None:
        metrics = np.unique(df['Metric'].tolist())

    types = np.unique(df['Classes'].tolist())
    for m in metrics:
        for t in types:
            df_temp = df[(df['Classes']==t) & (df['Metric']==m)]
            sns.catplot(data=df_temp,x='k',y='Value',kind='point',hue='Algorithm',capsize=0.2)
            plt.title(t,fontsize=24)
            plt.ylabel(m)
            plt.subplots_adjust(top=0.9)
            plt.xticks(rotation=90,fontsize=12)
            plt.yticks(fontsize=12)
            plt.xlabel('k',fontsize=18)
            plt.ylabel(m,fontsize=18)
            plt.subplots_adjust(bottom=0.15)
            plt.savefig(os.path.join(dir_results,subdir,m+'_'+t+'.eps'))
            plt.close()
//  [python]
def make_yost_localization_by_azim():
    pd_yost =  pd.read_csv("/om/user/francl/Data_Fig_7.csv",header=[0])
    pd_yost_pivoted = pd_yost.set_index('Band-Pass').stack().reset_index()
    pd_yost_pivoted.columns = ["Actual Position (Degrees)",
                               "Predicted Position (Degrees)","Percentage"]
    pd_yost_pivoted = pd_yost_pivoted.convert_objects(convert_numeric=True)
    pd_yost_pivoted["Percentage"] = 100*pd_yost_pivoted["Percentage"]
    pd_yost_pivoted["Predicted Position (Degrees)"] = (pd_yost_pivoted["Predicted Position (Degrees)"]
                                                       .apply(lambda x: (x*15)-105))
    pd_yost_pivoted["Actual Position (Degrees)"] = (pd_yost_pivoted["Actual Position (Degrees)"]
                                                       .apply(lambda x: (x*15)-105))
    pd_yost_distribution = (pd_yost_pivoted.loc[np.repeat(pd_yost_pivoted.index.values,
                                                         pd_yost_pivoted.Percentage)]
                                           .drop("Percentage",axis=1)
                                           .reset_index(drop=True))
    rgb_cmap = get_grayscale_colormap()
    fig = plt.figure(figsize=(14,12.5))
    sns.violinplot(x="Actual Position (Degrees)",
                y="Predicted Position (Degrees)", inner='quartile',palette=rgb_cmap,
                data=pd_yost_distribution.astype('int32'))
    plt.xlim(-1,11)
    plt.ylim(-105,105)
    plt.yticks([-90,-60,-30,0,30,60,90])
    plt.xticks(list(range(-1,12)),list(range(-90,105,15)))
    plt.savefig(plots_folder+"/yost_frontal_localization_human.svg")
//  [python]
def make_yost_localization_by_azim():
    pd_yost =  pd.read_csv("/om/user/francl/Data_Fig_7.csv",header=[0])
    pd_yost_pivoted = pd_yost.set_index('Band-Pass').stack().reset_index()
    pd_yost_pivoted.columns = ["Actual Position (Degrees)",
                               "Predicted Position (Degrees)","Percentage"]
    pd_yost_pivoted = pd_yost_pivoted.convert_objects(convert_numeric=True)
    pd_yost_pivoted["Percentage"] = 100*pd_yost_pivoted["Percentage"]
    pd_yost_pivoted["Predicted Position (Degrees)"] = (pd_yost_pivoted["Predicted Position (Degrees)"]
                                                       .apply(lambda x: (x*15)-105))
    pd_yost_pivoted["Actual Position (Degrees)"] = (pd_yost_pivoted["Actual Position (Degrees)"]
                                                       .apply(lambda x: (x*15)-105))
    pd_yost_distribution = (pd_yost_pivoted.loc[np.repeat(pd_yost_pivoted.index.values,
                                                         pd_yost_pivoted.Percentage)]
                                           .drop("Percentage",axis=1)
                                           .reset_index(drop=True))
    rgb_cmap = get_grayscale_colormap()
    fig = plt.figure(figsize=(14,12.5))
    sns.catplot(kind="violin",x="Actual Position (Degrees)",
                y="Predicted Position (Degrees)", height=8,
                aspect=1.45,inner='quartile',palette=rgb_cmap,
                data=pd_yost_distribution.astype('int32'))
    plt.xlim(-1,11)
    plt.ylim(-105,105)
    plt.yticks([-90,-60,-30,0,30,60,90])
    plt.xticks(list(range(-1,12)),list(range(-90,105,15)))
    plt.savefig(plots_folder+"/yost_frontal_localization_human.svg")
//  [python]
def explicit_viz(df):
    '''
    This function produces a swarm plot on explicit tracks' and non-explicit tracks' popularity.
    '''
    #print('Does a track being explicit or not correlate with its popularity?')
    sns.swarmplot(x="explicit", y="popularity", data=df)
    plt.title(label="Does a track being explicit or not correlate with its popularity?")
    plt.show()
//  [python]
def explicit_viz(df):
    '''
    This function produces a swarm plot on explicit tracks' and non-explicit tracks' popularity.
    '''
    #print('Does a track being explicit or not correlate with its popularity?')
    sns.catplot(x="explicit", y="popularity", kind="swarm", data=df, height=8, aspect=1)
    plt.title(label="Does a track being explicit or not correlate with its popularity?")
    plt.show()
//  [python]
sns.set(style="darkgrid")

dataku = pd.DataFrame({
    'x': np.arange(10),
    'y': np.random.randint(10, size=10),
    'z': ['Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No']
})

# sns.factorplot(x='x', y='y', data=dataku)
# sns.factorplot(x='x', y='y', data=dataku, kind='point')
sns.factorplot(x='x', y='y', hue='z', data=dataku, kind='bar')
//  [python]
sns.set(style="darkgrid")

dataku = pd.DataFrame({
    'x': np.arange(10),
    'y': np.random.randint(10, size=10),
    'z': ['Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No']
})

# sns.catplot(x='x', y='y', data=dataku)
# sns.catplot(x='x', y='y', data=dataku, kind='point')
sns.catplot(x='x', y='y', hue='z', data=dataku, kind='bar')
//  [python]
def plot_protein_numbers(data, x_col, y_col, title, y_lim=None, height=6, aspect=1.3):
    """
    Creates a combined box and strip plot for protein number visualization.

    Args:
        data (pd.DataFrame): DataFrame containing the data to be plotted.
        x_col (str): Column name in `data` to be plotted on the x-axis.
        y_col (str): Column name in `data` to be plotted on the y-axis.
        title (str): Title of the plot.
        y_lim (tuple, optional): Tuple specifying the limits for the y-axis (e.g., (0, 7000)).
        height (float, optional): Height (in inches) of each facet. Defaults to 6.
        aspect (float, optional): Aspect ratio of each facet, so that aspect * height gives the width of each facet in inches. Defaults to 1.3.

    Example:
        >>> plot_protein_numbers(protein_num, 'Type', 'Identification of Protein numbers',
                                'Protein numbers of HEK293T QC samples', y_lim=(0, 7000), height=5, aspect=1)
    """
    custom_params = {"axes.spines.right": False, "axes.spines.top": False}
    sns.set_theme(style="ticks", rc=custom_params)

    # Create a box plot
    box_plot = sns.boxplot(
        x=x_col,
        y=y_col,
        hue=x_col,
        data=data,
    )

    # Overlay with a strip plot
    sns.stripplot(
        x=x_col,
        y=y_col,
        hue=x_col,
        jitter=True,
        dodge=True,
        marker="o",
        palette="Set2",
        alpha=0.5,
        data=data,
    )

    # Set additional plot attributes
    plt.title(title)  # Set the title for the figure
    plt.legend(loc="lower right")
    if y_lim:
        plt.ylim(y_lim)

    plt.show()
//  [python]
def plot_protein_numbers(data, x_col, y_col, title, y_lim=None, height=6, aspect=1.3):
    """
    Creates a combined box and strip plot for protein number visualization.

    Args:
        data (pd.DataFrame): DataFrame containing the data to be plotted.
        x_col (str): Column name in `data` to be plotted on the x-axis.
        y_col (str): Column name in `data` to be plotted on the y-axis.
        title (str): Title of the plot.
        y_lim (tuple, optional): Tuple specifying the limits for the y-axis (e.g., (0, 7000)).
        height (float, optional): Height (in inches) of each facet. Defaults to 6.
        aspect (float, optional): Aspect ratio of each facet, so that aspect * height gives the width of each facet in inches. Defaults to 1.3.

    Example:
        >>> plot_protein_numbers(protein_num, 'Type', 'Identification of Protein numbers',
                                'Protein numbers of HEK293T QC samples', y_lim=(0, 7000), height=5, aspect=1)
    """
    custom_params = {"axes.spines.right": False, "axes.spines.top": False}
    sns.set_theme(style="ticks", rc=custom_params)

    # Create a box plot
    box_plot = sns.catplot(
        x=x_col,
        y=y_col,
        hue=x_col,
        kind="box",
        legend=False,
        height=height,
        aspect=aspect,
        data=data,
    )

    # Overlay with a strip plot
    sns.stripplot(
        x=x_col,
        y=y_col,
        hue=x_col,
        jitter=True,
        dodge=True,
        marker="o",
        palette="Set2",
        alpha=0.5,
        data=data,
    )

    # Set additional plot attributes
    box_plot.fig.suptitle(title)  # Set the title for the figure
    plt.legend(loc="lower right")
    if y_lim:
        plt.ylim(y_lim)

    plt.show()
//  [python]
def plot_binary_classification_balabit_results_boxplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/binary_300_balabit_p.csv")

    sns.boxplot(x="model", y="value", hue="metric", data=df, linewidth=2)
    sns.despine(top=False, right=False)

    plt.title('Bináris osztályozás eredménye Balabit adathalmaz esetén', fontsize=30)
    plt.ylabel('Érték', fontsize=30)
    plt.xlabel('CNN modell típusa', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1], fontsize=28)
    plt.ylim(0.35, 1) 
    plt.legend(fontsize=28, loc='lower right')
    plt.show()
//  [python]
def plot_binary_classification_balabit_results_boxplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/binary_300_balabit_p.csv")

    sns.catplot(x="model", y="value", hue="metric", kind="box", data=df, legend=False, linewidth=2)
    sns.despine(top=False, right=False)

    plt.title('Bináris osztályozás eredménye Balabit adathalmaz esetén', fontsize=30)
    plt.ylabel('Érték', fontsize=30)
    plt.xlabel('CNN modell típusa', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1], fontsize=28)
    plt.ylim(0.35, 1) 
    plt.legend(fontsize=28, loc='lower right')
    plt.show()
//  [python]
def plot_binary_classification_dfl_results_boxplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/binary_440_dfl_p.csv")

    sns.boxplot(x="model", y="value", hue="metric", data=df, linewidth=2)
    sns.despine(top=False, right=False)

    plt.title('Bináris osztályozás eredménye DFL adathalmaz esetén', fontsize=30)
    plt.ylabel('Érték', fontsize=30)
    plt.xlabel('CNN modell típusa', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1], fontsize=28)
    plt.ylim(0.35, 1) 
    plt.legend(fontsize=28, loc='lower right')
    plt.show()
//  [python]
def plot_binary_classification_dfl_results_boxplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/binary_440_dfl_p.csv")

    sns.catplot(x="model", y="value", hue="metric", kind="box", data=df, legend=False, linewidth=2)
    sns.despine(top=False, right=False)

    plt.title('Bináris osztályozás eredménye DFL adathalmaz esetén', fontsize=30)
    plt.ylabel('Érték', fontsize=30)
    plt.xlabel('CNN modell típusa', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1], fontsize=28)
    plt.ylim(0.35, 1) 
    plt.legend(fontsize=28, loc='lower right')
    plt.show()
//  [python]
def plot_occ_balabit_results_barplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/occ_balabit_barplot.csv")

    g = sns.factorplot(x="model", y="value", hue='metric', data=df, kind="bar", legend=False, linewidth=2.5,
                 errcolor=".2", edgecolor=".2") 
    sns.despine(top=False, right=False)

    plt.title('OCSVM átlag AUC értéke Balabit adathalmaz esetén', fontsize=30)
    plt.ylabel('AUC érték', fontsize=30)
    plt.xlabel('Tanító adathalmaz típusa', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.55, 0.60, 0.65, 0.70, 0.75], fontsize=28)
    plt.ylim(0.55, 0.75)
    plt.legend(fontsize=28, loc='upper right')
    plt.show()
//  [python]
def plot_occ_balabit_results_barplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/occ_balabit_barplot.csv")

    sns.catplot(x="model", y="value", hue='metric', data=df, kind="bar", legend=False, linewidth=2.5,
                 errcolor=".2", edgecolor=".2") 
    sns.despine(top=False, right=False)

    plt.title('OCSVM átlag AUC értéke Balabit adathalmaz esetén', fontsize=30)
    plt.ylabel('AUC érték', fontsize=30)
    plt.xlabel('Tanító adathalmaz típusa', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.55, 0.60, 0.65, 0.70, 0.75], fontsize=28)
    plt.ylim(0.55, 0.75)
    plt.legend(fontsize=28, loc='upper right')
    plt.show()
//  [python]
def plot_binary_classification_balabit_results_barplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/binary_classification_balabit_barplot.csv")

    sns.barplot(x="model", y="value", hue='metric', data=df, linewidth=2.5,
                 errcolor=".2", edgecolor=".2") 
    sns.despine(top=False, right=False)

    plt.title('Bináris osztályozás átlag eredménye Balabit adathalmaz esetén', fontsize=30)
    plt.ylabel('Érték', fontsize=30)
    plt.xlabel('CNN modell típusa', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.45, 0.55, 0.65, 0.75, 0.85, 0.95], fontsize=28)
    plt.ylim(0.45, 1)
    plt.legend(fontsize=28, loc='upper center')
    plt.show()
//  [python]
def plot_binary_classification_balabit_results_barplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/binary_classification_balabit_barplot.csv")

    sns.catplot(x="model", y="value", hue='metric', data=df, kind="bar", legend=False, linewidth=2.5,
                 errcolor=".2", edgecolor=".2") 
    sns.despine(top=False, right=False)

    plt.title('Bináris osztályozás átlag eredménye Balabit adathalmaz esetén', fontsize=30)
    plt.ylabel('Érték', fontsize=30)
    plt.xlabel('CNN modell típusa', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.45, 0.55, 0.65, 0.75, 0.85, 0.95], fontsize=28)
    plt.ylim(0.45, 1)
    plt.legend(fontsize=28, loc='upper center')
    plt.show()
//  [python]
def plot_occ_dfl_results_barplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/occ_dfl_barplot.csv")

    g = sns.factorplot(x="model", y="value", hue='blokkszam', data=df, kind="bar", legend=False, linewidth=2.5,
                 errcolor=".2", edgecolor=".2") 
    sns.despine(top=False, right=False)

    plt.title('OCSVM átlag AUC értéke DFL adathalmaz esetén', fontsize=30)
    plt.ylabel('AUC érték', fontsize=30)
    plt.xlabel('Tanító adathalmaz', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.55, 0.60, 0.65, 0.70, 0.75], fontsize=28)
    plt.ylim(0.55, 0.75)
    plt.legend(fontsize=28, loc='upper right')
    plt.show()
//  [python]
def plot_occ_dfl_results_barplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/occ_dfl_barplot.csv")

    sns.catplot(x="model", y="value", hue='blokkszam', data=df, kind="bar", legend=False, linewidth=2.5,
                 errcolor=".2", edgecolor=".2") 
    sns.despine(top=False, right=False)

    plt.title('OCSVM átlag AUC értéke DFL adathalmaz esetén', fontsize=30)
    plt.ylabel('AUC érték', fontsize=30)
    plt.xlabel('Tanító adathalmaz', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.55, 0.60, 0.65, 0.70, 0.75], fontsize=28)
    plt.ylim(0.55, 0.75)
    plt.legend(fontsize=28, loc='upper right')
    plt.show()
//  [python]
def plot_binary_classification_dfl_results_barplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/binary_classification_dfl_barplot.csv")

    g = sns.factorplot(x="model", y="value", hue='metric', data=df, kind="bar", legend=False, linewidth=2.5,
                 errcolor=".2", edgecolor=".2") 
    sns.despine(top=False, right=False)

    plt.title('Bináris osztályozás átlag eredménye DFL adathalmaz esetén', fontsize=30)
    plt.ylabel('Érték', fontsize=30)
    plt.xlabel('CNN modell típusa', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.45, 0.55, 0.65, 0.75, 0.85, 0.95], fontsize=28)
    plt.ylim(0.45, 1)
    plt.legend(fontsize=28, loc='upper center')
    plt.show()
//  [python]
def plot_binary_classification_dfl_results_barplot():
    df = pd.read_csv("C:/Anaconda projects/Software_mod/evaluationResults/binary_classification_dfl_barplot.csv")

    sns.catplot(x="model", y="value", hue='metric', data=df, kind="bar", legend=False, linewidth=2.5,
                 errcolor=".2", edgecolor=".2") 
    sns.despine(top=False, right=False)

    plt.title('Bináris osztályozás átlag eredménye DFL adathalmaz esetén', fontsize=30)
    plt.ylabel('Érték', fontsize=30)
    plt.xlabel('CNN modell típusa', fontsize=30)
    plt.xticks(fontsize=28)
    plt.yticks([0.45, 0.55, 0.65, 0.75, 0.85, 0.95], fontsize=28)
    plt.ylim(0.45, 1)
    plt.legend(fontsize=28, loc='upper center')
    plt.show()
//  [python]
def plot_shap_components(param, df_shap,height=2, aspect=4,is_normalize=False, config_kwargs={},
                         rc={'lines.linewidth': 2, "xtick.labelsize": 12, "legend.fontsize": 12},
                         is_colorbar=False,
                         **kwargs):
    variable = PRETTY_RENAMER[param]
    shap_prfx = PRETTY_RENAMER["normshap_"] if is_normalize else PRETTY_RENAMER["shap_"]
    other={}

    if is_colorbar:
        kwargs["legend"] = False

    with plot_config(font_scale=1.4,
                     rc=rc,
                     **config_kwargs):

        g=sns.stripplot(data=_prettify_df(df_shap, pretty_renamer=PRETTY_RENAMER),
                      x=f"{shap_prfx}{variable}",
                      y="Component",
                      hue=variable,
                      **kwargs)

        plt.axvline(color = "gray", alpha=0.5, linewidth=1.5)
        for y in g.get_yticks():
            plt.axhline(y=y, color = "gray", alpha=0.5, linewidth=0.5, linestyle=(0, (1, 5)))
        g.set(xlabel=shap_prfx.strip(), ylabel=None)

        if g.get_legend() is not None:
            g.get_legend().set_title(None)

        if is_colorbar:
            HueNorm = type(kwargs.get("hue_norm", plt.Normalize()))
            norm = HueNorm(df_shap[param].min(), df_shap[param].max())
            cmap = sns.cubehelix_palette(light=1, as_cmap=True)
            sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
            sm.set_array([])
            cb = plt.colorbar(sm, pad=0.01, aspect=10, drawedges=False)
            cb.ax.tick_params(labelsize=plt.rcParams["xtick.labelsize"], width=0.5, length=4, which="both")
            cb.outline.set_color('white')
            cb.outline.set_linewidth(2)
            cb.dividers.set_color('white')
            cb.dividers.set_linewidth(2)
            other["colorbar"] = cb

    return g, other
//  [python]
def plot_shap_components(param, df_shap,height=2, aspect=4,is_normalize=False, config_kwargs={},
                         rc={'lines.linewidth': 2, "xtick.labelsize": 12, "legend.fontsize": 12},
                         is_colorbar=False,
                         **kwargs):
    variable = PRETTY_RENAMER[param]
    shap_prfx = PRETTY_RENAMER["normshap_"] if is_normalize else PRETTY_RENAMER["shap_"]
    other={}

    if is_colorbar:
        kwargs["legend"] = False

    with plot_config(font_scale=1.4,
                     rc=rc,
                     **config_kwargs):

        g=sns.catplot(data=_prettify_df(df_shap, pretty_renamer=PRETTY_RENAMER),
                      x=f"{shap_prfx}{variable}",
                      y="Component",
                      hue=variable,
                      aspect=aspect,
                      kind="strip",
                      height=height,
                      **kwargs)

        plt.axvline(color = "gray", alpha=0.5, linewidth=1.5)
        for y in g.ax.get_yticks():
            plt.axhline(y=y, color = "gray", alpha=0.5, linewidth=0.5, linestyle=(0, (1, 5)))
        g.set(xlabel=shap_prfx.strip(), ylabel=None)

        if g._legend is not None:
            g._legend.set_title(None)

        if is_colorbar:
            HueNorm = type(kwargs.get("hue_norm", plt.Normalize()))
            norm = HueNorm(df_shap[param].min(), df_shap[param].max())
            cmap = sns.cubehelix_palette(light=1, as_cmap=True)
            sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
            sm.set_array([])
            cb = g.figure.colorbar(sm, pad=0.01, aspect=10, drawedges=False)
            cb.ax.tick_params(labelsize=plt.rcParams["xtick.labelsize"], width=0.5, length=4, which="both")
            cb.outline.set_color('white')
            cb.outline.set_linewidth(2)
            cb.dividers.set_color('white')
            cb.dividers.set_linewidth(2)
            other["colorbar"] = cb

    return g, other
//  [python]
print("*** Columns: ***", *df.columns, sep='\n')
print("****************")
N = len(df)
print("N", N)
# g = sns.catplot(x='history', y='accuracy', kind='bar', hue='model', data=df)
g = sns.factorplot(x='model', y='accuracy', col='dataset', kind='bar', hue='window', data=df)
//  [python]
print("*** Columns: ***", *df.columns, sep='\n')
print("****************")
N = len(df)
print("N", N)
# g = sns.catplot(x='history', y='accuracy', kind='bar', hue='model', data=df)
g = sns.catplot(x='model', y='accuracy', col='dataset', kind='bar', hue='window', data=df)
//  [python]
def analyze_accuracies_of_base_models():
  """Plot & compare train/test accuracies of base models in CNN collection."""

  logging.info('Analyzing base model accuracies...')

  _, base_model_metrics = load_base_model_weights_and_metrics()

  accuracy_tracker = pd.DataFrame({
      'chkpt': [],
      'accuracy': [],
      'accuracy_type': [],
  })

  for chkpt in [0, 1, 2, 3, 20, 40, 60, 80, 86]:

    indices = base_model_metrics.index[
        base_model_metrics['step'] == chkpt
    ].tolist()

    for accuracy_type in ['train', 'test']:
      chkpt_list = [chkpt] * len(indices)
      accuracy_type_list = [accuracy_type] * len(indices)
      accuracy_list = base_model_metrics.iloc[
          indices
      ][f'{accuracy_type}_accuracy'].to_numpy()

      # Add to accuracy_tracker.
      accuracy_tracker = accuracy_tracker.append(
          pd.DataFrame({
              'chkpt': chkpt_list,
              'accuracy': accuracy_list,
              'accuracy_type': accuracy_type_list,
          }),
          ignore_index=True,
      )

  catplot = sns.violinplot(
      x='chkpt',
      y='accuracy',
      hue='accuracy_type',
      data=accuracy_tracker,
  )
  fig = catplot.get_figure()
  fig.set_size_inches(18, 6)
  fig.savefig(
      gfile.GFile(
          os.path.join(
              config.PLOTS_FOLDER_PATH,
              'base_model_accuracies.png',
          ),
          'wb',
      ),
      dpi=400,
  )
//  [python]
def analyze_accuracies_of_base_models():
  """Plot & compare train/test accuracies of base models in CNN collection."""

  logging.info('Analyzing base model accuracies...')

  _, base_model_metrics = load_base_model_weights_and_metrics()

  accuracy_tracker = pd.DataFrame({
      'chkpt': [],
      'accuracy': [],
      'accuracy_type': [],
  })

  for chkpt in [0, 1, 2, 3, 20, 40, 60, 80, 86]:

    indices = base_model_metrics.index[
        base_model_metrics['step'] == chkpt
    ].tolist()

    for accuracy_type in ['train', 'test']:
      chkpt_list = [chkpt] * len(indices)
      accuracy_type_list = [accuracy_type] * len(indices)
      accuracy_list = base_model_metrics.iloc[
          indices
      ][f'{accuracy_type}_accuracy'].to_numpy()

      # Add to accuracy_tracker.
      accuracy_tracker = accuracy_tracker.append(
          pd.DataFrame({
              'chkpt': chkpt_list,
              'accuracy': accuracy_list,
              'accuracy_type': accuracy_type_list,
          }),
          ignore_index=True,
      )

  catplot = sns.catplot(
      x='chkpt',
      y='accuracy',
      hue='accuracy_type',
      data=accuracy_tracker,
      kind='violin',
  )
  fig = catplot.fig
  fig.set_size_inches(18, 6)
  fig.savefig(
      gfile.GFile(
          os.path.join(
              config.PLOTS_FOLDER_PATH,
              'base_model_accuracies.png',
          ),
          'wb',
      ),
      dpi=400,
  )
//  [python]
def main():
    '''
    Make plot such that x=Temporal gap, y=RMSE, lines=methods
    Band is static, selected to be 13
    '''
    T_range = [5,10,15,20,25,30,35,40,45,]
    N_samples = 20
    band = 13

    stat_file = '.tmp/temporal-stats.pkl'
    force = False

    if (os.path.exists(stat_file)) and (not force):
        all_stats = pd.read_pickle(stat_file)
        all_stats = all_stats.reset_index()
    else:
        pairs = comparison.random_dayhours(N_samples, 2019)
        jobs = []
        for p in pairs:
            for T in T_range:
                jobs.append(delayed(comparison.example_statistics)(2019, p[0], p[1], band, T=T))

        print("number of jobs", len(jobs))
        collect_stats = Parallel(n_jobs=4)(jobs)
        #collect_stats.append(p_stats)
        all_stats = pd.concat(collect_stats)
        all_stats = all_stats.reset_index()
        all_stats.to_pickle(stat_file)
    
    all_stats['Model'][all_stats['Model'] == 'Slomo'] = 'SSM-T'
    all_stats['Model'][all_stats['Model'] == 'Slomo-MS'] = 'SSM-TMS'
    all_stats['Model'][all_stats['Model'] == 'Slomo-G'] = 'SSM-G'

    g = sns.factorplot(x='T', y='PSNR', kind='point', hue='Model', data=all_stats, aspect=1.5,
                size=6, capsize=.05, legend=False)
    plt.xlabel("Temporal Gap Between Images")
    plt.legend(loc='upper right')
    g.despine(left=True)
    plt.savefig("figures/temporal_gap.pdf", dpi=300)
    plt.show()
//  [python]
def main():
    '''
    Make plot such that x=Temporal gap, y=RMSE, lines=methods
    Band is static, selected to be 13
    '''
    T_range = [5,10,15,20,25,30,35,40,45,]
    N_samples = 20
    band = 13

    stat_file = '.tmp/temporal-stats.pkl'
    force = False

    if (os.path.exists(stat_file)) and (not force):
        all_stats = pd.read_pickle(stat_file)
        all_stats = all_stats.reset_index()
    else:
        pairs = comparison.random_dayhours(N_samples, 2019)
        jobs = []
        for p in pairs:
            for T in T_range:
                jobs.append(delayed(comparison.example_statistics)(2019, p[0], p[1], band, T=T))

        print("number of jobs", len(jobs))
        collect_stats = Parallel(n_jobs=4)(jobs)
        #collect_stats.append(p_stats)
        all_stats = pd.concat(collect_stats)
        all_stats = all_stats.reset_index()
        all_stats.to_pickle(stat_file)
    
    all_stats['Model'][all_stats['Model'] == 'Slomo'] = 'SSM-T'
    all_stats['Model'][all_stats['Model'] == 'Slomo-MS'] = 'SSM-TMS'
    all_stats['Model'][all_stats['Model'] == 'Slomo-G'] = 'SSM-G'

    g = sns.catplot(x='T', y='PSNR', kind='point', hue='Model', data=all_stats, aspect=1.5,
                height=6, capsize=.05, legend=False)
    plt.xlabel("Temporal Gap Between Images")
    plt.legend(loc='upper right')
    g.despine(left=True)
    plt.savefig("figures/temporal_gap.pdf", dpi=300)
    plt.show()
//  [python]
def plot_discovered_missed_clusters(dataframe, file_path=''):
  """Plot location clusters comparing agents missed and discovered incidents."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.factorplot(
      x='param_value',
      y='missed_incidents',
      data=dataframe,
      hue='agent_type',
      palette='deep',
      size=plot_height,
      aspect=aspect_ratio,
      s=8,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Missed incidents for each location', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.tight_layout()
  plt.savefig(file_path + '_missed.pdf')

  sns.factorplot(
      x='param_value',
      y='discovered_incidents',
      data=dataframe,
      hue='agent_type',
      size=plot_height,
      aspect=aspect_ratio,
      s=8,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered incidents for each location', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.tight_layout()
  plt.savefig(file_path + '_discovered.pdf')