Skip to content

tesseract_robotics.trajopt_sqp

Sequential Quadratic Programming (SQP) solver for trajectory optimization. See the Low-Level SQP guide for the user-guide walkthrough.

The QP problem

TrajOptQPProblem(nodes_variables) is the problem the solver takes: the one tesseract_planning's TrajOpt-Ifopt planner and its online_planning_example.cpp build. Constraint and cost sets go straight in, and setup() runs after the last one:

Python
from tesseract_robotics import trajopt_ifopt as ti
from tesseract_robotics import trajopt_sqp as tsqp

nodes_variables = ti.createNodesVariables("trajectory", joint_names, states, bounds)
vars_list = [node.getVar("joints") for node in nodes_variables.getNodes()]
joint_constraint = ti.JointPosConstraint(states[0], vars_list[0], np.ones(len(joint_names)), "Joints")
collision_constraint = ti.DiscreteCollisionConstraint(evaluator, vars_list[1])
vel_cost = ti.JointVelConstraint(np.zeros(len(joint_names)), vars_list, np.ones(1), "Velocity")

problem = tsqp.TrajOptQPProblem(nodes_variables)
problem.addConstraintSet(joint_constraint)                  # joint / Cartesian constraints
problem.addConstraintSet(collision_constraint)              # collision constraints
problem.addCostSet(vel_cost, tsqp.CostPenaltyType.SQUARED)  # any penalty type
problem.setup()                                             # must call before solving

Every row of a cost or constraint set must be an equality or bounded on one side, with any penalty type; addCostSet and addConstraintSet raise on a two-sided range row. (trajopt 0.35.0 required equality rows for squared and absolute costs and one-sided rows for hinge costs.) Each set is linked to the variables when it is added, and dynamic sets (isDynamic()) are accepted. The exact merit weights each cost row by getCoefficients(), as the convex model does, and counts every cost term once; it charges each constraint set its violation weighted the same way (ConstraintViolations.weighted). So the trust-region ratio compares like with like for every penalty type. The problem keeps one merit coefficient, one violation and one name per constraint set, not per row, and counts cost sets the same way.

After convexify() the problem exposes the QP it built: minimise x'Hx + g'x over getNumQPVars() variables (the NLP variables, then the slacks) subject to lower ≤ A x ≤ upper over getNumQPConstraints() rows. getHessian() and getConstraintMatrix() return scipy.sparse copies; getGradient(), getBoundsLower(), getBoundsUpper() and getConstraintMeritCoeff() vectors.

problem.setVariables(x) sets the NLP variables and then updates every component, so a dynamic set recounts its rows; NodesVariables.setVariables only writes the values. It raises VariablesSizeError (a ValueError) unless len(x) == getNumNLPVars().

evaluateConvexCosts, evaluateTotalConvexCost and evaluateConvexConstraintViolations take a point of the QP the last convexify() built: getNumQPVars() entries, the NLP variables followed by the slacks. They raise QPSolutionSizeError for any other size and NotConvexifiedError before the first convexify(), both ValueErrors. trajopt reads only the NLP block, so a shorter vector would be read past its end, and before convexify() there is no model to read.

