Skip to content

Reference

Metrics

Forecast-quality and dynamical metrics for reservoir models, with first-class support for reporting horizons in Lyapunov times — the natural clock of a chaotic attractor — rather than raw integration steps. A valid-prediction time in Lyapunov times (\(\text{VPT}_{\Lambda t} = \text{steps} \cdot dt \cdot \lambda_\mathrm{max}\)) expresses a physical horizon relative to the system's instability rate. Comparisons still require matching error definitions, thresholds, normalization, forecast origins and censoring conventions. Supply the actual sampling interval and a suitable exponent when changing system parameters; canonical table values are reference values for their stated systems.

The conversions, the canonical \(\lambda_\mathrm{max}\) tables, valid_prediction_time, and reservoir_lyapunov are pure PyTorch/NumPy and always available. The series- and System-based paths of largest_lyapunov need the optional resdag[dynamics] extra (tsdynamics, Python ≥ 3.12) — see Work · Lyapunov time for the prose walkthrough.

Forecast accuracy

valid_prediction_time counts the contiguous prefix strictly below its threshold. Its NRMSE scales come from the supplied truth tensor, and per-step batch errors are reduced with the median. The common tuning workflow instead uses fixed training scales; record that distinction when comparing results. rmse, nrmse and r2 return aggregate scalar errors rather than a valid prefix.

valid_prediction_time

valid_prediction_time(
    pred: Tensor,
    truth: Tensor,
    *,
    threshold: float = 0.3,
    metric: str = "nrmse",
    units: str = "steps",
    dt: float | None = None,
    lambda_max: float | None = None,
    dataset: str | None = None,
    **kw: float
) -> float

Valid Prediction Time: contiguous steps a forecast stays accurate.

Per-step error is the NRMSE — the RMSE across feature channels, each channel normalised by the per-dimension standard deviation of truth over the (batch, time) axes — reduced across the batch with the median. The VPT is the number of steps, counting from the start, whose error stays strictly below threshold (0 if the very first step is already over).

This matches resdag.hpo.losses.forecast_horizon exactly (that copy is kept out of the optional-HPO import path); see the module docstring.

PARAMETER DESCRIPTION
pred

Forecast and ground truth of shape (batch, time, dim).

TYPE: Tensor

truth

Forecast and ground truth of shape (batch, time, dim).

TYPE: Tensor

threshold

NRMSE threshold below which a step counts as "valid".

TYPE: float DEFAULT: 0.3

metric

Per-step error metric. Only NRMSE is implemented (the reservoir-computing standard); the argument exists for forward compatibility.

TYPE: 'nrmse' DEFAULT: "nrmse"

units

Return the horizon in raw steps, or converted to Lyapunov times (steps * dt * lambda_max). "lyapunov" needs dt and lambda_max, or a known dataset name to infer them.

TYPE: ('steps', 'lyapunov') DEFAULT: "steps"

dt

Integration step, required for units="lyapunov" unless inferable from dataset.

TYPE: float DEFAULT: None

lambda_max

Largest Lyapunov exponent, required for units="lyapunov" unless inferable from a chaotic dataset.

TYPE: float DEFAULT: None

dataset

A built-in generator name ("lorenz", "rossler", "mackey_glass", ...) used to look up dt / lambda_max when they are not given explicitly.

TYPE: str DEFAULT: None

**kw

Extra keys forwarded to inference; tau= selects the Mackey-Glass exponent.

TYPE: float DEFAULT: {}

RETURNS DESCRIPTION
float

The VPT: an integer step count as a float when units="steps", or the horizon in Lyapunov times when units="lyapunov".

RAISES DESCRIPTION
ValueError

If metric is not "nrmse", units is unknown, or units="lyapunov" cannot resolve dt / lambda_max.

Examples:

>>> import torch
>>> pred = torch.zeros(1, 100, 3)
>>> truth = torch.zeros(1, 100, 3)
>>> valid_prediction_time(pred, truth)  # identical -> full horizon
100.0
Source code in src/resdag/metrics/forecast.py
 83
 84
 85
 86
 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def valid_prediction_time(
    pred: torch.Tensor,
    truth: torch.Tensor,
    *,
    threshold: float = 0.3,
    metric: str = "nrmse",
    units: str = "steps",
    dt: float | None = None,
    lambda_max: float | None = None,
    dataset: str | None = None,
    **kw: float,
) -> float:
    """Valid Prediction Time: contiguous steps a forecast stays accurate.

    Per-step error is the **NRMSE** — the RMSE across feature channels, each
    channel normalised by the per-dimension standard deviation of `truth` over
    the `(batch, time)` axes — reduced across the batch with the **median**.
    The VPT is the number of steps, counting from the start, whose error stays
    strictly below `threshold` (`0` if the very first step is already over).

    This matches `resdag.hpo.losses.forecast_horizon` exactly (that copy
    is kept out of the optional-HPO import path); see the module docstring.

    Parameters
    ----------
    pred, truth : torch.Tensor
        Forecast and ground truth of shape `(batch, time, dim)`.
    threshold : float, default=0.3
        NRMSE threshold below which a step counts as "valid".
    metric : {"nrmse"}, default="nrmse"
        Per-step error metric.  Only NRMSE is implemented (the reservoir-computing
        standard); the argument exists for forward compatibility.
    units : {"steps", "lyapunov"}, default="steps"
        Return the horizon in raw steps, or converted to Lyapunov times
        (`steps * dt * lambda_max`).  `"lyapunov"` needs `dt` and
        `lambda_max`, or a known `dataset` name to infer them.
    dt : float, optional
        Integration step, required for `units="lyapunov"` unless inferable
        from `dataset`.
    lambda_max : float, optional
        Largest Lyapunov exponent, required for `units="lyapunov"` unless
        inferable from a chaotic `dataset`.
    dataset : str, optional
        A built-in generator name (`"lorenz"`, `"rossler"`,
        `"mackey_glass"`, ...) used to look up `dt` / `lambda_max` when
        they are not given explicitly.
    **kw
        Extra keys forwarded to inference; `tau=` selects the Mackey-Glass
        exponent.

    Returns
    -------
    float
        The VPT: an integer step count as a `float` when `units="steps"`, or
        the horizon in Lyapunov times when `units="lyapunov"`.

    Raises
    ------
    ValueError
        If `metric` is not `"nrmse"`, `units` is unknown, or
        `units="lyapunov"` cannot resolve `dt` / `lambda_max`.

    Examples
    --------
    >>> import torch
    >>> pred = torch.zeros(1, 100, 3)
    >>> truth = torch.zeros(1, 100, 3)
    >>> valid_prediction_time(pred, truth)  # identical -> full horizon
    100.0
    """
    if metric != "nrmse":
        raise ValueError(f"Unknown metric {metric!r}; only 'nrmse' is implemented.")
    if units not in ("steps", "lyapunov"):
        raise ValueError(f"Unknown units {units!r}; expected 'steps' or 'lyapunov'.")

    p = pred.detach().cpu().double().numpy()
    t = truth.detach().cpu().double().numpy()
    # Compare over the overlapping prefix if the two differ in length.
    n = min(p.shape[1], t.shape[1])
    p, t = p[:, :n], t[:, :n]

    scale = t.std(axis=(0, 1), keepdims=True)
    scale = np.where(scale == 0.0, 1.0, scale)
    err = np.sqrt((((p - t) / scale) ** 2).mean(axis=2))  # (batch, time)
    e_t = np.median(err, axis=0)  # (time,)

    below = e_t < threshold
    if below.size == 0 or not below[0]:
        steps = 0
    elif (~below).any():
        steps = int(np.argmax(~below))
    else:
        steps = int(below.size)

    if units == "steps":
        return float(steps)

    dt_r, lam_r = _infer_dt_lambda(dataset, dt, lambda_max, **kw)
    return steps_to_lyapunov(steps, dt_r, lam_r)

rmse

rmse(pred: Tensor, truth: Tensor) -> float

Root-mean-square error between a forecast and the truth.

The RMSE is taken over all elements (batch, time, and feature axes), in the raw units of the data. For a scale-free, threshold-comparable error use nrmse instead.

PARAMETER DESCRIPTION
pred

Forecast and ground truth of shape (batch, time, dim). If the two differ in length along the time axis, they are compared over the overlapping prefix (as in valid_prediction_time).

TYPE: Tensor

truth

Forecast and ground truth of shape (batch, time, dim). If the two differ in length along the time axis, they are compared over the overlapping prefix (as in valid_prediction_time).

TYPE: Tensor

RETURNS DESCRIPTION
float

\(\sqrt{\operatorname{mean}((\hat y - y)^2)}\) over every element.

Examples:

