agentlib_mpc.models package

Package containing models for agentlib_mpc.

Submodules

agentlib_mpc.models.casadi_ml_model module

Holds the classes for CasADi variables and the CasADi model.

class agentlib_mpc.models.casadi_ml_model.CasadiMLModel(**kwargs)[source]

Bases: CasadiModel

This class is created to handle one or multiple ML models used to predict the states. Compared to previous version, it is now only dependent on the trained models which provides information about the lags with the serialized_ML_Models. This way, there is no need to define the lags again in the model class

property auxiliaries: List[CasadiState]

List of all CasadiStates without an associated equation. Common uses for this are slack variables that appear in cost functions and constraints of optimization models.

property bb_outputs: List[CasadiOutput]

List of all CasadiStates with an associated black box equation.

property bb_states: List[CasadiState]

List of all CasadiStates with an associated black box equation.

config_type: CasadiMLModelConfig
do_step(*, t_start, t_sample=None)[source]

Simulates a time step of the simulation model. In CasADi MLModel model, both black- and white-box models can be used in the simulation to be combined into a grey-box

get_ml_model_values(time: float)[source]

gets the inputs values with the correct lags or all MLModels

initialize(**ignored)[source]

Prepare the black- and white-box models for CasADi backend optimization and simulation

make_predict_function_for_mpc() Function[source]

Creates a prediction step function which is suitable for MPC with multiple shooting.

register_ml_models() tuple[dict[str, agentlib_mpc.models.serialized_ml_model.SerializedMLModel], dict[str, agentlib_mpc.models.casadi_predictor.CasadiPredictor]][source]

Loads a serialized MLModel and find the output states of the MLModel Divides the differential states of the model into states determined by white-box model (self._differentials) and by black-box model (self._differentials_network)

set_with_timestamp(name: str, value: Any, timestamp: float)[source]
setup_system()[source]
update_ml_models(*ml_models: SerializedMLModel, time: float)[source]

Updates the internal MLModels with the passed MLModels.

Warning: This function does not fully check, if the result makes sense! Consider the following case: You have two ml_models with outputs out1 in ml_model1, and out2 and out3 in ml_model2. You call this function with an ml_model3 that defines out2. This function would replace ml_model2 with ml_model3, leaving the out3 undefined, causing an error in subequent functions. Try to make sure you specify all outputs when supplying ml_models, that make parts of other ml_models obsolete.

pydantic model agentlib_mpc.models.casadi_ml_model.CasadiMLModelConfig[source]

Bases: CasadiModelConfig

Config:
  • validate_assignment: bool = True

  • arbitrary_types_allowed: bool = True

  • extra: str = forbid

Fields:
Validators:
field dt: float | int = 1
Validated by:
field ml_model_sources: list[Union[agentlib_mpc.models.serialized_ml_model.SerializedMLModel, pathlib.Path]] = []
Validated by:
validator check_dt  »  all fields[source]
validator check_or_load_models  »  ml_model_sources[source]
model_post_init(context: Any, /) None

We need to both initialize private attributes and call the user-defined model_post_init method.

agentlib_mpc.models.casadi_ml_model.assert_recursive_outputs_are_states(serialized: SerializedMLModel, outputs: dict[str, agentlib.core.datamodels.AgentVariable])[source]

Raises a ConfigurationError if there are recursive ML-models for outputs.

agentlib_mpc.models.casadi_ml_model.compute_dupes(collection: Iterable[T]) list[T][source]

Computes the duplicate elements in a collection

agentlib_mpc.models.casadi_model module

Holds the classes for CasADi variables and the CasADi model.

class agentlib_mpc.models.casadi_model.CasadiInput(*, name: str, timestamp: float | None = None, unit: str = 'Not defined', description: str = 'Not defined', ub=inf, lb=-inf, clip: bool = False, allowed_values: List[Any] = [], value: Any = None, causality: Causality = None, variability: Variability = None, type: str | None = 'float', sim_time: float = 0.0, _sym: MX | SX | DM | Sparsity = None)[source]

Bases: CasadiVariable

Class that stores various attributes of control variables.

property alg: MX | SX | DM | Sparsity
class agentlib_mpc.models.casadi_model.CasadiModel(**kwargs)[source]

Bases: Model

