jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_line(df: Union[pd.Series, pd.DataFrame],
              linestyles: List[str] = None,
              linestyle: Any = '-',
              linewidth: float = 1.0,
              legend_title: str = None,
              legend_loc: Optional[Union[str, bool]] = 'upper left',
              legend_stats: put.LegendStats = put.LegendStats.NONE,
              legend_labels: List[str] = None,
              x_labels: List[str] = None,
              xlabel: str = None,
              ylabel: str = None,
              title: str = None,
              xvar_format: Optional[str] = None,  # '{:,.2f}', # unless data is numerical
              yvar_format: Optional[str] = '{:,.2f}',
              markers: Union[str, List[str]] = False,
              fontsize: int = 10,
              colors: List[str] = None,
              x_limits: Tuple[Optional[float], Optional[float]] = None,
              y_limits: Tuple[Optional[float], Optional[float]] = None,
              ax: plt.Subplot = None,
              **kwargs
              ) -> Optional[plt.Figure]:

    if isinstance(df, pd.DataFrame):
        pass
    elif isinstance(df, pd.Series):
        df = df.to_frame()
    else:
        raise TypeError(f"unsuported data type {type(df)}")

    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = None

    if colors is None:
        colors = put.get_n_colors(n=len(df.columns), **kwargs)

    for i, col in enumerate(df.columns):
        ax.plot(df.index, df[col], color=colors[i], linestyle=linestyle, linewidth=linewidth, marker=markers)

    if title is not None:
        put.set_title(ax=ax, title=title, fontsize=fontsize, **kwargs)

    if legend_loc is not None:
        if legend_labels is None:
            legend_labels = put.get_legend_lines(data=df, legend_stats=legend_stats, var_format=yvar_format)
        put.set_legend(ax=ax,
                       labels=legend_labels,
                       colors=colors,
                       legend_loc=legend_loc,
                       legend_title=legend_title,
                       markers=markers,
                       fontsize=fontsize,
                       **kwargs)

    else:
        ax.legend().set_visible(False)

    if linestyles is not None:
        put.set_linestyles(ax=ax, linestyles=linestyles)

    if y_limits is not None:
        put.set_y_limits(ax=ax, y_limits=y_limits)
    if x_limits is not None:
        put.set_x_limits(ax=ax, x_limits=x_limits)

    put.set_ax_ticks_format(ax=ax, fontsize=fontsize, xvar_format=xvar_format, yvar_format=yvar_format)

    if x_labels is None:
        put.set_ax_ticks_format(ax=ax, fontsize=fontsize, **kwargs)

    put.set_ax_xy_labels(ax=ax, xlabel=xlabel, ylabel=ylabel, fontsize=fontsize, **kwargs)
    put.set_spines(ax=ax, **kwargs)

    return fig
//  [python]
def plot_line(df: Union[pd.Series, pd.DataFrame],
              linestyles: List[str] = None,
              linestyle: Any = '-',
              linewidth: float = 1.0,
              legend_title: str = None,
              legend_loc: Optional[Union[str, bool]] = 'upper left',
              legend_stats: put.LegendStats = put.LegendStats.NONE,
              legend_labels: List[str] = None,
              x_labels: List[str] = None,
              xlabel: str = None,
              ylabel: str = None,
              title: str = None,
              xvar_format: Optional[str] = None,  # '{:,.2f}', # unless data is numerical
              yvar_format: Optional[str] = '{:,.2f}',
              markers: Union[str, List[str]] = False,
              fontsize: int = 10,
              colors: List[str] = None,
              x_limits: Tuple[Optional[float], Optional[float]] = None,
              y_limits: Tuple[Optional[float], Optional[float]] = None,
              ax: plt.Subplot = None,
              **kwargs
              ) -> Optional[plt.Figure]:

    if isinstance(df, pd.DataFrame):
        pass
    elif isinstance(df, pd.Series):
        df = df.to_frame()
    else:
        raise TypeError(f"unsuported data type {type(df)}")

    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = None

    if colors is None:
        colors = put.get_n_colors(n=len(df.columns), **kwargs)

    sns.lineplot(data=df, palette=colors, dashes=False, markers=markers, linestyle=linestyle, linewidth=linewidth, ax=ax)

    if title is not None:
        put.set_title(ax=ax, title=title, fontsize=fontsize, **kwargs)

    if legend_loc is not None:
        if legend_labels is None:
            legend_labels = put.get_legend_lines(data=df, legend_stats=legend_stats, var_format=yvar_format)
        put.set_legend(ax=ax,
                       labels=legend_labels,
                       colors=colors,
                       legend_loc=legend_loc,
                       legend_title=legend_title,
                       markers=markers,
                       fontsize=fontsize,
                       **kwargs)

    else:
        ax.legend().set_visible(False)

    if linestyles is not None:
        put.set_linestyles(ax=ax, linestyles=linestyles)

    if y_limits is not None:
        put.set_y_limits(ax=ax, y_limits=y_limits)
    if x_limits is not None:
        put.set_x_limits(ax=ax, x_limits=x_limits)

    put.set_ax_ticks_format(ax=ax, fontsize=fontsize, xvar_format=xvar_format, yvar_format=yvar_format)

    if x_labels is None:
        put.set_ax_ticks_format(ax=ax, fontsize=fontsize, **kwargs)

    put.set_ax_xy_labels(ax=ax, xlabel=xlabel, ylabel=ylabel, fontsize=fontsize, **kwargs)
    put.set_spines(ax=ax, **kwargs)

    return fig
//  [python]
def main():
    device = get_device()
    esm2_8m_untrained = ESMEmbedder(EmbedderName.esm2_8m)
    esm2_8m_untrained.model = EsmModel(config=CONFIG_ESM2_8M_RANDOM).to(device)
    esm2_8m_untrained.name += "_untrained"
    esm2_650m_untrained = ESMEmbedder(EmbedderName.esm2_650m)
    esm2_650m_untrained.model = EsmModel(config=CONFIG_ESM2_650M_RANDOM).to(device)
    esm2_650m_untrained.name += "_untrained"

    df = pd.concat([
        increase_train_size(esm2_8m_untrained),
        increase_train_size(ESMEmbedder(EmbedderName.esm2_8m)),
        increase_train_size(ESMEmbedder(EmbedderName.esm2_650m)),
        increase_train_size(ProtT5Embedder(EmbedderName.prot_t5_xl)),
        increase_train_size(PhysicalPropertiesPosContextEmbedder(EmbedderName.imgt_aa_ctx_23)),
    ])

    df.to_csv(FILE_PATH.parent / "training_size.csv")

    fig, axs = plt.subplots(1, 1, figsize=(6, 6))
    sns.pointplot(
        df,
        x="fraction",
        y="mean_ap",
        hue="model",
        join=True,
        ax=axs
    )
    axs.set_title(f"Increasing training size for RF head")
    axs.set_xlabel("Fraction of training set")
    axs.set_ylabel("Average Precision")
    axs.set_ylim(0.1, 0.74)
    axs.grid()
    axs.legend(loc="center right", fontsize="6")
    sns.despine(ax=axs)

    plt.tight_layout()
    plt.savefig(FILE_PATH.parent / "training_size.pdf")
    plt.show()
