jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_results_game(experimental_data, title, game, agent_name, num_steps_per_iteration, num_iter, savefig=False, legend_loc=legend_loc, bc_file=None):
    fig, ax = plt.subplots(figsize=(15,10))
    sns.tsplot(data=experimental_data, time='iteration', unit='run_number',
             condition='agent', value='train_episode_reward', ax=ax)
    ### plot demonstration and BC baseline
    demo_score = CONFIGS[game]['demo_score']
    x = [i for i in range(num_iter)]
    y = [demo_score for _ in x] 
    ax.plot(x, y, label='Demonstration', marker='*',color='grey')
    if bc_file is not None:
        bc_mean, bc_std = get_bc_score(game, agent_name, bc_file)
        x = [i for i in range(num_iter)]
        y = [bc_mean for _ in x] 
        ax.plot(x, y, label='BC', marker='.')


    fontsize = 22
    title_fontsize = 20
    for tick in ax.xaxis.get_major_ticks():
        tick.label1.set_fontsize(fontsize)
        tick.label1.set_fontweight('bold')
    for tick in ax.yaxis.get_major_ticks():
        tick.label1.set_fontsize(fontsize)
        tick.label1.set_fontweight('bold')

    yaxis_label, xaxis_label = "Returns", "Steps ({}K)".format(int(num_steps_per_iteration //1000))
    fontsize = "30"
    title_axis_font = {'size': title_fontsize, 'weight': 'bold'}
    xylabel_axis_font = {'size': fontsize, 'weight': 'bold'}
    ax.set_ylabel(yaxis_label, **xylabel_axis_font)
    ax.set_xlabel(xaxis_label, **xylabel_axis_font)
    ax.set_title(title, **title_axis_font)
    legend_properties = {'weight':'bold','size':"18"}
    ax.legend(loc=legend_loc, prop=legend_properties)
    ax.legend(loc=legend_loc, prop=legend_properties)

    # plt.show()
    if savefig:
        title = title.replace(" ", "") 
        plt.savefig('../figs/{}.pdf'.format(title))
        plt.savefig('../figs/{}.eps'.format(title),format='eps')
        plt.close()
    else:
        plt.show()

    print("Figure {}.pdf saved to {}".format(title, "../figs/"))
    return experimental_data
//  [python]
def plot_results_game(experimental_data, title, game, agent_name, num_steps_per_iteration, num_iter, savefig=False, legend_loc=legend_loc, bc_file=None):
    fig, ax = plt.subplots(figsize=(15,10))
    sns.lineplot(data=experimental_data, x='iteration', y='train_episode_reward', hue='agent', units='run_number', estimator=None, ax=ax)
    ### plot demonstration and BC baseline
    demo_score = CONFIGS[game]['demo_score']
    x = [i for i in range(num_iter)]
    y = [demo_score for _ in x] 
    ax.plot(x, y, label='Demonstration', marker='*',color='grey')
    if bc_file is not None:
        bc_mean, bc_std = get_bc_score(game, agent_name, bc_file)
        x = [i for i in range(num_iter)]
        y = [bc_mean for _ in x] 
        ax.plot(x, y, label='BC', marker='.')


    fontsize = 22
    title_fontsize = 20
    for tick in ax.xaxis.get_major_ticks():
        tick.label1.set_fontsize(fontsize)
        tick.label1.set_fontweight('bold')
    for tick in ax.yaxis.get_major_ticks():
        tick.label1.set_fontsize(fontsize)
        tick.label1.set_fontweight('bold')

    yaxis_label, xaxis_label = "Returns", "Steps ({}K)".format(int(num_steps_per_iteration //1000))
    fontsize = "30"
    title_axis_font = {'size': title_fontsize, 'weight': 'bold'}
    xylabel_axis_font = {'size': fontsize, 'weight': 'bold'}
    ax.set_ylabel(yaxis_label, **xylabel_axis_font)
    ax.set_xlabel(xaxis_label, **xylabel_axis_font)
    ax.set_title(title, **title_axis_font)
    legend_properties = {'weight':'bold','size':"18"}
    ax.legend(loc=legend_loc, prop=legend_properties)
    ax.legend(loc=legend_loc, prop=legend_properties)

    # plt.show()
    if savefig:
        title = title.replace(" ", "") 
        plt.savefig('../figs/{}.pdf'.format(title))
        plt.savefig('../figs/{}.eps'.format(title),format='eps')
        plt.close()
    else:
        plt.show()

    print("Figure {}.pdf saved to {}".format(title, "../figs/"))
    return experimental_data
//  [python]
sns.set(rc={'figure.figsize':(10,9)})

results_1, time = getdata(FILE)
fig = plt.figure()

# Plot each line.
sns.tsplot(
    condition='ILPO', time=time, data=results_1, color='b', linestyle='-', err_style='ci_band', interpolate=False, legend=True)
//  [python]
sns.set(rc={'figure.figsize':(10,9)})

results_1, time = getdata(FILE)
fig = plt.figure()

sns.lineplot(
    x=time, y='ILPO', data=results_1, color='b', err_style='band', legend=True)
//  [python]
def plot_data(
    data, xaxis, value, condition, fig, i, ylabel, xlabel, smooth=1, **kwargs
):
    if smooth > 1:
        y = np.ones(smooth)
        for datum in data:
            x = np.asarray(datum[value])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x, y, "same") / np.convolve(z, y, "same")
            datum[value] = smoothed_x

    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)

    sns.set(style="darkgrid", rc=params)

    axes = fig.add_subplot(3, 1, i)
    sns.tsplot(
        data=data,
        time=xaxis,
        value=value,
        unit="Unit",
        condition=condition,
        ci="sd",
        linewidth=0.75,
        **kwargs,
    )

    if i == 1:
        plt.rcParams.update(params)
        plt.legend(
            handlelength=1,
            handleheight=0.0,
            bbox_to_anchor=(0.5, 1.31),
            loc="upper center",
            ncol=6,
            columnspacing=0.9,
        ).set_draggable(True)
    else:
        axes.get_legend().set_visible(False)

    if i == 2:
        axes.set_ylim([0, 1])

    if i == 3:
        plt.rcParams.update(params)
        plt.xlabel(xlabel)
        axes.set_ylim([0, 5])
    else:
        axes.xaxis.label.set_visible(False)
        axes.set_xticks([], minor=True)

    if (
        condition == "Number of Environments"
        and i == 1
        or condition == "Number of Environments"
        and i == 2
    ):
        axes.axes.xaxis.set_ticklabels([])

    plt.ylabel(ylabel)

    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale and not condition == "Number of Environments":
        plt.ticklabel_format(style="sci", axis="x", scilimits=(0, 0))
//  [python]
def plot_data(
    data, xaxis, value, condition, fig, i, ylabel, xlabel, smooth=1, **kwargs
):
    if smooth > 1:
        y = np.ones(smooth)
        for datum in data:
            x = np.asarray(datum[value])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x, y, "same") / np.convolve(z, y, "same")
            datum[value] = smoothed_x

    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)

    sns.set(style="darkgrid", rc=params)

    axes = fig.add_subplot(3, 1, i)
    sns.lineplot(
        data=data,
        x=xaxis,
        y=value,
        hue=condition,
        ci="sd",
        linewidth=0.75,
        **kwargs,
    )

    if i == 1:
        plt.rcParams.update(params)
        plt.legend(
            handlelength=1,
            handleheight=0.0,
            bbox_to_anchor=(0.5, 1.31),
            loc="upper center",
            ncol=6,
            columnspacing=0.9,
        ).set_draggable(True)
    else:
        axes.get_legend().set_visible(False)

    if i == 2:
        axes.set_ylim([0, 1])

    if i == 3:
        plt.rcParams.update(params)
        plt.xlabel(xlabel)
        axes.set_ylim([0, 5])
    else:
        axes.xaxis.label.set_visible(False)
        axes.set_xticks([], minor=True)

    if (
        condition == "Number of Environments"
        and i == 1
        or condition == "Number of Environments"
        and i == 2
    ):
        axes.axes.xaxis.set_ticklabels([])

    plt.ylabel(ylabel)

    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale and not condition == "Number of Environments":
        plt.ticklabel_format(style="sci", axis="x", scilimits=(0, 0))
