jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def plot_normalized_match_length(input_csv, outfolder):
    matplotlib.rcParams.update({'font.size': 16})
    sns.set(font_scale=1.1)
    indata = pd.read_csv(input_csv,sep='\t')
    # ax = sns.barplot(x="ref_id", y="nr_hits", hue="method", data=indata,
    #                       hue_order= ["randstrobes", "kmers"])
    plt.tick_params(axis='x', which='minor', labelsize=7)
    ax = sns.lineplot(x="ref_id", y="normalized_match_length", hue="method", ci = "sd", hue_order= ["randstrobes-(3,10,20,70)", "randstrobes-(2,15,20,70)", "hybridstrobes-(3,10,20,70)", "hybridstrobes-(2,15,20,70)", "minstrobes-(3,10,20,70)", "minstrobes-(2,15,20,70)", "kmers"], 
                        data=indata, markers=True)
    plt.xlabel('SIRV')
    plt.ylabel('Normalized NAM length')
    plt.tick_params(rotation=90)
    # ax.set_xticklabels(size = 10)
    ax.set_xticklabels(ax.get_xmajorticklabels())
    plt.ylim(0, 1)
    plt.tight_layout()
    plt.legend(loc='upper left', labels = ["randstrobes-(3,10,20,70)", "randstrobes-(2,15,20,70)", "hybridstrobes-(3,10,20,70)", "hybridstrobes-(2,15,20,70)", "minstrobes-(3,10,20,70)", "minstrobes-(2,15,20,70)", r'$k$-mers'])
    # ax.set_ylabel("Fraction correct")
    # ax.set_xlabel("Exon size")
    # plt.savefig(os.path.join(outfolder, "plot_normalized_match_length.eps"))
    plt.savefig(os.path.join(outfolder, "plot_normalized_match_length.pdf"))
    plt.clf()
    plt.close()
//  [python]
def plot_coverage_vs_time(coverage_dfs):
  print(yellow("Generating plots ..."))
  cov_metrics = [
      SW_LINE_COVERAGE_LABEL, SW_REGION_COVERAGE_LABEL, HW_LINE_COVERAGE_LABEL
  ]
  num_cores = len(TOPLEVELS)
  num_cov_metrics = len(cov_metrics)
  sns.set_theme(context="notebook", style="darkgrid")
  fig, axes = plt.subplots(num_cov_metrics,
                           num_cores,
                           sharex=True,
                           sharey=True)
  for trial in range(len(coverage_dfs)):
    # Select experiment trial number
    cov_df = coverage_dfs[trial]
    for row in range(len(axes)):
      # select portion of data corresponding to current COVERAGE METRIC
      sub_cov_df = cov_df[cov_df[COVERAGE_TYPE_LABEL] == cov_metrics[row]]
      for col in range(len(axes[row])):
        # select portion of data corresponding to current core
        plt_df = sub_cov_df[sub_cov_df[TOPLEVEL_LABEL] == TOPLEVELS[col]]
        # sns.set_context("paper")
        curr_ax = sns.lineplot(data=plt_df,
                               x=TIME_LABEL,
                               y=COVERAGE_LABEL,
                               hue=GRAMMAR_LABEL,
                               ax=axes[row][col],
                               legend=False)
        if row == 0 and col == 0 and trial == 0:
          lines = curr_ax.get_lines()
        axes[row][col].set_title("Coverage = %s | Core = %s" %
                                 (cov_metrics[row], TOPLEVELS[col]))
  fig.legend(
      lines,
      [
          "Const. Opcode & Variable Frame",
          "Const. Opcode & Fixed Frame",
          "Mapped Opcode & Variable Frame",
          "Mapped Opcode & Fixed Frame",
      ],
      loc="lower center",
      ncol=4,
  )
  print(green("Done."))
  print(LINE_SEP)
  plt.show()
//  [python]
def plot_mean_std(real: pd.DataFrame, fake: pd.DataFrame, ax=None, fname=None):
    """
    Plot the means and standard deviations of each dataset.

    :param real: DataFrame containing the real data
    :param fake: DataFrame containing the fake data
    :param ax: Axis to plot on. If none, a new figure is made.
    :param fname: If not none, saves the plot with this file name.
    """
    if ax is None:
        fig, ax = plt.subplots(1, 2, figsize=(10, 5))
        fig.suptitle('Absolute Log Mean and STDs of numeric data\n', fontsize=16)

    ax[0].grid(True)
    ax[1].grid(True)
    real = real.select_dtypes(include='number')
    fake = fake.select_dtypes(include='number')
    real_mean = np.log(np.add(abs(real.mean()).values, 1e-5))
    fake_mean = np.log(np.add(abs(fake.mean()).values, 1e-5))
    min_mean = min(real_mean) - 1
    max_mean = max(real_mean) + 1
    line = np.arange(min_mean, max_mean)
    sns.plt.plot(line, line, ax=ax[0])
    sns.scatterplot(x=real_mean,
                    y=fake_mean,
                    ax=ax[0])
    ax[0].set_title('Means of real and fake data')
    ax[0].set_xlabel('real data mean (log)')
    ax[0].set_ylabel('fake data mean (log)')

    real_std = np.log(np.add(real.std().values, 1e-5))
    fake_std = np.log(np.add(fake.std().values, 1e-5))
    min_std = min(real_std) - 1
    max_std = max(real_std) + 1
    line = np.arange(min_std, max_std)
    sns.plt.plot(line, line, ax=ax[1])
    sns.scatterplot(x=real_std,
                    y=fake_std,
                    ax=ax[1])
    ax[1].set_title('Stds of real and fake data')
    ax[1].set_xlabel('real data std (log)')
    ax[1].set_ylabel('fake data std (log)')

    if fname is not None:
        plt.savefig(fname)

    if ax is None:
        plt.show()
