jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def figure_basis_functions(targets):
    q = 12
    theta = 1.0

    thetas = np.linspace(0, theta, 1000)
    data = np.zeros((q, len(thetas)))

    for i, thetap in enumerate(thetas):
        data[:, i] = delay_readout(q, thetap, theta)

    cmap = sns.cubehelix_palette(len(data), light=0.7, reverse=True)

    with sns.axes_style('ticks'):
        with sns.plotting_context('paper', font_scale=2.8):
            pylab.figure(figsize=(18, 5))
            for i in range(len(data)):
                pylab.plot(thetas / theta, data[i], c=cmap[i],
                           lw=3, alpha=1.0, zorder=i)

            pylab.xlabel(r"$\theta' \times \theta^{-1}$ [s / s]", labelpad=20)
            pylab.ylabel(r"$w_{q - 1 - i}$")
            lc = LineCollection(len(cmap) * [[(0, 0)]], lw=10,
                                colors=cmap)
            pylab.legend([lc], [r"$i = 0 \ldots q - 1$"], handlelength=2,
                         handler_map={type(lc): HandlerDashedLines()},
                         bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0.)

            sns.despine(offset=15)

            savefig(targets[0])
//  [python]
def figure_basis_functions(targets):
    q = 12
    theta = 1.0

    thetas = np.linspace(0, theta, 1000)
    data = np.zeros((q, len(thetas)))

    for i, thetap in enumerate(thetas):
        data[:, i] = delay_readout(q, thetap, theta)

    cmap = sns.cubehelix_palette(len(data), light=0.7, reverse=True)

    with sns.axes_style('ticks'):
        with sns.plotting_context('paper', font_scale=2.8):
            pylab.figure(figsize=(18, 5))
            for i in range(len(data)):
                pylab.plot(thetas / theta, data[i], c=cmap[i],
                           lw=3, alpha=1.0, zorder=i)

            pylab.xlabel(r"$\theta' \times \theta^{-1}$ [s / s]", labelpad=20)
            pylab.ylabel(r"$w_{q - 1 - i}$")
            lc = LineCollection(len(cmap) * [[(0, 0)]], lw=10,
                                colors=cmap)
            pylab.legend([lc], [r"$i = 0 \ldots q - 1$"], handlelength=2,
                         handler_map={type(lc): HandlerDashedLines()},
                         bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0.)

            sns.utils.despine(offset=15)

            savefig(targets[0])
//  [python]
def plot_expression_vs_inconsistent_splicing(self, bins=None):

        expression_vs_inconsistent = self.expression_vs_inconsistent_splicing(
            bins=bins)

        fig, axes = plt.subplots(nrows=2, figsize=(6, 6))

        # Plot the percent inconsistent
        ax = axes[0]
        for phenotype in self.phenotype_order:
            s = expression_vs_inconsistent[(phenotype, 'percent')]
            color = self.phenotype_to_color[phenotype]
            ax.plot(s, 'o-', color=color)
        ax.set_xlabel('Expression threshold')
        ax.set_ylabel('Percent events inconsistent with pooled')
        ymin, ymax = ax.get_ylim()
        ax.set_ylim(0, ymax)

        # Plot number of events at each cutoff
        ax = axes[1]
        for phenotype in self.phenotype_order:
            s = expression_vs_inconsistent[(phenotype, 'n_events')]
            color = self.phenotype_to_color[phenotype]
            ax.plot(s, 'o-', color=color)
        ax.set_xlabel('Expression threshold')
        ax.set_ylabel('Number of events')
        ymin, ymax = ax.get_ylim()
        ax.set_ylim(0, ymax)
        ax.legend()

        sns.despine()
//  [python]
def plot_expression_vs_inconsistent_splicing(self, bins=None):

        expression_vs_inconsistent = self.expression_vs_inconsistent_splicing(
            bins=bins)

        fig, axes = plt.subplots(nrows=2, figsize=(6, 6))

        # Plot the percent inconsistent
        ax = axes[0]
        for phenotype in self.phenotype_order:
            s = expression_vs_inconsistent[(phenotype, 'percent')]
            color = self.phenotype_to_color[phenotype]
            ax.plot(s, 'o-', color=color)
        ax.set_xlabel('Expression threshold')
        ax.set_ylabel('Percent events inconsistent with pooled')
        ymin, ymax = ax.get_ylim()
        ax.set_ylim(0, ymax)

        # Plot number of events at each cutoff
        ax = axes[1]
        for phenotype in self.phenotype_order:
            s = expression_vs_inconsistent[(phenotype, 'n_events')]
            color = self.phenotype_to_color[phenotype]
            ax.plot(s, 'o-', color=color)
        ax.set_xlabel('Expression threshold')
        ax.set_ylabel('Number of events')
        ymin, ymax = ax.get_ylim()
        ax.set_ylim(0, ymax)
        ax.legend()

        sns.utils.despine()
//  [python]
def plot_roc(fprs, tprs, out_dir):
    plt.figure(figsize=(4,4))

    for fi in range(len(fprs)):
        plt.plot(fprs[fi], tprs[fi], alpha=0.25)

    ax = plt.gca()
    ax.set_xlabel('False positive rate')
    ax.set_ylabel('True positive rate')

    sns.despine()
    plt.tight_layout()

    plt.savefig('%s/roc.pdf' % out_dir)
    plt.close()
//  [python]
def plot_roc(fprs, tprs, out_dir):
    plt.figure(figsize=(4,4))

    for fi in range(len(fprs)):
        plt.plot(fprs[fi], tprs[fi], alpha=0.25)

    ax = plt.gca()
    ax.set_xlabel('False positive rate')
    ax.set_ylabel('True positive rate')

    sns.utils.despine()
    plt.tight_layout()

    plt.savefig('%s/roc.pdf' % out_dir)
    plt.close()
//  [python]
def close_ticks(ax):
    ax.tick_params(bottom=False, top=False, left=False, right=False,
                   labelbottom=False, labeltop=False,
                   labelleft=False, labelright=False,
                   )
    sns.despine(ax=ax, left=True, bottom=True)
//  [python]
def close_ticks(ax):
    ax.tick_params(bottom=False, top=False, left=False, right=False,
                   labelbottom=False, labeltop=False,
                   labelleft=False, labelright=False,
                   )
    sns.utils.despine(ax=ax, left=True, bottom=True)
