Esempio n. 1
0
def curves_i(
    cols: list,
    tc: np.array,
    highlight: list = None,
    labelsize: float = 12,
    factor: float = 1,
    xlabel: str = None,
    ylabel: str = None,
    sdir: str = None,
    show: bool = False,
):
    """Shows every breakthrough individually for each observation point. Will
    produce n_well figures of n_sim curves each.

    :param cols: List of colors
    :param labelsize:
    :param factor:
    :param xlabel:
    :param ylabel:
    :param tc: Curves with shape (n_sim, n_wells, n_time_steps)
    :param highlight: list: List of indices of curves to highlight in the plot
    :param sdir: Directory in which to save figure
    :param show: Whether to show or not
    """
    if highlight is None:
        highlight = []
    title = "curves"
    n_sim, n_wels, nts = tc.shape
    for t in range(n_wels):
        for i in range(n_sim):
            if i in highlight:
                plt.plot(tc[i][t] * factor, color="k", linewidth=2, alpha=1)
            else:
                plt.plot(tc[i][t] * factor, color=cols[t], linewidth=0.2, alpha=0.5)
        colors = [cols[t], "k"]
        plt.grid(linewidth=0.3, alpha=0.4)
        plt.tick_params(labelsize=labelsize)
        # plt.title(f'Well {t + 1}')

        alphabet = string.ascii_uppercase
        legend_a = _proxy_annotate([f"{alphabet[t]}. Well {t + 1}"], fz=12, loc=2)

        labels = ["Training", "Test"]
        _proxy_legend(legend1=legend_a, colors=colors, labels=labels, loc=1)

        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        if sdir:
            utils.dirmaker(sdir)
            plt.savefig(jp(sdir, f"{title}_{t + 1}.png"), dpi=300, transparent=False)
            if show:
                plt.show()
                plt.close()
        elif show:
            plt.show()
            plt.close()
        plt.close()
Esempio n. 2
0
def curves(
    cols: list,
    tc: np.array,
    highlight: list = None,
    ghost: bool = False,
    sdir: str = None,
    labelsize: float = 12,
    factor: float = 1,
    conc: bool = 0,
    xlabel: str = None,
    ylabel: str = None,
    title: str = "curves",
    show: bool = False,
):
    """Shows every breakthrough curve stacked on a plot.

    :param cols: List of colors
    :param ylabel:
    :param xlabel:
    :param factor:
    :param labelsize:
    :param tc: Curves with shape (n_sim, n_wells, n_time_steps)
    :param highlight: list: List of indices of curves to highlight in the plot
    :param ghost: bool: Flag to only display highlighted curves.
    :param sdir: Directory in which to save figure
    :param title: str: Title
    :param show: Whether to show or not
    """
    if highlight is None:
        highlight = []

    if not conc:
        n_sim, n_wells, nts = tc.shape
        for i in range(n_sim):
            for t in range(n_wells):
                if i in highlight:
                    plt.plot(tc[i][t] * factor, color=cols[t], linewidth=2, alpha=1)
                elif not ghost:
                    plt.plot(tc[i][t] * factor, color=cols[t], linewidth=0.2, alpha=0.5)
    else:
        plt.plot(np.concatenate(tc[0]) * factor, color=cols[0], linewidth=2, alpha=1)

    plt.grid(linewidth=0.3, alpha=0.4)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.tick_params(labelsize=labelsize)
    if sdir:
        utils.dirmaker(sdir)
        plt.savefig(jp(sdir, f"{title}.png"), dpi=300, transparent=False)
        if show:
            plt.show()
            plt.close()
    elif show:
        plt.show()
        plt.close()
    plt.close()
