Exemple #1
0
def get_roi(fig: plt.Figure, df: pd.DataFrame, params: dict) -> dict:
    """
    use the drawn figure to extract the relevant data in order to build an animation


    Parameters
    ----------
    fig : plt.Figure
        the figure to get data from.
    df : pd.DataFrame
        waves recording.
    params : dict of parameters

    Returns
    -------
    dict :
        containing ylims, xlims(point, dtime and sec)
    """

    ylims = tuple([_.get_ylim() for _ in fig.get_axes()])
    # xlims
    ax = fig.get_axes()[0]
    if params["dtime"]:
        dtime_lims = [pd.to_datetime(mdates.num2date(_)) for _ in ax.get_xlim()]
        # remove timezone
        dtime_lims = [_.tz_localize(None) for _ in dtime_lims]

        i_lims = [
            df.set_index("datetime").index.get_loc(_, method="nearest")
            for _ in dtime_lims
        ]
    else:
        # index = sec
        i_lims = [
            df.set_index("sec").index.get_loc(_, method="nearest")
            for _ in ax.get_xlim()
        ]
    roidict = {}
    for k, v in {"dt": "datetime", "pt": "point", "sec": "sec"}.items():
        if v in df.columns:
            lims = tuple([df.iloc[_][[v]].values[0] for _ in i_lims])
        else:
            # no dt values for televet
            lims = (np.nan, np.nan)
        roidict[k] = lims
    print(f"{'-' * 10} defined a roi")
    # append ylims and traces
    roidict["ylims"] = ylims
    return roidict
Exemple #2
0
def plot_deeppoly(ele: deeppoly.Ele,
                  x_lim=(-1, 1),
                  y_lim=(-1, 1),
                  fig: plt.Figure = None):

    lb = ele.lb().detach().numpy().squeeze()
    ub = ele.ub().detach().numpy().squeeze()
    step_size = 0.01

    assert len(lb) == 2

    h_bound_x = np.arange(lb[0], ub[0], step_size)
    h_bound_y1 = np.full_like(h_bound_x, lb[1])
    h_bound_y2 = np.full_like(h_bound_x, ub[1])

    v_bound_y = np.arange(lb[1], ub[1], step_size)
    v_bound_x1 = np.full_like(v_bound_y, lb[0])
    v_bound_x2 = np.full_like(v_bound_y, ub[0])

    if fig is None:
        fig, ax = plt.subplots()
    else:
        ax = fig.get_axes()[0]

    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    ax.grid(True)

    ax.plot(h_bound_x, h_bound_y1, "r-", alpha=0.5)
    ax.plot(h_bound_x, h_bound_y2, "r-", alpha=0.5)
    ax.plot(v_bound_x1, v_bound_y, "r-", alpha=0.5)
    ax.plot(v_bound_x2, v_bound_y, "r-", alpha=0.5)
    ax.fill_between(h_bound_x, h_bound_y1, h_bound_y2, alpha=0.5)

    return fig, ax
def plot_roc(roc: ROC,
             title: str = "",
             label: str = "",
             show=False,
             save=False,
             fig: plt.Figure = None):
    if fig is None:
        fig = plt.figure()
        ax = fig.add_axes([0.1, 0.1, 0.85, 0.8])
    else:
        ax = fig.get_axes()
        assert len(ax) == 1
        ax = ax[0]

    lw = 2
    fpr, tpr, _ = roc
    ax.plot(fpr, tpr, lw=lw, label=label)

    ax.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
    ax.set(xlabel='FPR', ylabel='TPR', ylim=[0.0, 1.05], xlim=[0.0, 1.0])
    ax.set_title(title, fontsize=15)
    ax.legend(loc="lower right")
    # fig.tight_layout()
    if show:
        fig.show()
    if save:
        fig.savefig(f'figs/{title}_{label}.png')
    return fig