An ABSOLUTE or HINGE cost is modelled on its linearized rows, without the slacks: the model charges each row its coefficient times the row's linearized violation, and the exact cost charges the same coefficient times the exact violation. A violation larger than the trust box is then reduced step by step, as a squared one is. #149's development builds on trajopt 0.35.0 read such a cost as 0 at every QP solution and dropped its coefficient from the exact cost (#151); trajopt#592 fixed both before any wheel shipped TrajOptQPProblem.

IfoptQPProblem and IfoptProblem are no longer bound

IfoptQPProblem(IfoptProblem(nodes_variables)), the two-layer form of 0.34, is gone; trajopt is removing IfoptQPProblem (trajopt#595). It is not a rename: see Breaking API changes for the migration and the five ways the problems differ.

Solver

TrustRegionSQPSolver

Main SQP solver with trust-region globalization.

Python
qp_solver = tsqp.OSQPEigenSolver()
solver = tsqp.TrustRegionSQPSolver(qp_solver)
solver.verbose = False
solver.params.initial_trust_box_size = 0.01

# Solve
solver.solve(problem)
results = solver.getResults()

# Or single incremental step (for online/replanning)
solver.init(problem)
solver.stepSQPSolver()
solver.setBoxSize(0.01)          # trust region resets don't belong in the solve loop

Cost/constraint evaluation uses getTotalExactCost() / getExactCosts() on the QP problem (no arguments) — the 0.33 evaluate* methods are gone.

OSQPEigenSolver

QPSolver implementation backed by OSQP. Used by TrustRegionSQPSolver, or driven by hand through the QPSolver interface: init(num_vars, num_cnts), then updateHessianMatrix(H), updateGradient(g), updateLinearConstraintsMatrix(A) and updateBounds(lower, upper), then solve() and getSolution(). The objective is x'Hx + g'x (the solver doubles H for OSQP's ½ x'Px). Each update raises QPSizeError (a ValueError) unless its size matches init(). Before the first solve() only updateBounds stores bounds; updateLowerBound and updateUpperBound return False until OSQP is set up.

Python
import scipy.sparse

qp_solver = tsqp.OSQPEigenSolver()
qp_solver.init(2, 2)
qp_solver.updateHessianMatrix(scipy.sparse.identity(2, format="csr"))
qp_solver.updateGradient([-2.0, -4.0])
qp_solver.updateLinearConstraintsMatrix(scipy.sparse.identity(2, format="csr"))
qp_solver.updateBounds([-10.0, -10.0], [0.5, 10.0])
qp_solver.solve()
qp_solver.getSolution()  # [0.5, 2.0]

setWarmStart has two forms: setWarmStart(True) / setWarmStart(False) sets the OSQP option, and setWarmStart(problem) seeds the next solve from a convexified problem's variables and slacks (a no-op while the option is off; the solver must be init()-ed at the problem's QP size, else QPSizeError).

Parameters and Results

  • SQPParameters — configure iteration limits, trust region, penalty coefficients. Mutated via solver.params before solve().
  • SQPResults — the solver's iteration state. Notable attributes: best_var_vals, best_exact_merit, best_costs, best_constraint_violations, cost_names, constraint_names, plus the various iteration counters.
  • Solver status: solver.getStatus() returns the SQPStatus enum; toString(status) gives trajopt's text for it ("SQP_CONVERGED").
  • SQPParameters compares by value and is unhashable.

Enums

Python
from tesseract_robotics.trajopt_sqp import (
    SQPStatus, QPSolverStatus, CostPenaltyType,
)

SQPStatus.RUNNING
SQPStatus.CONVERGED
QPSolverStatus.UNINITIALIZED
CostPenaltyType.SQUARED

Python names are unchanged from 0.33 — see changes. The 0.33 ConstraintType enum was removed; if you referenced it, drop the usage.

Callbacks

Override execute(problem, results) — return False to stop the solver.

Python
class MyCallback(tsqp.SQPCallback):
    def execute(self, problem, results):
        print(f"iter {results.overall_iteration}: best_merit={results.best_exact_merit}")
        return True

solver.registerCallback(MyCallback())

Reference

trajopt_sqp Python bindings - SQP solver for trajectory optimization

QPProblemExpiredError

Bases: RuntimeError

A QPProblemView used after the SQPCallback call it was passed to returned.

VariablesSizeError

Bases: ValueError

QPProblem.setVariables with a vector that is not getNumNLPVars() long.

QPSizeError

Bases: ValueError

QPSolver input whose size is not the (num_vars, num_cnts) of its init().

QPSolutionSizeError

Bases: ValueError

A convex evaluator's var_vals that is not getNumQPVars() long.

NotConvexifiedError

Bases: ValueError

A convex evaluator called before the problem's first convexify().

CostPenaltyType

Bases: Enum

Penalty type for cost terms

SQUARED class-attribute instance-attribute

Python
SQUARED = 0

Squared penalty (L2)

ABSOLUTE class-attribute instance-attribute

Python
ABSOLUTE = 1

Absolute penalty (L1)

HINGE class-attribute instance-attribute

Python
HINGE = 2

Hinge penalty

SQPStatus

Bases: Enum

Status codes for SQP optimization

RUNNING class-attribute instance-attribute

Python
RUNNING = 0

Optimization is currently running

CONVERGED class-attribute instance-attribute

Python
CONVERGED = 1

Optimization converged

ITERATION_LIMIT class-attribute instance-attribute

Python
ITERATION_LIMIT = 2

Reached iteration limit

PENALTY_ITERATION_LIMIT class-attribute instance-attribute

Python
PENALTY_ITERATION_LIMIT = 3

Reached penalty iteration limit

TIME_LIMIT class-attribute instance-attribute

Python
TIME_LIMIT = 4

Reached time limit

QP_SOLVE_FAILED class-attribute instance-attribute

Python
QP_SOLVE_FAILED = 5

QP solver failed

STOPPED_BY_CALLBACK class-attribute instance-attribute

Python
STOPPED_BY_CALLBACK = 6

Stopped by callback

QPSolverStatus

Bases: Enum

Status of QP solver

UNINITIALIZED class-attribute instance-attribute

Python
UNINITIALIZED = 0

Solver not initialized

INITIALIZED class-attribute instance-attribute

Python
INITIALIZED = 1

Solver initialized

FAILED class-attribute instance-attribute

Python
FAILED = 2

QP solver failed

SQPParameters

Parameters controlling SQP optimization

__hash__ class-attribute instance-attribute

Python
__hash__: None = None

improve_ratio_threshold property writable

Python
improve_ratio_threshold: float

Minimum ratio exact_improve/approx_improve to accept step (default: 0.25)

min_trust_box_size property writable

Python
min_trust_box_size: float

NLP converges if trust region smaller than this (default: 1e-4)

min_approx_improve property writable

Python
min_approx_improve: float

NLP converges if approx_merit_improve smaller than this (default: 1e-4)

min_approx_improve_frac property writable

Python
min_approx_improve_frac: float

NLP converges if approx_merit_improve/best_exact_merit < this

max_iter property writable

Python
max_iter: int

Max convexifications per penalty iteration; rejected trust-region steps do not count (default: 50)

trust_shrink_ratio property writable

Python
trust_shrink_ratio: float

Trust region scale factor when shrinking (default: 0.1)

trust_expand_ratio property writable

Python
trust_expand_ratio: float

Trust region scale factor when expanding (default: 1.5)

cnt_tolerance property writable

Python
cnt_tolerance: float

Constraint violation tolerance (default: 1e-4)

max_merit_coeff_increases property writable

Python
max_merit_coeff_increases: float

Max times constraints will be inflated (default: 5)

max_qp_solver_failures property writable

Python
max_qp_solver_failures: int

Max QP solver failures before abort (default: 3)

merit_coeff_increase_ratio property writable

Python
merit_coeff_increase_ratio: float

Scale factor for constraint inflation (default: 10)

max_time property writable

Python
max_time: float

Max optimization time in seconds

initial_merit_error_coeff property writable

Python
initial_merit_error_coeff: float

Initial constraint scaling coefficient (default: 10)

inflate_constraints_individually property writable

Python
inflate_constraints_individually: bool

If true, only violated constraints are inflated (default: true)

sum_constraint_set_violations property writable

Python
sum_constraint_set_violations: bool

If true, cnt_tolerance is tested against a set's summed row violations; if false, against its largest row. Applied by TrustRegionSQPSolver.init() (default: true)

initial_trust_box_size property writable

Python
initial_trust_box_size: float

Initial trust region size (default: 0.1)

log_results property writable

Python
log_results: bool

Enable logging (unused)

log_dir property writable

Python
log_dir: str

Log directory (unused)

__init__

Python
__init__() -> None

__eq__

Python
__eq__(other: object) -> bool

__ne__

Python
__ne__(other: object) -> bool

ConstraintViolations

Per merit unit constraint violations (non-negative; 0 = satisfied)

raw property writable

Python
raw: Annotated[NDArray[float64], dict(shape=(None,), order=C)]

Unweighted violation per merit unit; its sum is compared against cnt_tolerance

weighted property writable

Python
weighted: Annotated[NDArray[float64], dict(shape=(None,), order=C)]

Violation times row weight; the merit charges weighted.dot(merit_error_coeffs)

__init__

Python
__init__() -> None

SQPResults

Results and state from SQP optimization

best_exact_merit property writable

Python
best_exact_merit: float

Lowest cost ever achieved

new_exact_merit property writable

Python
new_exact_merit: float

Cost achieved this iteration

best_approx_merit property writable

Python
best_approx_merit: float

Lowest convexified cost ever achieved

new_approx_merit property writable

Python
new_approx_merit: float

Convexified cost this iteration

best_var_vals property writable

Python
best_var_vals: Annotated[NDArray[float64], dict(shape=(None,), order=C)]

Variable values for best_exact_merit

new_var_vals property writable

Python
new_var_vals: Annotated[NDArray[float64], dict(shape=(None,), order=C)]

Variable values this iteration

approx_merit_improve property writable

Python
approx_merit_improve: float

Convexified cost improvement this iteration

exact_merit_improve property writable

Python
exact_merit_improve: float

Exact cost improvement this iteration

merit_improve_ratio property writable

Python
merit_improve_ratio: float

Cost improvement as ratio of total cost

box_size property writable

Python
box_size: Annotated[NDArray[float64], dict(shape=(None,), order=C)]

Trust region box size (var_vals ± box_size)

merit_error_coeffs property writable

Python
merit_error_coeffs: Annotated[NDArray[float64], dict(shape=(None,), order=C)]

Coefficients weighting constraint violations

best_constraint_violations property writable

Python
best_constraint_violations: ConstraintViolations

Constraint violations for best solution (positive = violation)

new_constraint_violations property writable

Python
new_constraint_violations: ConstraintViolations

Constraint violations this iteration

best_approx_constraint_violations property writable

Python
best_approx_constraint_violations: ConstraintViolations

Convexified constraint violations for best solution

new_approx_constraint_violations property writable

Python
new_approx_constraint_violations: ConstraintViolations

Convexified constraint violations this iteration

best_costs property writable

Python
best_costs: Annotated[NDArray[float64], dict(shape=(None,), order=C)]

Cost values for best solution

new_costs property writable

Python
new_costs: Annotated[NDArray[float64], dict(shape=(None,), order=C)]

Cost values this iteration

best_approx_costs property writable

Python
best_approx_costs: Annotated[NDArray[float64], dict(shape=(None,), order=C)]

Convexified costs for best solution

new_approx_costs property writable

Python
new_approx_costs: Annotated[NDArray[float64], dict(shape=(None,), order=C)]

Convexified costs this iteration

constraint_names property writable

Python
constraint_names: list[str]

Names of constraint sets

cost_names property writable

Python
cost_names: list[str]

Names of cost terms

penalty_iteration property writable

Python
penalty_iteration: int

convexify_iteration property writable

Python
convexify_iteration: int

trust_region_iteration property writable

Python
trust_region_iteration: int

overall_iteration property writable

Python
overall_iteration: int

print

Python
print() -> None

Print results to console

QPSolver

Abstract base class for QP solvers

verbosity property writable

Python
verbosity: int

Verbosity level (0 = silent)

init

Python
init(num_vars: int, num_cnts: int) -> bool

Initialize the QP solver

clear

Python
clear() -> bool

Clear the QP solver

solve

Python
solve() -> bool

Solve the QP

getSolution

Python
getSolution() -> Annotated[NDArray[numpy.float64], dict(shape=(None,), order=C)]

Get the solution vector

getSolverStatus

Python
getSolverStatus() -> QPSolverStatus

Get solver status

updateHessianMatrix

Python
updateHessianMatrix(hessian: csr_matrix) -> bool

Set the Hessian H (sparse, num_vars square) of the objective x'Hx + g'x

updateGradient

Python
updateGradient(gradient: Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]) -> bool