//  [python]
def main():
    device = get_device()
    esm2_8m_untrained = ESMEmbedder(EmbedderName.esm2_8m)
    esm2_8m_untrained.model = EsmModel(config=CONFIG_ESM2_8M_RANDOM).to(device)
    esm2_8m_untrained.name += "_untrained"
    esm2_650m_untrained = ESMEmbedder(EmbedderName.esm2_650m)
    esm2_650m_untrained.model = EsmModel(config=CONFIG_ESM2_650M_RANDOM).to(device)
    esm2_650m_untrained.name += "_untrained"

    df = pd.concat([
        increase_train_size(esm2_8m_untrained),
        increase_train_size(ESMEmbedder(EmbedderName.esm2_8m)),
        increase_train_size(ESMEmbedder(EmbedderName.esm2_650m)),
        increase_train_size(ProtT5Embedder(EmbedderName.prot_t5_xl)),
        increase_train_size(PhysicalPropertiesPosContextEmbedder(EmbedderName.imgt_aa_ctx_23)),
    ])

    df.to_csv(FILE_PATH.parent / "training_size.csv")

    fig, axs = plt.subplots(1, 1, figsize=(6, 6))
    sns.lineplot(
        df,
        x="fraction",
        y="mean_ap",
        hue="model",
        style="model",
        markers=True,
        dashes=False,
        ax=axs
    )
    axs.set_title(f"Increasing training size for RF head")
    axs.set_xlabel("Fraction of training set")
    axs.set_ylabel("Average Precision")
    axs.set_ylim(0.1, 0.74)
    axs.grid()
    axs.legend(loc="center right", fontsize="6")
    sns.despine(ax=axs)

    plt.tight_layout()
    plt.savefig(FILE_PATH.parent / "training_size.pdf")
    plt.show()
//  [python]
def main():
    parser = argparse.ArgumentParser( description='Put a description of your script here')
    parser.add_argument('-i', '--input_file', type=str, required=True, help='Path to an input file to be read' )
    parser.add_argument('-o', '--output_file', type=str, required=True, help='Path to an output file to be created' )
    args = parser.parse_args()

    tpms = list()
    
    with open(args.input_file) as fh:
        # read off the header line
        fh.readline()
        
        for line in fh:
            line = line.rstrip()
            cols = line.split("\t")
            tpms.append(float(cols[4]))

    # stores the count of transcripts at each TPM value or lower
    tpm_c = dict()
    last_tpm = None
    tpm_count = 0

    for tpm in sorted(tpms, reverse=True):
        tpm_count += 1

        if tpm == last_tpm:
            tpm_c[tpm] += 1
        else:
            tpm_c[tpm] = tpm_count

        last_tpm = tpm

    tpm_for_df = dict({'tpm':[], 'count':[]})
    
    for tpm in tpm_c:
        tpm_for_df['tpm'].append(tpm)
        tpm_for_df['count'].append(tpm_c[tpm])
        print("{0}\t{1}".format(tpm, tpm_c[tpm]))

    df = pd.DataFrame(tpm_for_df)

    plt.figure(figsize=(20,9)) 
    lineplot = sns.pointplot(data=df, x='tpm', y='count')
    lineplot.set(xscale="log")
    fig = lineplot.get_figure()
    fig.savefig(args.output_file)
//  [python]
def main():
    parser = argparse.ArgumentParser( description='Put a description of your script here')
    parser.add_argument('-i', '--input_file', type=str, required=True, help='Path to an input file to be read' )
    parser.add_argument('-o', '--output_file', type=str, required=True, help='Path to an output file to be created' )
    args = parser.parse_args()

    tpms = list()
    
    with open(args.input_file) as fh:
        # read off the header line
        fh.readline()
        
        for line in fh:
            line = line.rstrip()
            cols = line.split("\t")
            tpms.append(float(cols[4]))

    # stores the count of transcripts at each TPM value or lower
    tpm_c = dict()
    last_tpm = None
    tpm_count = 0

    for tpm in sorted(tpms, reverse=True):
        tpm_count += 1

        if tpm == last_tpm:
            tpm_c[tpm] += 1
        else:
            tpm_c[tpm] = tpm_count

        last_tpm = tpm

    tpm_for_df = dict({'tpm':[], 'count':[]})
    
    for tpm in tpm_c:
        tpm_for_df['tpm'].append(tpm)
        tpm_for_df['count'].append(tpm_c[tpm])
        print("{0}\t{1}".format(tpm, tpm_c[tpm]))

    df = pd.DataFrame(tpm_for_df)

    plt.figure(figsize=(20,9)) 
    lineplot = sns.lineplot(data=df, x='tpm', y='count')
    lineplot.set(xscale="log")
    fig = lineplot.get_figure()
    fig.savefig(args.output_file)
//  [python]
def plot_density(x: np.array, y: np.array, p: np.array, path: Path, traj = None) -> None:
    plt.pcolormesh(x, y, p.reshape(x.shape),
                   shading='auto',
                   cmap=plt.cm.get_cmap("Greens"),
                   norm=matplotlib.colors.Normalize())
    if traj is not None:
        obs, gt = traj
        plt.plot(gt[:, 0], gt[:, 1], color='black', marker='o')
        plt.plot(obs[:, 0], obs[:, 1], color='green', marker='o')
        
    plt.axis('off')
    plt.gca().set_aspect('equal', adjustable='box')
    plt.savefig(path, bbox_inches='tight')
    plt.close()
//  [python]
def plot_density(x: np.array, y: np.array, p: np.array, path: Path, traj = None) -> None:
    plt.pcolormesh(x, y, p.reshape(x.shape),
                   shading='auto',
                   cmap=plt.cm.get_cmap("Greens"),
                   norm=matplotlib.colors.Normalize())
    if traj is not None:
        obs, gt = traj
        sns.lineplot(x=gt[:, 0], y=gt[:, 1],
                     color='black', marker='o')
        sns.lineplot(x=obs[:, 0], y=obs[:, 1],
                     color='green', marker='o')
        
    plt.axis('off')
    plt.gca().set_aspect('equal', adjustable='box')
    plt.savefig(path, bbox_inches='tight')
    plt.close()