//  [python]
def plot_mean_std(real: pd.DataFrame, fake: pd.DataFrame, ax=None, fname=None):
    """
    Plot the means and standard deviations of each dataset.

    :param real: DataFrame containing the real data
    :param fake: DataFrame containing the fake data
    :param ax: Axis to plot on. If none, a new figure is made.
    :param fname: If not none, saves the plot with this file name.
    """
    if ax is None:
        fig, ax = plt.subplots(1, 2, figsize=(10, 5))
        fig.suptitle('Absolute Log Mean and STDs of numeric data\n', fontsize=16)

    ax[0].grid(True)
    ax[1].grid(True)
    real = real.select_dtypes(include='number')
    fake = fake.select_dtypes(include='number')
    real_mean = np.log(np.add(abs(real.mean()).values, 1e-5))
    fake_mean = np.log(np.add(abs(fake.mean()).values, 1e-5))
    min_mean = min(real_mean) - 1
    max_mean = max(real_mean) + 1
    line = np.arange(min_mean, max_mean)
    sns.lineplot(x=line, y=line, ax=ax[0])
    sns.scatterplot(x=real_mean,
                    y=fake_mean,
                    ax=ax[0])
    ax[0].set_title('Means of real and fake data')
    ax[0].set_xlabel('real data mean (log)')
    ax[0].set_ylabel('fake data mean (log)')

    real_std = np.log(np.add(real.std().values, 1e-5))
    fake_std = np.log(np.add(fake.std().values, 1e-5))
    min_std = min(real_std) - 1
    max_std = max(real_std) + 1
    line = np.arange(min_std, max_std)
    sns.lineplot(x=line, y=line, ax=ax[1])
    sns.scatterplot(x=real_std,
                    y=fake_std,
                    ax=ax[1])
    ax[1].set_title('Stds of real and fake data')
    ax[1].set_xlabel('real data std (log)')
    ax[1].set_ylabel('fake data std (log)')

    if fname is not None:
        plt.savefig(fname)

    if ax is None:
        plt.show()
//  [python]
def plot_replication_rate(self, samples=None, num_samples=2,
                              min_score=1, line_kws=None):
        import seaborn as sns

        samples = samples or self.samples
        line_kws = line_kws or dict()

        df = self.replication_rate(samples, num_samples=num_samples,
                                   min_score=min_score)
        df['rank'] = df['score'].rank(ascending=False)
        return sns.pointplot(data=df, x='rank', y='replication', **line_kws)
//  [python]
def plot_replication_rate(self, samples=None, num_samples=2,
                              min_score=1, line_kws=None):
        import seaborn as sns

        samples = samples or self.samples
        line_kws = line_kws or dict()

        df = self.replication_rate(samples, num_samples=num_samples,
                                   min_score=min_score)
        df['rank'] = df['score'].rank(ascending=False)
        return sns.lineplot(data=df, x='rank', y='replication', **line_kws)
//  [python]
def _calculate(self, df: pd.DataFrame, ax: list[plt.Axes]) -> pd.Series:
        df = df.merge(
            cs_fetch(
                path='chain/index/charts?type=/charts/relative-unrealized-prof/',
                data_selector='value1',
                col_name='RUPL',
            ),
            on='Date',
            how='left',
        )
        df['RUPL'] = df['RUPL'].ffill()

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

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

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

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

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

        df['RUPLIndex'] = (df['RUPL'] - df['LowModel']) / (df['HighModel'] - df['LowModel'])

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

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

        return df['RUPLIndex']
//  [python]
def _calculate(self, df: pd.DataFrame, ax: list[plt.Axes]) -> pd.Series:
        df = df.merge(
            cs_fetch(
                path='chain/index/charts?type=/charts/relative-unrealized-prof/',
                data_selector='value1',
                col_name='RUPL',
            ),
            on='Date',
            how='left',
        )
        df['RUPL'] = df['RUPL'].ffill()

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

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

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

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

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

        df['RUPLIndex'] = (df['RUPL'] - df['LowModel']) / (df['HighModel'] - df['LowModel'])

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

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

        return df['RUPLIndex']
//  [python]
def draw(data_path):    # csv中的聊天记录有时间顺序
    df = pd.read_csv(data_path, encoding='utf-8')
    send_df = df[df['isSend']==1]
    receive_df = df[df['isSend']==0]
    send_mean = send_df.groupby('newTime').mean()
    receive_mean = receive_df.groupby('newTime').mean()

    new_df = pd.DataFrame({"月份":list(send_mean.index) + list(receive_mean.index),
                           "情感得分均值":send_mean['sentiment_score'].to_list() + receive_mean['sentiment_score'].to_list(),
                           "is_send":['send']*len(send_mean)+['receive']*len(receive_mean)})
    plt.figure()
    for is_send in new_df['is_send'].unique():
        temp_df = new_df[new_df['is_send']==is_send]
        plt.plot(temp_df['月份'], temp_df['情感得分均值'], label=is_send)
    plt.legend()
    plt.savefig("result/情感得分随时间变化.png")
    plt.show()
//  [python]
def draw(data_path):    # csv中的聊天记录有时间顺序
    df = pd.read_csv(data_path, encoding='utf-8')
    send_df = df[df['isSend']==1]
    receive_df = df[df['isSend']==0]
    send_mean = send_df.groupby('newTime').mean()
    receive_mean = receive_df.groupby('newTime').mean()

    new_df = pd.DataFrame({"月份":list(send_mean.index) + list(receive_mean.index),
                           "情感得分均值":send_mean['sentiment_score'].to_list() + receive_mean['sentiment_score'].to_list(),
                           "is_send":['send']*len(send_mean)+['receive']*len(receive_mean)})
    sns.lineplot(x="月份", y="情感得分均值", hue="is_send",data=new_df)
    plt.savefig("result/情感得分随时间变化.png")
    plt.show()
