Skip to content

API

Warning

This page is still under development 🚧.

Constraints

Constraints in openscvx are created using symbolic expressions with comparison operators (==, <=, >=). By default, constraints are enforced at discrete nodes along the trajectory (nodal constraints). The symbolic expression system provides two specialized constraint wrappers for precise control over when and how constraints are enforced.

Basic Constraints

All basic constraints are automatically enforced at all discrete nodes unless wrapped with .at() or .over().

Equality

openscvx.symbolic.expr.constraint.Equality

Bases: Constraint

Equality constraint for optimization problems.

Represents an equality constraint: lhs == rhs. Can be created using the == operator on Expr objects.

Example

Define an Equality constraint:

x = ox.State("x", shape=(3,))
constraint = x == 0  # Creates Equality(x, Constant(0))

Inequality

openscvx.symbolic.expr.constraint.Inequality

Bases: Constraint

Inequality constraint for optimization problems.

Represents an inequality constraint: lhs <= rhs. Can be created using the <= operator on Expr objects.

Example

Define an Inequality constraint:

x = ox.State("x", shape=(3,))
constraint = x <= 10  # Creates Inequality(x, Constant(10))

Specialized Constraint Wrappers

NodalConstraint

NodalConstraint allows selective enforcement of constraints at specific time points (nodes) in a discretized trajectory. Created using the .at() method on constraints. Note: Bare constraints without .at() or .over() are automatically converted to NodalConstraints applied at all nodes.

openscvx.symbolic.expr.constraint.NodalConstraint

Bases: Expr

Wrapper for constraints enforced only at specific discrete trajectory nodes.

NodalConstraint allows selective enforcement of constraints at specific time points (nodes) in a discretized trajectory, rather than enforcing them at every node. This is useful for:

  • Specifying waypoint constraints (e.g., pass through point X at node 10)
  • Boundary conditions at non-standard locations
  • Reducing computational cost by checking constraints less frequently
  • Enforcing periodic constraints (e.g., every 5th node)

The wrapper maintains clean separation between the constraint's mathematical definition and the specification of where it should be applied during optimization.

Note

Bare Constraint objects (without .at() or .over()) are automatically converted to NodalConstraints applied at all nodes during preprocessing.

Attributes:

Name Type Description
constraint

The wrapped Constraint (Equality or Inequality) to enforce

nodes

List of integer node indices where the constraint is enforced

Example

Enforce position constraint only at nodes 0, 10, and 20:

x = State("x", shape=(3,))
target = [10, 5, 0]
constraint = (x == target).at([0, 10, 20])

Equivalent using NodalConstraint directly:

constraint = NodalConstraint(x == target, nodes=[0, 10, 20])

Periodic constraint enforcement (every 10th node):

velocity_limit = (vel <= 100).at(list(range(0, 100, 10)))

Bare constraints are automatically applied at all nodes. These are equivalent:

constraint1 = vel <= 100  # Auto-converted to all nodes
constraint2 = (vel <= 100).at(list(range(n_nodes)))
_hash_into(hasher: hashlib._Hash) -> None

Hash NodalConstraint including its node list.

Parameters:

Name Type Description Default
hasher _Hash

A hashlib hash object to update

required
canonicalize() -> Expr

Canonicalize the wrapped constraint while preserving node specification.

Returns:

Name Type Description
NodalConstraint Expr

A new NodalConstraint with canonicalized inner constraint

check_shape() -> Tuple[int, ...]

Validate the wrapped constraint's shape.

NodalConstraint wraps a constraint without changing its computational meaning, only specifying where it should be applied. Like all constraints, it produces a scalar result.

Returns:

Name Type Description
tuple Tuple[int, ...]

Empty tuple () representing scalar shape

children()

Return the wrapped constraint as the only child.

Returns:

Name Type Description
list

Single-element list containing the wrapped constraint

convex() -> NodalConstraint

Mark the underlying constraint as convex for CVXPy lowering.

Returns:

Type Description
NodalConstraint

Self with underlying constraint's convex flag set to True (enables method chaining)

Example

Mark a constraint as convex: constraint = (x <= 10).at([0, 5, 10]).convex()

CTCS (Continuous-Time Constraint Satisfaction)

