Skip to content

Models

Summary

Package: dynamodels (re-exported as romda.models)

Base class for all dynamical systems. Every model stores its time history via HistoryTracker and delegates time integration to an Integrator instance.

Key attributes: psi0, dt, alpha (param dict), M (obs matrix), Nphi, Nq, Na

Key concrete methods: time_integrate(), init_ensemble(), get_observables(), get_observable_hist(), reset_model(), copy()

Subclasses must implement: - obs_labels — property; labels for observable dimensions - time_derivative(t, psi, **params) — static method (continuous models), or - time_step(Nt) — discrete-map stepping (discrete models)

Model
├── Lorenz63
├── Lorenz96
├── VdP
├── Annular
├── KS
├── Rijke
├── ESN_model (+ EchoStateNetwork)
│   └── POD_ESN (+ POD)
└── LinearModel

Model API builders

HistoryTracker — dynamodels.history

Mixin class used by both Model and Bias. Provides a pre-allocated buffer that grows on demand, avoiding repeated np.concatenate calls.

Property / Method Description
hist, hist_t Valid portion of the state / time buffer
current_state, current_time Latest entry in the buffer
update_history(state, t) Append, reset, or overwrite last states

Integrator — dynamodels.integrator

Strategy pattern: Model holds one Integrator instance and calls integrator.advance(). The integrator dispatches to advance_single or advance_ensemble depending on the ensemble size.

Class Use case Mechanism
IVPIntegrator Continuous ODEs scipy.integrate.solve_ivp; multiprocessing pool for ensembles
DiscreteIntegrator Discrete maps (ESN, KS, linear) Calls model.time_step(); interpolates if dt_output ≠ dt_step
ConstantIntegrator Constant-bias placeholder Returns ψ(t) = ψ(0)
Integrator
├── IVPIntegrator
├── DiscreteIntegrator
└── ConstantIntegrator

Available Models

The concrete subclasses, with figures, live on their own pages: Physical models (VdP, Lorenz63, Lorenz96, KS, Rijke, Annular) and Data-driven models (ESN_model, POD_ESN, LinearModel).


dynamodels.model.Model(psi0, dt, integrator_class=IVPIntegrator, **kwargs)

Base class for all forecast models.

A Model couples three ingredients:

  • a state history (HistoryTracker) with pre-allocated storage of shape \((N_t,\, N_\phi\,[+N_\alpha],\, m)\) — time, physical state (plus estimated parameters, once init_ensemble augments them), and ensemble members;
  • a time-integration strategy (Integrator) selected at construction;
  • the observation operator M, used by ensemble estimators to map the analysis-augmented state (state, estimated parameters, and observables stacked, size \(N=N_\phi+N_\alpha+N_q\)) to the observables.

Physical models implement time_derivative(t, psi, **params) (continuous) or time_step(Nt) (discrete maps) and declare their estimable parameters in params with bounds in alpha_lims. By convention, the leading \(N_q\) components of the physical state are directly observable (see get_observables).

Parameters:

Name Type Description Default
psi0 ndarray or list

Initial state, shape \((N_\phi,)\) or \((N_\phi, m)\).

required
dt float

Output time step.

required
integrator_class type[Integrator]

Time-integration strategy (default IVPIntegrator).

IVPIntegrator
**kwargs

Model-parameter overrides (any attribute defined by the child class).

{}

Attributes:

Name Type Description
params list of str

Names of the parameters that can be varied/estimated; declared by child classes.

fixed_params list of str

Names of parameters treated as fixed and forwarded to the governing equations through governing_eqns_params (see set_fixed_params).

extra_print_params list of str

Extra attribute names appended to params when building print_params.

governing_eqns_params dict

Extra keyword arguments passed to time_derivative / time_step.

t_transient float

Transient time discarded before the pre-allocated history / ensemble generation starts (see init_ensemble, create_long_timeseries).

t_CR float

Characteristic (e.g. recurrence) time used to size the "zoom" window in the visualize_*_hist plots.

Nq int

Number of observable components; declared by child classes (default 1).

alpha dict or None

Copy of alpha0 taken at construction; not updated automatically as parameters evolve (use get_alpha for per-member current values).

initialized bool

Set to True once __init__ has completed.

results_folder str or None

Optional path for saving results.

Source code in dynamodels/model.py
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
@typechecked
def __init__(self,
             psi0: np.ndarray | list,
             dt: float,
             integrator_class: type[Integrator] = IVPIntegrator,
             **kwargs):

    # ================= INITIALISE PHYSICAL MODEL ================== ##
    keys = list(kwargs.keys())
    [setattr(self, key, kwargs.pop(key)) for key in keys if hasattr(self, key)]

    if len(kwargs.keys()) > 1:
        print(f'Model key(s) {kwargs.keys()} not assigned')

    # ====================== SET INITIAL CONDITIONS ====================== ##

    # Ensure psi0 is ndarray with ndim=2
    if psi0 is None:
        raise ValueError("Initial state psi0 must be provided during Model initialization.")
    elif (isinstance(psi0, np.ndarray) and psi0.ndim == 1) or isinstance(psi0, list):
        psi0 = np.array([psi0]).T

    self.psi0 = psi0
    self.dt = dt
    self.alpha0 = {par: getattr(self, par) for par in self.params}
    self.alpha = self.alpha0.copy()

    # ========================== CREATE HISTORY ========================== ##
    # self._initial_capacity = int(self.t_transient / self.dt) # Initial capacity of history arrays
    # self._current_ti = 1  # Current time index in history arrays

    self.history = HistoryTracker()
    self.history._initial_capacity = int(self.t_transient / self.dt)*2 if self.t_transient > 0 else 1000
    self.update_history(psi=self.psi0[np.newaxis, :, :],
                        t=np.array([0.]),
                        reset=True)

    # ======================== SET RNG ================================== ##
    self.print_params = self.define_print_params()
    self.set_fixed_params()
    self.initialized = True

    # ================= INITIALISE INTEGRATOR STRATEGY ================== ##
    # The model holds an instance of the specific Integrator
    self.integrator = integrator_class(self)

state_labels property

list of str: LaTeX labels \(\phi_0, \phi_1, \dots\) for each physical state component, used by the visualize_* helpers.

obs_labels property

list of str: LaTeX labels for the observable components.

Must be implemented by child classes; raises NotImplementedError here.

name property writable

str: Model name used e.g. in filenames and plot titles.

Defaults to the class name if not explicitly set.

alpha_lims property writable

dict: Mapping {param_name: (lower, upper)} of physical bounds for each entry in params.

Lazily initialised to (None, None) (unbounded) for every parameter the first time it is accessed.

alpha_labels property writable

dict: Default parameter-label mapping.

Lazily initialised, the first time it is accessed, to {name_0: '$\alpha_0$', name_1: '$\alpha_1$', ...} — one entry per name in params (alphabetically sorted), keyed by parameter name. Assign a custom mapping via the setter, using the same key convention.

hist property

Returns only the valid (non-empty) portion of the history buffer.

hist_t property

Returns only the valid portion of the time history.

current_state property

ndarray: Most recent state in history, shape \((N_\phi\,[+N_\alpha], m)\).

current_time property

float: Time stamp of current_state.

filename property writable

str: Descriptive filename built from name and the parameters in alpha0 that differ from their class defaults (falls back to f"{name}_default" if none differ). Cached after first access; also extended with an _ensemble_m{m} suffix by init_ensemble.

psi0 property writable

ndarray: Initial state/ensemble passed at construction, shape \((N_\phi, m)\) (see the psi0 constructor parameter).

Re-assigning psi0 after construction is unusual and emits a UserWarning.

alpha0 property writable

dict: Initial parameter values {name: value}, one entry per name in params, captured at construction time and never mutated afterwards.

dt property writable

float: Output time step, rounded to precision_t decimal places.

precision_t property

int: Number of decimal places used to round time stamps, derived from dt (set as a side effect of the dt setter).

dt_step property

float: Time step used internally by the integrator.

Equal to dt for models whose output and integration steps coincide; discrete models with distinct output/integration steps override this (see DiscreteIntegrator).

Nphi property

int: Number of physical state components, len(psi0).

Na property