//  [python]
def plot_expected_vol_qvar(params: Dict[str, LogSvParams],
                           ttm: float = 1.5,
                           is_vol: bool = True,
                           n_terms: int = 4,
                           title: str = 'Expected values',
                           ax:  plt.Subplot = None
                           ) -> None:
    """
    plot expected vol / qvar curves in t
    """
    evs = []
    t = np.linspace(0.0, ttm, 50)
    for key, param in params.items():
        param.assert_vol_moments_stability(n_terms=n_terms)
        if is_vol:
            v_t = vmo.compute_expected_vol_t(params=param, t=t, n_terms=n_terms)
        else:
            v_t = vmo.compute_sqrt_qvar_t(params=param, t=t, n_terms=n_terms)
        evs.append(pd.Series(v_t, index=t, name=key))
    evs = pd.concat(evs, axis=1)

    colors = plot.get_n_sns_colors(n=len(params.keys())//2)
    palette = colors + colors
    for i, col in enumerate(evs.columns):
        ax.plot(evs.index, evs[col], label=col, linestyle='--', color=palette[i])
    yvar_format = '{:.0%}'
    ax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda z, _: yvar_format.format(z)))

    if title is not None:
        ax.set_title(title, fontsize=12, color='darkblue')
    ax.set_xlabel(r"$\tau$", fontsize=12)
    ax.set_xlim((0.0, None))
//  [python]
def plot_expected_vol_qvar(params: Dict[str, LogSvParams],
                           ttm: float = 1.5,
                           is_vol: bool = True,
                           n_terms: int = 4,
                           title: str = 'Expected values',
                           ax:  plt.Subplot = None
                           ) -> None:
    """
    plot expected vol / qvar curves in t
    """
    evs = []
    t = np.linspace(0.0, ttm, 50)
    for key, param in params.items():
        param.assert_vol_moments_stability(n_terms=n_terms)
        if is_vol:
            v_t = vmo.compute_expected_vol_t(params=param, t=t, n_terms=n_terms)
        else:
            v_t = vmo.compute_sqrt_qvar_t(params=param, t=t, n_terms=n_terms)
        evs.append(pd.Series(v_t, index=t, name=key))
    evs = pd.concat(evs, axis=1)

    colors = plot.get_n_sns_colors(n=len(params.keys())//2)
    palette = colors + colors
    sns.lineplot(data=evs, dashes=True, palette=palette, ax=ax)
    yvar_format = '{:.0%}'
    ax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda z, _: yvar_format.format(z)))

    if title is not None:
        ax.set_title(title, fontsize=12, color='darkblue')
    ax.set_xlabel(r"$\tau$", fontsize=12)
    ax.set_xlim((0.0, None))
//  [python]
def roc(
        true: np.ndarray, pred: np.ndarray, max_points: int = 500,
        ax: Optional[ma.Axes] = None, **kwargs
) -> ma.Axes:
    r"""
    Plot an ROC curve

    Parameters
    ----------
    true
        True labels
    pred
        Prediction values
    max_points
        Maximal number of points on the ROC curve, beyond which the points
        are equidistantly subsampled.
    ax
        Existing axes to plot on
    **kwargs
        Additional keyword arguments passed to :func:`seaborn.lineplot`

    Returns
    -------
    ax
        Plot axes
    """
    fpr, tpr, _ = sklearn.metrics.roc_curve(true, pred)
    idx = np.linspace(
        0, fpr.size, min(fpr.size, max_points), endpoint=False
    ).round().astype(int)
    idx[-1] = fpr.size - 1  # Always keep the last point
    data = pd.DataFrame({"FPR": fpr[idx], "TPR": tpr[idx]})
    ax = s.lineplot(x="FPR", y="TPR", data=data, ax=ax, **kwargs)
    return ax
//  [python]
def roc(
        true: np.ndarray, pred: np.ndarray, max_points: int = 500,
        ax: Optional[ma.Axes] = None, **kwargs
) -> ma.Axes:
    r"""
    Plot an ROC curve

    Parameters
    ----------
    true
        True labels
    pred
        Prediction values
    max_points
        Maximal number of points on the ROC curve, beyond which the points
        are equidistantly subsampled.
    ax
        Existing axes to plot on
    **kwargs
        Additional keyword arguments passed to :func:`seaborn.lineplot`

    Returns
    -------
    ax
        Plot axes
    """
    fpr, tpr, _ = sklearn.metrics.roc_curve(true, pred)
    idx = np.linspace(
        0, fpr.size, min(fpr.size, max_points), endpoint=False
    ).round().astype(int)
    idx[-1] = fpr.size - 1  # Always keep the last point
    data = pd.DataFrame({"FPR": fpr[idx], "TPR": tpr[idx]})
    ax = sns.lineplot(x="FPR", y="TPR", data=data, ax=ax, **kwargs)
    return ax
//  [python]
sns.set({'figure.figsize': (8, 4)})
sns.set_style('ticks')

plot_df = (hsize_df
    .sort_values(by=['hsize'])
    .reset_index(drop=True)
)
plot_df.hsize = plot_df.hsize.astype(int)

with sns.plotting_context('notebook', font_scale=1.6):
    g = sns.pointplot(
        data=plot_df,
        x='hsize', y='aupr', hue='data_type',
        hue_order=['train', 'cv', 'test'],
        markers=['o'] * 3, linestyles=['-'] * 3
    )
    g.set(xscale='log', xlim=(min(plot_df.hsize), max(plot_df.hsize)), ylim=(-0.05, 1.05))
    g.set_xlabel(f'Hidden layer size (lower = more regularization)')
    g.set_ylabel('AUPR')
        
    ax = plt.gca()
    legend_handles, _ = ax.get_legend_handles_labels()
    dataset_labels = ['TCGA (train)', 'TCGA (holdout)', 'CCLE'] 
    ax.legend(legend_handles, dataset_labels, title='Dataset')
    sns.move_legend(g, "upper left", bbox_to_anchor=(1.01, 1))
    plt.title(f'Hidden layer size vs. AUPR, all genes', y=1.025)
//  [python]
sns.set({'figure.figsize': (8, 4)})
sns.set_style('ticks')

plot_df = (hsize_df
    .sort_values(by=['hsize'])
    .reset_index(drop=True)
)
plot_df.hsize = plot_df.hsize.astype(int)

