Skip to content

plotting

Plotting functions often needed. Not extremely well polished, rather a tool for quick visualization.

plot_predicted_ts(ts_true, ts_pred, start=None, end=None, ax=None, title='', figsize=(6, 2), legend=True)

Parameters:

Name Type Description Default
ts_true Union[numpy.ndarray, List, pandas.core.series.Series]

np.ndarray, List, pd.Series Target time series.

required
ts_pred Union[numpy.ndarray, List, pandas.core.series.Series]

np.ndarray, List, pd.Series Predicted time series.

required
start int

int, optional Plot will be timeseries[start: end].

None
end int

int, optional Plot will be timeseries[start: end].

None
ax Axes

plt.Axes, optional Axes to plot on. If None, a new figure is created. Default None

None
title str

str,optional Plot title.

''
figsize Tuple

tuple Figure size. Default (6, 2).

(6, 2)
legend bool

bool If True, legend is added ("target", "predicted").

True

Returns:

Type Description
ax

matplotlib Axes Returns the Axes object with the plot drawn onto it.

Source code in echoes/plotting/_core.py
def plot_predicted_ts(
    ts_true: Union[np.ndarray, List, pd.Series],
    ts_pred: Union[np.ndarray, List, pd.Series],
    start: int = None,
    end: int = None,
    ax: plt.Axes = None,
    title: str = "",
    figsize: Tuple = (6, 2),
    legend: bool = True,
) -> None:
    """
    Arguments:
        ts_true: np.ndarray, List, pd.Series
            Target time series.
        ts_pred: np.ndarray, List, pd.Series
            Predicted time series.
        start: int, optional
            Plot will be timeseries[start: end].
        end: int, optional
            Plot will be timeseries[start: end].
        ax: plt.Axes, optional
            Axes to plot on. If None, a new figure is created.
            Default None
        title: str,optional
            Plot title.
        figsize: tuple
            Figure size.
            Default (6, 2).
        legend: bool
            If True, legend is added ("target", "predicted").

    Returns:
        ax: matplotlib Axes
            Returns the Axes object with the plot drawn onto it.
    """
    if isinstance(ts_true, pd.Series):
        ts_true = ts_true.values
    if isinstance(ts_pred, pd.Series):
        ts_pred = ts_pred.values
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)

    ax.set_title(title)
    ax.plot(ts_true[start:end], color="steelblue", label="target", linewidth=5.5)
    ax.set_xlabel("time")

    ax.plot(
        ts_pred[start:end],
        linestyle="--",
        color="orange",
        linewidth=2,
        label="prediction",
    )
    ax.set_ylabel("output value")
    ax.set_xlabel("time")

    if legend:
        ax.legend()
    return ax

plot_reservoir_activity(esn, neurons, train=False, pred=True, start=None, end=None, figsize=(15, 9), **kwargs)

Plot the activity, ie time series of states, of the reservoir neurons.

Parameters:

Name Type Description Default
esn Union[echoes.esn._regressor.ESNRegressor, echoes.esn._generator.ESNGenerator]

ESNPredictive, ESNGenerative Instances of ESN after fitting and/or prediction.

required
neurons Union[numpy.ndarray, List]

np.ndarray or List List of reservoir neurons indices whose time series will be plotted.

required
train bool

bool, optional If True, the time series during training will be plotted. Either train or pred must be True, but only one of the two.

False
pred bool

bool, optional If True, the time series during prediction will be plotted. Either train or pred must be True, but only one of the two.

True
start int

int, optional Plot will be timeseries[start: end].

None
end int

int, optional Plot will be timeseries[start: end].

None
suptitle

str, optional Plot suptitle.

required
figsize Tuple

tuple Figure size. Default (15, 10).

(15, 9)
kwargs

dict Plotting kwargs passed to plt.plot

{}

Returns:

Type Description
fig

plt.figure Figure object for fine tuning.

Source code in echoes/plotting/_core.py
def plot_reservoir_activity(
    esn: Union[ESNRegressor, ESNGenerator],
    neurons: Union[np.ndarray, List],
    train: bool = False,
    pred: bool = True,
    start: int = None,
    end: int = None,
    figsize: Tuple = (15, 9),
    **kwargs,
):
    """
    Plot the activity, ie time series of states, of the reservoir
    neurons.

    Arguments:
        esn: ESNPredictive, ESNGenerative
            Instances of ESN after fitting and/or prediction.
        neurons: np.ndarray or List
            List of reservoir neurons indices whose time series will be plotted.
        train: bool, optional
            If True, the time series during training will be plotted.
            Either train or pred must be True, but only one of the two.
        pred: bool, optional
            If True, the time series during prediction will be plotted.
            Either train or pred must be True, but only one of the two.
        start: int, optional
            Plot will be timeseries[start: end].
        end: int, optional
            Plot will be timeseries[start: end].
        suptitle: str, optional
            Plot suptitle.
        figsize: tuple
            Figure size.
            Default (15, 10).
        kwargs: dict
            Plotting kwargs passed to plt.plot

    Returns:
        fig: plt.figure
            Figure object for fine tuning.
    """
    assert train or pred, "either train or pred must be True"
    assert not (train and pred), "only one of train or pred can be True"

    n_neurons = len(neurons)
    # Grab time series to plot
    ts = esn.states_pred_ if pred else esn.states_train_

    # Plot test
    fig, axes = plt.subplots(
        nrows=int(np.ceil(n_neurons / 3)), ncols=3, figsize=figsize
    )

    if "linewidth" in kwargs:
        linewidth = kwargs.pop("linewidht")
    else:
        linewidth = 3
    if "color" in kwargs:
        color = kwargs.pop("color")
    else:
        color = ".6"

    for neuron_idx, neuron in enumerate(neurons):
        ax = axes.flat[neuron_idx]
        ax.plot(ts[start:end, neuron], linewidth=linewidth, color=color, **kwargs)
        ax.set_ylabel("state")
        ax.set_xlabel("time")
        ax.set_title(f"reservoir neuron idx: {neuron}")

    # Delete unnecessary axes
    if n_neurons % 3 == 1:
        fig.delaxes(axes.flat[-1])
        fig.delaxes(axes.flat[-2])
    elif n_neurons % 3 == 2:
        fig.delaxes(axes.flat[-1])

    fig.tight_layout()
    return fig

