jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_rate_and_memory(ys, data, hue, hue_order, style, style_order, output):
    fig, axes = plt.subplots(
        nrows=2,
        ncols=2,
        dpi=DPI,
        figsize=(10, 10),
        sharex=True,
        sharey="row",
        tight_layout=True,
    )

    for i, (y, ax) in enumerate(zip(ys, axes.flatten())):
        sns.lineplot(
            data=data,
            x=X,
            y=y,
            hue=hue,
            hue_order=hue_order,
            style=style,
            style_order=style_order,
            palette=PALETTE,
            markers=True,
            ax=ax,
            dashes=DASHES,
            mec=MEC,
            err_kws=ERR_KWS,
        )
        xticks = list(range(1, 20))
        _ = ax.set_xticks(xticks)

        if "rate" in y:
            ax.set_ylabel("Rate")
            ax.set_title(y.replace("_rate", "").capitalize())
            ax.set_yscale("log")
            KB = 1000
            MB = 1000 * KB
            yticks = [MB, 10 * MB, 25 * MB, 50 * MB, 100 * MB, 250 * MB, 500 * MB]
            ax.set_yticks(yticks)
            yticklabels = []
            for rate in yticks:
                rate, unit = format_size(rate).split()
                rate = round(float(rate))
                yticklabels.append(f"{rate} {unit}/s")

            ax.set_yticklabels(yticklabels)

            ax.legend(loc="upper right")

        else:
            ax.set_ylabel("Max. memory (MiB)")

        if y != "decompress_max_rss":
            ax.get_legend().remove()
        else:
            leg = ax.legend(loc="upper left", framealpha=1, frameon=True)
            # change the line width for the legend
            for line in leg.get_lines():
                line.set_linewidth(LEG_LW)

        for tool, lvl in DEFAULT_LVL.items():
            for t in set(data["technology"]):
                mean = data.query("tool==@tool and level==@lvl and technology==@t")[
                    y
                ].mean()
                ax.scatter(lvl, mean, s=110, fc="None", ec="red")

    fig.savefig(output)
//  [python]
def feature_power_plot(data, model_id, output_type, energy_source, feature_cols, actual_power_cols, predicted_power_cols, output_folder, name):
    plot_height = 5
    plot_width = 5

    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set(font_scale=1.2)
    row_num = len(feature_cols)
    col_num = len(actual_power_cols)
    width = max(10, col_num*plot_width)
    fig, axes = plt.subplots(row_num, col_num, figsize=(width, row_num*plot_height))
    for xi in range(0, row_num):
        feature_col = feature_cols[xi]
        for yi in range(0, col_num):
            if row_num == 1:
                if col_num == 1:
                    ax = axes
                else:
                    ax = axes[yi]
            else:
                if col_num == 1:
                    ax = axes[xi]
                else:
                    ax = axes[xi][yi]
            sorted_data = data.sort_values(by=[feature_col])
            sns.scatterplot(data=sorted_data, x=feature_col, y=actual_power_cols[yi], ax=ax, label="actual")
            sns.regplot(data=sorted_data, x=feature_col, y=predicted_power_cols[yi], ax=ax, label="predicted", color='C1', scatter=False)
            if xi == 0:
                ax.set_title(actual_power_cols[yi])
            if yi == 0:
                ax.set_ylabel("Power (W)")
    title = "{} {} prediction correlation \n by {}".format(energy_source, output_type, model_id)
    plt.suptitle(title, x=0.5, y=0.99)
    plt.tight_layout()
    filename = os.path.join(output_folder, name + ".png")
    fig.savefig(filename)
    plt.close()
//  [python]
def feature_power_plot(data, model_id, output_type, energy_source, feature_cols, actual_power_cols, predicted_power_cols, output_folder, name):
    plot_height = 5
    plot_width = 5

    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set(font_scale=1.2)
    row_num = len(feature_cols)
    col_num = len(actual_power_cols)
    width = max(10, col_num*plot_width)
    fig, axes = plt.subplots(row_num, col_num, figsize=(width, row_num*plot_height))
    for xi in range(0, row_num):
        feature_col = feature_cols[xi]
        for yi in range(0, col_num):
            if row_num == 1:
                if col_num == 1:
                    ax = axes
                else:
                    ax = axes[yi]
            else:
                if col_num == 1:
                    ax = axes[xi]
                else:
                    ax = axes[xi][yi]
            sorted_data = data.sort_values(by=[feature_col])
            sns.scatterplot(data=sorted_data, x=feature_col, y=actual_power_cols[yi], ax=ax, label="actual")
            sns.lineplot(data=sorted_data, x=feature_col, y=predicted_power_cols[yi], ax=ax, label="predicted", color='C1')
            if xi == 0:
                ax.set_title(actual_power_cols[yi])
            if yi == 0:
                ax.set_ylabel("Power (W)")
    title = "{} {} prediction correlation \n by {}".format(energy_source, output_type, model_id)
    plt.suptitle(title, x=0.5, y=0.99)
    plt.tight_layout()
    filename = os.path.join(output_folder, name + ".png")
    fig.savefig(filename)
    plt.close()
//  [python]
def make_line_plot(df_dict, x_col, y_col, include=None, title=None, xlabel=None, ylabel=None, legend=True):
    """
    Plot a line plot of two columns for each dataframe in `df_dict`.
    
    Uses `sns.lineplot` to plot a line plot of two columns for each
    dataframe in `df_dict`. The keys of `df_dict` are used as entries in
    the legend when `legend` is `True`.
    
    Parameters
    ----------
        df_dict: dict[str: pd.DataFrame]
            a dictionary mapping handles to dataframes with the data to plot
        x_col: str
            the name of a column in each dataframe in `df_dict` to plot on
            the x-axis
        y_col: str
            the name of a column in each dataframe in `df_dict` to plot on
            the y-axis
        include: list[str], optional
            a list of handles to include in the plot; all keys in `df_dict` not 
            present in `include`, if specified, will *not* be included in the plot
        title: str, optional
            a title for the plot
        xlabel: str, optional
            a label for the x-axis; if unspecified, `x_col` is used
        ylabel: str, optional
            a label for the y-axis; if unspecified, `y_col` is used
        legend: bool, optional
            whether to include a legend with each key in `df_dict`
    """
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    if include is not None:
        df_dict = {k: v for k, v in df_dict.items() if k in include}

    plt.figure(figsize=[10,6])
    for handle, df in df_dict.items():
        sns.lineplot(x=x_col, y=y_col, data=df, label=handle)
    if title:
        plt.title(title)
    if xlabel:
        plt.xlabel(xlabel)
    if ylabel:
        plt.ylabel(ylabel)
    if not legend:
        plt.gca().get_legend().remove()