with sns.plotting_context('notebook', font_scale=1.6):
    g = sns.lineplot(
        data=plot_df,
        x='hsize', y='aupr', hue='data_type',
        hue_order=['train', 'cv', 'test'],
        marker='o'
    )
    g.set(xscale='log', xlim=(min(plot_df.hsize), max(plot_df.hsize)), ylim=(-0.05, 1.05))
    g.set_xlabel(f'Hidden layer size (lower = more regularization)')
    g.set_ylabel('AUPR')
        
    ax = plt.gca()
    legend_handles, _ = ax.get_legend_handles_labels()
    dataset_labels = ['TCGA (train)', 'TCGA (holdout)', 'CCLE'] 
    ax.legend(legend_handles, dataset_labels, title='Dataset')
    sns.move_legend(g, "upper left", bbox_to_anchor=(1.01, 1))
    plt.title(f'Hidden layer size vs. AUPR, all genes', y=1.025)
//  [python]
def send_pics(update, context, interval):

    try:
        user = update.effective_user
        if user.is_bot:
            return
        username = str(user.username)
        if username not in ALLOWED_USERS:
            return
    except Exception as e:
        print(repr(e))
        return

    df = pd.read_csv(LOG_FILE, header=None, names=[
        'timestamp_string', 'max_val', 'max_support', 'med_val', 'med_support', 'block_number'
    ])
    df['timestamp'] = pd.to_datetime(df['timestamp_string'])

    now = datetime.datetime.now()
    if interval == 'week':
        one_x_ago = now - datetime.timedelta(weeks=1)
    elif interval == 'day':  # day
        one_x_ago = now - datetime.timedelta(days=1)
    else:
        one_x_ago = now - datetime.timedelta(hours=1)

    df = df[df['timestamp'] >= one_x_ago]

    cols_to_show = ['node_lag', 'best_node_lag']
    df['node_lag'] = df['block_number'] - df['med_val']
    df['best_node_lag'] = df['max_val'] - df['med_val']

    plt.figure()
    sns.set(rc={'figure.figsize': (11, 4)})  # set figure size
    for col in cols_to_show:
        plt.plot(df['timestamp'], df[col])
    plt.axhline(y=THRESHOLD, color='black', linestyle='--')
    plt.axhline(y=-THRESHOLD, color='black', linestyle='--')
    plt.legend(cols_to_show)

    # Save the plot as an image file
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)

    # Send the plot as a photo using the Telegram bot API
    context.bot.send_photo(chat_id=user.id, photo=buf)

    # Close the plot to avoid memory leaks
    plt.close()
//  [python]
def send_pics(update, context, interval):

    try:
        user = update.effective_user
        if user.is_bot:
            return
        username = str(user.username)
        if username not in ALLOWED_USERS:
            return
    except Exception as e:
        print(repr(e))
        return

    df = pd.read_csv(LOG_FILE, header=None, names=[
        'timestamp_string', 'max_val', 'max_support', 'med_val', 'med_support', 'block_number'
    ])
    df['timestamp'] = pd.to_datetime(df['timestamp_string'])

    now = datetime.datetime.now()
    if interval == 'week':
        one_x_ago = now - datetime.timedelta(weeks=1)
    elif interval == 'day':  # day
        one_x_ago = now - datetime.timedelta(days=1)
    else:
        one_x_ago = now - datetime.timedelta(hours=1)

    df = df[df['timestamp'] >= one_x_ago]

    cols_to_show = ['node_lag', 'best_node_lag']
    df['node_lag'] = df['block_number'] - df['med_val']
    df['best_node_lag'] = df['max_val'] - df['med_val']

    plt.figure()
    sns.set(rc={'figure.figsize': (11, 4)})  # set figure size
    sns.lineplot(x='timestamp', y='value', hue='variable', data=df[['timestamp']+cols_to_show].melt('timestamp', var_name='variable', value_name='value'))
    plt.axhline(y=THRESHOLD, color='black', linestyle='--')
    plt.axhline(y=-THRESHOLD, color='black', linestyle='--')

    # Save the plot as an image file
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)

    # Send the plot as a photo using the Telegram bot API
    context.bot.send_photo(chat_id=user.id, photo=buf)

    # Close the plot to avoid memory leaks
    plt.close()
//  [python]
def prc(
        true: np.ndarray, pred: np.ndarray, max_points: int = 500,
        ax: Optional[ma.Axes] = None, **kwargs
) -> ma.Axes:
    r"""
    Plot a precision-recall curve

    Parameters
    ----------
    true
        True labels
    pred
        Prediction values
    max_points
        Maximal number of points on the precision-recall curve, beyond which
        the points are equidistantly subsampled.
    ax
        Existing axes to plot on
    **kwargs
        Additional keyword arguments passed to :func:`seaborn.lineplot`

    Returns
    -------
    ax
        Plot axes
    """
    prec, rec, _ = sklearn.metrics.precision_recall_curve(true, pred)
    idx = np.linspace(
        0, prec.size, min(prec.size, max_points), endpoint=False
    ).round().astype(int)
    idx[-1] = prec.size - 1  # Always keep the last point
    data = pd.DataFrame({"Precision": prec[idx], "Recall": rec[idx]})
    ax = s.lineplot(x="Recall", y="Precision", data=data, ax=ax, **kwargs)
    return ax
//  [python]
def prc(
        true: np.ndarray, pred: np.ndarray, max_points: int = 500,
        ax: Optional[ma.Axes] = None, **kwargs
) -> ma.Axes:
    r"""
    Plot a precision-recall curve

    Parameters
    ----------
    true
        True labels
    pred
        Prediction values
    max_points
        Maximal number of points on the precision-recall curve, beyond which
        the points are equidistantly subsampled.
    ax
        Existing axes to plot on
    **kwargs
        Additional keyword arguments passed to :func:`seaborn.lineplot`

    Returns
    -------
    ax
        Plot axes
    """
    prec, rec, _ = sklearn.metrics.precision_recall_curve(true, pred)
    idx = np.linspace(
        0, prec.size, min(prec.size, max_points), endpoint=False
    ).round().astype(int)
    idx[-1] = prec.size - 1  # Always keep the last point
    data = pd.DataFrame({"Precision": prec[idx], "Recall": rec[idx]})
    ax = sns.lineplot(x="Recall", y="Precision", data=data, ax=ax, **kwargs)
    return ax
//  [python]
timeline['Lq']=0
for i in timeline.index:
    if timeline.n[i]>1:
        timeline.Lq[i]= timeline['n'][i]-c