>>> import torch
>>> x = torch.zeros(1, 10, 3)
>>> rmse(x, x)
0.0
Source code in src/resdag/metrics/observables.py
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
def rmse(pred: torch.Tensor, truth: torch.Tensor) -> float:
    """Root-mean-square error between a forecast and the truth.

    The RMSE is taken over **all** elements (batch, time, and feature axes),
    in the raw units of the data.  For a scale-free, threshold-comparable
    error use `nrmse` instead.

    Parameters
    ----------
    pred, truth : torch.Tensor
        Forecast and ground truth of shape `(batch, time, dim)`.  If the two
        differ in length along the time axis, they are compared over the
        overlapping prefix (as in `valid_prediction_time`).

    Returns
    -------
    float
        $\\sqrt{\\operatorname{mean}((\\hat y - y)^2)}$ over every element.

    Examples
    --------
    >>> import torch
    >>> x = torch.zeros(1, 10, 3)
    >>> rmse(x, x)
    0.0
    """
    p, t = _as_2d_pair(pred, truth)
    return float(np.sqrt(np.mean((p - t) ** 2)))

nrmse

nrmse(pred: Tensor, truth: Tensor, *, normalization: str = 'std') -> float

Normalised RMSE — scale-free forecast error.

The RMSE is normalised so the metric is invariant to the absolute scale of the data, which is what makes a fixed error threshold (the basis of valid_prediction_time) meaningful across systems. Two conventions:

  • normalization="std" (default) — per-feature RMSE, each channel divided by the per-dimension standard deviation of truth over the (batch, time) axes, then combined across channels. This is exactly the per-step NRMSE that valid_prediction_time thresholds (reduced here over the whole trajectory rather than per step), so the two never disagree.
  • normalization="range" — the scalar RMSE over all elements divided by the peak-to-peak range (max - min) of truth.
PARAMETER DESCRIPTION
pred

Forecast and ground truth of shape (batch, time, dim), compared over their overlapping time prefix.

TYPE: Tensor

truth

Forecast and ground truth of shape (batch, time, dim), compared over their overlapping time prefix.

TYPE: Tensor

normalization

Whether to normalise by the per-dimension standard deviation of the truth (the reservoir-computing standard, matching valid_prediction_time) or by its global peak-to-peak range.

TYPE: ('std', 'range') DEFAULT: "std"

RETURNS DESCRIPTION
float

The normalised RMSE (0 for a perfect forecast). A value of 1 under "std" normalisation corresponds to the error of predicting the per-channel mean.

RAISES DESCRIPTION
ValueError

If normalization is not "std" or "range".

Examples:

>>> import torch
>>> truth = torch.randn(1, 200, 3)
>>> nrmse(truth, truth)  # identical
0.0
Source code in src/resdag/metrics/observables.py
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def nrmse(
    pred: torch.Tensor,
    truth: torch.Tensor,
    *,
    normalization: str = "std",
) -> float:
    """Normalised RMSE — scale-free forecast error.

    The RMSE is normalised so the metric is invariant to the absolute scale of
    the data, which is what makes a fixed error *threshold* (the basis of
    `valid_prediction_time`) meaningful across systems.  Two conventions:

    - `normalization="std"` (default) — per-feature RMSE, each channel
      divided by the **per-dimension standard deviation** of `truth` over the
      `(batch, time)` axes, then combined across channels.  This is *exactly*
      the per-step NRMSE that `valid_prediction_time` thresholds (reduced
      here over the whole trajectory rather than per step), so the two never
      disagree.
    - `normalization="range"` — the scalar RMSE over all elements divided by
      the peak-to-peak range (`max - min`) of `truth`.

    Parameters
    ----------
    pred, truth : torch.Tensor
        Forecast and ground truth of shape `(batch, time, dim)`, compared over
        their overlapping time prefix.
    normalization : {"std", "range"}, default="std"
        Whether to normalise by the per-dimension standard deviation of the
        truth (the reservoir-computing standard, matching
        `valid_prediction_time`) or by its global peak-to-peak range.

    Returns
    -------
    float
        The normalised RMSE (`0` for a perfect forecast).  A value of `1`
        under `"std"` normalisation corresponds to the error of predicting the
        per-channel mean.

    Raises
    ------
    ValueError
        If `normalization` is not `"std"` or `"range"`.

    Examples
    --------
    >>> import torch
    >>> truth = torch.randn(1, 200, 3)
    >>> nrmse(truth, truth)  # identical
    0.0
    """
    if normalization not in ("std", "range"):
        raise ValueError(f"Unknown normalization {normalization!r}; expected 'std' or 'range'.")
    p, t = _as_2d_pair(pred, truth)
    if normalization == "std":
        scale = t.std(axis=(0, 1), keepdims=True)
        scale = np.where(scale == 0.0, 1.0, scale)
        # Per-step RMSE across channels of the standardised residual, then a
        # single RMS reduction across (batch, time) — the trajectory-level
        # counterpart of valid_prediction_time's per-step error.
        err = np.sqrt((((p - t) / scale) ** 2).mean(axis=2))  # (batch, time)
        return float(np.sqrt((err**2).mean()))
    # normalization == "range"
    span = float(t.max() - t.min())
    if span == 0.0:
        span = 1.0
    return float(np.sqrt(np.mean((p - t) ** 2)) / span)

r2

r2(pred: Tensor, truth: Tensor) -> float

Coefficient of determination \(R^2\) of a forecast.

The standard variance-explained score, pooled over all elements:

\[ R^2 = 1 - \frac{\sum (\hat y - y)^2}{\sum (y - \bar y)^2}, \]

where \(\bar y\) is the grand mean of truth. 1.0 is a perfect forecast; 0.0 matches the skill of predicting the mean; negative values are worse than the mean.

PARAMETER DESCRIPTION
pred

Forecast and ground truth of shape (batch, time, dim), compared over their overlapping time prefix.

TYPE: Tensor

truth

Forecast and ground truth of shape (batch, time, dim), compared over their overlapping time prefix.

TYPE: Tensor

RETURNS DESCRIPTION
float

The \(R^2\) score. Returns 1.0 when truth is constant and the forecast matches it exactly (zero residual and zero total variance), else 0.0 for a constant truth with any residual.

Examples:

>>> import torch
>>> truth = torch.randn(1, 200, 3)
>>> r2(truth, truth)
1.0
Source code in src/resdag/metrics/observables.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def r2(pred: torch.Tensor, truth: torch.Tensor) -> float:
    """Coefficient of determination $R^2$ of a forecast.

    The standard variance-explained score, pooled over all elements:

    $$
    R^2 = 1 - \\frac{\\sum (\\hat y - y)^2}{\\sum (y - \\bar y)^2},
    $$

    where $\\bar y$ is the grand mean of `truth`.  `1.0` is a perfect
    forecast; `0.0` matches the skill of predicting the mean; negative values
    are worse than the mean.

    Parameters
    ----------
    pred, truth : torch.Tensor
        Forecast and ground truth of shape `(batch, time, dim)`, compared over
        their overlapping time prefix.

    Returns
    -------
    float
        The $R^2$ score.  Returns `1.0` when `truth` is constant and
        the forecast matches it exactly (zero residual and zero total variance),
        else `0.0` for a constant truth with any residual.

    Examples
    --------
    >>> import torch
    >>> truth = torch.randn(1, 200, 3)
    >>> r2(truth, truth)
    1.0
    """
    p, t = _as_2d_pair(pred, truth)
    ss_res = float(np.sum((p - t) ** 2))
    ss_tot = float(np.sum((t - t.mean()) ** 2))
    if ss_tot == 0.0:
        # Constant truth: R^2 is conventionally 1 for a perfect fit, else 0.
        return 1.0 if ss_res == 0.0 else 0.0
    return 1.0 - ss_res / ss_tot

Lyapunov-time conversions

lyapunov_time

lyapunov_time(lambda_max: float) -> float

Return the Lyapunov time \(t_\lambda = 1 / \lambda_\mathrm{max}\).

One Lyapunov time is the characteristic timescale over which infinitesimally close trajectories of a chaotic system separate by a factor of \(e\).

PARAMETER DESCRIPTION
lambda_max

Largest Lyapunov exponent (must be strictly positive for a chaotic system).

TYPE: float

RETURNS DESCRIPTION
float

The Lyapunov time \(1 / \lambda_\mathrm{max}\), in the same time units as lambda_max is inverse to.

RAISES DESCRIPTION
ValueError

If lambda_max is not strictly positive.

Source code in src/resdag/metrics/lyapunov.py
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
def lyapunov_time(lambda_max: float) -> float:
    """Return the Lyapunov time $t_\\lambda = 1 / \\lambda_\\mathrm{max}$.

    One Lyapunov time is the characteristic timescale over which infinitesimally
    close trajectories of a chaotic system separate by a factor of $e$.

    Parameters
    ----------
    lambda_max : float
        Largest Lyapunov exponent (must be strictly positive for a chaotic
        system).

    Returns
    -------
    float
        The Lyapunov time $1 / \\lambda_\\mathrm{max}$, in the same time
        units as `lambda_max` is inverse to.

    Raises
    ------
    ValueError
        If `lambda_max` is not strictly positive.
    """
    if lambda_max <= 0.0:
        raise ValueError(f"lambda_max must be positive to define a Lyapunov time, got {lambda_max}")
    return 1.0 / lambda_max