//  [python]
def plot_event_response(local_ts: pd.DataFrame, response_col: str) -> None:
    """
    Plot lineplot of event response curve.

    :param local_ts: output of `core.event_study.core.build_local_timeseries`
    :param response_col: name of response column
    """
    local_ts = local_ts.copy()
    local_ts.index.names = ["grid_index", "event_timestamp"]
    local_ts = local_ts.reset_index()
    plt.plot(local_ts["grid_index"], local_ts[response_col])
    _ = plt.xticks(local_ts["grid_index"].unique())
//  [python]
def plot_event_response(local_ts: pd.DataFrame, response_col: str) -> None:
    """
    Plot lineplot of event response curve.

    :param local_ts: output of `core.event_study.core.build_local_timeseries`
    :param response_col: name of response column
    """
    local_ts = local_ts.copy()
    local_ts.index.names = ["grid_index", "event_timestamp"]
    local_ts = local_ts.reset_index()
    sns.lineplot(x="grid_index", y=response_col, data=local_ts)
    _ = plt.xticks(local_ts["grid_index"].unique())
//  [python]
preds = np.asarray([pred[sensor][timestep].detach().cpu().numpy() for pred in y_hat])
labs  = np.asarray([label[sensor][timestep].cpu().numpy() for label in labels])
print("Data points:,", preds.shape)

plt.figure(figsize=(20,5))
plt.plot(preds, label="pred")
//  [python]
preds = np.asarray([pred[sensor][timestep].detach().cpu().numpy() for pred in y_hat])
labs  = np.asarray([label[sensor][timestep].cpu().numpy() for label in labels])
print("Data points:,", preds.shape)

plt.figure(figsize=(20,5))
sns.lineplot(data=preds, label="pred")
//  [python]
def plot_Data(test_data,Farm):
    temp_err = test_data[test_data['Farm']==Farm].copy()
    plt.figure(figsize=(8, 4))
    num = 480
    farm_name = 'power'
    #plt.plot( temp_err['ws.power'].values[:num], 'r')
    #plt.plot( temp_err[farm_name].values[:num], 'b--')
    #sns.pointplot(  temp_err['ws.power'].values[:num], 'r', markersize=2)
    #sns.pointplot( temp_err[farm_name].values[:num], 'b', markersize=2)
    d1 = temp_err.loc[temp_err.index[:num]]
    d1 = d1.reset_index(drop=True).reset_index()
    plt.plot(d1["index"], d1['wp'], color = "#ff0000")
    plt.plot(d1["index"], d1['power'], dashes=True, color="#0000ff")
    plt.legend(['Predict Power', 'Real Power'])
    plt.xlabel('time')
    plt.ylabel('Wind Power')
    plt.title("Farm {}".format(Farm))
    save_file = join("core","image","Farm_Predict_Data_{}".format(Farm))
    if save_file is not None:
        plt.savefig(save_file, dpi=300, pad_inches = 0,bbox_inches='tight')
    plt.show()
//  [python]
def plot_Data(test_data,Farm):
    temp_err = test_data[test_data['Farm']==Farm].copy()
    plt.figure(figsize=(8, 4))
    num = 480
    farm_name = 'power'
    #plt.plot( temp_err['ws.power'].values[:num], 'r')
    #plt.plot( temp_err[farm_name].values[:num], 'b--')
    #sns.pointplot(  temp_err['ws.power'].values[:num], 'r', markersize=2)
    #sns.pointplot( temp_err[farm_name].values[:num], 'b', markersize=2)
    d1 = temp_err.loc[temp_err.index[:num]]
    d1 = d1.reset_index(drop=True).reset_index()
    sns.lineplot(x="index", y='wp', data=d1,color = "#ff0000")
    ax = sns.lineplot(x="index", y='power', data=d1,dashes=True, color="#0000ff")
    ax.lines[0].set_linestyle("--")
    ax.lines[0].set_linewidth(2)
    plt.legend(['Predict Power', 'Real Power'])
    plt.xlabel('time')
    plt.ylabel('Wind Power')
    plt.title("Farm {}".format(Farm))
    save_file = join("core","image","Farm_Predict_Data_{}".format(Farm))
    if save_file is not None:
        plt.savefig(save_file, dpi=300, pad_inches = 0,bbox_inches='tight')
    plt.show()
//  [python]
def plot_according_to_2pi_domain(x_2pi, df_bin_centers, center_measure, continuous_pred, LDS_pred, num_pred, L, num_datapoints, step_length, title='', plot_derivatives=False, file_name=''):
    name = 'Accent'
    cmap = get_cmap('tab10')
    colors = cmap.colors

    # fig, ax = plt.subplots(dpi=250, figsize=(12, 6.75))
    fig, ax = plt.subplots(dpi=250, figsize=(6.75, 2.5))
    ax.set_prop_cycle(color=colors)

    x_pred_LDS = np.arange(0, num_pred * step_length, step_length) * 2 * L / (num_datapoints) - L
    # x_2pi += L

    x = list(df_bin_centers['Bin Point num'])
    x += [2 * x[-1] - x[-2]]
    y = list(df_bin_centers[center_measure])
    y += [y[0]]
    # y_median = list(df_bin_centers['Bin Median'])
    # y_median += [y_median[0]]

    x_LDS = list(x_pred_LDS)
    x_LDS += [2 * x_LDS[-1] - x_LDS[-2]]
    y_LDS = list(LDS_pred[-2, :])
    y_LDS += [y_LDS[0]]

    # s.lineplot(x=df_bin_centers['Bin Point num'], y=df_bin_centers[center_measure], color='y', linewidth=3, label=center_measure, marker='D', alpha=0.8)
    plt.plot(x, y, color='y', linewidth=3, label=center_measure, marker='D', alpha=0.8)
    # s.lineplot(x=x, y=y_median, color='g', linewidth=1.5, label='Bin Median', marker='*', markersize=7, alpha=0.8)
    #plt.plot(x, y_median, color='g', linewidth=1.5, label='Bin Median', marker='*', markersize=7, alpha=0.8)
    plt.plot(x_2pi, continuous_pred, label='LDS ($\delta t \ll$)', linewidth=2, color='k')

    # s.lineplot(x=x_pred_LDS, y=LDS_pred[-2, :], label=f'LDS ($\delta t = {step_length}$)', marker='o', color='r', linewidth=1)
    plt.plot(x_LDS, y_LDS, label=f'LDS ($\delta t = {step_length}$)', marker='o', color='r', linewidth=1)

    if plot_derivatives:
        # x_pred_LDS += (x_pred_LDS[1] - x_pred_LDS[0]) / 2
        plt.plot(x_pred_LDS[: -1], np.diff(LDS_pred[-2, :]), label=f'diff( LDS ($\delta t = {step_length}$) )', marker='o', color='r', alpha=0.5, linewidth=0.5)
        plt.plot(x_pred_LDS[: -1], LDS_pred[-1, : -1], label='LDS derivative', marker='o', color='k', alpha=0.5, linewidth=0.5)

    xticks = [f'{(bin - 1) / 2 + 1}' if bin % 2 == 0 else f'{int((bin - 1) / 2 + 1)}' for bin in list(range(1, 1 + len(df_bin_centers['Bin Point num']))) + [1]]
    # plt.xticks(df_bin_centers['Bin Point num'], range(1, 1 + len(df_bin_centers['Bin Point num'])))
    # plt.xticks(x, list(range(1, 1 + len(df_bin_centers['Bin Point num']))) + [1])
    plt.xticks(x, xticks)

    # plt.title(title)
    plt.xlabel('Month')
    plt.ylabel('Rainfall (mm)')
    plt.tight_layout()
    plt.legend()

    if file_name:
        plt.savefig(file_name)
    else:
        plt.show()