ocupation= pd.Series(name='ocupation',data=[idletime/data.finish_times.max(),
                                            workingtime/data.finish_times.max()],index=['Idle','Ocuppied'])
#plots

plt.figure(figsize=(12,4))
plt.plot(data.index,wait_times,color='black')
//  [python]
timeline['Lq']=0
for i in timeline.index:
    if timeline.n[i]>1:
        timeline.Lq[i]= timeline['n'][i]-c


ocupation= pd.Series(name='ocupation',data=[idletime/data.finish_times.max(),
                                            workingtime/data.finish_times.max()],index=['Idle','Ocuppied'])
#plots

plt.figure(figsize=(12,4))
sns.lineplot(x=data.index,y=wait_times,color='black')
//  [python]
def test_example_plot(tmp_path: Path):
    """Test example plot"""
    fmri = sns.load_dataset("fmri")
    ax1 = pw.Brick(figsize=(3, 2))
    sns.pointplot(
        x="timepoint", y="signal", hue="region", style="event", data=fmri, ax=ax1
    )
    ax1.legend(bbox_to_anchor=(1.05, 1.0), loc="upper left")
    ax1.set_title("ax1")

    titanic = sns.load_dataset("titanic")
    ax2 = pw.Brick(figsize=(1, 2))
    sns.barplot(x="sex", y="survived", hue="class", data=titanic, ax=ax2)
    ax2.move_legend(new_loc="upper left", bbox_to_anchor=(1.05, 1.0))
    ax2.set_title("ax2")

    result_file = tmp_path / "ax12.png"
    ax12 = ax1 | ax2
    ax12.savefig(result_file)
    assert result_file.exists()
//  [python]
def test_example_plot(tmp_path: Path):
    """Test example plot"""
    fmri = sns.load_dataset("fmri")
    ax1 = pw.Brick(figsize=(3, 2))
    sns.lineplot(
        x="timepoint", y="signal", hue="region", style="event", data=fmri, ax=ax1
    )
    ax1.legend(bbox_to_anchor=(1.05, 1.0), loc="upper left")
    ax1.set_title("ax1")

    titanic = sns.load_dataset("titanic")
    ax2 = pw.Brick(figsize=(1, 2))
    sns.barplot(x="sex", y="survived", hue="class", data=titanic, ax=ax2)
    ax2.move_legend(new_loc="upper left", bbox_to_anchor=(1.05, 1.0))
    ax2.set_title("ax2")

    result_file = tmp_path / "ax12.png"
    ax12 = ax1 | ax2
    ax12.savefig(result_file)
    assert result_file.exists()
//  [python]
def plot_std_learning_curves(rewards, success_rates, num_it, no_show=False):
    r, sr = np.asarray(rewards), np.asarray(success_rates)
    df = pd.DataFrame(r).melt()
    sns.pointplot(x="variable", y="value", data=df, label='reward/eps')
    df = pd.DataFrame(sr).melt()
    sns.pointplot(x="variable", y="value", data=df, label='success rate')
    plt.xlabel("Training iterations")
    plt.ylabel("")
    plt.xlim([0, num_it])
    plt.ylim([0, 1])
    plt.legend()
    plt.grid('on')
    if not no_show:
        plt.show()
//  [python]
def plot_std_learning_curves(rewards, success_rates, num_it, no_show=False):
    r, sr = np.asarray(rewards), np.asarray(success_rates)
    df = pd.DataFrame(r).melt()
    sns.lineplot(x="variable", y="value", data=df, label='reward/eps')
    df = pd.DataFrame(sr).melt()
    sns.lineplot(x="variable", y="value", data=df, label='success rate')
    plt.xlabel("Training iterations")
    plt.ylabel("")
    plt.xlim([0, num_it])
    plt.ylim([0, 1])
    plt.legend()
    plt.grid('on')
    if not no_show:
        plt.show()
//  [python]
def plot_metric(dataset, metric, df, output_path):
    """
    Plot the results in the most basic fashion. No complex color markers labels etc.
    """
    models = sorted(df["model"].unique())
    als = sorted(df["AL"].unique())
    x_col = "train total count"
    for model in models:
        for al in als:
            if al == "no_active_learning":
                continue
            model_df_all = df[(df["model"] == model) & ((df["AL"] == al) | (df["AL"] == "no_active_learning"))]
            model_df = model_df_all[[x_col, metric]]
            model_df = model_df.dropna(axis=0)
            model_df = model_df.groupby(x_col, as_index=False).mean()
            x = model_df[x_col]
            y = model_df[metric]
            ax = plt.plot(x, y, label=f'{al}_{model}')
    plt.title(dataset)
    plt.savefig(os.path.join(output_path, f"{dataset}_{metric}"))
    plt.show()
    plt.close()
//  [python]
def plot_metric(dataset, metric, df, output_path):
    """
    Plot the results in the most basic fashion. No complex color markers labels etc.
    """
    models = sorted(df["model"].unique())
    als = sorted(df["AL"].unique())
    x_col = "train total count"
    for model in models:
        for al in als:
            if al == "no_active_learning":
                continue
            model_df_all = df[(df["model"] == model) & ((df["AL"] == al) | (df["AL"] == "no_active_learning"))]
            model_df = model_df_all[[x_col, metric]]
            model_df = model_df.dropna(axis=0)
            model_df = model_df.groupby(x_col, as_index=False).mean()
            x = model_df[x_col]
            y = model_df[metric]
            ax = sns.lineplot(x=x, y=y, label=f'{al}_{model}')
    plt.title(dataset)
    plt.savefig(os.path.join(output_path, f"{dataset}_{metric}"))
    plt.show()
    plt.close()