int: Number of parameters currently augmented into the state — the length of est_alpha if an ensemble is configured, else 0.

N property

int: Size \(N=N_\phi+N_\alpha+N_q\) of the analysis-augmented state vector (state, estimated parameters, and observables stacked), used e.g. to size the observation operator M. This is not the shape of the stored hist array, which only carries the \(N_\phi\,[+N_\alpha]\) state/parameter rows.

m property

int: Ensemble size — the last (member) dimension of hist.

rng property

numpy.random.Generator: Random-number generator, lazily created from seed via numpy.random.default_rng.

seed property writable

int: Seed used to (re)create rng. Defaults to 0.

M property writable

ndarray or callable: Linear observation operator, shape \((N_q, N)\) with \(N=N_\phi+N_\alpha+N_q\).

Used by ensemble estimators to extract the observables from the analysis-augmented state \([\phi;\alpha;y]\) (state, estimated parameters, and observables stacked), \(\mathbf{y}=\mathbf{M}\psi\). Lazily initialised to the default block matrix \([\mathbf{0}_{N_q\times(N_\phi+N_\alpha)},\ \mathbb{I}_{N_q}]\), which selects the trailing \(N_q\) rows — consistent with the observables being appended at the bottom of that augmented vector.

Ma property

ndarray: Parameter observation operator, shape \((N_\alpha, N)\).

Selects the \(N_\alpha\) estimated-parameter rows from the analysis-augmented state \([\phi;\alpha;y]\): the block matrix \([\mathbf{0}_{N_\alpha\times N_\phi},\ \mathbb{I}_{N_\alpha},\ \mathbf{0}_{N_\alpha\times N_q}]\).

ensemble_cfg property writable

dict or False: Ensemble configuration {'est_alpha': [...], 'm': m} set by init_ensemble, or False if no ensemble has been configured.

est_alpha property writable

list of str: Names of the parameters currently estimated (augmented into the state), or [] if no ensemble is configured.

update_history(psi, t=None, reset=False, modify_saved_states=False)

Append (or overwrite) states in the model's history.

Parameters:

Name Type Description Default
psi ndarray

State(s) to store; reshaped to \((N_t, N_\phi\,[+N_\alpha], m)\) if given with fewer dimensions.

required
t ndarray or float

Time stamp(s) matching psi. If None and neither reset nor modify_saved_states is set, it is inferred as current_time + arange(Nt) * dt.

None
reset bool

If True, replace the entire history with psi (and restart the clock unless t is given).

False
modify_saved_states bool

If True, overwrite the most recent psi.shape[0] entries already in history in place (e.g. after a data-assimilation analysis step) instead of appending new ones.

False
Source code in dynamodels/model.py
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
def update_history(self, psi: np.ndarray, t=None, reset=False, modify_saved_states=False):
    r"""Append (or overwrite) states in the model's `history`.

    Parameters
    ----------
    psi : ndarray
        State(s) to store; reshaped to $(N_t, N_\phi\,[+N_\alpha], m)$ if
        given with fewer dimensions.
    t : ndarray or float, optional
        Time stamp(s) matching `psi`. If None and neither `reset` nor
        `modify_saved_states` is set, it is inferred as
        ``current_time + arange(Nt) * dt``.
    reset : bool
        If True, replace the entire history with `psi` (and restart the
        clock unless `t` is given).
    modify_saved_states : bool
        If True, overwrite the most recent ``psi.shape[0]`` entries already
        in history in place (e.g. after a data-assimilation analysis step)
        instead of appending new ones.
    """
    psi = self.__format_state(psi)
    if t is None and not reset and not modify_saved_states:

        t = (np.arange(0, psi.shape[0]) * self.dt).round(self.precision_t) + self.current_time
    if isinstance(t, float):
        t = np.array([t])

    # if modify_saved_states:
        # print(f"Updating history with new state of shape {psi.shape} and time array {t}. \
        #     Reset={reset}, modify_saved_states={modify_saved_states}")

    self.history.update_history(psi, t=t, reset=reset, modify_saved_states=modify_saved_states)

define_print_params()

list of str: Parameter names shown by print_parametersparams followed by extra_print_params.

Source code in dynamodels/model.py
358
359
360
361
362
def define_print_params(self):
    """list of str: Parameter names shown by `print_parameters` — `params`
    followed by `extra_print_params`.
    """
    return [*self.params, *self.extra_print_params]

t_lyap_from_table(value, table, fallback) staticmethod

Parameter-dependent Lyapunov time from a table of measured exponents.

table maps sweep-parameter values to the dominant Lyapunov exponent \(\lambda_1\) measured there (chaotic points only). Inside the tabulated range, returns \(1/\lambda_1\) with \(\lambda_1\) log-interpolated at value; outside it (limit cycles, tori, untabulated configurations) returns fallback, where a Lyapunov time is not defined.

Source code in dynamodels/model.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
@staticmethod
def t_lyap_from_table(value, table, fallback):
    """Parameter-dependent Lyapunov time from a table of measured exponents.

    `table` maps sweep-parameter values to the dominant Lyapunov exponent
    $\\lambda_1$ measured there (chaotic points only). Inside the tabulated
    range, returns $1/\\lambda_1$ with $\\lambda_1$ log-interpolated at
    `value`; outside it (limit cycles, tori, untabulated configurations)
    returns `fallback`, where a Lyapunov time is not defined.
    """
    keys = sorted(table)
    if keys[0] <= value <= keys[-1]:
        return 1.0 / float(np.exp(np.interp(value, keys, np.log([table[k] for k in keys]))))
    return fallback

set_fixed_params()

Build the instance-level governing_eqns_params used by time_derivative / time_step.

Collects the current value of every attribute named in fixed_params and merges it into a fresh instance dict (copied from the class-level governing_eqns_params, which is left untouched so fixed parameters do not leak across Model subclasses). Called once during __init__.

Source code in dynamodels/model.py
491
492
493
494
495
496
497
498
499
500
501
502
503
def set_fixed_params(self):
    """Build the instance-level `governing_eqns_params` used by
    `time_derivative` / `time_step`.

    Collects the current value of every attribute named in `fixed_params`
    and merges it into a fresh instance dict (copied from the class-level
    `governing_eqns_params`, which is left untouched so fixed parameters
    do not leak across `Model` subclasses). Called once during `__init__`.
    """
    fixed_params = dict((key, getattr(self, key)) for key in self.fixed_params)
    # Create an instance-level dict: the class-level default must not be mutated,
    # otherwise fixed parameters leak across different Model subclasses.
    self.governing_eqns_params = {**self.governing_eqns_params, **fixed_params}

create_long_timeseries(Nt=None)

Integrate the model forward and append the result to history.

Useful e.g. to run a model onto its attractor before further use.

Parameters:

Name Type Description Default
Nt int

Number of forecast steps. Defaults to 10 * t_transient / dt.

None
Source code in dynamodels/model.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
def create_long_timeseries(self, Nt=None):
    """Integrate the model forward and append the result to `history`.

    Useful e.g. to run a model onto its attractor before further use.

    Parameters
    ----------
    Nt : int, optional
        Number of forecast steps. Defaults to ``10 * t_transient / dt``.
    """
    if Nt is None:
        Nt = int(self.t_transient * 10 / self.dt)
    state, t = self.time_integrate(Nt=Nt)
    self.update_history(state, t)
    self.close()

copy()

Model: A deep copy of this model (copy.deepcopy).

Source code in dynamodels/model.py
549
550
551
def copy(self):
    """Model: A deep copy of this model (`copy.deepcopy`)."""
    return deepcopy(self)

get_observables(Nt=1, **kwargs)

Return the most recent observable(s) from history.

By convention, the observables are the leading Nq rows of the physical state (see state_labels / obs_labels).

Parameters:

Name Type Description Default
Nt int

Number of trailing time steps to return. If 1 (default), the leading Nt axis is dropped.

1

Returns:

Type Description
ndarray

Shape (Nq, m) if Nt == 1, else (Nt, Nq, m).

