Skip to content

Reference

Data and datasets

resdag.data is the canonical home for time-series preparation, file I/O and windowed datasets. resdag.datasets contains benchmark generators. Existing imports through resdag.utils.data use the same functions.

Tensor preparation

prepare_esn_data accepts (batch, time, features) and returns warmup, train, target, forecast-warmup and validation tensors. Its default alignment="next" includes the final observed training target in forecast warmup, so forecasts align with the held-out validation tensor. Inspect the alignment option when working with older experiments.

normalize_data fits statistics on exactly the tensor passed to it. To apply one transformation to later observations, retain those statistics and pass them back through stats=; denormalize_data restores the original units. Keep final test observations out of any statistics fitted for model selection.

prepare_esn_data

prepare_esn_data(
    data: Tensor,
    warmup_steps: int,
    train_steps: int,
    val_steps: int | None = None,
    discard_steps: int = 0,
    normalize: bool = False,
    norm_method: NormMethod = "minmax",
    return_stats: bool = False,
    alignment: ForecastAlignment = "next",
) -> ESNDataSplits | ESNDataSplitsWithStats

Prepare time series data for ESN training and forecasting.

Splits data into segments appropriate for ESN workflows: 1. Warmup: Initial steps for reservoir state synchronization 2. Train: Training input data 3. Target: Training targets (train data shifted by 1 step) 4. Forecast warmup: Last warmup_steps of all observed data, including the final training target, for forecast initialization 5. Validation: Held-out data starting after that final training target.

Data layout (train_end = warmup_steps + train_steps):

[discard][warmup][------- train -------][s][------ val ------]

s is data[train_end]: the final training target, which is already observed during fitting. The forecast warmup includes it. Its readout predicts the first held-out value, data[train_end + 1], so forecast(forecast_warmup, horizon=val_steps) lines up element-for-element with val (no manual shift).

PARAMETER DESCRIPTION
data

Input time series of shape (B, T, D).

TYPE: Tensor

warmup_steps

Number of steps for reservoir warmup/synchronization.

TYPE: int

train_steps

Number of training steps (after warmup).

TYPE: int

val_steps

Number of validation steps. If None, uses all remaining data.

TYPE: int DEFAULT: None

discard_steps

Number of initial steps to discard (e.g., initial transients).

TYPE: int DEFAULT: 0

normalize

Whether to normalize data. If True, statistics are computed from training data and applied to all splits globally.

TYPE: bool DEFAULT: False

norm_method

Normalization method if normalize=True.

TYPE: str DEFAULT: "minmax"

return_stats

If True, append the fitted normalization statistics as a 6th return element so the normalize -> forecast -> report loop can be closed via denormalize_data. The element is the stats dict when normalize=True and None when normalize=False (nothing was fitted). When False (the default), the legacy 5-tuple is returned unchanged.

TYPE: bool DEFAULT: False

alignment

"next" includes the final training target in the forecast history. "legacy" ends that history one sample earlier; pair this with model.forecast(..., alignment="legacy") to reproduce old runs. Training and validation windows are identical in both modes.

TYPE: str DEFAULT: 'next'

RETURNS DESCRIPTION
warmup

Warmup data, shape (B, warmup_steps, D).

TYPE: Tensor

train

Training input, shape (B, train_steps, D).

TYPE: Tensor

target

Training target (shifted by 1), shape (B, train_steps, D).

TYPE: Tensor

forecast_warmup

Last warmup_steps of the observed prefix for forecast init, shape (B, warmup_steps, D). Includes earlier warmup history if train_steps is shorter than warmup_steps.

TYPE: Tensor

val

Validation data, shape (B, val_steps, D). Starts at data[train_end + 1] so it aligns directly with an autoregressive forecast of the same horizon. The final training target belongs to the observed history.

TYPE: Tensor

stats

Only returned when return_stats=True. The fitted normalization statistics (as returned by normalize_data) when normalize=True, otherwise None. Pass to denormalize_data to map forecasts back to the original scale.

TYPE: dict or None

RAISES DESCRIPTION
ValueError

If warmup_steps or train_steps is not strictly positive, if discard_steps is negative, if val_steps is negative, or if the data is too short for the requested splits.

WARNS DESCRIPTION
UserWarning

If the resulting validation window is empty (val_steps=0 or the data is exhausted by warmup, training inputs, and their final target), so no held-out validation data remains.

See Also

denormalize_data : Inverts the normalization using the returned stats.

Examples:

>>> data = torch.randn(1, 1000, 3)  # (batch=1, time=1000, features=3)
>>> warmup, train, target, f_warmup, val = prepare_esn_data(
...     data, warmup_steps=100, train_steps=500, val_steps=200
... )
>>> print(warmup.shape)   # (1, 100, 3)
>>> print(train.shape)    # (1, 500, 3)
>>> print(target.shape)   # (1, 500, 3)
>>> print(f_warmup.shape) # (1, 100, 3)
>>> print(val.shape)      # (1, 200, 3)

Close the round-trip by keeping the fitted stats and inverting later:

>>> warmup, train, target, f_warmup, val, stats = prepare_esn_data(
...     data, warmup_steps=100, train_steps=500, val_steps=200,
...     normalize=True, norm_method="minmax", return_stats=True,
... )
>>> val_physical = denormalize_data(val, "minmax", stats)  # original units
Source code in src/resdag/data/prepare.py
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
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def prepare_esn_data(
    data: torch.Tensor,
    warmup_steps: int,
    train_steps: int,
    val_steps: int | None = None,
    discard_steps: int = 0,
    normalize: bool = False,
    norm_method: NormMethod = "minmax",
    return_stats: bool = False,
    alignment: ForecastAlignment = "next",
) -> ESNDataSplits | ESNDataSplitsWithStats:
    """Prepare time series data for ESN training and forecasting.

    Splits data into segments appropriate for ESN workflows:
    1. Warmup: Initial steps for reservoir state synchronization
    2. Train: Training input data
    3. Target: Training targets (train data shifted by 1 step)
    4. Forecast warmup: Last warmup_steps of all observed data, including the
       final training target, for forecast initialization
    5. Validation: Held-out data starting after that final training target.

    Data layout (`train_end = warmup_steps + train_steps`):

    ```text
    [discard][warmup][------- train -------][s][------ val ------]
    ```

    `s` is `data[train_end]`: the final training target, which is already
    observed during fitting. The forecast warmup includes it. Its readout
    predicts the first held-out value, `data[train_end + 1]`, so
    `forecast(forecast_warmup, horizon=val_steps)` lines up element-for-element
    with `val` (no manual shift).


    Parameters
    ----------
    data : torch.Tensor
        Input time series of shape (B, T, D).
    warmup_steps : int
        Number of steps for reservoir warmup/synchronization.
    train_steps : int
        Number of training steps (after warmup).
    val_steps : int, optional
        Number of validation steps. If None, uses all remaining data.
    discard_steps : int, default=0
        Number of initial steps to discard (e.g., initial transients).
    normalize : bool, default=False
        Whether to normalize data. If True, statistics are computed from
        training data and applied to all splits globally.
    norm_method : str, default="minmax"
        Normalization method if normalize=True.
    return_stats : bool, default=False
        If True, append the fitted normalization statistics as a 6th return
        element so the normalize -> forecast -> report loop can be closed via
        `denormalize_data`. The element is the `stats` dict when
        `normalize=True` and `None` when `normalize=False` (nothing was
        fitted). When False (the default), the legacy 5-tuple is returned
        unchanged.
    alignment : str, optional
        `"next"` includes the final training target in the forecast history.
        `"legacy"` ends that history one sample earlier; pair this with
        `model.forecast(..., alignment="legacy")` to reproduce old runs.
        Training and validation windows are identical in both modes.

    Returns
    -------
    warmup : torch.Tensor
        Warmup data, shape (B, warmup_steps, D).
    train : torch.Tensor
        Training input, shape (B, train_steps, D).
    target : torch.Tensor
        Training target (shifted by 1), shape (B, train_steps, D).
    forecast_warmup : torch.Tensor
        Last warmup_steps of the observed prefix for forecast init, shape
        (B, warmup_steps, D). Includes earlier warmup history if train_steps
        is shorter than warmup_steps.
    val : torch.Tensor
        Validation data, shape (B, val_steps, D). Starts at `data[train_end + 1]`
        so it aligns directly with an autoregressive `forecast` of the same
        horizon. The final training target belongs to the observed history.
    stats : dict or None
        Only returned when `return_stats=True`. The fitted normalization
        statistics (as returned by `normalize_data`) when `normalize=True`,
        otherwise `None`. Pass to `denormalize_data` to map forecasts
        back to the original scale.

    Raises
    ------
    ValueError
        If `warmup_steps` or `train_steps` is not strictly positive, if
        `discard_steps` is negative, if `val_steps` is negative, or if the
        data is too short for the requested splits.

    Warns
    -----
    UserWarning
        If the resulting validation window is empty (`val_steps=0` or the data
        is exhausted by warmup, training inputs, and their final target), so no held-out validation data
        remains.

    See Also
    --------
    denormalize_data : Inverts the normalization using the returned `stats`.

    Examples
    --------
    >>> data = torch.randn(1, 1000, 3)  # (batch=1, time=1000, features=3)
    >>> warmup, train, target, f_warmup, val = prepare_esn_data(
    ...     data, warmup_steps=100, train_steps=500, val_steps=200
    ... )
    >>> print(warmup.shape)   # (1, 100, 3)
    >>> print(train.shape)    # (1, 500, 3)
    >>> print(target.shape)   # (1, 500, 3)
    >>> print(f_warmup.shape) # (1, 100, 3)
    >>> print(val.shape)      # (1, 200, 3)

    Close the round-trip by keeping the fitted stats and inverting later:

    >>> warmup, train, target, f_warmup, val, stats = prepare_esn_data(
    ...     data, warmup_steps=100, train_steps=500, val_steps=200,
    ...     normalize=True, norm_method="minmax", return_stats=True,
    ... )
    >>> val_physical = denormalize_data(val, "minmax", stats)  # original units
    """
    _validate_series_shape(data)
    validate_alignment(alignment)
    _, timesteps, _ = data.shape
    warmup_steps = _validate_step_count("warmup_steps", warmup_steps)
    train_steps = _validate_step_count("train_steps", train_steps)
    discard_steps = _validate_step_count("discard_steps", discard_steps, allow_zero=True)
    if val_steps is not None:
        val_steps = _validate_step_count("val_steps", val_steps, allow_zero=True)

    # Validate discard_steps
    if discard_steps >= timesteps:
        raise ValueError(
            f"discard_steps ({discard_steps}) must be less than data length ({timesteps})"
        )

    # Trim initial steps
    data = data[:, discard_steps:, :]
    timesteps = data.shape[1]

    # Calculate required length
    train_end = warmup_steps + train_steps

    if train_end >= timesteps:
        raise ValueError(
            f"warmup_steps + train_steps ({train_end}) exceeds "
            f"available data length ({timesteps}) after discarding {discard_steps} steps"
        )

    # The final supervised target data[train_end] is already observed. Include
    # it in canonical forecast history, then hold out data[train_end + 1] onward.
    # Legacy preparation omits that observation from history and relies on the
    # old forecast's additional predicted-seed update to reach the same val index.
    val_start = train_end + 1
    if val_steps is None:
        val_steps = timesteps - val_start
        if val_steps == 0:
            warnings.warn(
                "Validation window is empty: warmup + training inputs + their final "
                f"target consume all {timesteps} available steps (after discarding "
                f"{discard_steps}), leaving no held-out data for val. Reduce "
                "warmup_steps/train_steps or supply more data if you need a val split.",
                UserWarning,
                stacklevel=2,
            )
    else:
        required = val_start + val_steps
        if required > timesteps:
            raise ValueError(
                f"Required data ({required} = warmup + train + 1 final target + val) "
                f"exceeds available length ({timesteps}). The +1 supplies the final "
                "supervised target data[train_end], which is already observed "
                "and must precede held-out validation."
            )
        if val_steps == 0:
            warnings.warn(
                "val_steps=0 produces an empty validation split. Pass a positive "
                "val_steps (or None to use all remaining data) if you need a val "
                "window.",
                UserWarning,
                stacklevel=2,
            )

    # Split data
    warmup = data[:, :warmup_steps, :]
    train = data[:, warmup_steps:train_end, :]
    target = data[:, warmup_steps + 1 : train_end + 1, :]
    # Include earlier observed history when train_steps < warmup_steps.
    forecast_end = train_end + (alignment == "next")
    forecast_warmup = data[:, forecast_end - warmup_steps : forecast_end, :]
    val = data[:, val_start : val_start + val_steps, :]

    # Optional normalization (compute stats from training data only)
    stats: dict[str, torch.Tensor] | None = None
    if normalize:
        stats = _compute_stats(train, norm_method)
        warmup = _apply_norm(warmup, norm_method, stats)
        train = _apply_norm(train, norm_method, stats)
        target = _apply_norm(target, norm_method, stats)
        forecast_warmup = _apply_norm(forecast_warmup, norm_method, stats)
        val = _apply_norm(val, norm_method, stats)

    if return_stats:
        return warmup, train, target, forecast_warmup, val, stats
    return warmup, train, target, forecast_warmup, val

