Toy (Linear) Models#

ToyLinearTimeIndependent([configs])

Implementations of a toy linear model with equation \(x = A p\) (or \(F(p, x) := A p - x = 0)\).

ToyLinearTimeDependent([configs])

Implementations of a toy linear model with linear forward operator on the form

create_ToyLinearTimeIndependent_model([...])

A simplified interface to create instances of ToyLinearTimeIndependent

create_ToyLinearTimeDependent_model([ndim, ...])

A simplified interface to create toy linear time-dependent models;

This module provides functionality to create and test very basic toy models for debugging, performance evaluation, etc.

class ToyLinearTimeIndependentConfigs(*, debug=False, verbose=False, output_dir='./_PYOED_RESULTS_', model_name='Toy-Linear-Time-Independent', screen_output_iter=1, file_output_iter=1, np=5, ndim=1, nx=8, num_prog_vars=1, prog_vars_adjacent=False, num_decimals=2, random_seed=None)[source]#

Bases: TimeIndependentModelConfigs

Configurations for the ToyLinearTimeIndependent model. This model is an implementation of a very simple model

\[x = A p\]

where \(x\) is the model state, \(p\) is the model parameter, and \(A\) is an array representing the simulation model.

Note

This models allows multiple prognostic variables, multidimensional grids, and two ways of organizing the prognostic variables in the state vector.

In addition to the configurations available in

Parameters:
  • verbose (bool) – a boolean flag to control verbosity of the object.

  • debug (bool) – a boolean flag that enables adding extra functionality in a debug mode

  • output_dir (str | Path) – the base directory where the output files will be saved.

  • screen_output_iter (int) – iteration interval for screen output. Default is 1. Note that this should be a positive integer to enforce proper effect.

  • file_out_iter – iteration interval for file output. Default is 1. Note that this should be a positive integer to enforce proper effect.

  • np (int) – dimension of the model parameter. Default is 5. Note that this must be a positive integer.

  • ndim (int) – number of dimensions of the domain of the mode.

  • nx (int | Iterable[int]) – Number of discretization points. This can be a positive integer, or an iterable (e.g., list/tuple) of the same length as ndim holding the number of grid points in each dimension.

  • num_prog_vars (int) – the number of prognostic variables.

  • prog_vars_adjacent (bool) – if True all prognostic variables at one grid point are put adjacent to each other in the state vector, otherwise, all grids for one prognostic variable are adjacent (default).

  • num_decimals (int) – Number of decimal points to use for rounding the randomly generated values of the model array \(A\). If None, no rounding takes place. Default is 2.

  • random_seed (int | None) – the random seed to use while generating the model/initial condition as well as the model array. Default is set to the PyOED’s settings/default value of random seed found in pyoed.configs.SETTINGS.RANDOM_SEED.

  • model_name (str) – name of the model. Default is “Toy-Linear-Time-Independent”.

np: int#
ndim: int#
nx: int | Iterable[int]#
num_prog_vars: int#
prog_vars_adjacent: bool#
num_decimals: int#
random_seed: int | None#
__init__(*, debug=False, verbose=False, output_dir='./_PYOED_RESULTS_', model_name='Toy-Linear-Time-Independent', screen_output_iter=1, file_output_iter=1, np=5, ndim=1, nx=8, num_prog_vars=1, prog_vars_adjacent=False, num_decimals=2, random_seed=None)#
class ToyLinearTimeIndependent(configs=None)[source]#

Bases: TimeIndependentModel, RandomNumberGenerationMixin

Implementations of a toy linear model with equation \(x = A p\) (or \(F(p, x) := A p - x = 0)\). Here \(A\) is assumed to be an (nx x np) matrix with :math`np` being the parameter space dimension, and \(nx\) the dimension of the model state space. The state results by solving the model forward, i.e., by applying to the model equations to the parameter. This is useful for testing time independent models such as imaging, etc. An observation operator can be added on top of it, e.g., identity, with proper noise models for inversion/assimilation. The underlying matrix A is randomly generated; reproduction can be controlled by choosing the random seed.

Parameters:

configs (ToyLinearTimeIndependentConfigs | dict | None) – a dataclass containing configurations of the model. See ToyLinearTimeIndependentConfigs.

__init__(configs=None)[source]#

Initialize the random number generator

validate_configurations(configs, raise_for_invalid=True)[source]#

Check the passed configuratios and make sure they are conformable with each other, and with current configurations once combined. This guarantees that any key-value pair passed in configs can be properly used