//  [python]
def plot_figs(container, table_name, ax=None, fig=None, title=None, test_wilcoxn=False):
    allow_method_names = None
    if table_name is not None:
        allow_method_names = ['%s_%s' % (k, table_name)
                              for k in ['nn_rank', 'nn_joint_rank', 'nn_middle_rank', 'nn_specific_rank',
                                        'zero_rank', 'random_rank',
                                        'rf_rank', 'shuffle_rank',
                                        'marginal_rank', 'mim_rank', 'dfs_rank', 'enet_rank',
                                        'lasso_rank', 'iter_zero_rank', 'iter_shuffle_rank']]
    plot_table = container.get_pandas_table(allow_method_names)

    if test_wilcoxn:
        for sig_method, symbol, height in [(cal_rnn_rf_sig_in_table, '*', 0.45),
                                           # (cal_rnn_zero_sig_in_table, 'o', 0.48)
                                           ]:
            for nf in [1, 2, 5, 10, 15, 20, 30, 37]:
                pvalue, max_value = sig_method(plot_table, table_name, num_features=nf)
                if pvalue < 0.1:  # 1-side test
                    print(pvalue, nf, table_name)
                    ax.text(nf, height, symbol, ha='center', va='bottom', )

    # sort the table and change the name
    plot_table = change_name_table(plot_table)

    if ax is None:
        fig, ax = plt.subplots()
    ax = sns.tsplot(time=container.x_name, value=container.val_name, ax=ax,
                    unit="unit", condition=container.line_name,
                    data=plot_table, err_style="ci_bars", interpolate=True)

    # get the best line plot
    max_feature_val = plot_table[plot_table[container.x_name] ==
                                 plot_table[container.x_name].max()]
    max_feature_val = np.mean(max_feature_val[container.val_name])

    ax.axhline(max_feature_val, linestyle='--', color='black', alpha=0.3)

    if title is not None:
        ax.set_title(title)

    return fig, ax
//  [python]
def plot_figs(container, table_name, ax=None, fig=None, title=None, test_wilcoxn=False):
    allow_method_names = None
    if table_name is not None:
        allow_method_names = ['%s_%s' % (k, table_name)
                              for k in ['nn_rank', 'nn_joint_rank', 'nn_middle_rank', 'nn_specific_rank',
                                        'zero_rank', 'random_rank',
                                        'rf_rank', 'shuffle_rank',
                                        'marginal_rank', 'mim_rank', 'dfs_rank', 'enet_rank',
                                        'lasso_rank', 'iter_zero_rank', 'iter_shuffle_rank']]
    plot_table = container.get_pandas_table(allow_method_names)

    if test_wilcoxn:
        for sig_method, symbol, height in [(cal_rnn_rf_sig_in_table, '*', 0.45),
                                           # (cal_rnn_zero_sig_in_table, 'o', 0.48)
                                           ]:
            for nf in [1, 2, 5, 10, 15, 20, 30, 37]:
                pvalue, max_value = sig_method(plot_table, table_name, num_features=nf)
                if pvalue < 0.1:  # 1-side test
                    print(pvalue, nf, table_name)
                    ax.text(nf, height, symbol, ha='center', va='bottom', )

    # sort the table and change the name
    plot_table = change_name_table(plot_table)

    if ax is None:
        fig, ax = plt.subplots()
    ax = sns.lineplot(x=container.x_name, y=container.val_name, ax=ax,
                    hue=container.line_name,
                    data=plot_table, err_style="bars")

    # get the best line plot
    max_feature_val = plot_table[plot_table[container.x_name] ==
                                 plot_table[container.x_name].max()]
    max_feature_val = np.mean(max_feature_val[container.val_name])

    ax.axhline(max_feature_val, linestyle='--', color='black', alpha=0.3)

    if title is not None:
        ax.set_title(title)

    return fig, ax
//  [python]
def plot_data(data, value="AverageReturn"):
    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)
    plt.figure(figsize=(16, 9))
    sns.set(style="darkgrid", font_scale=1.5)
    sns.tsplot(data=data, time="Iteration", value=value, unit="Unit", condition="Condition")
    plt.legend(loc='best').draggable()
    plt.savefig('result.png', bbox_inches='tight')
    plt.show()