Set the gradient g (num_vars)

updateLowerBound

Python
updateLowerBound(lower_bound: Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]) -> bool

Set the constraint lower bounds (num_cnts)

updateUpperBound

Python
updateUpperBound(upper_bound: Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]) -> bool

Set the constraint upper bounds (num_cnts)

updateBounds

Python
updateBounds(lower_bound: Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float], upper_bound: Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]) -> bool

Set both constraint bounds (num_cnts each)

updateLinearConstraintsMatrix

Python
updateLinearConstraintsMatrix(linear_constraints_matrix: csr_matrix) -> bool

Set the constraint matrix A (sparse, num_cnts x num_vars)

setWarmStart

Python
setWarmStart(qp_problem: QPProblem) -> bool

Seed the next solve from the problem's variables (and its slacks); a no-op while the solver's warm-start option is off

OSQPEigenSolver

Bases: QPSolver

OSQP-based QP solver

__init__

Python
__init__() -> None

init

Python
init(num_vars: int, num_cnts: int) -> bool

clear

Python
clear() -> bool

solve

Python
solve() -> bool

getSolution

Python
getSolution() -> Annotated[NDArray[numpy.float64], dict(shape=(None,), order=C)]

getSolverStatus

Python
getSolverStatus() -> QPSolverStatus

setPolish