//  [python]
def plot(self):

        fig, ax = plt.subplots(len(self.q1), len(self.q2), sharex=True,
                               figsize=(len(self.q1) * 5 + 2,
                                        len(self.q2) * 3 + 2))

        j_support = np.arange(self.j1, self.j2+1)

        slope_param = {
            'c': 'black',
            'linestyle': '--',
            'linewidth': 1.25
        }

        plot_param = {
            'linewidth': 2.5
        }

        for ind_q1, q1 in enumerate(self.q1):
            for ind_q2, q2 in enumerate(self.q2):

                ax[ind_q1, ind_q2].plot(self.j, self.logvalues[ind_q1, ind_q2],
                                        **plot_param)
                ax[ind_q1, ind_q2].plot(j_support,
                                        (j_support * self.zeta[ind_q1, ind_q2])
                                        + self.intercept[ind_q1, ind_q2],
                                        **slope_param,
                                        label=rf'$\zeta({q1}, {q2}): '
                                        f'{self.zeta[ind_q1, ind_q2]:.2f}$')
                ax[ind_q1, ind_q2].legend()

                ax[ind_q1, ind_q2].set_ylabel(rf'$S_{{{q1}, {q2}}}(j)$',
                                              size='large')
                ax[ind_q1, ind_q2].set_title(f'{q1=}, {q2=}', size='large')
                ax[-1, ind_q2].set_xlabel('j', size='large')

        sns.despine()

        return fig
//  [python]
def plot(self):

        fig, ax = plt.subplots(len(self.q1), len(self.q2), sharex=True,
                               figsize=(len(self.q1) * 5 + 2,
                                        len(self.q2) * 3 + 2))

        j_support = np.arange(self.j1, self.j2+1)

        slope_param = {
            'c': 'black',
            'linestyle': '--',
            'linewidth': 1.25
        }

        plot_param = {
            'linewidth': 2.5
        }

        for ind_q1, q1 in enumerate(self.q1):
            for ind_q2, q2 in enumerate(self.q2):

                ax[ind_q1, ind_q2].plot(self.j, self.logvalues[ind_q1, ind_q2],
                                        **plot_param)
                ax[ind_q1, ind_q2].plot(j_support,
                                        (j_support * self.zeta[ind_q1, ind_q2])
                                        + self.intercept[ind_q1, ind_q2],
                                        **slope_param,
                                        label=rf'$\zeta({q1}, {q2}): '
                                        f'{self.zeta[ind_q1, ind_q2]:.2f}$')
                ax[ind_q1, ind_q2].legend()

                ax[ind_q1, ind_q2].set_ylabel(rf'$S_{{{q1}, {q2}}}(j)$',
                                              size='large')
                ax[ind_q1, ind_q2].set_title(f'{q1=}, {q2=}', size='large')
                ax[-1, ind_q2].set_xlabel('j', size='large')

        sns.utils.despine()

        return fig
//  [python]
def plot_histogram(
    data: pd.DataFrame,
    figsize: tuple = (10, 7),
    output_dir: Path = None,
    **kwargs,
):
    """
    It plots, in the same figure, the histograms of all the columns in the
    given dataframe. The function is mainly used to plot the distribution
    of correlation coefficients (columns) across gene pairs (rows). It sets
    some visual parameters to general the final figures.

    Args:
        data: a dataframe with gene pairs in rows and coefficient values
        in columns.
        figsize: figure's size.
        output_dir: if not None, the figure will be saved in this directory.
          The file name is "dist-histograms.svg"
        **kwargs: other parameter passed to seaborn.histplot.

    Returns:
        The figure and axis objects.
    """
    fig, ax = plt.subplots(figsize=figsize)

    ax = sns.histplot(
        data=data,
        stat="density",
        bins=100,
        common_bins=True,
        common_norm=False,
        kde=True,
        ax=ax,
        **kwargs,
    )
    sns.despine(ax=ax)

    ax.set_xticks(np.linspace(0, 1, 10 + 1))

    if output_dir is not None:
        plt.savefig(
            output_dir / "dist-histograms.svg",
            bbox_inches="tight",
            facecolor="white",
        )

    return fig, ax
//  [python]
def plot_histogram(
    data: pd.DataFrame,
    figsize: tuple = (10, 7),
    output_dir: Path = None,
    **kwargs,
):
    """
    It plots, in the same figure, the histograms of all the columns in the
    given dataframe. The function is mainly used to plot the distribution
    of correlation coefficients (columns) across gene pairs (rows). It sets
    some visual parameters to general the final figures.

    Args:
        data: a dataframe with gene pairs in rows and coefficient values
        in columns.
        figsize: figure's size.
        output_dir: if not None, the figure will be saved in this directory.
          The file name is "dist-histograms.svg"
        **kwargs: other parameter passed to seaborn.histplot.

    Returns:
        The figure and axis objects.
    """
    fig, ax = plt.subplots(figsize=figsize)

    ax = sns.histplot(
        data=data,
        stat="density",
        bins=100,
        common_bins=True,
        common_norm=False,
        kde=True,
        ax=ax,
        **kwargs,
    )
    sns.utils.despine(ax=ax)

    ax.set_xticks(np.linspace(0, 1, 10 + 1))

    if output_dir is not None:
        plt.savefig(
            output_dir / "dist-histograms.svg",
            bbox_inches="tight",
            facecolor="white",
        )

    return fig, ax
//  [python]
def plot_inner_product_as_box(self, ax=None, vm=1, vmin=None, vmax=None, args={}):

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

    if vmin is None:
        vmin = -vm
    if vmax is None:
        vmax = vm

    sns.boxplot(data=self.inner_product_df, x="pseudotime_id", y="score", color="white", ax=ax)
    ax.set_xlabel("Digitized_pseudotime")
    ax.set_ylabel("inner product score")
    ax.axhline(0, color="gray")
    ax.set_ylim([vmin*1.1, vmax*1.1])
    ax.tick_params(
                labelleft=False)
    sns.despine()