Esempio n. 3
0
    # %% Set directories
    data_dir = jp(os.getcwd(), "dataset")
    # Directory in which to unload forecasts
    sub_dir = jp(os.getcwd(), "results")

    # Folders
    obj_dir = jp(sub_dir, "obj")  # Location to save the BEL model
    fig_data_dir = jp(sub_dir, "data")  # Location to save the raw data figures
    fig_pca_dir = jp(sub_dir, "pca")  # Location to save the PCA figures
    fig_cca_dir = jp(sub_dir, "cca")  # Location to save the CCA figures
    fig_pred_dir = jp(sub_dir, "uq")  # Location to save the prediction figures

    # Creates directories
    [
        utils.dirmaker(f, erase=True) for f in [
            obj_dir,
            fig_data_dir,
            fig_pca_dir,
            fig_cca_dir,
            fig_pred_dir,
        ]
    ]

    # %% Load dataset
    X_train = pd.read_pickle(jp(data_dir, "X_train.pkl"))
    X_test = pd.read_pickle(jp(data_dir, "X_test.pkl"))
    y_train = pd.read_pickle(jp(data_dir, "y_train.pkl"))
    y_test = pd.read_pickle(jp(data_dir, "y_test.pkl"))

    # %% Initiate BEL model
Esempio n. 4
0
    # %% Set directories
    data_dir = jp(os.getcwd(), "dataset")
    # Directory in which to unload forecasts
    sub_dir = jp(os.getcwd(), "results_dev")

    # Folders
    obj_dir = jp(sub_dir, "obj")  # Location to save the BEL model
    fig_data_dir = jp(sub_dir, "data")  # Location to save the raw data figures
    fig_pca_dir = jp(sub_dir, "pca")  # Location to save the PCA figures
    fig_cca_dir = jp(sub_dir, "cca")  # Location to save the CCA figures
    fig_pred_dir = jp(sub_dir, "uq")  # Location to save the prediction figures

    # Creates directories
    [
        utils.dirmaker(f, erase=True)
        for f in [
            obj_dir,
            fig_data_dir,
            fig_pca_dir,
            fig_cca_dir,
            fig_pred_dir,
        ]
    ]

    # %% Load dataset
    X_train = pd.read_pickle(jp(data_dir, "X_train.pkl"))
    X_test = pd.read_pickle(jp(data_dir, "X_test.pkl"))
    y_train = pd.read_pickle(jp(data_dir, "y_train.pkl"))
    y_test = pd.read_pickle(jp(data_dir, "y_test.pkl"))
