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:
|
warmup_steps
|
Number of steps for reservoir warmup/synchronization.
TYPE:
|
train_steps
|
Number of training steps (after warmup).
TYPE:
|
val_steps
|
Number of validation steps. If None, uses all remaining data.
TYPE:
|
discard_steps
|
Number of initial steps to discard (e.g., initial transients).
TYPE:
|
normalize
|
Whether to normalize data. If True, statistics are computed from training data and applied to all splits globally.
TYPE:
|
norm_method
|
Normalization method if normalize=True.
TYPE:
|
return_stats
|
If True, append the fitted normalization statistics as a 6th return
element so the normalize -> forecast -> report loop can be closed via
TYPE:
|
alignment
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
warmup
|
Warmup data, shape (B, warmup_steps, D).
TYPE:
|
train
|
Training input, shape (B, train_steps, D).
TYPE:
|
target
|
Training target (shifted by 1), shape (B, train_steps, D).
TYPE:
|
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:
|
val
|
Validation data, shape (B, val_steps, D). Starts at
TYPE:
|
stats
|
Only returned when
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
| WARNS | DESCRIPTION |
|---|---|
UserWarning
|
If the resulting validation window is empty ( |
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 | |
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:
|
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:
|
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:
|
| RETURNS | DESCRIPTION |
|---|---|
normalized
|
Normalized data with same shape as input.
TYPE:
|
stats
|
Statistics used for normalization (for applying to other data).
TYPE:
|
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 | |
denormalize_data
¶
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:
|
method
|
Normalization method that produced
TYPE:
|
stats
|
Fitted statistics returned by
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Data restored to the original scale, with the same shape as |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
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 | |
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:
|
warmup_steps
|
Number of warmup steps.
TYPE:
|
train_steps
|
Number of training steps.
TYPE:
|
val_steps
|
Number of validation steps.
TYPE:
|
discard_steps
|
Initial steps to discard.
TYPE:
|
normalize
|
Whether to normalize data.
TYPE:
|
norm_method
|
Normalization method.
TYPE:
|
return_stats
|
If True, append the fitted normalization statistics as a 6th return
element (
TYPE:
|
dtype
|
Desired tensor dtype. If None, uses
TYPE:
|
alignment
|
Forecast timing convention,
TYPE:
|
**load_kwargs
|
Additional arguments passed to load_file (e.g., key for .npz).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ESNDataSplits or ESNDataSplitsWithStats
|
Tuple of (warmup, train, target, forecast_warmup, val) tensors, with a
trailing |
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 | |
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 byhorizonsteps, so windowicovers source steps[start, start + window_len)for the input and[start + horizon, start + horizon + window_len)for the target. - Regression (external
targetsgiven): the target is the matching window sliced fromtargetsat the same source positions as the input (horizonis 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
TYPE:
|
window_len
|
Number of timesteps in each input/target window. Must be positive.
TYPE:
|
horizon
|
Forecast offset: the target window is the input window shifted forward
by
TYPE:
|
stride
|
Step between successive window start positions within a trajectory. Must be positive.
TYPE:
|
washout
|
Number of leading steps in each window the caller should exclude from
the loss (transient reservoir warmup). Reported per item; must satisfy
TYPE:
|
targets
|
External regression targets aligned step-for-step with
TYPE:
|
stats
|
Pre-computed input normalization statistics from
TYPE:
|
norm_method
|
Normalization method matching
TYPE:
|
target_stats
|
Separate fitted normalization for external regression targets. Both must be supplied together; by default external targets are returned unchanged.
TYPE:
|
target_norm_method
|
Separate fitted normalization for external regression targets. Both must be supplied together; by default external targets are returned unchanged.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
window_len |
Window length.
TYPE:
|
horizon |
Forecast offset (forecasting mode only).
TYPE:
|
stride |
Window start spacing.
TYPE:
|
washout |
Leading steps to exclude from the loss.
TYPE:
|
feature_dim |
Input feature dimension
TYPE:
|
target_dim |
Target feature dimension (equals
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
For invalid |
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 | |
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
TYPE:
|
batch_size
|
Number of windows per batch.
TYPE:
|
window_len
|
Window length (timesteps per input/target window).
TYPE:
|
horizon
|
Forecast offset (ignored when
TYPE:
|
stride
|
Spacing between window starts within a trajectory.
TYPE:
|
washout
|
Leading steps per window to exclude from the loss.
TYPE:
|
targets
|
External regression targets aligned with
TYPE:
|
stats
|
Pre-computed normalization statistics (with
TYPE:
|
norm_method
|
Normalization method matching
TYPE:
|
target_stats
|
Separate normalization for external regression targets; see
TYPE:
|
target_norm_method
|
Separate normalization for external regression targets; see
TYPE:
|
shuffle
|
Whether to shuffle window order each epoch.
TYPE:
|
drop_last
|
Whether to drop the final, smaller-than-
TYPE:
|
num_workers
|
Number of worker processes for data loading.
TYPE:
|
**dataloader_kwargs
|
Extra keyword arguments forwarded to
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataLoader
|
Loader yielding |
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 | |
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 time series data from a file, detecting format from extension.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to the data file. Supported extensions: .csv, .npy, .npz, .nc |
dtype
|
Desired tensor dtype. If None, uses
TYPE:
|
**kwargs
|
Additional arguments passed to the specific loader (e.g., key for .npz).
TYPE:
|
| 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 | |
load_csv
¶
Load time series data from a CSV file.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to the CSV file. |
delimiter
|
Field delimiter.
TYPE:
|
dtype
|
Desired tensor dtype. If None, uses
TYPE:
|
| 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 ofNfeatures); - a single-column,
T-row file ->(T, 1)->(1, T, 1)(Ttimesteps 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 | |
load_npy
¶
Load time series data from a NumPy .npy file.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to the .npy file. |
dtype
|
Desired tensor dtype. If None, uses
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Data tensor with shape (B, T, D). |
| WARNS | DESCRIPTION |
|---|---|
UserWarning
|
If the stored array is 1D |
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 | |
load_npz
¶
Load time series data from a NumPy .npz file.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to the .npz file. |
key
|
Key to access the data array in the .npz file.
TYPE:
|
dtype
|
Desired tensor dtype. If None, uses
TYPE:
|
| 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 |
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 | |
load_nc
¶
Load time series data from a NetCDF (.nc) file.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to the .nc file. |
dtype
|
Desired tensor dtype. If None, uses
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Data tensor with shape (B, T, D). |
| WARNS | DESCRIPTION |
|---|---|
UserWarning
|
If the stored array is 1D |
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 | |
save_csv
¶
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:
|
path
|
Path to save the CSV file. |
delimiter
|
Field delimiter.
TYPE:
|
| 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 | |
save_npy
¶
save_npy(data: Tensor, path: PathLike) -> None
Save data to a NumPy .npy file.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Data to save.
TYPE:
|
path
|
Path to save the .npy file. |
Source code in src/resdag/data/io.py
362 363 364 365 366 367 368 369 370 371 372 | |
save_npz
¶
Save data to a NumPy .npz file.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Data to save.
TYPE:
|
path
|
Path to save the .npz file. |
key
|
Key to use when storing the data.
TYPE:
|
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 | |
save_nc
¶
save_nc(data: Tensor, path: PathLike) -> None
Save data to a NetCDF (.nc) file.
| PARAMETER | DESCRIPTION |
|---|---|
data
|
Data to save.
TYPE:
|
path
|
Path to save the .nc file. |
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 | |
list_files
¶
List files in a directory, optionally filtering by extension.
| PARAMETER | DESCRIPTION |
|---|---|
directory
|
Path to the directory. |
extensions
|
List of extensions to filter (e.g., [".csv", ".npy"]). If None, returns all files.
TYPE:
|
| 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 | |
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:
|
dt
|
Integration step (RK4). Default
TYPE:
|
sigma
|
Lorenz Prandtl parameter.
TYPE:
|
rho
|
Lorenz Rayleigh parameter. The defaults select the classic chaotic regime.
TYPE:
|
beta
|
Lorenz geometric parameter.
TYPE:
|
x0
|
Base initial condition
TYPE:
|
perturb
|
Std of the Gaussian perturbation added to
TYPE:
|
discard
|
Leading transient steps to drop so the trajectory sits on the
attractor. Default
TYPE:
|
normalize
|
Per-channel normalization:
TYPE:
|
seed
|
Seed for the initial-condition perturbation (via
TYPE:
|
dtype
|
Dtype of the returned tensor. Default
TYPE:
|
device
|
Device of the returned tensor. Default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Trajectory of shape |
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 | |
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:
|
dt
|
Integration step (RK4). Default
TYPE:
|
a
|
Linear growth coefficient in the Rössler y equation.
TYPE:
|
b
|
Constant forcing in the Rössler z equation.
TYPE:
|
c
|
Rössler z damping parameter. The defaults select the classic chaotic regime.
TYPE:
|
x0
|
Base initial condition
TYPE:
|
perturb
|
Std of the Gaussian perturbation added to
TYPE:
|
discard
|
Leading transient steps to drop. Default
TYPE:
|
normalize
|
Per-channel normalization:
TYPE:
|
seed
|
Seed for the initial-condition perturbation. Default
TYPE:
|
dtype
|
Dtype of the returned tensor. Default
TYPE:
|
device
|
Device of the returned tensor. Default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Trajectory of shape |
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 | |
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:
|
a
|
Quadratic coefficient in the Hénon map.
TYPE:
|
b
|
Linear feedback coefficient. The defaults select the classic chaotic regime.
TYPE:
|
x0
|
Base initial condition
TYPE:
|
perturb
|
Std of the Gaussian perturbation added to
TYPE:
|
discard
|
Leading transient steps to drop. Default
TYPE:
|
normalize
|
Per-channel normalization:
TYPE:
|
seed
|
Seed for the initial-condition perturbation. Default
TYPE:
|
dtype
|
Dtype of the returned tensor. Default
TYPE:
|
device
|
Device of the returned tensor. Default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Trajectory of shape |
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 | |
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:
|
tau
|
Delay. Default
TYPE:
|
beta
|
Strength of the delayed nonlinear feedback.
TYPE:
|
gamma
|
Linear decay coefficient.
TYPE:
|
n
|
Exponent in the delayed feedback denominator.
TYPE:
|
dt
|
Integration step. Default
TYPE:
|
x0
|
Constant value of the history buffer for
TYPE:
|
discard
|
Leading transient steps to drop. Default
TYPE:
|
normalize
|
Normalization:
TYPE:
|
seed
|
Accepted for signature symmetry with the other generators but unused:
the trajectory is fully deterministic and draws no randomness. Default
TYPE:
|
dtype
|
Dtype of the returned tensor. Default
TYPE:
|
device
|
Device of the returned tensor. Default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Trajectory of shape |
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 | |
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:
|
order
|
Memory order of the recurrence. Default
TYPE:
|
alpha
|
Coefficient of the previous output.
TYPE:
|
beta
|
Coefficient of the output-memory product.
TYPE:
|
gamma
|
Coefficient of the input product.
TYPE:
|
delta
|
Constant offset in the recurrence.
TYPE:
|
input_low
|
Lower bound of the uniform input
TYPE:
|
input_high
|
Upper bound of the uniform input
TYPE:
|
discard
|
Leading transient steps to drop. Default
TYPE:
|
normalize
|
Per-channel normalization:
TYPE:
|
seed
|
Seed for the random input (via
TYPE:
|
dtype
|
Dtype of the returned tensor. Default
TYPE:
|
device
|
Device of the returned tensor. Default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Trajectory of shape |
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 | |
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:
|
periods
|
Number of full oscillations over the returned window. Default
TYPE:
|
amplitude
|
Peak amplitude. Default
TYPE:
|
phase
|
Phase offset in radians. Default
TYPE:
|
offset
|
Additive vertical offset. Default
TYPE:
|
noise
|
Std of additive Gaussian noise (drawn from the seeded RNG). Default
TYPE:
|
discard
|
Leading transient steps to drop. Default
TYPE:
|
normalize
|
Normalization:
TYPE:
|
seed
|
Seed for the additive noise (via
TYPE:
|
dtype
|
Dtype of the returned tensor. Default
TYPE:
|
device
|
Device of the returned tensor. Default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Trajectory of shape |
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 | |
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
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:
|
n_grid
|
Number of spatial grid points (the feature dimension
TYPE:
|
length
|
Domain length
TYPE:
|
dt
|
Integration / sampling step. Default
TYPE:
|
x0
|
Initial field of shape
TYPE:
|
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
TYPE:
|
discard
|
Leading transient steps to drop so the trajectory sits on the attractor.
Default
TYPE:
|
normalize
|
Per-channel normalization:
TYPE:
|
seed
|
Seed for the initial-field perturbation (via
TYPE:
|
dtype
|
Dtype of the returned tensor. Default
TYPE:
|
device
|
Device of the returned tensor. Default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Trajectory of shape |
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 | |
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
¶
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):
TYPE:
|
**params
|
Generator parameters;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float or None
|
The canonical \(\lambda_\mathrm{max}\), or |
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 | |