normalize_data

normalize_data(
    data: Tensor, method: NormMethod = "minmax", stats: dict[str, Tensor] | None = None
) -> tuple[Tensor, dict[str, Tensor]]

Normalize time series data globally.

Computes statistics across all batches and timesteps, applying the same normalization to the entire dataset. This is the correct approach when batches contain trajectories from the same dynamical system.

PARAMETER DESCRIPTION
data

Data tensor of shape (B, T, D).

TYPE: Tensor

method

Normalization method: - "minmax": Scale to [-1, 1] range - "standard": Zero mean, unit variance - "noncentered": Scale by max absolute value (preserves zero) - "meanpreserving": Scale deviations to [-1, 1], then restore mean

TYPE: str DEFAULT: 'minmax'

stats

Pre-computed statistics for normalization. If provided, these are used instead of computing from data. They are applied on the input device and dtype without modifying the supplied statistics.

TYPE: dict DEFAULT: None

RETURNS DESCRIPTION
normalized

Normalized data with same shape as input.

TYPE: Tensor

stats

Statistics used for normalization (for applying to other data).

TYPE: dict

Examples:

>>> data = torch.randn(1, 100, 3)
>>> normalized, stats = normalize_data(data, method="minmax")
>>> # Apply same normalization to new data
>>> new_normalized, _ = normalize_data(new_data, method="minmax", stats=stats)
Source code in src/resdag/data/prepare.py
 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