Python
setPolish(polish: bool) -> None

Polish the ADMM solution (OSQP polishing).

getPolish

Python
getPolish() -> bool

getWarmStart

Python
getWarmStart() -> bool

setAdaptiveRho

Python
setAdaptiveRho(adaptive_rho: bool) -> None

Adapt the ADMM step size rho (OSQP adaptive_rho).

getAdaptiveRho

Python
getAdaptiveRho() -> bool

setAdaptiveRhoInterval

Python
setAdaptiveRhoInterval(interval: int) -> None

Adapt rho every interval iterations. OSQP's 0 adapts on wall-clock timing, which makes solutions differ run to run; a fixed interval (e.g. 25) makes them reproducible.

getAdaptiveRhoInterval

Python
getAdaptiveRhoInterval() -> int

setMaxIteration

Python
setMaxIteration(max_iter: int) -> None

Maximum ADMM iterations per QP solve.

getMaxIteration

Python
getMaxIteration() -> int

setAbsoluteTolerance

Python
setAbsoluteTolerance(abs_tol: float) -> None

Absolute convergence tolerance (OSQP eps_abs).

getAbsoluteTolerance

Python
getAbsoluteTolerance() -> float

setRelativeTolerance

Python
setRelativeTolerance(rel_tol: float) -> None