steps_per_lyapunov_time

steps_per_lyapunov_time(dt: float, lambda_max: float) -> float

Return the number of integration steps in one Lyapunov time.

A convenience for turning a horizon-in-steps into a horizon-in-Lyapunov-times (divide the step count by this) and vice versa.

PARAMETER DESCRIPTION
dt

Integration step (time between consecutive samples).

TYPE: float

lambda_max

Largest Lyapunov exponent (strictly positive).

TYPE: float

RETURNS DESCRIPTION
float

1 / (dt * lambda_max) — the number of samples spanning one Lyapunov time \(t_\lambda\).

RAISES DESCRIPTION
ValueError

If dt or lambda_max is not strictly positive.

Source code in src/resdag/metrics/lyapunov.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def steps_per_lyapunov_time(dt: float, lambda_max: float) -> float:
    """Return the number of integration steps in one Lyapunov time.

    A convenience for turning a horizon-in-steps into a horizon-in-Lyapunov-times
    (divide the step count by this) and vice versa.

    Parameters
    ----------
    dt : float
        Integration step (time between consecutive samples).
    lambda_max : float
        Largest Lyapunov exponent (strictly positive).

    Returns
    -------
    float
        `1 / (dt * lambda_max)` — the number of samples spanning one Lyapunov
        time $t_\\lambda$.

    Raises
    ------
    ValueError
        If `dt` or `lambda_max` is not strictly positive.
    """
    if dt <= 0.0:
        raise ValueError(f"dt must be positive, got {dt}")
    if lambda_max <= 0.0:
        raise ValueError(f"lambda_max must be positive, got {lambda_max}")
    return 1.0 / (dt * lambda_max)

steps_to_lyapunov

steps_to_lyapunov(steps: float, dt: float, lambda_max: float) -> float

Convert a step count to Lyapunov times \(\Lambda t\).

This is the headline conversion: VPT_in_Lyapunov = steps * dt * lambda_max.

PARAMETER DESCRIPTION
steps

Number of integration steps (e.g. a valid-prediction time).

TYPE: float

dt

Integration step.

TYPE: float

lambda_max

Largest Lyapunov exponent (strictly positive).

TYPE: float

RETURNS DESCRIPTION
float

The horizon expressed in Lyapunov times, steps * dt * lambda_max.

RAISES DESCRIPTION
ValueError

If dt or lambda_max is not strictly positive.

Examples:

A Lorenz-63 valid-prediction time of 357 steps at dt = 0.02:

>>> round(steps_to_lyapunov(357, dt=0.02, lambda_max=0.9056), 2)
6.47
Source code in src/resdag/metrics/lyapunov.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def steps_to_lyapunov(steps: float, dt: float, lambda_max: float) -> float:
    """Convert a step count to Lyapunov times $\\Lambda t$.

    This is the headline conversion: `VPT_in_Lyapunov = steps * dt * lambda_max`.

    Parameters
    ----------
    steps : float
        Number of integration steps (e.g. a valid-prediction time).
    dt : float
        Integration step.
    lambda_max : float
        Largest Lyapunov exponent (strictly positive).

    Returns
    -------
    float
        The horizon expressed in Lyapunov times, `steps * dt * lambda_max`.

    Raises
    ------
    ValueError
        If `dt` or `lambda_max` is not strictly positive.

    Examples
    --------
    A Lorenz-63 valid-prediction time of 357 steps at `dt = 0.02`:

    >>> round(steps_to_lyapunov(357, dt=0.02, lambda_max=0.9056), 2)
    6.47
    """
    if dt <= 0.0:
        raise ValueError(f"dt must be positive, got {dt}")
    if lambda_max <= 0.0:
        raise ValueError(f"lambda_max must be positive, got {lambda_max}")
    return steps * dt * lambda_max

lyapunov_to_steps

lyapunov_to_steps(lyap: float, dt: float, lambda_max: float) -> int

Convert a horizon in Lyapunov times back to a whole number of steps.

The inverse of steps_to_lyapunov, rounded to the nearest integer step (horizons are discrete step counts).

PARAMETER DESCRIPTION
lyap

Horizon in Lyapunov times \(\Lambda t\).

TYPE: float

dt

Integration step.

TYPE: float

lambda_max

Largest Lyapunov exponent (strictly positive).

TYPE: float

RETURNS DESCRIPTION
int

round(lyap / (dt * lambda_max)) — the equivalent step count.

RAISES DESCRIPTION
ValueError

If dt or lambda_max is not strictly positive.

Source code in src/resdag/metrics/lyapunov.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def lyapunov_to_steps(lyap: float, dt: float, lambda_max: float) -> int:
    """Convert a horizon in Lyapunov times back to a whole number of steps.

    The inverse of `steps_to_lyapunov`, rounded to the nearest integer
    step (horizons are discrete step counts).

    Parameters
    ----------
    lyap : float
        Horizon in Lyapunov times $\\Lambda t$.
    dt : float
        Integration step.
    lambda_max : float
        Largest Lyapunov exponent (strictly positive).

    Returns
    -------
    int
        `round(lyap / (dt * lambda_max))` — the equivalent step count.

    Raises
    ------
    ValueError
        If `dt` or `lambda_max` is not strictly positive.
    """
    if dt <= 0.0:
        raise ValueError(f"dt must be positive, got {dt}")
    if lambda_max <= 0.0:
        raise ValueError(f"lambda_max must be positive, got {lambda_max}")
    return int(round(lyap / (dt * lambda_max)))

Canonical exponents

CANONICAL_LAMBDA_MAX module-attribute

CANONICAL_LAMBDA_MAX: dict[str, float] = {
    "lorenz": 0.9056,
    "rossler": 0.0714,
    "kuramoto_sivashinsky": 0.043,
}

MACKEY_GLASS_LAMBDA module-attribute

MACKEY_GLASS_LAMBDA: dict[int, float] = {17: 0.0086, 23: 0.0097, 30: 0.0071}

Estimators

largest_lyapunov

largest_lyapunov(
    source: Any, *, dt: float | None = None, from_: str | None = None, **kw: Any
) -> float

Estimate the largest Lyapunov exponent of source.

A single entry point that dispatches on the type of source:

  • generator name (str, e.g. "lorenz", "mackey_glass") — returns the canonical literature value from CANONICAL_LAMBDA_MAX / MACKEY_GLASS_LAMBDA (keyed by tau= for Mackey-Glass). No dependency.
  • time series (numpy.ndarray / torch.Tensor) — a diagnostic estimate via tsdynamics.lyapunov_from_data. Data-driven exponents are noisy; you must opt in with from_="data" so a series is never silently mistaken for accurate. Needs resdag[dynamics].
  • tsdynamics System — a high-accuracy Benettin estimate via tsdynamics.lyapunov_spectrum. Needs resdag[dynamics].
PARAMETER DESCRIPTION
source

What to estimate the exponent of; see above.

TYPE: str, numpy.ndarray, torch.Tensor, or tsdynamics System

dt

Integration step. Required for the series path; forwarded to the System path if given. Ignored for a generator name.

TYPE: float DEFAULT: None

from_

Set to "data" to force the noisy data-driven estimate for an array source. Without it, passing a raw array raises to prevent silently trusting a diagnostic number.

TYPE: str or None DEFAULT: None

**kw

Extra arguments: tau= selects the Mackey-Glass canonical value; otherwise forwarded to the underlying tsdynamics estimator (e.g. method=, fit= for data; final_time=, transient= for a System).

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
float

The estimated largest Lyapunov exponent (inverse natural-time units).

RAISES DESCRIPTION
ImportError

If a tsdynamics path is taken but the package is not installed.

TypeError

If an array is passed without from_="data".

KeyError

If a generator name has no canonical value.

Examples:

>>> largest_lyapunov("lorenz")
0.9056
>>> largest_lyapunov("mackey_glass", tau=17)
0.0086
Source code in src/resdag/metrics/lyapunov.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
def largest_lyapunov(
    source: Any,
    *,
    dt: float | None = None,
    from_: str | None = None,
    **kw: Any,
) -> float:
    """Estimate the largest Lyapunov exponent of `source`.

    A single entry point that dispatches on the type of `source`:

    * **generator name** (`str`, e.g. `"lorenz"`, `"mackey_glass"`) —
      returns the canonical literature value from `CANONICAL_LAMBDA_MAX`
      / `MACKEY_GLASS_LAMBDA` (keyed by `tau=` for Mackey-Glass).
      **No dependency.**
    * **time series** (`numpy.ndarray` / `torch.Tensor`) — a
      *diagnostic* estimate via `tsdynamics.lyapunov_from_data`.  Data-driven
      exponents are noisy; you must opt in with `from_="data"` so a series is
      never silently mistaken for accurate.  **Needs** `resdag[dynamics]`.
    * **tsdynamics System** — a high-accuracy Benettin estimate via
      `tsdynamics.lyapunov_spectrum`.  **Needs** `resdag[dynamics]`.

    Parameters
    ----------
    source : str, numpy.ndarray, torch.Tensor, or tsdynamics System
        What to estimate the exponent of; see above.
    dt : float, optional
        Integration step.  Required for the series path; forwarded to the
        System path if given.  Ignored for a generator name.
    from_ : str or None, optional
        Set to `"data"` to force the noisy data-driven estimate for an array
        source.  Without it, passing a raw array raises to prevent silently
        trusting a diagnostic number.
    **kw
        Extra arguments: `tau=` selects the Mackey-Glass canonical value;
        otherwise forwarded to the underlying `tsdynamics` estimator (e.g.
        `method=`, `fit=` for data; `final_time=`, `transient=` for a
        System).

    Returns
    -------
    float
        The estimated largest Lyapunov exponent (inverse natural-time units).

    Raises
    ------
    ImportError
        If a `tsdynamics` path is taken but the package is not installed.
    TypeError
        If an array is passed without `from_="data"`.
    KeyError
        If a generator name has no canonical value.

    Examples
    --------
    >>> largest_lyapunov("lorenz")
    0.9056
    >>> largest_lyapunov("mackey_glass", tau=17)
    0.0086
    """
    if isinstance(source, str):
        return _lambda_from_name(source, **kw)

    if isinstance(source, torch.Tensor):
        source = source.detach().cpu().numpy()

    if isinstance(source, np.ndarray):
        if from_ != "data":
            raise TypeError(
                "Estimating a Lyapunov exponent from a raw data series is a noisy "
                "diagnostic; pass from_='data' (and dt=...) to opt in explicitly, "
                "or use a generator name / tsdynamics System for an accurate value."
            )
        if dt is None:
            raise ValueError("dt is required to estimate a Lyapunov exponent from data.")
        return _lambda_from_series(source, dt=dt, **kw)

    # Anything else is assumed to be a tsdynamics System (dispatched lazily so we
    # never import tsdynamics just to check the type).
    return _lambda_from_system(source, dt=dt, **kw)

reservoir_lyapunov

reservoir_lyapunov(
    source: Any,
    warmup_inputs: Tensor | tuple[Tensor, ...],
    *,
    horizon: int = 1000,
    k: int = 1,
    transient: int = 100,
    seed: int | None = 0
) -> float | ndarray

Largest (or top-k) Lyapunov exponent of a driven ESN reservoir.

Estimates the maximal Lyapunov exponent of the reservoir's own dynamics via Benettin's algorithm with QR reorthonormalisation of the analytic tangent map, iterated along an input-driven reservoir trajectory. This is a sampled local-stability diagnostic. Negative estimates support contraction along the supplied driven trajectory; they do not prove a global Echo State Property for every input. This is distinct from the forecasted attractor's largest Lyapunov exponent.

A local CPU float64 evaluation copy preserves caller weights, device, cached state and training mode. Training-only noise is disabled. The validated tangent map supports the standard tanh ESNCell, including per-neuron leaks, recurrent calibration gains and intrinsic gains/biases. Other update equations are rejected until their tangent maps are validated.

The reservoir map is the leaky-ESN update

\[ h_t = (1-\alpha) h_{t-1} + \alpha\, f(W_\mathrm{fb} x_t + W_\mathrm{in} u_t + W_\mathrm{hh} h_{t-1} + b), \]

whose Jacobian with respect to the state is

