Core classes for setting up and solving optimal control problems
Vector
sympy.Matrix
operations.
Arguments:
*args
- Number, list, Vector, sympy.Matrix, and/or BaseContainer. Input elements to initialize or concatenate.
Vector
/sympy.Matrix
inputs must be column vectors (if more than one argument is provided).
List elements must be valid slicings of a Vector
.
BaseContainer
instances are treated as collections of symbols.Vector
- Column vector if more than one argument is provided or the input is not a matrix.
Matrix if a single matrix argument is provided.ValueError
- If any matrix input is not a column vector (if more than one argument is provided)
or if any list element is not a valid slicing of a Vector
.BaseContainer
z.z1
).z[0]
).z[1:3]
).symbols
- List[sm.Symbol]. List of symbols contained in the container.BaseContainer.shape
ParameterSymbol
sympy.Symbol
while adding persistent value storage for numerical
evaluations. Maintains symbolic properties for mathematical operations.
Attributes:
value
- Float. Current numerical value associated with the symbol. Persists through symbolic
operations.ParameterSymbol.set_value
value
- Float. Numerical value to store with the symbol. Converted to float
internally.ValueError
- If the input is not a valid float
.TypeError
- If input cannot be converted to float
.Parameters
value
- List[float]. Current numerical values of all parameters in matrix order.Parameters.value
List[float]
- Contains None for any unset parameters.Parameters.set_value
*values
- Float. Numerical values corresponding to matrix elements.ValueError
- If number of values does not match parameter count.TypeError
- If any value cannot be converted to float
.ControlSymbol
sympy.Symbol
while adding persistent minimum and maximum value storage
for numerical evaluations. Maintains symbolic properties for mathematical operations.
Attributes:
initial
- Float. Initial value for the control input initial guess trajectory.final
- Float. Final value for the control input initial guess trajectory.minimum
- Float. Minimum allowable value for the control input.maximum
- Float. Maximum allowable value for the control input.max_rate
- Float. Maximum allowable rate for the control input.sol
- Ndarray. Solution trajectory obtained by solving the optimal control problem.sim
- Ndarray. Simulated trajectory obtained by propagating the system with the control input solution.ControlSymbol.set_initial
initial_value
- Float. Initial value to store.TypeError
- If input cannot be converted to float.ValueError
- If the input is not a valid float
.ControlSymbol.set_final
final_value
- Float. Final value to store.TypeError
- If input cannot be converted to float.ValueError
- If the input is not a valid float
.ControlSymbol.set_minimum
minimum_value
- Float. Minimum value to store.TypeError
- If input cannot be converted to float.ValueError
- If the input is not a valid float
.ControlSymbol.set_maximum
maximum_value
- Float. Maximum value to store.TypeError
- If input cannot be converted to float.ValueError
- If the input is not a valid float
.ControlSymbol.set_max_rate
max_rate_value
- Float or None (optional). Maximum rate to store.TypeError
- If input cannot be converted to float.ValueError
- If the input is not a valid float
or is negative.ControlSymbol.plot
**kwargs
- Dict. Additional plotting parameters.marker_color
- Str, optional. Color for solution markers. Defaults to 'tomato'
.use_tex
- Bool, optional. Whether to use LaTeX for text rendering. Defaults to True
.plot_sol
- Bool, optional. Whether to plot solution points. Defaults to True
.plot_sim
- Bool, optional. Whether to plot simulation line. Defaults to True
.show
- Bool, optional. Whether to display the plot. Defaults to True
.save
- Bool, optional. Whether to save the plot. Defaults to False
.save_filename
- Str, optional. Filename for the saved plot. Defaults to self.name
.save_dir
- Str, optional. Directory to save the plot in. Defaults to the {solver_directory}/plots
directory.save_format
- Str, optional. Format to save the plot in. Defaults to 'pdf'
.save_bbox_inches
- Str, optional. Bounding box for saved plot. Defaults to 'tight'
.sol_kwargs
- Dict, optional. Additional kwargs for solution plot.sim_kwargs
- Dict, optional. Additional kwargs for simulation plot.Controls
BaseContainer
.
Attributes:
minimum
- List[float]. Minimum allowable values for all control inputs in matrix order.maximum
- List[float]. Maximum allowable values for all control inputs in matrix order.max_rate
- List[float]. Maximum rate for all control inputs in matrix order.Controls.initial
List[float]
- Initial values of all control inputs.Controls.final
List[float]
- Final values of all control inputs.Controls.minimum
List[float]
- Minimum values of all control inputs.Controls.maximum
List[float]
- Maximum values of all control inputs.Controls.max_rate
List[float]
- Maximum rate of all control inputs.Controls.set_initial
*initial_values
- Float. Initial values corresponding to matrix elements in matrix order.ValueError
- If number of values does not match control count.TypeError
- If any value cannot be converted to float.Controls.set_final
*final_values
- Float. Final values corresponding to matrix elements in matrix order.ValueError
- If number of values does not match control count.TypeError
- If any value cannot be converted to float.Controls.set_minimum
*minimum_values
- Float. Minimum values corresponding to matrix elements in matrix order.ValueError
- If number of values does not match control count.TypeError
- If any value cannot be converted to float.Controls.set_maximum
*maximum_values
- Float. Maximum values corresponding to matrix elements.ValueError
- If number of values does not match control count.TypeError
- If any value cannot be converted to float.Controls.set_max_rate
*max_rate_values
- Float. Maximum rates corresponding to matrix elements.ValueError
- If number of values does not match control count.TypeError
- If any value cannot be converted to float.Controls.plot
**kwargs
- Dict. Additional plotting parameters.title
- Str, optional. Title for the plot grid. Defaults to None
.marker_color
- Str, optional. Color for solution markers. Defaults to 'tomato'
.use_tex
- Bool, optional. Whether to use LaTeX for text rendering. Defaults to True
.cols
- Int, optional. Number of columns in the grid. Defaults to 3
.plot_sol
- Bool, optional. Whether to plot solution points. Defaults to True
.plot_sim
- Bool, optional. Whether to plot simulation line. Defaults to True
.show
- Bool, optional. Whether to display the plot. Defaults to True
.save
- Bool, optional. Whether to save the plot. Defaults to False
.save_filename
- Str, optional. Filename for the saved plot. Defaults to "controls"
.save_dir
- Str, optional. Directory to save the plot in. Defaults to the {solver_directory}/plots
directory.save_format
- Str, optional. Format to save the plot in. Defaults to 'pdf'
.save_bbox_inches
- Str, optional. Bounding box for saved plot. Defaults to 'tight'
.sol_kwargs
- Dict, optional. Additional kwargs for solution plots.sim_kwargs
- Dict, optional. Additional kwargs for simulation plots.Free
guess
- Float. Initial guess for the free variable.Maximize
Free
.
Minimize
Free
.
StateSymbol
sympy.Symbol
while adding persistent minimum and maximum value storage
for numerical evaluations. Maintains symbolic properties for mathematical operations.
Attributes:
initial
- Float. Initial condition for the state.final
- Float. Final condition for the state.minimum
- Float. Minimum allowable value for the state.maximum
- Float. Maximum allowable value for the state.sol
- Ndarray. Solution trajectory obtained by solving the optimal control problem.sim
- Ndarray. Simulated trajectory obtained by propagating the system with the control input solution.StateSymbol.set_initial
initial_value
- Float or Free. Initial value to store.TypeError
- If input is not a float
or Free
.StateSymbol.set_final
final_value
- Float, Free, Minimize, or Maximize. Final value to store.TypeError
- If input is not an allowed type.StateSymbol.set_minimum
minimum_value
- Float. Minimum value to store.TypeError
- If input cannot be converted to float.ValueError
- If the input is not a valid float
.StateSymbol.set_maximum
maximum_value
- Float. Maximum value to store.TypeError
- If input cannot be converted to float.ValueError
- If the input is not a valid float
.StateSymbol.plot
**kwargs
- Dict. Additional plotting parameters.marker_color
- Str, optional. Color for solution markers. Defaults to 'mediumspringgreen'
.use_tex
- Bool, optional. Whether to use LaTeX for text rendering. Defaults to True
.plot_sol
- Bool, optional. Whether to plot solution points. Defaults to True
.plot_sim
- Bool, optional. Whether to plot simulation line. Defaults to True
.show
- Bool, optional. Whether to display the plot. Defaults to True
.save
- Bool, optional. Whether to save the plot. Defaults to False
.save_filename
- Str, optional. Filename for the saved plot. Defaults to self.name
.save_dir
- Str, optional. Directory to save the plot in. Defaults to the {solver_directory}/plots
directory.save_format
- Str, optional. Format to save the plot in. Defaults to 'pdf'
.save_bbox_inches
- Str, optional. Bounding box for saved plot. Defaults to 'tight'
.sol_kwargs
- Dict, optional. Additional kwargs for solution plot.sim_kwargs
- Dict, optional. Additional kwargs for simulation plot.States
BaseContainer
.
Attributes:
initial
- List[float]. Initial conditions for all states in matrix order.final
- List[float]. Final conditions for all states in matrix order.minimum
- List[float]. Minimum allowable values for all states in matrix order.maximum
- List[float]. Maximum allowable values for all states in matrix order.sol
- Ndarray. Solution trajectory obtained by solving the optimal control problem.sim
- Ndarray. Simulated trajectory obtained by propagating the system with the control input solution.States.initial
List[float]
- Initial values of all states.States.final
List[float]
- Final values of all states.States.minimum
List[float]
- Minimum values of all states.States.maximum
List[float]
- Maximum values of all states.States.set_initial
*initial_values
- Float or Free. Initial values corresponding to matrix elements in matrix order.ValueError
- If number of values does not match state count.TypeError
- If any value is not a float
or Free
.States.set_final
*final_values
- Float, Free, Minimize, or Maximize. Final values corresponding to matrix elements
in matrix order.ValueError
- If number of values does not match state count.TypeError
- If any value is not a float
, Free
, Minimize
, or Maximize
.ValueError
- If more than one instance of Maximize
or Minimize
is used.States.set_minimum
*minimum_values
- Float. Minimum values corresponding to matrix elements in matrix order.ValueError
- If number of values does not match state count.TypeError
- If any value cannot be converted to float.States.set_maximum
*maximum_values
- Float. Maximum scaling factors corresponding to matrix elements.ValueError
- If number of values does not match state count.TypeError
- If any value cannot be converted to float.States.plot
**kwargs
- Dict. Additional plotting parameters.title
- Str, optional. Title for the plot grid. Defaults to None
.marker_color
- Str, optional. Color for solution markers. Defaults to 'mediumspringgreen'
.use_tex
- Bool, optional. Whether to use LaTeX for text rendering. Defaults to True
.cols
- Int, optional. Number of columns in the grid. Defaults to 3
.plot_sol
- Bool, optional. Whether to plot solution points. Defaults to True
.plot_sim
- Bool, optional. Whether to plot simulation line. Defaults to True
.show
- Bool, optional. Whether to display the plot. Defaults to True
.save
- Bool, optional. Whether to save the plot. Defaults to False
.save_filename
- Str, optional. Filename for the saved plot. Defaults to "states"
.save_dir
- Str, optional. Directory to save the plot in. Defaults to the {solver_directory}/plots
directory.save_format
- Str, optional. Format to save the plot in. Defaults to 'pdf'
.save_bbox_inches
- Str, optional. Bounding box for saved plot. Defaults to 'tight'
.sol_kwargs
- Dict, optional. Additional kwargs for solution plots.sim_kwargs
- Dict, optional. Additional kwargs for simulation plots.Dynamics
Vector
.
Constraints
Vector
.
Attributes:
weights
- List[float]. Weights for the constraints.Constraints.weights
List[float]
- Contains None for any unset weights.Constraints.set_weights
*weights
- Float. Weights corresponding to matrix elements.ValueError
- If number of weights does not match constraint count.InequalityConstraints
Constraints
.
EqualityConstraints
Constraints
.
Time
value
- Float, optional. Fixed final time value (must be > 0).guess
- Float, optional. Initial guess for free-final-time optimization (must be > 0).t_max_factor
- Float, default=2.0. Multiplier for maximum time bound (≥ 1.0).t_min_factor
- Float, default=0.2. Multiplier for minimum time bound (≤ 1.0).sol
- Ndarray. Solution trajectory obtained by solving the optimal control problem.sim
- Ndarray. Simulated trajectory obtained by propagating the system with the control input solution.value
and guess
are specifiedvalue
nor guess
is specifiedvalue
t_max_factor
or t_min_factor
are provided along with guess
Time.is_free
Bool
- True if using free-final-time configuration.Time.t_max_factor
Float
- Configured upper bound factor.AttributeError
- If accessed when configured for fixed-final-time.Time.t_min_factor
Float
- Configured lower bound factor.AttributeError
- If accessed when configured for fixed-final-time.Time.value
Float
- Configured fixed-final-time valueAttributeError
- If accessed in free-final-time modeTime.guess
Float
- Configured free-final-time initial guessAttributeError
- If accessed in fixed-final-time modeSettings
N_disc
- Int, optional, default=5. Number of temporal discretization nodes. Must be ≥ 2.N_prop
- Int, optional, default=10. Number of integration/propagation steps per interval. Must be ≥ 1.row_norm_tol
- Float, optional, default=1e-4. Minimum row norm tolerance for constraint matrix preconditioning. Must be ≥ 0.auto_precondition
- Bool, optional, default=True. Enable automatic path constraint preconditioning.nonconvex_solver
- Str, optional, default=‘ct_scvx’. Primary nonconvex solver algorithm. Current options:
ct_scvx
: Continuous-time successive convexification (CT-SCvx)constraint_relax
- Float, optional, default=1e-4. Constraint violation relaxation tolerance. Must be ≥ 0.w_cost
- Float, optional, default=0.1. Cost function weight. Must be ≥ 0.w_trust
- Float, optional, default=1.0. Trust region penalty weight. Must be ≥ 0.w_slack
- Float, optional, default=0.0. Exact penalty weight (initial value). Must be ≥ 0.w_slack_step
- Float, optional, default=1.0. Dual integrator step-size. Must be ≥ 0.w_slack_step_multiplier
- Float, optional, default=5.0. Dual integrator step-size multiplier. Must be ≥ 0.w_slack_step_max
- Float, optional, default=1e8. Dual integrator step-size saturation value. Must be ≥ w_slack_step
.w_slack_max
- Float, optional, default=1e8. Dual parameter saturation value. Must be ≥ w_slack
.trust_tol
- Float, optional, default=5e-3. Trust region convergence tolerance. Must be ≥ 0.slack_tol
- Float, optional, default=1e-6. Exact penalty convergence tolerance. Must be ≥ 0.max_iters
- Int, optional, default=10. Maximum number of SCP iterations. Must be ≥ 1.convex_solver
- Str, optional, default=‘QOCO’. Convex optimization subproblem solver. Only valid when using ct_scvx
.Options
- [‘ECOS’, ‘OSQP’, ‘QOCO’, ‘QOCOGEN’, ‘PIPG’].cvx_abs_tol
- Float, optional, default=1e-7. Absolute convex solver tolerance. Must be ≥ 0.cvx_rel_tol
- Float, optional, default=1e-7. Relative convex solver tolerance. Must be ≥ 0.linear_algebra
- Str, optional, default=‘custom’. Linear algebra backend. Options: [‘custom’, ‘BLAS’].blas_path
- Str, required if linear_algebra='BLAS'
. Absolute path to OpenBLAS.precision
- Str, optional, default=‘double’. Floating-point precision. Options: [‘float’, ‘double’].target
- Str, optional, default=‘CPU’. Hardware target platform. Options: [‘CPU’, ‘GPU’].convex_solver
is specified with incompatible nonconvex_solver
.linear_algebra='BLAS'
and blas_path
is not provided/is not a string.linear_algebra='custom'
and blas_path
is provided.Problem
Problem
class serves as the primary interface for defining optimal control problems,
generating a C codebase for the full-stack solver, and solving the problem numerically.
Attributes:
time
- Time. Temporal attributes.parameters
- Parameters. System and constraint parameters (constants).states
- States. State variables of the system, including initial and final conditions, and bounds.controls
- Controls. Control inputs to the system, including initial guess endpoints and bounds.dynamics
- Dynamics. Equations of motion.inequality_constraints
- InequalityConstraints, optional. Path inequality constraints.
Defaults to None
if not provided.equality_constraints
- EqualityConstraints, optional. Path equality constraints.
Defaults to None
if not provided.settings
- Settings, optional. Numerical solver settings to configure the optimization process.
Defaults to a Settings
object with default solver configurations if not provided.BaseSolution
Solution
BaseSolution
namedtuple.
It overrides the _replace()
method to raise an error.
Raises:
AttributeError
- If _replace()
is called.Problem.generate_code
Problem
instance.
Arguments:
directory
- Str, optional. Directory to generate code in. Defaults to the current directory (’.’).name
- Str, optional. Name of the generated solver directory. Defaults to None
, in which case
the name will be scvxgen_solver
.verbose
- Bool, optional. If True
, displays names of the files generated during the code
generation process. Defaults to False
.Problem.get_base_parameters
ocp_params.yaml
file.
Returns:
Dict
- The base parameters from the ocp_params.yaml
file.RuntimeError
- If the code has not been generated.FileNotFoundError
- If the ocp_params.yaml
file is not found.IOError
- If there is an error reading or parsing the ocp_params.yaml
file.Problem.generate_initial_guess
initial
initial.guess
final
,
(b) If final is free with guess: final.guess
,
(c) If final is free without guess: midpoint of maximum and minimum bounds (with a buffer to ensure a nonzero guess for safety)final
final.guess
final.guess
initial
,
(b) If initial is free with guess: initial.guess
,
(c) If initial is free without guess: midpoint of maximum and minimum bounds (with a buffer to ensure a nonzero guess for safety)w_slack
is repeated across the entire profile.
Note that the last row of the dual parameter array corresponds to the constraint violation (augmented) state.
The dual integrator step-size, w_slack_step
, is taken from the Settings
object.
Returns:
Namedtuple
Solution - Initial guess with straight-line trajectories that can be either modified
directly or by attribute access.Problem.solve
modified_parameters
- Dict, optional. A dictionary of parameters to modify from the defaults
in ocp_params.yaml
. Each key should correspond to a parameter name in ocp_params.yaml
,
and the value will be the new value for that parameter. The updated parameters will be
written to modified_ocp_params.yaml
. If None
(default), the solver will use the
original default parameters in C. Modifications via the modified_parameters
argument
will result in a new modified_ocp_params.yaml
file being written to the solver directory.
Subsequent calls to solve()
without modified_parameters
will use the defaults in C.
Note that ocp_params.yaml
is not modified by solve()
—it is only used as a template
for the modified_ocp_params.yaml
file.initial_guess
- Solution, optional. Initial guess trajectories for the states and controls—these
can either be out.sol
from a previous call to solve()
or a Solution
object generated
by generate_initial_guess()
, both of which can be modified before being passed to solve()
as custom initial guesses.force_build
- Bool, optional. If True
, forces a re-build of the generated C code before solving.
Defaults to False
.build_verbose
- Bool, optional. If True
, prints output from the build process. Defaults to False
.display_progress
- Bool, optional. If True
, prints the solver progress table. Defaults to True
.save_output
- Bool, optional. If True
, saves the solver output to output.bin
in the data
directory and extracts the output data. Defaults to True
.RuntimeError
- If code has not been generated, or if the compilation process fails, or if the
solver encounters an error.FileNotFoundError
- If the bash scripts are not found in the build directory.OSError
- If there is a permission error when making the bash scripts executable.