Source code in dynamodels/model.py
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
def get_observables(self, Nt=1, **kwargs):
    """Return the most recent observable(s) from `history`.

    By convention, the observables are the leading `Nq` rows of the
    physical state (see `state_labels` / `obs_labels`).

    Parameters
    ----------
    Nt : int
        Number of trailing time steps to return. If 1 (default), the
        leading ``Nt`` axis is dropped.

    Returns
    -------
    ndarray
        Shape ``(Nq, m)`` if ``Nt == 1``, else ``(Nt, Nq, m)``.
    """
    if Nt == 1:
        return self.hist[-1, :self.Nq, :]
    else:
        return self.hist[-Nt:, :self.Nq, :]

get_observable_hist(Nt=0, **kwargs)

Alias for get_observables with a different default.

Parameters:

Name Type Description Default
Nt int

Number of trailing time steps to return. With the default 0, hist[-0:] is the full array, so the entire observable history is returned.

0

Returns:

Type Description
ndarray

Shape (Nt, Nq, m) (or (Nq, m) if Nt == 1); see get_observables.

Source code in dynamodels/model.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
def get_observable_hist(self, Nt=0, **kwargs):
    """Alias for `get_observables` with a different default.

    Parameters
    ----------
    Nt : int
        Number of trailing time steps to return. With the default 0,
        ``hist[-0:]`` is the *full* array, so the entire observable
        history is returned.

    Returns
    -------
    ndarray
        Shape ``(Nt, Nq, m)`` (or ``(Nq, m)`` if ``Nt == 1``); see
        `get_observables`.
    """
    return self.get_observables(Nt, **kwargs)

print_parameters(show_header=True, indent=0)

Print the model class, its print_params values, and — if configured — ensemble_cfg.

Parameters:

Name Type Description Default
show_header bool

If True, print a section header first.

True
indent int

Number of leading spaces for each printed line.

0
Source code in dynamodels/model.py
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
def print_parameters(self, show_header=True, indent=0):
    """Print the model class, its `print_params` values, and — if
    configured — `ensemble_cfg`.

    Parameters
    ----------
    show_header : bool
        If True, print a section header first.
    indent : int
        Number of leading spaces for each printed line.
    """
    if show_header:
        print('\n ------------------ Model Parameters ------------------ ')
    print(f'{" " * indent}Model class: {self.__class__.__name__}')
    for key in sorted(self.print_params):
        val = getattr(self, key)
        print(f'{" " * indent}{key} = {val:.6f}' if isinstance(val, float) else f'{" " * indent}{key} = {val}')
    if self.ensemble_cfg is not False:
        print(f'{" " * indent}Ensemble configuration: {self.ensemble_cfg}')

reset_model(psi0=None, **kwargs)

Re-initialise this model in place via Model.__init__.

Parameters:

Name Type Description Default
psi0 ndarray

New initial state; defaults to current_state.

None
**kwargs

Forwarded to Model.__init__ (e.g. dt, parameter overrides).

{}
Source code in dynamodels/model.py
672
673
674
675
676
677
678
679
680
681
682
683
684
685
def reset_model(self, psi0=None, **kwargs):
    """Re-initialise this model in place via `Model.__init__`.

    Parameters
    ----------
    psi0 : ndarray, optional
        New initial state; defaults to `current_state`.
    **kwargs
        Forwarded to `Model.__init__` (e.g. `dt`, parameter overrides).
    """
    if psi0 is None:
        psi0 = self.current_state

    Model.__init__(self, psi0=psi0, **kwargs)

modify_settings(**kwargs)

Hook for child classes to adjust internal configuration after ensemble_cfg changes (called by init_ensemble). No-op by default.

Source code in dynamodels/model.py
688
689
690
691
692
def modify_settings(self, **kwargs):
    """Hook for child classes to adjust internal configuration after
    `ensemble_cfg` changes (called by `init_ensemble`). No-op by default.
    """
    pass

close()

Release resources held by the integrator (e.g. multiprocessing pools); delegates to Integrator.close.

Source code in dynamodels/model.py
695
696
697
698
699
def close(self):
    """Release resources held by the integrator (e.g. multiprocessing
    pools); delegates to `Integrator.close`.
    """
    self.integrator.close()

get_alpha(psi=None)

Build the per-member parameter dict(s) for psi.

Parameters:

Name Type Description Default
psi ndarray

State to read parameters from; defaults to current_state. If it has exactly Nphi rows (no augmented parameters), every member gets a copy of alpha0 unchanged.

None

Returns:

Type Description
list of dict

One {name: value} dict per ensemble member (length psi.shape[-1]): alpha0 overridden, for each member, by the values of its last Na state rows at the est_alpha names.

Source code in dynamodels/model.py
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
def get_alpha(self, psi=None):
    """Build the per-member parameter dict(s) for `psi`.

    Parameters
    ----------
    psi : ndarray, optional
        State to read parameters from; defaults to `current_state`. If it
        has exactly `Nphi` rows (no augmented parameters), every member
        gets a copy of `alpha0` unchanged.

    Returns
    -------
    list of dict
        One ``{name: value}`` dict per ensemble member (length
        ``psi.shape[-1]``): `alpha0` overridden, for each member, by the
        values of its last `Na` state rows at the `est_alpha` names.
    """
    if psi is None:
        psi = self.current_state

    if psi.shape[0] == self.Nphi:
        # print('using the same get_alpha')
        return [self.alpha0.copy()] * psi.shape[-1]

    # ensure psi has members on last axis
    if psi.ndim == 1:
        psi = psi[:, np.newaxis]

    alpha_list = []
    for mi in range(psi.shape[-1]):
        alph = self.alpha0.copy()
        alph.update(zip(self.est_alpha, psi[-self.Na:, mi]))
        alpha_list.append(alph)

    return alpha_list

time_integrate(Nt=100, averaged=False)

Forecast the model Nt steps ahead.

Delegates to the currently configured Integrator strategy (self.integrator.advance); this is just a thin wrapper, kept overridable in case a child Model needs special handling.

Parameters:

Name Type Description Default
Nt int

Number of forecast steps.

100
averaged bool

Only affects ensemble runs (IVPIntegrator.advance_ensemble): if False (default), each ensemble member is forecast individually with its own parameters (get_alpha); if True, only the ensemble mean trajectory is integrated and each member's deviation from the mean is left unchanged (frozen) rather than propagated.

False

Returns:

Name Type Description
psi ndarray, shape $(N_t, N_\phi\,[+N_\alpha], m)$

Forecasted state, excluding the current (initial) state already present in history.

t ndarray, shape $(N_t,)$

Time stamps of psi.

Source code in dynamodels/model.py
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
def time_integrate(self, Nt=100, averaged=False):
    r"""Forecast the model `Nt` steps ahead.

    Delegates to the currently configured `Integrator` strategy
    (`self.integrator.advance`); this is just a thin wrapper, kept
    overridable in case a child `Model` needs special handling.

    Parameters
    ----------
    Nt : int
        Number of forecast steps.
    averaged : bool
        Only affects ensemble runs (`IVPIntegrator.advance_ensemble`): if
        False (default), each ensemble member is forecast individually
        with its own parameters (`get_alpha`); if True, only the ensemble
        *mean* trajectory is integrated and each member's deviation from
        the mean is left unchanged (frozen) rather than propagated.

    Returns
    -------
    psi : ndarray, shape $(N_t, N_\phi\,[+N_\alpha], m)$
        Forecasted state, excluding the current (initial) state already
        present in `history`.
    t : ndarray, shape $(N_t,)$
        Time stamps of `psi`.
    """
    return self.integrator.advance(Nt=Nt, averaged=averaged, alpha=self.get_alpha())

init_ensemble(m, std_phi=0.001, std_alpha=0.001, est_alpha=[], distribution_phi='normal', distribution_alpha='uniform', ensure_mean_at_init=False, ensemble_psi0=None)

Generate (or validate) the augmented initial ensemble.

Generates state and (optionally) parameter uncertainty, stacks them into the augmented ensemble psi0 of shape (1, Nphi+Na, m), stores it in the model history, and updates the model filename.

Parameters:

Name Type Description Default
m int

Ensemble size.

required
std_phi float

Fractional std for state perturbations.

0.001
std_alpha float or dict

Std (or {name: std}) for parameter perturbations.

0.001
est_alpha list[str]