//  [python]
def plot_inner_product_as_box(self, ax=None, vm=1, vmin=None, vmax=None, args={}):

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

    if vmin is None:
        vmin = -vm
    if vmax is None:
        vmax = vm

    sns.boxplot(data=self.inner_product_df, x="pseudotime_id", y="score", color="white", ax=ax)
    ax.set_xlabel("Digitized_pseudotime")
    ax.set_ylabel("inner product score")
    ax.axhline(0, color="gray")
    ax.set_ylim([vmin*1.1, vmax*1.1])
    ax.tick_params(
                labelleft=False)
    sns.utils.despine()
//  [python]
def plot_cumulative_histogram(
    data: pd.DataFrame,
    gene_pairs_percent: float = None,
    figsize: tuple = (10, 7),
    output_dir: Path = None,
):
    """
    Very similar to plot_histogram, but this plots the cummulative histogram
    instead.

    Args:
        data: same as in plot_histogram.
        figsize: same as in plot_histogram
        output_dir: same as in plot_histogram. The file name is
          "dist-cum_histograms.svg"

    Returns:
        The figure and axis objects.
    """
    fig, ax = plt.subplots(figsize=figsize)

    ax = sns.histplot(
        data=data,
        element="step",
        fill=False,
        stat="percent",
        common_norm=False,
        cumulative=True,
        legend=False,
        ax=ax,
    )
    sns.despine(ax=ax)

    ax.set_xticks(np.linspace(0, 1, 10 + 1))
    ax.set_yticks(np.linspace(0, 100, 10 + 1))

    ax.set_ylabel("Percent of gene pairs")

    if gene_pairs_percent is not None:
        coef_at_percent = data.quantile(gene_pairs_percent)

        # show values so it is saved in the notebook
        display(coef_at_percent.sort_values())

        x_lim = ax.get_xlim()
        hline_x_max = coef_at_percent.max()

        ax.hlines(
            y=gene_pairs_percent * 100,
            xmin=x_lim[0],
            xmax=hline_x_max,
            color="gray",
            linestyle="dotted",
        )

        for method_name in coef_at_percent.index:
            ax.vlines(
                x=coef_at_percent[method_name],
                ymin=0,
                ymax=gene_pairs_percent * 100,
                color="gray",
                linestyle="dotted",
            )

        ax.set_xlim(x_lim)

    if output_dir is not None:
        plt.savefig(
            output_dir / "dist-cum_histograms.svg",
            bbox_inches="tight",
            facecolor="white",
        )

    return fig, ax
//  [python]
def plot_cumulative_histogram(
    data: pd.DataFrame,
    gene_pairs_percent: float = None,
    figsize: tuple = (10, 7),
    output_dir: Path = None,
):
    """
    Very similar to plot_histogram, but this plots the cummulative histogram
    instead.

    Args:
        data: same as in plot_histogram.
        figsize: same as in plot_histogram
        output_dir: same as in plot_histogram. The file name is
          "dist-cum_histograms.svg"

    Returns:
        The figure and axis objects.
    """
    fig, ax = plt.subplots(figsize=figsize)

    ax = sns.histplot(
        data=data,
        element="step",
        fill=False,
        stat="percent",
        common_norm=False,
        cumulative=True,
        legend=False,
        ax=ax,
    )
    sns.utils.despine(ax=ax)

    ax.set_xticks(np.linspace(0, 1, 10 + 1))
    ax.set_yticks(np.linspace(0, 100, 10 + 1))

    ax.set_ylabel("Percent of gene pairs")

    if gene_pairs_percent is not None:
        coef_at_percent = data.quantile(gene_pairs_percent)

        # show values so it is saved in the notebook
        display(coef_at_percent.sort_values())

        x_lim = ax.get_xlim()
        hline_x_max = coef_at_percent.max()

        ax.hlines(
            y=gene_pairs_percent * 100,
            xmin=x_lim[0],
            xmax=hline_x_max,
            color="gray",
            linestyle="dotted",
        )

        for method_name in coef_at_percent.index:
            ax.vlines(
                x=coef_at_percent[method_name],
                ymin=0,
                ymax=gene_pairs_percent * 100,
                color="gray",
                linestyle="dotted",
            )

        ax.set_xlim(x_lim)

    if output_dir is not None:
        plt.savefig(
            output_dir / "dist-cum_histograms.svg",
            bbox_inches="tight",
            facecolor="white",
        )

    return fig, ax
//  [python]
def show_validation_results(predictions, show_plots=True, print_error=True):

    print('\n\nRESULTS')

    if print_error:
        mae = predictions['abs_error'].mean()
        print('\nMean Absolute Error: ' + str(round(float(mae), 2)) + ' knots')
        rmse = predictions['abs_error_squared'].mean() ** 0.5
        print('Root Mean Square Error: ' + str(round(float(rmse), 2)) + ' knots')

    if show_plots:
        # List of categories in order of ascending strength
        categories = ['T. Depression', 'T. Storm', 'Category 1', 'Category 2', 'Category 3', 'Category 4', 'Category 5']

        # Show bar graph of median absolute error for each category
        plt.figure(figsize=(10, 5), dpi=300)
        sns.barplot(
            x='category',
            y='abs_error',
            data=predictions,
            estimator=np.median,
            order=categories)
        sns.despine()
        plt.xlabel("Hurricane Strength")
        plt.ylabel("Absolute Error")
        plt.title("Median Absolute Error in Neural Network's Predictions By Category")
        plt.savefig('median_abs_error_by_category.png')
        print('Graph of median absolute error by category saved as median_abs_error_by_category.png')
        plt.clf()

        # Show density plot of error for each category
        for category in categories:
            num_samples_tested = len(predictions.loc[predictions.category == category]['abs_error'])
            sns.distplot(
                predictions.loc[predictions.category == category]['abs_error'],
                label=category + ' (' + str(num_samples_tested) + ' samples tested)',
                hist=False,
                kde_kws={"shade": True})
            sns.despine()
        plt.xlabel("Absolute Error")
        plt.title("Distribution of Absolute Error By Category")
        plt.legend()
        plt.xlim(0, None)
        plt.ylim(0, None)
        plt.savefig('error_dist_by_category.png')
        print('Graph of error distribution by category saved as error_dist_by_category.png')