//  [python]
def plot_learning_curve(episode_rewards, log_dir, window=10):
    """ Plot learning curve given episode reward list """
    # Calculate rolling window metrics
    rolling_average = episode_rewards.rolling(window=window, min_periods=1).mean().dropna()
    rolling_max = episode_rewards.rolling(window=window, min_periods=1).max().dropna()
    rolling_min = episode_rewards.rolling(window=window, min_periods=1).min().dropna()

    # Change column name
    rolling_average.columns = ['Average Reward']
    rolling_max.columns = ['Max Reward']
    rolling_min.columns = ['Min Reward']
    rolling_data = pd.concat([rolling_average, rolling_max, rolling_min], axis=1)

    # Plot
    sns.set()
    plt.figure(0, dpi=200)
    plt.clf()
    ax = sns.tsplot(data=rolling_data)
    ax.fill_between(rolling_average.index, rolling_min.iloc[:, 0], rolling_max.iloc[:, 0], alpha=0.2)
    ax.set_title('Learning Curve', fontsize=16)
    ax.set_ylabel('Reward')
    ax.set_xlabel('Episodes')

    # Save figure
    img_path = f'{log_dir}learning_curve{window}.png'
    plt.savefig(img_path, dpi=200)

    # Log figure
    image = plt.imread(img_path)
    wandb.log({f'Learning_Curve_{window}': [wandb.Image(image, caption="Learning_curve")]})
//  [python]
def plot_learning_curve(episode_rewards, log_dir, window=10):
    """ Plot learning curve given episode reward list """
    # Calculate rolling window metrics
    rolling_average = episode_rewards.rolling(window=window, min_periods=1).mean().dropna()
    rolling_max = episode_rewards.rolling(window=window, min_periods=1).max().dropna()
    rolling_min = episode_rewards.rolling(window=window, min_periods=1).min().dropna()

    # Change column name
    rolling_average.columns = ['Average Reward']
    rolling_max.columns = ['Max Reward']
    rolling_min.columns = ['Min Reward']
    rolling_data = pd.concat([rolling_average, rolling_max, rolling_min], axis=1)

    # Plot
    sns.set()
    plt.figure(0, dpi=200)
    plt.clf()
    ax = sns.lineplot(data=rolling_data)
    ax.fill_between(rolling_average.index, rolling_min.iloc[:, 0], rolling_max.iloc[:, 0], alpha=0.2)
    ax.set_title('Learning Curve', fontsize=16)
    ax.set_ylabel('Reward')
    ax.set_xlabel('Episodes')

    # Save figure
    img_path = f'{log_dir}learning_curve{window}.png'
    plt.savefig(img_path, dpi=200)

    # Log figure
    image = plt.imread(img_path)
    wandb.log({f'Learning_Curve_{window}': [wandb.Image(image, caption="Learning_curve")]})
//  [python]
def plot_reduction_errors(f, ax = None, figsize=(12,6)):
    """ Plots the resulting error/accuracy of a Forecaster object where `reduce_Xvars()` method has been called
    with method = 'pfi' or method = 'shap'.
    
    Args:
        f (Forecaster): An object that has called the `reduce_Xvars()` method with method = 'pfi'.
        ax (Axis): Optional. The existing axis to write the resulting figure to.
        figsize (tuple): Default (12,6). The size of the resulting figure. Ignored when ax is not None.
        
    Returns:
        (Axis) The figure's axis.

    >>> from scalecast.Forecaster import Forecaster
    >>> from scalecast.util import plot_reduction_errors
    >>> import matplotlib.pyplot as plt
    >>> import seaborn as sns
    >>> import pandas as pd
    >>> import pandas_datareader as pdr
    >>> 
    >>> df = pdr.get_data_fred('HOUSTNSA',start='1900-01-01',end='2021-06-01')
    >>> f = Forecaster(y=df['HOUSTNSA'],current_dates=df.index)
    >>> f.set_test_length(.2)
    >>> f.generate_future_dates(24)
    >>> f.add_ar_terms(24)
    >>> f.add_seasonal_regressors('month',raw=False,sincos=True,dummy=True)
    >>> f.add_seasonal_regressors('year')
    >>> f.add_time_trend()
    >>> f.reduce_Xvars(method='pfi')
    >>> plot_reduction_errors(f)
    >>> plt.show()
    """
    dropped = f.pfi_dropped_vars
    errors = f.pfi_error_values
    if ax is None:
        _, ax = plt.subplots(figsize=figsize)
    sns.lineplot(
        x=np.arange(0, len(dropped) + 1, 1), y=errors,
    )
    plt.xlabel("dropped Xvars")
    plt.ylabel("error")
    return ax
//  [python]
def plot(self, data=None, **fargs):
        if data is None:
            data = self.df
        data = data.melt("timeStamp", var_name="cols", value_name="vals")
        sns.tsplot(data=data, **fargs)
//  [python]
def plot(self, data=None, **fargs):
        if data is None:
            data = self.df
        data = data.melt("timeStamp", var_name="cols", value_name="vals")
        sns.lineplot(data=data, **fargs)
//  [python]
def rating(
    ctx: typer.Context,
    type: Optional[PerfType] = typer.Option(
        "blitz", help="Select type for which you want to see your rating"
    ),
):
    """Visualize the user's rating for selected chess game types"""
    config = create_config_from_options({**ctx.parent.params, **ctx.params})
    ratings = users_client.get_rating_history(config.user)
    available_types = [rating["name"].lower() for rating in ratings]
    if type not in available_types:
        print(
            f"User '{config.user}' did not play any '{type}' games yet! Time to play! :fire:"
        )

    for rating in ratings:
        name = rating["name"]
        if type is None or type == name.lower():
            ratings = [entry.rating for entry in rating["points"]]
            dates = [
                datetime.date(year=entry.year, month=entry.month + 1, day=entry.day)
                for entry in rating["points"]
            ]

            if ratings:
                console.log(f"Plotting {config.user}`s rating for '{type}' games")
                df = pd.DataFrame(index=dates, columns=[name], data=ratings)
                sns.set_theme(style="darkgrid")
                sns.plt.plot(df, palette="tab10", linewidth=2.5)
                plt.show()
            else:
                print(
                    f"User '{config.user}' did not play any '{type}' games yet! Time to play! :fire:"
                )