Note

Here only the locally-defined configurations in ToyLinearTimeIndependentConfigs are validated. Finally, super classes validators are called.

Parameters:
Returns:

flag indicating whether passed configurations dictionary is valid or not

Raises:
Return type:

bool

update_configurations(**kwargs)[source]#

Take any set of keyword arguments, and lookup each in the configurations, and update as nessesary/possible/valid

Raises:

TypeError – if any of the passed keys in kwargs is invalid/unrecognized

initialize()[source]#

Initialize (or reconfigure) the model based on the current configurations.

create_model()[source]#

Create the model matrix (linear dynamics operator). Here, the model is a normally distributed square matrix

parameter_vector(init_val=0.0)[source]#

Create an instance of model parameter vector

Parameters:

init_val (float) – (optional) value assigned to entries of the state vector upon initialization

is_parameter_vector(parameter)[source]#

Test whether the passed parameter vector is valid or not

state_vector(init_val=0)[source]#

Create an instance of model state vector

Parameters:

init_val (float) – (optional) value assigned to entries of the state vector upon initialization

is_state_vector(state)[source]#

Test whether the passed state vector is valid or not

solve_forward(parameter, verbose=False)[source]#

Apply (solve the forward model) to the given parameter, and return the resulting state.

Parameters:

parameter – parameter to which the forward model is applied.

Returns:

result from applying the model/matrix (A) to the passed parameter

Jacobian_T_matvec(state, eval_at=None, verbose=False)[source]#

Multiply the Jacobian of the model (derivative of model equation w.r.t parameter) by the passed state

Parameters:

state – state to which the forward sensitivities are applied to.

Returns:

result resulting from applying the forward sensitivities to model to the passed state

get_model_array()[source]#

return a copy of the model operator (matrix)

get_model_grid()[source]#

return a copy of the model grid

property np#

Number of model parameters (dimension of the parameter vector).

property nx#

Grid size per dimension. May be a scalar or a list of per-axis sizes; the total state size is prod(nx) * num_prog_vars.

property state_size#

Total number of degrees of freedom in the model state vector (prod(nx) × num_prog_vars).

property parameter_size#

Number of model parameters (same as np).

property random_seed#

Random seed used when generating the model matrix and noise.

property num_decimals#

Number of decimal places used when rounding model matrix entries.

class ToyLinearTimeDependentConfigs(*, debug=False, verbose=False, output_dir='./_PYOED_RESULTS_', model_name='Toy-Linear-Time-Dependent', screen_output_iter=1, file_output_iter=1, time_integration=<factory>, num_prognostic_variables=None, space_discretization=<factory>, ndim=1, nx=8, num_prog_vars=1, prog_vars_adjacent=False, num_decimals=2, random_seed=None, dt=0.5, t_eps=1e-06)[source]#

Bases: TimeDependentModelConfigs

Configurations for the ToyLinearTimeDependent model.

Parameters:
  • verbose (bool) – a boolean flag to control verbosity of the object.

  • debug (bool) – a boolean flag that enables adding extra functionality in a debug mode

  • output_dir (str | Path) – the base directory where the output files will be saved.

  • screen_output_iter (int) – iteration interval for screen output. Default is 1. Note that this should be a positive integer to enforce proper effect.

  • file_out_iter – iteration interval for file output. Default is 1. Note that this should be a positive integer to enforce proper effect.

  • time_integration (dict | None) –

    dictionary holding time integration configurations:

    • ’scheme’: string specifying the time integration scheme (e.g., ‘RK4’, ‘RK45’, ‘BDF’, etc.). Default is None.

    • ’stepsize’: float specifying the time integration stepsize. Default is None.

    • ’adaptive’: bool specifying whether the time integration is adaptive. Default is False.

  • num_prognostic_variables (int | None) – number of prognostic variables in the model. Default is None. Must be a positive integer if not None.

  • space_discretization (dict | None) –

    dictionary holding space discretization configurations. Contains:

    • ’scheme’: string specifying the space discretization scheme (e.g., ‘FD’, ‘FE’, ‘BE’, etc.). Default is None.

  • ndim (int) – number of dimensions of the domain of the mode.

  • nx (int | Iterable[int]) – Number of discretization points. This can be a positive integer, or an iterable (e.g., list/tuple) of the same length as ndim holding the number of grid points in each dimension.

  • num_prog_vars (int) – the number of prognostic variables.

  • prog_vars_adjacent (bool) – if True all prognostic variables at one grid point are put adjacent to each other in the state vector, otherwise, all grids for one prognostic variable are adjacent (default).

  • num_decimals (int) – Number of decimal points to use for rounding the randomly generated values of the model array \(A\). If None, no rounding takes place. Default is 2.

  • random_seed (int | None) – the random seed to use while generating the model/initial condition as well as the model array. Default is set to the PyOED’s settings/default value of random seed found in pyoed.configs.SETTINGS.RANDOM_SEED.

  • dt (float) – time step assumed for time integration. Default is 0.5

  • t_eps (float) – time precision. Default is 1e-6.

  • model_name (str) – name of the model. Default is “Toy-Linear-Time-Dependent”.