Base Class for CasADi models. To implement your own model, inherit from this class, specify the variables (inputs, outputs, states, parameters and override the setup_system() method.

property auxiliaries: List[CasadiState]

List of all CasadiStates without an associated equation. Common uses for this are slack variables that appear in cost functions and constraints of optimization models.

property differentials: List[CasadiState]

List of all CasadiStates with an associated differential equation.

do_step(*, t_start, t_sample=None)[source]

Performing one simulation step :param t_start: start time for integration :param t_sample: increment of solver integration

Returns:

get(name: str) CasadiVariable[source]

Get any variable from using name:

Parameters:

name (str) – The item to get from config by name of Variable. Hence, item=ModelVariable.name

Returns:

The matching variable

Return type:

var (ModelVariable)

Raises:

AttributeError – If the item was not found in the variables of the module.

get_constraints() List[ModelConstraint][source]

List of constraints of the form (lower, function, upper).

get_differential_values()[source]
get_input_values()[source]
initialize(**ignored)[source]

Initializes Casadi model. Creates the integrator to be used in do_step(). The integrator takes the current state and input values as input and returns the state values at the end of the interval and the value of the cost function integrated over the interval.

property inputs: list[agentlib_mpc.models.casadi_model.CasadiInput]

Get all model inputs as a list

property output_equations: List[MX | SX | DM | Sparsity]

List of algebraic equations RHS in the form 0 = z - g(x, z, p, … )

property outputs: list[agentlib_mpc.models.casadi_model.CasadiOutput]

Get all model outputs as a list

property parameters: list[agentlib_mpc.models.casadi_model.CasadiParameter]

Get all model parameters as a list

set_differential_values(values: List | ndarray)[source]

Sets the values for all differential variables. Provided values list MUST match the order in which differentials are saved, there is no check.

set_output_values(values: List | ndarray)[source]

Sets the values for all outputs. Provided values list MUST match the order in which outputs are saved, there is no check.

abstract setup_system()[source]
property states: list[agentlib_mpc.models.casadi_model.CasadiState]

Get all model states as a list

pydantic model agentlib_mpc.models.casadi_model.CasadiModelConfig[source]

Bases: ModelConfig

Config:
  • validate_assignment: bool = True

  • arbitrary_types_allowed: bool = True

  • extra: str = forbid

Fields:
Validators:
  • check_name » name

  • include_default_model_variables » inputs

  • include_default_model_variables » outputs

  • include_default_model_variables » parameters

  • include_default_model_variables » states

field cost_function: MX | SX | DM | Sparsity = None
field description: str = 'You forgot to document your model!'
field dt: float | int = 1
field inputs: List[CasadiInput] = []
Validated by:
  • include_default_model_variables

field name: str | None = None
Validated by:
  • check_name

field outputs: List[CasadiOutput] = []
Validated by:
  • include_default_model_variables

field parameters: List[CasadiParameter] = []
Validated by:
  • include_default_model_variables

field sim_time: float = 0
field states: List[CasadiState] = []
Validated by:
  • include_default_model_variables

field system: MX | SX | DM | Sparsity = None
field user_config: dict = None

The config given by the user to instantiate this class.Will be stored to enable a valid overwriting of the default config and to better restart modules.Is also useful to debug validators and the general BaseModuleConfig.

field validate_variables: bool = True

If true, the validator of a variables value is called whenever a new value is set. Disabled by default for performance reasons.

model_post_init(context: Any, /) None

We need to both initialize private attributes and call the user-defined model_post_init method.

class agentlib_mpc.models.casadi_model.CasadiOutput(*, name: str, timestamp: float | None = None, unit: str = 'Not defined', description: str = 'Not defined', ub=inf, lb=-inf, clip: bool = False, allowed_values: List[Any] = [], value: Any = None, causality: Causality = None, variability: Variability = None, type: str | None = 'float', sim_time: float = 0.0, _sym: MX | SX | DM | Sparsity = None, _alg: MX | SX | DM | Sparsity = None)[source]

Bases: CasadiVariable

Class that stores various attributes of control variables.

property alg: MX | SX | DM | Sparsity
json(**kwargs)[source]

Serializes the Variable in json format and returns a string

class agentlib_mpc.models.casadi_model.CasadiParameter(*, name: str, timestamp: float | None = None, unit: str = 'Not defined', description: str = 'Not defined', ub=inf, lb=-inf, clip: bool = False, allowed_values: List[Any] = [], value: Any = None, causality: Causality = None, variability: Variability = None, type: str | None = 'float', sim_time: float = 0.0, _sym: MX | SX | DM | Sparsity = None)[source]

Bases: CasadiVariable

Class that stores various attributes of parameters.

class agentlib_mpc.models.casadi_model.CasadiState(*, name: str, timestamp: float | None = None, unit: str = 'Not defined', description: str = 'Not defined', ub=inf, lb=-inf, clip: bool = False, allowed_values: List[Any] = [], value: Any = None, causality: Causality = None, variability: Variability = None, type: str | None = 'float', sim_time: float = 0.0, _sym: MX | SX | DM | Sparsity = None, _ode: MX | SX | DM | Sparsity | None = None)[source]

Bases: CasadiVariable

Class that stores various attributes of CasADi differential variables.

property alg: MX | SX | DM | Sparsity
json(indent: int = 2, **kwargs)[source]

Serializes the Variable in json format and returns a string

property ode: MX | SX | DM | Sparsity
class agentlib_mpc.models.casadi_model.CasadiVariable(*, name: str, timestamp: float | None = None, unit: str = 'Not defined', description: str = 'Not defined', ub=inf, lb=-inf, clip: bool = False, allowed_values: List[Any] = [], value: Any = None, causality: Causality = None, variability: Variability = None, type: str | None = 'float', sim_time: float = 0.0, _sym: MX | SX | DM | Sparsity = None)[source]

Bases: ModelVariable

Base Class for variables used in Casadi Models for simulation and optimization. Implements the standard arithmetic operations, so CasadiVariables can be used in equations. .. attribute:: sym

The symbolic CasADi variable used to define ode’s and optimization problems.

create_sym() MX[source]

Ensures a symbolic MX variable is created with each CasadiVariable instance, and that its dimensions are consistent.

property sym: MX
agentlib_mpc.models.casadi_model.get_symbolic(equation)[source]

agentlib_mpc.models.casadi_predictor module

class agentlib_mpc.models.casadi_predictor.ANNLayerTypes(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: str, Enum

BATCHNORMALIZATION = 'batch_normalization'
DENSE = 'dense'
FLATTEN = 'flatten'
LSTM = 'lstm'
RESCALING = 'rescaling'
class agentlib_mpc.models.casadi_predictor.BatchNormalization(layer: BatchNormalization)[source]

Bases: Layer

Batch Normalizing layer. Make sure the axis setting is set to two.

forward(input)[source]
class agentlib_mpc.models.casadi_predictor.CasadiANN(serialized_model: SerializedANN)[source]

Bases: CasadiPredictor

Generic implementations of sequential Keras models in CasADi.

property input_shape: tuple[int, int]

Input shape of Predictor.

class agentlib_mpc.models.casadi_predictor.CasadiGPR(serialized_model: SerializedGPR)[source]

Bases: CasadiPredictor

Generic implementation of scikit-learn Gaussian Process Regressor.

property input_shape: tuple[int, int]

Input shape of Predictor.

class agentlib_mpc.models.casadi_predictor.CasadiLinReg(serialized_model: SerializedLinReg)[source]

Bases: CasadiPredictor

Generic Casadi implementation of scikit-learn LinerRegression.

property input_shape: tuple[int, int]

Input shape of Predictor.

class agentlib_mpc.models.casadi_predictor.CasadiPredictor(serialized_model: SerializedMLModel)[source]

Bases: ABC

Protocol for generic Casadi implementation of various ML-Model-based predictors.

serialized_model

Serialized model which will be translated to a casadi model.

predictor_model

Predictor model from other libraries, which are translated to

casadi syntax.
sym_input

Symbolical input of predictor. Has the necessary shape of the input.

prediction_function

Symbolical casadi prediction function of the given model.

class Config[source]

Bases: object

arbitrary_types_allowed = True
classmethod from_serialized_model(serialized_model: SerializedMLModel)[source]

Initialize sub predictor class.

abstract property input_shape: tuple[int, int]

Input shape of Predictor.

property output_shape: tuple[int, int]

Output shape of Predictor.

predict(x: ndarray | MX) DM | MX[source]

Evaluate prediction function with input data. :param x: input data.

Returns:

results of evaluation of prediction function with input data.

class agentlib_mpc.models.casadi_predictor.Dense(layer: Dense)[source]

Bases: Layer

Fully connected layer.

forward(input)[source]
class agentlib_mpc.models.casadi_predictor.Flatten(layer: Layer)[source]

Bases: Layer

forward(input)[source]
class agentlib_mpc.models.casadi_predictor.LSTM(layer: LSTM)[source]

Bases: Layer

Long Short Term Memory cell.

forward(input)[source]
step(x_t, c_prev, h_prev)[source]
class agentlib_mpc.models.casadi_predictor.Layer(layer: Layer)[source]

Bases: object

Single layer of an artificial neural network.

static get_activation(function: str)[source]
update_dimensions()[source]

CasADi does only work with two dimensional arrays. So the dimensions must be updated.

agentlib_mpc.models.serialized_ml_model module

class agentlib_mpc.models.serialized_ml_model.CustomGPR(kernel=None, *, alpha=1e-10, optimizer='fmin_l_bfgs_b', n_restarts_optimizer=0, normalize_y=False, copy_X_train=True, random_state=None, data_handling=GPRDataHandlingParameters(normalize=False, scale=1.0, mean=None, std=None))[source]

Bases: GaussianProcessRegressor

Extends scikit-learn GaussianProcessRegressor with normalizing and scaling option by adding the attribute data_handling, customizing the predict function accordingly and adding a normalize function.

predict(X, return_std=False, return_cov=False)[source]

Overwrite predict method of GaussianProcessRegressor to include normalization.

set_predict_request(*, return_cov: bool | None | str = '$UNCHANGED$', return_std: bool | None | str = '$UNCHANGED$') CustomGPR

Request metadata passed to the predict method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to predict.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

New in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
  • return_cov (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_cov parameter in predict.

  • return_std (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for return_std parameter in predict.

Returns:

self – The updated object.

Return type:

object

set_score_request(*, sample_weight: bool | None | str = '$UNCHANGED$') CustomGPR

Request metadata passed to the score method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

New in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:

sample_weight (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for sample_weight parameter in score.

Returns:

self – The updated object.

Return type:

object

pydantic model agentlib_mpc.models.serialized_ml_model.GPRDataHandlingParameters[source]

Bases: BaseModel

Fields:
field mean: list | None = None

Mean values of input data for normalization. None if normalize equals to False.

field normalize: bool = False

Boolean which defines whether the input data will be normalized or not.

field scale: float = 1.0

Number by which the y vector is divided before training and multiplied after evaluation.

field std: list | None = None

Standard deviation of input data for normalization. None if normalize equals to False.

pydantic model agentlib_mpc.models.serialized_ml_model.GPRKernelParameters[source]

Bases: BaseModel

Config:
  • arbitrary_types_allowed: bool = True

Fields:
field constant_value: float = 1.0

The constant value which defines the covariance: k(x_1, x_2) = constant_value.

field constant_value_bounds: tuple | str = (1e-05, 100000.0)

The lower and upper bound on constant_value. If set to “fixed”, constant_value cannot be changed during hyperparameter tuning.

field length_scale: float | list = 1.0

The length scale of the kernel. If a float, an isotropic kernel is used. If an array, an anisotropic kernel is used where each dimension of l defines the length-scale of the respective feature dimension.

field length_scale_bounds: tuple | str = (1e-05, 100000.0)

The lower and upper bound on ‘length_scale’. If set to “fixed”, ‘length_scale’ cannot be changed during hyperparameter tuning.

field noise_level: float = 1.0

Parameter controlling the noise level (variance).

field noise_level_bounds: tuple | str = (1e-05, 100000.0)

The lower and upper bound on ‘noise_level’. If set to “fixed”, ‘noise_level’ cannot be changed during hyperparameter tuning.

field theta: list [Required]

Returns the (flattened, log-transformed) non-fixed gpr_parameters.

classmethod from_model(model: CustomGPR) GPRKernelParameters[source]
pydantic model agentlib_mpc.models.serialized_ml_model.GPRParameters[source]

Bases: BaseModel

Config:
  • arbitrary_types_allowed: bool = True

Fields:
field L: list [Required]

Lower-triangular Cholesky decomposition of the kernel in X_train.

field X_train: list [Required]

Feature vectors or other representations of training data (also required for prediction).

field alpha: float | list = 1e-10

Value added to the diagonal of the kernel matrix during fitting. This can prevent a potential numerical issue during fitting, by ensuring that the calculated values form a positive definite matrix. It can also be interpreted as the variance of additional Gaussian measurement noise on the training observations. Note that this is different from using a WhiteKernel. If an array is passed, it must have the same number of entries as the data used for fitting and is used as datapoint-dependent noise level. Allowing to specify the noise level directly as a parameter is mainly for convenience and for consistency with Ridge.

field log_marginal_likelihood_value: float [Required]

The log-marginal-likelihood of self.kernel_.theta.

field n_features_in: int [Required]

Number of features seen during fit.

field y_train: list [Required]

Target values in training data (also required for prediction).

classmethod from_model(model: CustomGPR) GPRParameters[source]
pydantic model agentlib_mpc.models.serialized_ml_model.LinRegParameters[source]

Bases: BaseModel

Fields:
field coef: list [Required]

Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features), while if only one target is passed, this is a 1D array of length n_features.

field intercept: float | list [Required]

Independent term in the linear model. Set to 0.0 if fit_intercept = False.

field n_features_in: int [Required]

Number of features seen during fit.

field rank: int [Required]

Rank of matrix X. Only available when X is dense.

field singular: list [Required]

Singular values of X. Only available when X is dense.

class agentlib_mpc.models.serialized_ml_model.MLModels(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: str, Enum

ANN = 'ANN'
GPR = 'GPR'
LINREG = 'LinReg'
pydantic model agentlib_mpc.models.serialized_ml_model.SerializedANN[source]

Bases: SerializedMLModel

Contains Keras ANN in serialized form and offers functions to transform Keras Sequential ANNs to SerializedANN objects (from_ANN) and vice versa (deserialize).

structure

architecture/structure of ANN saved as json string.

weights

weights and biases of all layers saved as lists of np.ndarrays.

Config:
  • protected_namespaces: tuple = ()

  • arbitrary_types_allowed: bool = True

Fields:
field model_type: MLModels = MLModels.ANN
field structure: str = None

The structure of the ANN as json string.

field weights: list = None

The weights of the ANN.

deserialize() Sequential[source]

Deserializes SerializedANN object and returns a Keras Sequential ANN.

classmethod serialize(model: Sequential, dt: float | int, input: dict[str, agentlib_mpc.data_structures.ml_model_datatypes.Feature], output: dict[str, agentlib_mpc.data_structures.ml_model_datatypes.OutputFeature], training_info: dict | None = None)[source]

Serializes Keras Sequential ANN and returns SerializedANN object

to_dict() dict[source]

Transforms self to a dictionary and the numpy arrays to lists, so they can be serialized.

pydantic model agentlib_mpc.models.serialized_ml_model.SerializedGPR[source]

Bases: SerializedMLModel

Contains scikit-learn GaussianProcessRegressor and its Kernel and provides functions to transform these to SerializedGPR objects and vice versa.

Attributes:

Config:
  • protected_namespaces: tuple = ()

  • arbitrary_types_allowed: bool = True

Fields:
field data_handling: GPRDataHandlingParameters = None

Information about data handling for GPR.

field gpr_parameters: GPRParameters = None

GPR parameters of GPR and its Kernel and Data of fitted GPR.

field kernel_parameters: GPRKernelParameters = None

Parameters of kernel of the fitted GPR.

field model_type: MLModels = MLModels.GPR
deserialize() CustomGPR[source]

Deserializes SerializedGPR object and returns a scikit learn GaussionProcessRegressor. :returns: GPR version of the SerializedGPR :rtype: gpr_fitted

classmethod serialize(model: CustomGPR, dt: float | int, input: dict[str, agentlib_mpc.data_structures.ml_model_datatypes.Feature], output: dict[str, agentlib_mpc.data_structures.ml_model_datatypes.OutputFeature], training_info: dict | None = None)[source]
Parameters:
  • model – GaussianProcessRegressor from ScikitLearn.

  • dt – The length of time step of one prediction of GPR in seconds.

  • input – GPR input variables with their lag order.

  • output – GPR output variables (which are automatically also inputs, as we need them recursively in MPC.) with their lag order.

  • training_info – Config of Trainer Class, which trained the Model.

Returns:

SerializedGPR version of the passed GPR.

pydantic model agentlib_mpc.models.serialized_ml_model.SerializedLinReg[source]

Bases: SerializedMLModel

Contains scikit-learn LinearRegression and provides functions to transform these to SerializedLinReg objects and vice versa.

Attributes:

Config:
  • protected_namespaces: tuple = ()

  • arbitrary_types_allowed: bool = True

Fields:
field model_type: MLModels = MLModels.LINREG
field parameters: LinRegParameters [Required]

Parameters of kernel of the fitted linear model.

deserialize() LinearRegression[source]

Deserializes SerializedLinReg object and returns a LinearRegression object of scikit-learn. :returns: LinearRegression version of the SerializedLinReg :rtype: linear_model_fitted

classmethod serialize(model: LinearRegression, dt: float | int, input: dict[str, agentlib_mpc.data_structures.ml_model_datatypes.Feature], output: dict[str, agentlib_mpc.data_structures.ml_model_datatypes.OutputFeature], training_info: dict | None = None)[source]
Parameters:
  • model – LinearRegression from ScikitLearn.

  • dt – The length of time step of one prediction of LinReg in seconds.

  • input – LinReg input variables with their lag order.

  • output – LinReg output variables (which are automatically also inputs, as ” “we need them recursively in MPC.) with their lag order.

  • training_info – Config of Trainer Class, which trained the Model.

Returns:

SerializedLinReg version of the passed linear model.

pydantic model agentlib_mpc.models.serialized_ml_model.SerializedMLModel[source]

Bases: BaseModel, ABC

Config:
  • protected_namespaces: tuple = ()

Fields:
field agentlib_mpc_hash: str [Optional]

The commit hash of the agentlib_mpc version this was created with.

field dt: float | int [Required]

The length of time step of one prediction of Model in seconds.

field input: dict[str, agentlib_mpc.data_structures.ml_model_datatypes.Feature] = None

Model input variables with their lag order.

field model_type: MLModels [Required]
field output: dict[str, agentlib_mpc.data_structures.ml_model_datatypes.OutputFeature] = None

Model output variables (which are automatically also inputs, as we need them recursively in MPC.) with their lag order.

field training_info: dict | None = None

Config of Trainer class with all the meta data used for training of the Model.

abstract deserialize()[source]

Deserializes SerializedMLModel object and returns a specific Machine Learning Model object. :returns: Machine Learning Model. :rtype: MLModel

classmethod load_serialized_model(model_data: dict | str | Path)[source]

Loads the ML model from a source

classmethod load_serialized_model_from_dict(model_data: dict)[source]

Loads SerializedMLModel object from a dict and creates a new specific Machine Learning Model object which is returned.

Parameters:

json_string – json string which will be loaded.

Returns:

SerializedMLModel object with data from json file.

classmethod load_serialized_model_from_file(path: Path)[source]

Loads SerializedMLModel object from a json file and creates a new specific Machine Learning Model object which is returned.

Parameters:

path – relative/absolute path which determines which json file will be loaded.

Returns:

SerializedMLModel object with data from json file.

classmethod load_serialized_model_from_string(json_string: str)[source]

Loads SerializedMLModel object from a json string and creates a new specific Machine Learning Model object which is returned.

Parameters:

json_string – json string which will be loaded.

Returns:

SerializedMLModel object with data from json file.

save_serialized_model(path: Path)[source]

Saves MLModel object as json string. :param path: relative/absolute path which determines where the json will be saved.

abstract classmethod serialize(model: Sequential | GaussianProcessRegressor | LinearRegression, dt: float | int, input: dict[str, agentlib_mpc.data_structures.ml_model_datatypes.Feature], output: dict[str, agentlib_mpc.data_structures.ml_model_datatypes.OutputFeature], training_info: dict | None = None)[source]
Parameters:
  • model – Machine Learning Model.

  • dt – The length of time step of one prediction of Model in seconds.

  • input – Model input variables with their lag order.

  • output – Model output variables (which are automatically also inputs, as we need them recursively in MPC.) with their lag order.

  • training_info – Config of Trainer Class, which trained the Model.

Returns:

SerializedMLModel version of the passed ML Model.

agentlib_mpc.models.serialized_ml_model.get_git_revision_short_hash() str[source]