CTCS guarantees strict constraint satisfaction throughout the entire continuous trajectory, not just at discrete nodes. It works by augmenting the state vector with additional states whose dynamics integrate constraint violation penalties. Created using the .over() method on constraints.

openscvx.symbolic.expr.constraint.CTCS

Bases: Expr

Continuous-Time Constraint Satisfaction using augmented state dynamics.

CTCS enables strict continuous-time constraint enforcement in discretized trajectory optimization by augmenting the state vector with additional states whose dynamics are the constraint violation penalties. By constraining these augmented states to remain at zero throughout the trajectory, the original constraints are guaranteed to be satisfied continuously, not just at discrete nodes.

How it works:

  1. Each constraint (in canonical form: lhs <= 0) is wrapped in a penalty function
  2. Augmented states s_aug_i are added with dynamics: ds_aug_i/dt = sum(penalty_j(lhs_j)) for all CTCS constraints j in group i
  3. Each augmented state is constrained: s_aug_i(t) = 0 for all t (strictly enforced)
  4. Since s_aug_i integrates the penalties, s_aug_i = 0 implies all penalties in the group are zero, which means all constraints in the group are satisfied continuously

Grouping and augmented states:

  • CTCS constraints with the same node interval are grouped into a single augmented state by default (their penalties are summed)
  • CTCS constraints with different node intervals create separate augmented states
  • Using the idx parameter explicitly assigns constraints to specific augmented states, allowing manual control over grouping
  • Each unique group creates one augmented state named _ctcs_aug_0, _ctcs_aug_1, etc.

This is particularly useful for:

  • Path constraints that must hold throughout the entire trajectory (not just at nodes)
  • Obstacle avoidance where constraint violation between nodes could be catastrophic
  • State limits that should be respected continuously (e.g., altitude > 0 for aircraft)
  • Ensuring smooth, feasible trajectories between discretization points

Penalty functions (applied to constraint violations):

  • squared_relu: Square(PositivePart(lhs)) - smooth, differentiable (default)
  • huber: Huber(PositivePart(lhs)) - less sensitive to outliers than squared
  • smooth_relu: SmoothReLU(lhs) - smooth approximation of ReLU

Attributes:

Name Type Description
constraint

The wrapped Constraint (typically Inequality) to enforce continuously

penalty

Penalty function type ('squared_relu', 'huber', or 'smooth_relu')

nodes

Optional (start, end) tuple specifying the interval for enforcement, or None to enforce over the entire trajectory

idx

Optional grouping index for managing multiple augmented states. CTCS constraints with the same idx and nodes are grouped together, sharing an augmented state. If None, auto-assigned based on node intervals.

check_nodally

Whether to also enforce the constraint at discrete nodes for additional numerical robustness (creates both continuous and nodal constraints)

Example

Single augmented state (default behavior - same node interval):

altitude = State("alt", shape=(1,))
constraints = [
    (altitude >= 10).over((0, 10)),  # Both constraints share
    (altitude <= 1000).over((0, 10))  # one augmented state
]

Multiple augmented states (different node intervals):

constraints = [
    (altitude >= 10).over((0, 5)),  # Creates _ctcs_aug_0
    (altitude >= 20).over((5, 10))  # Creates _ctcs_aug_1
]

Manual grouping with idx parameter:

constraints = [
    (altitude >= 10).over((0, 10), idx=0),    # Group 0
    (velocity <= 100).over((0, 10), idx=1),   # Group 1 (separate state)
    (altitude <= 1000).over((0, 10), idx=0)   # Also group 0
]
_hash_into(hasher: hashlib._Hash) -> None

Hash CTCS including all its parameters.

Parameters:

Name Type Description Default
hasher _Hash

A hashlib hash object to update

required
canonicalize() -> Expr

Canonicalize the inner constraint while preserving CTCS parameters.

Returns:

Name Type Description
CTCS Expr

A new CTCS with canonicalized inner constraint and same parameters

check_shape() -> Tuple[int, ...]

Validate the constraint and penalty expression shapes.

CTCS transforms the wrapped constraint into a penalty expression that is summed (integrated) over the trajectory, always producing a scalar result.

Returns:

Name Type Description
tuple Tuple[int, ...]

Empty tuple () representing scalar shape

Raises:

Type Description
ValueError

