Python Interface
Core classes for setting up and solving optimal control problems
Vector
Vector container supporting mixed scalar/vector/list initialization and easy concatenation.
Allows direct matrix inputs and maintains column vector structure while allowing multiple inputs.
Inherits all 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 aVector
.BaseContainer
instances are treated as collections of symbols.
Returns:
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.
Raises:
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 aVector
.
BaseContainer
Base class for containers of symbols with value storage capability.
Provides a structure for managing collections of symbols that can store individual values.
Supports multiple access patterns:
- Attribute-based access (
z.z1
). - Index-based access (
z[0]
). - Slice operations (
z[1:3]
).
Attributes:
symbols
- List[sm.Symbol]. List of symbols contained in the container.
BaseContainer.shape
ParameterSymbol
Enhanced symbolic type with numerical value storage capability.
Inherits from 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
Update the numerical value associated with this symbol.
Arguments:
value
- Float. Numerical value to store with the symbol. Converted tofloat
internally.
Raises:
ValueError
- If the input is not a validfloat
.TypeError
- If input cannot be converted tofloat
.
Parameters
Symbolic parameter vector container with value management.
Attributes:
value
- List[float]. Current numerical values of all parameters in matrix order.
Parameters.value
Current numerical values of all parameters in matrix order.
Returns:
List[float]
- Contains None for any unset parameters.
Parameters.set_value
Set numerical values for parameters in matrix order.
Arguments:
*values
- Float. Numerical values corresponding to matrix elements.
Raises:
ValueError
- If number of values does not match parameter count.TypeError
- If any value cannot be converted tofloat
.
ControlSymbol
Symbolic control input with minimum and maximum value storage capability.
Inherits from 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.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
Set the initial value for this control input initial guess trajectory.
Arguments:
initial_value
- Float. Initial value to store.
Raises:
TypeError
- If input cannot be converted to float.ValueError
- If the input is not a validfloat
.
ControlSymbol.set_final
Set the final value for this control input initial guess trajectory.
Arguments:
final_value
- Float. Final value to store.
Raises:
TypeError
- If input cannot be converted to float.ValueError
- If the input is not a validfloat
.
ControlSymbol.set_minimum
Set the minimum allowable value for this control input.
Arguments:
minimum_value
- Float. Minimum value to store.
Raises:
TypeError
- If input cannot be converted to float.ValueError
- If the input is not a validfloat
.
ControlSymbol.set_maximum
Set the maximum allowable value for this control input.
Arguments:
maximum_value
- Float. Maximum value to store.
Raises:
TypeError
- If input cannot be converted to float.ValueError
- If the input is not a validfloat
.
ControlSymbol.plot
Plot the control input signal as a function of time.
Arguments:
**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 toTrue
.plot_sol
- Bool, optional. Whether to plot solution points. Defaults toTrue
.plot_sim
- Bool, optional. Whether to plot simulation line. Defaults toTrue
.show
- Bool, optional. Whether to display the plot. Defaults toTrue
.save
- Bool, optional. Whether to save the plot. Defaults toFalse
.save_filename
- Str, optional. Filename for the saved plot. Defaults toself.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.
Returns:
Tuple. (fig, ax) - The figure and axes objects.
Controls
Symbolic control vector container with minimum and maximum value management.
Inherits from 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.
Controls.initial
Get the initial values for the control input initial guess trajectory in matrix order.
Returns:
List[float]
- Initial values of all control inputs.
Controls.final
Get the final values for the control input initial guess trajectory in matrix order.
Returns:
List[float]
- Final values of all control inputs.
Controls.minimum
Get the minimum values for control inputs in matrix order.
Returns:
List[float]
- Minimum values of all control inputs.
Controls.maximum
Get the maximum values for control inputs in matrix order.
Returns:
List[float]
- Maximum values of all control inputs.
Controls.set_initial
Set initial values for the control input initial guess trajectory in matrix order.
Arguments:
*initial_values
- Float. Initial values corresponding to matrix elements in matrix order.
Raises:
ValueError
- If number of values does not match control count.TypeError
- If any value cannot be converted to float.
Controls.set_final
Set final values for the control input initial guess trajectory in matrix order.
Arguments:
*final_values
- Float. Final values corresponding to matrix elements in matrix order.
Raises:
ValueError
- If number of values does not match control count.TypeError
- If any value cannot be converted to float.
Controls.set_minimum
Set minimum values for control inputs in matrix order.
Arguments:
*minimum_values
- Float. Minimum values corresponding to matrix elements in matrix order.
Raises:
ValueError
- If number of values does not match control count.TypeError
- If any value cannot be converted to float.
Controls.set_maximum
Set maximum values for control inputs in matrix order.
Arguments:
*maximum_values
- Float. Maximum values corresponding to matrix elements.
Raises:
ValueError
- If number of values does not match control count.TypeError
- If any value cannot be converted to float.
Controls.plot
Plot the control input signals as a function of time.
Arguments:
**kwargs
- Dict. Additional plotting parameters.title
- Str, optional. Title for the plot grid. Defaults toNone
.marker_color
- Str, optional. Color for solution markers. Defaults to'tomato'
.use_tex
- Bool, optional. Whether to use LaTeX for text rendering. Defaults toTrue
.cols
- Int, optional. Number of columns in the grid. Defaults to3
.plot_sol
- Bool, optional. Whether to plot solution points. Defaults toTrue
.plot_sim
- Bool, optional. Whether to plot simulation line. Defaults toTrue
.show
- Bool, optional. Whether to display the plot. Defaults toTrue
.save
- Bool, optional. Whether to save the plot. Defaults toFalse
.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.
Returns:
Tuple. (fig, axes) - The figure and axes objects.
Free
Flag for free state variables in the optimization problem.
Attributes:
guess
- Float. Initial guess for the free variable.
Maximize
Flag for maximizing a state variable.
Inherits from Free
.
Minimize
Flag for minimizing a state variable.
Inherits from Free
.
StateSymbol
Symbolic state with minimum and maximum value storage capability.
Inherits from 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
Set the initial condition for this state.
Arguments:
initial_value
- Float or Free. Initial value to store.
Raises:
TypeError
- If input is not afloat
orFree
.
StateSymbol.set_final
Set the final condition for this state.
Arguments:
final_value
- Float, Free, Minimize, or Maximize. Final value to store.
Raises:
TypeError
- If input is not an allowed type.
StateSymbol.set_minimum
Set the minimum scaling factor for this state.
Arguments:
minimum_value
- Float. Minimum value to store.
Raises:
TypeError
- If input cannot be converted to float.ValueError
- If the input is not a validfloat
.
StateSymbol.set_maximum
Set the maximum scaling factor for this state.
Arguments:
maximum_value
- Float. Maximum value to store.
Raises:
TypeError
- If input cannot be converted to float.ValueError
- If the input is not a validfloat
.
StateSymbol.plot
Plot the state trajectory as a function of time.
Arguments:
**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 toTrue
.plot_sol
- Bool, optional. Whether to plot solution points. Defaults toTrue
.plot_sim
- Bool, optional. Whether to plot simulation line. Defaults toTrue
.show
- Bool, optional. Whether to display the plot. Defaults toTrue
.save
- Bool, optional. Whether to save the plot. Defaults toFalse
.save_filename
- Str, optional. Filename for the saved plot. Defaults toself.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.
Returns:
Tuple. (fig, ax) - The figure and axes objects.
States
Symbolic state vector container with minimum and maximum value management.
Inherits from 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
Get the initial conditions for the state in matrix order.
Returns:
List[float]
- Initial values of all states.
States.final
Get the final conditions for the state in matrix order.
Returns:
List[float]
- Final values of all states.
States.minimum
Get the minimum scaling factors for states in matrix order.
Returns:
List[float]
- Minimum values of all states.
States.maximum
Get the maximum scaling factors for states in matrix order.
Returns:
List[float]
- Maximum values of all states.
States.set_initial
Set initial conditions for the state in matrix order.
Arguments:
*initial_values
- Float or Free. Initial values corresponding to matrix elements in matrix order.
Raises:
ValueError
- If number of values does not match state count.TypeError
- If any value is not afloat
orFree
.
States.set_final
Set final conditions for the state in matrix order.
Arguments:
*final_values
- Float, Free, Minimize, or Maximize. Final values corresponding to matrix elements in matrix order.
Raises:
ValueError
- If number of values does not match state count.TypeError
- If any value is not afloat
,Free
,Minimize
, orMaximize
.ValueError
- If more than one instance ofMaximize
orMinimize
is used.
States.set_minimum
Set minimum scaling factors for states in matrix order.
Arguments:
*minimum_values
- Float. Minimum values corresponding to matrix elements in matrix order.
Raises:
ValueError
- If number of values does not match state count.TypeError
- If any value cannot be converted to float.
States.set_maximum
Set maximum scaling factors for states in matrix order.
Arguments:
*maximum_values
- Float. Maximum scaling factors corresponding to matrix elements.
Raises:
ValueError
- If number of values does not match state count.TypeError
- If any value cannot be converted to float.
States.plot
Plot state trajectories as a function of time.
Arguments:
**kwargs
- Dict. Additional plotting parameters.title
- Str, optional. Title for the plot grid. Defaults toNone
.marker_color
- Str, optional. Color for solution markers. Defaults to'mediumspringgreen'
.use_tex
- Bool, optional. Whether to use LaTeX for text rendering. Defaults toTrue
.cols
- Int, optional. Number of columns in the grid. Defaults to3
.plot_sol
- Bool, optional. Whether to plot solution points. Defaults toTrue
.plot_sim
- Bool, optional. Whether to plot simulation line. Defaults toTrue
.show
- Bool, optional. Whether to display the plot. Defaults toTrue
.save
- Bool, optional. Whether to save the plot. Defaults toFalse
.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.
Returns:
Tuple. (fig, axes) - The figure and axes objects.
Dynamics
Class for managing dynamics.
Inherits from Vector
.
Constraints
Class for managing constraints.
Inherits from Vector
.
Attributes:
weights
- List[float]. Weights for the constraints.
Constraints.weights
Weights for constraints in matrix order.
Returns:
List[float]
- Contains None for any unset weights.
Constraints.set_weights
Set weights for constraints in matrix order.
Arguments:
*weights
- Float. Weights corresponding to matrix elements.
Raises:
ValueError
- If number of weights does not match constraint count.
InequalityConstraints
Class for managing inequality constraints.
Inherits from Constraints
.
EqualityConstraints
Class for managing equality constraints.
Inherits from Constraints
.
Time
Class for managing trajectory time parameters.
Arguments:
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).
Attributes:
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.
Raises:
ValueError:
- If both
value
andguess
are specified - If neither
value
norguess
is specified - If additional keyword arguments are provided with
value
- If keyword arguments other than
t_max_factor
ort_min_factor
are provided along withguess
- For invalid parameter values TypeError:
- If non-float values are provided where expected
Examples:
Time.is_free
Indicates if configured for free-final-time trajectory optimization.
Returns:
Bool
- True if using free-final-time configuration.
Time.t_max_factor
Trajectory time upper bound factor for free-final-time optimization.
Returns:
Float
- Configured upper bound factor.
Raises:
AttributeError
- If accessed when configured for fixed-final-time.
Time.t_min_factor
Trajectory time lower bound factor for free-final-time optimization.
Returns:
Float
- Configured lower bound factor.
Raises:
AttributeError
- If accessed when configured for fixed-final-time.
Time.value
Get fixed-final-time value.
Returns:
Float
- Configured fixed-final-time value
Raises:
AttributeError
- If accessed in free-final-time mode
Time.guess
Get free-final-time initial guess.
Returns:
Float
- Configured free-final-time initial guess
Raises:
AttributeError
- If accessed in fixed-final-time mode
Settings
Central container for trajectory optimization settings.
All parameters are optional with defaults.
Attributes:
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_max
- Float, optional, default=1e4. 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=‘ECOS’. Convex optimization subproblem solver. Only valid when usingct_scvx
.Options
- [‘ECOS’, ‘OSQP’, ‘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 iflinear_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’].
Raises:
TypeError:
- If any parameter has incorrect type. ValueError:
- If integer parameters are < 1.
- If float parameters are < 0.
- If invalid choice strings are provided.
- If
convex_solver
is specified with incompatiblenonconvex_solver
. - If CT-SCvx parameters are used with other solvers.
- If
linear_algebra='BLAS'
andblas_path
is not provided/is not a string. - If
linear_algebra='custom'
andblas_path
is provided.
Examples:
Problem
Central container for the optimal control problem attributes, solver code generation, and numerical solution.
The 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 toNone
if not provided.equality_constraints
- EqualityConstraints, optional. Path equality constraints. Defaults toNone
if not provided.settings
- Settings, optional. Numerical solver settings to configure the optimization process. Defaults to aSettings
object with default solver configurations if not provided.
Methods:
generate_code(directory=’.’) Generate a C implementation of the optimal control problem solver in the specified directory. solve(force_build=True) Solve the optimal control problem using the generated C code.
BaseSolution
Solution
Container for the solution of the optimal control problem.
This class inherits from the BaseSolution
namedtuple.
It overrides the _replace()
method to raise an error.
Raises:
AttributeError
- If_replace()
is called.
Problem.generate_code
Generate C implementation of the optimal control problem.
This method triggers the code generation process, creating a C implementation
of the solver for the optimal control problem defined by the 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 toNone
, in which case the name will bescvxgen_solver
.verbose
- Bool, optional. IfTrue
, displays names of the files generated during the code generation process. Defaults toFalse
.
Problem.get_base_parameters
Get the base parameters from the ocp_params.yaml
file.
Returns:
Dict
- The base parameters from theocp_params.yaml
file.
Raises:
RuntimeError
- If the code has not been generated.FileNotFoundError
- If theocp_params.yaml
file is not found.IOError
- If there is an error reading or parsing theocp_params.yaml
file.
Problem.generate_initial_guess
Generate default initial guess trajectories (with straight lines between endpoints), and return a namedtuple with enhanced arrays for the state and control trajectories to enable attribute access.
For each state variable:
Start point selection logic:
- If initial is fixed:
initial
- If initial is free with guess:
initial.guess
- If initial is free without guess:
(a) If final is fixed:
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)
End point selection logic:
- If final is fixed:
final
- If final is free with guess:
final.guess
- If final is Maximize/Minimize with guess:
final.guess
- If final is free without guess:
(a) If initial is fixed:
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)
For each control input variable, a straight-line trajectory is generated between the initial and final values.
For the dual parameter, 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.
Returns:
Namedtuple
Solution - Initial guess with straight-line trajectories that can be either modified directly or by attribute access.
Example:
Problem.solve
Solve the optimal control problem using generated C code.
This method builds (if required) and executes the SCvxGEN solver.
Arguments:
modified_parameters
- Dict, optional. A dictionary of parameters to modify from the defaults inocp_params.yaml
. Each key should correspond to a parameter name inocp_params.yaml
, and the value will be the new value for that parameter. The updated parameters will be written tomodified_ocp_params.yaml
. IfNone
(default), the solver will use the original default parameters in C. Modifications via themodified_parameters
argument will result in a newmodified_ocp_params.yaml
file being written to the solver directory. Subsequent calls tosolve()
withoutmodified_parameters
will use the defaults in C. Note thatocp_params.yaml
is not modified bysolve()
—it is only used as a template for themodified_ocp_params.yaml
file.initial_guess
- Solution, optional. Initial guess trajectories for the states and controls—these can either beout.sol
from a previous call tosolve()
or aSolution
object generated bygenerate_initial_guess()
, both of which can be modified before being passed tosolve()
as custom initial guesses.force_build
- Bool, optional. IfTrue
, forces a re-build of the generated C code before solving. Defaults toFalse
.build_verbose
- Bool, optional. IfTrue
, prints output from the build process. Defaults toFalse
.display_progress
- Bool, optional. IfTrue
, prints the solver progress table. Defaults toTrue
.save_output
- Bool, optional. IfTrue
, saves the solver output tooutput.bin
in the data directory and extracts the output data. Defaults toTrue
.
Returns:
Namedtuple (Output) or None: The solver output.
Raises:
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.