//  [python]
def show_validation_results(predictions, show_plots=True, print_error=True):

    print('\n\nRESULTS')

    if print_error:
        mae = predictions['abs_error'].mean()
        print('\nMean Absolute Error: ' + str(round(float(mae), 2)) + ' knots')
        rmse = predictions['abs_error_squared'].mean() ** 0.5
        print('Root Mean Square Error: ' + str(round(float(rmse), 2)) + ' knots')

    if show_plots:
        # List of categories in order of ascending strength
        categories = ['T. Depression', 'T. Storm', 'Category 1', 'Category 2', 'Category 3', 'Category 4', 'Category 5']

        # Show bar graph of median absolute error for each category
        plt.figure(figsize=(10, 5), dpi=300)
        sns.barplot(
            x='category',
            y='abs_error',
            data=predictions,
            estimator=np.median,
            order=categories)
        sns.utils.despine()
        plt.xlabel("Hurricane Strength")
        plt.ylabel("Absolute Error")
        plt.title("Median Absolute Error in Neural Network's Predictions By Category")
        plt.savefig('median_abs_error_by_category.png')
        print('Graph of median absolute error by category saved as median_abs_error_by_category.png')
        plt.clf()

        # Show density plot of error for each category
        for category in categories:
            num_samples_tested = len(predictions.loc[predictions.category == category]['abs_error'])
            sns.distplot(
                predictions.loc[predictions.category == category]['abs_error'],
                label=category + ' (' + str(num_samples_tested) + ' samples tested)',
                hist=False,
                kde_kws={"shade": True})
            sns.utils.despine()
        plt.xlabel("Absolute Error")
        plt.title("Distribution of Absolute Error By Category")
        plt.legend()
        plt.xlim(0, None)
        plt.ylim(0, None)
        plt.savefig('error_dist_by_category.png')
        print('Graph of error distribution by category saved as error_dist_by_category.png')
//  [python]
def plot_inner_product_on_pseudotime(self, ax=None, vm=1, s=CONFIG["s_grid"], vmin=None, vmax=None, cmap=None, args={}):

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

    if vmin is None:
        vmin = -vm
    if vmax is None:
        vmax = vm
    if cmap is None:
        cmap = CONFIG["cmap_ps"]

    try:
        norm = colors.TwoSlopeNorm(vmin=vmin, vcenter=0, vmax=vmax)
    except:
        norm = colors.DivergingNorm(vmin=vmin, vcenter=0, vmax=vmax)

    pcm = ax.scatter(self.pseudotime_on_grid[~self.mass_filter_simulation],
                     self.inner_product[~self.mass_filter_simulation],
                     c=self.inner_product[~self.mass_filter_simulation],
                     cmap=cmap,
                     norm=norm,#vmin=vmin, vmax=vmax,
                     s=s, **args)

    ax.set_ylim([vmin*1.1, vmax*1.1])
    ax.axhline(0, color="lightgray")
    pp = plt.colorbar(pcm, ax=ax, orientation="vertical")
    sns.despine()
    ax.set_xlabel("pseudotime")
    ax.set_ylabel("inner product score")
//  [python]
def plot_inner_product_on_pseudotime(self, ax=None, vm=1, s=CONFIG["s_grid"], vmin=None, vmax=None, cmap=None, args={}):

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

    if vmin is None:
        vmin = -vm
    if vmax is None:
        vmax = vm
    if cmap is None:
        cmap = CONFIG["cmap_ps"]

    try:
        norm = colors.TwoSlopeNorm(vmin=vmin, vcenter=0, vmax=vmax)
    except:
        norm = colors.DivergingNorm(vmin=vmin, vcenter=0, vmax=vmax)

    pcm = ax.scatter(self.pseudotime_on_grid[~self.mass_filter_simulation],
                     self.inner_product[~self.mass_filter_simulation],
                     c=self.inner_product[~self.mass_filter_simulation],
                     cmap=cmap,
                     norm=norm,#vmin=vmin, vmax=vmax,
                     s=s, **args)

    ax.set_ylim([vmin*1.1, vmax*1.1])
    ax.axhline(0, color="lightgray")
    pp = plt.colorbar(pcm, ax=ax, orientation="vertical")
    sns.utils.despine()
    ax.set_xlabel("pseudotime")
    ax.set_ylabel("inner product score")
//  [python]
def plot_guinier_curve(guinier_data, plot_choice):
    guiner_x = guinier_data["_rlnResolutionSquared"].astype(float)
    guinier_to_plot = [
        "_rlnLogAmplitudesOriginal",
        "_rlnLogAmplitudesMTFCorrected",
        "_rlnLogAmplitudesWeighted",
        "_rlnLogAmplitudesSharpened",
        "_rlnLogAmplitudesIntercept",
    ]

    if plot_choice == "Seaborn":
        sns.set(style="whitegrid", font_scale=1.2)
        fig, ax = plt.subplots(figsize=(10, 6))

        for meta in guinier_to_plot:
            y_data = guinier_data[meta].astype(float)
            y_data[y_data == -99] = float("nan")
            ax.plot(guiner_x, y_data, label=meta.replace("_rlnLogAmplitudes", ""))

        ax.set_xlabel("Resolution Squared, [1/Å²]")
        ax.set_ylabel("Ln(Amplitudes)")
        ax.set_title("Guinier plot")
        ax.legend(loc="upper right", fontsize=8)

        sns.despine()
        plt.tight_layout()
        st.pyplot(fig)
    else:
        fig = go.Figure()
        for meta in guinier_to_plot:
            y_data = guinier_data[meta].astype(float)
            y_data[y_data == -99] = float("nan")
            fig.add_trace(
                go.Scatter(
                    x=guiner_x, y=y_data, mode="lines", name=meta.replace("_rlnLogAmplitudes", "")
                )
            )

        fig.update_layout(
            title="Guinier plot",
            xaxis_title="Resolution Squared, [1/Å²]",
            yaxis_title="Ln(Amplitudes)",
        )
        st.plotly_chart(fig)