Relative convergence tolerance (OSQP eps_rel).

getRelativeTolerance

Python
getRelativeTolerance() -> float

setVerbosity

Python
setVerbosity(verbose: bool) -> None

Write OSQP's progress to the console.

getVerbosity

Python
getVerbosity() -> bool

QPProblem

Abstract base class for QP problems (convexified NLP)

addConstraintSet

Python
addConstraintSet(constraint_set: ConstraintSet) -> None

Add a set of constraints

addCostSet

Python
addCostSet(constraint_set: ConstraintSet, penalty_type: CostPenaltyType) -> None

Add a cost term with specified penalty type

setup

Python
setup() -> None

Setup the QP problem (call after adding all sets)

getVariableValues

Python
getVariableValues() -> Annotated[NDArray[numpy.float64], dict(shape=(None,), order=C)]

Get current optimization variable values

setVariables

Python
setVariables(x: Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]) -> None

Set the NLP variables and update every component (a TrajOptQPProblem also recounts its dynamic rows). Raises VariablesSizeError unless len(x) == getNumNLPVars().

convexify

Python
convexify() -> None

Run the full convexification routine

evaluateTotalConvexCost

Python
evaluateTotalConvexCost(var_vals: Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]) -> float

Evaluate the convexified total cost at var_vals.

Parameters:

Name Type Description Default
var_vals Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]

A point of the QP built by the last convexify(): getNumQPVars() entries, the NLP variables followed by the slack variables, as in a QP solution. To evaluate at an NLP point, append zeros for the slacks.

required

Returns:

Type Description
float

The sum of evaluateConvexCosts(var_vals).

Raises:

Type Description
QPSolutionSizeError

if var_vals does not have getNumQPVars() entries.

NotConvexifiedError

before the first convexify().

evaluateConvexCosts

Python
evaluateConvexCosts(var_vals: Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]) -> Annotated[NDArray[numpy.float64], dict(shape=(None,), order=C)]

Evaluate each cost term of the convexified problem at var_vals.

Parameters:

Name Type Description Default
var_vals Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]

A point of the QP built by the last convexify(): getNumQPVars() entries, the NLP variables followed by the slack variables, as in a QP solution. To evaluate at an NLP point, append zeros for the slacks.