Names of parameters to augment into the state. If empty, and std_alpha is a dict, all parameters in std_alpha are estimated. If empty and std_alpha is not a dict, no parameters are estimated.

[]
distribution_phi str

Sampling distribution for state ("normal" or "uniform").

'normal'
distribution_alpha str

Sampling distribution for parameters.

'uniform'
ensure_mean_at_init bool

If True one member is forced to equal the mean.

False
ensemble_psi0 ndarray(Nphi + Na, m) or (1, Nphi + Na, m)

Pre-built ensemble; bypasses generation if provided.

None
Notes

Does not return a value; the generated (or validated) ensemble is written directly to history via update_history(reset=True).

Source code in dynamodels/model.py
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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
def init_ensemble(
    self,
    m: int,
    std_phi: float = 0.001,
    std_alpha=0.001,
    est_alpha: list = [],
    distribution_phi: str = "normal",
    distribution_alpha: str = "uniform",
    ensure_mean_at_init: bool = False,
    ensemble_psi0=None,
):
    """Generate (or validate) the augmented initial ensemble.

    Generates state and (optionally) parameter uncertainty, stacks them
    into the augmented ensemble psi0 of shape ``(1, Nphi+Na, m)``, stores
    it in the model history, and updates the model filename.

    Parameters
    ----------
    m : int
        Ensemble size.
    std_phi : float
        Fractional std for state perturbations.
    std_alpha : float or dict
        Std (or {name: std}) for parameter perturbations.
    est_alpha : list[str], optional
        Names of parameters to augment into the state.
        If empty, and std_alpha is a dict, all parameters in std_alpha are estimated. If empty and std_alpha is not a dict, no parameters are estimated.
    distribution_phi : str
        Sampling distribution for state ("normal" or "uniform").
    distribution_alpha : str
        Sampling distribution for parameters.
    ensure_mean_at_init : bool
        If True one member is forced to equal the mean.
    ensemble_psi0 : ndarray (Nphi+Na, m) or (1, Nphi+Na, m), optional
        Pre-built ensemble; bypasses generation if provided.

    Notes
    -----
    Does not return a value; the generated (or validated) ensemble is
    written directly to `history` via `update_history(reset=True)`.
    """


    if isinstance(std_alpha, dict):
        est_alpha = sorted(list(std_alpha.keys()))
        # mean_vector_to_ensemble iterates std_alpha.values(), so its row order is the
        # dict's insertion order. est_alpha is sorted, and everything downstream
        # (get_alpha, alpha_limits_matrix, plotting) indexes rows by est_alpha position.
        # Re-key in est_alpha order so the two agree.
        std_alpha = {key: std_alpha[key] for key in est_alpha}


    # Push ensemble config so Na, est_alpha properties resolve correctly.
    self.ensemble_cfg = {'est_alpha': est_alpha.copy(), 'm': m}

    self.modify_settings()  # Allow child classes to modify settings based on the new ensemble configuration.

    # Invalidate M cache so it is rebuilt with the updated N = Nphi + Na + Nq.
    if hasattr(self, '_M'):
        del self._M

    if ensemble_psi0 is None:

        #forecast to avoid initializing before the attractor, which can cause issues for some models (e.g., Lorenz63)
        Ntransient = int(self.t_transient / self.dt)
        if Ntransient > 0:
            psi, t = self.time_integrate(Nt=Ntransient, averaged=False)
            mean_phi0 = np.mean(psi[-1], axis=-1)
        else:
            # no transient (e.g. LinearModel): seed from the current state
            mean_phi0 = np.mean(self.current_state[:self.Nphi], axis=-1)


        psi0 = mean_vector_to_ensemble(
            self.rng, mean_phi0, std_phi, m,
            method=distribution_phi,
            ensure_mean_at_init=ensure_mean_at_init,
        )

        if self.est_alpha:
            mean_a = np.array([getattr(self, a) for a in self.est_alpha])

            # print(f"Generating initial ensemble for parameters {self.est_alpha} with std {std_alpha} and distribution {distribution_alpha}.")
            # print(f"Parameter means shape: {mean_a.shape}")
            alpha0 = mean_vector_to_ensemble(
                self.rng, mean_a, std_alpha, m,
                method=distribution_alpha,
                ensure_mean_at_init=ensure_mean_at_init,
            )
            psi0 = np.concatenate((psi0, alpha0), axis=0)

        ensemble_psi0 = psi0[np.newaxis, :, :]  # (1, Nphi+Na, m)

    else:
        if ensemble_psi0.ndim == 2:
            ensemble_psi0 = ensemble_psi0[np.newaxis, :, :]
        assert ensemble_psi0.shape[-1] == m, (
            f"ensemble_psi0 has {ensemble_psi0.shape[-1]} members, expected {m}."
        )
        assert ensemble_psi0.shape[1] == self.Nphi + self.Na, (
            f"ensemble_psi0 state size {ensemble_psi0.shape[1]}, "
            f"expected {self.Nphi + self.Na}."
        )

    self.update_history(psi=ensemble_psi0, t=self.hist_t[[0]], reset=True)

    self.filename += f"_ensemble_m{m}"

visualize_history(**kwargs)

Plot observable and parameter histories.

Calls visualize_state_hist, visualize_observable_hist, and visualize_spatiotemporal_hist in turn, forwarding to each only the keyword arguments it accepts.

Source code in dynamodels/model.py
924
925
926
927
928
929
930
931
932
933
934
935
936
def visualize_history(self, **kwargs) -> None:
    """Plot observable and parameter histories.

    Calls `visualize_state_hist`, `visualize_observable_hist`, and
    `visualize_spatiotemporal_hist` in turn, forwarding to each only the
    keyword arguments it accepts.
    """

    for func in [self.visualize_state_hist,
                 self.visualize_observable_hist,
                 self.visualize_spatiotemporal_hist]:
        kwargs_obs = allowed_kwargs_for_func(func, kwargs)
        func(**kwargs_obs)

visualize_config()

No-op hook for subclasses to plot model-specific configuration (e.g. spatial mesh, filter kernels).

Source code in dynamodels/model.py
939
940
941
942
def visualize_config(self):
    """No-op hook for subclasses to plot model-specific configuration
    (e.g. spatial mesh, filter kernels)."""
    pass

visualize_state(**kwargs)

Plot ensemble state (and parameter) distributions via plot_state_distribution.

No-op (prints a message) if no ensemble is configured (ensemble_cfg is False).

Source code in dynamodels/model.py
946
947
948
949
950
951
952
953
954
955
956
957
def visualize_state(self, **kwargs) -> None:
    """Plot ensemble state (and parameter) distributions via
    `plot_state_distribution`.

    No-op (prints a message) if no ensemble is configured
    (`ensemble_cfg` is False).
    """
    if self.ensemble_cfg is False:
        print("No ensemble configuration found. Cannot plot state distribution.")
        return
    kwargs_state = allowed_kwargs_for_func(plot_state_distribution, kwargs)
    plot_state_distribution(self, **kwargs_state)

visualize_state_hist(psi=None, t=None, max_modes=10, t_zoom=None, reference_y=1.0, reference_t=1.0)

Plot the time evolution of each physical state component.

Two panels per component: the full history, and a zoomed-in view of the last t_zoom steps. Complex-valued states get separate real/imag traces.

Parameters:

Name Type Description Default
psi ndarray

State history to plot; defaults to hist[:, :Nphi].

None
t ndarray

Matching time stamps; defaults to the tail of hist_t.

None
max_modes int

Maximum number of state components to plot.

10
t_zoom int

Number of trailing steps shown in the zoomed panel; defaults to t_CR / dt.

None
reference_y float

Reference value used to normalise psi (and its axis label).

1.0
reference_t float

Reference value used to normalise t (and its axis label).