//  [python]
def plot_data(data, value="AverageReturn"):
    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)
    plt.figure(figsize=(16, 9))
    sns.set(style="darkgrid", font_scale=1.5)
    sns.lineplot(data=data, x="Iteration", y=value, hue="Condition", units="Unit")
    plt.legend(loc='best').draggable()
    plt.savefig('result.png', bbox_inches='tight')
    plt.show()
//  [python]
def result_comp(dfs, names, a, y_col="profit_eur", y_name="Gross profit increase [EUR]"):
    df_results = pd.DataFrame(columns=["timestamp", "Strategy", y_name])
    for df, name in zip(dfs, names):
        
        df = df.groupby(pd.Grouper(freq="M")).sum()
        df[y_name] = df[y_col].cumsum()
        df = df.reset_index()
        df["Strategy"] = name
        df = df[["timestamp", "Strategy", y_name]]
        df_results = df_results.append(df)

    
    ax = sns.tsplot(time="timestamp", value=y_name,
                      unit="Strategy", condition="Strategy",
                      err_style="sd", data=df_results, ax=a)

    ax.set(xlabel="");
//  [python]
def result_comp(dfs, names, a, y_col="profit_eur", y_name="Gross profit increase [EUR]"):
    df_results = pd.DataFrame(columns=["timestamp", "Strategy", y_name])
    for df, name in zip(dfs, names):
        
        df = df.groupby(pd.Grouper(freq="M")).sum()
        df[y_name] = df[y_col].cumsum()
        df = df.reset_index()
        df["Strategy"] = name
        df = df[["timestamp", "Strategy", y_name]]
        df_results = df_results.append(df)

    
    ax = sns.lineplot(x="timestamp", y=y_name,
                      hue="Strategy", style="Strategy",
                      markers=True, dashes=True, ci="sd", data=df_results, ax=a)

    ax.set(xlabel="");
//  [python]
def plot_results_game(experimental_data, title, num_iter, args, demo_score=None, demo_std=None):
    fig, ax = plt.subplots(figsize=(15,10))
    g = sns.tsplot(data=experimental_data, time='iteration', unit='run_number', condition='agent', value='train_episode_reward', ax=ax, ci=50)
    if demo_score is not None:
        x = [i * 10 for i in range(num_iter // 10)]
        y = [demo_score for _ in x]
        e = [demo_std for _ in x]
        ax.errorbar(x, y, e, label='Expert', marker='*',color='grey')

    fontsize = 40
    for tick in ax.xaxis.get_major_ticks():
        tick.label1.set_fontsize(fontsize)
        tick.label1.set_fontweight('bold')
    for tick in ax.yaxis.get_major_ticks():
        tick.label1.set_fontsize(fontsize)
        tick.label1.set_fontweight('bold')

    fontsize = "45"
    title_fontsize = 48
    yaxis_label, xaxis_label = "Returns", "Interaction Steps ({}e{})".format(str(args.steps).strip('0'),int(np.log10(args.steps)))
    title_axis_font = {'size': title_fontsize, 'weight': 'bold'}
    xylabel_axis_font = {'size': fontsize, 'weight': 'bold'}
    ax.set_ylabel(yaxis_label, **xylabel_axis_font)
    ax.set_xlabel(xaxis_label, **xylabel_axis_font)
    ax.set_title(title, **title_axis_font)
    legend_properties = {'weight':'bold','size':"35"}
    if args.plot:
        ax.legend(loc=legend_loc, prop=legend_properties,ncol=1)#,bbox_to_anchor=(-0.1,0.5))
    else:
        g.legend_.remove()

    plt.tight_layout()
    # plt.show()
    if args.savefig:
        title = title.replace(" ", "")
        title = '{}-ep{}'.format(title, args.episodes)
        if args.ab:
            title = '{}-ab{}'.format(title, args.ab)
        if args.title != '':
            title = '{}-{}'.format(title, args.title)
        plt.savefig('../figs/{}.pdf'.format(title))
        plt.close()
    else:
        plt.show()
    os.system("mkdir -p ../figs")
    print("Figure {}.pdf saved to {}".format(title, "../figs/"))
//  [python]
def plot_results_game(experimental_data, title, num_iter, args, demo_score=None, demo_std=None):
    fig, ax = plt.subplots(figsize=(15,10))
    g = sns.lineplot(data=experimental_data, x='iteration', y='train_episode_reward', hue='agent', units='run_number', estimator=None, lw=2, ax=ax, ci=50)
    if demo_score is not None:
        x = [i * 10 for i in range(num_iter // 10)]
        y = [demo_score for _ in x]
        e = [demo_std for _ in x]
        ax.errorbar(x, y, e, label='Expert', marker='*',color='grey')

    fontsize = 40
    for tick in ax.xaxis.get_major_ticks():
        tick.label1.set_fontsize(fontsize)
        tick.label1.set_fontweight('bold')
    for tick in ax.yaxis.get_major_ticks():
        tick.label1.set_fontsize(fontsize)
        tick.label1.set_fontweight('bold')

    fontsize = "45"
    title_fontsize = 48
    yaxis_label, xaxis_label = "Returns", "Interaction Steps ({}e{})".format(str(args.steps).strip('0'),int(np.log10(args.steps)))
    title_axis_font = {'size': title_fontsize, 'weight': 'bold'}
    xylabel_axis_font = {'size': fontsize, 'weight': 'bold'}
    ax.set_ylabel(yaxis_label, **xylabel_axis_font)
    ax.set_xlabel(xaxis_label, **xylabel_axis_font)
    ax.set_title(title, **title_axis_font)
    legend_properties = {'weight':'bold','size':"35"}
    if args.plot:
        ax.legend(loc=legend_loc, prop=legend_properties,ncol=1)#,bbox_to_anchor=(-0.1,0.5))
    else:
        g.legend_.remove()

    plt.tight_layout()
    # plt.show()
    if args.savefig:
        title = title.replace(" ", "")
        title = '{}-ep{}'.format(title, args.episodes)
        if args.ab:
            title = '{}-ab{}'.format(title, args.ab)
        if args.title != '':
            title = '{}-{}'.format(title, args.title)
        plt.savefig('../figs/{}.pdf'.format(title))
        plt.close()
    else:
        plt.show()
    os.system("mkdir -p ../figs")
    print("Figure {}.pdf saved to {}".format(title, "../figs/"))
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, add=False, **kwargs):
    if smooth > 1:
        data_smoothed = copy.deepcopy(data)
        """
        smooth data with moving window average.
        that is,
            smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
        where the "smooth" param is width of that window (2k+1)
        """
        y = np.ones(smooth)
        for datum in data_smoothed:
            x = np.asarray(datum[value])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x,y,'same') / np.convolve(z,y,'same')
            datum[value] = smoothed_x

    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)

    if smooth > 1 and isinstance(data_smoothed, list):
        data_smoothed = pd.concat(data_smoothed, ignore_index=True)

    # sns.set(style="whitegrid", font_scale=1.5)

    if (not add):
        sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci='sd',**kwargs)
    else:
        if smooth == 1:
            sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci='sd',**kwargs)
        elif smooth > 1:
            sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci='sd', alpha=0.5, legend=False,**kwargs)
            sns.tsplot(data=data_smoothed, time=xaxis, value=value, unit="Unit", condition=condition, ci='sd', **kwargs)

    """
    If you upgrade to any version of Seaborn greater than 0.8.1, switch from 
    tsplot to lineplot replacing L29 with 'sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)'
    Changes the colorscheme and the default legend style, though.
    """
    
    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale:
        # Just some formatting niceness: x-axis scale in scientific notation if max x is large
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

    # plt.tight_layout(pad=0.5)
    plt.tight_layout()

    # Add my own likings to the plots
    if value in label_equivs:
        plt.ylabel(label_equivs[value])

    if xaxis == 'TotalEnvInteracts':
        plt.xlabel(label_equivs[xaxis])

    plt.grid(False)
    # plt.grid(axis='y', linestyle='--', color='grey', alpha=0.5)
    ax = plt.gca()
    # ax.spines['left'].set_color('black')
    # ax.spines['bottom'].set_color('black')
    # ax.tick_params(bottom=True, left=True)

    plt.legend(loc='best').set_draggable(True)