If the wrapped constraint has invalid shape

ValueError

If the generated penalty expression is not scalar

children()

Return the wrapped constraint as the only child.

Returns:

Name Type Description
list

Single-element list containing the wrapped constraint

over(interval: tuple[int, int]) -> CTCS

Set or update the continuous interval for this CTCS constraint.

Parameters:

Name Type Description Default
interval tuple[int, int]

Tuple of (start, end) node indices defining the enforcement interval

required

Returns:

Name Type Description
CTCS CTCS

New CTCS constraint with the specified interval

Example

Define constraint over range:

constraint = (altitude >= 10).over((0, 50))

Update interval to cover different range:

constraint_updated = constraint.over((50, 100))
penalty_expr() -> Expr

Build the penalty expression for this CTCS constraint.

Transforms the constraint's left-hand side (in canonical form: lhs <= 0) into a penalty expression using the specified penalty function. The penalty is zero when the constraint is satisfied and positive when violated.

This penalty expression becomes part of the dynamics of an augmented state. Multiple CTCS constraints in the same group (same idx) have their penalties summed: ds_aug_i/dt = sum(penalty_j) for all j in group i. By constraining s_aug_i(t) = 0 for all t, we ensure all penalties in the group are zero, which strictly enforces all constraints in the group continuously.

Returns:

Name Type Description
Expr Expr

Sum of the penalty function applied to the constraint violation

Raises:

Type Description
ValueError

If an unknown penalty type is specified

Note

This method is used internally during problem compilation to create augmented state dynamics. Multiple penalty expressions with the same idx are summed together before being added to the dynamics vector via Concat.

Integrators

RK45Integrator

openscvx.integrators.solve_ivp_rk45(f: Callable[[jnp.ndarray, jnp.ndarray, Any], jnp.ndarray], tau_final: float, y_0: jnp.ndarray, args, tau_0: float = 0.0, num_substeps: int = 50, is_not_compiled: bool = False)

Solve an initial-value ODE problem using fixed-step RK45 integration.

Parameters:

Name Type Description Default
f Callable[[ndarray, ndarray, Any], ndarray]

ODE right-hand side; signature f(t, y, *args) -> dy/dt.

required
tau_final float

Final integration time.

required
y_0 ndarray

Initial state at tau_0.

required
args tuple

Extra arguments to pass to f.

required
tau_0 float

Initial time. Defaults to 0.0.

0.0
num_substeps int

Number of output time points. Defaults to 50.

50
is_not_compiled bool

If True, use Python loop instead of JAX lax.fori_loop. Defaults to False.

False

Returns:

Type Description

jnp.ndarray: Array of shape (num_substeps, state_dim) with solution at each time.

openscvx.integrators.rk45_step(f: Callable[[jnp.ndarray, jnp.ndarray, Any], jnp.ndarray], t: jnp.ndarray, y: jnp.ndarray, h: float, *args) -> jnp.ndarray

Perform a single RK45 (Runge-Kutta-Fehlberg) integration step.

This implements the classic Dorman-Prince coefficients for an explicit 4(5) method, returning the fourth-order estimate.

Parameters:

Name Type Description Default
f Callable[[ndarray, ndarray, Any], ndarray]

ODE right-hand side; signature f(t, y, *args) -> dy/dt.

required
t ndarray

Current time.

required
y ndarray

Current state vector.

required
h float

Step size.

required
*args

Additional arguments passed to f.

()

Returns:

Type Description
ndarray

jnp.ndarray: Next state estimate at t + h.

Diffrax Integrators

openscvx.integrators.solve_ivp_diffrax(f: Callable[[jnp.ndarray, jnp.ndarray, Any], jnp.ndarray], tau_final: float, y_0: jnp.ndarray, args, tau_0: float = 0.0, num_substeps: int = 50, solver_name: str = 'Dopri8', rtol: float = 0.001, atol: float = 1e-06, extra_kwargs=None)

Solve an initial-value ODE problem using a Diffrax adaptive solver.

Parameters:

Name Type Description Default
f Callable[[ndarray, ndarray, Any], ndarray]

ODE right-hand side; f(t, y, *args).

required
tau_final float

Final integration time.

required
y_0 ndarray

Initial state at tau_0.

required
args tuple