//  [python]
def plot_according_to_2pi_domain(x_2pi, df_bin_centers, center_measure, continuous_pred, LDS_pred, num_pred, L, num_datapoints, step_length, title='', plot_derivatives=False, file_name=''):
    name = 'Accent'
    cmap = get_cmap('tab10')
    colors = cmap.colors

    # fig, ax = plt.subplots(dpi=250, figsize=(12, 6.75))
    fig, ax = plt.subplots(dpi=250, figsize=(6.75, 2.5))
    ax.set_prop_cycle(color=colors)

    x_pred_LDS = np.arange(0, num_pred * step_length, step_length) * 2 * L / (num_datapoints) - L
    # x_2pi += L

    x = list(df_bin_centers['Bin Point num'])
    x += [2 * x[-1] - x[-2]]
    y = list(df_bin_centers[center_measure])
    y += [y[0]]
    # y_median = list(df_bin_centers['Bin Median'])
    # y_median += [y_median[0]]

    x_LDS = list(x_pred_LDS)
    x_LDS += [2 * x_LDS[-1] - x_LDS[-2]]
    y_LDS = list(LDS_pred[-2, :])
    y_LDS += [y_LDS[0]]

    # sns.lineplot(x=df_bin_centers['Bin Point num'], y=df_bin_centers[center_measure], color='y', linewidth=3, label=center_measure, marker='D', alpha=0.8)
    sns.lineplot(x=x, y=y, color='y', linewidth=3, label=center_measure, marker='D', alpha=0.8)
    # sns.lineplot(x=x, y=y_median, color='g', linewidth=1.5, label='Bin Median', marker='*', markersize=7, alpha=0.8)
    sns.lineplot(x=x_2pi, y=continuous_pred, label='LDS ($\delta t \ll$)', linewidth=2, color='k')

    # sns.lineplot(x=x_pred_LDS, y=LDS_pred[-2, :], label=f'LDS ($\delta t = {step_length}$)', marker='o', color='r', linewidth=1)
    sns.lineplot(x=x_LDS, y=y_LDS, label=f'LDS ($\delta t = {step_length}$)', marker='o', color='r', linewidth=1)

    if plot_derivatives:
        # x_pred_LDS += (x_pred_LDS[1] - x_pred_LDS[0]) / 2
        sns.lineplot(x=x_pred_LDS[: -1], y=np.diff(LDS_pred[-2, :]), label=f'diff( LDS ($\delta t = {step_length}$) )', marker='o', color='r', alpha=0.5, linewidth=0.5)
        sns.lineplot(x=x_pred_LDS[: -1], y=LDS_pred[-1, : -1], label='LDS derivative', marker='o', color='k', alpha=0.5, linewidth=0.5)

    xticks = [f'{(bin - 1) / 2 + 1}' if bin % 2 == 0 else f'{int((bin - 1) / 2 + 1)}' for bin in list(range(1, 1 + len(df_bin_centers['Bin Point num']))) + [1]]
    # plt.xticks(df_bin_centers['Bin Point num'], range(1, 1 + len(df_bin_centers['Bin Point num'])))
    # plt.xticks(x, list(range(1, 1 + len(df_bin_centers['Bin Point num']))) + [1])
    plt.xticks(x, xticks)

    # plt.title(title)
    plt.xlabel('Month')
    plt.ylabel('Rainfall (mm)')
    plt.tight_layout()
    plt.legend()

    if file_name:
        plt.savefig(file_name)
    else:
        plt.show()
//  [python]
def draw_boxplot(data, **kw):
    df = data[["Time", "Distance"]]
    seaborn.pointplot(x=df["Distance"], y=df["Time"])
//  [python]
def draw_boxplot(data, **kw):
    df = data[["Time", "Distance"]]
    seaborn.lineplot(x=df["Distance"], y=df["Time"])
//  [python]
def reward_timeseries_plot(self) -> None:
        """
        Generates a timeseries plot of the average reward
        recieved during each stage of the simulation process.
        """
        sns.set_style("darkgrid")
        ax = sns.tsplot(data=self.average_reward_timeseries)

        plt.axhline(
            y=self.bandit_collection.optimal_bandit.parameter_hat,
            color="r",
            linestyle="-",
            label="Optimal Bandit Estimated Parameter",
        )
        plt.axhline(
            y=self.bandit_collection.optimal_bandit.parameter,
            color="g",
            linestyle="--",
            label="Optimal Bandit True Parameter",
        )

        ax.set(
            title="Simulation Reward Over Time",
            xlabel="Simulation Number",
            ylabel="Average Reward",
        )

        plt.legend()
        plt.show()
//  [python]
def reward_timeseries_plot(self) -> None:
        """
        Generates a timeseries plot of the average reward
        recieved during each stage of the simulation process.
        """
        sns.set_style("darkgrid")
        ax = sns.lineplot(data=self.average_reward_timeseries)

        plt.axhline(
            y=self.bandit_collection.optimal_bandit.parameter_hat,
            color="r",
            linestyle="-",
            label="Optimal Bandit Estimated Parameter",
        )
        plt.axhline(
            y=self.bandit_collection.optimal_bandit.parameter,
            color="g",
            linestyle="--",
            label="Optimal Bandit True Parameter",
        )

        ax.set(
            title="Simulation Reward Over Time",
            xlabel="Simulation Number",
            ylabel="Average Reward",
        )

        plt.legend()
        plt.show()