ndim: int#
nx: int | Iterable[int]#
num_prog_vars: int#
prog_vars_adjacent: bool#
num_decimals: int#
random_seed: int | None#
dt: float#
t_eps: float#
__init__(*, debug=False, verbose=False, output_dir='./_PYOED_RESULTS_', model_name='Toy-Linear-Time-Dependent', screen_output_iter=1, file_output_iter=1, time_integration=<factory>, num_prognostic_variables=None, space_discretization=<factory>, ndim=1, nx=8, num_prog_vars=1, prog_vars_adjacent=False, num_decimals=2, random_seed=None, dt=0.5, t_eps=1e-06)#
class ToyLinearTimeDependent(configs=None)[source]#

Bases: TimeDependentModel, RandomNumberGenerationMixin

Implementations of a toy linear model with linear forward operator on the form

\[x_{k+1} = M x_k\]

where \(x_k\) is the model state at a time instance \(t_k\), and \(x_{k+1}\) is the model state at the next time instance t_{k+1}=t_{k} + dt. Here, An application of the operator \(M\) is associated with the time step dt specified in the configurations dictionary.

Note

Only multiples of this step size are allowed for forward integration (checkpointing) and/or adjoint integration (e.g., sensitivity analysis).

Parameters:

configs (dict | ToyLinearTimeDependentConfigs | None) – an object containing configurations of the toy linear model.

__init__(configs=None)[source]#

Initialize the random number generator

validate_configurations(configs, raise_for_invalid=True)[source]#

Check the passed configuratios and make sure they are conformable with each other, and with current configurations once combined. This guarantees that any key-value pair passed in configs can be properly used

Note

Here only the locally-defined configurations in ToyLinearTimeIndependentConfigs are validated. Finally, super classes validators are called.

Parameters:
Returns:

flag indicating whether passed configurations dictionary is valid or not

Raises:
Return type:

bool

update_configurations(**kwargs)[source]#

Take any set of keyword arguments, and lookup each in the configurations, and update as nessesary/possible/valid

Raises:

TypeError – if any of the passed keys in kwargs is invalid/unrecognized

initialize()[source]#

Initialize (or reconfigure) the model based on the current configurations.

create_model()[source]#

Create the model matrix (linear dynamics operator). Here, the model is a normally distributed square matrix

create_initial_condition()[source]#

Create the initial condition associated with the passed model dimension We are assuming a random integer initial condition

Returns:

numpy array (same shape as model_grid associated with the model) holding initial condition values.

parameter_vector(init_val=0.0)[source]#

Create an instance of model parameter vector. Here, the parameter is the model initial state, and thus parameter_vector() actually calls state_vector()

Parameters:

init_val (float) – (optional) value assigned to entries of the parameter vector upon initialization

is_parameter_vector(parameter)[source]#

Test whether the passed parameter vector is valid or not Here, the parameter is the model initial state, and thus is_parameter_vector() actually calls is_state_vector()

Parameters:

parameter – the input model parameter

state_vector(init_val=0.0)[source]#

Create an instance of model state vector. Here, this is a 1D Numpy array of size equal to the model grid.

Parameters:

init_val (float) – value assigned to entries of the state vector

Returns:

1d numpy array

is_state_vector(state)[source]#

Test whether the passed state vector is valid or not

integrate_state(state, tspan, checkpoints=None, verbose=False)[source]#

Simulate/integrate the model starting from the initial state over the passed checkpoints.

Note

This model is tied to a predefined time step dt in self.configurations; The distance between all checkpoints (including tspan) must be multiples of this timestep.