//  [python]
def plot_guinier_curve(guinier_data, plot_choice):
    guiner_x = guinier_data["_rlnResolutionSquared"].astype(float)
    guinier_to_plot = [
        "_rlnLogAmplitudesOriginal",
        "_rlnLogAmplitudesMTFCorrected",
        "_rlnLogAmplitudesWeighted",
        "_rlnLogAmplitudesSharpened",
        "_rlnLogAmplitudesIntercept",
    ]

    if plot_choice == "Seaborn":
        sns.set(style="whitegrid", font_scale=1.2)
        fig, ax = plt.subplots(figsize=(10, 6))

        for meta in guinier_to_plot:
            y_data = guinier_data[meta].astype(float)
            y_data[y_data == -99] = float("nan")
            ax.plot(guiner_x, y_data, label=meta.replace("_rlnLogAmplitudes", ""))

        ax.set_xlabel("Resolution Squared, [1/Å²]")
        ax.set_ylabel("Ln(Amplitudes)")
        ax.set_title("Guinier plot")
        ax.legend(loc="upper right", fontsize=8)

        sns.utils.despine()
        plt.tight_layout()
        st.pyplot(fig)
    else:
        fig = go.Figure()
        for meta in guinier_to_plot:
            y_data = guinier_data[meta].astype(float)
            y_data[y_data == -99] = float("nan")
            fig.add_trace(
                go.Scatter(
                    x=guiner_x, y=y_data, mode="lines", name=meta.replace("_rlnLogAmplitudes", "")
                )
            )

        fig.update_layout(
            title="Guinier plot",
            xaxis_title="Resolution Squared, [1/Å²]",
            yaxis_title="Ln(Amplitudes)",
        )
        st.plotly_chart(fig)
//  [python]
def showgoodlayout(tight_layout=True, despined=False):
    """
    Despine and show plots with a good layout.

    This function is called by the various plot functions contained in the
    library but can also be used by the user to quickly adjust the layout of
    custom plots.

    Parameters
    ----------
    tight_layout : bool, default True
        If true (default), plt.tight_layout() is applied to the figure.
    despined : bool or str {"2yaxes"}, default False

        False: left and bottom is not despined (standard plotting).

        True: all the sides are despined.

        ``2yaxes``
            Only the top is despined.
            This is used to show y axes both on the right and left side at the
            same time.
    """

    if despined is False:
        sns.despine()
    elif despined is True:
        sns.despine(top=True, bottom=True, left=True, right=True)
    elif despined == "2yaxes":
        sns.despine(top=True, bottom=False, left=False, right=False)
    else:
        raise ValueError(
            f"despined can be True, False or 2yaxes. {despined} was passed instead"
        )

    if tight_layout is True:
        plt.tight_layout()
//  [python]
def showgoodlayout(tight_layout=True, despined=False):
    """
    Despine and show plots with a good layout.

    This function is called by the various plot functions contained in the
    library but can also be used by the user to quickly adjust the layout of
    custom plots.

    Parameters
    ----------
    tight_layout : bool, default True
        If true (default), plt.tight_layout() is applied to the figure.
    despined : bool or str {"2yaxes"}, default False

        False: left and bottom is not despined (standard plotting).

        True: all the sides are despined.

        ``2yaxes``
            Only the top is despined.
            This is used to show y axes both on the right and left side at the
            same time.
    """

    if despined is False:
        sns.utils.despine()
    elif despined is True:
        sns.utils.despine(top=True, bottom=True, left=True, right=True)
    elif despined == "2yaxes":
        sns.utils.despine(top=True, bottom=False, left=False, right=False)
    else:
        raise ValueError(
            f"despined can be True, False or 2yaxes. {despined} was passed instead"
        )

    if tight_layout is True:
        plt.tight_layout()
//  [python]
def do_warmup_plot(name, runs, num_iter, subtitle='', color='blue', file_prefix=''):
    values = []
    groups = []

    N = len(runs)
    for i in range(num_iter):
        for r in runs:
            print(r)
            values.append(r[i])
            groups.append(i + 1)

    df = pd.DataFrame({'value': values, 'group': groups})
    print(df)

    plt.rcParams.update({
        "text.usetex": True,
        "font.family": "serif",
        "font.serif": ["Palatino"],
    })
    sns.set_color_codes()
    sns.despine()

    ax = df.boxplot(column='value', by='group', showfliers=True,
                    positions=range(df.group.unique().shape[0]), color="black")

    g = sns.pointplot(x='group', y='value', data=df.groupby('group', as_index=False).mean(), ax=ax, color=color,
                      linestyles='--', scale=0.5)

    plt.suptitle(subtitle, fontsize=15)
    plt.ylabel("execution time (s)")
    plt.xlabel("iteration")
    plt.title('')

    vals = df[["value"]].to_numpy()
    # plt.yticks(np.arange(min(vals) - 10, max(vals) + 10, 5))
    fig = plt.gcf()
    fig.set_size_inches(7, 2)

    ax2 = ax.twinx()
    ax2.set_ylabel('{} (N={})'.format(name, N)
                   , rotation=270, labelpad=30)  # fontsize=12)
    ax2.set_yticklabels([])
    ax2.set_yticks([])

    date = str(datetime.datetime.now()).replace(':', '-').replace(' ', '-').replace('.', '-')
    sns.despine(bottom=True, left=True)
    os.makedirs('render', exist_ok=True)
    plt.savefig("render/warmum-" + file_prefix + name.split(' ')[0] + date + '.svg')
    plt.show()

    pass
//  [python]
def do_warmup_plot(name, runs, num_iter, subtitle='', color='blue', file_prefix=''):
    values = []
    groups = []

    N = len(runs)
    for i in range(num_iter):
        for r in runs:
            print(r)
            values.append(r[i])
            groups.append(i + 1)

    df = pd.DataFrame({'value': values, 'group': groups})
    print(df)

    plt.rcParams.update({
        "text.usetex": True,
        "font.family": "serif",
        "font.serif": ["Palatino"],
    })
    sns.set_color_codes()
    sns.utils.despine()

    ax = df.boxplot(column='value', by='group', showfliers=True,
                    positions=range(df.group.unique().shape[0]), color="black")

    g = sns.pointplot(x='group', y='value', data=df.groupby('group', as_index=False).mean(), ax=ax, color=color,
                      linestyles='--', scale=0.5)

    plt.suptitle(subtitle, fontsize=15)
    plt.ylabel("execution time (s)")
    plt.xlabel("iteration")
    plt.title('')

    vals = df[["value"]].to_numpy()
    # plt.yticks(np.arange(min(vals) - 10, max(vals) + 10, 5))
    fig = plt.gcf()
    fig.set_size_inches(7, 2)

    ax2 = ax.twinx()
    ax2.set_ylabel('{} (N={})'.format(name, N)
                   , rotation=270, labelpad=30)  # fontsize=12)
    ax2.set_yticklabels([])
    ax2.set_yticks([])

    date = str(datetime.datetime.now()).replace(':', '-').replace(' ', '-').replace('.', '-')
    sns.utils.despine(bottom=True, left=True)
    os.makedirs('render', exist_ok=True)
    plt.savefig("render/warmum-" + file_prefix + name.split(' ')[0] + date + '.svg')
    plt.show()

    pass
