Skip to content

Simulation

simulation

PredictLike

Bases: Protocol

Protocol for models exposing a prediction function.

predict

predict(x: Array) -> Array

Predict output from input features.

FeatureBuilderLike

Bases: Protocol

Protocol for feature construction functions used in simulation.

ScalerLike

Bases: Protocol

Protocol for preprocessing scaler objects.

transform

transform(x: Array) -> Array

Transform input features into scaled space.

inverse_transform

inverse_transform(y: Array) -> Array

Inverse transform scaled values back to original space.

simulate_recursive

simulate_recursive(
    model: PredictLike,
    u_input: Array,
    y_init_output: Array,
    feature_builder: FeatureBuilderLike,
    x_sc: ScalerLike | None = None,
    y_sc: ScalerLike | None = None,
) -> Array

Perform recursive one-step-ahead simulation.

At each time step, a feature vector is constructed from the available input history and output history. The output history consists of the initial measured outputs followed by all previously simulated values.

The predicted output is appended to the output history and used when constructing features for subsequent time steps.

Parameters:

  • model (PredictLike) –

    Model exposing a predict(x) method that returns the predicted output.

  • u_input (Array) –

    Input sequence of shape (T,) or (T, m).

  • y_init_output (Array) –

    Initial measured outputs used to initialize the recursive simulation, with shape (K,), where 1 <= K <= T.

  • feature_builder (FeatureBuilderLike) –

    Constructs a feature vector from the available input and output history. It must follow the same lag convention used during model training. Output lag 0 is assumed to be excluded.

  • x_sc (ScalerLike | None, default: None ) –

    Optional input scaler.

  • y_sc (ScalerLike | None, default: None ) –

    Optional output scaler.

Returns:

  • Array –

    Simulated output sequence of shape (T,). The first K entries are copied from y_init_output and the remaining entries are recursively predicted.

Notes

Unlike one-step prediction using measured outputs, this function feeds its own predictions back into the model, so prediction errors may accumulate over time.

Raises:

  • ValueError –

    If u_input is empty, y_init_output is empty, or len(y_init_output) > len(u_input).

  • RuntimeError –

    If the simulation produces a non-finite value (NaN or Β±Inf), indicating numerical instability during recursive simulation.

Examples:

>>> import jax.numpy as jnp
>>> from tnkm.simulation import simulate_recursive
>>> T = 10
>>> u = jnp.sin(jnp.linspace(0, 2 * jnp.pi, T))
>>> y_init = jnp.array([0.0, 0.1, 0.2])
>>> def feature_builder(*, u_input, y_output): # simple feature builder
...     return jnp.concatenate([u_input[-1:], y_output[-2:]])[None, :]
>>> y_sim = simulate_recursive(
...     model=model,
...     u_input=u,
...     y_init_output=y_init,
...     feature_builder=feature_builder,
... )
>>> y_sim.shape
(10,)