Esempio n. 5
0
def whpa_plot(
    grf: float = None,
    well_comb: list = None,
    whpa: np.array = None,
    alpha: float = 0.4,
    halpha: float = None,
    lw: float = 0.5,
    bkg_field_array: np.array = None,
    vmin: float = None,
    vmax: float = None,
    x_lim: list = None,
    y_lim: list = None,
    xlabel: str = None,
    ylabel: str = None,
    cb_title: str = None,
    labelsize: float = 5,
    cmap: str = "coolwarm",
    color: str = "white",
    grid: bool = True,
    show_wells: bool = False,
    well_ids: list = None,
    title: str = None,
    annotation: list = None,
    fig_file: str = None,
    highlight: bool = False,
    show: bool = False,
):
    """Produces the WHPA plot, i.e. the zero-contour of the signed distance
    array.

    :param grid: Whether to plot the grid
    :param grf: Grid cell size
    :param well_comb: List of well combination
    :param highlight: Boolean to display lines on top of filling between contours or not.
    :param annotation: List of annotations (str)
    :param xlabel: X axis label
    :param ylabel: Y axis label
    :param cb_title: Colorbar title
    :param well_ids: List of well ids
    :param labelsize: Label size
    :param title: str: plot title
    :param show_wells: bool: whether to plot well coordinates or not
    :param cmap: str: colormap name for the background array
    :param vmax: float: max value to plot for the background array
    :param vmin: float: max value to plot for the background array
    :param bkg_field_array: np.array: 2D array whose values will be plotted on the grid
    :param whpa: np.array: Array containing grids of values whose 0 contour will be computed and plotted
    :param alpha: float: opacity of the 0 contour lines
    :param halpha: Alpha value for line plots if highlight is True
    :param lw: float: Line width
    :param color: str: Line color
    :param fig_file: str: File name to save the figure
    :param show: bool: Whether to show the figure or not
    :param x_lim: [x_min, x_max] For the figure
    :param y_lim: [y_min, y_max] For the figure
    """

    # Get basic settings
    focus = Setup.Focus
    wells = Setup.Wells

    if well_comb is not None:
        wells.combination = well_comb

    if y_lim is None:
        ylim = focus.y_range
    else:
        ylim = y_lim
    if x_lim is None:
        xlim = focus.x_range
    else:
        xlim = x_lim
    if grf is None:
        grf = focus.cell_dim
    else:
        grf = grf

    nrow, ncol, x, y = refine_machine(focus.x_range, focus.y_range, grf)

    # Plot background
    if bkg_field_array is not None:
        plt.imshow(
            bkg_field_array,
            extent=np.concatenate([focus.x_range, focus.y_range]),
            vmin=vmin,
            vmax=vmax,
            cmap=cmap,
        )
        cb = plt.colorbar(fraction=0.046, pad=0.04)
        cb.ax.set_title(cb_title)

    if halpha is None:
        halpha = alpha

    # Plot results
    if whpa is None:
        whpa = []

    if whpa.ndim > 2:  # New approach is to plot filled contours
        new_grf = 1  # Refine grid
        _, _, new_x, new_y = refine_machine(xlim, ylim, new_grf=new_grf)
        xys, nrow, ncol = grid_parameters(x_lim=xlim, y_lim=ylim, grf=new_grf)
        vertices = contours_vertices(x=x, y=y, arrays=whpa)
        b_low = binary_stack(xys=xys, nrow=nrow, ncol=ncol, vertices=vertices)
        contour = plt.contourf(
            new_x,
            new_y,
            1 - b_low,  # Trick to be able to fill contours
            # Use machine epsilon
            [np.finfo(float).eps, 1 - np.finfo(float).eps],
            colors=color,
            alpha=alpha,
        )
        if highlight:  # Also display curves
            for z in whpa:
                contour = plt.contour(
                    z,
                    [0],
                    extent=(xlim[0], xlim[1], ylim[0], ylim[1]),
                    colors=color,
                    linewidths=lw,
                    alpha=halpha,
                )

    else:  # If only one WHPA to display
        contour = plt.contour(
            whpa,
            [0],
            extent=np.concatenate([focus.x_range, focus.y_range]),
            colors=color,
            linewidths=lw,
            alpha=halpha,
        )

    # Grid
    if grid:
        plt.grid(color="c", linestyle="-", linewidth=0.5, alpha=0.2)

    # Plot wells
    well_legend = None
    if show_wells:
        plot_wells(wells, well_ids=well_ids, markersize=7)
        well_legend = plt.legend(fontsize=11)

    # Plot limits
    if x_lim is None:
        plt.xlim(xlim[0], xlim[1])
    else:
        plt.xlim(x_lim[0], x_lim[1])
    if y_lim is None:
        plt.ylim(ylim[0], ylim[1])
    else:
        plt.ylim(y_lim[0], y_lim[1])

    if title:
        plt.title(title)

    plt.xlabel(xlabel, fontsize=labelsize)
    plt.ylabel(ylabel, fontsize=labelsize)

    # Tick size
    plt.tick_params(labelsize=labelsize)

    if annotation:
        legend = _proxy_annotate(annotation=annotation, fz=14, loc=2)
        plt.gca().add_artist(legend)

    if fig_file:
        utils.dirmaker(os.path.dirname(fig_file))
        plt.savefig(fig_file, bbox_inches="tight", dpi=300, transparent=False)
        plt.close()
    elif show:
        plt.show()
        plt.close()

    return contour, well_legend