1.0
Source code in dynamodels/model.py
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
def visualize_state_hist(self, psi=None, t=None, max_modes=10, t_zoom=None,
                         reference_y=1.0, reference_t: float = 1.0):
    """Plot the time evolution of each physical state component.

    Two panels per component: the full history, and a zoomed-in view of
    the last `t_zoom` steps. Complex-valued states get separate real/imag
    traces.

    Parameters
    ----------
    psi : ndarray, optional
        State history to plot; defaults to ``hist[:, :Nphi]``.
    t : ndarray, optional
        Matching time stamps; defaults to the tail of `hist_t`.
    max_modes : int
        Maximum number of state components to plot.
    t_zoom : int, optional
        Number of trailing steps shown in the zoomed panel; defaults to
        ``t_CR / dt``.
    reference_y : float
        Reference value used to normalise `psi` (and its axis label).
    reference_t : float
        Reference value used to normalise `t` (and its axis label).
    """
    if psi is None:
        psi = self.hist[:, :self.Nphi]
    if t is None:
        t = self.hist_t[-len(psi):]

    (psi,), lbl = normalized_y(reference_y, self.state_labels, psi)
    (t,), t_lbl = normalized_time(reference_t, t)
    assert t is not None

    if t_zoom is None:
        t_zoom = int(self.t_CR / self.dt)
    nrows = min(self.Nphi, max_modes)

    fig = plt.figure(figsize=(8, nrows+1), layout="constrained")
    plt.suptitle('State time evolution')
    axs = fig.subplots(nrows, 2, sharey='row', sharex='col')
    if nrows == 1:
        axs = [axs]

    for ii, ax in enumerate(axs):
        ax[0].plot(t, psi[:, ii].real,  label='Real part')
        ax[1].plot(t[-t_zoom:], psi[-t_zoom:, ii].real,  label='Real')
        if np.iscomplexobj(psi[:, ii]):
            ax[0].plot(t, psi[:, ii].imag, label='Imag part')
            ax[1].plot(t[-t_zoom:], psi[-t_zoom:, ii].imag, label='Imag')
            ax[1].legend(fontsize='x-small', ncol=2)
        ax[0].set(ylabel=lbl[ii])
        if ii == nrows-1:
            ax[0].set(xlabel=t_lbl, xlim=[t[0], t[-t_zoom]])
            ax[1].set(xlabel=t_lbl, xlim=[t[-t_zoom], t[-1]])

visualize_observable_hist(y=None, t=None, t_zoom=None, reference_y=1.0, reference_t=1.0)

Plot the time evolution of each observable.

Two panels per observable: the full history, and a zoomed-in view of the last t_zoom steps.

Parameters:

Name Type Description Default
y ndarray

Observable history to plot; defaults to get_observable_hist.

None
t ndarray

Matching time stamps; defaults to the tail of hist_t.

None
t_zoom int

Number of trailing steps shown in the zoomed panel; defaults to t_CR / dt.

None
reference_y float

Reference value y is divided by (also appended to the axis label).

1.0
reference_t float

Reference value used to normalise t (and its axis label).

1.0
Source code in dynamodels/model.py
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
def visualize_observable_hist(self, y=None, t=None, t_zoom=None,
                              reference_y=1.0, reference_t: float = 1.0):
    """Plot the time evolution of each observable.

    Two panels per observable: the full history, and a zoomed-in view of
    the last `t_zoom` steps.

    Parameters
    ----------
    y : ndarray, optional
        Observable history to plot; defaults to `get_observable_hist`.
    t : ndarray, optional
        Matching time stamps; defaults to the tail of `hist_t`.
    t_zoom : int, optional
        Number of trailing steps shown in the zoomed panel; defaults to
        ``t_CR / dt``.
    reference_y : float
        Reference value `y` is divided by (also appended to the axis
        label).
    reference_t : float
        Reference value used to normalise `t` (and its axis label).
    """
    if y is None:
        y = self.get_observable_hist()
    if t is None:
        t = self.hist_t[-len(y):]

    lbl = list(self.obs_labels)
    (t,), t_lbl = normalized_time(reference_t, t)
    assert t is not None
    if reference_y != 1.0:
        y = y / reference_y
        lbl = [f'{lb} / {reference_y}' for lb in lbl]

    if t_zoom is None:
        t_zoom = int(self.t_CR / self.dt)

    fig = plt.figure(figsize=(8, self.Nq+1), layout="constrained")
    plt.suptitle('Observables time evolution')
    axs = fig.subplots(self.Nq, 2, sharey='row', sharex='col')
    if self.Nq == 1:
        axs = [axs]

    for ii, ax in enumerate(axs):
        ax[0].plot(t, y[:, ii])
        ax[1].plot(t[-t_zoom:], y[-t_zoom:, ii])
        ax[0].set(ylabel=lbl[ii])
        if ii == self.Nq-1:
            ax[0].set(xlabel=t_lbl, xlim=[t[0], t[-t_zoom]])
            ax[1].set(xlabel=t_lbl, xlim=[t[-t_zoom], t[-1]])

visualize_spatiotemporal_hist(y_hist=None, t=None, nrows=None, averaged=False, reference_y=1.0, reference_t=1.0, **kwargs)

Space-time diagram of the state history: state index vs time.

Generic default plotting hist[:, :Nphi] directly — one panel per ensemble member (up to nrows), or the ensemble mean and standard deviation with averaged=True. Called by visualize_history. Same signature as the physical-space overrides in KS, Rijke and Lorenz96, which rewrite this when the raw state history is not the physical field.

Source code in dynamodels/model.py
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
def visualize_spatiotemporal_hist(self, y_hist=None, t=None, nrows=None, averaged=False,
                                  reference_y=1.0, reference_t: float = 1.0, **kwargs):
    """Space-time diagram of the state history: state index vs time.

    Generic default plotting ``hist[:, :Nphi]`` directly — one panel per
    ensemble member (up to ``nrows``), or the ensemble mean and standard
    deviation with ``averaged=True``. Called by `visualize_history`. Same
    signature as the physical-space overrides in `KS`, `Rijke` and
    `Lorenz96`, which rewrite this when the raw state history is not the
    physical field.
    """
    if y_hist is None:
        y_hist = self.hist[:, :self.Nphi]
    if t is None:
        t = self.hist_t

    (t,), t_lbl = normalized_time(reference_t, t)
    assert t is not None
    if reference_y != 1.0:
        y_hist = y_hist / reference_y

    N = y_hist.shape[1]
    extent = [t[0], t[-1], -0.5, N - 0.5]

    if not averaged:
        if nrows is None:
            nrows = min(10, y_hist.shape[-1])
        fig = plt.figure(figsize=(8, 1.5 * nrows + 1), layout='constrained')
        axs = np.atleast_1d(fig.subplots(nrows=nrows, sharex=True, sharey=True))
        lim = np.max(abs(y_hist))
        for mi, ax in enumerate(axs):
            im = ax.imshow(y_hist[:, :, mi].T, aspect='auto', origin='lower',
                           cmap='RdBu_r', vmin=-lim, vmax=lim, extent=extent)
        axs[0].set(title=f'{self.name} state space-time evolution')
        fig.colorbar(im, ax=axs, shrink=1 / nrows)
    else:
        fig, axs = plt.subplots(nrows=2, figsize=(8, 6), sharex=True, layout='constrained')
        y_mean = np.mean(y_hist, axis=-1)
        lim = np.max(abs(y_mean))
        im0 = axs[0].imshow(y_mean.T, aspect='auto', origin='lower',
                            cmap='RdBu_r', vmin=-lim, vmax=lim, extent=extent)
        axs[0].set(title=f'{self.name} state space-time evolution (mean and std)')
        fig.colorbar(im0, ax=axs[0])
        y_std = np.std(y_hist, axis=-1, ddof=1)
        im1 = axs[1].imshow(y_std.T, aspect='auto', origin='lower',
                            cmap='magma', vmin=0, extent=extent)
        fig.colorbar(im1, ax=axs[1])

    axs[-1].set(xlabel=t_lbl)
    for ax in axs:
        if N <= 10:
            ax.set(yticks=np.arange(N), yticklabels=self.state_labels[:N])
        else:
            ax.set(ylabel='state index')

dynamodels.history.HistoryTracker(initial_capacity=1000)

Pre-allocated, growable storage for a state (and time) history.