Extra arguments to pass to f in the solver term.

required
tau_0 float

Initial time. Defaults to 0.0.

0.0
num_substeps int

Number of save points between tau_0 and tau_final. Defaults to 50.

50
solver_name str

Key into SOLVER_MAP for the Diffrax solver class. Defaults to "Dopri8".

'Dopri8'
rtol float

Relative tolerance for adaptive stepping. Defaults to 1e-3.

0.001
atol float

Absolute tolerance for adaptive stepping. Defaults to 1e-6.

1e-06
extra_kwargs dict

Additional keyword arguments forwarded to diffeqsolve.

None

Returns:

Type Description

jnp.ndarray: Solution states at the requested save points, shape (num_substeps, state_dim).

Raises:

Type Description
ValueError

If solver_name is not in SOLVER_MAP.

openscvx.integrators.solve_ivp_diffrax_prop(f: Callable[[jnp.ndarray, jnp.ndarray, Any], jnp.ndarray], tau_final: float, y_0: jnp.ndarray, args, tau_0: float = 0.0, num_substeps: int = 50, solver_name: str = 'Dopri8', rtol: float = 0.001, atol: float = 1e-06, extra_kwargs=None, save_time: jnp.ndarray = None, mask: jnp.ndarray = None)

Solve an initial-value ODE problem using a Diffrax adaptive solver. This function is specifically designed for use in the context of trajectory optimization and handles the nonlinear single-shot propagation of state variables in undilated time.

Parameters:

Name Type Description Default
f Callable[[ndarray, ndarray, Any], ndarray]

ODE right-hand side; signature f(t, y, *args) -> dy/dt.

required
tau_final float

Final integration time.

required
y_0 ndarray

Initial state at tau_0.

required
args tuple

Extra arguments to pass to f in the solver term.

required
tau_0 float

Initial time. Defaults to 0.0.

0.0
num_substeps int

Number of save points between tau_0 and tau_final. Defaults to 50.

50
solver_name str

Key into SOLVER_MAP for the Diffrax solver class. Defaults to "Dopri8".

'Dopri8'
rtol float

Relative tolerance for adaptive stepping. Defaults to 1e-3.

0.001
atol float

Absolute tolerance for adaptive stepping. Defaults to 1e-6.

1e-06
extra_kwargs dict

Additional keyword arguments forwarded to diffeqsolve.

None
save_time ndarray

Time points at which to evaluate the solution. Must be provided for export compatibility.

None
mask ndarray

Boolean mask for the save_time points.

None

Returns:

Type Description

jnp.ndarray: Solution states at the requested save points, shape (num_substeps, state_dim).

Raises: ValueError: If solver_name is not in SOLVER_MAP or if save_time is not provided.

Problem

openscvx.problem.Problem.__init__(dynamics: dict, constraints: List[Union[Constraint, CTCS]], states: List[State], controls: List[Control], N: int, time: Time, dynamics_prop: Optional[dict] = None, states_prop: Optional[List[State]] = None, licq_min=0.0, licq_max=0.0001, time_dilation_factor_min=0.3, time_dilation_factor_max=3.0)

The primary class in charge of compiling and exporting the solvers

Parameters:

Name Type Description Default
dynamics dict

Dictionary mapping state names to their dynamics expressions. Each key should be a state name, and each value should be an Expr representing the derivative of that state.

required
constraints List[Union[CTCSConstraint, NodalConstraint]]

List of constraints decorated with @ctcs or @nodal

required
states List[State]

List of State objects representing the state variables. May optionally include a State named "time" (see time parameter below).

required
controls List[Control]

List of Control objects representing the control variables

required
N int

Number of segments in the trajectory

required
time Time

Time configuration object with initial, final, min, max. Required. If including a "time" state in states, the Time object will be ignored and time properties should be set on the time State object instead.

required
dynamics_prop dict

Dictionary mapping EXTRA state names to their dynamics expressions for propagation. Only specify additional states beyond optimization states (e.g., {"distance": speed}). Do NOT duplicate optimization state dynamics here.

None
states_prop List[State]

List of EXTRA State objects for propagation only. Only specify additional states beyond optimization states. Used with dynamics_prop.

None
licq_min

Minimum LICQ constraint value

0.0
licq_max

