agentlib_mpc.optimization_backends.casadi_.core package

Submodules

agentlib_mpc.optimization_backends.casadi_.core.VariableGroup module

class agentlib_mpc.optimization_backends.casadi_.core.VariableGroup.OptimizationParameter(name: 'str', full_symbolic: 'ca.MX', dim: 'int', ref_names: 'tuple[str]', full_names: 'tuple[str]', use_in_stage_function: 'bool', full_with_defaults: 'ca.MX', add_default_values: 'ca.Function')[source]

Bases: OptimizationQuantity

add_default_values: Function
classmethod declare(denotation: str, variables: list[agentlib_mpc.models.casadi_model.CasadiVariable], ref_list: list[str], use_in_stage_function=True, assert_complete: bool = False)[source]

Declares a group of optimization parameters that serve a purpose in the optimization problem. Typical groups are uncontrollable inputs or physical parameters.

Parameters:
  • denotation – The key of the variable, e.g. ‘p’, ‘d’, etc. Use this key in the discretization function to add the parameter at different stages of the optimization problem.

  • variables – A list of CasadiVariables including all parameters within this category.

  • ref_list – A list of names indicating which parameters in full_list are AgentVariables and need to be updated before each optimization.

  • use_in_stage_function – If False, the parameter is not added to the stage function. If True, the variable needs to be provided to the stage function at every point in the discretization function.

  • assert_complete – If True, throws an error if the ref_list does not contain all variables.

dim: int
full_names: tuple[str]
full_symbolic: MX
full_with_defaults: MX
name: str
ref_names: tuple[str]
use_in_stage_function: bool
class agentlib_mpc.optimization_backends.casadi_.core.VariableGroup.OptimizationQuantity(name: 'str', full_symbolic: 'ca.MX', dim: 'int', ref_names: 'tuple[str]', full_names: 'tuple[str]', use_in_stage_function: 'bool')[source]

Bases: object

dim: int
full_names: tuple[str]
full_symbolic: MX
name: str
ref_names: tuple[str]
use_in_stage_function: bool
class agentlib_mpc.optimization_backends.casadi_.core.VariableGroup.OptimizationVariable(name: 'str', full_symbolic: 'ca.MX', dim: 'int', ref_names: 'tuple[str]', full_names: 'tuple[str]', use_in_stage_function: 'bool', input_map: 'ca.Function', output_map: 'ca.Function', binary: 'bool')[source]

Bases: OptimizationQuantity

binary: bool
classmethod declare(denotation: str, variables: list[agentlib_mpc.models.casadi_model.CasadiVariable], ref_list: list[str], use_in_stage_function: bool = True, assert_complete: bool = False, binary: bool = False) OptimizationVariable[source]

Declares a group of optimization variables that serve a purpose in the optimization problem. Typical groups are states, the control inputs or slack variables.

Parameters:
  • binary – Flag, whether these variables are binary

  • denotation – The key of the variable, e.g. ‘X’, ‘U’, etc. Use this key in the discretization function to add the variable at different stages of the optimization problem. The optimal value of these variables will also be mapped to this key.

  • variables – A list of CasadiVariables or an MX/SX vector including all variables within this category.

  • ref_list – A list of names indicating which variables in full_list are AgentVariables and need to be updated before each optimization.

  • use_in_stage_function – If False, the variable is not added to the stage function. If True, the variable needs to be provided to the stage function at every point in the discretization function.

  • assert_complete – If True, throws an error if the ref_list does not contain all variables.

dim: int
full_names: tuple[str]
full_symbolic: MX
input_map: Function
name: str
output_map: Function
ref_names: tuple[str]
use_in_stage_function: bool

agentlib_mpc.optimization_backends.casadi_.core.casadi_backend module

class agentlib_mpc.optimization_backends.casadi_.core.casadi_backend.CasADiBackend(config: dict)[source]

Bases: OptimizationBackend

OptimizationBackend for solving the optimization problem with CasADi. Requires the model to be a CasADi model.

config_type

alias of CasadiBackendConfig

cost_function: Callable | None
discretization: DiscretizationT
discretization_types: dict[agentlib_mpc.data_structures.casadi_utils.DiscretizationMethod, Type[DiscretizationT]]
model: ModelT
reset_setup_attributes()[source]

Cleans all attributes that are used for optimization setup.