//  [python]
def plot_smoothness(model, factors=None, color="#5F9EA0", return_data=False, **kwargs):
    z = model.get_factors(factors=factors)
    factor_indices, factors = model._check_factors(factors, unique=True)

    # Get scales
    scales = np.array(model.model["training_stats"]["scales"])

    df = pd.DataFrame({"factor": factors, "smooth": scales, "non_smooth": 1 - scales})

    if return_data:
        return df

    sns.barplot(data=df, y="factor", x="smooth", color="lightgrey")
    g = sns.barplot(data=df, color=color, y="factor", x="smooth", **kwargs)

    g.set(xlabel="Smoothness", ylabel="Factor")

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

    plt.tight_layout()

    return g
//  [python]
def plot_smoothness(model, factors=None, color="#5F9EA0", return_data=False, **kwargs):
    z = model.get_factors(factors=factors)
    factor_indices, factors = model._check_factors(factors, unique=True)

    # Get scales
    scales = np.array(model.model["training_stats"]["scales"])

    df = pd.DataFrame({"factor": factors, "smooth": scales, "non_smooth": 1 - scales})

    if return_data:
        return df

    sns.barplot(data=df, y="factor", x="smooth", color="lightgrey")
    g = sns.barplot(data=df, color=color, y="factor", x="smooth", **kwargs)

    g.set(xlabel="Smoothness", ylabel="Factor")

    sns.utils.despine(offset=10, trim=True, ax=g)

    plt.tight_layout()

    return g
//  [python]
def plot_cdf(Parameter, ax=None, show=True, lim_range=True):
    """ Plots the cumulative density function for a Parameter.

    Parameters
    ----------
    Parameter : Parameter
        An instance of the Parameter class.
    ax : matplotlib.axes.Axes, optional
        An instance of the ``matplotlib`` axes class to plot onto. If ``None``, a new figure and axes are created (default: ``None``).
    show : bool, optional
        Option to show the graph.
    lim_range : bool, optional
        Option to limit the range of the x-axis to just the immediate region of the pdf (rather than the full parameter support).

    Returns
    -------
    tuple
        Tuple (:obj:`~matplotlib.figure.Figure`, :obj:`~matplotlib.axes.Axes`) containing the generated figure and axes (only if `show=False`).
    """
    if ax is None:
        fig,ax = plt.subplots(figsize=(8, 6),tight_layout=True)
        ax.set_xlabel(Parameter.variable.capitalize())
        ax.set_ylabel('CDF')
    else:
        fig = ax.figure
    s_values, cdf = Parameter.get_cdf()
    ax.plot(s_values,cdf, '-', c='navy', lw=4)
    # Adjust xrange
    if lim_range:
        idx = np.argwhere((cdf >= 1e-5) & (cdf<=1-1e-5))
        ax.set_xlim([s_values[idx].min(),s_values[idx].max()])
    sns.despine(ax=ax, offset=10, trim=True)
    if show:
        plt.show()
    else:
        return fig, ax
//  [python]
def plot_cdf(Parameter, ax=None, show=True, lim_range=True):
    """ Plots the cumulative density function for a Parameter.

    Parameters
    ----------
    Parameter : Parameter
        An instance of the Parameter class.
    ax : matplotlib.axes.Axes, optional
        An instance of the ``matplotlib`` axes class to plot onto. If ``None``, a new figure and axes are created (default: ``None``).
    show : bool, optional
        Option to show the graph.
    lim_range : bool, optional
        Option to limit the range of the x-axis to just the immediate region of the pdf (rather than the full parameter support).

    Returns
    -------
    tuple
        Tuple (:obj:`~matplotlib.figure.Figure`, :obj:`~matplotlib.axes.Axes`) containing the generated figure and axes (only if `show=False`).
    """
    if ax is None:
        fig,ax = plt.subplots(figsize=(8, 6),tight_layout=True)
        ax.set_xlabel(Parameter.variable.capitalize())
        ax.set_ylabel('CDF')
    else:
        fig = ax.figure
    s_values, cdf = Parameter.get_cdf()
    ax.plot(s_values,cdf, '-', c='navy', lw=4)
    # Adjust xrange
    if lim_range:
        idx = np.argwhere((cdf >= 1e-5) & (cdf<=1-1e-5))
        ax.set_xlim([s_values[idx].min(),s_values[idx].max()])
    sns.utils.despine(ax=ax, offset=10, trim=True)
    if show:
        plt.show()
    else:
        return fig, ax
//  [python]
def plot_total_sobol(Polynomial, ax=None, show=True, labels=None, kwargs={}):
    """ Plots a polynomial's total-order Sobol' indices.

    Parameters
    ----------
    Polynomial : Poly 
        An instance of the Poly class.
    ax : matplotlib.axes.Axes, optional
        An instance of the ``matplotlib`` axes class to plot onto. If ``None``, a new figure and axes are created (default: ``None``).
    parameters : list, optional 
        List of the parameters for the given polynomial.
    show : bool, optional 
        Option to show the graph.
    kwargs : dict, optional
        Dictionary of keyword arguments to pass to matplotlib.bar().  

    Returns
    -------
    tuple
        Tuple (:obj:`~matplotlib.figure.Figure`, :obj:`~matplotlib.axes.Axes`) containing the generated figure and axes (only if `show=False`).
    """
    # Set default kwargs
    kwargs = set_defaults(kwargs, {'color':'dodgerblue', 'ec':'k','lw':2, 'alpha':0.7})

    if ax is None:
        fig,ax = plt.subplots(figsize=(9, 6),tight_layout=True)
    else:
        ax.figure

    ndims = Polynomial.dimensions
    sobol_indices=Polynomial.get_total_sobol_indices()

    ax.set_ylabel(r'$S_{T_i}$')
    if labels is None: labels=[r'$S_{T_%d}$' %i for i in range(ndims)]
    to_plot = [sobol_indices[(i,)] for i in range(ndims)]

    ax.set_xticks(np.arange(ndims))
    ax.set_xticklabels(labels,rotation=45,rotation_mode="anchor",ha='right')
    ax.bar(np.arange(ndims),to_plot,**kwargs)
    sns.despine(offset=10, trim=True)

    if show:
        plt.show()
    else:
        return fig, ax