Backs dynamodels.model.Model and bias estimators in downstream packages: states are written into two pre-allocated arrays, _hist (shape (capacity, N, m)) and _hist_t (shape (capacity,)), so that appending new states (the common case, one per forecast step) does not reallocate on every call. current_ti tracks the index of the next empty slot; hist / hist_t expose only the [:current_ti] valid prefix. When the buffer fills up, _increase_hist_size grows it in bulk.

Initialise an empty tracker (the storage arrays themselves are allocated lazily, by the first update_history(..., reset=True) call).

Parameters:

Name Type Description Default
initial_capacity int

Initial capacity of the history arrays.

1000
Source code in dynamodels/history.py
61
62
63
64
65
66
67
68
69
70
71
72
73
def __init__(self, initial_capacity=1000):
    """Initialise an empty tracker (the storage arrays themselves are
    allocated lazily, by the first ``update_history(..., reset=True)``
    call).

    Parameters
    ----------
    initial_capacity : int
        Initial capacity of the history arrays.
    """

    self._initial_capacity = initial_capacity
    self.current_ti = 0  # Current time index in history

hist property

ndarray: The valid (non-empty) portion of the state buffer, _hist[:current_ti], shape (current_ti, N, m).

hist_t property

ndarray: The valid portion of the time buffer, _hist_t[:current_ti], shape (current_ti,).

capacity property

int: Total number of pre-allocated slots, _hist_t.shape[0] (>= current_ti).

current_state property

ndarray: Most recent state, hist[current_ti - 1].

current_time property

float: Time stamp of current_state.

current_ti = 0 instance-attribute property writable

int: Index of the next empty slot in the buffer (i.e. the number of valid entries currently stored).

update_history(state, t, reset=False, modify_saved_states=False)

Write state into the history buffer.

Three mutually exclusive modes, selected by reset / modify_saved_states:

  • reset=True: replace the entire buffer with state (via _reset_history), re-allocating storage sized to max(state.shape[0], initial_capacity).
  • modify_saved_states=True: overwrite the most recent state.shape[0] already-stored entries in place (via _reset_last_states), without advancing current_ti.
  • otherwise (default): append state as new entries starting at current_ti, growing the buffer first (via _increase_hist_size) if it would not fit.

Parameters:

Name Type Description Default
state ndarray

State(s) to write. In append mode (the default) must have shape (Nt, N, m) with N matching the existing buffer.

required
t ndarray or None

Time stamp(s) matching state. Required in append mode; optional when resetting (defaults to zeros) or modifying saved states.

required
reset bool

If True, replace the entire history (see above).

False
modify_saved_states bool

If True, overwrite recent entries in place instead of appending (see above); ignored if reset is True.

False
Source code in dynamodels/history.py
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
def update_history(self,
                   state: np.ndarray, t: np.ndarray | None,
                   reset=False, modify_saved_states=False):
    """Write `state` into the history buffer.

    Three mutually exclusive modes, selected by `reset` /
    `modify_saved_states`:

    - `reset=True`: replace the entire buffer with `state` (via
      `_reset_history`), re-allocating storage sized to
      ``max(state.shape[0], initial_capacity)``.
    - `modify_saved_states=True`: overwrite the most recent
      ``state.shape[0]`` already-stored entries in place (via
      `_reset_last_states`), without advancing `current_ti`.
    - otherwise (default): append `state` as new entries starting at
      `current_ti`, growing the buffer first (via `_increase_hist_size`)
      if it would not fit.

    Parameters
    ----------
    state : ndarray
        State(s) to write. In append mode (the default) must have shape
        ``(Nt, N, m)`` with ``N`` matching the existing buffer.
    t : ndarray or None
        Time stamp(s) matching `state`. Required in append mode; optional
        when resetting (defaults to zeros) or modifying saved states.
    reset : bool
        If True, replace the entire history (see above).
    modify_saved_states : bool
        If True, overwrite recent entries in place instead of appending
        (see above); ignored if `reset` is True.
    """
    if t is not None and state.ndim == 3:
        t = np.atleast_1d(t)
        assert state.shape[0] == t.shape[0], f"Length of t ({t.shape}) must match number of time steps in state ({state.shape})."
    if reset: # Reset the full history
        self._reset_history(state, t)

    elif modify_saved_states: # Update only the last state in history
        self._reset_last_states(new_state=state, t=t)
    else:
        assert t is not None, "Time array t must be provided when adding new states to history."
        assert state.ndim == 3, f"State must have shape (Nt, N, m), but got {state.shape}."
        assert state.shape[1] == self._hist.shape[1], f"State N dimension ({state.shape[1]}) must match history N dimension ({self._hist.shape[1]})."

        t0 = self.current_ti
        t1 = t0 + state.shape[0]

        if t1 > self.capacity:
            self._increase_hist_size(Nt=state.shape[0]*10)

        self._hist[t0:t1] = state
        self._hist_t[t0:t1] = t
        self.current_ti = t1

dynamodels.integrator.Integrator(model_instance)

Abstract base class for the time-integration strategies.

Defines the interface for advancing the model state; child classes implement advance_single and advance_ensemble. Three strategies are provided:

  • IVPIntegrator — continuous, variable-step integration with SciPy's solve_ivp of \(\dot{\boldsymbol{\psi}} = f(t, \boldsymbol{\psi}, \boldsymbol{\alpha})\); the model must define time_derivative.
  • DiscreteIntegrator — fixed, discrete-step maps \(\boldsymbol{\psi}_{t+\Delta t} = F(\boldsymbol{\psi}_t, \boldsymbol{\alpha})\) (e.g., ETDRK4, ESN); the model must define time_step.
  • ConstantIntegrator — holds the state constant, \(\boldsymbol{\psi}(t) = \boldsymbol{\psi}(0)\).

Initialize the integrator with a model instance.

Parameters:

Name Type Description Default
model_instance object

The (not necessarily Model) instance to integrate; must expose time_derivative/time_step, current_state, dt, and the other attributes each concrete strategy relies on.

required
Source code in dynamodels/integrator.py
49
50
51
52
53
54
55
56
57
58
59
60
61
@typechecked
def __init__(self, model_instance: object):
    """Initialize the integrator with a model instance.

    Parameters
    ----------
    model_instance : object
        The (not necessarily `Model`) instance to integrate; must expose
        `time_derivative`/`time_step`, `current_state`, `dt`, and the other
        attributes each concrete strategy relies on.
    """

    self.model = model_instance

is_ensemble property

bool: True if model.current_state carries more than one member (its last axis has size \(>1\)), i.e. advance should dispatch to advance_ensemble rather than advance_single.

close()

Close resources held by the integrator (e.g., multiprocessing pools).

Source code in dynamodels/integrator.py
75
76
77
def close(self):
    """ Close resources held by the integrator (e.g., multiprocessing pools). """
    pass

advance(averaged=False, **kwargs)

Common entry point for all integrators; dispatches to advance_single or advance_ensemble based on is_ensemble.

Parameters:

Name Type Description Default
averaged bool

Forwarded to advance_ensemble when the model carries an ensemble; ignored for a single member.

False
**kwargs

Forwarded to advance_single / advance_ensemble (typically Nt and alpha).

{}

Returns:

Name Type Description
psi ndarray

Forecasted state, excluding the initial condition.

t ndarray

Corresponding time stamps.

Source code in dynamodels/integrator.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def advance(self, averaged=False, **kwargs) -> tuple[np.ndarray, np.ndarray]:
    """Common entry point for all integrators; dispatches to
    `advance_single` or `advance_ensemble` based on `is_ensemble`.

    Parameters
    ----------
    averaged : bool
        Forwarded to `advance_ensemble` when the model carries an
        ensemble; ignored for a single member.
    **kwargs
        Forwarded to `advance_single` / `advance_ensemble` (typically
        `Nt` and `alpha`).

    Returns
    -------
    psi : ndarray
        Forecasted state, excluding the initial condition.
    t : ndarray
        Corresponding time stamps.
    """
    if not self.is_ensemble:
        return self.advance_single(**kwargs)
    else:
        return self.advance_ensemble(averaged=averaged, **kwargs)

advance_single(**kwargs)

Advance a single (non-ensemble) member. Must be implemented by child classes.

Returns:

Name Type Description
psi ndarray

Forecasted state, excluding the initial condition.

t ndarray

Corresponding time stamps.