//  [python]
def rating(
    ctx: typer.Context,
    type: Optional[PerfType] = typer.Option(
        "blitz", help="Select type for which you want to see your rating"
    ),
):
    """Visualize the user's rating for selected chess game types"""
    config = create_config_from_options({**ctx.parent.params, **ctx.params})
    ratings = users_client.get_rating_history(config.user)
    available_types = [rating["name"].lower() for rating in ratings]
    if type not in available_types:
        print(
            f"User '{config.user}' did not play any '{type}' games yet! Time to play! :fire:"
        )

    for rating in ratings:
        name = rating["name"]
        if type is None or type == name.lower():
            ratings = [entry.rating for entry in rating["points"]]
            dates = [
                datetime.date(year=entry.year, month=entry.month + 1, day=entry.day)
                for entry in rating["points"]
            ]

            if ratings:
                console.log(f"Plotting {config.user}`s rating for '{type}' games")
                df = pd.DataFrame(index=dates, columns=[name], data=ratings)
                sns.set_theme(style="darkgrid")
                sns.lineplot(data=df, palette="tab10", linewidth=2.5)
                plt.show()
            else:
                print(
                    f"User '{config.user}' did not play any '{type}' games yet! Time to play! :fire:"
                )
//  [python]
def net_train(args, net, verbose = False):
    net.train()
    net.set_batch_size(args.tr_batch_size)
    opt = args.opt_outer_fn(net.parameters())
    tbar = range(1, args.tr_outer_epochs + 1)
    if verbose:
        tbar = tqdm(tbar)
        losses = []
    for epoch in tbar:
        opt.zero_grad()
        x, adj = tsp_gen(args.tr_batch_size, args.n_nodes)
        par0 = net(x, adj)
        par1 = tsp_optim(adj, par0, args.opt_inner_fn, args.tr_inner_epochs, args.tr_inner_samples)
        par0.backward(par1.grad / args.tr_batch_size)
        opt.step()
        if verbose:
            losses.append(tsp_greedy(adj, par1)[0].mean().item())
            tbar.set_description(f'[epoch {epoch}] loss={losses[-1]:.4f}')
        net.eval()
        torch.save(net.state_dict(), NET_SAVE_PATH % epoch)
        net.train()
    if verbose:
        ts = np.arange(1, args.tr_outer_epochs + 1)
        plt.plot(ts, losses)
        plt.title('loss vs epoch')
        plt.show()
    return net
//  [python]
def net_train(args, net, verbose = False):
    net.train()
    net.set_batch_size(args.tr_batch_size)
    opt = args.opt_outer_fn(net.parameters())
    tbar = range(1, args.tr_outer_epochs + 1)
    if verbose:
        tbar = tqdm(tbar)
        losses = []
    for epoch in tbar:
        opt.zero_grad()
        x, adj = tsp_gen(args.tr_batch_size, args.n_nodes)
        par0 = net(x, adj)
        par1 = tsp_optim(adj, par0, args.opt_inner_fn, args.tr_inner_epochs, args.tr_inner_samples)
        par0.backward(par1.grad / args.tr_batch_size)
        opt.step()
        if verbose:
            losses.append(tsp_greedy(adj, par1)[0].mean().item())
            tbar.set_description(f'[epoch {epoch}] loss={losses[-1]:.4f}')
        net.eval()
        torch.save(net.state_dict(), NET_SAVE_PATH % epoch)
        net.train()
    if verbose:
        ts = np.arange(1, args.tr_outer_epochs + 1)
        sns.lineplot(x = ts, y = losses)
        plt.title('loss vs epoch')
        plt.show()
    return net
//  [python]
def line_plot(
        df: pd.DataFrame,
        x: str,
        y: str,
        x_label: Optional[str] = None,
        y_label: Optional[str] = None,
        title: Optional[str] = None,
        save_path: Optional[Union[str, os.PathLike]] = None,
    ):

        check_instance(
            source=f"{PlottingMixin.line_plot.__name__} df",
            instance=df,
            accepted_types=(pd.DataFrame),
        )
        check_str(
            name=f"{PlottingMixin.line_plot.__name__} x",
            value=x,
            options=tuple(df.columns),
        )
        check_str(
            name=f"{PlottingMixin.line_plot.__name__} y",
            value=y,
            options=tuple(df.columns),
        )

        check_valid_lst(
            data=list(df[y]),
            source=f"{PlottingMixin.line_plot.__name__} y",
            valid_dtypes=(np.float32, np.float64, np.int32, np.int64, int, float),
        )
        sns.set_style("whitegrid", {"grid.linestyle": "--"})
        plot = sns.lineplot(data=df, x=x, y=y)

        if x_label is not None:
            check_str(name=f"{PlottingMixin.line_plot.__name__} x_label", value=x_label)
            plt.xlabel(x_label)
        if y_label is not None:
            check_str(name=f"{PlottingMixin.line_plot.__name__} y_label", value=y_label)
            plt.ylabel(y_label)
        if title is not None:
            check_str(name=f"{PlottingMixin.line_plot.__name__} title", value=title)
            plt.title(title, ha="center", fontsize=15)
        if save_path is not None:
            check_str(
                name=f"{PlottingMixin.line_plot.__name__} save_path", value=save_path
            )
            check_if_dir_exists(in_dir=os.path.dirname(save_path))
            plot.figure.savefig(save_path)
            plt.close("all")
        else:
            return plot
//  [python]
def tsp_optim(adj, ze0, opt_fn, steps, samples, epsilon = 0., show = 0, show_freq = 100, verbose = False, x = None):
    batch_size, n_nodes, _ = adj.shape
    ze = nn.Parameter(ze0.to(device), requires_grad = True)
    opt = opt_fn([ze])
    y_means = []
    tbar = range(1, steps + 1)
    if verbose:
        tbar = tqdm(tbar)
    y_bl = torch.zeros((batch_size, 1)).to(device)
    if show > 0:
        sol = [tsp_greedy(adj[ : show], ze[ : show])]
    for t in tbar:
        opt.zero_grad()
        y, logp, logq = tsp_sample(adj, ze, 'softmax', samples, epsilon)
        y_means.append(y.mean().item())
        if verbose:
            tbar.set_description(f'step={t} y_mean={y_means[-1]:.4f}')
        y_bl = y.mean(dim = -1, keepdim = True)
        J = (((y - y_bl) * torch.exp(logp - logq)).detach() * logp).mean(dim = -1).sum()
        J.backward()
        opt.step()
        if show > 0 and t % show_freq == 0:
            sol.append(tsp_greedy(adj[ : show], ze[ : show]))
    if verbose:
        ts = np.arange(1, steps + 1)
        plt.plot(ts, y_means)
        plt.title('E[y] vs step')
        plt.show()
    if show > 0:
        assert x is not None
        tsp_plot(
            x[ : show].repeat(len(sol), 1, 1),
            torch.cat([s[0] for s in sol], dim = 0),
            torch.cat([s[1] for s in sol], dim = 0),
            (len(sol), show),
        )
    return ze