Maximum LICQ constraint value

0.0001
time_dilation_factor_min

Minimum time dilation factor

0.3
time_dilation_factor_max

Maximum time dilation factor

3.0

Returns:

Type Description

None

Note

There are two approaches for handling time: 1. Auto-create (simple): Don't include "time" in states, provide Time object 2. User-provided (for time-dependent constraints): Include "time" State in states and in dynamics dict, don't provide Time object

ScpConfig

openscvx.config.ScpConfig.__init__(n: Optional[int] = None, k_max: int = 200, w_tr: float = 1.0, lam_vc: float = 1.0, ep_tr: float = 0.0001, ep_vb: float = 0.0001, ep_vc: float = 1e-08, lam_cost: float = 0.0, lam_vb: float = 0.0, uniform_time_grid: bool = False, cost_drop: int = -1, cost_relax: float = 1.0, w_tr_adapt: float = 1.0, w_tr_max: Optional[float] = None, w_tr_max_scaling_factor: Optional[float] = None)

Configuration class for Sequential Convex Programming (SCP).

This class defines the parameters used to configure the SCP solver. You will very likely need to modify the weights for your problem. Please refer to my guide here for more information.

Attributes:

Name Type Description
n int

The number of discretization nodes. Defaults to None.

k_max int

The maximum number of SCP iterations. Defaults to 200.

w_tr float

The trust region weight. Defaults to 1.0.

lam_vc float

The penalty weight for virtual control. Defaults to 1.0.

ep_tr float

The trust region convergence tolerance. Defaults to 1e-4.

ep_vb float

The boundary constraint convergence tolerance. Defaults to 1e-4.

ep_vc float

The virtual constraint convergence tolerance. Defaults to 1e-8.

lam_cost float

The weight for original cost. Defaults to 0.0.

lam_vb float

The weight for virtual buffer. This is only used if there are nonconvex nodal constraints present. Defaults to 0.0.

uniform_time_grid bool

Whether to use a uniform time grid. Defaults to False.

cost_drop int

The number of iterations to allow for cost stagnation before termination. Defaults to -1 (disabled).

cost_relax float

The relaxation factor for cost reduction. Defaults to 1.0.

w_tr_adapt float

The adaptation factor for the trust region weight. Defaults to 1.0.

w_tr_max float

The maximum allowable trust region weight. Defaults to None.

w_tr_max_scaling_factor float

The scaling factor for the maximum trust region weight. Defaults to None.

DiscretizationConfig

openscvx.config.DiscretizationConfig.__init__(dis_type: str = 'FOH', custom_integrator: bool = False, solver: str = 'Tsit5', args: Optional[dict] = None, atol: float = 0.001, rtol: float = 1e-06)

Configuration class for discretization settings.

This class defines the parameters required for discretizing system dynamics.

Main arguments: These are the arguments most commonly used day-to-day.

Parameters:

Name Type Description Default
dis_type str

The type of discretization to use (e.g., "FOH" for First-Order Hold). Defaults to "FOH".

'FOH'
custom_integrator bool

This enables our custom fixed-step RK45 algorithm. This tends to be faster than Diffrax but unless you're going for speed, it's recommended to stick with Diffrax for robustness and other solver options. Defaults to False.

False
solver str

Not used if custom_integrator is enabled. Any choice of solver in Diffrax is valid, please refer here, How to Choose a Solver. Defaults to "Tsit5".

'Tsit5'

Other arguments: These arguments are less frequently used, and for most purposes you shouldn't need to understand these.

Parameters:

Name Type Description Default
args Dict

Additional arguments to pass to the solver which can be found here. Defaults to an empty dictionary.

None
atol float

Absolute tolerance for the solver. Defaults to 1e-3.

0.001
rtol float

Relative tolerance for the solver. Defaults to 1e-6.

1e-06

PropagationConfig

openscvx.config.PropagationConfig.__init__(inter_sample: int = 30, dt: float = 0.01, solver: str = 'Dopri8', max_tau_len: int = 1000, args: Optional[dict] = None, atol: float = 0.001, rtol: float = 1e-06)

Configuration class for propagation settings.

This class defines the parameters required for propagating the nonlinear system dynamics using the optimal control sequence.