//  [python]
def create_plot(dir_name, xname, yname, xlabel, ylabel, title, outfile, methods, labels, colors, steps_per_epoch, cutoff=50,
                residual_start_offset=0, log_plot=False, add_to_plot=None, legend_loc="lower right"):
    plt.figure()

    for method, label, color in zip(methods, labels, colors):
        df = load_df(dir_name=dir_name, method=method, xname=xname, yname=yname)
        if df is False:
            print("Warning: skipping {}.".format(method))
            continue
        df = df[df.epoch < cutoff]
        df['simulator_steps'] = df.epoch * steps_per_epoch
        if 'RPL' in label or 'Expert' in label:
            df['simulator_steps'] += residual_start_offset
        plt.plot(df[xname], df[yname], label=label, c=color)

    if log_plot:
        ax = plt.gca()
        ax.set(xscale="log")
        _, xmax = plt.xlim()
        plt.xlim((1., xmax))

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)
    if 'success_rate' in yname:
        plt.ylim((-0.1, 1.1))
        plt.yticks(np.arange(0., 1.1, 0.2))
    plt.legend(loc=legend_loc)
    if not log_plot:
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

    if add_to_plot:
        add_to_plot()

    plt.savefig(outfile)
    print("Wrote out to {}.".format(outfile))
//  [python]
def create_plot(dir_name, xname, yname, xlabel, ylabel, title, outfile, methods, labels, colors, steps_per_epoch, cutoff=50,
                residual_start_offset=0, log_plot=False, add_to_plot=None, legend_loc="lower right"):
    plt.figure()

    for method, label, color in zip(methods, labels, colors):
        df = load_df(dir_name=dir_name, method=method, xname=xname, yname=yname)
        if df is False:
            print("Warning: skipping {}.".format(method))
            continue
        df = df[df.epoch < cutoff]
        df['simulator_steps'] = df.epoch * steps_per_epoch
        if 'RPL' in label or 'Expert' in label:
            df['simulator_steps'] += residual_start_offset
        sns.lineplot(x=xname, y=yname, data=df, label=label, ci='sd', c=color)

    if log_plot:
        ax = plt.gca()
        ax.set(xscale="log")
        _, xmax = plt.xlim()
        plt.xlim((1., xmax))

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)
    if 'success_rate' in yname:
        plt.ylim((-0.1, 1.1))
        plt.yticks(np.arange(0., 1.1, 0.2))
    plt.legend(loc=legend_loc)
    if not log_plot:
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

    if add_to_plot:
        add_to_plot()

    plt.savefig(outfile)
    print("Wrote out to {}.".format(outfile))
//  [python]
def lineplot(x, y, df, palette=None, title=None, hue=None, hue_order=None, \
             err_style='band', markers=True, marker='D', markersize=12, \
             linewidth=1, sort=False, xlim=None, x_major_loc=None, ylim=None, \
             y_major_loc=None, legend=True, figsize=(15,8), fig_name=None, \
             **kwargs):

     sns.set(style="ticks", font_scale=2.0)

     fig = plt.figure(figsize=figsize)
     ax = plt.subplot(111)

     sns.pointplot(x=x, y=y,
                  data=df,
                  palette=palette,
                  hue=hue,
                  hue_order=hue_order,
                  join=True,
                  err_style=err_style, #'band' 'bars'
                  markers=markers,
                  marker=marker,
                  markersize=markersize,
                  linewidth=linewidth,
                  sort=sort,
                  ax=ax,
                  **kwargs
                  )

     if legend: ax.legend(fontsize=15, frameon=False, ncol=1, loc='upper right')
     else: ax.get_legend().remove()

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

     if xlim is not None: ax.set_ylim(xlim)
     if x_major_loc is not None: ax.xaxis.set_major_locator(MultipleLocator(x_major_loc))

     if ylim is not None: ax.set_ylim(ylim)
     if y_major_loc is not None: ax.yaxis.set_major_locator(MultipleLocator(y_major_loc))

     sns.despine(offset=10, trim=True)

     if fig_name is not None: fig.savefig(fname=os.path.join(FIG_DIR, fig_name + FIG_EXT), transparent=True, bbox_inches='tight', dpi=300)

     plt.show()
     plt.close()
//  [python]
def lineplot(x, y, df, palette=None, title=None, hue=None, hue_order=None, \
             err_style='band', markers=True, marker='D', markersize=12, \
             linewidth=1, sort=False, xlim=None, x_major_loc=None, ylim=None, \
             y_major_loc=None, legend=True, figsize=(15,8), fig_name=None, \
             **kwargs):

     sns.set(style="ticks", font_scale=2.0)

     fig = plt.figure(figsize=figsize)
     ax = plt.subplot(111)

     sns.lineplot(x=x, y=y,
                  data=df,
                  palette=palette,
                  hue=hue,
                  hue_order=hue_order,
                  err_style=err_style, #'band' 'bars'
                  markers=markers,
                  marker=marker,
                  markersize=markersize,
                  linewidth=linewidth,
                  sort=sort,
                  ax=ax,
                  **kwargs
                  )

     if legend: ax.legend(fontsize=15, frameon=False, ncol=1, loc='upper right')
     else: ax.get_legend().remove()

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

     if xlim is not None: ax.set_ylim(xlim)
     if x_major_loc is not None: ax.xaxis.set_major_locator(MultipleLocator(x_major_loc))

     if ylim is not None: ax.set_ylim(ylim)
     if y_major_loc is not None: ax.yaxis.set_major_locator(MultipleLocator(y_major_loc))

     sns.despine(offset=10, trim=True)

     if fig_name is not None: fig.savefig(fname=os.path.join(FIG_DIR, fig_name + FIG_EXT), transparent=True, bbox_inches='tight', dpi=300)

     plt.show()
     plt.close()