//  [python]
def tsp_optim(adj, ze0, opt_fn, steps, samples, epsilon = 0., show = 0, show_freq = 100, verbose = False, x = None):
    batch_size, n_nodes, _ = adj.shape
    ze = nn.Parameter(ze0.to(device), requires_grad = True)
    opt = opt_fn([ze])
    y_means = []
    tbar = range(1, steps + 1)
    if verbose:
        tbar = tqdm(tbar)
    y_bl = torch.zeros((batch_size, 1)).to(device)
    if show > 0:
        sol = [tsp_greedy(adj[ : show], ze[ : show])]
    for t in tbar:
        opt.zero_grad()
        y, logp, logq = tsp_sample(adj, ze, 'softmax', samples, epsilon)
        y_means.append(y.mean().item())
        if verbose:
            tbar.set_description(f'step={t} y_mean={y_means[-1]:.4f}')
        y_bl = y.mean(dim = -1, keepdim = True)
        J = (((y - y_bl) * torch.exp(logp - logq)).detach() * logp).mean(dim = -1).sum()
        J.backward()
        opt.step()
        if show > 0 and t % show_freq == 0:
            sol.append(tsp_greedy(adj[ : show], ze[ : show]))
    if verbose:
        ts = np.arange(1, steps + 1)
        sns.lineplot(x = ts, y = y_means)
        plt.title('E[y] vs step')
        plt.show()
    if show > 0:
        assert x is not None
        tsp_plot(
            x[ : show].repeat(len(sol), 1, 1),
            torch.cat([s[0] for s in sol], dim = 0),
            torch.cat([s[1] for s in sol], dim = 0),
            (len(sol), show),
        )
    return ze
//  [python]
def plot_efficientnet_results(ax=None, save=False, xcol='MParams'):
    # df = load_efficientnet_results()
    df = load_existing_models_results()

    # ycol = 'Top1'
    ycol = 'Top5'
    dset = 'ImageNet'

    # these are so extreme in some dimension that they mess up the {x,y}lims
    df = df[~df['Method'].isin(
        ['GPipe (2018)', 'AlexNet (2012)', 'SqueezeNet (2016)'])]

    df = df[~df[xcol].isna()]

    given_ax = ax is None
    if given_ax:
        _, ax = plt.subplots(figsize=(10, 8))

    filled_markers = ('o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd', 'P', 'X')
    filled_markers += filled_markers

    for i, method in enumerate(list(df['Method'].unique())):
        subdf = df[df['Method'] == method]
        marker = filled_markers[i % len(filled_markers)]
        plt.plot(subdf[xcol], subdf[ycol], marker=marker, label=method)


    if given_ax:
        plt.legend()
    if 'params' in xcol.lower():
        plt.semilogx()
    plt.title('{} vs Top 1 Accuracy for various architectures on {}'.format(xcol, dset))
    plt.xlabel(xcol)
    plt.ylabel(ycol)

    # print(df)

    if save:
        # path = FIGS_SAVE_DIR / fname
        fname = '{}_{}_{}_{}'.format(dset, model, xcol, ycol)
        save_fig(fname)
    else:
        plt.show()
    plt.close()
//  [python]
def plot_efficientnet_results(ax=None, save=False, xcol='MParams'):
    # df = load_efficientnet_results()
    df = load_existing_models_results()

    # ycol = 'Top1'
    ycol = 'Top5'
    dset = 'ImageNet'

    # these are so extreme in some dimension that they mess up the {x,y}lims
    df = df[~df['Method'].isin(
        ['GPipe (2018)', 'AlexNet (2012)', 'SqueezeNet (2016)'])]

    df = df[~df[xcol].isna()]

    given_ax = ax is None
    if given_ax:
        _, ax = plt.subplots(figsize=(10, 8))

    filled_markers = ('o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd', 'P', 'X')
    filled_markers += filled_markers

    sb.lineplot(data=df, x=df[xcol], y=df[ycol], estimator=np.median,
                ax=ax, style='Method', hue='Method', dashes=False,
                markers=filled_markers, legend='brief')

    # for i, method in enumerate(list(df['Method'].unique())):
    #     subdf = df[df['Method'] == method]
    #     # if subdf.shape[0] == 1:
    #     #     # plt.scatter(subdf[xcol], subdf[ycol], label=method)
    #     #     ax.scatter(subdf[xcol], subdf[ycol], label=method)
    #     #     continue
    #     marker = ALL_NOT_HIDEOUS_MARKERS[i % len(ALL_NOT_HIDEOUS_MARKERS)]
    #     print("method, marker: ", method, marker)
    #     sb.lineplot(x=subdf[xcol], y=subdf[ycol], estimator=np.median,
    #                 label=method, ax=ax, markers=marker)

    if given_ax:
        plt.legend()
    if 'params' in xcol.lower():
        plt.semilogx()
    plt.title('{} vs Top 1 Accuracy for various architectures on {}'.format(xcol, dset))
    plt.xlabel(xcol)
    plt.ylabel(ycol)

    # print(df)

    if save:
        # path = FIGS_SAVE_DIR / fname
        fname = '{}_{}_{}_{}'.format(dset, model, xcol, ycol)
        save_fig(fname)
    else:
        plt.show()
    plt.close()
//  [python]
def plot_refOp_vs_refTflite_rmse_fig():
    mobilenetv3_tflite_vs_CloudQuantRef = "python/plots/analysis_results/MobileNetV3_Small/tflite_vs_cloudQuant/0_0_debug_report.csv"
    output_start = 114
    pd_data = get_norm_rmse_from_csv(fp=mobilenetv3_tflite_vs_CloudQuantRef,
                                     output_row_start=output_start)
    refOp_vs_refTflite_rmse_fig = "python/plots/refOp_vs_refTflite_rmse.png"
    # plot_norm_RMSE(norm_rmse=pd_data, output_dir=refOp_vs_refTflite_rmse_fig)
    plt.figure()
    print(pd_data)
    plt.plot(pd_data, marker='o')
    plt.xlabel("Layer Index")
    plt.ylabel("Normalized rMSE")
    plt.legend("MobileNetv3 Small")
    plt.title("Mobile Quant Ref vs. Mobile")
    plt.savefig(refOp_vs_refTflite_rmse_fig)