save_result_df(results: Results, now: float = 0)[source]

Save the results of solve into a dataframe at each time step.

Example results dataframe:

value_type variable … lower variable T_0 T_0_slack … T_0_slack mDot_0 time_step … 2 0.000000 298.160000 NaN … NaN NaN

101.431499 297.540944 -149.465942 … -inf 0.0 450.000000 295.779780 -147.704779 … -inf 0.0 798.568501 294.720770 -146.645769 … -inf 0.0

Parameters:
  • results

  • now

Returns:

setup_optimization(var_ref: VariableReference)[source]

Performs all necessary steps to make the solve method usable. To do this, it calls several auxiliary functions. These functions can be overloaded to change the resulting optimization problem.

Parameters:

var_ref – class with variable name lists sorted by function in the mpc.

solve(now: float, current_vars: dict[str, agentlib_mpc.data_structures.mpc_datamodels.MPCVariable]) Results[source]

Solves the optimization problem given the current values of the corresponding AgentVariables and system time. The standardization of return values is a work in progress.

Parameters:
  • now – Current time used for interpolation of input trajectories.

  • current_vars – Dict of AgentVariables holding the values relevant to the optimization problem. Keys are the names

Returns:

A dataframe with all optimization variables over their respective grids. Depending on discretization, can include many nan’s, so care should be taken when using this, e.g. always use dropna() after accessing a column.

Example:

variables mDot | T_0 | slack_T

time 0 0.1 | 298 | nan 230 nan | 297 | 3 470 nan | 296 | 2 588 nan | 295 | 1 700 0.05 | 294 | nan 930 nan | 294 | 0.1

system: SystemT
system_type: Type[SystemT]
var_ref: mpc_datamodels.VariableReference | None
pydantic model agentlib_mpc.optimization_backends.casadi_.core.casadi_backend.CasadiBackendConfig[source]

Bases: BackendConfig

Config:
  • extra: str = forbid

Fields:
Validators:
field build_batch_bat: Path | None = None

Path to a batch file, which can compile C code on windows.

field discretization_options: CasadiDiscretizationOptions [Optional]
field do_jit: bool | None = None

Boolean to turn JIT of the optimization problems on or off.

Validated by:
field model: dict [Required]
field name: str | None = None
field overwrite_result_file: bool | None = False
Validated by:
field results_file: Path | None = None
Validated by:
field save_results: bool | None = None
Validated by:
field solver: SolverOptions [Optional]
validator validate_compile  »  do_jit[source]

Checks whether code compilation should be done.

agentlib_mpc.optimization_backends.casadi_.core.discretization module

Holds classes that implement different transcriptions of the OCP

class agentlib_mpc.optimization_backends.casadi_.core.discretization.Discretization(options: CasadiDiscretizationOptions)[source]

Bases: ABC

opt_vars: holds symbolic variables during problem creation opt_vars_lb: holds symbolic variables during problem creation opt_vars_ub: holds symbolic variables during problem creation initial_guess: holds symbolic variables during problem creation opt_pars: holds symbolic variables during problem creation constraints: holds symbolic variables during problem creation constraints_lb: holds symbolic variables during problem creation constraints_ub: holds symbolic variables during problem creation objective_function: cost function during problem creation mpc_opt_vars (dict): holds the symbolic variables and grids during

problem creation sorted by type as in system_variables

mpc_opt_pars (dict): holds the symbolic variables and grids during

problem creation sorted by type as in system_parameters

add_constraint(constraint_function: MX | SX | Sparsity | DM | float | int, lb: MX | SX | Sparsity | DM | float | int = None, ub: MX | SX | Sparsity | DM | float | int = None, *, gap_closing: bool = False)[source]

Add a constraint to the optimization problem. If no bounds are given, adds an equality constraint.

add_opt_par(quantity: OptimizationParameter, post_den: str = '')[source]

Create an optimization parameter and append to all the associated lists.

denotation[str]: the key of the parameter, e.g. ‘P’, ‘Q’, … dimension[int]: the dimension of the parameter post_den[str]: string to add to casadi MX after denotation (for debugging)

add_opt_var(quantity: OptimizationVariable, lb: MX = None, ub: MX = None, guess: float = None, post_den: str = '')[source]