\[ J_t = (1-\alpha) I + \alpha\, \mathrm{diag}\!\big(f'(\mathrm{pre}_t)\big)\, W_\mathrm{hh}, \]

with \(f' = 1 - \tanh^2\) and calibrated gains included in \(W_\mathrm{hh}\). Scalar leakage generalizes row-wise for vector leaks. The driving inputs come from warmup_inputs; the trajectory is looped over them if horizon exceeds their length, so a short synchronisation window still yields a long tangent-space average.

PARAMETER DESCRIPTION
source

The reservoir to analyse, or a model containing exactly one ESN reservoir.

TYPE: BaseReservoirLayer or ESNModel

warmup_inputs

Driving inputs of shape (batch, time, features). A bare tensor is the feedback stream; a tuple is (feedback, driver, ...). Only the first sample of the batch is used (the exponent is a property of the dynamics, not the batch).

TYPE: torch.Tensor or tuple of torch.Tensor

horizon

Number of tangent-map iterations (after the transient). Longer gives a tighter estimate.

TYPE: int DEFAULT: 1000

k

Number of leading exponents to return. k=1 returns the scalar maximal exponent; k>1 returns the top-k as a (k,) array.

TYPE: int DEFAULT: 1

transient

Additional tangent iterations discarded before the horizon scoring iterations. Must be non-negative; it is not subtracted from the horizon.

TYPE: int DEFAULT: 100

seed

Seed for the random initial tangent frame. Defaults to 0 so the estimate is fully deterministic (the converged leading exponent is robust to the frame regardless). Pass None to draw from the process-global RNG instead.

TYPE: int or None DEFAULT: 0

RETURNS DESCRIPTION
float or ndarray

The maximal Lyapunov exponent (k=1) or the top-k spectrum as a (k,) array, in inverse-step units (per reservoir update).

RAISES DESCRIPTION
ValueError

If source has no (or more than one) ESN reservoir, or k exceeds the reservoir size.

NotImplementedError

If the cell is not a standard tanh ESNCell.

Notes

Exponents are per reservoir step. Multiply by 1/dt to compare with a natural-time attractor exponent from CANONICAL_LAMBDA_MAX.

Examples:

>>> import torch
>>> from resdag.layers import ESNLayer
>>> res = ESNLayer(100, feedback_size=3, spectral_radius=0.9, seed=0)
>>> feedback = torch.randn(1, 300, 3)
>>> lam = reservoir_lyapunov(res, feedback, horizon=500)
>>> lam < 0.0  # contraction along this driven trajectory
True
Source code in src/resdag/metrics/lyapunov.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
def reservoir_lyapunov(
    source: Any,
    warmup_inputs: torch.Tensor | tuple[torch.Tensor, ...],
    *,
    horizon: int = 1000,
    k: int = 1,
    transient: int = 100,
    seed: int | None = 0,
) -> float | np.ndarray:
    """Largest (or top-`k`) Lyapunov exponent of a driven ESN reservoir.

    Estimates the maximal Lyapunov exponent of the reservoir's own dynamics via
    **Benettin's algorithm with QR reorthonormalisation** of the analytic
    tangent map, iterated along an input-driven reservoir trajectory.  This is a
    sampled local-stability diagnostic. Negative estimates support contraction
    along the supplied driven trajectory; they do not prove a global Echo State
    Property for every input. This is distinct from the forecasted attractor's
    largest Lyapunov exponent.

    A local CPU float64 evaluation copy preserves caller weights, device,
    cached state and training mode. Training-only noise is disabled. The
    validated tangent map supports the standard tanh `ESNCell`, including
    per-neuron leaks, recurrent calibration gains and intrinsic gains/biases.
    Other update equations are rejected until their tangent maps are validated.

    The reservoir map is the leaky-ESN update

    $$
    h_t = (1-\\alpha) h_{t-1} + \\alpha\\, f(W_\\mathrm{fb} x_t
          + W_\\mathrm{in} u_t + W_\\mathrm{hh} h_{t-1} + b),
    $$

    whose Jacobian with respect to the state is

    $$
    J_t = (1-\\alpha) I + \\alpha\\, \\mathrm{diag}\\!\\big(f'(\\mathrm{pre}_t)\\big)\\, W_\\mathrm{hh},
    $$

    with $f' = 1 - \\tanh^2$ and calibrated gains included in
    $W_\\mathrm{hh}$. Scalar leakage generalizes row-wise for vector leaks.  The
    driving inputs come from `warmup_inputs`; the trajectory is looped over
    them if `horizon` exceeds their length, so a short synchronisation window
    still yields a long tangent-space average.

    Parameters
    ----------
    source : BaseReservoirLayer or ESNModel
        The reservoir to analyse, or a model containing exactly one ESN
        reservoir.
    warmup_inputs : torch.Tensor or tuple of torch.Tensor
        Driving inputs of shape `(batch, time, features)`.  A bare tensor is
        the feedback stream; a tuple is `(feedback, driver, ...)`.  Only the
        first sample of the batch is used (the exponent is a property of the
        dynamics, not the batch).
    horizon : int, default=1000
        Number of tangent-map iterations (after the transient).  Longer gives a
        tighter estimate.
    k : int, default=1
        Number of leading exponents to return.  `k=1` returns the scalar
        maximal exponent; `k>1` returns the top-`k` as a `(k,)` array.
    transient : int, default=100
        Additional tangent iterations discarded before the `horizon` scoring
        iterations. Must be non-negative; it is not subtracted from the horizon.
    seed : int or None, default=0
        Seed for the random initial tangent frame.  Defaults to `0` so the
        estimate is fully deterministic (the converged leading exponent is robust
        to the frame regardless).  Pass `None` to draw from the process-global
        RNG instead.

    Returns
    -------
    float or numpy.ndarray
        The maximal Lyapunov exponent (`k=1`) or the top-`k` spectrum as a
        `(k,)` array, in **inverse-step units** (per reservoir update).

    Raises
    ------
    ValueError
        If `source` has no (or more than one) ESN reservoir, or `k` exceeds
        the reservoir size.
    NotImplementedError
        If the cell is not a standard tanh `ESNCell`.

    Notes
    -----
    Exponents are per **reservoir step**.  Multiply by `1/dt` to compare with
    a natural-time attractor exponent from `CANONICAL_LAMBDA_MAX`.

    Examples
    --------
    >>> import torch
    >>> from resdag.layers import ESNLayer
    >>> res = ESNLayer(100, feedback_size=3, spectral_radius=0.9, seed=0)
    >>> feedback = torch.randn(1, 300, 3)
    >>> lam = reservoir_lyapunov(res, feedback, horizon=500)
    >>> lam < 0.0  # contraction along this driven trajectory
    True
    """
    from resdag.data.prepare import _validate_step_count

    horizon = _validate_step_count("horizon", horizon)
    transient = _validate_step_count("transient", transient, allow_zero=True)
    k = _validate_step_count("k", k)
    cell = _diagnostic_cell(source, tanh_esn=True)
    streams = [warmup_inputs] if isinstance(warmup_inputs, torch.Tensor) else list(warmup_inputs)
    if not streams or any(x.ndim != 3 or x.shape[0] < 1 or x.shape[1] < 1 for x in streams):
        raise ValueError("warmup_inputs must contain non-empty (batch, time, features) streams.")
    if any(x.shape[:2] != streams[0].shape[:2] for x in streams):
        raise ValueError("warmup input streams must have matching batch and time dimensions.")
    inputs = [x[:1].detach().cpu().to(dtype=torch.float64) for x in streams]
    if not all(bool(torch.isfinite(x).all()) for x in inputs):
        raise ValueError("warmup inputs must be finite.")
    _, state = _drive_cell(cell, inputs)
    n = int(cell.state_size)
    if k > n:
        raise ValueError(f"k must be in [1, reservoir_size={n}], got {k}.")
    weight = _esn_recurrent_jacobian_weight(cell)
    alpha = torch.as_tensor(cell.leak_rate, dtype=torch.float64)
    if alpha.ndim == 0:
        alpha = alpha.expand(n)
    projected = cell.project_inputs(inputs)
    generator = torch.Generator().manual_seed(int(seed)) if seed is not None else None
    frame = torch.linalg.qr(torch.randn(n, k, dtype=torch.float64, generator=generator))[0]
    log_sums = torch.zeros(k, dtype=torch.float64)
    identity = torch.eye(n, dtype=torch.float64)
    with torch.no_grad():
        for step in range(transient + horizon):
            t = step % inputs[0].shape[1]
            # Match the live cell's calibrated preactivation, then advance via
            # its actual implementation rather than a second update equation.
            pre = projected[:, t] + cell._recurrent(state)
            if cell._has_intrinsic:
                pre = cell._intrinsic_gain * pre + cell._intrinsic_bias
            gate = 1.0 - torch.tanh(pre).reshape(n).square()
            jacobian = alpha[:, None] * gate[:, None] * weight
            jacobian = jacobian + (1.0 - alpha)[:, None] * identity
            _, state = cell.step(projected[:, t], state)
            frame, triangular = torch.linalg.qr(jacobian @ frame)
            if step >= transient:
                growth = triangular.diagonal().abs().clamp_min(1e-300)
                log_sums += growth.log()
    exponents = (log_sums / horizon).numpy()
    return float(exponents[0]) if k == 1 else exponents

Reservoir and attractor observables

memory_capacity

memory_capacity(
    source: Any,
    *,
    max_delay: int = 100,
    n_samples: int = 2000,
    washout: int = 200,
    alpha: float = 1e-08,
    input_low: float = -1.0,
    input_high: float = 1.0,
    seed: int = 0,
    return_curve: bool = False,
    test_samples: int | None = None
) -> float | tuple[float, ndarray]

Linear short-term memory capacity of a reservoir (Jaeger 2001).

Drives the reservoir with a scalar i.i.d. uniform input \(u_t\) and, for each delay \(k = 1 \dots\) max_delay, fits a linear readout from the reservoir state \(h_t\) to the delayed input \(u_{t-k}\). The memory capacity is the sum of the squared correlations of the reconstruction

\[ MC = \sum_{k=1}^{k_{\max}} R^2_k, \qquad R^2_k = \frac{\operatorname{cov}(\hat u_{t-k},\, u_{t-k})^2} {\operatorname{var}(\hat u_{t-k})\,\operatorname{var}(u_{t-k})}, \]

the standard forgetting-curve integral (Jaeger, Short-term memory in echo state networks, 2001). Readouts are fitted on one random input trajectory and scored on an independently generated, independently warmed trajectory. No evaluation samples enter fitting or centering statistics.

The theoretical population capacity is at most the number of reservoir states, under the usual independent-input assumptions. This finite-sample estimator may exceed that bound through sampling noise, particularly for many delays and few test samples. It is not guaranteed to increase with spectral radius. Increase test_samples and repeat seeds to assess uncertainty; this diagnostic is not an autonomous forecast score.

The actual cell update runs on a local CPU float64 evaluation copy. Caller weights, cached state, device and training mode are preserved. Training-only noise is disabled. One augmented least-squares solve fits all delayed targets together, avoiding the loss of conditioning from normal equations.

PARAMETER DESCRIPTION
source

The reservoir to probe, or a model containing exactly one ESN reservoir. The reservoir must accept a scalar feedback (feedback_size == 1), since memory capacity is defined for a one-dimensional i.i.d. drive.

TYPE: BaseReservoirLayer or ESNModel

max_delay

Largest delay \(k_{\max}\) in the forgetting sum. Should comfortably exceed the reservoir's memory (a few times N for a linear reservoir) so the tail \(R^2_k \approx 0\) and the sum has converged.

TYPE: int DEFAULT: 100

n_samples

Number of (state, delayed-input) samples used to fit each linear readout after washout and delay history. More samples than reservoir states are recommended; positive ridge regularization permits fewer.

TYPE: int DEFAULT: 2000

washout

Leading driven steps discarded so the reservoir state reflects the input history rather than the (zero) initial condition.

TYPE: int DEFAULT: 200

alpha

Non-negative ridge regularization on centered reservoir features. The intercept is unpenalized. Zero selects an unregularized least-squares fit; positive values stabilize correlated or underdetermined states.

TYPE: float DEFAULT: 1e-8

input_low

Lower bound of the uniform input distribution.

TYPE: float DEFAULT: -1.0

input_high

Upper bound of the uniform input distribution \(u_t \sim \mathcal{U}(\text{low}, \text{high})\). The default symmetric [-1, 1] is the Jaeger convention; a smaller range keeps a tanh reservoir nearer its linear regime (larger MC).

TYPE: float DEFAULT: 1.0

seed

Seed for the input draw, so the estimate is fully deterministic.

TYPE: int DEFAULT: 0

test_samples

Number of independent scoring samples, at least 2. None uses max(1000, n_samples) to limit chance correlations at long delays.

TYPE: int or None DEFAULT: None

return_curve

If True, also return the per-delay forgetting curve \((R^2_1, \dots, R^2_{k_{\max}})\) as a (max_delay,) array.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
float or tuple of (float, numpy.ndarray)

The memory capacity \(MC\). When return_curve is True, a (MC, curve) pair where curve[k-1] is \(R^2_k\).

RAISES DESCRIPTION
ValueError

If the reservoir needs multiple feedback channels or an external driver, counts are invalid, training/scoring samples are fewer than 2, or the distribution bounds / regularization are invalid.

Examples:

>>> from resdag.layers import ESNLayer
>>> res = ESNLayer(100, feedback_size=1, spectral_radius=0.9, seed=0)
>>> mc = memory_capacity(res, max_delay=120, n_samples=2000)
>>> mc >= 0.0
True
See Also

effective_spectral_radius : Realized contraction rate of the driven reservoir.

Source code in src/resdag/metrics/observables.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
def memory_capacity(
    source: Any,
    *,
    max_delay: int = 100,
    n_samples: int = 2000,
    washout: int = 200,
    alpha: float = 1e-8,
    input_low: float = -1.0,
    input_high: float = 1.0,
    seed: int = 0,
    return_curve: bool = False,
    test_samples: int | None = None,
) -> float | tuple[float, np.ndarray]:
    r"""Linear short-term memory capacity of a reservoir (Jaeger 2001).

    Drives the reservoir with a scalar i.i.d. uniform input $u_t$ and, for
    each delay $k = 1 \dots$ `max_delay`, fits a **linear** readout from
    the reservoir state $h_t$ to the delayed input $u_{t-k}$.  The
    memory capacity is the sum of the squared correlations of the reconstruction

    $$
    MC = \sum_{k=1}^{k_{\max}} R^2_k, \qquad
    R^2_k = \frac{\operatorname{cov}(\hat u_{t-k},\, u_{t-k})^2}
                 {\operatorname{var}(\hat u_{t-k})\,\operatorname{var}(u_{t-k})},
    $$

    the standard forgetting-curve integral (Jaeger, *Short-term memory in echo
    state networks*, 2001). Readouts are fitted on one random input trajectory
    and scored on an independently generated, independently warmed trajectory.
    No evaluation samples enter fitting or centering statistics.

    The theoretical population capacity is at most the number of reservoir
    states, under the usual independent-input assumptions. This finite-sample
    estimator may exceed that bound through sampling noise, particularly for
    many delays and few test samples. It is not guaranteed to increase with
    spectral radius. Increase `test_samples` and repeat seeds to assess
    uncertainty; this diagnostic is not an autonomous forecast score.

    The actual cell update runs on a local CPU float64 evaluation copy. Caller
    weights, cached state, device and training mode are preserved. Training-only
    noise is disabled. One augmented least-squares solve fits all delayed
    targets together, avoiding the loss of conditioning from normal equations.

    Parameters
    ----------
    source : BaseReservoirLayer or ESNModel
        The reservoir to probe, or a model containing exactly one ESN reservoir.
        The reservoir must accept a **scalar** feedback (`feedback_size == 1`),
        since memory capacity is defined for a one-dimensional i.i.d. drive.
    max_delay : int, default=100
        Largest delay $k_{\max}$ in the forgetting sum.  Should comfortably
        exceed the reservoir's memory (a few times `N` for a linear reservoir)
        so the tail $R^2_k \approx 0$ and the sum has converged.
    n_samples : int, default=2000
        Number of `(state, delayed-input)` samples used to fit each linear
        readout after washout and delay history. More samples than reservoir
        states are recommended; positive ridge regularization permits fewer.
    washout : int, default=200
        Leading driven steps discarded so the reservoir state reflects the input
        history rather than the (zero) initial condition.
    alpha : float, default=1e-8
        Non-negative ridge regularization on centered reservoir features. The
        intercept is unpenalized. Zero selects an unregularized least-squares
        fit; positive values stabilize correlated or underdetermined states.
    input_low : float, optional
        Lower bound of the uniform input distribution.
    input_high : float, optional
        Upper bound of the uniform input distribution $u_t \sim \mathcal{U}(\text{low}, \text{high})$.  The default symmetric `[-1, 1]`
        is the Jaeger convention; a smaller range keeps a `tanh` reservoir
        nearer its linear regime (larger MC).
    seed : int, default=0
        Seed for the input draw, so the estimate is fully deterministic.
    test_samples : int or None, default=None
        Number of independent scoring samples, at least 2. `None` uses
        `max(1000, n_samples)` to limit chance correlations at long delays.
    return_curve : bool, default=False
        If `True`, also return the per-delay forgetting curve
        $(R^2_1, \dots, R^2_{k_{\max}})$ as a `(max_delay,)` array.

    Returns
    -------
    float or tuple of (float, numpy.ndarray)
        The memory capacity $MC$.  When `return_curve` is `True`, a
        `(MC, curve)` pair where `curve[k-1]` is $R^2_k$.

    Raises
    ------
    ValueError
        If the reservoir needs multiple feedback channels or an external driver,
        counts are invalid, training/scoring samples are fewer than 2, or the
        distribution bounds / regularization are invalid.

    Examples
    --------
    >>> from resdag.layers import ESNLayer
    >>> res = ESNLayer(100, feedback_size=1, spectral_radius=0.9, seed=0)
    >>> mc = memory_capacity(res, max_delay=120, n_samples=2000)
    >>> mc >= 0.0
    True

    See Also
    --------
    effective_spectral_radius : Realized contraction rate of the driven reservoir.
    """
    from resdag.data.prepare import _validate_step_count
    from resdag.metrics.lyapunov import _diagnostic_cell, _drive_cell

    max_delay = _validate_step_count("max_delay", max_delay)
    n_samples = _validate_step_count("n_samples", n_samples)
    washout = _validate_step_count("washout", washout, allow_zero=True)
    test_samples = _validate_step_count(
        "test_samples", max(1000, n_samples) if test_samples is None else test_samples
    )
    if n_samples < 2 or test_samples < 2:
        raise ValueError("n_samples and test_samples must both be at least 2.")
    if not np.isfinite(alpha) or alpha < 0:
        raise ValueError("alpha must be finite and non-negative.")
    if not (np.isfinite(input_low) and np.isfinite(input_high) and input_low < input_high):
        raise ValueError("input_low and input_high must be finite with input_low < input_high.")
    cell = _diagnostic_cell(source)
    if getattr(cell, "feedback_size", None) != 1 or getattr(cell, "input_size", None) not in (
        None,
        0,
    ):
        raise ValueError("memory_capacity requires feedback_size == 1 and no external driver.")
    generator = torch.Generator().manual_seed(int(seed))
    start = washout + max_delay

    def samples(count: int) -> tuple[torch.Tensor, torch.Tensor]:
        u = torch.rand(1, start + count, 1, generator=generator, dtype=torch.float64)
        u = input_low + (input_high - input_low) * u
        states, _ = _drive_cell(cell, [u])
        times = torch.arange(start, start + count)
        delays = torch.arange(1, max_delay + 1)
        targets = u[0, times[:, None] - delays, 0]
        return states[0, start:], targets

    # Independent i.i.d. streams, independently warmed from the reset template:
    # no evaluation target or state belongs to the fitting sequence.
    train_x, train_y = samples(n_samples)
    test_x, test_y = samples(test_samples)
    x_mean, y_mean = train_x.mean(0), train_y.mean(0)
    centered = train_x - x_mean
    centered_targets = train_y - y_mean
    if alpha > 0:
        # Solve the equivalent ridge least-squares problem directly. Forming
        # X.T @ X squares the condition number and can round away a positive
        # alpha for large, correlated states, leaving a singular Gram matrix.
        n_features = centered.shape[1]
        centered = torch.cat(
            (centered, np.sqrt(alpha) * torch.eye(n_features, dtype=centered.dtype))
        )
        centered_targets = torch.cat(
            (centered_targets, centered_targets.new_zeros(n_features, max_delay))
        )
    coefficients = torch.linalg.lstsq(centered, centered_targets).solution
    predictions = (test_x - x_mean) @ coefficients + y_mean
    predictions = predictions - predictions.mean(0)
    targets = test_y - test_y.mean(0)
    denominator = predictions.square().sum(0) * targets.square().sum(0)
    correlations = (predictions * targets).sum(0).square()
    curve_tensor = torch.where(denominator > 0, correlations / denominator, 0.0).clamp(0, 1)
    curve = curve_tensor.numpy()
    capacity = float(curve.sum())
    return (capacity, curve) if return_curve else capacity

effective_spectral_radius

effective_spectral_radius(
    source: Any, states: Tensor, *, max_states: int = 256, seed: int = 0
) -> float

Mean spectral radius of the state-dependent leaky-ESN Jacobian.

For leak rate \(\alpha\) and recurrent matrix \(W\), the update is \(h_t = (1-\alpha)h_{t-1} + \alpha\tanh(\mathrm{pre}_t)\), with Jacobian

\[ J_t = (1-\alpha)I + \alpha\operatorname{diag} (1-\tanh^2(\mathrm{pre}_t))W. \]

The activation derivative depends on tanh(pre), which differs from the stored hidden state when any neuron has a leak rate below 1. Consecutive states recover that activation without re-running the reservoir. Bias and drive affect the result through the trajectory's activation saturation. W here includes calibrated recurrent row gains and intrinsic gains. Leak rates may differ per neuron. Caller weights, cached state and mode are preserved.

This returns a mean local eigenvalue radius. Leakage and non-normal weights mean it need not be below the weight spectral radius, and it does not bound transient amplification. Eigensolves use CPU float64 after one transfer, so trajectories from CUDA and MPS reservoirs are both supported.

PARAMETER DESCRIPTION
source

The reservoir whose recurrent Jacobian is analysed, or a model containing exactly one standard ESNCell reservoir with tanh. Alternative cell update equations are explicitly unsupported.

TYPE: BaseReservoirLayer or ESNModel

states

Reservoir states sampled along an attractor trajectory, of shape (batch, time, N) or (time, N) (with N the reservoir size). Supply consecutive states from each trajectory, as returned by the reservoir on representative input. For leak rate 1 the activation is the state itself. For a leaky reservoir it is recovered from adjacent states as (h_t - (1-alpha)*h_{t-1}) / alpha; the first state of each trajectory is excluded because its predecessor is unavailable.

TYPE: Tensor

max_states

Cap on the number of trajectory states the mean is taken over; the states are subsampled on an evenly spaced deterministic grid so the estimate stays manageable for a long trajectory — each state costs one \(N \times N\) eigenvalue solve.

TYPE: int DEFAULT: 256

seed

Retained for API compatibility; even subsampling uses no randomness.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
float

The mean realized spectral radius \(\langle \rho(J_t) \rangle\) over the sampled states, in per-step units. Leakage and non-normal recurrent weights mean this need not be below the weight spectral radius.

RAISES DESCRIPTION
ValueError

If source has no (or more than one) ESN reservoir, or if states does not have a trailing dimension equal to the reservoir size.

NotImplementedError

If the cell is not a standard tanh ESNCell.

Examples:

>>> import torch
>>> from resdag.layers import ESNLayer
>>> res = ESNLayer(100, feedback_size=1, spectral_radius=0.9, seed=0)
>>> u = torch.rand(1, 1500, 1) * 2 - 1
>>> res.reset_state(batch_size=1)
>>> st = res(u)
>>> esr = effective_spectral_radius(res, st)
>>> esr < 0.9  # tanh saturation contracts below the nominal weight radius
True
See Also

resdag.layers.cells.ESNCell.spectral_radius_achieved : The weight spectral radius including calibration gains, before activation derivatives and leakage. resdag.metrics.reservoir_lyapunov : Benettin/QR maximal Lyapunov exponent of the driven reservoir (a time-averaged log-contraction, vs this per-step eigenvalue mean).

Source code in src/resdag/metrics/observables.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
def effective_spectral_radius(
    source: Any,
    states: torch.Tensor,
    *,
    max_states: int = 256,
    seed: int = 0,
) -> float:
    r"""Mean spectral radius of the state-dependent leaky-ESN Jacobian.

    For leak rate $\alpha$ and recurrent matrix $W$, the update is
    $h_t = (1-\alpha)h_{t-1} + \alpha\tanh(\mathrm{pre}_t)$, with Jacobian

    $$
    J_t = (1-\alpha)I + \alpha\operatorname{diag}
          (1-\tanh^2(\mathrm{pre}_t))W.
    $$

    The activation derivative depends on `tanh(pre)`, which differs from the
    stored hidden state when any neuron has a leak rate below 1. Consecutive states recover
    that activation without re-running the reservoir. Bias and drive affect the
    result through the trajectory's activation saturation. `W` here includes
    calibrated recurrent row gains and intrinsic gains. Leak rates may differ
    per neuron. Caller weights, cached state and mode are preserved.

    This returns a mean local eigenvalue radius. Leakage and non-normal weights
    mean it need not be below the weight spectral radius, and it does not bound
    transient amplification. Eigensolves use CPU float64 after one transfer, so
    trajectories from CUDA and MPS reservoirs are both supported.

    Parameters
    ----------
    source : BaseReservoirLayer or ESNModel
        The reservoir whose recurrent Jacobian is analysed, or a model
        containing exactly one standard `ESNCell` reservoir with `tanh`.
        Alternative cell update equations are explicitly unsupported.
    states : torch.Tensor
        Reservoir states sampled along an attractor trajectory, of shape
        `(batch, time, N)` or `(time, N)` (with `N` the reservoir size).
        Supply consecutive states from each trajectory, as returned by the
        reservoir on representative input. For leak rate 1 the activation is
        the state itself. For a leaky reservoir it is recovered from adjacent
        states as `(h_t - (1-alpha)*h_{t-1}) / alpha`; the first state of each
        trajectory is excluded because its predecessor is unavailable.
    max_states : int, default=256
        Cap on the number of trajectory states the mean is taken over; the
        states are subsampled on an evenly spaced deterministic grid so
        the estimate stays manageable for a long trajectory —
        each state costs one $N \times N$ eigenvalue solve.
    seed : int, default=0
        Retained for API compatibility; even subsampling uses no randomness.

    Returns
    -------
    float
        The mean realized spectral radius $\langle \rho(J_t) \rangle$ over
        the sampled states, in per-step units. Leakage and non-normal recurrent
        weights mean this need not be below the weight spectral radius.

    Raises
    ------
    ValueError
        If `source` has no (or more than one) ESN reservoir, or if `states`
        does not have a trailing dimension equal to the reservoir size.
    NotImplementedError
        If the cell is not a standard tanh `ESNCell`.

    Examples
    --------
    >>> import torch
    >>> from resdag.layers import ESNLayer
    >>> res = ESNLayer(100, feedback_size=1, spectral_radius=0.9, seed=0)
    >>> u = torch.rand(1, 1500, 1) * 2 - 1
    >>> res.reset_state(batch_size=1)
    >>> st = res(u)
    >>> esr = effective_spectral_radius(res, st)
    >>> esr < 0.9  # tanh saturation contracts below the nominal weight radius
    True

    See Also
    --------
    resdag.layers.cells.ESNCell.spectral_radius_achieved : The *weight* spectral
        radius including calibration gains, before activation derivatives and leakage.
    resdag.metrics.reservoir_lyapunov : Benettin/QR maximal Lyapunov exponent of
        the driven reservoir (a time-averaged log-contraction, vs this per-step
        eigenvalue mean).
    """
    from resdag.data.prepare import _validate_step_count
    from resdag.metrics.lyapunov import _diagnostic_cell, _esn_recurrent_jacobian_weight

    max_states = _validate_step_count("max_states", max_states)
    cell = _diagnostic_cell(source, tanh_esn=True)
    weight = _esn_recurrent_jacobian_weight(cell)
    n = weight.shape[0]
    h = states.detach().cpu().to(dtype=torch.float64)
    if h.ndim not in (2, 3) or h.shape[-1] != n:
        raise ValueError(f"states must have shape (time,{n}) or (batch,time,{n}).")
    if not bool(torch.isfinite(h).all()):
        raise ValueError("states must be finite.")
    alpha = torch.as_tensor(cell.leak_rate, dtype=torch.float64)
    if alpha.ndim == 0:
        alpha = alpha.expand(n)
    if not bool((alpha == 1).all()):
        if h.shape[-2] < 2:
            raise ValueError(
                "Leaky reservoirs need at least two consecutive states per trajectory."
            )
        # Invert leakage per neuron, preserving trajectory boundaries.
        h = (h[..., 1:, :] - (1 - alpha) * h[..., :-1, :]) / alpha
    h = h.reshape(-1, n)
    if not h.shape[0]:
        raise ValueError("states must contain at least one trajectory state.")
    if h.shape[0] > max_states:
        indices = torch.linspace(0, h.shape[0] - 1, max_states).round().long().unique()
        h = h[indices]
    _ = seed  # The even subsampling grid does not draw randomness.
    identity = torch.eye(n, dtype=torch.float64)
    radii = []
    for activation in h:
        jacobian = alpha[:, None] * (1 - activation.square())[:, None] * weight
        jacobian += (1 - alpha)[:, None] * identity
        radii.append(torch.linalg.eigvals(jacobian).abs().max())
    return float(torch.stack(radii).mean())

correlation_dimension

correlation_dimension(
    trajectory: Tensor | ndarray,
    *,
    n_bins: int = 20,
    r_min_frac: float = 0.01,
    r_max_frac: float = 0.5,
    fit_window: tuple[float, float] = (0.1, 0.5),
    max_points: int = 2000,
    seed: int = 0
) -> float

Grassberger-Procaccia correlation dimension of an attractor trajectory.

Estimates the fractal (correlation) dimension \(D_2\) of the attractor a trajectory lives on, via the Grassberger-Procaccia algorithm (Grassberger & Procaccia, Characterization of strange attractors, 1983). The correlation sum

\[ C(r) = \frac{2}{M(M-1)} \sum_{i<j} \Theta\!\big(r - \lVert x_i - x_j \rVert\big) \]

counts the fraction of point pairs closer than \(r\). On a \(D_2\)-dimensional attractor it scales as \(C(r) \sim r^{D_2}\) over an intermediate ("scaling") range of \(r\), so \(D_2\) is the slope of \(\log C(r)\) against \(\log r\) fit over that range.

This is the standard attractor-fidelity metric for reservoir forecasts: a free-running forecast that reproduces the true system's climate (its long-run geometry) matches the truth's correlation dimension, even when the pointwise trajectory has long since decorrelated.

Reference values (used to validate this implementation):

  • Lorenz-63 \(D_2 \approx 2.05\) (literature; Grassberger & Procaccia 1983).
  • A limit cycle / closed curve \(D_2 \approx 1.0\) (a 1-D manifold).
  • \(d\)-dimensional i.i.d. noise \(D_2 \approx d\) (it fills the embedding space).
PARAMETER DESCRIPTION
trajectory

The attractor trajectory, of shape (time, dim) (a 1-D (time,) signal is treated as a single channel). A leading singleton batch axis (1, time, dim) is squeezed. For a fair comparison of a forecast to the truth, embed both the same way and pass equal-length windows.

TYPE: Tensor or ndarray

n_bins

Number of log-spaced radii \(r\) at which \(C(r)\) is evaluated.

TYPE: int DEFAULT: 20

r_min_frac

Smallest radius as a fraction of the largest pairwise distance.

TYPE: float DEFAULT: 0.01

r_max_frac

Largest radius as a fraction of the largest pairwise distance. The radius grid spans [r_min_frac, r_max_frac] * d_max where d_max is the largest pairwise distance, so the grid adapts to the attractor's size.

TYPE: float DEFAULT: 0.5

fit_window

The scaling region over which the \(\log C\) vs \(\log r\) slope is fit, given as fractions of the (valid) log r span. The default lower-middle window avoids the noisy small-\(r\) depletion and the large-\(r\) saturation that bias a full-range fit.

TYPE: tuple of float DEFAULT: (0.1, 0.5)

max_points

Cap on the number of trajectory points used (the pair count is \(O(M^2)\)); a longer trajectory is uniformly subsampled. 2000 points (~2M pairs) already give a stable dimension for Lorenz-63.

TYPE: int DEFAULT: 2000

seed

Seed for the subsampling draw, so the estimate is deterministic.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
float

The estimated correlation dimension \(D_2\).

RAISES DESCRIPTION
ValueError

If trajectory is not 1-D/2-D (after squeezing a batch axis), has fewer than 2 points, or is a single constant point (zero extent).

Notes

The estimate is a geometry metric, not an error: two trajectories on the same attractor but out of phase share a correlation dimension. Compare a forecast's dimension to the truth's (|D2_pred - D2_truth|) to score climate reconstruction — this is what resdag.hpo.losses.attractor_dimension_error optimises.

Examples:

>>> import numpy as np
>>> t = np.linspace(0, 2 * np.pi, 3000, endpoint=False)
>>> circle = np.stack([np.cos(t), np.sin(t)], axis=1)
>>> abs(correlation_dimension(circle) - 1.0) < 0.15
True
Source code in src/resdag/metrics/observables.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
def correlation_dimension(
    trajectory: torch.Tensor | np.ndarray,
    *,
    n_bins: int = 20,
    r_min_frac: float = 0.01,
    r_max_frac: float = 0.5,
    fit_window: tuple[float, float] = (0.1, 0.5),
    max_points: int = 2000,
    seed: int = 0,
) -> float:
    r"""Grassberger-Procaccia correlation dimension of an attractor trajectory.

    Estimates the fractal (correlation) dimension $D_2$ of the attractor
    a trajectory lives on, via the Grassberger-Procaccia algorithm (Grassberger
    & Procaccia, *Characterization of strange attractors*, 1983).  The
    correlation sum

    $$
    C(r) = \frac{2}{M(M-1)} \sum_{i<j} \Theta\!\big(r - \lVert x_i - x_j \rVert\big)
    $$

    counts the fraction of point pairs closer than $r$.  On a
    $D_2$-dimensional attractor it scales as $C(r) \sim r^{D_2}$ over
    an intermediate ("scaling") range of $r$, so $D_2$ is the slope
    of $\log C(r)$ against $\log r$ fit over that range.

    This is the standard **attractor-fidelity** metric for reservoir forecasts:
    a free-running forecast that reproduces the true system's *climate* (its
    long-run geometry) matches the truth's correlation dimension, even when the
    pointwise trajectory has long since decorrelated.

    Reference values (used to validate this implementation):

    * **Lorenz-63** $D_2 \approx 2.05$ (literature; Grassberger & Procaccia
      1983).
    * **A limit cycle / closed curve** $D_2 \approx 1.0$ (a 1-D manifold).
    * **$d$-dimensional i.i.d. noise** $D_2 \approx d$ (it fills the
      embedding space).

    Parameters
    ----------
    trajectory : torch.Tensor or numpy.ndarray
        The attractor trajectory, of shape `(time, dim)` (a 1-D `(time,)`
        signal is treated as a single channel).  A leading singleton batch axis
        `(1, time, dim)` is squeezed.  For a fair comparison of a forecast to
        the truth, embed both the same way and pass equal-length windows.
    n_bins : int, default=20
        Number of log-spaced radii $r$ at which $C(r)$ is evaluated.
    r_min_frac : float, optional
        Smallest radius as a fraction of the largest pairwise distance.
    r_max_frac : float, optional
        Largest radius as a fraction of the largest pairwise distance.
        The radius grid spans `[r_min_frac, r_max_frac] * d_max` where
        `d_max` is the largest pairwise distance, so the grid adapts to the
        attractor's size.
    fit_window : tuple of float, default=(0.1, 0.5)
        The scaling region over which the $\log C$ vs $\log r$ slope
        is fit, given as fractions of the (valid) `log r` span.  The default
        lower-middle window avoids the noisy small-$r$ depletion and the
        large-$r$ saturation that bias a full-range fit.
    max_points : int, default=2000
        Cap on the number of trajectory points used (the pair count is
        $O(M^2)$); a longer trajectory is uniformly subsampled.  `2000`
        points (~2M pairs) already give a stable dimension for Lorenz-63.
    seed : int, default=0
        Seed for the subsampling draw, so the estimate is deterministic.

    Returns
    -------
    float
        The estimated correlation dimension $D_2$.

    Raises
    ------
    ValueError
        If `trajectory` is not 1-D/2-D (after squeezing a batch axis), has
        fewer than 2 points, or is a single constant point (zero extent).

    Notes
    -----
    The estimate is a **geometry** metric, not an error: two trajectories on the
    *same* attractor but out of phase share a correlation dimension.  Compare a
    forecast's dimension to the truth's (`|D2_pred - D2_truth|`) to score
    climate reconstruction — this is what
    `resdag.hpo.losses.attractor_dimension_error` optimises.

    Examples
    --------
    >>> import numpy as np
    >>> t = np.linspace(0, 2 * np.pi, 3000, endpoint=False)
    >>> circle = np.stack([np.cos(t), np.sin(t)], axis=1)
    >>> abs(correlation_dimension(circle) - 1.0) < 0.15
    True
    """
    if isinstance(trajectory, torch.Tensor):
        x = trajectory.detach().cpu().double().numpy()
    else:
        x = np.asarray(trajectory, dtype=np.float64)

    if x.ndim == 3 and x.shape[0] == 1:
        x = x[0]
    if x.ndim == 1:
        x = x[:, None]
    if x.ndim != 2:
        raise ValueError(
            f"trajectory must be 1-D (time,), 2-D (time, dim), or 3-D (1, time, dim); "
            f"got shape {np.asarray(trajectory).shape}."
        )
    n_points = x.shape[0]
    if n_points < 2:
        raise ValueError(f"trajectory needs at least 2 points, got {n_points}.")

    if n_points > max_points:
        rng = np.random.default_rng(seed)
        idx = rng.choice(n_points, size=max_points, replace=False)
        idx.sort()
        x = x[idx]
        n_points = max_points

    # Upper-triangular pairwise Euclidean distances.
    diff = x[:, None, :] - x[None, :, :]
    dmat = np.sqrt(np.einsum("ijk,ijk->ij", diff, diff))
    iu = np.triu_indices(n_points, k=1)
    dists = dmat[iu]
    dists = dists[dists > 0.0]
    if dists.size == 0:
        raise ValueError(
            "trajectory has zero extent (all points coincide); the correlation "
            "dimension is undefined."
        )
    d_max = float(dists.max())

    radii = np.logspace(
        np.log10(r_min_frac * d_max),
        np.log10(r_max_frac * d_max),
        n_bins,
    )
    # Correlation sum C(r): fraction of pairs closer than r. searchsorted on the
    # sorted distances turns each count into an O(log) lookup.
    dists_sorted = np.sort(dists)
    counts = np.searchsorted(dists_sorted, radii, side="left")
    corr_sum = counts / dists_sorted.size

    valid = corr_sum > 0.0
    log_r = np.log(radii[valid])
    log_c = np.log(corr_sum[valid])
    if log_r.size < 2:
        raise ValueError(
            "not enough non-empty correlation-sum bins to fit a slope; "
            "increase n_bins or the trajectory length."
        )

    lo, hi = fit_window
    r0, r1 = log_r.min(), log_r.max()
    span = r1 - r0
    if span <= 0.0:
        fit_mask = np.ones_like(log_r, dtype=bool)
    else:
        fit_mask = (log_r >= r0 + lo * span) & (log_r <= r0 + hi * span)
        if fit_mask.sum() < 2:
            fit_mask = np.ones_like(log_r, dtype=bool)

    slope = float(np.polyfit(log_r[fit_mask], log_c[fit_mask], 1)[0])
    return slope