//  [python]
def plot_refOp_vs_refTflite_rmse_fig():
    mobilenetv3_tflite_vs_CloudQuantRef = "python/plots/analysis_results/MobileNetV3_Small/tflite_vs_cloudQuant/0_0_debug_report.csv"
    output_start = 114
    pd_data = get_norm_rmse_from_csv(fp=mobilenetv3_tflite_vs_CloudQuantRef,
                                     output_row_start=output_start)
    refOp_vs_refTflite_rmse_fig = "python/plots/refOp_vs_refTflite_rmse.png"
    # plot_norm_RMSE(norm_rmse=pd_data, output_dir=refOp_vs_refTflite_rmse_fig)
    plt.figure()
    print(pd_data)
    sns.lineplot(data=pd_data, markers=True)
    plt.xlabel("Layer Index")
    plt.ylabel("Normalized rMSE")
    plt.legend("MobileNetv3 Small")
    plt.title("Mobile Quant Ref vs. Mobile")
    plt.savefig(refOp_vs_refTflite_rmse_fig)
//  [python]
def plot_curves(df, out_pref="test", title="", ax=None, **kwargs):
    """
    Plot precision recall curves, or (TODO) ROC curves 
    """
    # make a prec-rec plot per term
    for term in sorted(df["#term"].unique()):
        curr_df = df[df['#term'] == term]
        plot_df = curr_df.copy()
        # get only the positive examples to plot prec_rec
        #curr_df = curr_df[curr_df['pos/neg'] == 1]
        # also put the fmax on the plot, and add it to the label
        new_alg_names = []
        fmax_points = {}
        for alg in curr_df['Algorithm'].unique():
            df_alg = plot_df[plot_df['Algorithm'] == alg]
            #print(df_alg['prec'], df_alg['rec'])
            fmax, idx = eval_utils.compute_fmax(df_alg['prec'].values, df_alg['rec'].values, fmax_idx=True)
            new_alg_name = "%s (%0.3f)" % (alg, fmax)
            new_alg_names.append(new_alg_name) 
            fmax_points[alg] = (df_alg['prec'].values[idx], df_alg['rec'].values[idx])

        fig, ax = plt.subplots()
        sns.tsplot(x='rec', y='prec', hue='Algorithm', data=plot_df,
                    #ci=kwargs.get('ci',95), ax=ax, legend=False,
                    # use this to show the individual replicates
                    units='repetition', estimator=None, lw=0.3, alpha=0.1,
                    ax=ax, legend=False,
                )

        ax.set_xlim(-0.02,1.02)
        ax.set_ylim(-0.02,1.02)

        ax.legend(title="Alg (Fmax)", labels=new_alg_names)
        ax.set_xlabel("Recall")
        ax.set_ylabel("Precision")

        # also add the fmax point to the plot
        for i, alg in enumerate(fmax_points):
            prec, rec = fmax_points[alg]
            ax.plot([rec], [prec], marker="*", color=sns.color_palette()[i])

        if kwargs.get('term_stats') is not None:
            df_stats = kwargs['term_stats'] 
            curr_df_stats = df_stats[df_stats['#GO term'] == term]
            # TODO what if there are multiple stats lines?
            term_name = curr_df_stats['GO term name'].values[0]
            term_cat = curr_df_stats['GO category'].values[0]
            # For HPO, map O to Phenotypic abnormality
            cat_map = {"O": "PA", 'P': 'BP', 'F': 'MF', 'c': 'CC'}
            term_cat = cat_map[term_cat] if term_cat in cat_map else term_cat
            term_ann = curr_df_stats['# positive examples'].values[0]
            print(term_name, term_cat, term_ann)
            ax.set_title(title + "\n %s (%s) - %s, %s ann" % (term_name, term, term_cat, term_ann))
        else:
            ax.set_title(title + " %s" % (term))

        if out_pref is not None:
            out_file = "%s%s-prec-rec.pdf" % (out_pref, term)
            savefig(out_file)
//  [python]
def plot_curves(df, out_pref="test", title="", ax=None, **kwargs):
    """
    Plot precision recall curves, or (TODO) ROC curves 
    """
    # make a prec-rec plot per term
    for term in sorted(df["#term"].unique()):
        curr_df = df[df['#term'] == term]
        plot_df = curr_df.copy()
        # get only the positive examples to plot prec_rec
        #curr_df = curr_df[curr_df['pos/neg'] == 1]
        # also put the fmax on the plot, and add it to the label
        new_alg_names = []
        fmax_points = {}
        for alg in curr_df['Algorithm'].unique():
            df_alg = plot_df[plot_df['Algorithm'] == alg]
            #print(df_alg['prec'], df_alg['rec'])
            fmax, idx = eval_utils.compute_fmax(df_alg['prec'].values, df_alg['rec'].values, fmax_idx=True)
            new_alg_name = "%s (%0.3f)" % (alg, fmax)
            new_alg_names.append(new_alg_name) 
            fmax_points[alg] = (df_alg['prec'].values[idx], df_alg['rec'].values[idx])

        fig, ax = plt.subplots()
        sns.lineplot(x='rec', y='prec', hue='Algorithm', data=plot_df,
                    #ci=kwargs.get('ci',95), ax=ax, legend=False,
                    # use this to show the individual replicates
                    units='repetition', estimator=None, lw=0.3, alpha=0.1,
                    ax=ax, legend=False,
                )

        ax.set_xlim(-0.02,1.02)
        ax.set_ylim(-0.02,1.02)

        ax.legend(title="Alg (Fmax)", labels=new_alg_names)
        ax.set_xlabel("Recall")
        ax.set_ylabel("Precision")

        # also add the fmax point to the plot
        for i, alg in enumerate(fmax_points):
            prec, rec = fmax_points[alg]
            ax.plot([rec], [prec], marker="*", color=sns.color_palette()[i])

        if kwargs.get('term_stats') is not None:
            df_stats = kwargs['term_stats'] 
            curr_df_stats = df_stats[df_stats['#GO term'] == term]
            # TODO what if there are multiple stats lines?
            term_name = curr_df_stats['GO term name'].values[0]
            term_cat = curr_df_stats['GO category'].values[0]
            # For HPO, map O to Phenotypic abnormality
            cat_map = {"O": "PA", 'P': 'BP', 'F': 'MF', 'c': 'CC'}
            term_cat = cat_map[term_cat] if term_cat in cat_map else term_cat
            term_ann = curr_df_stats['# positive examples'].values[0]
            print(term_name, term_cat, term_ann)
            ax.set_title(title + "\n %s (%s) - %s, %s ann" % (term_name, term, term_cat, term_ann))
        else:
            ax.set_title(title + " %s" % (term))

        if out_pref is not None:
            out_file = "%s%s-prec-rec.pdf" % (out_pref, term)
            savefig(out_file)