//  [python]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, add=False, **kwargs):
    if smooth > 1:
        data_smoothed = copy.deepcopy(data)
        """
        smooth data with moving window average.
        that is,
            smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
        where the "smooth" param is width of that window (2k+1)
        """
        y = np.ones(smooth)
        for datum in data_smoothed:
            x = np.asarray(datum[value])
            z = np.ones(len(x))
            smoothed_x = np.convolve(x,y,'same') / np.convolve(z,y,'same')
            datum[value] = smoothed_x

    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)

    if smooth > 1 and isinstance(data_smoothed, list):
        data_smoothed = pd.concat(data_smoothed, ignore_index=True)

    # sns.set(style="whitegrid", font_scale=1.5)

    if (not add):
        sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)
    else:
        if smooth == 1:
            sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)
        elif smooth > 1:
            sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', alpha=0.5, legend=False,**kwargs)
            sns.lineplot(data=data_smoothed, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)

    """
    If you upgrade to any version of Seaborn greater than 0.8.1, switch from 
    tsplot to lineplot replacing L29 with 'sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)'
    Changes the colorscheme and the default legend style, though.
    """
    
    xscale = np.max(np.asarray(data[xaxis])) > 5e3
    if xscale:
        # Just some formatting niceness: x-axis scale in scientific notation if max x is large
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

    # plt.tight_layout(pad=0.5)
    plt.tight_layout()

    # Add my own likings to the plots
    if value in label_equivs:
        plt.ylabel(label_equivs[value])

    if xaxis == 'TotalEnvInteracts':
        plt.xlabel(label_equivs[xaxis])

    plt.grid(False)
    # plt.grid(axis='y', linestyle='--', color='grey', alpha=0.5)
    ax = plt.gca()
    # ax.spines['left'].set_color('black')
    # ax.spines['bottom'].set_color('black')
    # ax.tick_params(bottom=True, left=True)

    plt.legend(loc='best').set_draggable(True)