Exemple #4
0
def set_figure_properties(fig: plt.Figure, **kwargs) -> None:
    """
    Ease the configuration of a :class:`matplotlib.figure.Figure`.

    Parameters
    ----------
    fig : matplotlib.figure.Figure
        The figure.

    Keyword arguments
    -----------------
    fontsize : int
        Font size to use for the plot titles, and axes ticks and labels.
        Defaults to 12.
    tight_layout : bool
        `True` to fit the whole subplots into the figure area,
        `False` otherwise. Defaults to `True`.
    tight_layout_rect : Sequence[float]
        A rectangle (left, bottom, right, top) in the normalized figure
        coordinate that the whole subplots area (including labels) will
        fit into. Defaults to (0, 0, 1, 1).
    suptitle : str
        The figure title. Defaults to an empty string.
    xlabel : str
        TODO
    ylabel : str
        TODO
    figlegend_on : bool
        TODO
    figlegend_ax : int
        TODO
    figlegend_loc : `str` or `Tuple[float, float]`
        TODO
    figlegend_framealpha : float
        TODO
    figlegend_ncol : int
        TODO
    subplots_adjust_hspace : float
        TODO
    subplots_adjust_vspace : float
        TODO
    """
    fontsize = kwargs.get("fontsize", 12)
    tight_layout = kwargs.get("tight_layout", True)
    tight_layout_rect = kwargs.get("tight_layout_rect", (0, 0, 1, 1))
    suptitle = kwargs.get("suptitle", "")
    x_label = kwargs.get("x_label", "")
    x_labelpad = kwargs.get("x_labelpad", 20)
    y_label = kwargs.get("y_label", "")
    y_labelpad = kwargs.get("y_labelpad", 20)
    figlegend_on = kwargs.get("figlegend_on", False)
    figlegend_ax = kwargs.get("figlegend_ax", 0)
    figlegend_loc = kwargs.get("figlegend_loc", "lower center")
    figlegend_framealpha = kwargs.get("figlegend_framealpha", 1.0)
    figlegend_ncol = kwargs.get("figlegend_ncol", 1)
    wspace = kwargs.get("subplots_adjust_wspace", None)
    hspace = kwargs.get("subplots_adjust_hspace", None)

    rcParams["font.size"] = fontsize

    if suptitle is not None and suptitle != "":
        fig.suptitle(suptitle, fontsize=fontsize + 1)

    if x_label != "" or y_label != "":
        ax = fig.add_subplot(111)
        ax.set_frame_on(False)
        ax.set_xticks([])
        ax.set_xticklabels([], visible=False)
        ax.set_yticks([])
        ax.set_yticklabels([], visible=False)

        if x_label != "":
            ax.set_xlabel(x_label, labelpad=x_labelpad)
        if y_label != "":
            ax.set_ylabel(y_label, labelpad=y_labelpad)

    if tight_layout:
        fig.tight_layout(rect=tight_layout_rect)

    if figlegend_on:
        handles, labels = fig.get_axes()[figlegend_ax].get_legend_handles_labels()
        fig.legend(
            handles,
            labels,
            loc=figlegend_loc,
            framealpha=figlegend_framealpha,
            ncol=figlegend_ncol,
        )

    if wspace is not None:
        fig.subplots_adjust(wspace=wspace)
    if hspace is not None:
        fig.subplots_adjust(hspace=hspace)
Exemple #5
0
def append_beat(
    beatdf: pd.DataFrame,
    ekgdf: pd.DataFrame,
    tochangedf: pd.DataFrame,
    fig: plt.Figure,
    lim: Tuple = None,
    yscale: float = 1,
) -> pd.DataFrame:
    """
    append a beat coordonate from the figure to the tochangedf['toAppend']

    Parameters
    ----------
    beatdf : pd.Dataframe
        beat position (point based location : p_locs)
    ekgdf : pd.Dataframe
        waves data (wekg_lowpass).
    tochangedf : pd.Dataframe
        the beat to add or remove (point based toAppend & toRemove)
    fig : plt.Figure
        the figure to get the location.
    lim : TYPE, optional (default is None)
        ptBasedLim optional to give it manually
    yscale : TYPE, optional (default is 1)
        amplitude mutliplication factor for detection.

    Returns
    -------
    tochangedf : pd.DataFrame
        incremented changedf (pt location).


    methods :

        locate the beat in the figure, append to a dataframe['toAppend']
        0.: if not present : build a dataframe:
            >>> to_change_df = pd.DataFrame(columns=['toAppend', 'toRemove'])

        1.: locate the extra beat in the figure (cf plot_beats())
            and zoom to observe only a negative peak

        2.: call the function:
            >>> to_change_df = remove_beat(beatdf, ekgdf, tochangedf, fig)
            -> the beat parameters will be added the dataFrame

        .in the end of the manual check, update the beat_df
              - first : save beat_df and to_change_df
              - second : run:
                  >>> beat_df = update_beat_df())
    """

    # find the limits of the figure
    if lim is None:
        lims = fig.get_axes()[0].get_xlim()
        lim = (int(lims[0]), int(lims[1]))
    # restrict area around the undetected pic (based on pt x val)
    df = ekgdf.wekg_lowpass.loc[lim[0]:lim[1]]
    # locate the beat (external call)
    onepoint_beatdf = detect_beats(df, mult=yscale)
    onepoint_beatdf["action"] = "append"
    if len(onepoint_beatdf) < 1:
        print("no beat founded")
        return tochangedf
    found_loc = onepoint_beatdf.p_loc.values[0]
    y_loc = onepoint_beatdf.y_loc.values[0]
    # reassign the pt value
    p_loc = ekgdf.wekg_lowpass.loc[lim[0]:lim[1]].index[found_loc]
    onepoint_beatdf["p_loc"] = p_loc
    print("founded ", p_loc)
    # append to figure
    fig.get_axes()[0].plot(p_loc, y_loc, "og")
    onepoint_beatdf.p_loc = p_loc
    onepoint_beatdf.left_bases += p_loc - found_loc
    onepoint_beatdf.right_bases.values[0] += p_loc - found_loc
    # insert in the tochangedf
    # beatdf = beatdf.drop_duplicates('p_loc')
    tochangedf = tochangedf.append(onepoint_beatdf)
    return tochangedf