//  [python]
def plot_one_model(mobilenetv2_quant_vs_CloudQuantRef_pd, mobilenetv2_quantRef_vs_CloudQuantRef_pd, model_name, quant_vs_CloudQuantRef_fig):

    quant_vs_CloudQuantRef_data = pd.DataFrame(
        [mobilenetv2_quant_vs_CloudQuantRef_pd, mobilenetv2_quantRef_vs_CloudQuantRef_pd])

    quant_vs_CloudQuantRef_data = quant_vs_CloudQuantRef_data.transpose()
    quant_vs_CloudQuantRef_data.columns = [f'{model_name} Quant', f'{model_name} Quant Ref']
    print(quant_vs_CloudQuantRef_data)
    quant_vs_CloudQuantRef_data = quant_vs_CloudQuantRef_data.stack().reset_index()
    quant_vs_CloudQuantRef_data.columns = ['Layer Index', 'Pipeline', 'normRMSE']

    print(quant_vs_CloudQuantRef_data)

    plt.figure(figsize=[5.2, 3.9])

    sns.pointplot(data=quant_vs_CloudQuantRef_data, x='Layer Index', y='normRMSE', hue="Pipeline", markers=["o", "x"])

    plt.legend([f'Quant vs Baseline', f'Quant Ref vs. Baseline'],
               loc='upper right')
    plt.xlabel("Layer Index")
    plt.ylabel("Normalized rMSE")
    plt.title(f"{model_name}")
    plt.ylim([0, 1])
    plt.savefig(quant_vs_CloudQuantRef_fig)
//  [python]
def plot_one_model(mobilenetv2_quant_vs_CloudQuantRef_pd, mobilenetv2_quantRef_vs_CloudQuantRef_pd, model_name, quant_vs_CloudQuantRef_fig):

    quant_vs_CloudQuantRef_data = pd.DataFrame(
        [mobilenetv2_quant_vs_CloudQuantRef_pd, mobilenetv2_quantRef_vs_CloudQuantRef_pd])

    quant_vs_CloudQuantRef_data = quant_vs_CloudQuantRef_data.transpose()
    quant_vs_CloudQuantRef_data.columns = [f'{model_name} Quant', f'{model_name} Quant Ref']
    print(quant_vs_CloudQuantRef_data)
    quant_vs_CloudQuantRef_data = quant_vs_CloudQuantRef_data.stack().reset_index()
    quant_vs_CloudQuantRef_data.columns = ['Layer Index', 'Pipeline', 'normRMSE']

    print(quant_vs_CloudQuantRef_data)

    plt.figure(figsize=[5.2, 3.9])

    sns.lineplot(data=quant_vs_CloudQuantRef_data, x='Layer Index', y='normRMSE', hue="Pipeline", style="Pipeline",
                 markers=True)

    plt.legend([f'Quant vs Baseline', f'Quant Ref vs. Baseline'],
               loc='upper right')
    plt.xlabel("Layer Index")
    plt.ylabel("Normalized rMSE")
    plt.title(f"{model_name}")
    plt.ylim([0, 1])
    plt.savefig(quant_vs_CloudQuantRef_fig)
//  [python]
def _plot_distribution_line(data, ax, **kwargs):
    sb.pointplot(data=data, x="state", y="probability", ax=ax, **kwargs)
    return ax
//  [python]
def _plot_distribution_line(data, ax, **kwargs):
    sb.lineplot(data=data, x="state", y="probability", ax=ax, **kwargs)
    return ax
//  [python]
def plot_avg_coverage_vs_time(hwf_cov_df, rfuzz_cov_df, time_units="m"):
  print(yellow("Generating plot ..."))

  # Set plot style and extract only HDL line coverage
  sns.set_theme(context="notebook", style="darkgrid")
  hdl_cov_df = pd.concat([hwf_cov_df, rfuzz_cov_df])

  # create figure and plot the data
  fig, ax = plt.subplots(1, 1, figsize=(6, 4))
  sns.pointplot(data=hdl_cov_df,
               x=TIME_LABEL,
               y=COVERAGE_LABEL,
               hue=TOPLEVEL_LABEL,
               style=FUZZER_LABEL,
               ax=ax)

  # format the plot
  if time_units == "m":
    time_units_label = "min."
  elif time_units == "h":
    time_units_label = "hours"
  else:
    time_units_label = "s"
  ax.set_xlabel(TIME_LABEL + " (%s)" % time_units_label,
                fontsize=LABEL_FONT_SIZE)
  ax.set_ylabel("HDL Line " + COVERAGE_LABEL, fontsize=LABEL_FONT_SIZE)
  ax.tick_params("x", labelsize=TICK_FONT_SIZE)
  ax.tick_params("y", labelsize=TICK_FONT_SIZE)
  plt.legend(fontsize=LEGEND_FONT_SIZE,
             title_fontsize=LEGEND_TITLE_FONT_SIZE,
             bbox_to_anchor=(1.01, 0.75),
             loc='upper left')
  plt.tight_layout()

  # save the plot
  plt.savefig(PLOT_FILE_NAME, format=PLOT_FORMAT)
  print(green("Done."))
  print(LINE_SEP)
//  [python]
def plot_avg_coverage_vs_time(hwf_cov_df, rfuzz_cov_df, time_units="m"):
  print(yellow("Generating plot ..."))

  # Set plot style and extract only HDL line coverage
  sns.set_theme(context="notebook", style="darkgrid")
  hdl_cov_df = pd.concat([hwf_cov_df, rfuzz_cov_df])

  # create figure and plot the data
  fig, ax = plt.subplots(1, 1, figsize=(6, 4))
  sns.lineplot(data=hdl_cov_df,
               x=TIME_LABEL,
               y=COVERAGE_LABEL,
               hue=TOPLEVEL_LABEL,
               style=FUZZER_LABEL,
               ax=ax)

  # format the plot
  if time_units == "m":
    time_units_label = "min."
  elif time_units == "h":
    time_units_label = "hours"
  else:
    time_units_label = "s"
  ax.set_xlabel(TIME_LABEL + " (%s)" % time_units_label,
                fontsize=LABEL_FONT_SIZE)
  ax.set_ylabel("HDL Line " + COVERAGE_LABEL, fontsize=LABEL_FONT_SIZE)
  ax.tick_params("x", labelsize=TICK_FONT_SIZE)
  ax.tick_params("y", labelsize=TICK_FONT_SIZE)
  plt.legend(fontsize=LEGEND_FONT_SIZE,
             title_fontsize=LEGEND_TITLE_FONT_SIZE,
             bbox_to_anchor=(1.01, 0.75),
             loc='upper left')
  plt.tight_layout()

  # save the plot
  plt.savefig(PLOT_FILE_NAME, format=PLOT_FORMAT)
  print(green("Done."))
  print(LINE_SEP)