Esempio n. 6
0
def h_pca_inverse_plot(bel, fig_dir: str = None, show: bool = False):
    """Plot used to compare the reproduction of the original physical space
    after PCA transformation.

    :param bel: BEL model
    :param fig_dir: str: directory where to save the figure
    :param show: bool: if True, show the figure
    :return:
    """

    shape = bel.Y_shape

    if bel.Y_obs_pc is not None:
        v_pc = check_array(bel.Y_obs_pc.reshape(1, -1))
    else:
        try:
            Y_obs = check_array(bel.Y_obs, allow_nd=True)
        except ValueError:
            Y_obs = check_array(bel.Y_obs.to_numpy().reshape(1, -1))

        v_pc = bel.Y_pre_processing.transform(Y_obs)[
            :, : Setup.HyperParameters.n_pc_target
        ]

    nc = bel.Y_pre_processing["pca"].n_components_
    dummy = np.zeros((1, nc))
    dummy[:, : v_pc.shape[1]] = v_pc
    v_pred = bel.Y_pre_processing.inverse_transform(dummy)

    h_to_plot = np.copy(Y_obs.reshape(1, shape[1], shape[2]))

    whpa_plot(whpa=h_to_plot, color="red", alpha=1, lw=2)

    whpa_plot(
        whpa=v_pred.reshape(1, shape[1], shape[2]),
        color="blue",
        alpha=1,
        lw=2,
        labelsize=11,
        xlabel="X(m)",
        ylabel="Y(m)",
        x_lim=[850, 1100],
        y_lim=[350, 650],
    )

    # Add title inside the box
    an = ["B"]

    legend_a = _proxy_annotate(annotation=an, loc=2, fz=14)

    _proxy_legend(
        legend1=legend_a,
        colors=["red", "blue"],
        labels=["Physical", "Back transformed"],
        marker=["-", "-"],
    )

    if fig_dir is not None:
        utils.dirmaker(fig_dir)
        plt.savefig(
            jp(fig_dir, f"h_pca_inverse_transform.png"), dpi=300, transparent=False
        )
        if show:
            plt.show()
            plt.close()
    elif show:
        plt.show()
        plt.close()
Esempio n. 7
0
def d_pca_inverse_plot(
    bel,
    root,
    factor: float = 1.0,
    xlabel: str = None,
    ylabel: str = None,
    labelsize: float = 11.0,
    fig_dir: str = None,
    show: bool = False,
):
    """Plot used to compare the reproduction of the original physical space
    after PCA transformation.

    :param bel: BEL model
    :param xlabel:
    :param ylabel:
    :param labelsize:
    :param factor:
    :param fig_dir: str:
    :param show: bool:
    :return:
    """

    shape = bel.X_shape
    v_pc = bel.X_obs_pc

    nc = bel.X_pre_processing["pca"].n_components_
    dummy = np.zeros((1, nc))
    dummy[:, : v_pc.shape[1]] = v_pc

    v_pred = bel.X_pre_processing.inverse_transform(dummy).reshape((-1,) + shape)
    to_plot = np.copy(bel.X_obs).reshape((-1,) + shape)

    cols = ["r" for _ in range(shape[1])]
    highlights = [i for i in range(shape[1])]
    curves(cols=cols, tc=to_plot, factor=factor, highlight=highlights, conc=True)

    cols = ["b" for _ in range(shape[1])]
    curves(cols=cols, tc=v_pred, factor=factor, highlight=highlights, conc=True)

    # Add title inside the box
    an = ["A"]
    legend_a = _proxy_annotate(annotation=an, loc=2, fz=14)
    _proxy_legend(
        legend1=legend_a,
        colors=["red", "blue"],
        labels=["Physical", "Back transformed"],
        marker=["-", "-"],
        loc=1,
    )
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.tick_params(labelsize=labelsize)

    # Increase y axis by a small percentage for annotation in upper left corner
    yrange = np.max(to_plot * factor) * 1.15
    plt.ylim([0, yrange])

    if fig_dir is not None:
        utils.dirmaker(fig_dir)
        plt.savefig(jp(fig_dir, f"{root}_d.png"), dpi=300, transparent=False)
        if show:
            plt.show()
            plt.close()
    elif show:
        plt.show()
        plt.close()