//  [python]
def plot_results(data_dir, plot_dir=PLOT_DIR, test_id=""):
    data_dir = Path(f"{data_dir}")
    conf_name = "test_config"
    config = parse_config(data_dir, conf_name)
    modes = config["modes"]
    epochs = config["epochs"]
    teacher_name = config["teacher_name"] + "_teacher"
    student_name = config["student_name"]
    dfs = {}
    for mode in modes:
        mode = mode.lower()
        mode_path = data_dir.joinpath(mode)
        csv_path = mode_path.joinpath(f"{student_name}_train.csv")
        try:
            dfs[mode] = read_csv(csv_path)
        except FileNotFoundError:
            print(f"Results for {mode} not found, ignoring...")
    teacher_path = data_dir.joinpath(f"{teacher_name}_val.csv")
    dfs["teacher"] = read_csv(teacher_path)
    df = pd.concat(dfs.values(), axis=1, keys=dfs.keys())
    print(df.max().sort_values(ascending=True))
    df = compute_rolling_df_mean(df, 10)
    if (len(modes) + 1) > len(DASH_STYLES):
        print("Too many lines to plot!")
        return

    sns.tsplot(data=df, palette="tab10",
                 condition="event", unit="time",err_style="band")
    plot_dir = Path(plot_dir).joinpath(test_id)
    util.check_dir(plot_dir)
    plt_name = f"{epochs}_epochs_{teacher_name}_to_{student_name}"
    plt_name = Path(plot_dir).joinpath(plt_name)
    plt.savefig(f"{plt_name}.pdf", bbox_inches='tight', pad_inches=0.05)
    plt.savefig(f"{plt_name}.png", bbox_inches='tight', pad_inches=0.05)
    plt.gcf().clear()
//  [python]
def plot_results(data_dir, plot_dir=PLOT_DIR, test_id=""):
    data_dir = Path(f"{data_dir}")
    conf_name = "test_config"
    config = parse_config(data_dir, conf_name)
    modes = config["modes"]
    epochs = config["epochs"]
    teacher_name = config["teacher_name"] + "_teacher"
    student_name = config["student_name"]
    dfs = {}
    for mode in modes:
        mode = mode.lower()
        mode_path = data_dir.joinpath(mode)
        csv_path = mode_path.joinpath(f"{student_name}_train.csv")
        try:
            dfs[mode] = read_csv(csv_path)
        except FileNotFoundError:
            print(f"Results for {mode} not found, ignoring...")
    teacher_path = data_dir.joinpath(f"{teacher_name}_val.csv")
    dfs["teacher"] = read_csv(teacher_path)
    df = pd.concat(dfs.values(), axis=1, keys=dfs.keys())
    print(df.max().sort_values(ascending=True))
    df = compute_rolling_df_mean(df, 10)
    if (len(modes) + 1) > len(DASH_STYLES):
        print("Too many lines to plot!")
        return

    sns.lineplot(data=df, palette="tab10",
                 style="event", dashes=DASH_STYLES)
    plot_dir = Path(plot_dir).joinpath(test_id)
    util.check_dir(plot_dir)
    plt_name = f"{epochs}_epochs_{teacher_name}_to_{student_name}"
    plt_name = Path(plot_dir).joinpath(plt_name)
    plt.savefig(f"{plt_name}.pdf", bbox_inches='tight', pad_inches=0.05)
    plt.savefig(f"{plt_name}.png", bbox_inches='tight', pad_inches=0.05)
    plt.gcf().clear()
//  [python]
def plot_data(data, xaxis="Epoch", value="AverageEpRet", condition="Condition1", smooth=1, **kwargs):
	if smooth > 1:
		"""
		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:
			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)

	# Default
	sns.set(style="white", font_scale=1.5)
	ax = sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci="sd", **kwargs)
	# ax = sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci="sd", **kwargs)
	
	ax.set_xlabel("Steps")
	"""
	If you upgrade to any version of Seaborn greater than 0.8.1, switch from 
	tsplot to lineplot replacing L34 with:

		sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci="sd", **kwargs)

	Changes the colorscheme and the default legend style, though.
	"""
	plt.legend(loc="best").set_draggable(True)
	plt.tick_params(direction="out", length=4)
	"""
	For the version of the legend used in the Spinning Up benchmarking page, 
	swap L38 with:

	plt.legend(loc="upper center", ncol=6, handlelength=1,
			   mode="expand", borderaxespad=0., prop={"size": 13})
	"""

	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)
//  [python]
def plot_data(data, xaxis="Epoch", value="AverageEpRet", condition="Condition1", smooth=1, **kwargs):
	if smooth > 1:
		"""
		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:
			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)

	# Default
	sns.set(style="white", font_scale=1.5)
	# ax = sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci="sd", **kwargs)
	ax = sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci="sd", **kwargs)
	
	ax.set_xlabel("Steps")
	"""
	If you upgrade to any version of Seaborn greater than 0.8.1, switch from 
	tsplot to lineplot replacing L34 with:

		sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci="sd", **kwargs)

	Changes the colorscheme and the default legend style, though.
	"""
	plt.legend(loc="best").set_draggable(True)
	plt.tick_params(direction="out", length=4)
	"""
	For the version of the legend used in the Spinning Up benchmarking page, 
	swap L38 with:

	plt.legend(loc="upper center", ncol=6, handlelength=1,
			   mode="expand", borderaxespad=0., prop={"size": 13})
	"""

	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)
//  [python]
def plot_pareto_frontiers(df, x_axis, y_axis, max_x, colors):
    df = df[df['frontier']].copy()
    dfs = []
    for rep in df.representation.unique():
        df_temp = df[df.representation == rep].copy()
        df_temp = get_pareto_frontiers(df_temp, x_axis, y_axis, rep, max_x)
        dfs += [df_temp]

    df = pd.concat(dfs)
    df.sort_values(y_axis, ascending=True, inplace=True)
    df.sort_values(x_axis, ascending=True, inplace=True)
    df.sort_values('Representation', ascending=True, inplace=True)

    df.reset_index(inplace=True)
    for rep, data in df.groupby('Representation'):
        plt.plot(data[x_axis], data[y_axis], label=rep, color=colors[rep])
    plt.legend()
//  [python]
def plot_pareto_frontiers(df, x_axis, y_axis, max_x, colors):
    df = df[df['frontier']].copy()
    dfs = []
    for rep in df.representation.unique():
        df_temp = df[df.representation == rep].copy()
        df_temp = get_pareto_frontiers(df_temp, x_axis, y_axis, rep, max_x)
        dfs += [df_temp]

    df = pd.concat(dfs)
    df.sort_values(y_axis, ascending=True, inplace=True)
    df.sort_values(x_axis, ascending=True, inplace=True)
    df.sort_values('Representation', ascending=True, inplace=True)

    df.reset_index(inplace=True)
    sns.lineplot(x=x_axis, y=y_axis, hue='Representation',
        data=df, legend=False, palette=colors)