Main arguments: These are the arguments most commonly used day-to-day.

Other arguments: The solver should likely not be changed as it is a high accuracy 8th-order Runge-Kutta method.

Parameters:

Name Type Description Default
inter_sample int

How dense the propagation within multishot discretization should be. Defaults to 30.

30
dt float

The time step for propagation. Defaults to 0.1.

0.01
solver str

The numerical solver to use for propagation (e.g., "Dopri8"). Defaults to "Dopri8".

'Dopri8'
max_tau_len int

The maximum length of the time vector for propagation. Defaults to 1000.

1000
args Dict

Additional arguments to pass to the solver. Defaults to an empty dictionary.

None
atol float

Absolute tolerance for the solver. Defaults to 1e-3.

0.001
rtol float

Relative tolerance for the solver. Defaults to 1e-6.

1e-06

SimConfig

openscvx.config.SimConfig.__init__(x: UnifiedState, x_prop: UnifiedState, u: UnifiedControl, total_time: float, save_compiled: bool = False, ctcs_node_intervals: Optional[list] = None, n_states: Optional[int] = None, n_states_prop: Optional[int] = None, n_controls: Optional[int] = None)

Configuration class for simulation settings.

This class defines the parameters required for simulating a trajectory optimization problem.

Main arguments: These are the arguments most commonly used day-to-day.

Parameters:

Name Type Description Default
x State

State object, must have .min and .max attributes for bounds.

required
x_prop State

Propagation state object, must have .min and .max attributes for bounds.

required
u Control

Control object, must have .min and .max attributes for bounds.

required
total_time float

The total simulation time.

required
idx_x_true slice

Slice for true state indices.

required
idx_x_true_prop slice

Slice for true propagation state indices.

required
idx_u_true slice

Slice for true control indices.

required
idx_t slice

Slice for time index.

required
idx_y slice

Slice for constraint violation indices.

required
idx_y_prop slice

Slice for propagation constraint violation indices.

required
idx_s slice

Slice for time dilation index.

required
save_compiled bool

If True, save and reuse compiled solver functions. Defaults to False.

False
ctcs_node_intervals list

Node intervals for CTCS constraints.

None
n_states int

The number of state variables. Defaults to None (inferred from x.max).

None
n_states_prop int

The number of propagation state variables. Defaults to None (inferred from x_prop.max).

None
n_controls int

The number of control variables. Defaults to None (inferred from u.max).

None
Note

You can specify custom scaling for specific states/controls using the scaling_min and scaling_max attributes on State, Control, and Time objects. If not set, the default min/max bounds will be used for scaling.

ConvexSolverConfig

openscvx.config.ConvexSolverConfig.__init__(solver: str = 'QOCO', solver_args: Optional[dict] = None, cvxpygen: bool = False, cvxpygen_override: bool = False)

Configuration class for convex solver settings.

This class defines the parameters required for configuring a convex solver.

These are the arguments most commonly used day-to-day. Generally I have found QOCO to be the most performant of the CVXPY solvers for these types of problems (I do have a bias as the author is from my group) and can handle up to SOCP's. CLARABEL is also a great option with feasibility checking and can handle a few more problem types. CVXPYGen is also great if your problem isn't too large. I have found qocogen to be the most performant of the CVXPYGen solvers.

Parameters:

Name Type Description Default
solver str

The name of the CVXPY solver to use. A list of options can be found here. Defaults to "QOCO".

'QOCO'
solver_args dict

Ensure you are using the correct arguments for your solver as they are not all common. Additional arguments to configure the solver, such as tolerances. Defaults to {"abstol": 1e-6, "reltol": 1e-9}.

None
cvxpygen bool

Whether to enable CVXPY code generation for the solver. Defaults to False.

False

DevConfig

openscvx.config.DevConfig.__init__(profiling: bool = False, debug: bool = False, printing: bool = True)

Configuration class for development settings.

This class defines the parameters used for development and debugging purposes.

Main arguments: These are the arguments most commonly used day-to-day.

Parameters:

Name Type Description Default
profiling bool

Whether to enable profiling for performance analysis. Defaults to False.

False
debug bool

Disables all precompilation so you can place breakpoints and inspect values. Defaults to False.

False
printing bool

Whether to enable printing during development. Defaults to True.

True