Parameters:
  • state – data structure holding the initial model state

  • tspan – (t0, tf) iterable with two entries specifying of the time integration window

  • checkpoints – times at which to store the computed solution, must be sorted and lie within tspan. If None (default), use points selected by the solver [t0, t1, …, tf].

  • verbose (bool) – output progress to screen if True. If set to False, nothing is printed to screen.

Returns:

a list holding the timespan, and a list holding the model trajectory with entries corresponding to the simulated model state at entries of checkpoints starting from checkpoints[0] and ending at checkpoints[-1].

Raises:
  • TypeError – if tspan is not valid, or checkpoints are not within tspan or are not calculable by multiple stepsizes dt as configured.

  • TypeError – if the passed state is not a valid state vector.

Jacobian_T_matvec(state, eval_at_t=None, eval_at=None, dt=None)[source]#

Evaluate and return the product of the Jacobian (of the right-hand-side) of the model (TLM) transposed, by a model state. This moodel is linear, so the TLM is the same as the underlying model

Parameters:
  • state – state to multiply the Jacobian by

  • eval_at_t – time at which the Jacobian (i.e., the model is linearized) is evaluated (Discarded here since the model is linear)

  • eval_at – state around which the Jacobian (i.e., the model is linearized) is evaluated (Discarded here since the model is linear)

  • dt (float) – the step size

Returns:

the product of the Jacobian transposed (adjoint operator) by a model state.

Raises:

TypeError – if the steps size dt is invalid

solve_adjoint_sub(adjoint, t_final, t_init, return_np=True)[source]#

Propagate the adjoint/sensitivity vector backward by solving the adjoint problem over the interval [t_init, t_final], and return the resulting initial condition/state This ignores any observations made in the time subinterval

Parameters:
  • adjoint – the adjoint vector to start with (state to propagate backward)

  • t_final (float) – the time at which Jacobian is to be evaluated (transpose multiplied by the adjoint)

  • t_init (float) – initial time

Raises:

ValueError – if the final time is not more initial time

get_model_array()[source]#

return a copy of the model operator (matrix)

get_model_grid()[source]#

return a copy of the model grid

property np#

Number of model parameters (dimension of the initial-state / parameter vector).

property nx#

Grid size per dimension. May be a scalar or a list of per-axis sizes; the total state size is prod(nx) * num_prog_vars.

property state_size#

Total number of degrees of freedom in the model state vector (prod(nx) × num_prog_vars).

property parameter_size#

Number of model parameters — equal to the state size for this time-dependent model.

property dt#

Integration time step used to advance the state by one step.

property t_eps#

Tolerance for floating-point time comparisons (e.g., checkpoint matching).

property random_seed#

Random seed used when generating the model matrix and noise.

create_ToyLinearTimeIndependent_model(ndim=1, np=5, nx=8, num_prog_vars=1, prog_vars_adjacent=False, num_decimals=2, random_seed=None, output_dir='./_PYOED_RESULTS_')[source]#

A simplified interface to create instances of ToyLinearTimeIndependent

Note

This function accepts all configurations of ToyLinearTimeIndependentConfigs

Returns:

an instance of ToyLinearTimeIndependent

create_ToyLinearTimeDependent_model(ndim=1, nx=8, num_prog_vars=1, prog_vars_adjacent=False, num_decimals=2, random_seed=None, dt=0.5, output_dir='./_PYOED_RESULTS_')[source]#
A simplified interface to create toy linear time-dependent models;

this inistantiates an instance of ToyLinearTimeDependent

Note

This function accepts all configurations of ToyLinearTimeDependentConfigs

Returns:

an instance of ToyLinearTimeDependent

create_time_independent_linear_model(ndim=1, np=5, nx=8, num_prog_vars=1, prog_vars_adjacent=False, num_decimals=2, random_seed=None, output_dir='./_PYOED_RESULTS_')#

A simplified interface to create instances of ToyLinearTimeIndependent

Note

This function accepts all configurations of ToyLinearTimeIndependentConfigs

Returns:

an instance of ToyLinearTimeIndependent

create_time_dependent_linear_model(ndim=1, nx=8, num_prog_vars=1, prog_vars_adjacent=False, num_decimals=2, random_seed=None, dt=0.5, output_dir='./_PYOED_RESULTS_')#
A simplified interface to create toy linear time-dependent models;

this inistantiates an instance of ToyLinearTimeDependent

Note

This function accepts all configurations of ToyLinearTimeDependentConfigs

Returns:

an instance of ToyLinearTimeDependent