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 ndarray | list | Series

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

required
ts_pred ndarray | list | Series

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

required
start int | None

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

None
end int | None

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

None
ax Axes | None

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:

Name Type Description
ax

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

Source code in echoes/plotting/_core.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def plot_predicted_ts(
    ts_true: np.ndarray | list | pd.Series,
    ts_pred: np.ndarray | list | pd.Series,
    start: int | None = None,
    end: int | None = None,
    ax: plt.Axes | None = None,
    title: str = "",
    figsize: tuple = (6, 2),
    legend: bool = True,
):
    """
    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 ESNRegressor | ESNGenerator

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

required
neurons 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 | None

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

None
end int | None

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:

Name Type Description
fig

plt.figure Figure object for fine tuning.

Source code in echoes/plotting/_core.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def plot_reservoir_activity(
    esn: ESNRegressor | ESNGenerator,
    neurons: np.ndarray | list,
    train: bool = False,
    pred: bool = True,
    start: int | None = None,
    end: int | None = 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
16
17
18
19
20
21
22
23
def set_mystyle():
    """Set context and a couple of defaults for nicer plots."""
    sns.set_theme(
        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 list | 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
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def plot_forgetting_curve(
    lags: 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 list | 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def plot_mc_predicted_ts(
    lags: list | np.ndarray,
    outputs_true: np.ndarray,
    outputs_pred: np.ndarray,
    start: int | None = None,
    end: int | None = 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()