set_mystyle()

Set context and a couple of defaults for nicer plots.

Source code in echoes/plotting/_core.py
def set_mystyle():
    """Set context and a couple of defaults for nicer plots."""
    sns.set(
        context="paper",
        style="whitegrid",
        font_scale=1.4,
        rc={"grid.linestyle": "--", "grid.linewidth": 0.8},
    )

Plotting functions related to the Memory Capacity task.

plot_forgetting_curve(lags, forgetting_curve, ax=None, **kwargs)

Plot forgetting curve, ie, memory capacity (MC) vs lag.

Parameters:

Name Type Description Default
lags Union[List, numpy.ndarray]

np.ndarray or List Sequence of lags used in the memory capacity task.

required
forgetting_curve ndarray

np.ndarray Sequence of results from the memory task.

required
ax Axes

plt.Axes, optional If given plot will use this axes.

None
kwargs

mapping, optional Plotting args passed to ax.plot.

{}
Source code in echoes/plotting/_memory_capacity.py
def plot_forgetting_curve(
    lags: Union[List, np.ndarray],
    forgetting_curve: np.ndarray,
    ax: plt.Axes = None,
    **kwargs,
) -> None:
    """
    Plot forgetting curve, ie, memory capacity (MC) vs lag.

    Arguments:
        lags: np.ndarray or List
            Sequence of lags used in the memory capacity task.
        forgetting_curve: np.ndarray
            Sequence of results from the memory task.
        ax: plt.Axes, optional
            If given plot will use this axes.
        kwargs: mapping, optional
            Plotting args passed to ax.plot.
    """
    if ax is None:
        fig, ax = plt.subplots()
    ax.plot(lags, forgetting_curve, **kwargs)
    ax.set_xlabel("$k$")
    ax.set_ylabel(r"$MC_k$")

plot_mc_predicted_ts(lags, outputs_true, outputs_pred, start=None, end=None)

Plot true and predicted time series coming from memory capacity task for all lags.

Parameters:

Name Type Description Default
lags Union[List, numpy.ndarray]

np.ndarray or List Delays to be evaluated (memory capacity). For example: np.arange(1, 31, 5).

required
ouputs_true

np.ndarray of shape (len(ts), len(n_lags)) Target time series used for testing the model.

required
ouputs_pred

np.ndarray of shape (len(ts), len(n_lags)) Predicted time series resulting from testing the model.

required
start/end

int, optional Plot will we timeseries[start: end], to exclude transient.

required
Source code in echoes/plotting/_memory_capacity.py
def plot_mc_predicted_ts(
    lags: Union[List, np.ndarray],
    outputs_true: np.ndarray,
    outputs_pred: np.ndarray,
    start: int = None,
    end: int = None,
) -> None:
    """
    Plot true and predicted time series coming from memory capacity
    task for all lags.

    Arguments:
        lags: np.ndarray or List
            Delays to be evaluated (memory capacity).
            For example: np.arange(1, 31, 5).
        ouputs_true: np.ndarray of shape (len(ts), len(n_lags))
            Target time series used for testing the model.
        ouputs_pred: np.ndarray of shape (len(ts), len(n_lags))
            Predicted time series resulting from testing the model.
        start/end: int, optional
            Plot will we timeseries[start: end], to exclude transient.
    """
    assert (
        outputs_true.shape == outputs_pred.shape
    ), "true and pred outputs must have same shape"
    assert (
        len(lags) == outputs_true.shape[1]
    ), "second dimension of outputs must equal len(lags)"

    n_lags = len(lags)

    # Plot test
    fig, axes = plt.subplots(
        nrows=int(np.ceil(n_lags / 2)), ncols=2, figsize=(18, 2.0 * n_lags)
    )
    for lag_idx, lag in enumerate(lags):
        ax = axes.flat[lag_idx]

        plot_predicted_ts(
            outputs_true[:, lag_idx],
            outputs_pred[:, lag_idx],
            start=start,
            end=end,
            title=f"lag = {lag}",
            ax=ax,
            legend=False,
        )

    handles, labels = ax.get_legend_handles_labels()
    fig.legend(
        handles,
        labels,
        loc="upper center",
        fontsize=20,
        ncol=2,
        fancybox=True,
        shadow=True,
    )
    if n_lags % 2 != 0:
        fig.delaxes(axes.flat[-1])
    fig.tight_layout()