required

Returns:

Type Description
Annotated[NDArray[float64], dict(shape=(None,), order=C)]

One convexified cost per cost term, in getNLPCostNames() order.

Raises:

Type Description
QPSolutionSizeError

if var_vals does not have getNumQPVars() entries.

NotConvexifiedError

before the first convexify().

getTotalExactCost

Python
getTotalExactCost() -> float

Get exact (non-convexified) total cost

getExactCosts

Python
getExactCosts() -> Annotated[NDArray[numpy.float64], dict(shape=(None,), order=C)]

Get current exact costs

evaluateConvexConstraintViolations

Python
evaluateConvexConstraintViolations(var_vals: Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]) -> ConstraintViolations

Evaluate the convexified constraint violations at var_vals.

Parameters:

Name Type Description Default
var_vals Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]

A point of the QP built by the last convexify(): getNumQPVars() entries, the NLP variables followed by the slack variables, as in a QP solution. To evaluate at an NLP point, append zeros for the slacks.

required

Returns:

Type Description
ConstraintViolations

One violation per constraint set, in getNLPConstraintNames() order; 0 where

ConstraintViolations

satisfied.

Raises:

Type Description
QPSolutionSizeError

if var_vals does not have getNumQPVars() entries.

NotConvexifiedError

before the first convexify().

getExactConstraintViolations

Python
getExactConstraintViolations() -> ConstraintViolations

Get current exact constraint violations

setSumConstraintSetViolations

Python
setSumConstraintSetViolations(sum: bool) -> None

Reduce a merit unit's row violations to their sum (True) or to the largest (False) in ConstraintViolations.raw. TrustRegionSQPSolver.init() overwrites this with SQPParameters.sum_constraint_set_violations.

scaleBoxSize

Python
scaleBoxSize(scale: float) -> None

Uniformly scale the trust region box size

setBoxSize

Python
setBoxSize(box_size: Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]) -> None

Set trust region box size

setConstraintMeritCoeff

Python
setConstraintMeritCoeff(merit_coeff: Annotated[NDArray[float64], dict(shape=(None,), writable=False)] | Sequence[float]) -> None

Set constraint merit coefficients

getBoxSize

Python
getBoxSize() -> Annotated[NDArray[numpy.float64], dict(shape=(None,), order=C)]

Get trust region box size

getConstraintMeritCoeff

Python
getConstraintMeritCoeff() -> Annotated[NDArray[numpy.float64], dict(shape=(None,), order=C)]

Get the constraint merit coefficients, one per constraint set

getHessian

Python
getHessian() -> scipy.sparse.csr_matrix

The QP Hessian (sparse, getNumQPVars() square), from the last convexify()

getGradient

Python
getGradient() -> Annotated[NDArray[numpy.float64], dict(shape=(None,), order=C)]

The QP gradient (getNumQPVars()), from the last convexify()

getConstraintMatrix

Python
getConstraintMatrix() -> scipy.sparse.csr_matrix

The QP constraint matrix (sparse, getNumQPConstraints() x getNumQPVars()), from the last convexify()

getBoundsLower

Python
getBoundsLower() -> Annotated[NDArray[numpy.float64], dict(shape=(None,), order=C)]

The QP constraint lower bounds (getNumQPConstraints()), from the last convexify()

getBoundsUpper

Python
getBoundsUpper() -> Annotated[NDArray[numpy.float64], dict(shape=(None,), order=C)]

The QP constraint upper bounds (getNumQPConstraints()), from the last convexify()

print

Python
print() -> None

Print problem to console

getNumNLPVars

Python
getNumNLPVars() -> int

Number of NLP variables

getNumNLPConstraints

Python
getNumNLPConstraints() -> int

Number of NLP constraints

getNumNLPCosts

Python
getNumNLPCosts() -> int

Number of NLP cost terms

getNumQPVars

Python
getNumQPVars() -> int

Number of QP variables (includes slack)

getNumQPConstraints

Python
getNumQPConstraints() -> int

Number of QP constraints

getNLPConstraintNames

Python
getNLPConstraintNames() -> list[str]

Get constraint names

getNLPCostNames