Create an optimization variable and append to all the associated lists. If lb or ub are given, they override the values provided at runtime! The usual application of this is, to fix the initial value of a state to a parameter.

Parameters:
  • quantity – corresponding system variable

  • lb – lower bound of the variable

  • ub – upper bound of the variable

  • guess – default for the initial guess

  • post_den – string to add to casadi MX after denotation (for debugging)

property binary_vars: list[bool]

List specifying for every optimization variable, whether it is binary.

constraints: list[casadi.casadi.MX] | MX
constraints_lb: list[casadi.casadi.MX]
constraints_ub: list[casadi.casadi.MX]
create_nlp_in_out_mapping(system: System)[source]

Function creating mapping functions between the MPC variables ordered by type (as defined in declare_quantities and the raw input/output vector of the CasADi NLP.

equalities: list[bool]
grid(var: OptimizationQuantity) list[float][source]
initial_guess: list[casadi.casadi.MX]
initialize(system: System, solver_factory: SolverFactory)[source]

Initializes the trajectory optimization problem, creating all symbolic variables of the OCP, the mapping function and the numerical solver.

k: int
mpc_opt_pars: dict[str, agentlib_mpc.data_structures.casadi_utils.OptParMXContainer]
mpc_opt_vars: dict[str, agentlib_mpc.data_structures.casadi_utils.OptVarMXContainer]
property nlp: dict[str, casadi.casadi.MX]

The nlp dict that casadi solvers need for instantiation

objective_function: MX | SX | Sparsity | DM | float | int
only_positive_times_in_results = True
opt_pars: list[casadi.casadi.MX] | MX
opt_vars: list[casadi.casadi.MX] | MX
opt_vars_lb: list[casadi.casadi.MX]
opt_vars_ub: list[casadi.casadi.MX]
pred_time: float
solve(mpc_inputs: dict[str, casadi.casadi.DM]) Results[source]

Solves the discretized trajectory optimization problem.

Parameters:

mpc_inputs – Casadi Matrices specifying the input of all different types of optimization parameters. Matrices consist of different variable rows and have a column for each time step in the discretization. There are separate matrices for each input type (as defined in the System), and also for the upper and lower boundaries of variables respectively.

Returns:

The complete evolution of the states, inputs and boundaries of each

variable and parameter over the prediction horizon, as well as solve statistics.

Return type:

Results

class agentlib_mpc.optimization_backends.casadi_.core.discretization.Results(matrix: casadi.casadi.MX, grid: list[float], columns: pandas.core.indexes.multi.MultiIndex, stats: dict, variable_grid_indices: dict[str, list[int]], _variable_name_to_index: dict[str, int] = None)[source]

Bases: object

columns: MultiIndex
property df: DataFrame
grid: list[float]
matrix: MX
stats: dict
stats_line(index: str) str[source]
variable_grid_indices: dict[str, list[int]]
variable_lookup() dict[str, int][source]

Creates a mapping from variable names to the column index in the Matrix

write_columns(file: Path)[source]
write_stats_columns(file: Path)[source]

agentlib_mpc.optimization_backends.casadi_.core.system module

Holds the System class, which knows the model

class agentlib_mpc.optimization_backends.casadi_.core.system.System[source]

Bases: ABC

Examples

class MySystem(System):

# variables states: OptimizationVariable controls: OptimizationVariable algebraics: OptimizationVariable outputs: OptimizationVariable

# parameters non_controlled_inputs: OptimizationParameter model_parameters: OptimizationParameter initial_state: OptimizationParameter

# dynamics model_constraints: Constraint cost_function: ca.MX ode: ca.MX

def initialize(self, model: CasadiModel, var_ref: VariableReference):

self.states = OptimizationVariable.declare(

denotation=”state”, variables=model.get_states(var_ref.states), ref_list=var_ref.states, assert_complete=True,

)

.

)

abstract initialize(model: CasadiModel, var_ref: VariableReference)[source]
property parameters: list[agentlib_mpc.optimization_backends.casadi_.core.VariableGroup.OptimizationParameter]
property quantities: list[Union[agentlib_mpc.optimization_backends.casadi_.core.VariableGroup.OptimizationParameter, agentlib_mpc.optimization_backends.casadi_.core.VariableGroup.OptimizationVariable]]
property variables: list[agentlib_mpc.optimization_backends.casadi_.core.VariableGroup.OptimizationVariable]