//  [python]
def plot_qsp_response(f, model=None, phis=None, title="QSP Response"):
    """Plot the QSP response againts the desired function response.

    Params
    ------
    f : function float --> float
            the desired function to be implemented by the QSP sequence
    model : Keras `Model` with `QSP` layer
            model trained to approximate f
    phis: numpy array of qsp phase angles (may be supplied instead of model)
    title: plot title (str)
    """
    qsp_response, all_th, circuit_px, circuit_qx = compute_qsp_response(
        model=model, phis=phis, return_all=True)

    pdata = {
        "x": np.cos(all_th),
        "Imag[p(x)]": np.imag(circuit_px),
        "Real[p(x)]": np.real(circuit_px),
        "Real[q(x)]": np.real(circuit_qx),
        "QSP Response": np.real(qsp_response)}
    if f is not None:
        pdata["desired f"] = f(np.cos(all_th))
    df = pd.DataFrame(pdata)
    df = df.melt("x", var_name="src", value_name="value")
    sns.plt.plot(x="x", y="value", data=df[df.src == 'desired f'], label='desired f')
    sns.plt.plot(x="x", y="value", data=df[df.src == 'QSP Response'], label='QSP Response')
    sns.plt.plot(x="x", y="value", data=df[df.src == 'Real[p(x)]'], label='Real[p(x)]')
    sns.plt.plot(x="x", y="value", data=df[df.src == 'Real[q(x)]'], label='Real[q(x)]')
    sns.plt.plot(x="x", y="value", data=df[df.src == 'Imag[p(x)]'], label='Imag[p(x)]')
    sns.plt.legend()
    sns.plt.title(title)
    plt.show()
//  [python]
def plot_qsp_response(f, model=None, phis=None, title="QSP Response"):
    """Plot the QSP response againts the desired function response.

    Params
    ------
    f : function float --> float
            the desired function to be implemented by the QSP sequence
    model : Keras `Model` with `QSP` layer
            model trained to approximate f
    phis: numpy array of qsp phase angles (may be supplied instead of model)
    title: plot title (str)
    """
    qsp_response, all_th, circuit_px, circuit_qx = compute_qsp_response(
        model=model, phis=phis, return_all=True)

    pdata = {
        "x": np.cos(all_th),
        "Imag[p(x)]": np.imag(circuit_px),
        "Real[p(x)]": np.real(circuit_px),
        "Real[q(x)]": np.real(circuit_qx),
        "QSP Response": np.real(qsp_response)}
    if f is not None:
        pdata["desired f"] = f(np.cos(all_th))
    df = pd.DataFrame(pdata)
    df = df.melt("x", var_name="src", value_name="value")
    sns.lineplot(x="x", y="value", hue="src", data=df).set_title(title)
    plt.show()
//  [python]
def linkage_decay_plot(db, chunkSize=5, min_vals=5, title=''):
    COLS = ['r2', 'r2_normalized', 'd_prime', 'd_prime_normalized']
    sns.set_style('white')

    # Make chunks
    max_d = db['distance'].max()
    table = defaultdict(list)
    numberChunks = max_d // chunkSize + 1
    #db['distance'] = db['distance'].astype(int)
    db = db.astype({'distance': int})
    for i in range(numberChunks):
        d = db[(db['distance'] >= int(i*chunkSize)) & (db['distance'] < int((i+1)*chunkSize))]

        table['d_start'].append(int(i*chunkSize))
        table['d_end'].append(int((i+1)*chunkSize))
        table['values'].append(len(d))
        for col in COLS:
            table[col].append(d[col].mean())
            table[col + '_values'].append(len(d[~d[col].isna()]))
    df = pd.DataFrame(table)
    df.loc[:,'distance'] = [np.mean([x, y]) for x, y in zip(df['d_start'], df['d_end'])]
    df = df.sort_values('distance')

    for col in COLS:
        df[col] = [c if v >= min_vals else np.nan for c, v in zip(df[col], df[col + '_values'])]

    for col in COLS:
        plt.plot(df['distance'], df[col], label=col, marker='o')

    plt.title(title)
    plt.xlabel('Distance between SNPs (bp)\nAveraged over {0}bp windows; plotting windows with at least {1} values'.format(
                chunkSize, min_vals))
    plt.ylabel("SNP linkage")
    return df
//  [python]
def linkage_decay_plot(db, chunkSize=5, min_vals=5, title=''):
    COLS = ['r2', 'r2_normalized', 'd_prime', 'd_prime_normalized']
    sns.set_style('white')

    # Make chunks
    max_d = db['distance'].max()
    table = defaultdict(list)
    numberChunks = max_d // chunkSize + 1
    #db['distance'] = db['distance'].astype(int)
    db = db.astype({'distance': int})
    for i in range(numberChunks):
        d = db[(db['distance'] >= int(i*chunkSize)) & (db['distance'] < int((i+1)*chunkSize))]

        table['d_start'].append(int(i*chunkSize))
        table['d_end'].append(int((i+1)*chunkSize))
        table['values'].append(len(d))
        for col in COLS:
            table[col].append(d[col].mean())
            table[col + '_values'].append(len(d[~d[col].isna()]))
    df = pd.DataFrame(table)
    df.loc[:,'distance'] = [np.mean([x, y]) for x, y in zip(df['d_start'], df['d_end'])]
    df = df.sort_values('distance')

    for col in COLS:
        df[col] = [c if v >= min_vals else np.nan for c, v in zip(df[col], df[col + '_values'])]

    for col in COLS:
        sns.lineplot(x=df['distance'], y=df[col], label=col, marker='o')

    plt.title(title)
    plt.xlabel('Distance between SNPs (bp)\nAveraged over {0}bp windows; plotting windows with at least {1} values'.format(
                chunkSize, min_vals))
    plt.ylabel("SNP linkage")
    return df
//  [python]
def cumulative_reward_timeseries_plot(self) -> None:
        """
        Generates a timeseries plot of the cumulative reward
        recieved during each stage of the simulation process.

        This includes lines of expected cumulatove reward over all
        bandits, as well as best and worst parameters.
        """
        best_expected_parameter = np.max(self.bandit_collection.true_parameters)
        worst_expected_parameter = np.min(self.bandit_collection.true_parameters)
        avg_expected_parameter = np.mean(self.bandit_collection.true_parameters)

        cumulative_rewards = pd.DataFrame(
            {
                "True Cumulative Reward": list(
                    np.cumsum(
                        [result["value"] for result in self.bandit_collection.results]
                    )
                ),
                "Expected Average Reward": [
                    avg_expected_parameter * sim for sim in range(self.num_simulations)
                ],
                "Expected Best Reward": [
                    best_expected_parameter * sim for sim in range(self.num_simulations)
                ],
                "Expected Worst Reward": [
                    worst_expected_parameter * sim
                    for sim in range(self.num_simulations)
                ],
            }
        )
        ax = sns.tsplot(data=cumulative_rewards)

        ax.set(
            title="Simulation Cumulative Reward",
            xlabel="Simulation Number",
            ylabel="Cumulative Reward",
        )

        plt.legend()
        plt.show()