Python
getNLPCostNames() -> list[str]

Get cost names

TrajOptQPProblem

Bases: QPProblem

QP problem over trajopt_ifopt variables: the problem tesseract_planning's TrajOpt-Ifopt planner builds. Costs and constraints are added directly.

__init__

Python
__init__(variables: Variables) -> None

Construct over the optimization variables (e.g. createNodesVariables(...))

addConstraintSet

Python
addConstraintSet(constraint_set: ConstraintSet) -> None

addCostSet

Python
addCostSet(constraint_set: ConstraintSet, penalty_type: CostPenaltyType) -> None

setup

Python
setup() -> None

convexify

Python
convexify() -> None

print

Python
print() -> None

QPProblemView

Bases: QPProblem

The problem an SQPCallback receives from a solve whose problem has no Python object (one a planner built in C++). Valid only during that call; afterwards every method raises QPProblemExpiredError.

SQPCallback

Base class for SQP optimization callbacks

__init__

Python
__init__() -> None

execute

Python
execute(problem: QPProblem, sqp_results: SQPResults) -> bool

Called during SQP. Return false to stop optimization. problem is valid only during the call: a problem passed to solve() from Python arrives as that object; one a planner built in C++ arrives as a QPProblemView, which raises QPProblemExpiredError once the call has returned. sqp_results is a copy the callback may keep.

PIQPKKTSolver

Bases: Enum

PIQP's KKT system solver

dense_cholesky class-attribute instance-attribute

Python
dense_cholesky = 0

sparse_ldlt class-attribute instance-attribute

Python
sparse_ldlt = 1

sparse_ldlt_eq_cond class-attribute instance-attribute

Python
sparse_ldlt_eq_cond = 2

sparse_ldlt_ineq_cond class-attribute instance-attribute

Python
sparse_ldlt_ineq_cond = 3

sparse_ldlt_cond class-attribute instance-attribute

Python
sparse_ldlt_cond = 4

sparse_multistage class-attribute instance-attribute

Python
sparse_multistage = 5

PIQPSettings

PIQP solver settings (piqp::Settings)

rho_init property writable

Python
rho_init: float

Initial primal proximal penalty

delta_init property writable

Python
delta_init: float

Initial augmented Lagrangian penalty

eps_abs property writable

Python
eps_abs: float

Absolute tolerance

eps_rel property writable

Python
eps_rel: float

Relative tolerance

check_duality_gap property writable

Python
check_duality_gap: bool

Also stop on the duality gap

eps_duality_gap_abs property writable

Python
eps_duality_gap_abs: float

Absolute duality gap tolerance

eps_duality_gap_rel property writable

Python
eps_duality_gap_rel: float

Relative duality gap tolerance

infeasibility_threshold property writable

Python
infeasibility_threshold: float

Threshold for the infeasibility detection

reg_lower_limit property writable

Python
reg_lower_limit: float

Lower limit of the regularization

reg_finetune_lower_limit property writable

Python
reg_finetune_lower_limit: float

Fine-tune lower limit of the regularization

reg_finetune_primal_update_threshold property writable

Python
reg_finetune_primal_update_threshold: int

Primal updates before fine-tuning the regularization

reg_finetune_dual_update_threshold property writable

Python
reg_finetune_dual_update_threshold: int

Dual updates before fine-tuning the regularization

max_iter property writable

Python
max_iter: int

Maximum number of iterations

max_factor_retires property writable

Python
max_factor_retires: int

Maximum number of factorization retries

preconditioner_scale_cost property writable

Python
preconditioner_scale_cost: bool

Scale the cost in the preconditioner

preconditioner_reuse_on_update property writable

Python
preconditioner_reuse_on_update: bool

Reuse the preconditioner when the problem is updated

preconditioner_iter property writable

Python
preconditioner_iter: int

Preconditioner iterations

tau property writable

Python
tau: float

Maximum step size fraction to the boundary

kkt_solver property writable

Python
kkt_solver: PIQPKKTSolver

KKT system solver

iterative_refinement_always_enabled property writable

Python
iterative_refinement_always_enabled: bool

Always run iterative refinement

iterative_refinement_eps_abs property writable

Python
iterative_refinement_eps_abs: float