//  [python]
def plot_total_sobol(Polynomial, ax=None, show=True, labels=None, kwargs={}):
    """ Plots a polynomial's total-order Sobol' indices.

    Parameters
    ----------
    Polynomial : Poly 
        An instance of the Poly class.
    ax : matplotlib.axes.Axes, optional
        An instance of the ``matplotlib`` axes class to plot onto. If ``None``, a new figure and axes are created (default: ``None``).
    parameters : list, optional 
        List of the parameters for the given polynomial.
    show : bool, optional 
        Option to show the graph.
    kwargs : dict, optional
        Dictionary of keyword arguments to pass to matplotlib.bar().  

    Returns
    -------
    tuple
        Tuple (:obj:`~matplotlib.figure.Figure`, :obj:`~matplotlib.axes.Axes`) containing the generated figure and axes (only if `show=False`).
    """
    # Set default kwargs
    kwargs = set_defaults(kwargs, {'color':'dodgerblue', 'ec':'k','lw':2, 'alpha':0.7})

    if ax is None:
        fig,ax = plt.subplots(figsize=(9, 6),tight_layout=True)
    else:
        ax.figure

    ndims = Polynomial.dimensions
    sobol_indices=Polynomial.get_total_sobol_indices()

    ax.set_ylabel(r'$S_{T_i}$')
    if labels is None: labels=[r'$S_{T_%d}$' %i for i in range(ndims)]
    to_plot = [sobol_indices[(i,)] for i in range(ndims)]

    ax.set_xticks(np.arange(ndims))
    ax.set_xticklabels(labels,rotation=45,rotation_mode="anchor",ha='right')
    ax.bar(np.arange(ndims),to_plot,**kwargs)
    sns.utils.despine(offset=10, trim=True)

    if show:
        plt.show()
    else:
        return fig, ax
//  [python]
def _make_plot(self, df):
        """
        Build the plot with the dataset in the correct format.

        Parameters
        ----------
        df: pd.DataFrame
            DataFrame with the metrics data.

        Returns
        -------
        ax: matplotlib.axes.Axes
            ax object as returned by matplotlib.
        """
        plt.rcParams["figure.figsize"] = (20, 15)
        plt.rcParams["xtick.labelsize"] = "large"
        plt.rcParams["ytick.labelsize"] = "large"

        ax = sns.barplot(
            y="dataset_name",
            x=self.metric_field,
            data=df.sort_values(["model_name", "dataset_name"]),
            hue="model_name",
        )
        ax.set_xticks(
            np.linspace(
                0.0,
                (
                    1.0
                    if df[self.metric_field].max() < 1.0
                    else df[self.metric_field].max()
                ),
                25,
            )
        )
        plt.grid(True, color="#93a1a1", alpha=0.9, linestyle="--", which="both")
        plt.title(
            "Experiments Results",
            size=22,
            fontdict={
                "fontstyle": "normal",
                "fontfamily": "serif",
                "fontweight": "bold",
            },
        )
        plt.ylabel("Dataset Name", size=18, fontdict={"fontfamily": "serif"})
        plt.xlabel(
            f"{self.metric_field if not self.modified_metric_fieldname else self.modified_metric_fieldname}",
            size=18,
            fontdict={"fontfamily": "serif"},
        )
        sns.despine()
        plt.legend(bbox_to_anchor=(0.9, 0.98), loc=3, borderaxespad=0.0)
        return ax
//  [python]
def _make_plot(self, df):
        """
        Build the plot with the dataset in the correct format.

        Parameters
        ----------
        df: pd.DataFrame
            DataFrame with the metrics data.

        Returns
        -------
        ax: matplotlib.axes.Axes
            ax object as returned by matplotlib.
        """
        plt.rcParams["figure.figsize"] = (20, 15)
        plt.rcParams["xtick.labelsize"] = "large"
        plt.rcParams["ytick.labelsize"] = "large"

        ax = sns.barplot(
            y="dataset_name",
            x=self.metric_field,
            data=df.sort_values(["model_name", "dataset_name"]),
            hue="model_name",
        )
        ax.set_xticks(
            np.linspace(
                0.0,
                (
                    1.0
                    if df[self.metric_field].max() < 1.0
                    else df[self.metric_field].max()
                ),
                25,
            )
        )
        plt.grid(True, color="#93a1a1", alpha=0.9, linestyle="--", which="both")
        plt.title(
            "Experiments Results",
            size=22,
            fontdict={
                "fontstyle": "normal",
                "fontfamily": "serif",
                "fontweight": "bold",
            },
        )
        plt.ylabel("Dataset Name", size=18, fontdict={"fontfamily": "serif"})
        plt.xlabel(
            f"{self.metric_field if not self.modified_metric_fieldname else self.modified_metric_fieldname}",
            size=18,
            fontdict={"fontfamily": "serif"},
        )
        sns.utils.despine()
        plt.legend(bbox_to_anchor=(0.9, 0.98), loc=3, borderaxespad=0.0)
        return ax
//  [python]
def plot_sharedness(
    model, groups=None, factors=None, color="#B8CF87", return_data=False, **kwargs
):
    GROUPS_MSG = "Multiple groups are required to determine sharedness"
    assert model.ngroups > 1, GROUPS_MSG
    if groups is not None:
        assert not isinstance(groups, str) and len(groups) > 1, GROUPS_MSG

    z = model.get_factors(factors=factors, groups=groups)
    factor_indices, factors = model._check_factors(factors, unique=True)

    groups = model._check_groups(groups)
    all_groups = np.array(model.groups)
    group_indices = [np.where(all_groups == gr)[0][0] for gr in groups]

    # Get group kernels
    Kgs = model.get_group_kernel()[factor_indices, :, :][:, group_indices, :][
        :, :, group_indices
    ]

    # Calculate distance
    gr = np.array(
        [
            np.abs(Kgs[i, :, :])[np.tril(Kgs[i, :, :], -1).astype(bool)].mean()
            for i in range(Kgs.shape[0])
        ]
    )

    df = pd.DataFrame({"factor": factors, "shared": gr, "non_shared": 1 - gr})

    if return_data:
        return df

    sns.barplot(data=df, y="factor", x="shared", color="lightgrey")
    g = sns.barplot(data=df, color=color, y="factor", x="shared", **kwargs)

    g.set(xlabel="Sharedness", ylabel="Factor")

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

    plt.tight_layout()

    return g