//  [python]
def cumulative_reward_timeseries_plot(self) -> None:
        """
        Generates a timeseries plot of the cumulative reward
        recieved during each stage of the simulation process.

        This includes lines of expected cumulatove reward over all
        bandits, as well as best and worst parameters.
        """
        best_expected_parameter = np.max(self.bandit_collection.true_parameters)
        worst_expected_parameter = np.min(self.bandit_collection.true_parameters)
        avg_expected_parameter = np.mean(self.bandit_collection.true_parameters)

        cumulative_rewards = pd.DataFrame(
            {
                "True Cumulative Reward": list(
                    np.cumsum(
                        [result["value"] for result in self.bandit_collection.results]
                    )
                ),
                "Expected Average Reward": [
                    avg_expected_parameter * sim for sim in range(self.num_simulations)
                ],
                "Expected Best Reward": [
                    best_expected_parameter * sim for sim in range(self.num_simulations)
                ],
                "Expected Worst Reward": [
                    worst_expected_parameter * sim
                    for sim in range(self.num_simulations)
                ],
            }
        )
        ax = sns.lineplot(data=cumulative_rewards)

        ax.set(
            title="Simulation Cumulative Reward",
            xlabel="Simulation Number",
            ylabel="Cumulative Reward",
        )

        plt.legend()
        plt.show()
//  [python]
def plot_results(results_df):
    """Generates and saves and lineplot with one line indicating RMSE scores
    for each model and one line indicating MAE scores for each model.
    """
    fig, ax = plt.subplots(figsize=(12, 5))
    sns.pointplot(np.arange(len(results_df)), 'RMSE', data=results_df, ax=ax,
                 label='RMSE', color='mediumblue', linestyles='-')
    sns.pointplot(np.arange(len(results_df)), 'MAE', data=results_df, ax=ax,
                 label='MAE', color='Cyan', linestyles='-')

    plt.xticks(np.arange(len(results_df)), rotation=45)
    ax.set_xticklabels(results_df['index'])
    ax.set(xlabel="Model",
           ylabel="Scores",
           title="Model Error Comparison")
    sns.despine()

    plt.savefig(f'../model_output/compare_models.png')
//  [python]
def plot_results(results_df):
    """Generates and saves and lineplot with one line indicating RMSE scores
    for each model and one line indicating MAE scores for each model.
    """
    fig, ax = plt.subplots(figsize=(12, 5))
    sns.lineplot(np.arange(len(results_df)), 'RMSE', data=results_df, ax=ax,
                 label='RMSE', color='mediumblue')
    sns.lineplot(np.arange(len(results_df)), 'MAE', data=results_df, ax=ax,
                 label='MAE', color='Cyan')

    plt.xticks(np.arange(len(results_df)), rotation=45)
    ax.set_xticklabels(results_df['index'])
    ax.set(xlabel="Model",
           ylabel="Scores",
           title="Model Error Comparison")
    sns.despine()

    plt.savefig(f'../model_output/compare_models.png')
//  [python]
def linkage_decay_type(Odb, chunkSize=5, min_vals=2, title=''):
    sns.set_style('white')

    COLS = ['r2', 'r2_normalized', 'd_prime', 'd_prime_normalized']

    # Make chunks
    max_d = Odb['distance'].max()
    table = defaultdict(list)
    numberChunks = max_d // chunkSize + 1
    for lt in ['S=S', 'N-N', 'all']:
        if lt == 'all':
            db = Odb
        else:
            db = Odb[Odb['link_type'] == lt]

        #db['distance'] = db['distance'].astype(int)
        db = db.astype({'distance':int})
        for i in range(numberChunks):
            d = db[(db['distance'] >= int(i*chunkSize)) & (db['distance'] < int((i+1)*chunkSize))]

            table['d_start'].append(int(i*chunkSize))
            table['d_end'].append(int((i+1)*chunkSize))
            table['values'].append(len(d))
            table['link_type'].append(lt)
            for col in COLS:
                table[col].append(d[col].mean())
                table[col + '_values'].append(len(d[~d[col].isna()]))
    df = pd.DataFrame(table)
    df.loc[:,'distance'] = [np.mean([x, y]) for x, y in zip(df['d_start'], df['d_end'])]
    df = df.sort_values('distance')

    for thing in ['S-S', 'N-N', 'all']:
        if thing == 'all':
            fdb = df
        else:
            fdb = df[df['link_type'] == thing]
        plt.plot(fdb['distance'], fdb['r2'], label=thing, marker='o')

    plt.title(title)
    plt.xlabel('Distance between SNPs (bp)\nAveraged over {0}bp windows; plotting windows with at least {1} values'.format(
                chunkSize, min_vals))
    plt.ylabel("SNP linkage")
    plt.legend()
    return df
//  [python]
def linkage_decay_type(Odb, chunkSize=5, min_vals=2, title=''):
    sns.set_style('white')

    COLS = ['r2', 'r2_normalized', 'd_prime', 'd_prime_normalized']

    # Make chunks
    max_d = Odb['distance'].max()
    table = defaultdict(list)
    numberChunks = max_d // chunkSize + 1
    for lt in ['S=S', 'N-N', 'all']:
        if lt == 'all':
            db = Odb
        else:
            db = Odb[Odb['link_type'] == lt]

        #db['distance'] = db['distance'].astype(int)
        db = db.astype({'distance':int})
        for i in range(numberChunks):
            d = db[(db['distance'] >= int(i*chunkSize)) & (db['distance'] < int((i+1)*chunkSize))]

            table['d_start'].append(int(i*chunkSize))
            table['d_end'].append(int((i+1)*chunkSize))
            table['values'].append(len(d))
            table['link_type'].append(lt)
            for col in COLS:
                table[col].append(d[col].mean())
                table[col + '_values'].append(len(d[~d[col].isna()]))
    df = pd.DataFrame(table)
    df.loc[:,'distance'] = [np.mean([x, y]) for x, y in zip(df['d_start'], df['d_end'])]
    df = df.sort_values('distance')

    for thing in ['S-S', 'N-N', 'all']:
        if thing == 'all':
            fdb = df
        else:
            fdb = df[df['link_type'] == thing]
        sns.lineplot(data=fdb, x='distance', y='r2', label=thing, marker='o')

    plt.title(title)
    plt.xlabel('Distance between SNPs (bp)\nAveraged over {0}bp windows; plotting windows with at least {1} values'.format(
                chunkSize, min_vals))
    plt.ylabel("SNP linkage")
    return df