//  [python]
def main():
    expl_var_dirs = glob.glob(os.path.join(sys.argv[1], "*"))
    auc_tables = []

    for expl_var_path in expl_var_dirs:
        if os.path.isdir(expl_var_path):
            expl_variance = expl_var_path.split("_")[4][1]
            expl_variance_title = "0.{}".format(expl_variance)
            print(expl_var_path, expl_variance_title)
            auc_file_paths = glob.glob(os.path.join(expl_var_path, "*", "predictions_auc_bonf.pkl"))
            for auc_file_path in auc_file_paths:
                auc_df = pd.read_pickle(auc_file_path)
                database_name = auc_file_path.split("/")[2]
                database_title = database_trans_table[database_name]
                print(database_title, database_name)
                single_df = pd.DataFrame(
                    {"AUC": auc_df["auc"],
                     "pathway": database_title,
                     "group": expl_variance_title})
                auc_tables.append(single_df)


    total_df = pd.concat(auc_tables)
    total_df.sort_values(by="group", inplace=True)
    fig, ax = plt.subplots(1, 1, figsize=(1 * 14, 12), subplot_kw= dict(facecolor="white"))

    calculate_p_val(total_df)

    print("total_df means average", total_df.groupby(["group"]).mean())
    sns.pointplot("group", "AUC", hue="pathway",
                 markers=["o"] * 4,
                 data=total_df,
                 palette=color_table,
                 # ci="sd",
                 ci=None,
                 sort=False,
                 zorder=10, ax=ax, alpha=0.3, err_kws={"alpha": 0.3})
    sns.pointplot("group", "AUC", markers=["o"] * 4,
                 data=total_df, sort=False, ci=None,
                 zorder=10, ax=ax, color="black", label="Average")
    ax.set_xlabel("Explained variance")
    ax.set_ylabel("Mean AUC")
    ax.set_title("Explained variance cutoffs of GeneNetwork data")

    ax.grid(False)

    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')

    ax.spines['bottom'].set_position(('axes', -0.05))
    ax.yaxis.set_ticks_position('left')
    ax.spines['left'].set_position(('axes', -0.05))
    ax.spines['left'].set_color("black")
    ax.spines['bottom'].set_color("black")
    plt.legend(title="Pathway name")




    fig_path = os.path.join(sys.argv[1], "genenetwork_expl_var_auc.png")
    plt.savefig(fig_path, dpi=300, bbox_inches='tight')
    print("Figure created: {}".format(fig_path))
    fig_path = os.path.join(sys.argv[1], "genenetwork_expl_var_auc.pdf")
    plt.savefig(fig_path, dpi=300, bbox_inches='tight')
    print("Figure created: {}".format(fig_path))
//  [python]
def main():
    expl_var_dirs = glob.glob(os.path.join(sys.argv[1], "*"))
    auc_tables = []

    for expl_var_path in expl_var_dirs:
        if os.path.isdir(expl_var_path):
            expl_variance = expl_var_path.split("_")[4][1]
            expl_variance_title = "0.{}".format(expl_variance)
            print(expl_var_path, expl_variance_title)
            auc_file_paths = glob.glob(os.path.join(expl_var_path, "*", "predictions_auc_bonf.pkl"))
            for auc_file_path in auc_file_paths:
                auc_df = pd.read_pickle(auc_file_path)
                database_name = auc_file_path.split("/")[2]
                database_title = database_trans_table[database_name]
                print(database_title, database_name)
                single_df = pd.DataFrame(
                    {"AUC": auc_df["auc"],
                     "pathway": database_title,
                     "group": expl_variance_title})
                auc_tables.append(single_df)


    total_df = pd.concat(auc_tables)
    total_df.sort_values(by="group", inplace=True)
    fig, ax = plt.subplots(1, 1, figsize=(1 * 14, 12), subplot_kw= dict(facecolor="white"))

    calculate_p_val(total_df)

    print("total_df means average", total_df.groupby(["group"]).mean())
    sns.lineplot("group", "AUC", hue="pathway", style="pathway",
                 markers=["o"] * 4, dashes=False,
                 data=total_df,
                 palette=color_table,
                 # ci="sd",
                 ci=None,
                 sort=False,
                 zorder=10, ax=ax, alpha=0.3, err_kws={"alpha": 0.3})
    sns.lineplot("group", "AUC", markers=["o"] * 4, dashes=False,
                 data=total_df, sort=False, ci=None,
                 zorder=10, ax=ax, color="black", label="Average")
    ax.set_xlabel("Explained variance")
    ax.set_ylabel("Mean AUC")
    ax.set_title("Explained variance cutoffs of GeneNetwork data")

    ax.grid(False)

    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')

    ax.spines['bottom'].set_position(('axes', -0.05))
    ax.yaxis.set_ticks_position('left')
    ax.spines['left'].set_position(('axes', -0.05))
    ax.spines['left'].set_color("black")
    ax.spines['bottom'].set_color("black")
    plt.legend(title="Pathway name")




    fig_path = os.path.join(sys.argv[1], "genenetwork_expl_var_auc.png")
    plt.savefig(fig_path, dpi=300, bbox_inches='tight')
    print("Figure created: {}".format(fig_path))
    fig_path = os.path.join(sys.argv[1], "genenetwork_expl_var_auc.pdf")
    plt.savefig(fig_path, dpi=300, bbox_inches='tight')
    print("Figure created: {}".format(fig_path))
//  [python]
def vis_training_curves(history=None, output_dir: str = None) -> None:
    """
    Visualizes the training curves of the model.

    Args:
        history: The history object returned by the model.fit() method.
        output_dir (Optional[str]): The output directory to save the training curves plot.

    Returns:
        None
    """
    # Extract the accuracy and loss values for training and validation data
    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    epochs_range = range(len(acc))

    # Create dataframes for the training and validation data
    df_val = pd.DataFrame(
        {'run': 'validation', 'step': epochs_range, 'epoch_accuracy': val_acc, 'epoch_loss': val_loss})
    df_train = pd.DataFrame({'run': 'train', 'step': epochs_range, 'epoch_accuracy': acc, 'epoch_loss': loss})

    # Concatenate the dataframes
    frames = [df_val, df_train]
    df = pd.concat(frames)
    df = df.reset_index()

    # Plot the training curves
    plt.figure(figsize=(16, 6))
    plt.suptitle('Training curves', fontsize=16)
    plt.subplot(1, 2, 1)
    sns.pointplot(data=df, x="step", y="epoch_accuracy", hue="run").set_title("accuracy")
    plt.grid()
    plt.subplot(1, 2, 2)
    sns.pointplot(data=df, x="step", y="epoch_loss", hue="run").set_title("loss")
    plt.grid()
    plt.savefig(os.path.join(output_dir, 'Training_curves.png'))
