Python Interface#
acados_template
is a Python package that can be used to specify optimal control problems from Python and to generate self-contained C code to solve them using acados
.
The pip
package is based on templated code (C files, Header files and Makefiles), which are rendered from Python using the templating engine Tera
.
The generated C code can be compiled into a self-contained C library that can be deployed on an embedded system.
One can interact with the generated solver using the Python wrapper.
There is a ctypes
based wrapper which is the default and a cython
based wrapper which allows for faster interaction with the C code, to allow deployment of the acados
solver in a Python framework with less overhead.
Examples#
Examples for Python can be found in the folder examples/acados_python
of the acados
repository.
Optimal Control Problem description#
The Python interface relies on the same problem formulation as the MATLAB interface see here. Currently, Python >= 3.8 is tested.
Installation#
Compile and install
acados
by following the CMake installation instructions.Optional: Recommended. Create a Python virtual environment using
virtualenv
.virtualenv env --python=/usr/bin/python3 # Source the environment source env/bin/activate
Note: There are known path issues with more high level virtual environment managers. Such as
conda
,miniconda
,Pycharm
. It is not recommended to use them. However, if you need to do so and have issues, please have a look in theacados
forum.Install
acados_template
Python package:pip install -e <acados_root>/interfaces/acados_template
Note: The option
-e
makes the installation editable, so you can seamlessly switch to a lateracados
version and make changes in the Python interface yourself.Add the path to the compiled shared libraries
libacados.so, libblasfeo.so, libhpipm.so
toLD_LIBRARY_PATH
(default path is<acados_root/lib>
) by running:export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:"<acados_root>/lib" export ACADOS_SOURCE_DIR="<acados_root>"
NOTE: On MacOS
DYLD_LIBRARY_PATH
should be used instead ofLD_LIBRARY_PATH
. Hint: you can add these lines to your.bashrc
/.zshrc
.Run a Python example to check that everything works. We suggest to get started with the example
<acados_root>/examples/acados_python/getting_started/minimal_example_ocp.py
. The example has to be run from the folder in which it is located.Optional: Can be done automatically through the interface: In order to be able to successfully render C code templates, you need to download the
t_renderer
binaries for your platform from acados/tera_renderer and place them in<acados_root>/bin
Please strip the version and platform from the binaries (e.g.t_renderer-v0.0.34 -> t_renderer
). Notice that you might need to maket_renderer
executable. Runexport ACADOS_SOURCE_DIR=<acados_root>
such that the location of acados will be known to the Python package at run time.Optional: Set
acados_lib_path
,acados_include_path
. If you want the generated Makefile to refer to a specific path (e.g. when cross-compiling or compiling from a location different from the one where you generate the C code), you will have to set these paths accordingly in the generating Python code.
Windows 10+ (WSL) and VSCode#
Virtual Environment#
Follow the installation instructions above, using a virtual environment.
Connect to VS-Code#
Install VS-Code on Windows
Install the Remote Development Extension.
Inside the WSL Ubuntu shell run
code .
to start VS-Code in the current folder.
Select the created virtual environment as Python interpreter.
Windows#
The Python interface of acados can run natively under Windows using the CMake process.
Take a look at the CMake installation instructions for Workflow with Microsoft Visual C Compiler (MSVC).
We suggest to get started with the example
<acados_root>/examples/acados_python/getting_started/minimal_example_ocp_cmake.py
. It uses CMake instead of Make by providing an instance of the CMakeBuilder class to the constructor of AcadosOcpSolver
or AcadosSimSolver
. Depending on your Visual Studio Version the CMake generator might have to be adapted (see CMakeBuilder.generator
).
Overview#
The following image shows an overview of the available classes in the acados
Python interface and their dependencies.
acados
OCP solver interface#
The class AcadosOcp
can be used to formulate optimal control problems (OCP), for which an acados
solver (AcadosOcpSolver
) can be created.
The interface to interact with the acados
OCP solver in C is based on ctypes.
Additionally, there is the option to use a Cython based wrapper around the C part.
This offers faster interaction with the solver, because getter and setter calls, which include shape checking are done in compiled C code.
The cython based wrapper is called AcadosOcpSolverCython
and was added in PR #791.
AcadosOcpSolverCython
and AcadosOcpSolver
offer the same functionality and equivalent behavior is ensured in CI tests.
AcadosOcpSolver
#
- class acados_template.acados_ocp_solver.AcadosOcpSolver(acados_ocp: Union[AcadosOcp, AcadosMultiphaseOcp], json_file=None, simulink_opts=None, build=True, generate=True, cmake_builder: Optional[CMakeBuilder] = None, verbose=True)#
Class to interact with the acados ocp solver C object.
- param acados_ocp
type
AcadosOcp
orAcadosMultiphaseOcp
- description of the OCP for acados- param json_file
name for the json file used to render the templated code - default: acados_ocp_nlp.json
- __get_pointers_solver()#
Private function to get the pointers for solver
- property acados_lib#
acados_lib - acados shared library
- property acados_lib_uses_omp#
acados_lib_uses_omp - flag indicating whether the acados library has been compiled with openMP.
- classmethod build(code_export_dir, with_cython=False, cmake_builder: Optional[CMakeBuilder] = None, verbose: bool = True)#
- Builds the code for an acados OCP solver, that has been generated in code_export_dir
- param code_export_dir
directory in which acados OCP solver has been generated, see generate()
- param with_cython
option indicating if the cython interface is build, default: False.
- param cmake_builder
type
CMakeBuilder
generate a CMakeLists.txt and use the CMake pipeline instead of a Makefile (CMake seems to be the better option in conjunction with MS Visual Studio); default: None- param verbose
indicating if build command is printed
- constraints_set(stage_, field_, value_, api='warn')#
Set numerical data in the constraint module of the solver.
- param stage
integer corresponding to shooting node
- param field
string in [‘lbx’, ‘ubx’, ‘lbu’, ‘ubu’, ‘lg’, ‘ug’, ‘lh’, ‘uh’, ‘uphi’, ‘C’, ‘D’]
- param value
of appropriate size
- cost_set(stage_: int, field_: str, value_, api='warn')#
Set numerical data in the cost module of the solver.
- param stage
integer corresponding to shooting node
- param field
string, e.g. ‘yref’, ‘W’, ‘ext_cost_num_hess’, ‘zl’, ‘zu’, ‘Zl’, ‘Zu’, ‘scaling’
- param value
of appropriate size
Note: by default the cost is scaled with the time step, and the terminal cost term scaled with 1. This can be overwritten by setting the ‘scaling’ field.
- classmethod create_cython_solver(json_file)#
Returns an AcadosOcpSolverCython object.
This is an alternative Cython based Python wrapper to the acados OCP solver in C. This offers faster interaction with the solver, because getter and setter calls, which include shape checking are done in compiled C code.
The default wrapper AcadosOcpSolver is based on ctypes.
- custom_update(data_: ndarray)#
A custom function that can be implemented by a user to be called between solver calls. By default this does nothing. The idea is to have a convenient wrapper to do complex updates of parameters and numerical data efficiently in C, in a function that is compiled into the solver library and can be conveniently used in the Python environment.
- dump_last_qp_to_json(filename: str = '', overwrite=False)#
Dumps the latest QP data into a json file
- param filename
if not set, use name + timestamp + ‘.json’
- param overwrite
if false and filename exists add timestamp to filename
- eval_adjoint_solution_sensitivity(seed_x: Optional[Sequence[Tuple[int, ndarray]]], seed_u: Optional[Sequence[Tuple[int, ndarray]]], with_respect_to: str = 'p_global', sanity_checks: bool = True) ndarray #
- Evaluate the adjoint sensitivity of the solution with respect to the parameters.
- :param seed_xSequence of tuples of the form (stage: int, seed_vec: np.ndarray).
The stage is the stage at which the seed_vec is applied, and seed_vec is the seed for the states at that stage with shape (nx, n_seeds)
- :param seed_uSequence of tuples of the form (stage: int, seed_vec: np.ndarray).
The stage is the stage at which the seed_vec is applied, and seed_vec is the seed for the controls at that stage with shape (nu, n_seeds).
:param with_respect_to : string in [“p_global”] :param sanity_checks : bool - whether to perform sanity checks, turn off for minimal overhead, default: True
- eval_and_get_optimal_value_gradient(with_respect_to: str = 'initial_state') ndarray #
Returns the gradient of the optimal value function w.r.t. what is specified in with_respect_to.
Disclaimer: This function only returns reasonable values if the solver has converged for the current problem instance.
Notes: - for field initial_state, the gradient is the Lagrange multiplier of the initial state constraint. The gradient computation consists of adding the Lagrange multipliers corresponding to the upper and lower bound of the initial state.
for field initial_control, the gradient is the Lagrange multiplier of the initial control constraint.
The gradient computation consists of adding the Lagrange multipliers corresponding to the upper and lower bound of the initial control. This requires the OCP to have control bounds with lbu = ubu at the first stage, i.e. the gradient of the state-action value function or Q-function is computed.
for field p_global, the gradient of the Lagrange function w.r.t. the global parameters is computed.
- Parameters
with_respect_to – string in [“initial_state”, “initial_control”, “p_global”]
- eval_param_sens(index: int, stage: int = 0, field='ex')#
Calculate the sensitivity of the current solution with respect to the initial state component of index.
NOTE: Correct computation of sensitivities requires
HPIPM as QP solver,
the usage of an exact Hessian,
positive definiteness of the full-space Hessian if the square-root version of the Riccati recursion is used OR positive definiteness of the reduced Hessian if the classic Riccati recursion is used (compare: solver_options.qp_solver_ric_alg),
the solution of at least one QP in advance to evaluation of the sensitivities as the factorization is reused.
- param index
integer corresponding to initial state index in range(nx)
- eval_solution_sensitivity(stages: Union[int, List[int]], with_respect_to: str, return_sens_x: bool = True, return_sens_u: bool = True, return_sens_pi: bool = False, return_sens_lam: bool = False, return_sens_su: bool = False, return_sens_sl: bool = False) Dict #
Evaluate the sensitivity of the current solution x_i, u_i with respect to the initial state or the parameters for all stages i in stages.
- param stages
stages for which the sensitivities are returned, int or list of int
- param with_respect_to
string in [“initial_state”, “p_global”]
- param return_sens_x
Flag indicating whether sensitivities of x should be returned. Default: True.
- param return_sens_u
Flag indicating whether sensitivities of u should be returned. Default: True.
- param return_sens_pi
Flag indicating whether sensitivities of pi should be returned. Default: False.
- param return_sens_lam
Flag indicating whether sensitivities of lam should be returned. Default: False.
- param return_sens_su
Flag indicating whether sensitivities of su should be returned. Default: False.
- param return_sens_sl
Flag indicating whether sensitivities of sl should be returned. Default: False.
- returns
A dictionary with the solution sensitivities with fields sens_x, sens_u, sens_pi, sens_lam, sens_su, sens_sl if corresponding flags were set. If stages is a list, sens_x, sens_lam, sens_su, sens_sl is a list of the same length. For sens_u, sens_pi, the list has length len(stages) or len(stages)-1 depending on whether N is included or not. If stages is a scalar, the returned sensitivities are np.ndarrays of shape (nfield[stages], ngrad).
Note
Correct computation of sensitivities requires
HPIPM as QP solver,
the usage of an exact Hessian,
positive definiteness of the full-space Hessian if the square-root version of the Riccati recursion is used OR positive definiteness of the reduced Hessian if the classic Riccati recursion is used (compare: solver_options.qp_solver_ric_alg),
the solution of at least one QP in advance to evaluation of the sensitivities as the factorization is reused.
Note
Timing of the sensitivities computation consists of time_solution_sens_lin, time_solution_sens_solve.
Note
Solution sensitivities with respect to parameters are currently implemented assuming the parameter vector p is global within the OCP, i.e. p=p_i with i=0, …, N.
Note
Solution sensitivities with respect to parameters are currently implemented only for parametric discrete dynamics and parametric external costs (in particular, parametric constraints are not covered).
- classmethod generate(acados_ocp: Union[AcadosOcp, AcadosMultiphaseOcp], json_file: str, simulink_opts=None, cmake_builder: Optional[CMakeBuilder] = None)#
- Generates the code for an acados OCP solver, given the description in acados_ocp.
- param acados_ocp
type Union[AcadosOcp, AcadosMultiphaseOcp] - description of the OCP for acados
- param json_file
name for the json file used to render the templated code - default: acados_ocp_nlp.json
- param simulink_opts
Options to configure Simulink S-function blocks, mainly to activate possible inputs and outputs; default: None
- param cmake_builder
type
CMakeBuilder
generate a CMakeLists.txt and use the CMake pipeline instead of a Makefile (CMake seems to be the better option in conjunction with MS Visual Studio); default: None
- get(stage_: int, field_: str)#
Get the last solution of the solver:
- param stage
integer corresponding to shooting node
- param field
string in [‘x’, ‘u’, ‘z’, ‘pi’, ‘lam’, ‘sl’, ‘su’, ‘p’, ‘sens_u’, ‘sens_pi’, ‘sens_x’, ‘sens_lam’, ‘sens_sl’, ‘sens_su’]
Note
regarding lam:
the inequalities are internally organized in the following order:
[ lbu lbx lg lh lphi ubu ubx ug uh uphi;
lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi]
Note
pi: multipliers for dynamics equality constraints
lam: multipliers for inequalities
t: slack variables corresponding to evaluation of all inequalities (at the solution)
sl: slack variables of soft lower inequality constraints
su: slack variables of soft upper inequality constraints
- get_cost() float #
Returns the cost value of the current solution.
- get_dim_flat(field: str)#
Get dimension of flattened iterate.
- get_flat(field_: str) ndarray #
Get concatenation of all stages of last solution of the solver.
- param field
string in [‘x’, ‘u’, ‘z’, ‘pi’, ‘lam’, ‘sl’, ‘su’, ‘p’]
- get_from_qp_in(stage_: int, field_: str)#
Get numerical data from the current QP.
- param stage
integer corresponding to shooting node
- param field
string in [‘A’, ‘B’, ‘b’, ‘Q’, ‘R’, ‘S’, ‘q’, ‘r’, ‘C’, ‘D’, ‘lg’, ‘ug’, ‘lbx’, ‘ubx’, ‘lbu’, ‘ubu’]
Note: - additional supported fields are [‘P’, ‘K’, ‘Lr’], which can be extracted form QP solver PARTIAL_CONDENSING_HPIPM. - for PARTIAL_CONDENSING_* QP solvers, the following additional fields are available: [‘pcond_Q’, ‘pcond_R’, ‘pcond_S’]
- get_hessian_block(stage: int) ndarray #
Get Hessian block from last QP at stage i In HPIPM form [[R, S^T], [S, Q]]
- get_initial_residuals() ndarray #
Returns an array of the form [res_stat, res_eq, res_ineq, res_comp]. Residuals: residuals of initial iterate in previous solver call
- get_residuals(recompute=False)#
Returns an array of the form [res_stat, res_eq, res_ineq, res_comp]. The residuals has to be computed for SQP_RTI solver, since it is not available by default.
res_stat: stationarity residual
res_eq: residual wrt equality constraints (dynamics)
res_ineq: residual wrt inequality constraints (constraints)
res_comp: residual wrt complementarity conditions
- get_stats(field_: str) Union[int, float, ndarray] #
Get the information of the last solver call.
- param field
string in [‘statistics’, ‘time_tot’, ‘time_lin’, ‘time_sim’, ‘time_sim_ad’, ‘time_sim_la’, ‘time_qp’, ‘time_qp_solver_call’, ‘time_reg’, ‘nlp_iter’, ‘sqp_iter’, ‘residuals’, ‘qp_iter’, ‘alpha’]
- Available fileds:
time_tot: total CPU time previous call
time_lin: CPU time for linearization
time_sim: CPU time for integrator
time_sim_ad: CPU time for integrator contribution of external function calls
time_sim_la: CPU time for integrator contribution of linear algebra
time_qp: CPU time qp solution
time_qp_solver_call: CPU time inside qp solver (without converting the QP)
time_qp_xcond: time_glob: CPU time globalization
time_solution_sensitivities: CPU time for previous call to eval_param_sens
time_solution_sens_lin: CPU time for linearization in eval_param_sens
time_solution_sens_solve: CPU time for solving in eval_solution_sensitivity
time_reg: CPU time regularization
time_preparation: CPU time for last preparation phase, relevant for (AS-)RTI, zero otherwise
time_feedback: CPU time for last feedback phase, relevant for (AS-)RTI, otherwise returns total compuation time.
sqp_iter: number of SQP iterations
nlp_iter: number of NLP solver iterations (DDP or SQP)
qp_stat: status of QP solver
qp_iter: vector of QP iterations for last SQP call
statistics: table with info about last iteration
stat_m: number of rows in statistics matrix
stat_n: number of columns in statistics matrix
residuals: residuals of current iterate
alpha: step sizes of SQP iterations
- get_status() int #
Returns the status of the last solver call.
- Status codes:
0: Success (ACADOS_SUCCESS)
1: NaN detected (ACADOS_NAN_DETECTED)
2: Maximum number of iterations reached (ACADOS_MAXITER)
3: Minimum step size reached (ACADOS_MINSTEP)
4: QP solver failed (ACADOS_QP_FAILURE)
5: Solver created (ACADOS_READY)
6: Problem unbounded (ACADOS_UNBOUNDED)
7: Solver timeout (ACADOS_TIMEOUT)
See return_values in acados/acados
- load_iterate(filename: str, verbose: bool = True)#
Loads the iterate stored in json file with filename into the ocp solver. Note: This does not contain the iterate of the integrators, and the parameters.
- load_iterate_from_flat_obj(iterate: AcadosOcpFlattenedIterate) None #
Loads the provided iterate into the OCP solver. Note: The iterate object does not contain the the parameters.
- load_iterate_from_obj(iterate: AcadosOcpIterate)#
Loads the provided iterate into the OCP solver. Note: The iterate object does not contain the the parameters.
- options_set(field_, value_)#
Set options of the solver.
- param field
string, e.g. ‘print_level’, ‘rti_phase’, ‘globalization_fixed_step_length’, ‘globalization_alpha_min’, ‘globalization_alpha_reduction’, ‘qp_warm_start’, ‘globalization_line_search_use_sufficient_descent’, ‘globalization_full_step_dual’, ‘globalization_use_SOC’, ‘qp_tol_stat’, ‘qp_tol_eq’, ‘qp_tol_ineq’, ‘qp_tol_comp’, ‘qp_tau_min’, ‘qp_mu0’, ‘qp_print_level’, ‘globalization_funnel_init_increase_factor’, ‘globalization_funnel_init_upper_bound’, ‘globalization_funnel_sufficient_decrease_factor’, ‘globalization_funnel_kappa’, ‘globalization_funnel_fraction_switching_condition’, ‘globalization_funnel_initial_penalty_parameter’, ‘levenberg_marquardt’, ‘adaptive_levenberg_marquardt_lam’, ‘adaptive_levenberg_marquardt_mu_min’, ‘adaptive_levenberg_marquardt_mu0’,
- param value
of type int, float, string, bool
qp_tol_stat: QP solver tolerance stationarity
qp_tol_eq: QP solver tolerance equalities
qp_tol_ineq: QP solver tolerance inequalities
qp_tol_comp: QP solver tolerance complementarity
qp_tau_min: for HPIPM QP solvers: minimum value of barrier parameter in HPIPM
qp_mu0: for HPIPM QP solvers: initial value for complementarity slackness
warm_start_first_qp: indicates if first QP in SQP is warm_started
rti_phase: 0: PREPARATION_AND_FEEDBACK, 1: PREPARATION, 2: FEEDBACK; only support for nlp_solver = ‘SQP_RTI’
- print_statistics()#
- prints statistics of previous solver run as a table:
iter: iteration number
res_stat: stationarity residual
res_eq: residual wrt equality constraints (dynamics)
res_ineq: residual wrt inequality constraints (constraints)
res_comp: residual wrt complementarity conditions
qp_stat: status of QP solver
qp_iter: number of QP iterations
alpha: SQP step size
qp_res_stat: stationarity residual of the last QP solution
qp_res_eq: residual wrt equality constraints (dynamics) of the last QP solution
qp_res_ineq: residual wrt inequality constraints (constraints) of the last QP solution
qp_res_comp: residual wrt complementarity conditions of the last QP solution
- qp_diagnostics(hessian_type: str = 'FULL_HESSIAN')#
Compute some diagnostic values for the last QP. result = ocp_solver.qp_diagnostics(hessian_type). Possible values are ‘FULL_HESSIAN’ or ‘PROJECTED_HESSIAN’
returns a dictionary with the following fields: - min_eigv_stage: dict with minimum eigenvalue for each Hessian block. - max_eigv_stage: dict with maximum eigenvalue for each Hessian block. - condition_number_stage: dict with condition number for each Hessian block. - condition_number_global: condition number for the full Hessian. - min_eigv_global: minimum eigenvalue for the full Hessian. - min_abs_eigv_global: minimum absolute eigenvalue for the full Hessian. - max_eigv_global: maximum eigenvalue for the full Hessian.
for the ‘PROJECTED_HESSIAN’ it also includes - min_eigv_P_global: minimum eigenvalue of P matrices - min_abs_eigv_P_global: minimum absolute eigenvalue of P matrices
- reset(reset_qp_solver_mem=1)#
Sets current iterate to all zeros.
- set(stage_: int, field_: str, value_: ndarray)#
Set numerical data inside the solver.
- param stage
integer corresponding to shooting node
- param field
string in [‘x’, ‘u’, ‘pi’, ‘lam’, ‘p’, ‘xdot_guess’, ‘z_guess’, ‘sens_x’, ‘sens_u’]
Note
regarding lam:
the inequalities are internally organized in the following order:
[ lbu lbx lg lh lphi ubu ubx ug uh uphi;
lsbu lsbx lsg lsh lsphi usbu usbx usg ush usphi]
Note
pi: multipliers for dynamics equality constraints
lam: multipliers for inequalities
t: slack variables corresponding to evaluation of all inequalities (at the solution)
sl: slack variables of soft lower inequality constraints
su: slack variables of soft upper inequality constraints
- set_flat(field_: str, value_: ndarray) None #
Set concatenation solver initialization .
- param field
string in [‘x’, ‘u’, ‘z’, ‘pi’, ‘lam’, ‘sl’, ‘su’, ‘p’]
- set_new_time_steps(new_time_steps)#
Set new time steps. Recreates the solver if N changes.
- param new_time_steps
1 dimensional np array of new time steps for the solver
Note
This allows for different use-cases: either set a new size of time_steps or a new distribution of the shooting nodes without changing the number, e.g., to reach a different final time. Both cases do not require a new code export and compilation.
- set_p_global_and_precompute_dependencies(data_: ndarray)#
Sets values of p_global and precomputes all parts of the CasADi graphs of all other functions that only depend on p_global.
- set_params_sparse(stage_: int, idx_values_: ndarray, param_values_)#
set parameters of the solvers external function partially: Pseudo: solver.param[idx_values] = param_values; Parameters:
- param stage
integer corresponding to shooting node
- param idx_values
0 based np array (or iterable) of integers: indices of parameter to be set
- param param_values
new parameter values as numpy array
shared_lib - solver shared library
- solve() int #
Solve the ocp with current input.
- Returns
status of the solver
- solve_for_x0(x0_bar, fail_on_nonzero_status=True, print_stats_on_failure=True)#
Wrapper around solve() which sets initial state constraint, solves the OCP, and returns u0.
- store_iterate(filename: str = '', overwrite: bool = False, verbose: bool = True)#
Stores the current iterate of the OCP solver in a json file. Note: This does not contain the iterate of the integrators, and the parameters.
- param filename
if not set, use f’{self.name}_iterate.json’
- param overwrite
if false and filename exists add timestamp to filename
- store_iterate_to_flat_obj() AcadosOcpFlattenedIterate #
Returns the current iterate of the OCP solver as an AcadosOcpFlattenedIterate.
- store_iterate_to_obj() AcadosOcpIterate #
Returns the current iterate of the OCP solver as an AcadosOcpIterate.
- update_qp_solver_cond_N(qp_solver_cond_N: int)#
Recreate solver with new value qp_solver_cond_N with a partial condensing QP solver. This function is relevant for code reuse, i.e., if either set_new_time_steps(…) is used or the influence of a different qp_solver_cond_N is studied without code export and compilation.
- param qp_solver_cond_N
new number of condensing stages for the solver
Note
This function can only be used in combination with a partial condensing QP solver.
Note
After set_new_time_steps(…) is used and depending on the new number of time steps it might be necessary to change qp_solver_cond_N as well (using this function), i.e., typically qp_solver_cond_N < N.
AcadosOcp
#
- class acados_template.acados_ocp.AcadosOcp(acados_path='')#
Class containing the full description of the optimal control problem. This object can be used to create an
acados_template.acados_ocp_solver.AcadosOcpSolver
.The class has the following properties that can be modified to formulate a specific OCP, see below:
constraints
of typeacados_template.acados_ocp_constraints.AcadosOcpConstraints
solver_options
of typeacados_template.acados_ocp_options.AcadosOcpOptions
acados_include_path
(set automatically)shared_lib_ext
(set automatically)acados_lib_path
(set automatically)parameter_values
- used to initialize the parameters (can be changed)p_global_values
- used to initialize the global parameters (can be changed)
- __get_template_list(cmake_builder=None) list #
returns a list of tuples in the form: (input_filename, output_filname) or (input_filename, output_filname, output_directory)
- acados_include_path#
Path to acados include directory (set automatically), type: string
- acados_lib_path#
Path to where acados library is located, type: string
- add_linear_constraint(C: ndarray, D: ndarray, lg: ndarray, ug: ndarray) None #
Add a linear constraint of the form lg <= C * x + D * u <= ug to the OCP.
- augment_with_t0_param() None #
Add a parameter t0 to the model and set it to 0.0.
- code_export_directory#
Path to where code will be exported. Default: c_generated_code.
- constraints#
Constraints definitions, type
acados_template.acados_ocp_constraints.AcadosOcpConstraints
- copy_path_cost_to_stage_0()#
Set all cost definitions at stage 0 to the corresponding path cost definitions.
- cost#
Cost definitions, type
acados_template.acados_ocp_cost.AcadosOcpCost
- dims#
Dimension definitions, type
acados_template.acados_dims.AcadosOcpDims
- formulate_constraint_as_Huber_penalty(constr_expr: Union[SX, MX], weight: float, upper_bound: Optional[float] = None, lower_bound: Optional[float] = None, residual_name: str = 'new_residual', huber_delta: float = 1.0, use_xgn=True, min_hess=0) None #
Formulate a constraint as Huber penalty and add it to the current cost.
use_xgn: if true an XGN Hessian is used, if false a GGN Hessian (= exact Hessian, in this case) is used. min_hess: provide a minimum value for the hessian weight: weight of the penalty corresponding to Hessian in quadratic region
- formulate_constraint_as_L2_penalty(constr_expr: SX, weight: float, upper_bound: Optional[float], lower_bound: Optional[float], residual_name: str = 'new_residual', constraint_type: str = 'path') None #
Formulate a constraint as an L2 penalty and add it to the current cost.
- property json_file#
Name of the json file where the problem description is stored.
- make_consistent(is_mocp_phase=False) None #
Detect dimensions, perform sanity checks
- model#
Model definitions, type
acados_template.acados_model.AcadosModel
- property p_global_values#
initial values for \(p_\text{global}\) vector, see AcadosModel.p_global - can be updated. Type: numpy.ndarray of shape (np_global, ).
- property parameter_values#
\(p\) - initial values for parameter vector - can be updated stagewise
- simulink_opts#
Options to configure Simulink S-function blocks, mainly to activate possible Inputs and Outputs.
- solver_options#
Solver Options, type
acados_template.acados_ocp_options.AcadosOcpOptions
- translate_cost_to_external_cost(p: Optional[Union[SX, MX]] = None, p_values: Optional[ndarray] = None, p_global: Optional[Union[SX, MX]] = None, p_global_values: Optional[ndarray] = None, yref_0: Optional[Union[SX, MX]] = None, yref: Optional[Union[SX, MX]] = None, yref_e: Optional[Union[SX, MX]] = None, W_0: Optional[Union[SX, MX]] = None, W: Optional[Union[SX, MX]] = None, W_e: Optional[Union[SX, MX]] = None)#
Translates cost to EXTERNAL cost and optionally provide parametrization of references and weighting matrices. p: Optional CasADi symbolics with additional stagewise parameters which are used to define yref_0, yref, yref_e, W_0, W, W_e. Will be appended to model.p. p_values: numpy array with the same shape as p providing initial parameter values. p_global: Optional CasADi symbolics with additional global parameters which are used to define yref_0, yref, yref_e, W_0, W, W_e. Will be appended to model.p_global. p_global_values: numpy array with the same shape as p_global providing initial global parameter values. W_0, W, W_e: Optional CasADi expressions which should be used instead of the numerical values provided by the cost module, shapes should be (ny_0, ny_0), (ny, ny), (ny_e, ny_e). yref_0, yref, yref_e: Optional CasADi expressions which should be used instead of the numerical values provided by the cost module, shapes should be (ny_0, 1), (ny, 1), (ny_e, 1).
- translate_nls_cost_to_conl()#
Translates a NONLINEAR_LS cost to a CONVEX_OVER_NONLINEAR cost.
- translate_to_feasibility_problem(keep_x0: bool = False, keep_cost: bool = False, parametric_x0: bool = False) None #
Translate an OCP to a feasibility problem by removing all cost term and then formulating all constraints as L2 penalties.
Note: all weights are set to 1.0 for now. Options to specify weights should be implemented later for advanced use cases.
- Parameters
keep_x0 – if True, x0 constraint is kept as a constraint
keep_cost – if True, cost is not removed before formulating constraints as penalties
parametric_x0 – if True, replace the value of the initial state constraint with a parameter that is appended to the model parameters.
- zoro_description#
zoRO - zero order robust optimization - description: for advanced users.
AcadosOcpCost
#
- class acados_template.acados_ocp_cost.AcadosOcpCost#
Class containing the numerical data of the cost:
NOTE: By default, the Lagrange cost term provided in continuous time is internally integrated using the explicit Euler method, cost_discretization = ‘EULER’, which allows for a seamless OCP discretization with a nonuniform time grid. This means that all cost terms, except for the terminal one, are weighted with the corresponding time step. \(c_\text{total} = \Delta t_0 \cdot l_0(x_0, u_0, z_0, p_0) + ... + \Delta t_{N-1} \cdot l_{N-1}(x_{N-1}, u_{N-1}, z_{N-1}, p_{N-1}) + l_N(x_N, p_N)\).
If a nonlinear least-squares or convex-over-nonlinear cost is used, the cost can also be integrated using the same integration scheme, which is used for the dynamics, cost_discretization = ‘INTEGRATOR’.
In case of LINEAR_LS: stage cost is \(l(x,u,z) = 0.5 \cdot || V_x \, x + V_u \, u + V_z \, z - y_\text{ref}||^2_W\), terminal cost is \(m(x) = 0.5 \cdot || V^e_x \, x - y_\text{ref}^e||^2_{W^e}\)
In case of NONLINEAR_LS: stage cost is \(l(x,u,z,t,p) = 0.5 \cdot || y(x,u,z,t,p) - y_\text{ref}||^2_W\), terminal cost is \(m(x,p) = 0.5 \cdot || y^e(x,p) - y_\text{ref}^e||^2_{W^e}\)
In case of CONVEX_OVER_NONLINEAR: stage cost is \(l(x,u,z,t,p) = \psi(y(x,u,z,t,p) - y_\text{ref}, t, p)\), terminal cost is \(m(x, p) = \psi^e (y^e(x,p) - y_\text{ref}^e, p)\)
- property Vu#
\(V_u\) - u matrix coefficient at intermediate shooting nodes (1 to N-1). Default:
np.zeros((0,0))
.
- property Vu_0#
\(V_u^0\) - u matrix coefficient at initial shooting node (0). Default:
None
.
- property Vx#
\(V_x\) - x matrix coefficient at intermediate shooting nodes (1 to N-1). Default:
np.zeros((0,0))
.
- property Vx_0#
\(V_x^0\) - x matrix coefficient at initial shooting node (0). Default:
None
.
- property Vx_e#
\(V_x^e\) - x matrix coefficient for cost at terminal shooting node (N). Default:
np.zeros((0,0))
.
- property Vz#
\(V_z\) - z matrix coefficient at intermediate shooting nodes (1 to N-1). Default:
np.zeros((0,0))
.
- property Vz_0#
\(V_z^0\) - z matrix coefficient at initial shooting node (0). Default:
None
.
- property W#
\(W\) - weight matrix at intermediate shooting nodes (1 to N-1). Default:
np.zeros((0,0))
.
- property W_0#
\(W_0\) - weight matrix at initial shooting node (0). Default:
None
.
- property W_e#
\(W_e\) - weight matrix at terminal shooting node (N). Default:
np.zeros((0,0))
.
- property Zl#
\(Z_l\) - diagonal of Hessian wrt lower slack at intermediate shooting nodes (0 to N-1). Default:
np.array([])
.
- property Zl_0#
\(Z_l^0\) - diagonal of Hessian wrt lower slack at initial node 0. Default:
np.array([])
.
- property Zl_e#
\(Z_l^e\) - diagonal of Hessian wrt lower slack at terminal shooting node (N). Default:
np.array([])
.
- property Zu#
\(Z_u\) - diagonal of Hessian wrt upper slack at intermediate shooting nodes (0 to N-1). Default:
np.array([])
.
- property Zu_0#
\(Z_u^0\) - diagonal of Hessian wrt upper slack at initial node 0. Default:
np.array([])
.
- property Zu_e#
\(Z_u^e\) - diagonal of Hessian wrt upper slack at terminal shooting node (N). Default:
np.array([])
.
- property cost_ext_fun_type#
Type of external function for cost at intermediate shooting nodes (1 to N-1). – string in {casadi, generic} Default: :code:’casadi’.
- property cost_ext_fun_type_0#
Type of external function for cost at initial shooting node (0) – string in {casadi, generic} or
None
Default: :code:’casadi’.Note
Cost at initial stage is the same as for intermediate shooting nodes if not set differently explicitly.
- property cost_ext_fun_type_e#
Type of external function for cost at terminal shooting node (N). – string in {casadi, generic} Default: :code:’casadi’.
- property cost_type#
Cost type at intermediate shooting nodes (1 to N-1) – string in {EXTERNAL, LINEAR_LS, NONLINEAR_LS, CONVEX_OVER_NONLINEAR}. Default: ‘LINEAR_LS’.
- property cost_type_0#
Cost type at initial shooting node (0) – string in {EXTERNAL, LINEAR_LS, NONLINEAR_LS, CONVEX_OVER_NONLINEAR} or
None
. Default:None
.
- property cost_type_e#
Cost type at terminal shooting node (N) – string in {EXTERNAL, LINEAR_LS, NONLINEAR_LS, CONVEX_OVER_NONLINEAR}. Default: ‘LINEAR_LS’.
- property yref#
\(y_\text{ref}\) - reference at intermediate shooting nodes (1 to N-1). Default:
np.array([])
.
- property yref_0#
\(y_\text{ref}^0\) - reference at initial shooting node (0). Default:
None
.
- property yref_e#
\(y_\text{ref}^e\) - cost reference at terminal shooting node (N). Default:
np.array([])
.
- property zl#
\(z_l\) - gradient wrt lower slack at intermediate shooting nodes (0 to N-1). Default:
np.array([])
.
- property zl_0#
\(z_l^0\) - gradient wrt lower slack at initial node 0. Default:
np.array([])
.
- property zl_e#
\(z_l^e\) - gradient wrt lower slack at terminal shooting node (N). Default:
np.array([])
.
- property zu#
\(z_u\) - gradient wrt upper slack at intermediate shooting nodes (0 to N-1). Default:
np.array([])
.
- property zu_0#
\(z_u^0\) - gradient wrt upper slack at initial node 0. Default:
np.array([])
.
- property zu_e#
\(z_u^e\) - gradient wrt upper slack at terminal shooting node (N). Default:
np.array([])
.
AcadosOcpConstraints
#
- class acados_template.acados_ocp_constraints.AcadosOcpConstraints#
class containing the description of the constraints
- property C#
\(C\) - C matrix in \(\underline{g} \leq D \, u + C \, x \leq \bar{g}\) at shooting nodes (0 to N-1). Type:
np.ndarray
; default:np.array((0,0))
.
- property C_e#
\(C^e\) - C matrix at terminal shooting node N. Type:
np.ndarray
; default:np.array((0,0))
.
- property D#
\(D\) - D matrix in \(\underline{g} \leq D \, u + C \, x \leq \bar{g}\) at shooting nodes (0 to N-1). Type:
np.ndarray
; default:np.array((0,0))
- property Jbu#
\(J_{bu}\) - matrix coefficient for bounds on u at shooting nodes (0 to N-1). Translated internally to
idxbu
.
- property Jbx#
\(J_{bx}\) - matrix coefficient for bounds on x at intermediate shooting nodes (1 to N-1). Translated internally into
idxbx
.
- property Jbx_0#
\(J_{bx,0}\) - matrix coefficient for bounds on x at initial stage 0. Translated internally to
idxbx_0
- property Jbx_e#
\(J_{bx}^e\) matrix coefficient for bounds on x at terminal shooting node N. Translated internally into
idxbx_e
.
- property Jsbu#
\(J_{sbu}\) - matrix coefficient for soft bounds on u at stages (0 to N-1); internally translated into
idxsbu
- property Jsbx#
\(J_{sbx}\) - matrix coefficient for soft bounds on x at stages (1 to N-1); Translated internally into
idxsbx
.
- property Jsbx_e#
\(J_{sbx}^e\) - matrix coefficient for soft bounds on x at terminal shooting node N. Translated internally to
idxsbx_e
- property Jsg#
\(J_{sg}\) - matrix coefficient for soft bounds on general linear constraints. Translated internally to
idxsg
- property Jsg_e#
\(J_{s,h}^e\) - matrix coefficient for soft bounds on general linear constraints at terminal shooting node N. Translated internally to
idxsg_e
- property Jsh#
\(J_{sh}\) - matrix coefficient for soft bounds on nonlinear constraints. Translated internally to
idxsh
- property Jsh_0#
\(J_{s,h}^0\) - matrix coefficient for soft bounds on nonlinear constraints at initial shooting node 0; fills
idxsh_0
- property Jsh_e#
\(J_{s,h}^e\) - matrix coefficient for soft bounds on nonlinear constraints at terminal shooting node N; fills
idxsh_e
- property Jsphi#
\(J_{s, \phi}\) - matrix coefficient for soft bounds on convex-over-nonlinear constraints. Translated internally into
idxsphi
.
- property Jsphi_0#
\(J_{sh}^0\) - matrix coefficient for soft bounds on convex-over-nonlinear constraints at shooting node N. Translated internally to
idxsphi_0
- property Jsphi_e#
\(J_{sh}^e\) - matrix coefficient for soft bounds on convex-over-nonlinear constraints at shooting node N. Translated internally to
idxsphi_e
- property constr_type#
Constraints type for shooting nodes (0 to N-1). string in {BGH, BGP}. Detected automatically from model. Default: BGH; BGP is for convex over nonlinear.
- property constr_type_0#
Constraints type for initial shooting node. string in {BGH, BGP}. Detected automatically from model. Default: BGH; BGP is for convex over nonlinear.
- property constr_type_e#
Constraints type for terminal shooting node N. string in {BGH, BGP}. Detected automatically from model. Default: BGH; BGP is for convex over nonlinear.
- property has_x0#
Internal variable to check if x0 is set. Cannot be set from outside. :bool: True if x0 is set, False otherwise.
- property idxbu#
Indices of bounds on u (defines \(J_{bu}\)) at shooting nodes (0 to N-1). Can be set by using
Jbu
. Type:np.ndarray
; default:np.array([])
- property idxbx#
indices of bounds on x (defines \(J_{bx}\)) at intermediate shooting nodes (1 to N-1). Can be set by using
Jbx
. Type:np.ndarray
; default:np.array([])
- property idxbx_0#
Indices of bounds on x at initial stage 0 – can be set automatically via x0. Can be set by using
Jbx_0
. Type:np.ndarray
; default:np.array([])
- property idxbx_e#
Indices for bounds on x at terminal shooting node N (defines \(J_{bx}^e\)). Can be set by using
Jbx_e
. Type:np.ndarray
; default:np.array([])
- property idxbxe_0#
Indices of bounds on x0 that are equalities – can be set automatically via
x0
. Type:np.ndarray
; default:np.array([])
- property idxsbu#
Indices of soft bounds on u within the indices of bounds on u at stages (0 to N-1). Can be set by using
Jsbu
. Type:np.ndarray
; default:np.array([])
- property idxsbx#
Indices of soft bounds on x within the indices of bounds on x at stages (1 to N-1). Can be set by using
Jsbx
. Type:np.ndarray
; default:np.array([])
- property idxsbx_e#
Indices of soft bounds on x at shooting node N, within the indices of bounds on x at terminal shooting node N. Can be set by using
Jsbx_e
. Type:np.ndarray
; default:np.array([])
- property idxsg#
Indices of soft general linear constraints within the indices of general linear constraints. Can be set by using
Jsg
. Type:np.ndarray
; default:np.array([])
- property idxsg_e#
Indices of soft general linear constraints at shooting node N within the indices of general linear constraints at shooting node N. Can be set by using
Jsg_e
.
- property idxsh#
Indices of soft nonlinear constraints within the indices of nonlinear constraints. Can be set by using
Jbx
. Type:np.ndarray
; default:np.array([])
- property idxsh_0#
Indices of soft nonlinear constraints at shooting node N within the indices of nonlinear constraints at initial shooting node 0. Can be set by using
Jsh_0
.
- property idxsh_e#
Indices of soft nonlinear constraints at shooting node N within the indices of nonlinear constraints at terminal shooting node N. Can be set by using
Jsh_e
.
- property idxsphi#
Indices of soft convex-over-nonlinear constraints within the indices of nonlinear constraints. Can be set by using
Jsphi
. Type:np.ndarray
; default:np.array([])
- property idxsphi_0#
Indices of soft nonlinear constraints at shooting node N within the indices of nonlinear constraints at initial shooting node 0. Can be set by using
Jsphi_0
. Type:np.ndarray
; default:np.array([])
- property idxsphi_e#
Indices of soft nonlinear constraints at shooting node N within the indices of nonlinear constraints at terminal shooting node N. Can be set by using
Jsphi_e
. Type:np.ndarray
; default:np.array([])
- property lbu#
\(\underline{u}\) - lower bounds on u at shooting nodes (0 to N-1). Type:
np.ndarray
; default:np.array([])
- property lbx#
\(\underline{x}\) - lower bounds on x at intermediate shooting nodes (1 to N-1). Type:
np.ndarray
; default:np.array([])
- property lbx_0#
\(\underline{x_0}\) - lower bounds on x at initial stage 0. Type:
np.ndarray
; default:np.array([])
.
- property lbx_e#
\(\underline{x}^e\) - lower bounds on x at terminal shooting node N. Type:
np.ndarray
; default:np.array([])
- property lg#
\(\underline{g}\) - lower bound for general polytopic inequalities at shooting nodes (0 to N-1). Type:
np.ndarray
; default:np.array([])
- property lg_e#
\(\underline{g}^e\) - lower bound on general polytopic inequalities at terminal shooting node N. Type:
np.ndarray
; default:np.array([])
.
- property lh#
\(\underline{h}\) - lower bound for nonlinear inequalities at intermediate shooting nodes (1 to N-1). Type:
np.ndarray
; default:np.array([])
.
- property lh_0#
\(\underline{h}^0\) - lower bound on nonlinear inequalities at initial shooting node (0). Type:
np.ndarray
; default:np.array([])
.
- property lh_e#
\(\underline{h}^e\) - lower bound on nonlinear inequalities at terminal shooting node N. Type:
np.ndarray
; default:np.array([])
.
- property lphi#
\(\underline{\phi}\) - lower bound for convex-over-nonlinear inequalities at shooting nodes (0 to N-1). Type:
np.ndarray
; default:np.array([])
.
- property lphi_0#
\(\underline{\phi}^0\) - lower bound on convex-over-nonlinear inequalities at shooting node 0. Type:
np.ndarray
; default:np.array([])
.
- property lphi_e#
\(\underline{\phi}^e\) - lower bound on convex-over-nonlinear inequalities at terminal shooting node N. Type:
np.ndarray
; default:np.array([])
.
- property lsbu#
Lower bounds on slacks corresponding to soft lower bounds on u at stages (0 to N-1). Not required - zeros by default.
- property lsbx#
Lower bounds on slacks corresponding to soft lower bounds on x at stages (1 to N-1); not required - zeros by default
- property lsbx_e#
Lower bounds on slacks corresponding to soft lower bounds on x at shooting node N. Not required - zeros by default
- property lsg#
Lower bounds on slacks corresponding to soft lower bounds for general linear constraints at stages (0 to N-1). Type:
np.ndarray
; default:np.array([])
- property lsg_e#
Lower bounds on slacks corresponding to soft lower bounds for general linear constraints at shooting node N. Not required - zeros by default
- property lsh#
Lower bounds on slacks corresponding to soft lower bounds for nonlinear constraints. Not required - zeros by default
- property lsh_0#
Lower bounds on slacks corresponding to soft lower bounds for nonlinear constraints at initial shooting node 0. Not required - zeros by default
- property lsh_e#
Lower bounds on slacks corresponding to soft lower bounds for nonlinear constraints at terminal shooting node N. Not required - zeros by default
- property lsphi#
Lower bounds on slacks corresponding to soft lower bounds for convex-over-nonlinear constraints. Not required - zeros by default
- property lsphi_0#
Lower bounds on slacks corresponding to soft lower bounds for convex-over-nonlinear constraints at initial shooting node 0. Not required - zeros by default
- property lsphi_e#
Lower bounds on slacks corresponding to soft lower bounds for convex-over-nonlinear constraints at terminal shooting node N. Not required - zeros by default
- property ubu#
\(\bar{u}\) - upper bounds on u at shooting nodes (0 to N-1). Type:
np.ndarray
; default:np.array([])
- property ubx#
\(\bar{x}\) - upper bounds on x at intermediate shooting nodes (1 to N-1). Type:
np.ndarray
; default:np.array([])
- property ubx_0#
\(\bar{x_0}\) - upper bounds on x at initial stage 0. Type:
np.ndarray
; default:np.array([])
- property ubx_e#
\(\bar{x}^e\) - upper bounds on x at terminal shooting node N. Type:
np.ndarray
; default:np.array([])
- property ug#
\(\bar{g}\) - upper bound for general polytopic inequalities at shooting nodes (0 to N-1). Type:
np.ndarray
; default:np.array([])
.
- property ug_e#
\(\bar{g}^e\) - upper bound on general polytopic inequalities at terminal shooting node N. Type:
np.ndarray
; default:np.array([])
.
- property uh#
\(\bar{h}\) - upper bound for nonlinear inequalities at intermediate shooting nodes (1 to N-1). Type:
np.ndarray
; default:np.array([])
.
- property uh_0#
\(\bar{h}^0\) - upper bound on nonlinear inequalities at initial shooting node (0). Type:
np.ndarray
; default:np.array([])
.
- property uh_e#
\(\bar{h}^e\) - upper bound on nonlinear inequalities at terminal shooting node N. Type:
np.ndarray
; default:np.array([])
.
- property uphi#
\(\bar{\phi}\) - upper bound for convex-over-nonlinear inequalities at shooting nodes (0 to N-1). Type:
np.ndarray
; default:np.array([])
.
- property uphi_0#
\(\bar{\phi}^0\) - upper bound on convex-over-nonlinear inequalities at shooting node 0. Type:
np.ndarray
; default:np.array([])
.
- property uphi_e#
\(\bar{\phi}^e\) - upper bound on convex-over-nonlinear inequalities at terminal shooting node N. Type:
np.ndarray
; default:np.array([])
.
- property usbu#
Lower bounds on slacks corresponding to soft upper bounds on u at stages (0 to N-1); not required - zeros by default
- property usbx#
Lower bounds on slacks corresponding to soft upper bounds on x at stages (1 to N-1); not required - zeros by default
- property usbx_e#
Lower bounds on slacks corresponding to soft upper bounds on x at shooting node N. Not required - zeros by default
- property usg#
Lower bounds on slacks corresponding to soft upper bounds for general linear constraints. Not required - zeros by default
- property usg_e#
Lower bounds on slacks corresponding to soft upper bounds for general linear constraints at shooting node N. Not required - zeros by default
- property ush#
Lower bounds on slacks corresponding to soft upper bounds for nonlinear constraints. Not required - zeros by default
- property ush_0#
Lower bounds on slacks corresponding to soft upper bounds for nonlinear constraints at initial shooting node 0. Not required - zeros by default
- property ush_e#
Lower bounds on slacks corresponding to soft upper bounds for nonlinear constraints at terminal shooting node N. Not required - zeros by default
- property usphi#
Lower bounds on slacks corresponding to soft upper bounds for convex-over-nonlinear constraints. Not required - zeros by default
- property usphi_0#
Lower bounds on slacks corresponding to soft upper bounds for convex-over-nonlinear constraints at initial shooting node 0. Not required - zeros by default
- property usphi_e#
Lower bounds on slacks corresponding to soft upper bounds for convex-over-nonlinear constraints at terminal shooting node N. Not required - zeros by default
AcadosOcpOptions
#
- class acados_template.acados_ocp_options.AcadosOcpOptions#
class containing the description of the solver options
- property N_horizon#
Number of shooting intervals. Type: int > 0 Default:
None
- property Tsim#
Time horizon for one integrator step. Automatically calculated as first time step if not provided. Default:
None
- property adaptive_levenberg_marquardt_lam#
So far: Only relevant for DDP Flag defining the value of lambda in the adaptive levenberg_marquardt. Must be > 1. type: float
- property adaptive_levenberg_marquardt_mu0#
So far: Only relevant for DDP Flag defining the value of mu0 in the adaptive levenberg_marquardt. Must be > 0. type: float
- property adaptive_levenberg_marquardt_mu_min#
So far: Only relevant for DDP Flag defining the value of mu_min in the adaptive levenberg_marquardt. Must be > 0. type: float
- property alpha_min#
The option alpha_min is deprecated and has new name: globalization_alpha_min
- property alpha_reduction#
The option alpha_reduction is deprecated and has new name: globalization_alpha_reduction
- property as_rti_iter#
Maximum number of iterations in the advanced-step real-time iteration. Default: 1
- property as_rti_level#
Level of the advanced-step real-time iteration.
LEVEL-A: 0 LEVEL-B: 1 LEVEL-C: 2 LEVEL-D: 3 STANDARD_RTI: 4
Default: 4
- property collocation_type#
Collocation type: only relevant for implicit integrators – string in {‘GAUSS_RADAU_IIA’, ‘GAUSS_LEGENDRE’, ‘EXPLICIT_RUNGE_KUTTA’}.
Default: GAUSS_LEGENDRE
- property cost_discretization#
Cost discretization: string in {‘EULER’, ‘INTEGRATOR’}. Default: ‘EULER’ ‘EULER’: cost is evaluated at shooting nodes ‘INTEGRATOR’: cost is integrated over the shooting intervals - only supported for IRK integrator
- property cost_scaling#
Vector with cost scaling factors of length N_horizon + 1. If None set automatically to [time_steps, 1.0]. Default:
None
- property custom_templates#
List of tuples of the form: (input_filename, output_filename)
Custom templates are render in OCP solver generation.
Default: [].
- property custom_update_copy#
Boolean; If True, the custom update function files are copied into the code_export_directory.
- property custom_update_filename#
Filename of the custom C function to update solver data and parameters in between solver calls. Compare also AcadosOcpOptions.custom_update_header_filename.
This file has to implement the functions int custom_update_init_function([model.name]_solver_capsule* capsule); int custom_update_function([model.name]_solver_capsule* capsule, double* data, int data_len); int custom_update_terminate_function([model.name]_solver_capsule* capsule);
Default: ‘’.
- property custom_update_header_filename#
Header filename of the custom C function to update solver data and parameters in between solver calls.
This file has to declare the custom_update functions and look as follows:
// Called at the end of solver creation.
// This is allowed to allocate memory and store the pointer to it into capsule->custom_update_memory.
int custom_update_init_function([model.name]_solver_capsule* capsule);
// Custom update function that can be called between solver calls
int custom_update_function([model.name]_solver_capsule* capsule, double* data, int data_len);
// Called just before destroying the solver.
// Responsible to free allocated memory, stored at capsule->custom_update_memory.
int custom_update_terminate_function([model.name]_solver_capsule* capsule);
Default: ‘’.
- property eps_sufficient_descent#
The option eps_sufficient_descent is deprecated and has new name: globalization_line_search_use_sufficient_descent
- property eval_residual_at_max_iter#
Determines, if the problem data is again evaluated after the last iteration has been performed. If True, the residuals are evaluated at the last iterate and convergence will be checked. If False, after the last iteration, the solver will terminate with max iterations status, although the final iterate might fulfill the convergence criteria.
Type: bool Default: None
If None is given: if globalization == FUNNEL_L1PEN_LINESEARCH: true else: false
- property exact_hess_constr#
Used in case of hessian_approx == ‘EXACT’.
Can be used to turn off exact hessian contributions from the constraints module.
- property exact_hess_cost#
Used in case of hessian_approx == ‘EXACT’.
Can be used to turn off exact hessian contributions from the cost module.
- property exact_hess_dyn#
Used in case of hessian_approx == ‘EXACT’.
Can be used to turn off exact hessian contributions from the dynamics module.
- property ext_cost_num_hess#
Determines if custom hessian approximation for cost contribution is used (> 0).
Or if hessian contribution is evaluated exactly using CasADi external function (=0 - default).
- property ext_fun_compile_flags#
String with compiler flags for external function compilation. Default: ‘-O2’ if environment variable ACADOS_EXT_FUN_COMPILE_FLAGS is not set, else ACADOS_EXT_FUN_COMPILE_FLAGS is used as default.
- property fixed_hess#
Indicates if the hessian is fixed (1) or not (0).
If fixed, the hessian is computed only once and not updated in the SQP loop. This can safely be set to 1 if there are no slacked constraints, cost module is ‘LINEAR_LS’ with Gauss-Newton Hessian, and the weighting matrix ‘W’ is not updated after solver creation. Default: 0
- property full_step_dual#
The option full_step_dual is deprecated and has new name: globalization_full_step_dual
- property globalization#
Globalization type. String in (‘FIXED_STEP’, ‘MERIT_BACKTRACKING’, ‘FUNNEL_L1PEN_LINESEARCH’). Default: ‘FIXED_STEP’.
FIXED_STEP: performs steps with a given step length, see option globalization_fixed_step_length
MERIT_BACKTRACKING: performs a merit function based backtracking line search following Following Leineweber1999, Section “3.5.1 Line Search Globalization”
- FUNNEL_L1PEN_LINESEARCH: following “A Unified Funnel Restoration SQP Algorithm” by Kiessling et al.
https://arxiv.org/pdf/2409.09208 NOTE: preliminary implementation
- property globalization_alpha_min#
Minimal step size for globalization.
default: None.
If None is given: - in case of FUNNEL_L1PEN_LINESEARCH, value is set to 1e-17. - in case of MERIT_BACKTRACKING, value is set to 0.05.
- property globalization_alpha_reduction#
Step size reduction factor for globalization MERIT_BACKTRACKING,
Type: float Default: None.
If None is given: - in case of FUNNEL_L1PEN_LINESEARCH, value is set to 0.5. - in case of MERIT_BACKTRACKING, value is set to 0.7. default: 0.7.
- property globalization_eps_sufficient_descent#
Factor for sufficient descent (Armijo) conditon, see also globalization_line_search_use_sufficient_descent.
Type: float, Default: None.
If None is given: - in case of FUNNEL_L1PEN_LINESEARCH, value is set to 1e-6. - in case of MERIT_BACKTRACKING, value is set to 1e-4.
- property globalization_fixed_step_length#
Fixed Newton step length, used if globalization == “FIXED_STEP” Type: float >= 0. Default: 1.0.
- property globalization_full_step_dual#
Determines if dual variables are updated with full steps (alpha=1.0) when primal variables are updated with smaller step.
Type: int; 0 or 1; default for funnel globalization: 1 default else: 0.
- property globalization_funnel_fraction_switching_condition#
Multiplication factor in switching condition.
Type: float Default: 1e-3
- property globalization_funnel_init_increase_factor#
Increase factor for initialization of funnel width. Initial funnel is max(globalization_funnel_init_upper_bound, globalization_funnel_init_increase_factor * initial_infeasibility)
Type: float Default: 15.0
- property globalization_funnel_init_upper_bound#
Initial upper bound for funnel width. Initial funnel is max(globalization_funnel_init_upper_bound, globalization_funnel_init_increase_factor * initial_infeasibility)
Type: float Default: 1.0
- property globalization_funnel_initial_penalty_parameter#
Initialization.
Type: float Default: 1.0
- property globalization_funnel_kappa#
Interpolation factor for convex combination in funnel decrease function.
Type: float Default: 0.9
- property globalization_funnel_sufficient_decrease_factor#
Sufficient decrease factor for infeasibility in h iteration: trial_infeasibility <= kappa * globalization_funnel_width
Type: float Default: 0.9
- property globalization_line_search_use_sufficient_descent#
Determines if sufficient descent (Armijo) condition is used in line search. Type: int; 0 or 1; default: 0.
- property globalization_use_SOC#
Determines if second order correction (SOC) is done when using MERIT_BACKTRACKING. SOC is done if preliminary line search does not return full step. Type: int; 0 or 1; default: 0.
- property hessian_approx#
Hessian approximation. String in (‘GAUSS_NEWTON’, ‘EXACT’). Default: ‘GAUSS_NEWTON’.
- property hpipm_mode#
Mode of HPIPM to be used,
String in (‘BALANCE’, ‘SPEED_ABS’, ‘SPEED’, ‘ROBUST’).
Default: ‘BALANCE’.
see https://cdn.syscop.de/publications/Frison2020a.pdf and the HPIPM code: giaf/hpipm
- property integrator_type#
Integrator type. String in (‘ERK’, ‘IRK’, ‘GNSF’, ‘DISCRETE’, ‘LIFTED_IRK’). Default: ‘ERK’.
- property levenberg_marquardt#
Factor for LM regularization. Type: float >= 0 Default: 0.0.
- property line_search_use_sufficient_descent#
The option line_search_use_sufficient_descent is deprecated and has new name: globalization_line_search_use_sufficient_descent
- property log_primal_step_norm#
Flag indicating whether the max norm of the primal steps should be logged. This is implemented only for solver type SQP. Default: False
Path to the .so lib
Name of the .so lib
- property nlp_solver_ext_qp_res#
Determines if residuals of QP are computed externally within NLP solver (for debugging)
Type: int; 0 or 1; Default: 0.
- property nlp_solver_max_iter#
NLP solver maximum number of iterations. Type: int >= 0 Default: 100
- property nlp_solver_step_length#
This option is deprecated and has new name: globalization_fixed_step_length
- property nlp_solver_tol_comp#
NLP solver complementarity tolerance
- property nlp_solver_tol_eq#
NLP solver equality tolerance
- property nlp_solver_tol_ineq#
NLP solver inequality tolerance
- property nlp_solver_tol_min_step_norm#
NLP solver tolerance for minimal step norm. Solver terminates if step norm is below given value. If value is 0.0, then the solver does not test for the small step.
Type: float Default: None
If None: in case of FUNNEL_L1PEN_LINESEARCH: 1e-12 otherwise: 0.0
- property nlp_solver_tol_stat#
NLP solver stationarity tolerance. Type: float > 0 Default: 1e-6
- property nlp_solver_type#
NLP solver. String in (‘SQP’, ‘SQP_RTI’, ‘DDP’). Default: ‘SQP’.
- property nlp_solver_warm_start_first_qp#
Flag indicating whether the first QP in an NLP solve should be warm started. Type: int. Default: 0.
- property num_threads_in_batch_solve#
Integer indicating how many threads should be used within the batch solve. If more than one thread should be used, the solver is compiled with openmp. Default: 1.
- property print_level#
Verbosity of printing.
Type: int >= 0 Default: 0
Level 1: print iteration log Level 2: print high level debug output in funnel globalization Level 3: print more detailed debug output in funnel, including objective values and infeasibilities Level 4: print QP inputs and outputs. Please specify with max_iter how many QPs should be printed
- property qp_solver#
QP solver to be used in the NLP solver. String in (‘PARTIAL_CONDENSING_HPIPM’, ‘FULL_CONDENSING_QPOASES’, ‘FULL_CONDENSING_HPIPM’, ‘PARTIAL_CONDENSING_QPDUNES’, ‘PARTIAL_CONDENSING_OSQP’, ‘FULL_CONDENSING_DAQP’). Default: ‘PARTIAL_CONDENSING_HPIPM’.
- property qp_solver_cond_N#
QP solver: New horizon after partial condensing. Set to N by default -> no condensing.
- property qp_solver_cond_block_size#
QP solver: list of integers of length qp_solver_cond_N + 1 Denotes how many blocks of the original OCP are lumped together into one in partial condensing. Note that the last entry is the number of blocks that are condensed into the terminal cost of the partially condensed QP. Default: None -> compute even block size distribution based on qp_solver_cond_N
- property qp_solver_cond_ric_alg#
QP solver: Determines which algorithm is used in HPIPM condensing. 0: dont factorize hessian in the condensing; 1: factorize. Default: 1
- property qp_solver_iter_max#
QP solver: maximum number of iterations. Type: int > 0 Default: 50
- property qp_solver_mu0#
For HPIPM QP solver: Initial value for the barrier parameter. If 0, the default value according to hpipm_mode is used.
Default: 0
- property qp_solver_ric_alg#
QP solver: Determines which algorithm is used in HPIPM OCP QP solver. 0 classical Riccati, 1 square-root Riccati.
Note: taken from [HPIPM paper]:
the classical implementation requires the reduced (projected) Hessian with respect to the dynamics equality constraints to be positive definite, but allows the full-space Hessian to be indefinite)
the square-root implementation, which in order to reduce the flop count employs the Cholesky factorization of the Riccati recursion matrix (P), and therefore requires the full-space Hessian to be positive definite
[HPIPM paper]: HPIPM: a high-performance quadratic programming framework for model predictive control, Frison and Diehl, 2020 https://cdn.syscop.de/publications/Frison2020a.pdf
Default: 1
- property qp_solver_tol_comp#
QP solver complementarity. Default:
None
- property qp_solver_tol_eq#
QP solver equality tolerance. Default:
None
- property qp_solver_tol_ineq#
QP solver inequality. Default:
None
- property qp_solver_tol_stat#
QP solver stationarity tolerance. Default:
None
- property qp_solver_warm_start#
QP solver: Warm starting. 0: no warm start; 1: warm start; 2: hot start. Default: 0
- property qp_tol#
QP solver tolerance. Sets all of the following at once or gets the max of
qp_solver_tol_eq
,qp_solver_tol_ineq
,qp_solver_tol_comp
andqp_solver_tol_stat
.
- property reg_epsilon#
Epsilon for regularization, used if regularize_method in [‘PROJECT’, ‘MIRROR’, ‘CONVEXIFY’]
- property regularize_method#
Regularization method for the Hessian. String in (‘NO_REGULARIZE’, ‘MIRROR’, ‘PROJECT’, ‘PROJECT_REDUC_HESS’, ‘CONVEXIFY’) or
None
.MIRROR: performs eigenvalue decomposition H = V^T D V and sets D_ii = max(eps, abs(D_ii))
PROJECT: performs eigenvalue decomposition H = V^T D V and sets D_ii = max(eps, D_ii)
CONVEXIFY: Algorithm 6 from Verschueren2017, https://cdn.syscop.de/publications/Verschueren2017.pdf, does not support nonlinear constraints
PROJECT_REDUC_HESS: experimental
Note: default eps = 1e-4
Default: ‘NO_REGULARIZE’.
- property rti_log_only_available_residuals#
Relevant if rti_log_residuals is set to 1. If rti_log_only_available_residuals is set to 1, only residuals that do not require additional function evaluations are logged.
Type: int; 0 or 1; Default: 0.
- property rti_log_residuals#
Determines if residuals are computed and logged within RTI / AS-RTI iterations (for debugging).
Type: int; 0 or 1; Default: 0.
- property shooting_nodes#
Vector of length N_horizon + 1 containing the shooting nodes. If None set automatically to uniform discretization using
N_horizon
andtf
. For nonuniform discretization: Either provide shooting_nodes or time_steps. Default:None
- property sim_method_jac_reuse#
Integer determining if jacobians are reused within integrator or ndarray of ints > 0 of shape (N,). 0: False (no reuse); 1: True (reuse) Default: 0
- property sim_method_newton_iter#
Number of Newton iterations in implicit integrators. Type: int > 0 Default: 3
- property sim_method_newton_tol#
Tolerance of Newton system in implicit integrators. This option is not implemented for LIFTED_IRK Type: float: 0.0 means not used Default: 0.0
- property sim_method_num_stages#
Number of stages in the integrator. Type: int > 0 or ndarray of ints > 0 of shape (N,). Default: 4
- property sim_method_num_steps#
Number of steps in the integrator. Type: int > 0 or ndarray of ints > 0 of shape (N,). Default: 1
- property store_iterates#
Flag indicating whether the intermediate primal-dual iterates should be stored. This is implemented only for solver types SQP and DDP. Default: False
- property tf#
Prediction horizon Type: float > 0 Default:
None
- property time_steps#
Vector of length N_horizon containing the time steps between the shooting nodes. If None set automatically to uniform discretization using
N_horizon
andtf
. For nonuniform discretization: Either provide shooting_nodes or time_steps. Default:None
- property timeout_heuristic#
Heuristic to be used for predicting the runtime of the next SQP iteration, cf. timeout_max_time. Possible values are “MAX_CALL”, “MAX_OVERALL”, “LAST”, “AVERAGE”, “ZERO”. MAX_CALL: Use the maximum time per iteration for the current solver call as estimate. MAX_OVERALL: Use the maximum time per iteration over all solver calls as estimate. LAST: Use the time required by the last iteration as estimate. AVERAGE: Use an exponential moving average of the previous per iteration times as estimate (weight is currently fixed at 0.5). ZERO: Use 0 as estimate. Currently implemented for SQP only. Default: ZERO.
- property timeout_max_time#
Maximum time before solver timeout. If 0, there is no timeout. A timeout is triggered if the condition current_time_tot + predicted_per_iteration_time > timeout_max_time is satisfied at the end of an SQP iteration. The value of predicted_per_iteration_time is estimated using timeout_heuristic. Currently implemented for SQP only. Default: 0.
- property tol#
NLP solver tolerance. Sets or gets the max of
nlp_solver_tol_eq
,nlp_solver_tol_ineq
,nlp_solver_tol_comp
andnlp_solver_tol_stat
.
- property with_adaptive_levenberg_marquardt#
So far: Only relevant for DDP Flag indicating whether adaptive levenberg marquardt should be used. This is useful for NLS or LS problem where the residual goes to zero since quadratic local convergence can be achieved. type: bool
- property with_solution_sens_wrt_params#
Flag indicating whether solution sensitivities wrt. parameters can be computed.
- property with_value_sens_wrt_params#
Flag indicating whether value function sensitivities wrt. parameters can be computed.
AcadosOcpDims
#
- class acados_template.acados_dims.AcadosOcpDims#
Class containing the dimensions of the optimal control problem.
- property N#
\(N\) - Number of shooting intervals. DEPRECATED: use ocp.solver_options.N instead.
Type: int; default: None
- property n_global_data#
size of global_data; expressions that only depend on p_global; detected automatically during code generation. Type: int; default: 0
- property nbu#
\(n_{b_u}\) - number of input bounds. Type: int; default: 0
- property nbx#
\(n_{b_x}\) - number of state bounds. Type: int; default: 0
- property nbx_0#
\(n_{b_{x0}}\) - number of state bounds for initial state. Type: int; default: 0
- property nbx_e#
\(n_{b_x}\) - number of state bounds at terminal shooting node N. Type: int; default: 0
- property nbxe_0#
\(n_{be_{x0}}\) - number of state bounds at initial shooting node that are equalities. Type: int; default: None
- property ng#
\(n_{g}\) - number of general polytopic constraints. Type: int; default: 0
- property ng_e#
\(n_{g}^e\) - number of general polytopic constraints at terminal shooting node N. Type: int; default: 0
- property nh#
\(n_h\) - number of nonlinear constraints. Type: int; default: 0
- property nh_0#
\(n_{h}^e\) - number of nonlinear constraints at initial shooting node. Type: int; default: 0
- property nh_e#
\(n_{h}^e\) - number of nonlinear constraints at terminal shooting node N. Type: int; default: 0
- property np#
\(n_p\) - number of parameters. Type: int; default: 0
- property np_global#
number of global parameters p_global; default: 0
- property nphi#
\(n_{\phi}\) - number of convex-over-nonlinear constraints. Type: int; default: 0
- property nphi_0#
\(n_{\phi}^0\) - number of convex-over-nonlinear constraints at initial shooting node 0. Type: int; default: 0
- property nphi_e#
\(n_{\phi}^e\) - number of convex-over-nonlinear constraints at terminal shooting node N. Type: int; default: 0
- property nr#
\(n_{\pi}\) - dimension of the image of the inner nonlinear function in positive definite constraints. Type: int; default: 0
- property nr_0#
\(n_{\pi}^0\) - dimension of the image of the inner nonlinear function in positive definite constraints. Type: int; default: 0
- property nr_e#
\(n_{\pi}^e\) - dimension of the image of the inner nonlinear function in positive definite constraints. Type: int; default: 0
- property ns#
\(n_{s}\) - total number of slacks at stages (1, N-1). Type: int; default: 0
- property ns_0#
\(n_{s}^0\) - total number of slacks at shooting node 0. Type: int; default: 0
- property ns_e#
\(n_{s}^e\) - total number of slacks at terminal shooting node N. Type: int; default: 0
- property nsbu#
\(n_{{sb}_u}\) - number of soft input bounds. Type: int; default: 0
- property nsbx#
\(n_{{sb}_x}\) - number of soft state bounds. Type: int; default: 0
- property nsbx_e#
\(n_{{sb}^e_{x}}\) - number of soft state bounds at terminal shooting node N. Type: int; default: 0
- property nsg#
\(n_{{sg}}\) - number of soft general linear constraints. Type: int; default: 0
- property nsg_e#
\(n_{{sg}^e}\) - number of soft general linear constraints at terminal shooting node N. Type: int; default: 0
- property nsh#
\(n_{{sh}}\) - number of soft nonlinear constraints. Type: int; default: 0
- property nsh_0#
\(n_{{sh}}^0\) - number of soft nonlinear constraints at shooting node 0. Type: int; default: 0
- property nsh_e#
\(n_{{sh}}^e\) - number of soft nonlinear constraints at terminal shooting node N. Type: int; default: 0
- property nsphi#
\(n_{{s\phi}}\) - number of soft convex-over-nonlinear constraints. Type: int; default: 0
- property nsphi_0#
\(n_{{s\phi}^0}\) - number of soft convex-over-nonlinear constraints at shooting node 0. Type: int; default: 0
- property nsphi_e#
\(n_{{s\phi}^e}\) - number of soft convex-over-nonlinear constraints at terminal shooting node N. Type: int; default: 0
- property nu#
\(n_u\) - number of inputs. Type: int; default: None
- property nx#
\(n_x\) - number of states. Type: int; default: None
- property nx_next#
\(n_{x, \text{next}}\) - state dimension of next state. Type: int; default: None
- property ny#
\(n_y\) - number of residuals in Lagrange term. Type: int; default: 0
- property ny_0#
\(n_{y}^0\) - number of residuals in Mayer term. Type: int; default: 0
- property ny_e#
\(n_{y}^e\) - number of residuals in Mayer term. Type: int; default: 0
- property nz#
\(n_z\) - number of algebraic variables. Type: int; default: 0
AcadosModel
#
- class acados_template.acados_model.AcadosModel#
Class containing all the information to code generate the external CasADi functions that are needed when creating an acados ocp solver or acados integrator. Thus, this class contains:
the
name
of the model,all CasADi variables/expressions needed in the CasADi function generation process.
- con_h_expr#
CasADi expression for the constraint \(h\); Default:
[]
- con_h_expr_0#
CasADi expression for the initial constraint \(h^0\); Default:
[]
- con_h_expr_e#
CasADi expression for the terminal constraint \(h^e\); Default:
[]
- con_phi_expr#
CasADi expression for the constraint phi; Default:
[]
- con_phi_expr_0#
CasADi expression for the terminal constraint \(\phi_0\); Default:
[]
- con_phi_expr_e#
CasADi expression for the terminal constraint \(\phi_e\); Default:
[]
- con_r_expr#
CasADi expression for the constraint phi(r), dummy input for outer function; Default:
[]
- con_r_expr_0#
CasADi expression for the terminal constraint \(\phi_0(r)\), dummy input for outer function; Default:
[]
- con_r_expr_e#
CasADi expression for the terminal constraint \(\phi_e(r)\), dummy input for outer function; Default:
[]
- con_r_in_phi#
CasADi expression for the terminal constraint \(\phi(r)\), input for outer function; Default:
[]
- con_r_in_phi_0#
CasADi expression for the terminal constraint \(\phi_0(r)\), input for outer function; Default:
[]
- con_r_in_phi_e#
CasADi expression for the terminal constraint \(\phi_e(r)\), input for outer function; Default:
[]
- cost_conl_custom_outer_hess#
CasADi expression for the custom hessian of the outer loss function (only for convex-over-nonlinear cost); Default:
[]
Used ifacados_template.acados_ocp_options.AcadosOcpOptions.cost_type
is ‘CONVEX_OVER_NONLINEAR’.
- cost_conl_custom_outer_hess_0#
CasADi expression for the custom hessian of the outer loss function (only for convex-over-nonlinear cost), initial; Default:
[]
Used ifacados_template.acados_ocp_options.AcadosOcpOptions.cost_type_0
is ‘CONVEX_OVER_NONLINEAR’.
- cost_conl_custom_outer_hess_e#
CasADi expression for the custom hessian of the outer loss function (only for convex-over-nonlinear cost), terminal; Default:
[]
Used ifacados_template.acados_ocp_options.AcadosOcpOptions.cost_type_e
is ‘CONVEX_OVER_NONLINEAR’.
- cost_expr_ext_cost#
CasADi expression for external cost; Default:
[]
- cost_expr_ext_cost_0#
CasADi expression for external cost, initial; Default:
[]
- cost_expr_ext_cost_custom_hess#
CasADi expression for custom hessian (only for external cost); Default:
[]
- cost_expr_ext_cost_custom_hess_0#
CasADi expression for custom hessian (only for external cost), initial; Default:
[]
- cost_expr_ext_cost_custom_hess_e#
CasADi expression for custom hessian (only for external cost), terminal; Default:
[]
- cost_expr_ext_cost_e#
CasADi expression for external cost, terminal; Default:
[]
- cost_psi_expr#
CasADi expression for the outer loss function \(\psi(r - yref, t, p)\); Default:
[]
Used ifacados_template.acados_ocp_options.AcadosOcpOptions.cost_type
is ‘CONVEX_OVER_NONLINEAR’.
- cost_psi_expr_0#
CasADi expression for the outer loss function \(\psi(r - yref, t, p)\), initial; Default:
[]
Used ifacados_template.acados_ocp_options.AcadosOcpOptions.cost_type_0
is ‘CONVEX_OVER_NONLINEAR’.
- cost_psi_expr_e#
CasADi expression for the outer loss function \(\psi(r - yref, p)\), terminal; Default:
[]
Used ifacados_template.acados_ocp_options.AcadosOcpOptions.cost_type_e
is ‘CONVEX_OVER_NONLINEAR’.
- cost_r_in_psi_expr#
CasADi symbolic input variable for the argument \(r\) to the outer loss function \(\psi(r, t, p)\); Default:
[]
Used ifacados_template.acados_ocp_options.AcadosOcpOptions.cost_type
is ‘CONVEX_OVER_NONLINEAR’.
- cost_r_in_psi_expr_0#
CasADi symbolic input variable for the argument \(r\) to the outer loss function \(\psi(r, t, p)\), initial; Default:
[]
Used ifacados_template.acados_ocp_options.AcadosOcpOptions.cost_type_0
is ‘CONVEX_OVER_NONLINEAR’.
- cost_r_in_psi_expr_e#
CasADi symbolic input variable for the argument \(r\) to the outer loss function \(\psi(r, p)\), terminal; Default:
[]
Used ifacados_template.acados_ocp_options.AcadosOcpOptions.cost_type_e
is ‘CONVEX_OVER_NONLINEAR’.
- cost_y_expr#
CasADi expression for nonlinear least squares; Default:
[]
- cost_y_expr_0#
CasADi expression for nonlinear least squares, initial; Default:
[]
- cost_y_expr_e#
CasADi expression for nonlinear least squares, terminal; Default:
[]
- disc_dyn_expr#
CasADi expression for the discrete dynamics \(x_{+} = f_\text{disc}(x, u, p)\). Used if
acados_template.acados_ocp_options.AcadosOcpOptions.integrator_type
== ‘DISCRETE’. Default:[]
- dyn_disc_fun#
name of function discrete dynamics, only relevant if
dyn_ext_fun_type
is'generic'
; Default:None
- dyn_disc_fun_jac#
name of function discrete dynamics + jacobian, only relevant if
dyn_ext_fun_type
is'generic'
; Default:None
- dyn_disc_fun_jac_hess#
name of function discrete dynamics + jacobian and hessian, only relevant if
dyn_ext_fun_type
is'generic'
; Default:None
- dyn_ext_fun_type#
type of external functions for dynamics module; ‘casadi’ or ‘generic’; Default: ‘casadi’
- dyn_generic_source#
name of source file for discrete dynamics, only relevant if
dyn_ext_fun_type
is'generic'
; Default:None
- dyn_impl_dae_fun#
name of source files for implicit DAE function value, only relevant if
dyn_ext_fun_type
is'generic'
; Default:None
- dyn_impl_dae_fun_jac#
name of source files for implicit DAE function value and jacobian, only relevant if
dyn_ext_fun_type
is'generic'
; Default:None
- dyn_impl_dae_jac#
name of source files for implicit DAE jacobian, only relevant if
dyn_ext_fun_type
is'generic'
; Default:None
- f_expl_expr#
CasADi expression for the explicit dynamics \(\dot{x} = f_\text{expl}(x, u, p)\). Used if
acados_template.acados_ocp_options.AcadosOcpOptions.integrator_type
== ‘ERK’. Default:[]
- f_impl_expr#
CasADi expression for the implicit dynamics \(f_\text{impl}(\dot{x}, x, u, z, p) = 0\). Used if
acados_template.acados_ocp_options.AcadosOcpOptions.integrator_type
== ‘IRK’. Default:[]
- gnsf_nontrivial_f_LO#
GNSF: Flag indicating whether GNSF stucture has nontrivial f.
- gnsf_purely_linear#
GNSF: Flag indicating whether GNSF stucture is purely linear.
- name#
The model name is used for code generation. Type: string. Default:
None
- nu_original#
Number of original control inputs (before polynomial control augmentation); Default:
None
- p#
CasADi variable describing parameters of the DAE; Default:
[]
- p_global#
CasADi variable containing global parameters. This feature can be used to precompute expensive terms which only depend on these parameters, e.g. spline coefficients, when p_global are underlying data points. Only supported for OCP solvers. Updating these parameters can be done using
acados_template.acados_ocp_solver.AcadosOcpSolver.set_p_global_and_precompute_dependencies(values)
. NOTE: this is only supported with CasADi beta release casadi/casadi Default:[]
- reformulate_with_polynomial_control(degree: int) None #
Augment the model with polynomial control.
Replace the original control input \(u\) with a polynomial control input \(v_{\text{poly}} = \sum_{i=0}^d u_i t^i\) New controls are \(u_0, \dots, u_d\).
NOTE: bounds on controls are not changed in this function.
- Parameters
degree (int) – degree of the polynomial control
- substitute(var: Union[SX, MX], expr_new: Union[SX, MX]) None #
Substitutes the variables var with expr_new in all symbolic CasADi expressions within AcadosModel
- t#
CasADi variable representing time t in functions; Default:
[]
NOTE: - For integrators, the start time has to be explicitly set via :py:attr:`acados_template.AcadosSimSolver.set`(‘t0’). - For OCPs, the start time is set to 0. on each stage. The time dependency can be used within cost formulations and is relevant when cost integration is used. Start times of shooting intervals can be added using parameters.
- t0#
CasADi variable representing the start time of an interval; Default:
None
- property t_label#
Label for the time variable. Default: :code:’t’
- u#
CasADi variable describing the input of the system; Default:
[]
- property u_labels#
Contains list of labels for the controls. Default:
None
- x#
CasADi variable describing the state of the system; Default:
[]
- property x_labels#
Contains list of labels for the states. Default:
None
- xdot#
CasADi variable describing the derivative of the state wrt time; Default:
[]
- z#
CasADi variable describing the algebraic variables of the DAE; Default:
[]
acados
integrator interface#
The class AcadosSim
can be used to formulate a simulation problem, for which an acados integrator, AcadosSimSolver
, can be created.
The interface to interact with the acados integrator in C is based on ctypes.
AcadosSim
#
- class acados_template.acados_sim.AcadosSim(acados_path='')#
The class has the following properties that can be modified to formulate a specific simulation problem, see below:
- Parameters
acados_path – string with the path to acados. It is used to generate the include and lib paths.
dims
of typeacados_template.acados_dims.AcadosSimDims
- are automatically detected from modelsolver_options
of typeacados_template.acados_sim.AcadosSimOptions
acados_include_path
(set automatically)shared_lib_ext
(set automatically)acados_lib_path
(set automatically)parameter_values
- used to initialize the parameters (can be changed)
- acados_include_path#
Path to acados include directory (set automatically), type: string
- acados_lib_path#
Path to where acados library is located (set automatically), type: string
- code_export_directory#
Path to where code will be exported. Default: c_generated_code.
- dims#
Dimension definitions, automatically detected from
model
. Typeacados_template.acados_dims.AcadosSimDims
- model#
Model definitions, type
acados_template.acados_model.AcadosModel
- property parameter_values#
\(p\) - initial values for parameter - can be updated
- solver_options#
Solver Options, type
acados_template.acados_sim.AcadosSimOptions
AcadosSimSolver
#
- class acados_template.acados_sim_solver.AcadosSimSolver(acados_sim: AcadosSim, json_file='acados_sim.json', generate=True, build=True, cmake_builder: Optional[CMakeBuilder] = None, verbose: bool = True)#
Class to interact with the acados integrator C object.
- param acados_sim
type
AcadosOcp
(takes values to generate an instanceAcadosSim
) orAcadosSim
- param json_file
Default: ‘acados_sim.json’
- param build
Default: True
- param cmake_builder
type
CMakeBuilder
generate a CMakeLists.txt and use the CMake pipeline instead of a Makefile (CMake seems to be the better option in conjunction with MS Visual Studio); default: None
- property acados_lib_uses_omp#
acados_lib_uses_omp - flag indicating whether the acados library has been compiled with openMP.
- classmethod create_cython_solver(json_file)#
- classmethod generate(acados_sim: AcadosSim, json_file='acados_sim.json', cmake_builder: Optional[CMakeBuilder] = None)#
Generates the code for an acados sim solver, given the description in acados_sim
- get(field_)#
Get the last solution of the solver.
- param str field
string in [‘x’, ‘u’, ‘z’, ‘S_forw’, ‘Sx’, ‘Su’, ‘S_adj’, ‘S_hess’, ‘S_algebraic’, ‘CPUtime’, ‘time_tot’, ‘ADtime’, ‘time_ad’, ‘LAtime’, ‘time_la’]
- options_set(field_: str, value_: bool)#
Set solver options
- param field
string in [‘sens_forw’, ‘sens_adj’, ‘sens_hess’]
- param value
Boolean
- set(field_: str, value_)#
Set numerical data inside the solver.
- param field
string in [‘x’, ‘u’, ‘p’, ‘xdot’, ‘z’, ‘seed_adj’, ‘T’, ‘t0’]
- param value
the value with appropriate size.
- simulate(x=None, u=None, z=None, xdot=None, p=None)#
Simulate the system forward for the given x, u, p and return x_next. The values xdot, z are used as initial guesses for implicit integrators, if provided. Wrapper around solve() taking care of setting/getting inputs/outputs.
- solve()#
Solve the simulation problem with current input.
AcadosSimOptions
#
- class acados_template.acados_sim.AcadosSimOptions#
class containing the solver options
- property T#
Time horizon
- property collocation_type#
Collocation type: relevant for implicit integrators – string in {‘GAUSS_RADAU_IIA’, ‘GAUSS_LEGENDRE’, ‘EXPLICIT_RUNGE_KUTTA’}.
Default: GAUSS_LEGENDRE
- property ext_fun_compile_flags#
String with compiler flags for external function compilation. Default: ‘-O2’ if environment variable ACADOS_EXT_FUN_COMPILE_FLAGS is not set, else ACADOS_EXT_FUN_COMPILE_FLAGS is used as default.
- property integrator_type#
Integrator type. Default: ‘ERK’.
- property newton_iter#
Number of Newton iterations in simulation method. Default: 3
- property newton_tol#
Tolerance for Newton system solved in implicit integrator (IRK, GNSF). 0.0 means this is not used and exactly newton_iter iterations are carried out. Default: 0.0
- property num_stages#
Number of stages in the integrator. Default: 1
- property num_steps#
Number of steps in the integrator. Default: 1
- property num_threads_in_batch_solve#
Integer indicating how many threads should be used within the batch solve. If more than one thread should be used, the sim solver is compiled with openmp. Default: 1.
- property output_z#
Boolean determining if values for algebraic variables (corresponding to start of simulation interval) are computed. Default: True
- property sens_adj#
Boolean determining if adjoint sensitivities are computed. Default: False
- property sens_algebraic#
Boolean determining if sensitivities wrt algebraic variables are computed. Default: False
- property sens_forw#
Boolean determining if forward sensitivities are computed. Default: True
- property sens_hess#
Boolean determining if hessians are computed. Default: False
- property sim_method_jac_reuse#
Integer determining if jacobians are reused (0 or 1). Default: 0
AcadosSimDims
#
- class acados_template.acados_dims.AcadosSimDims#
Class containing the dimensions of the model to be simulated.
- property np#
\(n_p\) - number of parameters. Type: int >= 0
- property nu#
\(n_u\) - number of inputs. Type: int >= 0
- property nx#
\(n_x\) - number of states. Type: int > 0
- property nz#
\(n_z\) - number of algebraic variables. Type: int >= 0
Builders#
The default builder for acados
is make
using a Makefile
generated by acados
.
If cross-platform compatibility is required CMake
can be used to build the binaries required by the solvers.
- class acados_template.builders.CMakeBuilder#
Class to work with the CMake build system.
- build_targets#
A comma-separated list of the build targets, if None then all targets will be build; type: List of strings; default: None.
- exec(code_export_directory, verbose=True)#
Execute the compilation using CMake with the given settings. :param code_export_directory: must be the absolute path to the directory where the code was exported to
- host#
Defines the generator, options can be found via cmake –help under ‘Generator’. Type: string. Linux default ‘Unix Makefiles’, Windows ‘Visual Studio 15 2017 Win64’; default value: None.
- options_on#
List of strings as CMake options which are translated to ‘-D Opt[0]=ON -D Opt[1]=ON …’; default: None.
- acados_template.builders.ocp_get_default_cmake_builder() CMakeBuilder #
If
AcadosOcpSolver
is used with CMake this function returns a good first setting. :return: defaultCMakeBuilder
- acados_template.builders.sim_get_default_cmake_builder() CMakeBuilder #
If
AcadosSimSolver
is used with CMake this function returns a good first setting. :return: defaultCMakeBuilder
acados
multi-phase OCP#
Advanced feature interface to formulate multi-phase OCPs.
- class acados_template.acados_multiphase_ocp.AcadosMultiphaseOcp(N_list: list)#
Class containing the description of an optimal control problem with multiple phases. This object can be used to create an
acados_template.acados_ocp_solver.AcadosOcpSolver
.Initial cost and constraints are defined by the first phase, terminal cost and constraints by the last phase. All other phases are treated as intermediate phases, where only dynamics and path cost and constraints are used.
Solver options are shared between all phases. Options that can vary phase-wise must be set via self.mocp_opts of type
acados_template.acados_multiphase_ocp.AcadosMultiphaseOptions
.- Parameters
N_list – list containing the number of shooting intervals for each phase
- __get_template_list(cmake_builder=None) list #
returns a list of tuples in the form: (input_filename, output_filname) or (input_filename, output_filname, output_directory)
- acados_include_path#
Path to acados include directory (set automatically), type: string
- acados_lib_path#
Path to where acados library is located, type: string
- code_export_directory#
Path to where code will be exported. Default: c_generated_code.
- constraints#
Constraints definitions, type
acados_template.acados_ocp_constraints.AcadosOcpConstraints
- cost#
Cost definitions, type
acados_template.acados_ocp_cost.AcadosOcpCost
- property json_file#
Name of the json file where the problem description is stored.
- mocp_opts#
Phase-wise varying solver Options, type
acados_template.acados_multiphase_ocp.AcadosMultiphaseOptions
- model#
Model definitions, type
acados_template.acados_model.AcadosModel
- property p_global_values#
initial values for \(p_\text{global}\) vector, see AcadosModel.p_global - can be updated. NOTE: p_global is shared between all phases. Type: numpy.ndarray of shape (np_global, ).
- property parameter_values#
\(p\) - list of initial values for parameter vector. Type: list of numpy.ndarray of shape (np_i, ). - can be updated stagewise.
- set_phase(ocp: AcadosOcp, phase_idx: int) None #
Set phase of the multiphase OCP to match the given OCP.
- NOTE: model, cost, constraints and parameter_values are taken from phase OCP,
all other fields, especially options are ignored.
- Parameters
ocp – OCP to be set as phase
phase_idx – index of the phase, must be in [0, n_phases-1]
- simulink_opts#
Options to configure Simulink S-function blocks, mainly to activate possible Inputs and Outputs.
- solver_options#
Solver Options, type
acados_template.acados_ocp_options.AcadosOcpOptions
- class acados_template.acados_multiphase_ocp.AcadosMultiphaseOptions#
Class containing options that might be different for each phase.
All of the fields can be either None, then the corresponding value from ocp.solver_options is used, or a list of length n_phases describing the value for this option at each phase.
integrator_type: list of strings, must be in [“ERK”, “IRK”, “GNSF”, “DISCRETE”, “LIFTED_IRK”]
collocation_type: list of strings, must be in [“GAUSS_RADAU_IIA”, “GAUSS_LEGENDRE”, “EXPLICIT_RUNGE_KUTTA”]
cost_discretization: list of strings, must be in [“EULER”, “INTEGRATOR”]