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

create_ToyLinearTimeIndependent_model([...])

A simplified interface to create instances of ToyLinearTimeIndependent

create_ToyLinearTimeDependent_model([nx, ...])

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, nx=8, 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.

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 functionlity 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.

  • nx (int) – dimension of the model state. Default is 8. Note that this must be a positive integer.

  • 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#
nx: int#
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, nx=8, 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

initialize()[source]#
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:
  • configs (dict | TimeIndependentModelConfigs) – full or partial (subset) configurations to be validated

  • raise_for_invalid (bool) – if True raise TypeError for invalid configrations type/key. Default True

Returns:

flag indicating whether passed configurations dictionary is valid or not

Raises:
Return type:

bool

create_model()[source]#

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

parameter_vector(init_val=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#
property nx#
property random_seed#
property num_decimals#
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>, nx=2, dt=0.5, t_eps=1e-06, random_seed=1234, num_decimals=2)[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 functionlity 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.

  • nx (int) – dimension of the model state. Default is 2

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

  • t_eps (float) – a small number to compare time steps. Default is 1e-6.

  • num_decimals (int | None) – number of decimal points used to round the random model matrix. If None, no rounding takes place. Default is 2.

  • random_seed (int) – for reproduction of the model/initial condition.

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

nx: int#
dt: float#
t_eps: float#
random_seed: int#
num_decimals: int | None#
__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>, nx=2, dt=0.5, t_eps=1e-06, random_seed=1234, num_decimals=2)#
class ToyLinearTimeDependent(configs=None)[source]#

Bases: TimeDependentModel, RandomNumberGenerationMixin

Implementations of a toy linear model with linear forward operator

\[x_{k+1} = Mx_k\]

Here, An application of the operator \(M\) is associated with the time step dt specified in the configurations dictionary. 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

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

Check the passed configurations 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 ToyLinearTimeDependentConfigs are validated. Finally, super classes validators are called.

Parameters:
  • configs (dict | TimeDependentModelConfigs) – full or partial (subset) configurations to be validated

  • raise_for_invalid (bool) – if True raise TypeError for invalid configrations type/key. Default True

Returns:

flag indicating whether passed configurations dictionary is valid or not

Raises:
Return type:

bool

create_model()[source]#

Create the model matrix (linear dynamics operator). Here, the model is a normally distributed 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)[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()

state_vector(init_val=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.

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:
  • AssertionError if tspan is not valid, or checkpoints are not within tspan

  • TypeError is raised if the passed state is not a valid state vector

Remarks:

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.

Jacobian_T_matvec(state, eval_at_t=None, eval_at=None, dt=None, sparse=True)[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 is evaluated

  • eval_at – state around which the Jacobian is evaluated

  • dt (float) – the step size

Returns:

the product of the Jacobian transposed (adjoint operator) by a model 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 nx#
property dt#
property t_eps#
property random_seed#
property num_decimals#
create_ToyLinearTimeIndependent_model(parameter_size=5, state_size=8, random_seed=1234, output_dir='./_PYOED_RESULTS_')[source]#

A simplified interface to create instances of ToyLinearTimeIndependent

Parameters:
  • np (int) – number of parameter entries; i.e., size of the model’s parameter vector

  • nx (int) – number of state entries; i.e., size of the model’s state vector

  • random_seedNone or an integer random seed (passed to numpy) for reproduction of the model/initial condition

Output_dir:

Path to folder (will be created if doesn’t exist) in which to write reports, output, etc.

Returns:

an instance of ToyLinearTimeIndependent

create_ToyLinearTimeDependent_model(nx=3, dt=0.5, random_seed=1234, output_dir='./_PYOED_RESULTS_')[source]#
A simplified interface to create toy linear time-dependent models;

this inistantiates an instance of ToyLinearTimeDependent

Parameters:
  • nx (int) – number of state entries; i.e., size of the model vector

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

  • random_seedNone or an integer random seed (passed to numpy) for reproduction of the model/initial condition

  • output_dir – Path to folder (will be created if doesn’t exist) in which to write reports, output, etc.

Returns:

an instance of ToyLinearTimeDependent

create_time_independent_linear_model(parameter_size=5, state_size=8, random_seed=1234, output_dir='./_PYOED_RESULTS_')#

A simplified interface to create instances of ToyLinearTimeIndependent

Parameters:
  • np (int) – number of parameter entries; i.e., size of the model’s parameter vector

  • nx (int) – number of state entries; i.e., size of the model’s state vector

  • random_seedNone or an integer random seed (passed to numpy) for reproduction of the model/initial condition

Output_dir:

Path to folder (will be created if doesn’t exist) in which to write reports, output, etc.

Returns:

an instance of ToyLinearTimeIndependent

create_time_dependent_linear_model(nx=3, dt=0.5, random_seed=1234, output_dir='./_PYOED_RESULTS_')#
A simplified interface to create toy linear time-dependent models;

this inistantiates an instance of ToyLinearTimeDependent

Parameters:
  • nx (int) – number of state entries; i.e., size of the model vector

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

  • random_seedNone or an integer random seed (passed to numpy) for reproduction of the model/initial condition

  • output_dir – Path to folder (will be created if doesn’t exist) in which to write reports, output, etc.

Returns:

an instance of ToyLinearTimeDependent