//  [python]
def vis_training_curves(history=None, output_dir: str = None) -> None:
    """
    Visualizes the training curves of the model.

    Args:
        history: The history object returned by the model.fit() method.
        output_dir (Optional[str]): The output directory to save the training curves plot.

    Returns:
        None
    """
    # Extract the accuracy and loss values for training and validation data
    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    epochs_range = range(len(acc))

    # Create dataframes for the training and validation data
    df_val = pd.DataFrame(
        {'run': 'validation', 'step': epochs_range, 'epoch_accuracy': val_acc, 'epoch_loss': val_loss})
    df_train = pd.DataFrame({'run': 'train', 'step': epochs_range, 'epoch_accuracy': acc, 'epoch_loss': loss})

    # Concatenate the dataframes
    frames = [df_val, df_train]
    df = pd.concat(frames)
    df = df.reset_index()

    # Plot the training curves
    plt.figure(figsize=(16, 6))
    plt.suptitle('Training curves', fontsize=16)
    plt.subplot(1, 2, 1)
    sns.lineplot(data=df, x="step", y="epoch_accuracy", hue="run").set_title("accuracy")
    plt.grid()
    plt.subplot(1, 2, 2)
    sns.lineplot(data=df, x="step", y="epoch_loss", hue="run").set_title("loss")
    plt.grid()
    plt.savefig(os.path.join(output_dir, 'Training_curves.png'))
//  [python]
def PlotPowerLawRelationship(df, x_axis_col, y_axis_col, title, gamma, scale):
    plt.clf()  # make sure we're starting with a fresh plot
    # filter out zeros
    df = df[df[x_axis_col] > 0]
    df = df[df[y_axis_col] > 0]

    log_x_axis_label = f"natural log ({x_axis_col})"
    log_y_axis_label = f"natural log ({y_axis_col})"
    log_x_vals = np.log(df[x_axis_col])
    log_y_vals = np.log(df[y_axis_col])
    values = np.vstack([log_x_vals, log_y_vals])
    kernel = stats.gaussian_kde(values)(values)
    ax = sns.scatterplot(x=log_x_vals, y=log_y_vals, c=kernel, cmap="viridis")

    fitted_y_vals = scale + -1 * gamma * log_x_vals
    plt.plot(
        log_x_vals, fitted_y_vals, color="red", label="Fitted Powerlaw Fit"
    )
    ax.set(title=title)
    ax.set_xlabel(log_x_axis_label)
    ax.set_ylabel(log_y_axis_label)
    return ax.get_figure()
//  [python]
def PlotPowerLawRelationship(df, x_axis_col, y_axis_col, title, gamma, scale):
    plt.clf()  # make sure we're starting with a fresh plot
    # filter out zeros
    df = df[df[x_axis_col] > 0]
    df = df[df[y_axis_col] > 0]

    log_x_axis_label = f"natural log ({x_axis_col})"
    log_y_axis_label = f"natural log ({y_axis_col})"
    log_x_vals = np.log(df[x_axis_col])
    log_y_vals = np.log(df[y_axis_col])
    values = np.vstack([log_x_vals, log_y_vals])
    kernel = stats.gaussian_kde(values)(values)
    ax = sns.scatterplot(x=log_x_vals, y=log_y_vals, c=kernel, cmap="viridis")

    fitted_y_vals = scale + -1 * gamma * log_x_vals
    sns.lineplot(
        x=log_x_vals, y=fitted_y_vals, color="red", label="Fitted Powerlaw Fit"
    )
    ax.set(title=title)
    ax.set_xlabel(log_x_axis_label)
    ax.set_ylabel(log_y_axis_label)
    return ax.get_figure()
//  [python]
def plot_avg_coverage_vs_time_broken(hwf_cov_df, rfuzz_cov_df, time_units="m"):
  print(yellow("Generating plot ..."))

  # Set plot style and extract only HDL line coverage
  # sns.set_theme(context="notebook", style="darkgrid")
  hdl_cov_df = pd.concat([hwf_cov_df, rfuzz_cov_df])

  # create subplots
  fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(6, 4))

  # create figure and plot the data
  # fig, ax = plt.subplots(1, 1, figsize=(6, 4))
  sns.pointplot(data=hdl_cov_df,
               x=TIME_LABEL,
               y=COVERAGE_LABEL,
               hue=TOPLEVEL_LABEL,
               style=FUZZER_LABEL,
               ax=ax1)
  sns.pointplot(data=hdl_cov_df,
               x=TIME_LABEL,
               y=COVERAGE_LABEL,
               hue=TOPLEVEL_LABEL,
               style=FUZZER_LABEL,
               ax=ax2)

  # set axis ranges
  ax1.set_ylim(0.3, 1.0)
  ax2.set_ylim(0, 0.05)

  # hide the spines between the two axes
  ax1.spines['bottom'].set_visible(False)
  ax2.spines['top'].set_visible(False)
  ax1.xaxis.tick_top()
  ax1.tick_params(labeltop=False)
  ax2.xaxis.tick_bottom()

  # format the plot
  if time_units == "m":
    time_units_label = "min."
  elif time_units == "h":
    time_units_label = "hours"
  else:
    time_units_label = "s"
  # ax1.set_xlabel(TIME_LABEL + " (%s)" % time_units_label,
  # fontsize=LABEL_FONT_SIZE)
  # ax1.set_ylabel("HDL Line " + COVERAGE_LABEL, fontsize=LABEL_FONT_SIZE)
  # ax1.tick_params("x", labelsize=TICK_FONT_SIZE)
  # ax1.tick_params("y", labelsize=TICK_FONT_SIZE)
  # plt.legend(fontsize=LEGEND_FONT_SIZE,
  # title_fontsize=LEGEND_TITLE_FONT_SIZE,
  # bbox_to_anchor=(1.01, 0.75),
  # loc='upper left')
  plt.tight_layout()

  # save the plot
  plt.savefig(PLOT_FILE_NAME, format=PLOT_FORMAT)
  print(green("Done."))
  print(LINE_SEP)