//  [python]
def plot_all_algorithms_data(self):
		sns.set(style="darkgrid", font_scale=1.5, font='serif', rc={'figure.figsize': (10, 8)})
		all_algorithms_dir = self.get_files_path()
		line_width = 2.3

		for dir in sorted(all_algorithms_dir):
			self.all_files_path(rootDir=dir, file_name="train_rewards_episode.txt")  # get all txt files. -> saved in self.filepaths
			x_data, y_data = self.get_data(self.filepaths)
			y_data = self.smooth(y_data, sm=80)
			# '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
			if dir.split('/')[-1] == 'dreamer':
				l1 = sns.tsplot(time=x_data, data=y_data, color='m', condition='Dreamer', linestyle='-.', linewidth=line_width, estimator=np.median)
				# sns.tsplot(time=x_data, data=y_data, color='m', condition='action scale 1', err_style='ci_band', linestyle = '-.',linewidth=line_width,estimator=np.median)
			# if dir.split('/')[-1] == 'two_scale':
			#     sns.tsplot(time=x_data, data=y_data, color='g', condition='action scale 2', err_style='ci_band', linestyle = ':',linewidth=line_width,estimator=np.median)
			if dir.split('/')[-1] == 'planet':
				l2 = sns.tsplot(time=x_data, data=y_data, color='teal', condition='PlaNet', linestyle='--', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'aap2':
				l3 = sns.tsplot(time=x_data, data=y_data, color='r', condition='EPN With 2 Sub-Agents', linestyle='-', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'aap3':
				l4 = sns.tsplot(time=x_data, data=y_data, color='c', condition='EPN With 3 Sub-Agents', linestyle='--', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'aap4':
				l5 = sns.tsplot(time=x_data, data=y_data, color='g', condition='EPN With 4 Sub-Agents', linestyle=':', linewidth=line_width, estimator=np.median)

			self.filepaths = []  # clear -> self.filepaths

		plt.ylabel("Return")
		plt.xlabel("Environment Steps(x1000)")
		plt.title(self.root_path.split('/')[-1])

		plt.xlim(-0.5, 900)
		plt.ylim(-0.5, 1000)
		# plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
		plt.savefig('/home/hzq/' + self.root_path.split('/')[-1] + '_aap_all_algorithms_Figure_1.png')
		# plt.savefig('/home/hzq/Figure_2.png')
		# plt.legend(handles=[l1, l2, l3, l4, l5],
		#            labels=['Dreamer', 'PlaNet', 'EPN With 2 Sub-Agents', 'EPN With 3 Sub-Agents',
		#                    'EPN With 4 Sub-Agents'])
		plt.show()
//  [python]
def plot_all_algorithms_data(self):
		sns.set(style="darkgrid", font_scale=1.5, font='serif', rc={'figure.figsize': (10, 8)})
		all_algorithms_dir = self.get_files_path()
		line_width = 2.3

		for dir in sorted(all_algorithms_dir):
			self.all_files_path(rootDir=dir, file_name="train_rewards_episode.txt")  # get all txt files. -> saved in self.filepaths
			x_data, y_data = self.get_data(self.filepaths)
			y_data = self.smooth(y_data, sm=80)
			# '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
			if dir.split('/')[-1] == 'dreamer':
				sns.lineplot(x=x_data, y=y_data, color='m', label='Dreamer', linestyle='-.', linewidth=line_width, estimator=np.median)
				# sns.tsplot(time=x_data, data=y_data, color='m', condition='action scale 1', err_style='ci_band', linestyle = '-.',linewidth=line_width,estimator=np.median)
			# if dir.split('/')[-1] == 'two_scale':
			#     sns.tsplot(time=x_data, data=y_data, color='g', condition='action scale 2', err_style='ci_band', linestyle = ':',linewidth=line_width,estimator=np.median)
			if dir.split('/')[-1] == 'planet':
				sns.lineplot(x=x_data, y=y_data, color='teal', label='PlaNet', linestyle='--', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'aap2':
				sns.lineplot(x=x_data, y=y_data, color='r', label='EPN With 2 Sub-Agents', linestyle='-', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'aap3':
				sns.lineplot(x=x_data, y=y_data, color='c', label='EPN With 3 Sub-Agents', linestyle='--', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'aap4':
				sns.lineplot(x=x_data, y=y_data, color='g', label='EPN With 4 Sub-Agents', linestyle=':', linewidth=line_width, estimator=np.median)

			self.filepaths = []  # clear -> self.filepaths

		plt.ylabel("Return")
		plt.xlabel("Environment Steps(x1000)")
		plt.title(self.root_path.split('/')[-1])

		plt.xlim(-0.5, 900)
		plt.ylim(-0.5, 1000)
		# plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
		plt.savefig('/home/hzq/' + self.root_path.split('/')[-1] + '_aap_all_algorithms_Figure_1.png')
		# plt.savefig('/home/hzq/Figure_2.png')
		plt.legend()
		plt.show()
//  [python]
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--workspace",
        type=str,
        default="./workspace",
        help="Workdir containing rdvl_*.npy files.",
    )
    args = parser.parse_args()

    rdvl_files = glob.glob(os.path.join(args.workspace, "**", "rdvl_*.npy"), recursive=True)
    assert len(rdvl_files) > 0, f"No RDVL files found in {args.workspace}"

    results = {
        "RDVL": [],
        "Site": [],
        "Round": [],
    }
    for rdvl_file in rdvl_files:
        _result = np.load(rdvl_file, allow_pickle=True).item()

        img_recon_sim_reduced = _result["img_recon_sim_reduced"]

        for rdvl in img_recon_sim_reduced:
            results["RDVL"].append(float(rdvl))
            results["Site"].append(_result["site"])
            results["Round"].append(_result["round"])

    # plot
    sns.tsplot(x="Round", y="RDVL", unit="Site", data=results)
    plt.plot([np.min(results["Round"]), np.max(results["Round"])], [0, 0], "k", linewidth=1.0)
    plt.grid()
    plt.show()
//  [python]
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--workspace",
        type=str,
        default="./workspace",
        help="Workdir containing rdvl_*.npy files.",
    )
    args = parser.parse_args()

    rdvl_files = glob.glob(os.path.join(args.workspace, "**", "rdvl_*.npy"), recursive=True)
    assert len(rdvl_files) > 0, f"No RDVL files found in {args.workspace}"

    results = {
        "RDVL": [],
        "Site": [],
        "Round": [],
    }
    for rdvl_file in rdvl_files:
        _result = np.load(rdvl_file, allow_pickle=True).item()

        img_recon_sim_reduced = _result["img_recon_sim_reduced"]

        for rdvl in img_recon_sim_reduced:
            results["RDVL"].append(float(rdvl))
            results["Site"].append(_result["site"])
            results["Round"].append(_result["round"])

    # plot
    sns.lineplot(x="Round", y="RDVL", hue="Site", data=results)
    plt.plot([np.min(results["Round"]), np.max(results["Round"])], [0, 0], "k", linewidth=1.0)
    plt.grid()
    plt.show()
//  [python]
def plot_multi_view(self):
		sns.set(style="darkgrid", font_scale=1.5, font='serif', rc={'figure.figsize': (10, 16)})
		all_algorithms_dir = self.get_files_path()
		line_width = 2.3

		# plt.title(self.root_path.split('/')[-1])

		plt.subplot(211)
		for dir in all_algorithms_dir:
			self.all_files_path(rootDir=dir, file_name="train_rewards_episode.txt")  # get all txt files. -> saved in self.filepaths
			x_data, y_data = self.get_data(self.filepaths)
			y_data = self.smooth(y_data)
			# '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
			if dir.split('/')[-1] == 'dreamer':
				sns.tsplot(time=x_data, data=y_data, color='m', condition='viewpoint with 1 action scale', err_style='ci_band', linestyle='-.', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'two_scale':
				sns.tsplot(time=x_data, data=y_data, color='g', condition='viewpoint with 2 action scale', err_style='ci_band', linestyle=':', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'three_scale':
				sns.tsplot(time=x_data, data=y_data, color='b', condition='viewpoint with 3 action scale', err_style='ci_band', linestyle='--', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'four_scale':
				sns.tsplot(time=x_data, data=y_data, color='c', condition='viewpoint with 4 action scale', err_style='ci_band', linestyle='-', linewidth=line_width, estimator=np.median)

			self.filepaths = []  # clear -> self.filepaths

		plt.ylabel("Return")
		plt.xlabel("Environment Steps(x1000)")
		# plt.title(self.root_path.split('/')[-1])
		plt.xlim(-0.5, 900)
		plt.ylim(-0.5, 150)

		plt.subplot(212)
		for dir in all_algorithms_dir:
			self.all_files_path(rootDir=dir, file_name="reward_loss_episode.txt")  # get all txt files. -> saved in self.filepaths
			x_data, y_data = self.get_data(self.filepaths)
			y_data = self.smooth(y_data, sm=10)
			# '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
			if dir.split('/')[-1] == 'dreamer':
				sns.tsplot(time=x_data, data=y_data, color='m', condition='viewpoint with 1 action scale', err_style='ci_band', linestyle='-.', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'two_scale':
				sns.tsplot(time=x_data, data=y_data, color='g', condition='viewpoint with 2 action scale', err_style='ci_band', linestyle=':', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'three_scale':
				sns.tsplot(time=x_data, data=y_data, color='b', condition='viewpoint with 3 action scale', err_style='ci_band', linestyle='--', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'four_scale':
				sns.tsplot(time=x_data, data=y_data, color='c', condition='viewpoint with 4 action scale', err_style='ci_band', linestyle='-', linewidth=line_width, estimator=np.median)

			self.filepaths = []  # clear -> self.filepaths

		plt.ylabel("Reward Loss")
		plt.xlabel("Environment Steps(x1000)")
		# plt.title(self.root_path.split('/')[-1])
		plt.xlim(-0.5, 900)
		plt.ylim(0, 0.05)

		plt.savefig('/home/hzq/' + self.root_path.split('/')[-1] + 'Figure_1.png')
		plt.show()
//  [python]
def plot_multi_view(self):
		sns.set(style="darkgrid", font_scale=1.5, font='serif', rc={'figure.figsize': (10, 16)})
		all_algorithms_dir = self.get_files_path()
		line_width = 2.3

		# plt.title(self.root_path.split('/')[-1])

		plt.subplot(211)
		for dir in all_algorithms_dir:
			self.all_files_path(rootDir=dir, file_name="train_rewards_episode.txt")  # get all txt files. -> saved in self.filepaths
			x_data, y_data = self.get_data(self.filepaths)
			y_data = self.smooth(y_data)
			# '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
			if dir.split('/')[-1] == 'dreamer':
				sns.lineplot(x=x_data, y=y_data, color='m', label='viewpoint with 1 action scale', linestyle='-.', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'two_scale':
				sns.lineplot(x=x_data, y=y_data, color='g', label='viewpoint with 2 action scale', linestyle=':', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'three_scale':
				sns.lineplot(x=x_data, y=y_data, color='b', label='viewpoint with 3 action scale', linestyle='--', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'four_scale':
				sns.lineplot(x=x_data, y=y_data, color='c', label='viewpoint with 4 action scale', linestyle='-', linewidth=line_width, estimator=np.median)

			self.filepaths = []  # clear -> self.filepaths

		plt.ylabel("Return")
		plt.xlabel("Environment Steps(x1000)")
		# plt.title(self.root_path.split('/')[-1])
		plt.xlim(-0.5, 900)
		plt.ylim(-0.5, 150)

		plt.subplot(212)
		for dir in all_algorithms_dir:
			self.all_files_path(rootDir=dir, file_name="reward_loss_episode.txt")  # get all txt files. -> saved in self.filepaths
			x_data, y_data = self.get_data(self.filepaths)
			y_data = self.smooth(y_data, sm=10)
			# '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
			if dir.split('/')[-1] == 'dreamer':
				sns.lineplot(x=x_data, y=y_data, color='m', label='viewpoint with 1 action scale', linestyle='-.', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'two_scale':
				sns.lineplot(x=x_data, y=y_data, color='g', label='viewpoint with 2 action scale', linestyle=':', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'three_scale':
				sns.lineplot(x=x_data, y=y_data, color='b', label='viewpoint with 3 action scale', linestyle='--', linewidth=line_width, estimator=np.median)
			if dir.split('/')[-1] == 'four_scale':
				sns.lineplot(x=x_data, y=y_data, color='c', label='viewpoint with 4 action scale', linestyle='-', linewidth=line_width, estimator=np.median)

			self.filepaths = []  # clear -> self.filepaths

		plt.ylabel("Reward Loss")
		plt.xlabel("Environment Steps(x1000)")
		# plt.title(self.root_path.split('/')[-1])
		plt.xlim(-0.5, 900)
		plt.ylim(0, 0.05)

		plt.savefig('/home/hzq/' + self.root_path.split('/')[-1] + 'Figure_1.png')
		plt.show()
//  [python]
def plot_results(results_df, output_dir):
  """Plots metrics and saves plots as png files."""
  for metric_name in results_df.columns:
    if metric_name == 'seq_len' or metric_name == 'method':
      continue
    pylab.figure()
    sns.pointplot(
        x='seq_len',
        y=metric_name,
        data=results_df,
        hue='method',
        estimator=np.mean,
        join=True,
        ci=95)
    output = six.StringIO()
    pylab.savefig(output, format='png')
    image = output.getvalue()
    with open(os.path.join(output_dir, metric_name + '.png'), 'w+') as f:
      f.write(image)
//  [python]
def plot_results(results_df, output_dir):
  """Plots metrics and saves plots as png files."""
  for metric_name in results_df.columns:
    if metric_name == 'seq_len' or metric_name == 'method':
      continue
    pylab.figure()
    sns.lineplot(
        x='seq_len',
        y=metric_name,
        data=results_df,
        hue='method',
        estimator=np.mean,
        err_style='bars')
    output = six.StringIO()
    pylab.savefig(output, format='png')
    image = output.getvalue()
    with open(os.path.join(output_dir, metric_name + '.png'), 'w+') as f:
      f.write(image)
//  [python]
def evaluate_correlated_logit_model():
    pvalue_dict = defaultdict(list)
    rng = np.random.default_rng(seed)

    beta_space = np.hstack((np.linspace(0.01, 2.5, 8), np.linspace(5, 20, 7)))
    for beta in beta_space:
        for idx in range(5):
            new_seed = rng.integers(0, np.iinfo(np.uint32).max, dtype=np.uint32)

            elements_dict = correlated_logit_model(beta, new_seed)
            for key, value in elements_dict.items():
                pvalue_dict[key].append(value)
            pvalue_dict["sigma_factor"].append(beta)

    df = pd.DataFrame(pvalue_dict)

    fig, axs = plt.subplots(3, 1, figsize=(8, 6), sharey=True, sharex=True)
    axs = axs.flatten()

    for ax, name in zip(axs, ["X1", "X2", "X500"]):
        sns.pointplot(data=df, x="sigma_factor", y=name, ax=ax)

        ax.axhline([0.05], ls="--", color="red", label="alpha")
        ax.set(title=name, ylabel="pvalue", xlabel="SNR (beta)")
        ax.legend()
    fig.suptitle("Correlated Logit model")
    fig.tight_layout()
//  [python]
def evaluate_correlated_logit_model():
    pvalue_dict = defaultdict(list)
    rng = np.random.default_rng(seed)

    beta_space = np.hstack((np.linspace(0.01, 2.5, 8), np.linspace(5, 20, 7)))
    for beta in beta_space:
        for idx in range(5):
            new_seed = rng.integers(0, np.iinfo(np.uint32).max, dtype=np.uint32)

            elements_dict = correlated_logit_model(beta, new_seed)
            for key, value in elements_dict.items():
                pvalue_dict[key].append(value)
            pvalue_dict["sigma_factor"].append(beta)

    df = pd.DataFrame(pvalue_dict)

    fig, axs = plt.subplots(3, 1, figsize=(8, 6), sharey=True, sharex=True)
    axs = axs.flatten()

    for ax, name in zip(axs, ["X1", "X2", "X500"]):
        sns.lineplot(data=df, x="sigma_factor", y=name, ax=ax, marker="o")

        ax.axhline([0.05], ls="--", color="red", label="alpha")
        ax.set(title=name, ylabel="pvalue", xlabel="SNR (beta)")
        ax.legend()
    fig.suptitle("Correlated Logit model")
    fig.tight_layout()
//  [python]
def evaluate_linear_ancova_model():
    pvalue_dict = defaultdict(list)
    rng = np.random.default_rng(seed)

    j_space = np.linspace(0.005, 2.25, 9)

    for sigma_factor in j_space:
        for idx in range(5):
            new_seed = rng.integers(0, np.iinfo(np.uint32).max, dtype=np.uint32)

            elements_dict = linear_model_ancova(sigma_factor, new_seed)
            for key, value in elements_dict.items():
                pvalue_dict[key].append(value)
            pvalue_dict["sigma_factor"].append(sigma_factor)

    df = pd.DataFrame(pvalue_dict)

    fig, axs = plt.subplots(2, 2, figsize=(8, 6), sharey=True, sharex=True)
    axs = axs.flatten()

    for ax, name in zip(axs, ["X1", "X2", "X6", "X7"]):
        sns.pointplot(data=df, x="sigma_factor", y=name, ax=ax)

        ax.axhline([0.05], ls="--", color="red", label="alpha")
        ax.set(title=name, ylabel="pvalue", xlabel="SNR (10 / x)")
        ax.legend()
    fig.suptitle("Linear ANCOVA model")
    fig.tight_layout()
//  [python]
def evaluate_linear_ancova_model():
    pvalue_dict = defaultdict(list)
    rng = np.random.default_rng(seed)

    j_space = np.linspace(0.005, 2.25, 9)

    for sigma_factor in j_space:
        for idx in range(5):
            new_seed = rng.integers(0, np.iinfo(np.uint32).max, dtype=np.uint32)

            elements_dict = linear_model_ancova(sigma_factor, new_seed)
            for key, value in elements_dict.items():
                pvalue_dict[key].append(value)
            pvalue_dict["sigma_factor"].append(sigma_factor)

    df = pd.DataFrame(pvalue_dict)

    fig, axs = plt.subplots(2, 2, figsize=(8, 6), sharey=True, sharex=True)
    axs = axs.flatten()

    for ax, name in zip(axs, ["X1", "X2", "X6", "X7"]):
        sns.lineplot(data=df, x="sigma_factor", y=name, ax=ax, marker="o")

        ax.axhline([0.05], ls="--", color="red", label="alpha")
        ax.set(title=name, ylabel="pvalue", xlabel="SNR (10 / x)")
        ax.legend()
    fig.suptitle("Linear ANCOVA model")
    fig.tight_layout()
//  [python]
def plot_training_curve(training_curve_file, outputfilename, vae_train, threshold):
    """Plot training curves as output from either the VAE training or VAE MLP."""
    import os
    os.makedirs(outputfilename[:outputfilename.rfind('/')],exist_ok=True)
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import seaborn as sns
    #from scipy.signal import find_peaks_cwt
    #from impyute import moving_window
    def impute_peaks(signal):
        signal=signal.values
        idxs=signal>=threshold
        signal[idxs]=np.nan
        """for idx in idxs:
            signal[idx]=(signal[idx-1]+signal[idx+1])/2 if idx else signal[idx+1]"""
        return signal
    def impute_df(df):
        df=df.apply(impute_peaks,axis=0).fillna(method='bfill',axis=0)
        print(df)
        return df
    sns.set(style="whitegrid")
    df=pd.DataFrame(pickle.load(open(training_curve_file,'rb')))
    plt.subplots(1,3 if vae_train else 2,figsize=(15 if vae_train else 10,5))
    plt.subplot(131 if vae_train else 121)
    if vae_train:
        df['loss']=df['recon_loss']+df['kl_loss']
        df['val_loss']=df['val_recon_loss']+df['val_kl_loss']
    plt.plot(impute_df(df[['loss','val_loss']+(['recon_loss','val_recon_loss'] if vae_train else [])]))
    plt.xlabel('Epoch')
    plt.ylabel('Loss')
    plt.tight_layout()
    plt.subplot(132 if vae_train else 122)
    plt.plot(df[['lr_vae', 'lr_mlp'] if not vae_train else ['lr']])
    plt.xlabel('Epoch')
    plt.ylabel('Learning Rate')
    if vae_train:
        plt.subplot(133)
        plt.plot(impute_df(df[['kl_loss','val_kl_loss']]))
        plt.xlabel('Epoch')
        plt.ylabel('Loss')
    plt.tight_layout()
    plt.savefig(outputfilename)
//  [python]
def plot_training_curve(training_curve_file, outputfilename, vae_train, threshold):
    """Plot training curves as output from either the VAE training or VAE MLP."""
    import os
    os.makedirs(outputfilename[:outputfilename.rfind('/')],exist_ok=True)
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import seaborn as sns
    #from scipy.signal import find_peaks_cwt
    #from impyute import moving_window
    def impute_peaks(signal):
        signal=signal.values
        idxs=signal>=threshold
        signal[idxs]=np.nan
        """for idx in idxs:
            signal[idx]=(signal[idx-1]+signal[idx+1])/2 if idx else signal[idx+1]"""
        return signal
    def impute_df(df):
        df=df.apply(impute_peaks,axis=0).fillna(method='bfill',axis=0)
        print(df)
        return df
    sns.set(style="whitegrid")
    df=pd.DataFrame(pickle.load(open(training_curve_file,'rb')))
    plt.subplots(1,3 if vae_train else 2,figsize=(15 if vae_train else 10,5))
    plt.subplot(131 if vae_train else 121)
    if vae_train:
        df['loss']=df['recon_loss']+df['kl_loss']
        df['val_loss']=df['val_recon_loss']+df['val_kl_loss']
    sns.lineplot(data=impute_df(df[['loss','val_loss']+(['recon_loss','val_recon_loss'] if vae_train else [])]), palette="tab10", linewidth=2.5)
    plt.xlabel('Epoch')
    plt.ylabel('Loss')
    plt.tight_layout()
    plt.subplot(132 if vae_train else 122)
    sns.lineplot(data=df[['lr_vae', 'lr_mlp'] if not vae_train else ['lr']], palette="tab10", linewidth=2.5)
    plt.xlabel('Epoch')
    plt.ylabel('Learning Rate')
    if vae_train:
        plt.subplot(133)
        sns.lineplot(data=impute_df(df[['kl_loss','val_kl_loss']]), palette="tab10", linewidth=2.5)
        plt.xlabel('Epoch')
        plt.ylabel('Loss')
    plt.tight_layout()
    plt.savefig(outputfilename)
//  [python]
def _update_r_plot_grouped_by_phi(var_name, ax, df):
        ax.clear()
        sns.tsplot(x='$r$', y='u', hue='$\\phi$', data=df, ax=ax)
        ax.set_title(f'{var_name}($r$) grouped by $\\phi$')
        ax.set_ylabel(var_name)
//  [python]
def _update_r_plot_grouped_by_phi(var_name, ax, df):
        ax.clear()
        sns.lineplot(x='$r$', y='u', hue='$\\phi$', data=df, ax=ax)
        ax.set_title(f'{var_name}($r$) grouped by $\\phi$')
        ax.set_ylabel(var_name)
//  [python]
def visualize_distribution_time_serie(ts,value,path=None):
    """
    Visualize the time-serie data in each individual dimensions.

    Parameters
    ----------
    ts: numpy array of shape (n_test, n_features)
        The value of the test time serie data.
    value: numpy array of shape (n_test, )
        The outlier score of the test data.
    path: string
        The saving path for result figures.
    """
    sns.set(style="ticks")

    ts = pd.DatetimeIndex(ts)
    value=value.to_numpy()[:,1:]
    data = pd.DataFrame(value,ts)
    data = data.rolling(2).mean()
    sns_plot=sns.tsplot(data=data, palette="BuGn_r", linewidth=0.5)
    if path:
        sns_plot.figure.savefig(path+'/timeserie.png')
    plt.show()
//  [python]
def visualize_distribution_time_serie(ts,value,path=None):
    """
    Visualize the time-serie data in each individual dimensions.

    Parameters
    ----------
    ts: numpy array of shape (n_test, n_features)
        The value of the test time serie data.
    value: numpy array of shape (n_test, )
        The outlier score of the test data.
    path: string
        The saving path for result figures.
    """
    sns.set(style="ticks")

    ts = pd.DatetimeIndex(ts)
    value=value.to_numpy()[:,1:]
    data = pd.DataFrame(value,ts)
    data = data.rolling(2).mean()
    sns_plot=sns.lineplot(data=data, palette="BuGn_r", linewidth=0.5)
    if path:
        sns_plot.figure.savefig(path+'/timeserie.png')
    plt.show()
//  [python]
def _update_r_plot_grouped_by_theta(var_name, ax, df):
        ax.clear()
        sns.tsplot(x='$r$', y='u', hue='$\\theta$', data=df, ax=ax)
        ax.set_title(f'{var_name}($r$) grouped by $\\theta$')
        ax.set_ylabel(var_name)
//  [python]
def _update_r_plot_grouped_by_theta(var_name, ax, df):
        ax.clear()
        sns.lineplot(x='$r$', y='u', hue='$\\theta$', data=df, ax=ax)
        ax.set_title(f'{var_name}($r$) grouped by $\\theta$')
        ax.set_ylabel(var_name)
//  [python]
def plot_number_of_proteins(count, accu, colors, outpath, time_name):
    """
    Plot number of quantified proteins and cumulative protein numbers.

    Args:
        count (pd.DataFrame): DataFrame containing count data.
        accu (pd.DataFrame): DataFrame containing accumulation data.
        colors (dict): Dictionary of colors for each cohort.
        outpath (str): Output path for saving the plot.
        time_name (str): Time identifier for the output file.
    """
    fig, ax1 = plt.subplots(figsize=(14, 9))
    sns.barplot(x='Exp', y='count', data=count, hue='cohort', palette=colors, ax=ax1)
    ax1.set_xlabel('Cohort', fontsize=14)
    ax1.set_ylabel('Quantified protein numbers', fontsize=14)
    ax1.legend(loc='upper left', fontsize=10, shadow=True, fancybox=True)
    plt.ylim(0, count['count'].max() * 1.1)

    ax2 = ax1.twinx()
    # sns.lineplot(x='Exp', y='accumulation', data=accu, palette=colors, marker='o', linewidth=2, ax=ax2, label='Your Label')
    sns.pointplot(x='Exp', y='accumulation', data=accu, palette=colors, marker='o', linewidth=2, ax=ax2)
    ax2.set_ylabel('Cumulative protein numbers', fontsize=14)
    ax2.legend().remove()

    plt.title('Quantified protein numbers', fontsize=14)
    plt.savefig(f'{outpath}/GPs_numbers_{time_name}.pdf', dpi=400, transparent=True)
    plt.show()