Iterative refinement absolute tolerance

iterative_refinement_eps_rel property writable

Python
iterative_refinement_eps_rel: float

Iterative refinement relative tolerance

iterative_refinement_max_iter property writable

Python
iterative_refinement_max_iter: int

Iterative refinement maximum iterations

iterative_refinement_min_improvement_rate property writable

Python
iterative_refinement_min_improvement_rate: float

Iterative refinement minimum improvement rate

iterative_refinement_static_regularization_eps property writable

Python
iterative_refinement_static_regularization_eps: float

Iterative refinement static regularization

iterative_refinement_static_regularization_rel property writable

Python
iterative_refinement_static_regularization_rel: float

Iterative refinement relative static regularization

verbose property writable

Python
verbose: bool

Print solver progress

compute_timings property writable

Python
compute_timings: bool

Measure the solver timings

__hash__ class-attribute instance-attribute

Python
__hash__: None = None

__init__

Python
__init__() -> None

PIQP's own defaults

__eq__

Python
__eq__(other: object) -> bool

__ne__

Python
__ne__(other: object) -> bool

PIQPSolver

Bases: QPSolver

PIQP-based (interior point) QP solver

settings property writable

Python
settings: PIQPSettings

PIQP settings, applied when the solver is next set up

__init__

Python
__init__() -> None

With trajopt's default PIQP settings

defaultSettings staticmethod

Python
defaultSettings() -> PIQPSettings

The PIQP settings trajopt uses by default

reusedSetup

Python
reusedSetup() -> bool

Whether the last solve reused the previous setup (only the vectors changed)

TrustRegionSQPSolver

Trust region SQP solver for trajectory optimization.

Key methods for incremental optimization

  • init(qp_prob): Initialize solver with problem
  • stepSQPSolver(): Run ONE SQP iteration (for real-time control)
  • getResults(): Get current optimization results
  • setBoxSize(): Control trust region size

verbose property writable

Python
verbose: bool

If true, print debug info to console

params property writable

Python
params: SQPParameters

SQP parameters (modify before calling init/solve)

qp_solver property writable

Python
qp_solver: QPSolver

The QP solver used internally

qp_problem property writable

Python
qp_problem: QPProblem

The current QP problem

__init__

Python
__init__(qp_solver: QPSolver) -> None

Construct with a QP solver (e.g., OSQPEigenSolver)

init

Python
init(qp_prob: QPProblem) -> bool

Initialize the solver with a QP problem for incremental solving

solve

Python
solve(qp_prob: QPProblem) -> None

Run complete SQP optimization

stepSQPSolver

Python
stepSQPSolver() -> bool

Run a SINGLE SQP convexification step.

Used for online planning, where the caller updates the problem between steps.

Returns True when no further step should follow at the current penalty: the step converged, the QP failure budget was spent, or a callback stopped the solve; getStatus() tells which. It does not mean the SQP solver has converged.

Example:

Python
solver.init(problem)
while solver.getStatus() == SQPStatus.RUNNING:
    solver.stepSQPSolver()
    # Check constraints, update environment, etc.

verifySQPSolverConvergence

Python
verifySQPSolverConvergence() -> bool

Check if SQP constraints are satisfied

adjustPenalty

Python
adjustPenalty() -> None

Increase penalty on constraints when SQP reports convergence but constraints violated

runTrustRegionLoop

Python
runTrustRegionLoop() -> None

Run trust region loop (adjusts box size)

solveQPProblem

Python
solveQPProblem() -> SQPStatus

Solve current QP problem, store results, call callbacks

setBoxSize

Python
setBoxSize(box_size: float) -> None

Set trust region box size (for online planning control)

callCallbacks

Python
callCallbacks() -> bool

Call all registered callbacks. Returns false if any callback returned false.

printStepInfo

Python
printStepInfo() -> None

Print info about current optimization state

registerCallback

Python
registerCallback(callback: SQPCallback) -> None

Register an optimization callback

getStatus

Python
getStatus() -> SQPStatus

Get current SQP status

getResults

Python
getResults() -> SQPResults

Get current SQP results

toString

Python
toString(status: SQPStatus) -> str

trajopt's text for a solver status (e.g. 'SQP_CONVERGED')

See also