//  [python]
def show_line(self, on, groupby, filename="line.png", title="Line"):
        log.d("DataAnalysis show line plot of {} on {}".format(self.dataset_name, on))
        start = time.time()

        title = "{} {}".format(self.title_prefix, title)
        fig, ax = plt.subplots()
        x, y, z = None, None, None
        if len(on) == 3:
            x, y, z = on
            title = "{}, {} and {} ".format(x, y, z) + title
            unique = self.x[z].unique()
            palette = dict(zip(unique, sns.color_palette(PALETTE, n_colors=len(unique))))
            for _, g in self.x.groupby(by=groupby):
                sns.plt.plot(x, y, data=g, label=z)
        elif len(on) == 2:
            x, y = on
            title = "{} and {} ".format(x, y) + title
            palette = sns.color_palette(n_colors=1)[0]
            for _, g in self.x.groupby(by=groupby):
                sns.plt.plot(x, y, data=g[[x, y]])
        else:
            log.e("show_line parameter error: \"on\" size {}".format(len(on)))
            return self

        fig.suptitle(title)

        if self.save_file:
            if z is None:
                filename = self.filename_prefix + "-{}-{}-_".format(x, y) + filename
            else:
                filename = self.filename_prefix + "-{}-{}-{}-_".format(x, y, z) + filename
            fig.savefig(os.path.join(self.image_folder, filename))

        plt.show()

        end = time.time()
        log.d("elapsed time: {}".format(get_elapsed(start, end)))
        return self
//  [python]
def show_line(self, on, groupby, filename="line.png", title="Line"):
        log.d("DataAnalysis show line plot of {} on {}".format(self.dataset_name, on))
        start = time.time()

        title = "{} {}".format(self.title_prefix, title)
        fig, ax = plt.subplots()
        x, y, z = None, None, None
        if len(on) == 3:
            x, y, z = on
            title = "{}, {} and {} ".format(x, y, z) + title
            unique = self.x[z].unique()
            palette = dict(zip(unique, sns.color_palette(PALETTE, n_colors=len(unique))))
            for _, g in self.x.groupby(by=groupby):
                sns.lineplot(x=x, y=y, hue=z, estimator=None, data=g, legend=False, sort=False, palette=palette, ax=ax)
        elif len(on) == 2:
            x, y = on
            title = "{} and {} ".format(x, y) + title
            palette = sns.color_palette(n_colors=1)[0]
            for _, g in self.x.groupby(by=groupby):
                sns.lineplot(x=x, y=y, estimator=None, data=g[[x, y]], legend=False, sort=False, color=palette, ax=ax)
        else:
            log.e("show_line parameter error: \"on\" size {}".format(len(on)))
            return self

        fig.suptitle(title)

        if self.save_file:
            if z is None:
                filename = self.filename_prefix + "-{}-{}-_".format(x, y) + filename
            else:
                filename = self.filename_prefix + "-{}-{}-{}-_".format(x, y, z) + filename
            fig.savefig(os.path.join(self.image_folder, filename))

        plt.show()

        end = time.time()
        log.d("elapsed time: {}".format(get_elapsed(start, end)))
        return self
//  [python]
sns.set(font_scale=1.3, style='white')


if __name__ == '__main__':
    fig, ax = plt.subplots(1, 2, sharex=True, figsize=(6,3))
    df = pd.read_csv("~/Downloads/run-vampire_AG_log_validation-tag-npmi.csv") 
    df1 = pd.read_csv("~/Downloads/run-vampire_AG_log_validation-tag-nll.csv")
    sns.tsplot(time="Step", value="Value", data=df1, ax=ax[0])
    sns.tsplot(time="Step", value="Value", data=df, ax=ax[1])
    ax[1].set_xlabel("Epoch")
    ax[0].set_ylabel("NLL")
    ax[1].set_ylabel("NPMI")
    plt.tight_layout()
    plt.savefig("curves.pdf")
//  [python]
sns.set(font_scale=1.3, style='white')


if __name__ == '__main__':
    fig, ax = plt.subplots(1, 2, sharex=True, figsize=(6,3))
    df = pd.read_csv("~/Downloads/run-vampire_AG_log_validation-tag-npmi.csv") 
    df1 = pd.read_csv("~/Downloads/run-vampire_AG_log_validation-tag-nll.csv")
    sns.lineplot(df1['Step'], df1['Value'], ax=ax[0])
    sns.lineplot(df['Step'], df['Value'], ax=ax[1])
    ax[1].set_xlabel("Epoch")
    ax[0].set_ylabel("NLL")
    ax[1].set_ylabel("NPMI")
    plt.tight_layout()
    plt.savefig("curves.pdf")
//  [python]
def _calculate(self, df: pd.DataFrame, ax: list[plt.Axes]) -> pd.Series:
        df = df.merge(_fetch_df(), on='Date', how='left')
        df['Top'] = df['Top'].ffill()
        df['TopLog'] = np.log(df['Top'])
        df['CVDD'] = df['CVDD'].ffill()
        df['CVDDLog'] = np.log(df['CVDD'])

        df['Woobull'] = (df['PriceLog'] - df['CVDDLog']) / (df['TopLog'] - df['CVDDLog'])

        high_rows = df.loc[df['PriceHigh'] == 1]
        high_x = high_rows.index.values.reshape(-1, 1)
        high_y = high_rows['Woobull'].values.reshape(-1, 1)

        low_rows = df.loc[df['PriceLow'] == 1][1:]
        low_x = low_rows.index.values.reshape(-1, 1)
        low_y = low_rows['Woobull'].values.reshape(-1, 1)

        x = df.index.values.reshape(-1, 1)

        lin_model = LinearRegression()
        lin_model.fit(high_x, high_y)
        df['HighModel'] = lin_model.predict(x)
        df['HighModel'] = df['HighModel'] - 0.025

        lin_model.fit(low_x, low_y)
        df['LowModel'] = lin_model.predict(x)

        df['WoobullIndex'] = (df['Woobull'] - df['LowModel']) / (df['HighModel'] - df['LowModel'])

        ax[0].set_title(self.description)
        plt.plot(df['Date'], df['WoobullIndex'], ax=ax[0])
        add_common_markers(df, ax[0])

        plt.plot(df['Date'], df['Woobull'], ax=ax[1])
        plt.plot(df['Date'], df['HighModel'], ax=ax[1])
        plt.plot(df['Date'], df['LowModel'], ax=ax[1])
        add_common_markers(df, ax[1], price_line=False)

        return df['WoobullIndex']
