Reference
Utilities¶
Data loading and ESN-shaped splitting, seeded RNG construction, and the
echo-state-property diagnostic. load_file and prepare_esn_data are
re-exported at resdag.utils for convenience; their canonical home is
resdag.utils.data. The ESP index, esp_index, is likewise re-exported at
resdag.utils and at the top level, so all three of these work:
from resdag import esp_index
from resdag.utils import esp_index
from resdag.utils.states import esp_index # canonical home
utils
¶
Utility Functions¶
This module provides utility functions for data loading, preparation, and general operations in resdag.
Submodules
data Data loading and preparation utilities for ESN training. states Reservoir-state diagnostics (the Echo State Property index).
| FUNCTION | DESCRIPTION |
|---|---|
seed_everything |
Seed Python, NumPy, and torch (CPU + CUDA) for reproducible runs. |
resolve_device |
Resolve a device spec ( |
create_rng |
Create a NumPy random number generator with optional seed. |
create_torch_generator |
Create a torch |
coerce_seed_to_int |
Reduce an int/ |
SeedLike |
Type alias for accepted seed inputs ( |
DeviceLike |
Type alias for accepted device specs ( |
load_file |
Load a time series from disk (re-exported from |
prepare_esn_data |
Split a series into ESN train/forecast segments (re-exported from
|
normalize_data |
Normalize a series and return the fitted statistics (re-exported from
|
denormalize_data |
Invert a normalization back to the original scale (re-exported from
|
lorenz, rossler, henon, mackey_glass, narma, sine |
Canonical reservoir-computing dataset generators (re-exported from
|
esp_index |
Echo State Property index — the library's signature stability diagnostic
(re-exported from |
Examples:
>>> import resdag as rd
>>> data = rd.utils.load_file("timeseries.csv")
>>> warmup, train, target, f_warmup, val = rd.utils.prepare_esn_data(
... data, warmup_steps=100, train_steps=500, val_steps=200
... )
See Also
resdag.utils.data : Data loading and preparation. resdag.utils.states : Echo State Property diagnostics.
create_rng
¶
Create a NumPy random number generator.
This is the NumPy-RNG-for-graph-topology helper: it is threaded into the
graph builders and named initializers, which draw exclusively from NumPy.
For whole-program reproducibility (torch + NumPy + random at once) use
:func:seed_everything instead; for a torch :class:~torch.Generator for
weight/bias draws use :func:create_torch_generator.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
If int, used as seed for a new Generator.
If Generator, returned as-is.
If None, the seed is derived from torch's global RNG so that
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Generator
|
A NumPy random number generator. |
Notes
When seed is None the numpy seed is sampled from torch's global RNG
via torch.randint. This advances the torch global RNG state, but ties
every NumPy draw to torch.manual_seed for end-to-end reproducibility.
See Also
seed_everything : Seed torch, NumPy, and random in one call.
create_torch_generator : Build a torch Generator for weight draws.
Source code in src/resdag/utils/general.py
create_torch_generator
¶
Create a torch :class:~torch.Generator for reproducible weight draws.
Used for the default nn.init weight/bias draws inside reservoir cells so
that a single seed deterministically fixes every parameter without
touching (and without depending on the prior state of) torch's global RNG.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
If
TYPE:
|
device
|
Device for the new generator. Ignored when
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Generator
|
A generator suitable for passing to |
Notes
When seed is None the integer seed is sampled from torch's global RNG
via torch.randint, advancing the global state but tying the draws to
torch.manual_seed for end-to-end reproducibility.
Source code in src/resdag/utils/general.py
coerce_seed_to_int
¶
coerce_seed_to_int(seed: SeedLike) -> int | None
Reduce a torch/int/None seed to a plain int seed (or None).
The NumPy-backed graph builders and named initializers thread an integer
(or None) seed down to :func:create_rng. A :class:torch.Generator
cannot be passed there directly, so this helper extracts a deterministic
integer from its initial seed — two generators created with the same
manual_seed therefore yield the same int, keeping the topology a pure
function of the generator.
| PARAMETER | DESCRIPTION |
|---|---|
seed
|
Seed in any of the accepted forms.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int or None
|
|
Source code in src/resdag/utils/general.py
data
¶
Data Loading and Preparation (compatibility shim)¶
.. deprecated:: 0.7.0
The canonical home for data preparation and file I/O is now
:mod:resdag.data. This module re-exports those symbols unchanged for
back-compat, so from resdag.utils.data import prepare_esn_data (etc.)
keeps working. New code should import from :mod:resdag.data.
The re-exported callables are the same function objects as their
:mod:resdag.data counterparts, so identity checks hold::
resdag.utils.data.prepare_esn_data is resdag.data.prepare_esn_data # True
The canonical dataset generators (:func:lorenz, :func:rossler, …) still
live here and are re-exported by :mod:resdag.datasets.
File I/O Functions
load_file Auto-detect format and load time series data. load_csv, load_npy, load_npz, load_nc Format-specific loaders. save_csv, save_npy, save_npz, save_nc Save data in respective formats. list_files List files matching a pattern.
Data Preparation Functions
prepare_esn_data Split time series into warmup, train, target, f_warmup, val. normalize_data Normalize data using various methods. denormalize_data Invert a normalization, mapping data back to its original scale. load_and_prepare Load and prepare data in one step.
Canonical Dataset Generators
lorenz, rossler Chaotic continuous-time attractors (RK4 integration). henon Chaotic discrete-time map. mackey_glass Chaotic delay-differential-equation series. narma Nonlinear system-identification benchmark (input/output series). sine Simple periodic signal for sanity checks.
Each generator returns a (1, T, D) tensor, is seedable via create_rng,
supports a transient/discard period, and supports optional normalization.
Examples:
Loading and preparing data (canonical home is :mod:resdag.data):
>>> from resdag.data import load_file, prepare_esn_data
>>> data = load_file("lorenz.csv")
>>> warmup, train, target, f_warmup, val = prepare_esn_data(
... data, warmup_steps=100, train_steps=500, val_steps=200, normalize="minmax"
... )
Generating a canonical benchmark series:
>>> from resdag.datasets import lorenz
>>> series = lorenz(2000) # (1, 2000, 3) — chaotic Lorenz-63 trajectory
See Also
resdag.data : Canonical home for data preparation, file I/O, and streaming windows. resdag.datasets : Canonical benchmark time-series generators.
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
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
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
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
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
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
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
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
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
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
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) -> 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 training for forecast initialization 5. Validation: Held-out data for testing, starting one step after the train window so it aligns with the (purely autoregressive) forecast.
Data layout (train_end = warmup_steps + train_steps)::
[discard][warmup][------- train -------][s][------ val ------]
s is data[train_end]: the autoregressive seam — the final training
target and the value the forecast warmup's last output predicts (the seed
the forecast consumes). It is intentionally excluded from val, 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
:func:
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 training for forecast init, shape (B, warmup_steps, D).
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
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | |
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.
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
load_and_prepare
¶
load_and_prepare(paths: str | list[str], 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, **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:
|
**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
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 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 | |
states
¶
State management and analysis utilities for reservoir layers.
esp_index
¶
esp_index(model: 'ESNModel', feedback_seq: Tensor, *driving_seqs: Tensor, history: bool = False, iterations: int = 10, transient: int = 0, window: int | None = None, relative: bool = False, chunk_size: int | None = None, verbose: bool = True) -> Union[dict[str, list[Tensor]], Tuple[dict[str, list[Tensor]], dict[str, list[Tensor]]]]
Compute the Echo State Property (ESP) index for reservoir layers.
The ESP index measures how quickly trajectories from different initial
states converge when driven by the same input. All
:class:~resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer
reservoirs are discovered automatically, so the diagnostic applies equally
to ESN, NG-RC, and any future custom-cell reservoir.
Random restarts are drawn through each reservoir's public
:meth:~resdag.layers.reservoirs.base_reservoir.BaseReservoirLayer.set_random_state,
which samples a standard-normal state — the same convention as
:meth:~resdag.core.ESNModel.set_random_reservoir_states. The index is
therefore directly comparable to states produced elsewhere in the library.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Model containing reservoir layers.
TYPE:
|
feedback_seq
|
Feedback sequence, shape
TYPE:
|
*driving_seqs
|
Optional driving sequences in model input order.
TYPE:
|
history
|
If True, return full distance history over time.
TYPE:
|
iterations
|
Number of random initial states to average over.
TYPE:
|
transient
|
Timesteps to discard from sequence start.
TYPE:
|
window
|
Length of the trailing window over which the index is averaged. By
default (
TYPE:
|
relative
|
If True, normalise each per-step distance by the corresponding
base-state norm,
TYPE:
|
chunk_size
|
Maximum number of random restarts run together in a single batched
forward pass. All restarts are statistically independent and differ
only in their initial state, so they are folded into the batch
dimension and evaluated in one forward pass instead of
TYPE:
|
verbose
|
Print progress and skip messages.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict or tuple
|
If Reservoirs whose ESP is undefined (no randomisable state) are omitted from both dictionaries. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Notes
For LINEAR systems (identity activation), input does NOT affect ESP because the input contribution cancels out in the state difference. This is mathematically correct behavior.
State is never mutated by direct assignment. The zero base orbit is set
via res.reset_state(batch_size=...) and the random restarts via
res.set_random_state(), so each cell's own shape contract (2-D for
ESN, 3-D delay buffer for NG-RC) is honoured and validated by the public
state-management API.
The caller's reservoir states are saved before the computation and
restored afterwards (even on error), so calling esp_index never leaves
the model's reservoirs in a mutated (random) state.
Batched restarts. The iterations random restarts are statistically
independent and differ only in their initial state, so they are folded into
the batch dimension: the feedback (and any drivers) are tiled iterations
times, one random initial state is composed per restart into a single
(batch * iterations, ...) state, and the whole ensemble is evaluated in
one forward pass rather than iterations sequential passes. The
random restarts are drawn in exactly the same order as the sequential loop
(outer over restarts, inner over reservoirs), so the initial states are
bit-identical to the sequential computation. The reservoir outputs — and
hence the returned index — match the sequential value to floating-point
rounding (typically < 1e-6 relative), the only difference being the
reassociation of a wider batched matmul; the result is fully deterministic
under a fixed seed. (If a reservoir cell injects per-step state noise in
training mode, noise > 0, the batched noise draws differ from the
sequential ones; the index remains a valid, seed-deterministic stochastic
diagnostic but is no longer numerically identical. Run the model in eval
mode, the default for a diagnostic, to disable noise entirely.)
Examples:
Score only the asymptotic regime with a scale-free statistic::
idx = esp_index(model, feedback, window=50, relative=True)
See Also
resdag.core.ESNModel.set_random_reservoir_states : Source of the standard-normal restart convention used here.
Source code in src/resdag/utils/states/esp_index.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 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 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | |
DataLoader path¶
TimeSeriesWindowDataset and make_dataloader (both in resdag.data, and
re-exported at the top level) are the windowed-DataLoader training path — see
Work · Streaming & DataLoaders for the worked
loops. The time-series generators in resdag.datasets (lorenz, rossler,
henon, mackey_glass, narma, sine) each return a (1, n_timesteps,
features) tensor and take n_timesteps as their first positional argument.
data
¶
Data Pipeline: Preparation, I/O, and Streaming Windows¶
Canonical public home for resdag's data plumbing. Three layers live here:
Whole-tensor preparation — split a long trajectory into the fixed
warmup/train/target/f_warmup/val tensors the algebraic (:class:resdag.training.ESNTrainer)
path consumes, with optional normalization.
File I/O — load and save time series from CSV / NPY / NPZ / NetCDF, always
returning the (B, T, D) convention.
Streaming / SGD windows — slice a long trajectory (or many) into
fixed-length, batchable windows behind a standard
:class:torch.utils.data.DataLoader, for the SGD and streaming-algebraic paths.
| CLASS | DESCRIPTION |
|---|---|
TimeSeriesWindowDataset |
Sliding-window |
| FUNCTION | DESCRIPTION |
|---|---|
make_dataloader |
Wrap :class: |
prepare_esn_data |
Split a series into warmup, train, target, f_warmup, val. |
normalize_data, denormalize_data |
Normalize a series (and invert it) using various methods. |
load_and_prepare |
Load and prepare data from file(s) in one step. |
load_file, load_csv, load_npy, load_npz, load_nc |
Auto-detecting and format-specific loaders. |
save_csv, save_npy, save_npz, save_nc, list_files |
Savers and a directory listing helper. |
Examples:
Whole-tensor preparation for the algebraic path:
>>> from resdag.data import load_file, prepare_esn_data
>>> data = load_file("lorenz.csv")
>>> warmup, train, target, f_warmup, val = prepare_esn_data(
... data, warmup_steps=100, train_steps=500, val_steps=200, normalize="minmax"
... )
Streaming windows for the SGD path:
>>> import torch
>>> from resdag.data import make_dataloader
>>> series = torch.randn(2000, 3)
>>> loader = make_dataloader(series, batch_size=16, window_len=200, washout=50)
>>> for x, y, washout in loader:
... model.reset_reservoirs()
... pred = model(x)
... loss = mse(pred[:, washout:], y[:, washout:])
See Also
resdag.datasets : Canonical benchmark time-series generators. resdag.layers.IncrementalRidgeReadoutLayer : Streaming ridge readout for the loader.
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)
Bases: Dataset[WindowItem]
Sliding-window :class:~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() (or relying on
:attr:~resdag.layers.BaseReservoirLayer.detach_state_between_calls) 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 normalization statistics from
:func:
TYPE:
|
norm_method
|
Normalization method matching
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
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, **dataloader_kwargs: object) -> DataLoader[WindowItem]
Build a windowed :class:~torch.utils.data.DataLoader over series.
Convenience wrapper that constructs a :class:TimeSeriesWindowDataset from
series and the windowing parameters, then returns a
:class:~torch.utils.data.DataLoader whose batches are
(inputs, targets, washout) with inputs/targets of shape
(B, window_len, D) — ready to feed straight into
:class:~resdag.layers.ESNLayer / :class:~resdag.core.ESNModel.forward.
| PARAMETER | DESCRIPTION |
|---|---|
series
|
Source data; see :class:
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:
|
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 :class:
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
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 460 461 462 463 464 465 | |