100
101
102
103
104
105
106
107
108
109
110
def normalize_data(
    data: torch.Tensor,
    method: NormMethod = "minmax",
    stats: dict[str, torch.Tensor] | None = None,
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
    """Normalize time series data globally.

    Computes statistics across all batches and timesteps, applying the same
    normalization to the entire dataset. This is the correct approach when
    batches contain trajectories from the same dynamical system.

    Parameters
    ----------
    data : torch.Tensor
        Data tensor of shape (B, T, D).
    method : str
        Normalization method:
        - "minmax": Scale to [-1, 1] range
        - "standard": Zero mean, unit variance
        - "noncentered": Scale by max absolute value (preserves zero)
        - "meanpreserving": Scale deviations to [-1, 1], then restore mean
    stats : dict, optional
        Pre-computed statistics for normalization. If provided, these are used
        instead of computing from data. They are applied on the input device
        and dtype without modifying the supplied statistics.

    Returns
    -------
    normalized : torch.Tensor
        Normalized data with same shape as input.
    stats : dict
        Statistics used for normalization (for applying to other data).

    Examples
    --------
    >>> data = torch.randn(1, 100, 3)
    >>> normalized, stats = normalize_data(data, method="minmax")
    >>> # Apply same normalization to new data
    >>> new_normalized, _ = normalize_data(new_data, method="minmax", stats=stats)
    """
    _validate_series_shape(data)
    if stats is None:
        stats = _compute_stats(data, method)

    normalized = _apply_norm(data, method, stats)
    return normalized, stats

denormalize_data

denormalize_data(data: Tensor, method: NormMethod, stats: dict[str, Tensor]) -> Tensor

Invert normalize_data, mapping data back to its original scale.

Applies the exact inverse of the transform that normalize_data (and prepare_esn_data(normalize=True, ...)) applied, using the fitted statistics. This closes the normalize -> forecast -> report loop: feed model predictions through denormalize_data to recover physical units, compute errors in the original scale, or plot against the raw series.

PARAMETER DESCRIPTION
data

Normalized data of shape (B, T, D) to map back to the original scale.

TYPE: Tensor

method

Normalization method that produced data. Must match the method used for the forward transform. The inverse of each method is:

  • "minmax": (data + 1) / 2 * range + min
  • "standard": data * std + mean
  • "noncentered": data * scale
  • "meanpreserving": (data - mean) * maxdev + mean

TYPE: str

stats

Fitted statistics returned by normalize_data (or by prepare_esn_data with return_stats=True). The required keys depend on method: {"min", "range"} for "minmax", {"mean", "std"} for "standard", {"scale"} for "noncentered", and {"mean", "maxdev"} for "meanpreserving".

TYPE: dict

RETURNS DESCRIPTION
Tensor

Data restored to the original scale, with the same shape as data.

RAISES DESCRIPTION
ValueError

If method is not a recognized normalization method.

See Also

normalize_data : The forward transform this function inverts. prepare_esn_data : Returns the fitted stats when return_stats=True.

Examples:

>>> data = torch.randn(1, 100, 3)
>>> normalized, stats = normalize_data(data, method="standard")
>>> restored = denormalize_data(normalized, method="standard", stats=stats)
>>> torch.allclose(restored, data, atol=1e-6)
True
Source code in src/resdag/data/prepare.py
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
def denormalize_data(
    data: torch.Tensor,
    method: NormMethod,
    stats: dict[str, torch.Tensor],
) -> torch.Tensor:
    """Invert `normalize_data`, mapping data back to its original scale.

    Applies the exact inverse of the transform that `normalize_data` (and
    `prepare_esn_data(normalize=True, ...)`) applied, using the fitted
    statistics. This closes the normalize -> forecast -> report loop: feed model
    predictions through `denormalize_data` to recover physical units, compute
    errors in the original scale, or plot against the raw series.

    Parameters
    ----------
    data : torch.Tensor
        Normalized data of shape (B, T, D) to map back to the original scale.
    method : str
        Normalization method that produced `data`. Must match the method used
        for the forward transform. The inverse of each method is:

        - "minmax": `(data + 1) / 2 * range + min`
        - "standard": `data * std + mean`
        - "noncentered": `data * scale`
        - "meanpreserving": `(data - mean) * maxdev + mean`
    stats : dict
        Fitted statistics returned by `normalize_data` (or by
        `prepare_esn_data` with `return_stats=True`). The required keys
        depend on `method`: `{"min", "range"}` for "minmax",
        `{"mean", "std"}` for "standard", `{"scale"}` for "noncentered",
        and `{"mean", "maxdev"}` for "meanpreserving".

    Returns
    -------
    torch.Tensor
        Data restored to the original scale, with the same shape as `data`.

    Raises
    ------
    ValueError
        If `method` is not a recognized normalization method.

    See Also
    --------
    normalize_data : The forward transform this function inverts.
    prepare_esn_data : Returns the fitted `stats` when `return_stats=True`.

    Examples
    --------
    >>> data = torch.randn(1, 100, 3)
    >>> normalized, stats = normalize_data(data, method="standard")
    >>> restored = denormalize_data(normalized, method="standard", stats=stats)
    >>> torch.allclose(restored, data, atol=1e-6)
    True
    """
    return _apply_denorm(data, method, stats)

load_and_prepare

load_and_prepare(
    paths: str | Path | list[str | Path],
    warmup_steps: int,
    train_steps: int,
    val_steps: int | None = None,
    discard_steps: int = 0,
    normalize: bool = False,
    norm_method: NormMethod = "minmax",
    return_stats: bool = False,
    dtype: dtype | None = None,
    alignment: ForecastAlignment = "next",
    **load_kwargs: Any
) -> ESNDataSplits | ESNDataSplitsWithStats

Load data from file(s) and prepare for ESN training.

Convenience function that combines loading and preparation. If multiple paths are provided, data is concatenated along the batch dimension.

PARAMETER DESCRIPTION
paths

Path(s) to data file(s). Supports .csv, .npy, .npz, .nc

TYPE: str, pathlib.Path, or list of paths

warmup_steps

Number of warmup steps.

TYPE: int

train_steps

Number of training steps.

TYPE: int

val_steps

Number of validation steps.

TYPE: int DEFAULT: None

discard_steps

Initial steps to discard.

TYPE: int DEFAULT: 0

normalize

Whether to normalize data.

TYPE: bool DEFAULT: False

norm_method

Normalization method.

TYPE: str DEFAULT: "minmax"

return_stats

If True, append the fitted normalization statistics as a 6th return element (None when normalize=False). Forwarded to prepare_esn_data; see its docstring for details.

TYPE: bool DEFAULT: False

dtype

Desired tensor dtype. If None, uses torch.get_default_dtype().

TYPE: dtype DEFAULT: None

alignment

Forecast timing convention, "next" or "legacy", forwarded to prepare_esn_data.

TYPE: str DEFAULT: 'next'

**load_kwargs

Additional arguments passed to load_file (e.g., key for .npz).

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
ESNDataSplits or ESNDataSplitsWithStats

Tuple of (warmup, train, target, forecast_warmup, val) tensors, with a trailing stats element when return_stats=True.

See Also

denormalize_data : Inverts the normalization using the returned stats.

Examples:

>>> splits = load_and_prepare(
...     "timeseries.csv",
...     warmup_steps=100,
...     train_steps=500,
...     val_steps=200,
...     normalize=True,
... )
>>> warmup, train, target, f_warmup, val = splits
Source code in src/resdag/data/prepare.py
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
540
541
542
543
544
545
546
547
548
549
550
551
552
def load_and_prepare(
    paths: str | Path | list[str | Path],
    warmup_steps: int,
    train_steps: int,
    val_steps: int | None = None,
    discard_steps: int = 0,
    normalize: bool = False,
    norm_method: NormMethod = "minmax",
    return_stats: bool = False,
    dtype: torch.dtype | None = None,
    alignment: ForecastAlignment = "next",
    **load_kwargs: Any,
) -> ESNDataSplits | ESNDataSplitsWithStats:
    """Load data from file(s) and prepare for ESN training.

    Convenience function that combines loading and preparation.
    If multiple paths are provided, data is concatenated along the batch dimension.

    Parameters
    ----------
    paths : str, pathlib.Path, or list of paths
        Path(s) to data file(s). Supports .csv, .npy, .npz, .nc
    warmup_steps : int
        Number of warmup steps.
    train_steps : int
        Number of training steps.
    val_steps : int, optional
        Number of validation steps.
    discard_steps : int, default=0
        Initial steps to discard.
    normalize : bool, default=False
        Whether to normalize data.
    norm_method : str, default="minmax"
        Normalization method.
    return_stats : bool, default=False
        If True, append the fitted normalization statistics as a 6th return
        element (`None` when `normalize=False`). Forwarded to
        `prepare_esn_data`; see its docstring for details.
    dtype : torch.dtype, optional
        Desired tensor dtype. If None, uses `torch.get_default_dtype()`.
    alignment : str, optional
        Forecast timing convention, `"next"` or `"legacy"`, forwarded to
        `prepare_esn_data`.
    **load_kwargs
        Additional arguments passed to load_file (e.g., key for .npz).

    Returns
    -------
    ESNDataSplits or ESNDataSplitsWithStats
        Tuple of (warmup, train, target, forecast_warmup, val) tensors, with a
        trailing `stats` element when `return_stats=True`.

    See Also
    --------
    denormalize_data : Inverts the normalization using the returned `stats`.

    Examples
    --------
    >>> splits = load_and_prepare(
    ...     "timeseries.csv",
    ...     warmup_steps=100,
    ...     train_steps=500,
    ...     val_steps=200,
    ...     normalize=True,
    ... )
    >>> warmup, train, target, f_warmup, val = splits
    """
    from .io import load_file

    # Handle single path or list of paths
    if isinstance(paths, (str, Path, type(None))):
        paths = [paths] if paths else []

    if not paths:
        raise ValueError("At least one data path must be provided")

    # Load and concatenate along batch dimension
    tensors = [load_file(p, dtype=dtype, **load_kwargs) for p in paths]
    data = torch.cat(tensors, dim=0) if len(tensors) > 1 else tensors[0]

    return prepare_esn_data(
        data,
        warmup_steps=warmup_steps,
        train_steps=train_steps,
        val_steps=val_steps,
        discard_steps=discard_steps,
        normalize=normalize,
        norm_method=norm_method,
        return_stats=return_stats,
        alignment=alignment,
    )

Streaming windows

TimeSeriesWindowDataset accepts one trajectory, a batched tensor, or a list of trajectories. Windows never cross trajectory boundaries. With external targets, input and target windows share their origin; otherwise horizon sets the target offset. make_dataloader batches (inputs, targets, washout). See streaming and DataLoaders for training loops.

TimeSeriesWindowDataset

TimeSeriesWindowDataset(
    series: Tensor | Sequence[Tensor],
    window_len: int,
    horizon: int = 1,
    stride: int = 1,
    washout: int = 0,
    targets: Tensor | Sequence[Tensor] | None = None,
    stats: dict[str, Tensor] | None = None,
    norm_method: NormMethod | None = None,
    *,
    target_stats: dict[str, Tensor] | None = None,
    target_norm_method: NormMethod | None = None
)

Bases: Dataset[WindowItem]

Sliding-window torch.utils.data.Dataset over time-series data.

Slices one or more trajectories into fixed-length windows suitable for SGD (or streaming-algebraic) training of a reservoir model. Each item is an (input_window, target_window, washout) triple where input_window and target_window both have shape (window_len, D):

  • Forecasting (default, no external targets): the target is the input shifted forward by horizon steps, so window i covers source steps [start, start + window_len) for the input and [start + horizon, start + horizon + window_len) for the target.
  • Regression (external targets given): the target is the matching window sliced from targets at the same source positions as the input (horizon is ignored — supply pre-aligned targets).

Windows are generated per trajectory and never straddle a trajectory boundary, so feeding the loader's batches with a per-batch reset_reservoirs() keeps reservoir state from leaking across unrelated trajectories. The first washout steps of every window are reported in the returned triple so the caller can exclude them from the loss while the reservoir synchronises.

PARAMETER DESCRIPTION
series

Source data. A (T, D) tensor (one trajectory), a (B, T, D) tensor (B trajectories), or a list of (T, D) tensors of varying length (ragged trajectories).

TYPE: torch.Tensor or sequence of torch.Tensor

window_len

Number of timesteps in each input/target window. Must be positive.

TYPE: int

horizon

Forecast offset: the target window is the input window shifted forward by horizon steps. Ignored when targets is provided. Must be non-negative.

TYPE: int DEFAULT: 1

stride

Step between successive window start positions within a trajectory. Must be positive.

TYPE: int DEFAULT: 1

washout

Number of leading steps in each window the caller should exclude from the loss (transient reservoir warmup). Reported per item; must satisfy 0 <= washout < window_len.

TYPE: int DEFAULT: 0

targets

External regression targets aligned step-for-step with series. Must have the same form and per-trajectory length as series (the feature dimension may differ). When given, the dataset returns input/target windows sliced from the same source positions and horizon is ignored.

TYPE: torch.Tensor or sequence of torch.Tensor DEFAULT: None

stats

Pre-computed input normalization statistics from resdag.data.normalize_data. Applied to inputs and shifted forecast targets; external regression targets retain their own units. Requires norm_method.

TYPE: dict DEFAULT: None

norm_method

Normalization method matching stats: "minmax", "standard", "noncentered", or "meanpreserving". Required when stats is given, ignored otherwise.

TYPE: str or None DEFAULT: None

target_stats

Separate fitted normalization for external regression targets. Both must be supplied together; by default external targets are returned unchanged.

TYPE: (optional, keyword - only) DEFAULT: None

target_norm_method

Separate fitted normalization for external regression targets. Both must be supplied together; by default external targets are returned unchanged.

TYPE: (optional, keyword - only) DEFAULT: None

ATTRIBUTE DESCRIPTION
window_len

Window length.

TYPE: int

horizon

Forecast offset (forecasting mode only).

TYPE: int

stride

Window start spacing.

TYPE: int

washout

Leading steps to exclude from the loss.

TYPE: int

feature_dim

Input feature dimension D.

TYPE: int

target_dim

Target feature dimension (equals feature_dim in forecasting mode).

TYPE: int

RAISES DESCRIPTION
ValueError

For invalid window_len/horizon/stride/washout, mismatched targets, or an incomplete stats/norm_method pair.

Examples:

Forecasting windows over a single (T, D) series:

>>> import torch
>>> from resdag.data import TimeSeriesWindowDataset
>>> series = torch.randn(1000, 3)
>>> ds = TimeSeriesWindowDataset(series, window_len=200, horizon=1, washout=50)
>>> x, y, washout = ds[0]
>>> x.shape, y.shape, washout
(torch.Size([200, 3]), torch.Size([200, 3]), 50)
See Also

make_dataloader : Wrap this dataset in a batched DataLoader. resdag.layers.IncrementalRidgeReadoutLayer : Algebraic over-DataLoader fit.

Source code in src/resdag/data/dataset.py
242
243
244
245
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
def __init__(
    self,
    series: torch.Tensor | Sequence[torch.Tensor],
    window_len: int,
    horizon: int = 1,
    stride: int = 1,
    washout: int = 0,
    targets: torch.Tensor | Sequence[torch.Tensor] | None = None,
    stats: dict[str, torch.Tensor] | None = None,
    norm_method: NormMethod | None = None,
    *,
    target_stats: dict[str, torch.Tensor] | None = None,
    target_norm_method: NormMethod | None = None,
) -> None:
    window_len = _validate_step_count("window_len", window_len)
    horizon = _validate_step_count("horizon", horizon, allow_zero=True)
    stride = _validate_step_count("stride", stride)
    washout = _validate_step_count("washout", washout, allow_zero=True)
    if washout >= window_len:
        raise ValueError(
            f"washout must satisfy 0 <= washout < window_len, got washout={washout}, "
            f"window_len={window_len}."
        )
    if (stats is None) != (norm_method is None):
        raise ValueError(
            "stats and norm_method must be provided together; got "
            f"stats={'set' if stats is not None else None}, norm_method={norm_method!r}."
        )

    if (target_stats is None) != (target_norm_method is None):
        raise ValueError("target_stats and target_norm_method must be provided together.")
    if target_stats is not None and targets is None:
        raise ValueError(
            "target_stats requires external targets; forecast targets use input stats."
        )

    self.window_len = window_len
    self.horizon = horizon
    self.stride = stride
    self.washout = washout
    self._stats = stats
    self._norm_method = norm_method
    self._target_stats = target_stats
    self._target_norm_method = target_norm_method

    self._inputs = _as_trajectory_list(series)
    self.feature_dim = self._inputs[0].shape[-1]

    self._has_external_targets = targets is not None
    if targets is not None:
        self._targets: list[torch.Tensor] = _as_trajectory_list(targets)
        if len(self._targets) != len(self._inputs):
            raise ValueError(
                f"series has {len(self._inputs)} trajectories but targets has "
                f"{len(self._targets)}; they must match."
            )
        for i, (x_traj, y_traj) in enumerate(zip(self._inputs, self._targets)):
            if x_traj.shape[0] != y_traj.shape[0]:
                raise ValueError(
                    f"trajectory {i}: series length ({x_traj.shape[0]}) and targets "
                    f"length ({y_traj.shape[0]}) must match."
                )
        self.target_dim = self._targets[0].shape[-1]
        # Targets are pre-aligned; no forecast offset is applied.
        self._offset = 0
    else:
        self._targets = self._inputs
        self.target_dim = self.feature_dim
        self._offset = horizon

    # One cumulative count per trajectory, rather than a Python tuple for
    # every overlapping window. Memory stays O(number of trajectories).
    self._window_ends: list[int] = []
    total = 0
    for traj in self._inputs:
        max_start = traj.shape[0] - self.window_len - self._offset
        total += max(0, max_start // self.stride + 1)
        self._window_ends.append(total)

make_dataloader

make_dataloader(
    series: Tensor | Sequence[Tensor],
    batch_size: int,
    window_len: int,
    horizon: int = 1,
    stride: int = 1,
    washout: int = 0,
    targets: Tensor | Sequence[Tensor] | None = None,
    stats: dict[str, Tensor] | None = None,
    norm_method: NormMethod | None = None,
    shuffle: bool = False,
    drop_last: bool = False,
    num_workers: int = 0,
    *,
    target_stats: dict[str, Tensor] | None = None,
    target_norm_method: NormMethod | None = None,
    **dataloader_kwargs: object
) -> DataLoader[WindowItem]

Build a windowed torch.utils.data.DataLoader over series.

Convenience wrapper that constructs a TimeSeriesWindowDataset from series and the windowing parameters, then returns a torch.utils.data.DataLoader whose batches are (inputs, targets, washout) with inputs/targets of shape (B, window_len, D) — ready to feed straight into resdag.layers.ESNLayer / resdag.core.ESNModel.forward.

PARAMETER DESCRIPTION
series

Source data; see TimeSeriesWindowDataset.

TYPE: torch.Tensor or sequence of torch.Tensor

batch_size

Number of windows per batch.

TYPE: int

window_len

Window length (timesteps per input/target window).

TYPE: int

horizon

Forecast offset (ignored when targets is given).

TYPE: int DEFAULT: 1

stride

Spacing between window starts within a trajectory.

TYPE: int DEFAULT: 1

washout

Leading steps per window to exclude from the loss.

TYPE: int DEFAULT: 0

targets

External regression targets aligned with series.

TYPE: torch.Tensor or sequence of torch.Tensor DEFAULT: None

stats

Pre-computed normalization statistics (with norm_method).

TYPE: dict DEFAULT: None

norm_method

Normalization method matching stats.

TYPE: str DEFAULT: None

target_stats

Separate normalization for external regression targets; see TimeSeriesWindowDataset.

TYPE: (optional, keyword - only) DEFAULT: None

target_norm_method

Separate normalization for external regression targets; see TimeSeriesWindowDataset.

TYPE: (optional, keyword - only) DEFAULT: None

shuffle

Whether to shuffle window order each epoch.

TYPE: bool DEFAULT: False

drop_last

Whether to drop the final, smaller-than-batch_size batch.

TYPE: bool DEFAULT: False

num_workers

Number of worker processes for data loading.

TYPE: int DEFAULT: 0

**dataloader_kwargs

Extra keyword arguments forwarded to torch.utils.data.DataLoader (e.g. pin_memory, generator). collate_fn is supplied here and must not be overridden.

TYPE: object DEFAULT: {}

RETURNS DESCRIPTION
DataLoader

Loader yielding (inputs, targets, washout) batches.

Examples:

>>> import torch
>>> from resdag.data import make_dataloader
>>> series = torch.randn(1000, 3)
>>> loader = make_dataloader(series, batch_size=16, window_len=200, washout=50)
>>> x, y, washout = next(iter(loader))
>>> x.shape  # (B, window_len, D)
torch.Size([16, 200, 3])
See Also

TimeSeriesWindowDataset : The underlying windowing dataset.

Source code in src/resdag/data/dataset.py
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
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
def make_dataloader(
    series: torch.Tensor | Sequence[torch.Tensor],
    batch_size: int,
    window_len: int,
    horizon: int = 1,
    stride: int = 1,
    washout: int = 0,
    targets: torch.Tensor | Sequence[torch.Tensor] | None = None,
    stats: dict[str, torch.Tensor] | None = None,
    norm_method: NormMethod | None = None,
    shuffle: bool = False,
    drop_last: bool = False,
    num_workers: int = 0,
    *,
    target_stats: dict[str, torch.Tensor] | None = None,
    target_norm_method: NormMethod | None = None,
    **dataloader_kwargs: object,
) -> DataLoader[WindowItem]:
    """Build a windowed `torch.utils.data.DataLoader` over `series`.

    Convenience wrapper that constructs a `TimeSeriesWindowDataset` from
    `series` and the windowing parameters, then returns a
    `torch.utils.data.DataLoader` whose batches are
    `(inputs, targets, washout)` with `inputs`/`targets` of shape
    `(B, window_len, D)` — ready to feed straight into
    `resdag.layers.ESNLayer` / `resdag.core.ESNModel.forward`.

    Parameters
    ----------
    series : torch.Tensor or sequence of torch.Tensor
        Source data; see `TimeSeriesWindowDataset`.
    batch_size : int
        Number of windows per batch.
    window_len : int
        Window length (timesteps per input/target window).
    horizon : int, default=1
        Forecast offset (ignored when `targets` is given).
    stride : int, default=1
        Spacing between window starts within a trajectory.
    washout : int, default=0
        Leading steps per window to exclude from the loss.
    targets : torch.Tensor or sequence of torch.Tensor, optional
        External regression targets aligned with `series`.
    stats : dict, optional
        Pre-computed normalization statistics (with `norm_method`).
    norm_method : str, optional
        Normalization method matching `stats`.
    target_stats, target_norm_method : optional, keyword-only
        Separate normalization for external regression targets; see
        `TimeSeriesWindowDataset`.
    shuffle : bool, default=False
        Whether to shuffle window order each epoch.
    drop_last : bool, default=False
        Whether to drop the final, smaller-than-`batch_size` batch.
    num_workers : int, default=0
        Number of worker processes for data loading.
    **dataloader_kwargs : object
        Extra keyword arguments forwarded to `torch.utils.data.DataLoader`
        (e.g. `pin_memory`, `generator`). `collate_fn` is supplied here and
        must not be overridden.

    Returns
    -------
    torch.utils.data.DataLoader
        Loader yielding `(inputs, targets, washout)` batches.

    Examples
    --------
    >>> import torch
    >>> from resdag.data import make_dataloader
    >>> series = torch.randn(1000, 3)
    >>> loader = make_dataloader(series, batch_size=16, window_len=200, washout=50)
    >>> x, y, washout = next(iter(loader))
    >>> x.shape  # (B, window_len, D)
    torch.Size([16, 200, 3])

    See Also
    --------
    TimeSeriesWindowDataset : The underlying windowing dataset.
    """
    dataset = TimeSeriesWindowDataset(
        series,
        window_len=window_len,
        horizon=horizon,
        stride=stride,
        washout=washout,
        targets=targets,
        stats=stats,
        norm_method=norm_method,
        target_stats=target_stats,
        target_norm_method=target_norm_method,
    )
    return DataLoader(
        dataset,
        batch_size=batch_size,
        shuffle=shuffle,
        drop_last=drop_last,
        num_workers=num_workers,
        collate_fn=_collate_windows,
        **dataloader_kwargs,  # type: ignore[arg-type]
    )

Files

Loaders return (batch, time, features). CSV rows represent timesteps and columns represent features, including single-row and single-column files. An NPY/NPZ/NetCDF vector is interpreted as a univariate series and emits an ambiguity warning; store a (time, features) array to make the axes explicit. NPY and NPZ loading use NumPy's default restricted object-array policy. NetCDF requires the optional xarray dependency.

load_file

load_file(path: PathLike, dtype: dtype | None = None, **kwargs: Any) -> Tensor

Load time series data from a file, detecting format from extension.

PARAMETER DESCRIPTION
path

Path to the data file. Supported extensions: .csv, .npy, .npz, .nc

TYPE: str or Path

dtype

Desired tensor dtype. If None, uses torch.get_default_dtype().

TYPE: dtype DEFAULT: None

**kwargs

Additional arguments passed to the specific loader (e.g., key for .npz).

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION
Tensor

Data tensor with shape (B, T, D).

RAISES DESCRIPTION
ValueError

If the file extension is not supported.

Source code in src/resdag/data/io.py
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
def load_file(path: PathLike, dtype: torch.dtype | None = None, **kwargs: Any) -> torch.Tensor:
    """Load time series data from a file, detecting format from extension.

    Parameters
    ----------
    path : str or Path
        Path to the data file. Supported extensions: .csv, .npy, .npz, .nc
    dtype : torch.dtype, optional
        Desired tensor dtype. If None, uses `torch.get_default_dtype()`.
    **kwargs
        Additional arguments passed to the specific loader (e.g., key for .npz).

    Returns
    -------
    torch.Tensor
        Data tensor with shape (B, T, D).

    Raises
    ------
    ValueError
        If the file extension is not supported.
    """
    path = Path(path)
    suffix = path.suffix.lower()

    loaders: dict[str, Callable[..., torch.Tensor]] = {
        ".csv": load_csv,
        ".npy": load_npy,
        ".npz": load_npz,
        ".nc": load_nc,
    }

    if suffix not in loaders:
        raise ValueError(
            f"Unsupported file extension '{suffix}' for '{path}'. Supported: {list(loaders.keys())}"
        )

    return loaders[suffix](path, dtype=dtype, **kwargs)

load_csv

load_csv(path: PathLike, delimiter: str = ',', dtype: dtype | None = None) -> Tensor

Load time series data from a CSV file.

PARAMETER DESCRIPTION
path

Path to the CSV file.

TYPE: str or Path

delimiter

Field delimiter.

TYPE: str DEFAULT: ","

dtype

Desired tensor dtype. If None, uses torch.get_default_dtype().

TYPE: dtype DEFAULT: None

RETURNS DESCRIPTION
Tensor

Data tensor with shape (1, T, D).

Notes

Expects headerless CSV with numeric values only.

The file is read with ndmin=2 so the on-disk grid maps directly to (T, D) and the (timesteps, features) convention is preserved without ambiguity:

  • a single-row, N-column file -> (1, N) -> (1, 1, N) (one timestep of N features);
  • a single-column, T-row file -> (T, 1) -> (1, T, 1) (T timesteps of one feature).

Without ndmin=2 np.loadtxt collapses a single row to a 1D array, which would silently transpose the time and feature axes.

Source code in src/resdag/data/io.py
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
def load_csv(
    path: PathLike, delimiter: str = ",", dtype: torch.dtype | None = None
) -> torch.Tensor:
    """Load time series data from a CSV file.

    Parameters
    ----------
    path : str or Path
        Path to the CSV file.
    delimiter : str, default=","
        Field delimiter.
    dtype : torch.dtype, optional
        Desired tensor dtype. If None, uses `torch.get_default_dtype()`.

    Returns
    -------
    torch.Tensor
        Data tensor with shape (1, T, D).

    Notes
    -----
    Expects headerless CSV with numeric values only.

    The file is read with `ndmin=2` so the on-disk grid maps directly to
    `(T, D)` and the `(timesteps, features)` convention is preserved without
    ambiguity:

    - a single-row, `N`-column file -> `(1, N)` -> `(1, 1, N)`
      (one timestep of `N` features);
    - a single-column, `T`-row file -> `(T, 1)` -> `(1, T, 1)`
      (`T` timesteps of one feature).

    Without `ndmin=2` `np.loadtxt` collapses a single row to a 1D array,
    which would silently transpose the time and feature axes.
    """
    dtype = dtype or torch.get_default_dtype()
    np_dtype = _torch_to_numpy_dtype(dtype)
    data = np.loadtxt(path, delimiter=delimiter, dtype=np_dtype, ndmin=2)
    data = _ensure_3d(data, f"CSV file '{path}'")
    return torch.from_numpy(data)

load_npy

load_npy(path: PathLike, dtype: dtype | None = None) -> Tensor

Load time series data from a NumPy .npy file.

PARAMETER DESCRIPTION
path

Path to the .npy file.

TYPE: str or Path

dtype

Desired tensor dtype. If None, uses torch.get_default_dtype().

TYPE: dtype DEFAULT: None

RETURNS DESCRIPTION
Tensor

Data tensor with shape (B, T, D).

WARNS DESCRIPTION
UserWarning

If the stored array is 1D (T,). It is interpreted as a univariate series and reshaped to (1, T, 1); store data as 2D (T, D) to make the shape unambiguous and suppress the warning.

Source code in src/resdag/data/io.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def load_npy(path: PathLike, dtype: torch.dtype | None = None) -> torch.Tensor:
    """Load time series data from a NumPy .npy file.

    Parameters
    ----------
    path : str or Path
        Path to the .npy file.
    dtype : torch.dtype, optional
        Desired tensor dtype. If None, uses `torch.get_default_dtype()`.

    Returns
    -------
    torch.Tensor
        Data tensor with shape (B, T, D).

    Warns
    -----
    UserWarning
        If the stored array is 1D `(T,)`. It is interpreted as a univariate
        series and reshaped to `(1, T, 1)`; store data as 2D `(T, D)` to
        make the shape unambiguous and suppress the warning.
    """
    dtype = dtype or torch.get_default_dtype()
    np_dtype = _torch_to_numpy_dtype(dtype)
    data = np.load(path).astype(np_dtype)
    _warn_if_1d(data, f"NPY file '{path}'")
    data = _ensure_3d(data, f"NPY file '{path}'")
    return torch.from_numpy(data)

load_npz

load_npz(path: PathLike, key: str = 'data', dtype: dtype | None = None) -> Tensor

Load time series data from a NumPy .npz file.

PARAMETER DESCRIPTION
path

Path to the .npz file.

TYPE: str or Path

key

Key to access the data array in the .npz file.

TYPE: str DEFAULT: "data"

dtype

Desired tensor dtype. If None, uses torch.get_default_dtype().

TYPE: dtype DEFAULT: None

RETURNS DESCRIPTION
Tensor

Data tensor with shape (B, T, D).

RAISES DESCRIPTION
KeyError

If the specified key is not found in the file.

WARNS DESCRIPTION
UserWarning

If the stored array is 1D (T,). It is interpreted as a univariate series and reshaped to (1, T, 1); store data as 2D (T, D) to make the shape unambiguous and suppress the warning.

Source code in src/resdag/data/io.py
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
239
240
241
242
243
244
245
246
247
248
def load_npz(path: PathLike, key: str = "data", dtype: torch.dtype | None = None) -> torch.Tensor:
    """Load time series data from a NumPy .npz file.

    Parameters
    ----------
    path : str or Path
        Path to the .npz file.
    key : str, default="data"
        Key to access the data array in the .npz file.
    dtype : torch.dtype, optional
        Desired tensor dtype. If None, uses `torch.get_default_dtype()`.

    Returns
    -------
    torch.Tensor
        Data tensor with shape (B, T, D).

    Raises
    ------
    KeyError
        If the specified key is not found in the file.

    Warns
    -----
    UserWarning
        If the stored array is 1D `(T,)`. It is interpreted as a univariate
        series and reshaped to `(1, T, 1)`; store data as 2D `(T, D)` to
        make the shape unambiguous and suppress the warning.
    """
    dtype = dtype or torch.get_default_dtype()
    np_dtype = _torch_to_numpy_dtype(dtype)
    with np.load(path) as data_dict:
        if key not in data_dict:
            available = list(data_dict.keys())
            raise KeyError(f"Key '{key}' not found in '{path}'. Available keys: {available}")
        data = data_dict[key].astype(np_dtype)
    _warn_if_1d(data, f"NPZ file '{path}' (key '{key}')")
    data = _ensure_3d(data, f"NPZ file '{path}'")
    return torch.from_numpy(data)

load_nc

load_nc(path: PathLike, dtype: dtype | None = None) -> Tensor

Load time series data from a NetCDF (.nc) file.

PARAMETER DESCRIPTION
path

Path to the .nc file.

TYPE: str or Path

dtype

Desired tensor dtype. If None, uses torch.get_default_dtype().

TYPE: dtype DEFAULT: None

RETURNS DESCRIPTION
Tensor

Data tensor with shape (B, T, D).

WARNS DESCRIPTION
UserWarning

If the stored array is 1D (T,). It is interpreted as a univariate series and reshaped to (1, T, 1); store data as 2D (T, D) to make the shape unambiguous and suppress the warning.

Notes

Requires xarray to be installed.

Source code in src/resdag/data/io.py
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
def load_nc(path: PathLike, dtype: torch.dtype | None = None) -> torch.Tensor:
    """Load time series data from a NetCDF (.nc) file.

    Parameters
    ----------
    path : str or Path
        Path to the .nc file.
    dtype : torch.dtype, optional
        Desired tensor dtype. If None, uses `torch.get_default_dtype()`.

    Returns
    -------
    torch.Tensor
        Data tensor with shape (B, T, D).

    Warns
    -----
    UserWarning
        If the stored array is 1D `(T,)`. It is interpreted as a univariate
        series and reshaped to `(1, T, 1)`; store data as 2D `(T, D)` to
        make the shape unambiguous and suppress the warning.

    Notes
    -----
    Requires xarray to be installed.
    """
    try:
        import xarray as xr
    except ImportError as e:
        raise ImportError(
            "xarray is required to load NetCDF files. Install with: pip install xarray netcdf4"
        ) from e

    dtype = dtype or torch.get_default_dtype()
    np_dtype = _torch_to_numpy_dtype(dtype)
    with xr.open_dataarray(path) as array:
        data = array.to_numpy().astype(np_dtype)
    _warn_if_1d(data, f"NetCDF file '{path}'")
    data = _ensure_3d(data, f"NetCDF file '{path}'")
    return torch.from_numpy(data)

save_csv

save_csv(data: Tensor, path: PathLike, delimiter: str = ',') -> None

Save data to a CSV file.

PARAMETER DESCRIPTION
data

Data to save. Will be squeezed to 2D (T, D) if 3D with B=1.

TYPE: Tensor

path

Path to save the CSV file.

TYPE: str or Path

delimiter

Field delimiter.

TYPE: str DEFAULT: ","

RAISES DESCRIPTION
ValueError

If data cannot be represented as 2D.

Source code in src/resdag/data/io.py
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
def save_csv(data: torch.Tensor, path: PathLike, delimiter: str = ",") -> None:
    """Save data to a CSV file.

    Parameters
    ----------
    data : torch.Tensor
        Data to save. Will be squeezed to 2D (T, D) if 3D with B=1.
    path : str or Path
        Path to save the CSV file.
    delimiter : str, default=","
        Field delimiter.

    Raises
    ------
    ValueError
        If data cannot be represented as 2D.
    """
    arr = data.detach().cpu().numpy()

    # Squeeze batch dim if B=1
    if arr.ndim == 3 and arr.shape[0] == 1:
        arr = arr.squeeze(0)

    if arr.ndim != 2:
        raise ValueError(f"CSV saving requires 2D data, got shape {arr.shape}")

    np.savetxt(path, arr, delimiter=delimiter)

save_npy

save_npy(data: Tensor, path: PathLike) -> None

Save data to a NumPy .npy file.

PARAMETER DESCRIPTION
data

Data to save.

TYPE: Tensor

path

Path to save the .npy file.

TYPE: str or Path

Source code in src/resdag/data/io.py
362
363
364
365
366
367
368
369
370
371
372
def save_npy(data: torch.Tensor, path: PathLike) -> None:
    """Save data to a NumPy .npy file.

    Parameters
    ----------
    data : torch.Tensor
        Data to save.
    path : str or Path
        Path to save the .npy file.
    """
    np.save(path, data.detach().cpu().numpy())

save_npz

save_npz(data: Tensor, path: PathLike, key: str = 'data') -> None

Save data to a NumPy .npz file.

PARAMETER DESCRIPTION
data

Data to save.

TYPE: Tensor

path

Path to save the .npz file.

TYPE: str or Path

key

Key to use when storing the data.

TYPE: str DEFAULT: "data"

Source code in src/resdag/data/io.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def save_npz(data: torch.Tensor, path: PathLike, key: str = "data") -> None:
    """Save data to a NumPy .npz file.

    Parameters
    ----------
    data : torch.Tensor
        Data to save.
    path : str or Path
        Path to save the .npz file.
    key : str, default="data"
        Key to use when storing the data.
    """
    # ``key`` is dynamic, so the array is passed via ``**``. numpy 2.4's typed
    # stub for ``savez`` added an ``allow_pickle`` keyword that a str-keyed ``**``
    # mapping cannot satisfy; bind through a generically-typed reference so the
    # call type-checks identically on every supported numpy (>=2.0) without
    # changing the runtime call.
    savez: Callable[..., None] = np.savez
    savez(path, **{key: data.detach().cpu().numpy()})

save_nc

save_nc(data: Tensor, path: PathLike) -> None

Save data to a NetCDF (.nc) file.

PARAMETER DESCRIPTION
data

Data to save.

TYPE: Tensor

path

Path to save the .nc file.

TYPE: str or Path

Notes

Requires xarray to be installed.

Source code in src/resdag/data/io.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
def save_nc(data: torch.Tensor, path: PathLike) -> None:
    """Save data to a NetCDF (.nc) file.

    Parameters
    ----------
    data : torch.Tensor
        Data to save.
    path : str or Path
        Path to save the .nc file.

    Notes
    -----
    Requires xarray to be installed.
    """
    try:
        import xarray as xr
    except ImportError as e:
        raise ImportError(
            "xarray is required to save NetCDF files. Install with: pip install xarray netcdf4"
        ) from e

    arr = data.detach().cpu().numpy()
    xr.DataArray(arr).to_netcdf(path)

list_files

list_files(directory: PathLike, extensions: list[str] | None = None) -> list[Path]

List files in a directory, optionally filtering by extension.

PARAMETER DESCRIPTION
directory

Path to the directory.

TYPE: str or Path

extensions

List of extensions to filter (e.g., [".csv", ".npy"]). If None, returns all files.

TYPE: list of str DEFAULT: None

RETURNS DESCRIPTION
list[Path]

List of file paths (excluding directories).

Source code in src/resdag/data/io.py
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
def list_files(directory: PathLike, extensions: list[str] | None = None) -> list[Path]:
    """List files in a directory, optionally filtering by extension.

    Parameters
    ----------
    directory : str or Path
        Path to the directory.
    extensions : list of str, optional
        List of extensions to filter (e.g., [".csv", ".npy"]).
        If None, returns all files.

    Returns
    -------
    list[Path]
        List of file paths (excluding directories).
    """
    directory = Path(directory)
    files = [f for f in directory.iterdir() if f.is_file()]

    if extensions:
        # Normalize extensions to lowercase with leading dot
        exts = {e.lower() if e.startswith(".") else f".{e.lower()}" for e in extensions}
        files = [f for f in files if f.suffix.lower() in exts]

    return sorted(files)

Dataset generators

Each generator takes n_timesteps first and returns a (1, time, features) tensor. Continuous Lorenz and Rössler generators use RK4; these convenience generators are separate from optional TSDynamics trajectory integration. All generators return raw values by default (normalize=None). The common rd.ESN.fit / rd.Model.fit workflow learns scaling from training observations. For raw graph workflows, split first and fit normalization on the training prefix with prepare_esn_data(..., normalize=True) or normalize_data. Explicit normalize="standard" or normalize="minmax" scales the entire returned window; use that option only when the complete window belongs to one training split, or when global normalization is intentionally part of your experiment. Record the actual dt, system parameters, initial-condition/seed settings and discarded transient alongside any forecast result.

lorenz

lorenz(
    n_timesteps: int,
    *,
    dt: float = 0.02,
    sigma: float = 10.0,
    rho: float = 28.0,
    beta: float = 8.0 / 3.0,
    x0: tuple[float, float, float] = (1.0, 1.0, 1.0),
    perturb: float = 0.01,
    discard: int = 1000,
    normalize: Normalize | None = None,
    seed: int | Generator | None = 0,
    dtype: dtype = float32,
    device: device | str | None = None
) -> Tensor

Generate a Lorenz-63 trajectory (classic RK4 integration).

The Lorenz-63 system is the canonical chaotic benchmark for reservoir forecasting:

dx/dt = sigma * (y - x)
dy/dt = x * (rho - z) - y
dz/dt = x * y - beta * z
PARAMETER DESCRIPTION
n_timesteps

Number of timesteps to return (after the discarded transient).

TYPE: int

dt

Integration step (RK4). Default 0.02.

TYPE: float DEFAULT: 0.02

sigma

Lorenz Prandtl parameter.

TYPE: float DEFAULT: 10.0

rho

Lorenz Rayleigh parameter. The defaults select the classic chaotic regime.

TYPE: float DEFAULT: 28.0

beta

Lorenz geometric parameter.

TYPE: float DEFAULT: 8.0 / 3.0

x0

Base initial condition (x, y, z). Default (1.0, 1.0, 1.0).

TYPE: tuple of float DEFAULT: (1.0, 1.0, 1.0)

perturb

Std of the Gaussian perturbation added to x0 (drawn from the seeded RNG). Set to 0 for a fully deterministic initial condition.

TYPE: float DEFAULT: 0.01

discard

Leading transient steps to drop so the trajectory sits on the attractor. Default 1000.

TYPE: int DEFAULT: 1000

normalize

Per-channel normalization: "standard", "minmax", or None. Default None (raw values).

TYPE: str or None DEFAULT: None

seed

Seed for the initial-condition perturbation (via resdag.utils.create_rng). Default 0.

TYPE: int, numpy.random.Generator, or None DEFAULT: 0

dtype

Dtype of the returned tensor. Default torch.float32 (matches torch's default, so the series drops straight into a model).

TYPE: dtype DEFAULT: float32

device

Device of the returned tensor. Default None (CPU).

TYPE: torch.device, str, or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Trajectory of shape (1, n_timesteps, 3).

See Also

rossler : Another canonical chaotic attractor.

Source code in src/resdag/utils/data/datasets.py
234
235
236
237
238
239
240
241
242
243
244
245
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
def lorenz(
    n_timesteps: int,
    *,
    dt: float = 0.02,
    sigma: float = 10.0,
    rho: float = 28.0,
    beta: float = 8.0 / 3.0,
    x0: tuple[float, float, float] = (1.0, 1.0, 1.0),
    perturb: float = 0.01,
    discard: int = 1000,
    normalize: Normalize | None = None,
    seed: int | np.random.Generator | None = 0,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.Tensor:
    """Generate a Lorenz-63 trajectory (classic RK4 integration).

    The Lorenz-63 system is the canonical chaotic benchmark for reservoir
    forecasting:

    ```text
    dx/dt = sigma * (y - x)
    dy/dt = x * (rho - z) - y
    dz/dt = x * y - beta * z
    ```

    Parameters
    ----------
    n_timesteps : int
        Number of timesteps to return (after the discarded transient).
    dt : float, optional
        Integration step (RK4). Default `0.02`.
    sigma : float, optional
        Lorenz Prandtl parameter.
    rho : float, optional
        Lorenz Rayleigh parameter. The defaults select the classic chaotic regime.
    beta : float, optional
        Lorenz geometric parameter.
    x0 : tuple of float, optional
        Base initial condition `(x, y, z)`. Default `(1.0, 1.0, 1.0)`.
    perturb : float, optional
        Std of the Gaussian perturbation added to `x0` (drawn from the seeded
        RNG). Set to `0` for a fully deterministic initial condition.
    discard : int, optional
        Leading transient steps to drop so the trajectory sits on the
        attractor. Default `1000`.
    normalize : str or None, optional
        Per-channel normalization: `"standard"`, `"minmax"`, or `None`.
        Default `None` (raw values).
    seed : int, numpy.random.Generator, or None, optional
        Seed for the initial-condition perturbation (via
        `resdag.utils.create_rng`). Default `0`.
    dtype : torch.dtype, optional
        Dtype of the returned tensor. Default `torch.float32` (matches
        torch's default, so the series drops straight into a model).
    device : torch.device, str, or None, optional
        Device of the returned tensor. Default `None` (CPU).

    Returns
    -------
    torch.Tensor
        Trajectory of shape `(1, n_timesteps, 3)`.

    See Also
    --------
    rossler : Another canonical chaotic attractor.
    """
    rng = create_rng(seed)
    state = np.asarray(x0, dtype=np.float64)
    if perturb:
        state = state + perturb * rng.standard_normal(3)

    def rhs(s: np.ndarray) -> np.ndarray:
        x, y, z = s
        return np.array([sigma * (y - x), x * (rho - z) - y, x * y - beta * z])

    traj = _integrate_rk4(rhs, state, n_timesteps + discard, dt)
    series = _normalize(traj[discard:], normalize)
    return _to_tensor(series, dtype, device)

rossler

rossler(
    n_timesteps: int,
    *,
    dt: float = 0.05,
    a: float = 0.2,
    b: float = 0.2,
    c: float = 5.7,
    x0: tuple[float, float, float] = (1.0, 1.0, 1.0),
    perturb: float = 0.01,
    discard: int = 1000,
    normalize: Normalize | None = None,
    seed: int | Generator | None = 0,
    dtype: dtype = float32,
    device: device | str | None = None
) -> Tensor

Generate a Rössler trajectory (classic RK4 integration).

The Rössler system is a three-dimensional chaotic attractor:

dx/dt = -y - z
dy/dt = x + a * y
dz/dt = b + z * (x - c)
PARAMETER DESCRIPTION
n_timesteps

Number of timesteps to return (after the discarded transient).

TYPE: int

dt

Integration step (RK4). Default 0.05.

TYPE: float DEFAULT: 0.05

a

Linear growth coefficient in the Rössler y equation.

TYPE: float DEFAULT: 0.2

b

Constant forcing in the Rössler z equation.

TYPE: float DEFAULT: 0.2

c

Rössler z damping parameter. The defaults select the classic chaotic regime.

TYPE: float DEFAULT: 5.7

x0

Base initial condition (x, y, z). Default (1.0, 1.0, 1.0).

TYPE: tuple of float DEFAULT: (1.0, 1.0, 1.0)

perturb

Std of the Gaussian perturbation added to x0. Set to 0 for a deterministic initial condition.

TYPE: float DEFAULT: 0.01

discard

Leading transient steps to drop. Default 1000.

TYPE: int DEFAULT: 1000

normalize

Per-channel normalization: "standard", "minmax", or None. Default None (raw values).

TYPE: str or None DEFAULT: None

seed

Seed for the initial-condition perturbation. Default 0.

TYPE: int, numpy.random.Generator, or None DEFAULT: 0

dtype

Dtype of the returned tensor. Default torch.float32 (matches torch's default, so the series drops straight into a model).

TYPE: dtype DEFAULT: float32

device

Device of the returned tensor. Default None (CPU).

TYPE: torch.device, str, or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Trajectory of shape (1, n_timesteps, 3).

See Also

lorenz : The canonical chaotic forecasting benchmark.

Source code in src/resdag/utils/data/datasets.py
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
def rossler(
    n_timesteps: int,
    *,
    dt: float = 0.05,
    a: float = 0.2,
    b: float = 0.2,
    c: float = 5.7,
    x0: tuple[float, float, float] = (1.0, 1.0, 1.0),
    perturb: float = 0.01,
    discard: int = 1000,
    normalize: Normalize | None = None,
    seed: int | np.random.Generator | None = 0,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.Tensor:
    """Generate a Rössler trajectory (classic RK4 integration).

    The Rössler system is a three-dimensional chaotic attractor:

    ```text
    dx/dt = -y - z
    dy/dt = x + a * y
    dz/dt = b + z * (x - c)
    ```

    Parameters
    ----------
    n_timesteps : int
        Number of timesteps to return (after the discarded transient).
    dt : float, optional
        Integration step (RK4). Default `0.05`.
    a : float, optional
        Linear growth coefficient in the Rössler y equation.
    b : float, optional
        Constant forcing in the Rössler z equation.
    c : float, optional
        Rössler z damping parameter. The defaults select the classic chaotic regime.
    x0 : tuple of float, optional
        Base initial condition `(x, y, z)`. Default `(1.0, 1.0, 1.0)`.
    perturb : float, optional
        Std of the Gaussian perturbation added to `x0`. Set to `0` for a
        deterministic initial condition.
    discard : int, optional
        Leading transient steps to drop. Default `1000`.
    normalize : str or None, optional
        Per-channel normalization: `"standard"`, `"minmax"`, or `None`.
        Default `None` (raw values).
    seed : int, numpy.random.Generator, or None, optional
        Seed for the initial-condition perturbation. Default `0`.
    dtype : torch.dtype, optional
        Dtype of the returned tensor. Default `torch.float32` (matches
        torch's default, so the series drops straight into a model).
    device : torch.device, str, or None, optional
        Device of the returned tensor. Default `None` (CPU).

    Returns
    -------
    torch.Tensor
        Trajectory of shape `(1, n_timesteps, 3)`.

    See Also
    --------
    lorenz : The canonical chaotic forecasting benchmark.
    """
    rng = create_rng(seed)
    state = np.asarray(x0, dtype=np.float64)
    if perturb:
        state = state + perturb * rng.standard_normal(3)

    def rhs(s: np.ndarray) -> np.ndarray:
        x, y, z = s
        return np.array([-y - z, x + a * y, b + z * (x - c)])

    traj = _integrate_rk4(rhs, state, n_timesteps + discard, dt)
    series = _normalize(traj[discard:], normalize)
    return _to_tensor(series, dtype, device)

henon

henon(
    n_timesteps: int,
    *,
    a: float = 1.4,
    b: float = 0.3,
    x0: tuple[float, float] = (0.0, 0.0),
    perturb: float = 0.0,
    discard: int = 1000,
    normalize: Normalize | None = None,
    seed: int | Generator | None = 0,
    dtype: dtype = float32,
    device: device | str | None = None
) -> Tensor

Generate a Hénon-map trajectory.

The Hénon map is a two-dimensional discrete-time chaotic system:

x_{n+1} = 1 - a * x_n^2 + y_n
y_{n+1} = b * x_n
PARAMETER DESCRIPTION
n_timesteps

Number of timesteps to return (after the discarded transient).

TYPE: int

a

Quadratic coefficient in the Hénon map.

TYPE: float DEFAULT: 1.4

b

Linear feedback coefficient. The defaults select the classic chaotic regime.

TYPE: float DEFAULT: 0.3

x0

Base initial condition (x, y). Default (0.0, 0.0).

TYPE: tuple of float DEFAULT: (0.0, 0.0)

perturb

Std of the Gaussian perturbation added to x0. Default 0.0 (the map is robustly chaotic, so a fixed start suffices).

TYPE: float DEFAULT: 0.0

discard

Leading transient steps to drop. Default 1000.

TYPE: int DEFAULT: 1000

normalize

Per-channel normalization: "standard", "minmax", or None. Default None (raw values).

TYPE: str or None DEFAULT: None

seed

Seed for the initial-condition perturbation. Default 0.

TYPE: int, numpy.random.Generator, or None DEFAULT: 0

dtype

Dtype of the returned tensor. Default torch.float32 (matches torch's default, so the series drops straight into a model).

TYPE: dtype DEFAULT: float32

device

Device of the returned tensor. Default None (CPU).

TYPE: torch.device, str, or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Trajectory of shape (1, n_timesteps, 2).

Source code in src/resdag/utils/data/datasets.py
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def henon(
    n_timesteps: int,
    *,
    a: float = 1.4,
    b: float = 0.3,
    x0: tuple[float, float] = (0.0, 0.0),
    perturb: float = 0.0,
    discard: int = 1000,
    normalize: Normalize | None = None,
    seed: int | np.random.Generator | None = 0,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.Tensor:
    """Generate a Hénon-map trajectory.

    The Hénon map is a two-dimensional discrete-time chaotic system:

    ```text
    x_{n+1} = 1 - a * x_n^2 + y_n
    y_{n+1} = b * x_n
    ```

    Parameters
    ----------
    n_timesteps : int
        Number of timesteps to return (after the discarded transient).
    a : float, optional
        Quadratic coefficient in the Hénon map.
    b : float, optional
        Linear feedback coefficient. The defaults select the classic chaotic regime.
    x0 : tuple of float, optional
        Base initial condition `(x, y)`. Default `(0.0, 0.0)`.
    perturb : float, optional
        Std of the Gaussian perturbation added to `x0`. Default `0.0` (the
        map is robustly chaotic, so a fixed start suffices).
    discard : int, optional
        Leading transient steps to drop. Default `1000`.
    normalize : str or None, optional
        Per-channel normalization: `"standard"`, `"minmax"`, or `None`.
        Default `None` (raw values).
    seed : int, numpy.random.Generator, or None, optional
        Seed for the initial-condition perturbation. Default `0`.
    dtype : torch.dtype, optional
        Dtype of the returned tensor. Default `torch.float32` (matches
        torch's default, so the series drops straight into a model).
    device : torch.device, str, or None, optional
        Device of the returned tensor. Default `None` (CPU).

    Returns
    -------
    torch.Tensor
        Trajectory of shape `(1, n_timesteps, 2)`.
    """
    rng = create_rng(seed)
    state = np.asarray(x0, dtype=np.float64)
    if perturb:
        state = state + perturb * rng.standard_normal(2)

    total = n_timesteps + discard
    out = np.empty((total, 2), dtype=np.float64)
    x, y = float(state[0]), float(state[1])
    for i in range(total):
        out[i] = (x, y)
        x, y = 1.0 - a * x * x + y, b * x

    series = _normalize(out[discard:], normalize)
    return _to_tensor(series, dtype, device)

mackey_glass

mackey_glass(
    n_timesteps: int,
    *,
    tau: int = 17,
    beta: float = 0.2,
    gamma: float = 0.1,
    n: float = 10.0,
    dt: float = 1.0,
    x0: float = 1.2,
    discard: int = 1000,
    normalize: Normalize | None = None,
    seed: int | Generator | None = 0,
    dtype: dtype = float32,
    device: device | str | None = None
) -> Tensor

Generate a Mackey-Glass delay-differential-equation trajectory.

The Mackey-Glass equation is a scalar delay system whose dynamics are chaotic for tau > ~16.8:

dx/dt = beta * x(t - tau) / (1 + x(t - tau)^n) - gamma * x(t)

Integrated with the Euler method on the history buffer (the standard scheme for this benchmark). The delay tau and step dt give an effective integer lag of exactly round(tau / dt) samples, so the default tau=17 is the canonical chaotic MG-17 system.

PARAMETER DESCRIPTION
n_timesteps

Number of timesteps to return (after the discarded transient).

TYPE: int

tau

Delay. Default 17 (the canonical chaotic value).

TYPE: int DEFAULT: 17

beta

Strength of the delayed nonlinear feedback.

TYPE: float DEFAULT: 0.2

gamma

Linear decay coefficient.

TYPE: float DEFAULT: 0.1

n

Exponent in the delayed feedback denominator.

TYPE: float DEFAULT: 10.0

dt

Integration step. Default 1.0.

TYPE: float DEFAULT: 1.0

x0

Constant value of the history buffer for t <= 0. Default 1.2.

TYPE: float DEFAULT: 1.2

discard

Leading transient steps to drop. Default 1000.

TYPE: int DEFAULT: 1000

normalize

Normalization: "standard", "minmax", or None. Default None (raw values).

TYPE: str or None DEFAULT: None

seed

Accepted for signature symmetry with the other generators but unused: the trajectory is fully deterministic and draws no randomness. Default 0.

TYPE: int, numpy.random.Generator, or None DEFAULT: 0

dtype

Dtype of the returned tensor. Default torch.float32 (matches torch's default, so the series drops straight into a model).

TYPE: dtype DEFAULT: float32

device

Device of the returned tensor. Default None (CPU).

TYPE: torch.device, str, or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Trajectory of shape (1, n_timesteps, 1).

Source code in src/resdag/utils/data/datasets.py
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
540
541
542
543
544
545
546
547
548
549
550
551
def mackey_glass(
    n_timesteps: int,
    *,
    tau: int = 17,
    beta: float = 0.2,
    gamma: float = 0.1,
    n: float = 10.0,
    dt: float = 1.0,
    x0: float = 1.2,
    discard: int = 1000,
    normalize: Normalize | None = None,
    seed: int | np.random.Generator | None = 0,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.Tensor:
    """Generate a Mackey-Glass delay-differential-equation trajectory.

    The Mackey-Glass equation is a scalar delay system whose dynamics are
    chaotic for `tau > ~16.8`:

    ```text
    dx/dt = beta * x(t - tau) / (1 + x(t - tau)^n) - gamma * x(t)
    ```

    Integrated with the Euler method on the history buffer (the standard scheme
    for this benchmark). The delay `tau` and step `dt` give an effective
    integer lag of exactly `round(tau / dt)` samples, so the default
    `tau=17` is the canonical chaotic MG-17 system.

    Parameters
    ----------
    n_timesteps : int
        Number of timesteps to return (after the discarded transient).
    tau : int, optional
        Delay. Default `17` (the canonical chaotic value).
    beta : float, optional
        Strength of the delayed nonlinear feedback.
    gamma : float, optional
        Linear decay coefficient.
    n : float, optional
        Exponent in the delayed feedback denominator.
    dt : float, optional
        Integration step. Default `1.0`.
    x0 : float, optional
        Constant value of the history buffer for `t <= 0`. Default `1.2`.
    discard : int, optional
        Leading transient steps to drop. Default `1000`.
    normalize : str or None, optional
        Normalization: `"standard"`, `"minmax"`, or `None`.
        Default `None` (raw values).
    seed : int, numpy.random.Generator, or None, optional
        Accepted for signature symmetry with the other generators but unused:
        the trajectory is fully deterministic and draws no randomness. Default
        `0`.
    dtype : torch.dtype, optional
        Dtype of the returned tensor. Default `torch.float32` (matches
        torch's default, so the series drops straight into a model).
    device : torch.device, str, or None, optional
        Device of the returned tensor. Default `None` (CPU).

    Returns
    -------
    torch.Tensor
        Trajectory of shape `(1, n_timesteps, 1)`.
    """
    # ``seed`` is unused: the trajectory is fully deterministic and draws no
    # randomness, so no RNG is created (calling ``create_rng(None)`` would draw
    # from torch's global RNG as a side effect and perturb downstream torch
    # reproducibility for nothing).
    lag = max(1, round(tau / dt))
    total = n_timesteps + discard

    # Flat buffer indexed arithmetically: ``buf[lag:]`` holds the trajectory and
    # ``buf[:lag]`` is the constant history ``x0`` for ``t <= 0``. Writing the
    # value at index ``lag + i`` while reading the delayed term at index ``i``
    # gives an effective delay of exactly ``lag`` samples (the roll-buffer scheme
    # this replaces was off by one, yielding a ``lag + 1`` delay). This is also
    # ~15x faster: it drops the per-step ``np.roll`` allocation.
    buf = np.empty(total + lag, dtype=np.float64)
    buf[:lag] = float(x0)

    x_t = float(x0)
    for i in range(total):
        buf[lag + i] = x_t
        x_lag = buf[i]
        x_next = x_t + dt * (beta * x_lag / (1.0 + x_lag**n) - gamma * x_t)
        x_t = x_next

    series = _normalize(buf[lag + discard :].reshape(-1, 1), normalize)
    return _to_tensor(series, dtype, device)

narma

narma(
    n_timesteps: int,
    *,
    order: int = 10,
    alpha: float = 0.3,
    beta: float = 0.05,
    gamma: float = 1.5,
    delta: float = 0.1,
    input_low: float = 0.0,
    input_high: float = 0.5,
    discard: int = 200,
    normalize: Normalize | None = None,
    seed: int | Generator | None = 0,
    dtype: dtype = float32,
    device: device | str | None = None
) -> Tensor

Generate a NARMA (Nonlinear Auto-Regressive Moving Average) series.

NARMA-order is a standard nonlinear system-identification benchmark: a random uniform input u drives a recurrence whose output y depends on its own order past values:

y_{t+1} = alpha * y_t
          + beta * y_t * sum_{i=0}^{order-1} y_{t-i}
          + gamma * u_t * u_{t-order+1}
          + delta

Two channels are returned per timestep: the input u and the output y (so a readout can be trained to map u -> y).

PARAMETER DESCRIPTION
n_timesteps

Number of timesteps to return (after the discarded transient).

TYPE: int

order

Memory order of the recurrence. Default 10 (NARMA-10).

TYPE: int DEFAULT: 10

alpha

Coefficient of the previous output.

TYPE: float DEFAULT: 0.3

beta

Coefficient of the output-memory product.

TYPE: float DEFAULT: 0.05

gamma

Coefficient of the input product.

TYPE: float DEFAULT: 1.5

delta

Constant offset in the recurrence.

TYPE: float DEFAULT: 0.1

input_low

Lower bound of the uniform input u.

TYPE: float DEFAULT: 0.0

input_high

Upper bound of the uniform input u.

TYPE: float DEFAULT: 0.5

discard

Leading transient steps to drop. Default 200.

TYPE: int DEFAULT: 200

normalize

Per-channel normalization: "standard", "minmax", or None. Default None (NARMA is conventionally used on its native scale).

TYPE: str or None DEFAULT: None

seed

Seed for the random input (via resdag.utils.create_rng). Default 0.

TYPE: int, numpy.random.Generator, or None DEFAULT: 0

dtype

Dtype of the returned tensor. Default torch.float32 (matches torch's default, so the series drops straight into a model).

TYPE: dtype DEFAULT: float32

device

Device of the returned tensor. Default None (CPU).

TYPE: torch.device, str, or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Trajectory of shape (1, n_timesteps, 2) — columns [u, y].

Source code in src/resdag/utils/data/datasets.py
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
def narma(
    n_timesteps: int,
    *,
    order: int = 10,
    alpha: float = 0.3,
    beta: float = 0.05,
    gamma: float = 1.5,
    delta: float = 0.1,
    input_low: float = 0.0,
    input_high: float = 0.5,
    discard: int = 200,
    normalize: Normalize | None = None,
    seed: int | np.random.Generator | None = 0,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.Tensor:
    """Generate a NARMA (Nonlinear Auto-Regressive Moving Average) series.

    NARMA-`order` is a standard nonlinear system-identification benchmark: a
    random uniform input `u` drives a recurrence whose output `y` depends on
    its own `order` past values:

    ```text
    y_{t+1} = alpha * y_t
              + beta * y_t * sum_{i=0}^{order-1} y_{t-i}
              + gamma * u_t * u_{t-order+1}
              + delta
    ```

    Two channels are returned per timestep: the input `u` and the output
    `y` (so a readout can be trained to map `u -> y`).

    Parameters
    ----------
    n_timesteps : int
        Number of timesteps to return (after the discarded transient).
    order : int, optional
        Memory order of the recurrence. Default `10` (NARMA-10).
    alpha : float, optional
        Coefficient of the previous output.
    beta : float, optional
        Coefficient of the output-memory product.
    gamma : float, optional
        Coefficient of the input product.
    delta : float, optional
        Constant offset in the recurrence.
    input_low : float, optional
        Lower bound of the uniform input `u`.
    input_high : float, optional
        Upper bound of the uniform input `u`.
    discard : int, optional
        Leading transient steps to drop. Default `200`.
    normalize : str or None, optional
        Per-channel normalization: `"standard"`, `"minmax"`, or `None`.
        Default `None` (NARMA is conventionally used on its native scale).
    seed : int, numpy.random.Generator, or None, optional
        Seed for the random input (via `resdag.utils.create_rng`).
        Default `0`.
    dtype : torch.dtype, optional
        Dtype of the returned tensor. Default `torch.float32` (matches
        torch's default, so the series drops straight into a model).
    device : torch.device, str, or None, optional
        Device of the returned tensor. Default `None` (CPU).

    Returns
    -------
    torch.Tensor
        Trajectory of shape `(1, n_timesteps, 2)` — columns `[u, y]`.
    """
    rng = create_rng(seed)
    total = n_timesteps + discard
    u = rng.uniform(input_low, input_high, size=total)
    y = np.zeros(total, dtype=np.float64)

    for t in range(order, total - 1):
        y[t + 1] = (
            alpha * y[t]
            + beta * y[t] * np.sum(y[t - order + 1 : t + 1])
            + gamma * u[t] * u[t - order + 1]
            + delta
        )

    series = np.stack([u, y], axis=1)
    series = _normalize(series[discard:], normalize)
    return _to_tensor(series, dtype, device)

sine

sine(
    n_timesteps: int,
    *,
    periods: float = 20.0,
    amplitude: float = 1.0,
    phase: float = 0.0,
    offset: float = 0.0,
    noise: float = 0.0,
    discard: int = 0,
    normalize: Normalize | None = None,
    seed: int | Generator | None = 0,
    dtype: dtype = float32,
    device: device | str | None = None
) -> Tensor

Generate a (optionally noisy) sine wave.

A simple, smooth, periodic signal — useful as a sanity-check task and for illustrating the API:

y_t = offset + amplitude * sin(2*pi * periods * t / n_timesteps + phase)
PARAMETER DESCRIPTION
n_timesteps

Number of timesteps to return (after the discarded transient).

TYPE: int

periods

Number of full oscillations over the returned window. Default 20.0.

TYPE: float DEFAULT: 20.0

amplitude

Peak amplitude. Default 1.0.

TYPE: float DEFAULT: 1.0

phase

Phase offset in radians. Default 0.0.

TYPE: float DEFAULT: 0.0

offset

Additive vertical offset. Default 0.0.

TYPE: float DEFAULT: 0.0

noise

Std of additive Gaussian noise (drawn from the seeded RNG). Default 0.0.

TYPE: float DEFAULT: 0.0

discard

Leading transient steps to drop. Default 0 (a pure sine has no transient).

TYPE: int DEFAULT: 0

normalize

Normalization: "standard", "minmax", or None. Default None (raw values).

TYPE: str or None DEFAULT: None

seed

Seed for the additive noise (via resdag.utils.create_rng). Default 0.

TYPE: int, numpy.random.Generator, or None DEFAULT: 0

dtype

Dtype of the returned tensor. Default torch.float32 (matches torch's default, so the series drops straight into a model).

TYPE: dtype DEFAULT: float32

device

Device of the returned tensor. Default None (CPU).

TYPE: torch.device, str, or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Trajectory of shape (1, n_timesteps, 1).

Source code in src/resdag/utils/data/datasets.py
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
def sine(
    n_timesteps: int,
    *,
    periods: float = 20.0,
    amplitude: float = 1.0,
    phase: float = 0.0,
    offset: float = 0.0,
    noise: float = 0.0,
    discard: int = 0,
    normalize: Normalize | None = None,
    seed: int | np.random.Generator | None = 0,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.Tensor:
    """Generate a (optionally noisy) sine wave.

    A simple, smooth, periodic signal — useful as a sanity-check task and for
    illustrating the API:

    ```python
    y_t = offset + amplitude * sin(2*pi * periods * t / n_timesteps + phase)
    ```

    Parameters
    ----------
    n_timesteps : int
        Number of timesteps to return (after the discarded transient).
    periods : float, optional
        Number of full oscillations over the returned window. Default `20.0`.
    amplitude : float, optional
        Peak amplitude. Default `1.0`.
    phase : float, optional
        Phase offset in radians. Default `0.0`.
    offset : float, optional
        Additive vertical offset. Default `0.0`.
    noise : float, optional
        Std of additive Gaussian noise (drawn from the seeded RNG). Default
        `0.0`.
    discard : int, optional
        Leading transient steps to drop. Default `0` (a pure sine has no
        transient).
    normalize : str or None, optional
        Normalization: `"standard"`, `"minmax"`, or `None`.
        Default `None` (raw values).
    seed : int, numpy.random.Generator, or None, optional
        Seed for the additive noise (via `resdag.utils.create_rng`).
        Default `0`.
    dtype : torch.dtype, optional
        Dtype of the returned tensor. Default `torch.float32` (matches
        torch's default, so the series drops straight into a model).
    device : torch.device, str, or None, optional
        Device of the returned tensor. Default `None` (CPU).

    Returns
    -------
    torch.Tensor
        Trajectory of shape `(1, n_timesteps, 1)`.
    """
    rng = create_rng(seed)
    total = n_timesteps + discard
    t = np.arange(total, dtype=np.float64)
    omega = 2.0 * np.pi * periods / max(1, n_timesteps)
    y = offset + amplitude * np.sin(omega * t + phase)
    if noise:
        y = y + noise * rng.standard_normal(total)

    series = _normalize(y[discard:].reshape(-1, 1), normalize)
    return _to_tensor(series, dtype, device)

kuramoto_sivashinsky

kuramoto_sivashinsky(
    n_timesteps: int,
    *,
    n_grid: int = 64,
    length: float = 22.0,
    dt: float = 0.25,
    x0: ndarray | None = None,
    perturb: float = 1.0,
    discard: int = 1000,
    normalize: Normalize | None = None,
    seed: int | Generator | None = 0,
    dtype: dtype = float32,
    device: device | str | None = None
) -> Tensor

Generate a Kuramoto-Sivashinsky (KS) 1-D PDE trajectory.

The KS equation is the canonical spatiotemporally chaotic benchmark for reservoir computing — a 1-D field \(u(x, t)\) on a periodic domain of length L obeying

\[ u_t = -u\,u_x - u_{xx} - u_{xxxx}, \]

which develops a chaotic attractor whose number of positive Lyapunov exponents grows with L. On the standard L = 22 domain (Pathak et al. 2018) it is high-dimensionally chaotic — too large for a single global reservoir to forecast well, which is exactly what the parallel / local-state architecture (resdag.models.parallel_esn) targets.

Integration uses the fourth-order exponential time-differencing Runge-Kutta scheme ETDRK4 (Kassam & Trefethen 2005) in Fourier space — the standard, stiffly-accurate integrator for KS — so the linear \(-u_{xx} - u_{xxxx}\) term is handled exactly and only the nonlinear advection is stepped.

The returned trajectory is the field sampled on the n_grid spatial points, so the output has n_grid feature channels: shape (1, n_timesteps, n_grid).

PARAMETER DESCRIPTION
n_timesteps

Number of timesteps to return (after the discarded transient).

TYPE: int

n_grid

Number of spatial grid points (the feature dimension D). Should be even for the real FFT grid. Default 64.

TYPE: int DEFAULT: 64

length

Domain length L (periodic). Default 22.0 — the canonical parallel-RC benchmark size. The Lyapunov exponent in resdag.metrics.CANONICAL_LAMBDA_MAX is only valid for this value.

TYPE: float DEFAULT: 22.0

dt

Integration / sampling step. Default 0.25.

TYPE: float DEFAULT: 0.25

x0

Initial field of shape (n_grid,). None (default) uses the classic cos(2*pi*x/L) * (1 + sin(2*pi*x/L)) seed.

TYPE: ndarray DEFAULT: None

perturb

Std of a Gaussian perturbation added to the initial field (drawn from the seeded RNG), breaking symmetry so seeds give distinct trajectories on the same attractor. Set to 0 for a fully deterministic start. Default 1.0.

TYPE: float DEFAULT: 1.0

discard

Leading transient steps to drop so the trajectory sits on the attractor. Default 1000.

TYPE: int DEFAULT: 1000

normalize

Per-channel normalization: "standard", "minmax", or None. Default None (KS is conventionally used on its native scale, and the channels are already comparable across the homogeneous spatial grid).

TYPE: str or None DEFAULT: None

seed

Seed for the initial-field perturbation (via resdag.utils.create_rng). Default 0.

TYPE: int, numpy.random.Generator, or None DEFAULT: 0

dtype

Dtype of the returned tensor. Default torch.float32.

TYPE: dtype DEFAULT: float32

device

Device of the returned tensor. Default None (CPU).

TYPE: torch.device, str, or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

Trajectory of shape (1, n_timesteps, n_grid) — the KS field sampled on the spatial grid at each timestep.

References

A.-K. Kassam and L. N. Trefethen, "Fourth-order time-stepping for stiff PDEs," SIAM J. Sci. Comput. 26(4), 1214-1233 (2005).

J. Pathak, B. Hunt, M. Girvan, Z. Lu, and E. Ott, "Model-Free Prediction of Large Spatiotemporally Chaotic Systems from Data: A Reservoir Computing Approach," Phys. Rev. Lett. 120, 024102 (2018).

See Also

resdag.models.parallel_esn : Parallel local-state reservoir for KS / large spatiotemporal systems.

Source code in src/resdag/utils/data/datasets.py
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
def kuramoto_sivashinsky(
    n_timesteps: int,
    *,
    n_grid: int = 64,
    length: float = 22.0,
    dt: float = 0.25,
    x0: np.ndarray | None = None,
    perturb: float = 1.0,
    discard: int = 1000,
    normalize: Normalize | None = None,
    seed: int | np.random.Generator | None = 0,
    dtype: torch.dtype = torch.float32,
    device: torch.device | str | None = None,
) -> torch.Tensor:
    r"""Generate a Kuramoto-Sivashinsky (KS) 1-D PDE trajectory.

    The KS equation is the canonical *spatiotemporally chaotic* benchmark for
    reservoir computing — a 1-D field $u(x, t)$ on a periodic domain of
    length `L` obeying

    $$
    u_t = -u\,u_x - u_{xx} - u_{xxxx},
    $$

    which develops a chaotic attractor whose number of positive Lyapunov
    exponents grows with `L`.  On the standard `L = 22` domain (Pathak et
    al. 2018) it is high-dimensionally chaotic — too large for a single global
    reservoir to forecast well, which is exactly what the parallel / local-state
    architecture (`resdag.models.parallel_esn`) targets.

    Integration uses the fourth-order exponential time-differencing Runge-Kutta
    scheme **ETDRK4** (Kassam & Trefethen 2005) in Fourier space — the standard,
    stiffly-accurate integrator for KS — so the linear $-u_{xx} - u_{xxxx}$
    term is handled exactly and only the nonlinear advection is stepped.

    The returned trajectory is the field sampled on the `n_grid` spatial
    points, so the output has `n_grid` feature channels: shape
    `(1, n_timesteps, n_grid)`.

    Parameters
    ----------
    n_timesteps : int
        Number of timesteps to return (after the discarded transient).
    n_grid : int, optional
        Number of spatial grid points (the feature dimension `D`).  Should be
        even for the real FFT grid.  Default `64`.
    length : float, optional
        Domain length `L` (periodic).  Default `22.0` — the canonical
        parallel-RC benchmark size.  The Lyapunov exponent in
        `resdag.metrics.CANONICAL_LAMBDA_MAX` is only valid for this value.
    dt : float, optional
        Integration / sampling step.  Default `0.25`.
    x0 : numpy.ndarray, optional
        Initial field of shape `(n_grid,)`.  `None` (default) uses the
        classic `cos(2*pi*x/L) * (1 + sin(2*pi*x/L))` seed.
    perturb : float, optional
        Std of a Gaussian perturbation added to the initial field (drawn from the
        seeded RNG), breaking symmetry so seeds give distinct trajectories on the
        same attractor.  Set to `0` for a fully deterministic start.  Default
        `1.0`.
    discard : int, optional
        Leading transient steps to drop so the trajectory sits on the attractor.
        Default `1000`.
    normalize : str or None, optional
        Per-channel normalization: `"standard"`, `"minmax"`, or `None`.
        Default `None` (KS
        is conventionally used on its native scale, and the channels are already
        comparable across the homogeneous spatial grid).
    seed : int, numpy.random.Generator, or None, optional
        Seed for the initial-field perturbation (via
        `resdag.utils.create_rng`).  Default `0`.
    dtype : torch.dtype, optional
        Dtype of the returned tensor.  Default `torch.float32`.
    device : torch.device, str, or None, optional
        Device of the returned tensor.  Default `None` (CPU).

    Returns
    -------
    torch.Tensor
        Trajectory of shape `(1, n_timesteps, n_grid)` — the KS field sampled
        on the spatial grid at each timestep.

    References
    ----------
    A.-K. Kassam and L. N. Trefethen, "Fourth-order time-stepping for stiff
    PDEs," SIAM J. Sci. Comput. 26(4), 1214-1233 (2005).

    J. Pathak, B. Hunt, M. Girvan, Z. Lu, and E. Ott, "Model-Free Prediction of
    Large Spatiotemporally Chaotic Systems from Data: A Reservoir Computing
    Approach," Phys. Rev. Lett. 120, 024102 (2018).

    See Also
    --------
    resdag.models.parallel_esn : Parallel local-state reservoir for KS / large
        spatiotemporal systems.
    """
    rng = create_rng(seed)

    # Spatial grid and initial field on the periodic domain [0, L).
    x = length * np.arange(n_grid, dtype=np.float64) / n_grid
    if x0 is None:
        u = np.cos(2.0 * np.pi * x / length) * (1.0 + np.sin(2.0 * np.pi * x / length))
    else:
        u = np.asarray(x0, dtype=np.float64).reshape(-1)
        if u.shape[0] != n_grid:
            raise ValueError(
                f"kuramoto_sivashinsky: x0 must have shape ({n_grid},) to match n_grid, "
                f"got shape {u.shape}."
            )
    if perturb:
        u = u + perturb * rng.standard_normal(n_grid)

    v = np.fft.rfft(u)

    # Fourier wavenumbers k for the rfft layout (0 .. n_grid/2).
    k = 2.0 * np.pi * np.fft.rfftfreq(n_grid, d=length / n_grid)
    # Linear operator L(k) = k^2 - k^4 (the -u_xx - u_xxxx term in Fourier space).
    lin = k**2 - k**4

    # ETDRK4 precomputed coefficients (Kassam & Trefethen 2005).  The phi-function
    # integrals are evaluated by averaging over a circle of ``m`` points in the
    # complex plane to avoid cancellation error when lin*dt is small.
    e = np.exp(dt * lin)
    e2 = np.exp(dt * lin / 2.0)
    m = 32
    roots = np.exp(1j * np.pi * (np.arange(1, m + 1) - 0.5) / m)
    lr = dt * lin[:, None] + roots[None, :]
    q = dt * ((np.exp(lr / 2.0) - 1.0) / lr).mean(axis=1).real
    f1 = dt * ((-4.0 - lr + np.exp(lr) * (4.0 - 3.0 * lr + lr**2)) / lr**3).mean(axis=1).real
    f2 = dt * ((2.0 + lr + np.exp(lr) * (-2.0 + lr)) / lr**3).mean(axis=1).real
    f3 = dt * ((-4.0 - 3.0 * lr - lr**2 + np.exp(lr) * (4.0 - lr)) / lr**3).mean(axis=1).real

    # Nonlinear term N(v) = -0.5 * i * k * FFT(IFFT(v)^2).
    g = -0.5j * k

    def nonlinear(vh: np.ndarray) -> np.ndarray:
        real = np.fft.irfft(vh, n=n_grid)
        return g * np.fft.rfft(real**2)

    total = n_timesteps + discard
    out = np.empty((total, n_grid), dtype=np.float64)
    for i in range(total):
        out[i] = np.fft.irfft(v, n=n_grid)
        # One ETDRK4 step.
        nv = nonlinear(v)
        a = e2 * v + q * nv
        na = nonlinear(a)
        b = e2 * v + q * na
        nb = nonlinear(b)
        c = e2 * a + q * (2.0 * nb - nv)
        nc = nonlinear(c)
        v = e * v + nv * f1 + 2.0 * (na + nb) * f2 + nc * f3

    series = _normalize(out[discard:], normalize)
    return _to_tensor(series, dtype, device)

Default sampling intervals and reference exponent lookup remain available from the existing data utility namespace; explicitly supplied system or sampling parameters take precedence in an experiment.

DATASET_DT module-attribute

DATASET_DT: dict[str, float] = {
    "lorenz": 0.02,
    "rossler": 0.05,
    "henon": 1.0,
    "mackey_glass": 1.0,
    "narma": 1.0,
    "sine": 1.0,
    "kuramoto_sivashinsky": 0.25,
}

dataset_lambda_max

dataset_lambda_max(name: str, **params: float) -> float | None

Return the canonical largest Lyapunov exponent for a built-in generator.

Reads the literature tables in resdag.metrics — imported lazily here so the dataset module and the metrics module never form an import cycle (metrics owns the constant tables; this module is imported by metrics' dt/lambda helpers only through the duplicated DATASET_DT).

PARAMETER DESCRIPTION
name

Generator name (case-insensitive): "lorenz", "rossler", or "mackey_glass". Non-chaotic generators ("sine", "narma") have no Lyapunov exponent and return None.

TYPE: str

**params

Generator parameters; tau= selects the Mackey-Glass value (default 17).

TYPE: float DEFAULT: {}

RETURNS DESCRIPTION
float or None

The canonical \(\lambda_\mathrm{max}\), or None for a non-chaotic generator or an unknown / non-canonical tau.

Examples:

>>> from resdag.utils.data import dataset_lambda_max
>>> dataset_lambda_max("lorenz")
0.9056
>>> dataset_lambda_max("mackey_glass", tau=17)
0.0086
>>> dataset_lambda_max("sine") is None
True
Source code in src/resdag/utils/data/datasets.py
 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
def dataset_lambda_max(name: str, **params: float) -> float | None:
    """Return the canonical largest Lyapunov exponent for a built-in generator.

    Reads the literature tables in `resdag.metrics` — imported lazily here
    so the dataset module and the metrics module never form an import cycle
    (metrics owns the constant tables; this module is imported *by* metrics'
    dt/lambda helpers only through the duplicated `DATASET_DT`).

    Parameters
    ----------
    name : str
        Generator name (case-insensitive): `"lorenz"`, `"rossler"`, or
        `"mackey_glass"`.  Non-chaotic generators (`"sine"`, `"narma"`)
        have no Lyapunov exponent and return `None`.
    **params
        Generator parameters; `tau=` selects the Mackey-Glass value (default
        `17`).

    Returns
    -------
    float or None
        The canonical $\\lambda_\\mathrm{max}$, or `None` for a
        non-chaotic generator or an unknown / non-canonical `tau`.

    Examples
    --------
    >>> from resdag.utils.data import dataset_lambda_max
    >>> dataset_lambda_max("lorenz")
    0.9056
    >>> dataset_lambda_max("mackey_glass", tau=17)
    0.0086
    >>> dataset_lambda_max("sine") is None
    True
    """
    from resdag.metrics.lyapunov import CANONICAL_LAMBDA_MAX, MACKEY_GLASS_LAMBDA

    key = name.lower()
    if key in CANONICAL_LAMBDA_MAX:
        return CANONICAL_LAMBDA_MAX[key]
    if key in ("mackey_glass", "mackeyglass", "mackey-glass"):
        tau = int(params.get("tau", 17))
        return MACKEY_GLASS_LAMBDA.get(tau)
    return None