//  [python]
def _calculate(self, df: pd.DataFrame, ax: list[plt.Axes]) -> pd.Series:
        df = df.merge(_fetch_df(), on='Date', how='left')
        df['Top'] = df['Top'].ffill()
        df['TopLog'] = np.log(df['Top'])
        df['CVDD'] = df['CVDD'].ffill()
        df['CVDDLog'] = np.log(df['CVDD'])

        df['Woobull'] = (df['PriceLog'] - df['CVDDLog']) / (df['TopLog'] - df['CVDDLog'])

        high_rows = df.loc[df['PriceHigh'] == 1]
        high_x = high_rows.index.values.reshape(-1, 1)
        high_y = high_rows['Woobull'].values.reshape(-1, 1)

        low_rows = df.loc[df['PriceLow'] == 1][1:]
        low_x = low_rows.index.values.reshape(-1, 1)
        low_y = low_rows['Woobull'].values.reshape(-1, 1)

        x = df.index.values.reshape(-1, 1)

        lin_model = LinearRegression()
        lin_model.fit(high_x, high_y)
        df['HighModel'] = lin_model.predict(x)
        df['HighModel'] = df['HighModel'] - 0.025

        lin_model.fit(low_x, low_y)
        df['LowModel'] = lin_model.predict(x)

        df['WoobullIndex'] = (df['Woobull'] - df['LowModel']) / (df['HighModel'] - df['LowModel'])

        ax[0].set_title(self.description)
        sns.lineplot(data=df, x='Date', y='WoobullIndex', ax=ax[0])
        add_common_markers(df, ax[0])

        sns.lineplot(data=df, x='Date', y='Woobull', ax=ax[1])
        sns.lineplot(data=df, x='Date', y='HighModel', ax=ax[1])
        sns.lineplot(data=df, x='Date', y='LowModel', ax=ax[1])
        add_common_markers(df, ax[1], price_line=False)

        return df['WoobullIndex']
//  [python]
def draw_line_plot():
    # Draw line plot
    fig, ax = plt.subplots(figsize=(16, 6))

    ax = sns.pointplot(data=df, x="date", y="value")

    ax.set(
        xlabel="Date",
        ylabel="Page Views",
    )

    ax.set_title("Daily freeCodeCamp Forum Page Views 5/2016-12/2019")

    return fig
//  [python]
def draw_line_plot():
    # Draw line plot
    fig, ax = plt.subplots(figsize=(16, 6))

    ax = sns.lineplot(data=df, x="date", y="value")

    ax.set(
        xlabel="Date",
        ylabel="Page Views",
    )

    ax.set_title("Daily freeCodeCamp Forum Page Views 5/2016-12/2019")

    return fig
//  [python]
def plot_time_and_percentile(results : dict, filename : str, unit : str) :
        plt.cla()
        plt.clf()
        sns.set(style="whitegrid")
        fig, (ax1, ax2) = plt.subplots(2)
        plt.gcf().set_size_inches((6.4,9.6))
        ax1.set_title("timedata")
        ax2.set_title("percentile")
        ax1.set(xlabel='iteration')
        ax1.set(ylabel='time ({})'.format(unit))
        ax2.set(xlabel='n-th percentile')
        ax2.set(ylabel='time ({})'.format(unit))
        p = np.arange(100)
        percentile, data = results['percentile'], results['data']
        median, mean = results['median'], results['mean']
        mean_x = np.abs(percentile-mean).argmin()
        p_90 = percentile[90]
        timedata = pd.DataFrame(data, index=range(len(data)), columns=["timedata"])
        sns.pointplot(data=timedata, palette="tab10", linewidth=0.15, ax=ax1)
        ax2.plot(p, percentile,label='percentile')
        ax2.scatter(
            50, median, linestyle=':', 
            label='median ({0:.2f})'.format(median)
        )
        ax2.scatter(
            90, p_90, linestyle=':', 
            label='90-th percentile ({0:.2f})'.format(p_90)
        )
        ax2.scatter(
            np.abs(percentile-mean).argmin(),
            mean, label='mean ({0:.2f})'.format(mean)
        )
        ax2.legend()
        plt.autoscale()
        plt.tight_layout()
        plt.savefig(filename)
        plt.gcf().set_size_inches((6.4,4.8)) ## reset back to matplotlib default
        sns.reset_defaults()
//  [python]
def plot_time_and_percentile(results : dict, filename : str, unit : str) :
        plt.cla()
        plt.clf()
        sns.set(style="whitegrid")
        fig, (ax1, ax2) = plt.subplots(2)
        plt.gcf().set_size_inches((6.4,9.6))
        ax1.set_title("timedata")
        ax2.set_title("percentile")
        ax1.set(xlabel='iteration')
        ax1.set(ylabel='time ({})'.format(unit))
        ax2.set(xlabel='n-th percentile')
        ax2.set(ylabel='time ({})'.format(unit))
        p = np.arange(100)
        percentile, data = results['percentile'], results['data']
        median, mean = results['median'], results['mean']
        mean_x = np.abs(percentile-mean).argmin()
        p_90 = percentile[90]
        timedata = pd.DataFrame(data, index=range(len(data)), columns=["timedata"])
        sns.lineplot(data=timedata, palette="tab10", linewidth=0.15, ax=ax1)
        ax2.plot(p, percentile,label='percentile')
        ax2.scatter(
            50, median, linestyle=':', 
            label='median ({0:.2f})'.format(median)
        )
        ax2.scatter(
            90, p_90, linestyle=':', 
            label='90-th percentile ({0:.2f})'.format(p_90)
        )
        ax2.scatter(
            np.abs(percentile-mean).argmin(),
            mean, label='mean ({0:.2f})'.format(mean)
        )
        ax2.legend()
        plt.autoscale()
        plt.tight_layout()
        plt.savefig(filename)
        plt.gcf().set_size_inches((6.4,4.8)) ## reset back to matplotlib default
        sns.reset_defaults()
//  [python]
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.patch.set_facecolor('lightgray')
ax.patch.set_alpha(0.4)
s.lineplot(data = data, x = data.index , y = "Meters_Error", marker="o", color='r')
//  [python]
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.patch.set_facecolor('lightgray')
ax.patch.set_alpha(0.4)
sns.lineplot(data = data, x = data.index , y = "Meters_Error", marker="o", color='r')