//  [python]
def plot_mixture(probs, x, elbo, kl, evidence):

    plt.plot(x, probs[:, 0])
    plt.plot(x, probs[:, 1])
    plt.legend(['True Posterior', 'Surrogate Posterior'])
    plt.title('${} = {} + {}$'.format(elbo, kl, evidence))
    plt.show()
//  [python]
def plot_mixture(probs, x, elbo, kl, evidence):

    sns.lineplot(x=x, y=probs[:, 0])
    sns.lineplot(x=x, y=probs[:, 1])
    plt.legend(['True Posterior', 'Surrogate Posterior'])
    plt.title('${} = {} + {}$'.format(elbo, kl, evidence))
    plt.show()
//  [python]
sns.distplot(decoys['score'], label = 'decoys', bins=20, norm_hist=False)
plt.legend()


# Time versus smiles length 
plt.figure()
lens = np.array([len(s) for s in df['can']])
sns.regplot(x=lens, y=df['time'])
//  [python]
sns.distplot(decoys['score'], label = 'decoys', bins=20, norm_hist=False)
plt.legend()


# Time versus smiles length 
plt.figure()
lens = np.array([len(s) for s in df['can']])
sns.lineplot(x=lens, y=df['time'])
//  [python]
def evaluate_CAG(
    G,
    target_node: str,
    intervened_node: str,
    input = None,
    start_year=2012,
    start_month=None,
    end_year=2017,
    end_month=None,
    dampen=False,
):
    if input is not None:
        with open(input,"rb") as f:
            G = pickle.load(f)

    G.parameterize(year = start_year,month = start_month)
    G.get_timeseries_values_for_indicators()

    if start_month is None:
        start_month = 1
    if end_month is None:
        end_month = 1

    n_timesteps = calculate_timestep(start_year,start_month,end_year,end_month)

    true_vals_df = get_true_values(G,target_node,n_timesteps,start_year,start_month)

    true_vals = true_vals_df.values

    deltas = estimate_deltas(G,intervened_node,n_timesteps,start_year,start_month)

    preds_df = get_predictions(G, target_node, intervened_node, deltas, n_timesteps, dampen=False)

    preds_df = preds_df.set_index(true_vals_df.index)

    preds = preds_df.values

    sq_error = (preds-true_vals)**2

    mean_sq_error = np.mean(sq_error)

    compare_df = pd.concat([true_vals_df,preds_df],axis=1,join_axes=[true_vals_df.index])

    sns.set(rc={'figure.figsize':(15,8)},style='whitegrid')
    ax = sns.tsplot(data=compare_df)
    ax.set_xticklabels(compare_df.index,rotation=45,ha='right',fontsize=8)
//  [python]
def evaluate_CAG(
    G,
    target_node: str,
    intervened_node: str,
    input = None,
    start_year=2012,
    start_month=None,
    end_year=2017,
    end_month=None,
    dampen=False,
):
    if input is not None:
        with open(input,"rb") as f:
            G = pickle.load(f)

    G.parameterize(year = start_year,month = start_month)
    G.get_timeseries_values_for_indicators()

    if start_month is None:
        start_month = 1
    if end_month is None:
        end_month = 1

    n_timesteps = calculate_timestep(start_year,start_month,end_year,end_month)

    true_vals_df = get_true_values(G,target_node,n_timesteps,start_year,start_month)

    true_vals = true_vals_df.values

    deltas = estimate_deltas(G,intervened_node,n_timesteps,start_year,start_month)

    preds_df = get_predictions(G, target_node, intervened_node, deltas, n_timesteps, dampen=False)

    preds_df = preds_df.set_index(true_vals_df.index)

    preds = preds_df.values

    sq_error = (preds-true_vals)**2

    mean_sq_error = np.mean(sq_error)

    compare_df = pd.concat([true_vals_df,preds_df],axis=1,join_axes=[true_vals_df.index])

    sns.set(rc={'figure.figsize':(15,8)},style='whitegrid')
    ax = sns.lineplot(data=compare_df)
    ax.set_xticklabels(compare_df.index,rotation=45,ha='right',fontsize=8)
//  [python]
def hyperparameter_gauge(self, fig, gridspec):
    """Hyperparameter gauge, currently showing the learning rate over time.

    This instrument visualizes the hyperparameters values over the course of the
    training. Currently, it shows the learning rate, the most likely parameter to
    be adapted during training. The current learning rate is additionally shown
    in the figure's legend.

    **Preview**

    .. image:: ../../_static/instrument_previews/Hyperparameters.png
        :alt: Preview Hyperparameter Gauge

    **Requires**

    This instrument requires the learning rate data passed via the
    :func:`cockpit.Cockpit.log()` method.

    Args:
        self (CockpitPlotter): The cockpit plotter requesting this instrument.
        fig (matplotlib.figure.Figure): Figure of the Cockpit.
        gridspec (matplotlib.gridspec.GridSpec): GridSpec where the instrument should be
            placed
    """
    # Plot Trace vs iteration
    title = "Hyperparameters"

    # Check if the required data is available, else skip this instrument
    requires = ["iteration", "learning_rate"]
    plot_possible = check_data(self.tracking_data, requires)
    if not plot_possible:
        if self.debug:
            warnings.warn(
                "Couldn't get the required data for the " + title + " instrument",
                stacklevel=1,
            )
        return

    ax = fig.add_subplot(gridspec)

    clean_learning_rate = self.tracking_data[["iteration", "learning_rate"]].dropna()

    # Plot Settings
    plot_args = {
        "x": "iteration",
        "y": "learning_rate",
        "data": clean_learning_rate,
    }
    ylabel = plot_args["y"].replace("_", " ").title()
    sns.lineplot(
        **plot_args, ax=ax, label=ylabel, linewidth=2, color=self.secondary_color
    )

    _beautify_plot(
        ax=ax,
        xlabel=plot_args["x"],
        ylabel=ylabel,
        x_scale="symlog" if self.show_log_iter else "linear",
        title=title,
        xlim="tight",
        fontweight="bold",
        facecolor=self.bg_color_instruments2,
    )

    ax.legend()
    _add_last_value_to_legend(ax)