Source code in dynamodels/integrator.py
105
106
107
108
109
110
111
112
113
114
115
116
def advance_single(self, **kwargs) -> tuple[np.ndarray, np.ndarray]:
    """Advance a single (non-ensemble) member. Must be implemented by
    child classes.

    Returns
    -------
    psi : ndarray
        Forecasted state, excluding the initial condition.
    t : ndarray
        Corresponding time stamps.
    """
    raise NotImplementedError("Child Integrator class must implement the advance_single() method.")

advance_ensemble(Nt=100, averaged=False, alpha=None)

Advance every ensemble member. Must be implemented by child classes.

Parameters:

Name Type Description Default
Nt int

Number of forecast steps.

100
averaged bool

Strategy-dependent flag controlling whether members are propagated individually or only the ensemble mean is integrated.

False
alpha dict

Parameter values forwarded to the governing equations.

None

Returns:

Name Type Description
psi ndarray

Forecasted ensemble state, excluding the initial condition.

t ndarray

Corresponding time stamps.

Source code in dynamodels/integrator.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def advance_ensemble(self, Nt: int = 100, averaged: bool = False, alpha: dict[str, Any] = None) -> tuple[np.ndarray, np.ndarray]:
    """Advance every ensemble member. Must be implemented by child
    classes.

    Parameters
    ----------
    Nt : int
        Number of forecast steps.
    averaged : bool
        Strategy-dependent flag controlling whether members are
        propagated individually or only the ensemble mean is integrated.
    alpha : dict, optional
        Parameter values forwarded to the governing equations.

    Returns
    -------
    psi : ndarray
        Forecasted ensemble state, excluding the initial condition.
    t : ndarray
        Corresponding time stamps.
    """
    raise NotImplementedError("Child Integrator class must implement the advance_ensemble() method.")

dynamodels.integrator.IVPIntegrator(model_instance, method='RK45')

Bases: Integrator

Integrator using SciPy's solve_ivp for continuous, variable-step integration of \(\dot{\psi}=f(t,\psi,\alpha)\).

The model must define time_derivative(t, psi, **params). A single member is solved directly with ivp_forecast_helper; an ensemble is either solved member-by-member in parallel (a multiprocessing pool sized to model.m, created lazily) or, if averaged=True, solved once for the ensemble mean with each member's deviation from the mean left unchanged (see advance_ensemble).

Parameters:

Name Type Description Default
model_instance object

See Integrator.__init__.

required
method str

Integration method forwarded to scipy.integrate.solve_ivp (default 'RK45').

'RK45'
Source code in dynamodels/integrator.py
305
306
307
def __init__(self, model_instance, method: str = 'RK45'):
    super().__init__(model_instance)
    self.method = method

close()

Terminate and join the multiprocessing pool, if one was created.

Source code in dynamodels/integrator.py
323
324
325
326
327
328
def close(self):
    """Terminate and join the multiprocessing pool, if one was created."""
    if hasattr(self, '_pool') and self._pool is not None:
        self._pool.terminate()
        self._pool.join()
        self._pool = None

advance_single(Nt=100, averaged=False, alpha=None)

Solve the IVP for the single (non-ensemble) member.

Parameters:

Name Type Description Default
Nt int

Number of forecast steps.

100
averaged bool

Accepted for interface compatibility with advance_ensemble but not used: with one member there is nothing to average.

False
alpha dict

Accepted for interface compatibility but not used: the governing equations are called with {**model.alpha0, **model.governing_eqns_params} directly rather than with this argument.

None

Returns:

Name Type Description
psi ndarray, shape ``(Nt, N, 1)``

Forecasted state, excluding the initial condition.

t ndarray, shape ``(Nt,)``

Time stamps spaced by model.dt.

Source code in dynamodels/integrator.py
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
def advance_single(self, Nt = 100, averaged=False, alpha = None):
    """Solve the IVP for the single (non-ensemble) member.

    Parameters
    ----------
    Nt : int
        Number of forecast steps.
    averaged : bool
        Accepted for interface compatibility with `advance_ensemble` but
        not used: with one member there is nothing to average.
    alpha : dict, optional
        Accepted for interface compatibility but not used: the governing
        equations are called with ``{**model.alpha0, **model.governing_eqns_params}``
        directly rather than with this argument.

    Returns
    -------
    psi : ndarray, shape ``(Nt, N, 1)``
        Forecasted state, excluding the initial condition.
    t : ndarray, shape ``(Nt,)``
        Time stamps spaced by `model.dt`.
    """
    # print('Using IVPIntegrator advance_single')
    pm = self.model

    t_all = np.round(pm.current_time + np.arange(0, Nt + 1) * pm.dt, pm.precision_t)

    psi0 = pm.current_state
    args = pm.governing_eqns_params

    # --- IVP Logic
    psi = [ivp_forecast_helper(y0=psi0[:, 0],
                                fun=pm.time_derivative,
                                t=t_all,
                                params={**pm.alpha0, **args})]

    try:
        psi = np.array(psi).transpose((1, 2, 0))
    except ValueError as e:
        print(f"Error during final array construction: {e}")
        psi = np.array(psi).T.reshape(-1, psi0.shape[0], pm.m)

    return psi[1:], t_all[1:]

advance_ensemble(Nt=100, averaged=False, alpha=None)

Solve the IVP for every ensemble member.

Parameters:

Name Type Description Default
Nt int

Number of forecast steps.

100
averaged bool

If False (default), each member is solved independently and in parallel (via a multiprocessing pool), each with its own parameters from model.get_alpha. If True, the IVP is solved once for the ensemble mean \(\overline{\psi}_0\), and each member's forecast is reconstructed as \(\overline{\psi}(t) + (\psi_{0,i}-\overline{\psi}_0)\), i.e. its initial deviation from the mean is carried forward unchanged rather than being independently propagated.

False
alpha dict

Accepted for interface compatibility but not used: parameters are always taken from model.get_alpha (or model.get_alpha on the ensemble mean, if averaged).

None

Returns:

Name Type Description
psi ndarray, shape ``(Nt, N, m)``

Forecasted ensemble state, excluding the initial condition.

t ndarray, shape ``(Nt,)``

Time stamps spaced by model.dt.

Source code in dynamodels/integrator.py
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
def advance_ensemble(self, Nt=100, averaged=False, alpha=None):
    r"""Solve the IVP for every ensemble member.

    Parameters
    ----------
    Nt : int
        Number of forecast steps.
    averaged : bool
        If False (default), each member is solved independently and in
        parallel (via a multiprocessing pool), each with its own
        parameters from `model.get_alpha`. If True, the IVP is solved
        once for the ensemble *mean* $\overline{\psi}_0$, and each
        member's forecast is reconstructed as
        $\overline{\psi}(t) + (\psi_{0,i}-\overline{\psi}_0)$, i.e. its
        initial deviation from the mean is carried forward unchanged
        rather than being independently propagated.
    alpha : dict, optional
        Accepted for interface compatibility but not used: parameters are
        always taken from `model.get_alpha` (or `model.get_alpha` on the
        ensemble mean, if `averaged`).

    Returns
    -------
    psi : ndarray, shape ``(Nt, N, m)``
        Forecasted ensemble state, excluding the initial condition.
    t : ndarray, shape ``(Nt,)``
        Time stamps spaced by `model.dt`.
    """
    pm = self.model

    t_all = np.round(pm.current_time + np.arange(0, Nt + 1) * pm.dt, pm.precision_t)

    psi0 = pm.current_state
    args = pm.governing_eqns_params

    # --- IVP Logic (Similar to previous Model.time_integrate) ---

    if not averaged:
        # Ensemble run (using multiprocessing pool)
        alpha_list = pm.get_alpha()
        forecast_part = partial(ivp_forecast_helper,
                                fun=pm.time_derivative, t=t_all, method=self.method)

        sol = [self.__pool.apply_async(forecast_part,
                                        kwds={'y0': psi0[:, mi].T, 'params': {**args, **alpha_list[mi]}})
                for mi in range(pm.m)]

        psi = [s.get() for s in sol]

    else:
        # Averaged forecast
        psi_mean0 = np.mean(psi0, axis=1, keepdims=True)
        psi_deviation = psi0 - psi_mean0
        alpha = pm.get_alpha(psi_mean0)[0]

        psi_mean = ivp_forecast_helper(y0=psi_mean0[:, 0],
                                        fun=pm.time_derivative,
                                        t=t_all,
                                        params={**alpha, **args},
                                        method=self.method)

        psi = [psi_mean + psi_deviation[:, ii] for ii in range(pm.m)]


    # Rearrange dimensions to be Nt+1 x N x m and remove initial condition
    try:
        psi = np.array(psi).transpose((1, 2, 0))
    except ValueError as e:
        print(f"Error during final array construction: {e}")
        psi = np.array(psi).T.reshape(-1, psi0.shape[0], pm.m)

    return psi[1:], t_all[1:]