//  [python]
def plot_sharedness(
    model, groups=None, factors=None, color="#B8CF87", return_data=False, **kwargs
):
    GROUPS_MSG = "Multiple groups are required to determine sharedness"
    assert model.ngroups > 1, GROUPS_MSG
    if groups is not None:
        assert not isinstance(groups, str) and len(groups) > 1, GROUPS_MSG

    z = model.get_factors(factors=factors, groups=groups)
    factor_indices, factors = model._check_factors(factors, unique=True)

    groups = model._check_groups(groups)
    all_groups = np.array(model.groups)
    group_indices = [np.where(all_groups == gr)[0][0] for gr in groups]

    # Get group kernels
    Kgs = model.get_group_kernel()[factor_indices, :, :][:, group_indices, :][
        :, :, group_indices
    ]

    # Calculate distance
    gr = np.array(
        [
            np.abs(Kgs[i, :, :])[np.tril(Kgs[i, :, :], -1).astype(bool)].mean()
            for i in range(Kgs.shape[0])
        ]
    )

    df = pd.DataFrame({"factor": factors, "shared": gr, "non_shared": 1 - gr})

    if return_data:
        return df

    sns.barplot(data=df, y="factor", x="shared", color="lightgrey")
    g = sns.barplot(data=df, color=color, y="factor", x="shared", **kwargs)

    g.set(xlabel="Sharedness", ylabel="Factor")

    sns.utils.despine(offset=10, trim=True, ax=g)

    plt.tight_layout()

    return g
//  [python]
sns.set_theme(style="whitegrid")

# Load the example diamonds dataset
diamonds = sns.load_dataset("diamonds")

# Draw a scatter plot while assigning point colors and sizes to different
# variables in the dataset
f, ax = plt.subplots(figsize=(6.5, 6.5))
sns.despine(f, left=True, bottom=True)
//  [python]
sns.set_theme(style="whitegrid")

# Load the example diamonds dataset
diamonds = sns.load_dataset("diamonds")

# Draw a scatter plot while assigning point colors and sizes to different
# variables in the dataset
f, ax = plt.subplots(figsize=(6.5, 6.5))
sns.utils.despine(f, left=True, bottom=True)
//  [python]
def show_SD(axis, xi, yi, text):
    '''Show the area covered by 1/2/3 SDs'''
    
    fc = 'red'
    axis.plot(x,y)
    axis.fill_between(xi, yi, facecolor=fc)
    
    axis.text(0, 0.05, text, horizontalalignment='center', fontsize=25)
    axis.set_xlim([-3.5, 3.5])
    axis.set_ylim([-0.0, 0.5])
    sns.despine(ax=axis, left=True)
    axis.set_yticks([])
//  [python]
def show_SD(axis, xi, yi, text):
    '''Show the area covered by 1/2/3 SDs'''
    
    fc = 'red'
    axis.plot(x,y)
    axis.fill_between(xi, yi, facecolor=fc)
    
    axis.text(0, 0.05, text, horizontalalignment='center', fontsize=25)
    axis.set_xlim([-3.5, 3.5])
    axis.set_ylim([-0.0, 0.5])
    sns.utils.despine(ax=axis, left=True)
    axis.set_yticks([])
//  [python]
def plot_group_kernel(
    model, groups=None, factors=None, palette=None, vmin=-1, vmax=1, ncols=4, **kwargs
):

    z = model.get_factors(factors=factors, groups=groups)
    factor_indices, factors = model._check_factors(factors, unique=True)

    groups = model._check_groups(groups)
    all_groups = np.array(model.groups)
    group_indices = [np.where(all_groups == gr)[0][0] for gr in groups]

    # Get group kernels
    Kgs = model.get_group_kernel()[factor_indices, :, :][:, group_indices, :][
        :, :, group_indices
    ]

    df_list = [
        pd.DataFrame(Kgs[i], index=groups, columns=groups) for i in range(Kgs.shape[0])
    ]

    if palette is None:
        palette = "RdBu_r"

    # Only use clustermap when there's one factors to plot
    # since it creates its own figure
    if len(factors) == 1:
        g = sns.clustermap(df_list[0], cmap=palette, vmin=vmin, vmax=vmax, **kwargs)
        g.ax_heatmap.set(ylabel="Group", xlabel="Group", title=factors[0])
        g.ax_heatmap.set_yticklabels(g.ax_heatmap.yaxis.get_ticklabels(), rotation=0)

        sns.despine(offset=10, trim=True, ax=g.ax_heatmap)

    else:
        # Figure out rows & columns for the grid with plots
        ncols = min(ncols, len(factors))
        nrows = int(np.ceil(len(factors) / ncols))
        fig, axes = plt.subplots(
            nrows,
            ncols,
            figsize=(
                ncols * rcParams["figure.figsize"][0],
                nrows * rcParams["figure.figsize"][1],
            ),
        )

        if ncols == 1:
            axes = np.array(axes).reshape(-1, 1)
        if nrows == 1:
            axes = np.array(axes).reshape(1, -1)

        for i, factor in enumerate(factors):

            ri = i // ncols
            ci = i % ncols

            g = sns.heatmap(
                df_list[i],
                square=True,
                cmap=palette,
                vmin=vmin,
                vmax=vmax,
                ax=axes[ri, ci],
                **kwargs,
            )
            g.set(ylabel="Group", xlabel="Group", title=factor)
            g.set_yticklabels(g.yaxis.get_ticklabels(), rotation=0)

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

        # Remove unused axes
        for i in range(len(factors), ncols * nrows):
            ri = i // ncols
            ci = i % ncols
            fig.delaxes(axes[ri, ci])

    plt.tight_layout()

    return g