dynamodels.integrator.DiscreteIntegrator(model_instance)

Bases: Integrator

Integrator for models advanced by a fixed, discrete map or scheme (single member), \(\psi_{t+\mathrm{d}t}=F(\psi_t,\alpha)\) (e.g. ETDRK4 in KS, or an ESN).

The model must define time_step(Nt), stepping at its own internal time step dt_step (dt_integrator); if this differs from the model's output step dt (dt_output), the integrator's output is linearly interpolated back onto the requested output times.

Attributes:

Name Type Description
dt_output float

Output time step, model.dt.

dt_integrator float

Time step used internally by model.time_step, model.dt_step.

relation_integrator_output float

dt_output / dt_integrator (1.0 if the two coincide); the number of internal steps per output step.

See Integrator.__init__; also derives dt_output, dt_integrator, and relation_integrator_output from the model.

Source code in dynamodels/integrator.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def __init__(self, model_instance):
    """See `Integrator.__init__`; also derives `dt_output`,
    `dt_integrator`, and `relation_integrator_output` from the model.
    """
    super().__init__(model_instance)

    self.dt_output = getattr(self.model, 'dt')
    self.dt_integrator = getattr(self.model, 'dt_step')

    if self.dt_output != self.dt_integrator:
        self.relation_integrator_output = self.dt_output / self.dt_integrator
        self.relation_integrator_output = round(self.relation_integrator_output, self.model.precision_t)
    else:
        self.relation_integrator_output = 1.0

advance_single(Nt=100, **kwargs)

Advance the model via model.time_step, resampled onto the requested output times.

Parameters:

Name Type Description Default
Nt int

Number of output forecast steps (at spacing dt_output).

100
**kwargs

Accepted for interface compatibility with advance_ensemble (e.g. averaged, alpha) but not used here.

{}

Returns:

Name Type Description
psi ndarray, shape ``(Nt, N, m)``

Forecasted state at the output times, excluding the initial condition. Taken directly from model.time_step if its internal time grid already coincides with the output grid; otherwise linearly interpolated onto it (never extrapolated beyond the integrator's own time range).

t ndarray, shape ``(Nt,)``

Output time stamps, spaced by dt_output.

Source code in dynamodels/integrator.py
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
def advance_single(self, Nt: int = 100, **kwargs) -> tuple[np.ndarray, np.ndarray]:
    """Advance the model via `model.time_step`, resampled onto the
    requested output times.

    Parameters
    ----------
    Nt : int
        Number of *output* forecast steps (at spacing `dt_output`).
    **kwargs
        Accepted for interface compatibility with `advance_ensemble`
        (e.g. `averaged`, `alpha`) but not used here.

    Returns
    -------
    psi : ndarray, shape ``(Nt, N, m)``
        Forecasted state at the output times, excluding the initial
        condition. Taken directly from `model.time_step` if its internal
        time grid already coincides with the output grid; otherwise
        linearly interpolated onto it (never extrapolated beyond the
        integrator's own time range).
    t : ndarray, shape ``(Nt,)``
        Output time stamps, spaced by `dt_output`.
    """
    model = self.model

    t_out = np.round(model.current_time + np.arange(Nt + 1) * self.dt_output, model.precision_t)

    Nt_step = int(np.ceil(Nt * self.relation_integrator_output))

    psi, t = model.time_step(Nt=Nt_step)

    # Equal lengths do not imply equal times: with dt_output != dt_integrator a short
    # request (e.g. Nt=1 at upsample=2 -> Nt_step=1) gives two arrays of the same
    # length spanning different intervals, and returning the integrator's own times
    # would overshoot t_out[-1]. Only skip the interpolation when the two grids
    # genuinely coincide.
    if self.relation_integrator_output == 1.0 and len(t_out) == len(t):
        return psi[1:], t[1:]
    else:
        # Interpolate
        assert t[-1] >= t_out[-1], f"do not extrapolate beyond the integrator time range, {t[-1]} vs {t_out[-1]}"

        psi_interp = interpolate(t, psi, t_eval=t_out, fill_values='extrapolate')
        # model.reset_last_state(psi_interp[-1], t_out[-1])
        return psi_interp[1:], t_out[1:]

advance_ensemble(Nt=100, averaged=False, alpha=None)

Identical to advance_single; averaged and alpha are forwarded but unused (the discrete map is applied uniformly to however many members model.time_step handles internally).

Source code in dynamodels/integrator.py
274
275
276
277
278
279
def advance_ensemble(self, Nt = 100, averaged = False, alpha = None):
    """Identical to `advance_single`; `averaged` and `alpha` are
    forwarded but unused (the discrete map is applied uniformly to
    however many members `model.time_step` handles internally).
    """
    return self.advance_single(Nt, averaged=averaged, alpha=alpha)

dynamodels.integrator.ConstantIntegrator(model_instance)

Bases: Integrator

Integrator that holds the state constant over time, \(\psi(t)=\psi(0)\).

Useful for testing or as a placeholder while other model components (e.g. a bias model) are advanced.

See Integrator.__init__.

Source code in dynamodels/integrator.py
150
151
152
def __init__(self, model_instance):
    """See `Integrator.__init__`."""
    super().__init__(model_instance)

advance_single(Nt=100, **kwargs)

Repeat model.current_state at every output time.

Parameters:

Name Type Description Default
Nt int

Number of forecast steps.

100
**kwargs

Accepted for interface compatibility with advance_ensemble (e.g. averaged, alpha) but not used: the state is simply held constant regardless of these.

{}

Returns:

Name Type Description
psi ndarray, shape ``(Nt, N, m)``

current_state repeated Nt times, excluding the initial condition.

t ndarray, shape ``(Nt,)``

Time stamps spaced by model.dt.

Source code in dynamodels/integrator.py
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
def advance_single(self, Nt: int = 100, **kwargs) -> tuple[np.ndarray, np.ndarray]:
    """Repeat `model.current_state` at every output time.

    Parameters
    ----------
    Nt : int
        Number of forecast steps.
    **kwargs
        Accepted for interface compatibility with `advance_ensemble`
        (e.g. `averaged`, `alpha`) but not used: the state is simply held
        constant regardless of these.

    Returns
    -------
    psi : ndarray, shape ``(Nt, N, m)``
        `current_state` repeated `Nt` times, excluding the initial
        condition.
    t : ndarray, shape ``(Nt,)``
        Time stamps spaced by `model.dt`.
    """
    model = self.model
    t_out = np.round(model.current_time + np.arange(Nt + 1) * model.dt, model.precision_t)
    psi = np.repeat(model.current_state[:, :, np.newaxis], Nt + 1, axis=2)
    # return psi, t_out, psi shoud have dimensions Nt x N x m
    psi = psi.transpose((2, 0, 1))  # Nt+1 x N x m

    return psi[1:], t_out[1:]

advance_ensemble(Nt=100, averaged=False, alpha=None)

Identical to advance_single (the state is constant regardless of ensemble size); averaged and alpha are forwarded but unused.

Source code in dynamodels/integrator.py
182
183
184
185
186
def advance_ensemble(self, Nt: int = 100, averaged: bool = False, alpha: dict[str, Any] = None) -> tuple[np.ndarray, np.ndarray]:
    """Identical to `advance_single` (the state is constant regardless of
    ensemble size); `averaged` and `alpha` are forwarded but unused.
    """
    return self.advance_single(Nt=Nt, averaged=averaged, alpha=alpha)