cmvr-es/cmvr-es/common/math/qp_solver.h
lgv 37a62fb3e3 feat(arm): add collision-aware planning and refactor motion control
Integrate OMPL RRTConnect and quintic B-spline smoothing into moveP, reuse
the B-spline trajectory generator for moveJ, and remove the TOPPRA paths
and dependencies. Separate joint and Cartesian planners, smoothers, and
the standalone curve math library.

Move speedL execution into SpeedLExecutor, tighten velocity QP feasibility,
and add adaptive speed reduction, braking recovery, feedback-derived TCP
velocity, and grouped cyclic velocity submission. Improve MuJoCo control
cycle synchronization and camera streaming.

Centralize kinematics and collision geometry in RobotModel, expose box
obstacles through CollisionChecker, and extract SelfCollisionMonitor for
protective stops and recovery. Add cancellable moveP pre-approach and
configurable failure recovery to the touch workflow, with updated configs,
documentation, and regression coverage.

Validation: recorded -j8 build and 133 passing tests on 2026-10-08, including
headless MuJoCo checks for eight target poses and seven moveJ returns.
Static scene configuration removal passed 27 follow-up tests and six arm
configuration parses. Staged diff and shell syntax checks pass; no new
hardware tests were run for this commit.
2026-10-13 09:18:06 +08:00

436 lines
13 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// Created by lgv on 12/2/25.
//
#ifndef CMVR_MATH_QP_SOLVER_H
#define CMVR_MATH_QP_SOLVER_H
#pragma once
#include <exception>
#include <memory>
#include <optional>
#include <unordered_map>
#include "common/base/logging/logger.h"
#include <Eigen/Core>
#include <OsqpEigen/OsqpEigen.h>
namespace cmvr {
class QPSolverException : public std::exception {
public:
static constexpr unsigned int kStatusOffset = 100;
explicit QPSolverException(int error_code);
const char* what() const noexcept override;
int code() const noexcept;
static std::string GenerateMessage(int code);
private:
int error_code_;
std::string message_;
};
inline QPSolverException::QPSolverException(int error_code)
: error_code_(error_code)
, message_(GenerateMessage(error_code))
{
}
inline const char* QPSolverException::what() const noexcept {
return message_.c_str();
}
inline int QPSolverException::code() const noexcept {
return error_code_;
}
inline std::string QPSolverException::GenerateMessage(int code) {
static const std::unordered_map<int, std::string> error_messages = {
{OSQP_DATA_VALIDATION_ERROR, "Data validation error"},
{OSQP_SETTINGS_VALIDATION_ERROR, "Settings validation error"},
#ifdef OSQP_EIGEN_OSQP_IS_V1
{OSQP_ALGEBRA_LOAD_ERROR, "Linear system solver load error"},
#else
{OSQP_LINSYS_SOLVER_LOAD_ERROR, "Linear system solver load error"},
#endif
{OSQP_LINSYS_SOLVER_INIT_ERROR, "Linear system solver initialization error"},
{OSQP_NONCVX_ERROR, "Non-convex error"},
{OSQP_MEM_ALLOC_ERROR, "Memory allocation error"},
{OSQP_WORKSPACE_NOT_INIT_ERROR, "Workspace not initialized"},
{QPSolverException::kStatusOffset + OSQP_SOLVED, "Solved"},
{QPSolverException::kStatusOffset + OSQP_SOLVED_INACCURATE, "Solved inaccurate"},
{QPSolverException::kStatusOffset + OSQP_PRIMAL_INFEASIBLE, "Primal infeasible"},
{QPSolverException::kStatusOffset + OSQP_PRIMAL_INFEASIBLE_INACCURATE, "Primal infeasible inaccurate"},
{QPSolverException::kStatusOffset + OSQP_DUAL_INFEASIBLE, "Dual infeasible"},
{QPSolverException::kStatusOffset + OSQP_DUAL_INFEASIBLE_INACCURATE, "Dual infeasible inaccurate"},
{QPSolverException::kStatusOffset + OSQP_MAX_ITER_REACHED, "Maximum iterations reached"},
{QPSolverException::kStatusOffset + OSQP_TIME_LIMIT_REACHED, "Run time limit reached"},
{QPSolverException::kStatusOffset + OSQP_NON_CVX, "Problem non convex"},
{QPSolverException::kStatusOffset + OSQP_SIGINT, "Interrupted"},
{QPSolverException::kStatusOffset + OSQP_UNSOLVED, "Unsolved"},
{-1, "General solver error or matrix update failure"},
};
auto it = error_messages.find(code);
if (it != error_messages.end()) {
return it->second;
}
return "Unknown solver error (code: " + std::to_string(code) + ")";
}
class QPSolverImpl {
public:
QPSolverImpl() = default;
~QPSolverImpl() = default;
void SetupImpl(int n_var, int n_const, double time_limit = 2e-3,
double absolute_tolerance = 1e-3, double relative_tolerance = 1e-3,
bool polish = false);
void InitFunctionImpl();
void AddCostFunctionImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b);
void SetCostFunctionImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b);
void SetConstraintsFunctionImpl(const Eigen::MatrixXd &A,
const Eigen::VectorXd &lb,
const Eigen::VectorXd &ub);
void SetPrimalVariableImpl(const Eigen::VectorXd &pv);
void ResetIsFirstImpl();
Eigen::VectorXd SolveImpl();
Eigen::MatrixXd GetACostImpl() const;
Eigen::VectorXd GetBCostImpl() const;
Eigen::MatrixXd GetAConstImpl() const;
Eigen::VectorXd GetLowerBoundImpl() const;
Eigen::VectorXd GetUpperBoundImpl() const;
private:
OsqpEigen::Solver solver_;
int n_var_{0};
int n_const_{0};
int err_code_{0};
int is_first_{1};
int n_hessian_element_{0};
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> A_cost_;
Eigen::Matrix<double, Eigen::Dynamic, 1> b_cost_;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> A_const_;
Eigen::Matrix<double, Eigen::Dynamic, 1> lb_;
Eigen::Matrix<double, Eigen::Dynamic, 1> ub_;
Eigen::SparseMatrix<double> hessian_;
Eigen::Matrix<double, Eigen::Dynamic, 1> gradient_;
Eigen::SparseMatrix<double> linearMatrix_;
Eigen::Matrix<double, Eigen::Dynamic, 1> lowerBound_;
Eigen::Matrix<double, Eigen::Dynamic, 1> upperBound_;
Eigen::Matrix<double, Eigen::Dynamic, 1> primal_variable_for_warmstart_;
};
inline void QPSolverImpl::SetupImpl(int n_var, int n_const, double time_limit,
double absolute_tolerance, double relative_tolerance,
bool polish) {
n_var_ = n_var;
n_const_ = n_const;
solver_.settings()->setWarmStart(true);
solver_.settings()->setVerbosity(false);
solver_.settings()->setTimeLimit(time_limit);
solver_.settings()->setAbsoluteTolerance(absolute_tolerance);
solver_.settings()->setRelativeTolerance(relative_tolerance);
solver_.settings()->setPolish(polish);
solver_.data()->setNumberOfVariables(n_var_);
solver_.data()->setNumberOfConstraints(n_const_);
primal_variable_for_warmstart_.resize(n_var_, 1);
primal_variable_for_warmstart_.setZero();
is_first_ = true;
n_hessian_element_ = 0;
}
inline void QPSolverImpl::InitFunctionImpl() {
A_cost_.resize(0, n_var_);
b_cost_.resize(0, 1);
A_const_.resize(0, n_var_);
lb_.resize(0, 1);
ub_.resize(0, 1);
A_cost_.setZero();
b_cost_.setZero();
A_const_.setZero();
lb_.setZero();
ub_.setZero();
}
inline void QPSolverImpl::AddCostFunctionImpl(const Eigen::MatrixXd &A, const Eigen::VectorXd &b) {
if (A.rows() != b.rows()) {
CMVR_LOG(ERROR) << "OSQP Solver Add cost function failed: Size issue Ax = b (A.rows(): "
<< A.rows() << ", b.rows(): " << b.rows() << ")";
return;
}
if (b.cols() != 1) {
CMVR_LOG(ERROR) << "OSQP Solver Add cost function failed: Size issue: b (Nx1)";
return;
}
int n_rows_old = static_cast<int>(A_cost_.rows());
int n_rows_add = static_cast<int>(A.rows());
if (n_rows_old == 0) {
A_cost_.resize(n_rows_add, A.cols());
b_cost_.resize(n_rows_add, 1);
A_cost_.bottomRows(n_rows_add) = A;
b_cost_.bottomRows(n_rows_add) = b;
} else {
A_cost_.conservativeResize(n_rows_old + n_rows_add, Eigen::NoChange);
b_cost_.conservativeResize(n_rows_old + n_rows_add, Eigen::NoChange);
A_cost_.bottomRows(n_rows_add) = A;
b_cost_.bottomRows(n_rows_add) = b;
}
}
inline void QPSolverImpl::SetCostFunctionImpl(const Eigen::MatrixXd &A,
const Eigen::VectorXd &b) {
// 代价:min ||A x - b||^2
// => H = A^T A, g = -A^T b
hessian_ = (A.transpose() * A).sparseView();
gradient_ = -A.transpose() * b;
}
inline void QPSolverImpl::SetConstraintsFunctionImpl(const Eigen::MatrixXd &A,
const Eigen::VectorXd &lb,
const Eigen::VectorXd &ub) {
// 约束:lb <= A x <= ub
A_const_ = A;
lb_ = lb;
ub_ = ub;
linearMatrix_ = A.sparseView();
lowerBound_ = lb;
upperBound_ = ub;
}
inline void QPSolverImpl::SetPrimalVariableImpl(const Eigen::VectorXd &pv) {
primal_variable_for_warmstart_ = pv;
}
inline void QPSolverImpl::ResetIsFirstImpl() {
is_first_ = true;
}
inline Eigen::VectorXd QPSolverImpl::SolveImpl() {
bool need_init = false;
if (!is_first_) {
if (n_hessian_element_ == hessian_.nonZeros()) {
if (!solver_.updateHessianMatrix(hessian_)) {
need_init = true;
}
if (!solver_.updateGradient(gradient_)) {
need_init = true;
}
if (!solver_.updateLinearConstraintsMatrix(linearMatrix_)) {
need_init = true;
}
if (!solver_.updateBounds(lowerBound_, upperBound_)) {
need_init = true;
}
} else {
need_init = true;
}
} else {
need_init = true;
}
if (need_init) {
solver_.data()->clearHessianMatrix();
solver_.data()->clearLinearConstraintsMatrix();
solver_.clearSolver();
n_hessian_element_ = static_cast<int>(hessian_.nonZeros());
if (!solver_.data()->setHessianMatrix(hessian_)) {
throw QPSolverException(-1);
}
if (!solver_.data()->setGradient(gradient_)) {
throw QPSolverException(-1);
}
if (!solver_.data()->setLinearConstraintsMatrix(linearMatrix_)) {
throw QPSolverException(-1);
}
if (!solver_.data()->setLowerBound(lowerBound_)) {
throw QPSolverException(-1);
}
if (!solver_.data()->setUpperBound(upperBound_)) {
throw QPSolverException(-1);
}
if (!solver_.initSolver()) {
throw QPSolverException(-1);
}
is_first_ = false;
}
solver_.setPrimalVariable(primal_variable_for_warmstart_);
const auto result = solver_.solveProblem();
if (result != OsqpEigen::ErrorExitFlag::NoError) {
throw QPSolverException(static_cast<int>(result));
}
if (solver_.getStatus() != OsqpEigen::Status::Solved) {
throw QPSolverException(
static_cast<int>(QPSolverException::kStatusOffset) +
static_cast<int>(solver_.getStatus()));
}
return solver_.getSolution();
}
inline Eigen::MatrixXd QPSolverImpl::GetACostImpl() const {
return A_cost_;
}
inline Eigen::VectorXd QPSolverImpl::GetBCostImpl() const {
return b_cost_;
}
inline Eigen::MatrixXd QPSolverImpl::GetAConstImpl() const {
return A_const_;
}
inline Eigen::VectorXd QPSolverImpl::GetLowerBoundImpl() const {
return lb_;
}
inline Eigen::VectorXd QPSolverImpl::GetUpperBoundImpl() const {
return ub_;
}
// -----------------------------------------------------------
// 对外的 QPSolver 封装
// -----------------------------------------------------------
class QPSolver {
public:
QPSolver();
~QPSolver();
void Setup(int n_var, int n_const, double time_limit = 2e-3,
double absolute_tolerance = 1e-3, double relative_tolerance = 1e-3,
bool polish = false);
void InitFunction();
void AddCostFunction(const Eigen::MatrixXd& A, const Eigen::VectorXd& b);
void SetCostFunction(const Eigen::MatrixXd& A, const Eigen::VectorXd& b);
void SetConstraintsFunction(const Eigen::MatrixXd& A,
const Eigen::VectorXd& lb,
const Eigen::VectorXd& ub);
void SetPrimalVariable(const Eigen::VectorXd& pv);
void ResetIsFirst();
/**
* Solve the QP problem
* @return Solution
* @throw QPSolverException
*/
Eigen::VectorXd Solve();
Eigen::MatrixXd GetACost() const; // NOLINT
Eigen::VectorXd GetBCost() const; // NOLINT
Eigen::MatrixXd GetAConst() const; // NOLINT
Eigen::VectorXd GetLowerBound() const; // NOLINT
Eigen::VectorXd GetUpperBound() const; // NOLINT
private:
std::unique_ptr<QPSolverImpl> impl_;
};
inline QPSolver::QPSolver() {
impl_ = std::make_unique<QPSolverImpl>();
}
inline QPSolver::~QPSolver() = default;
inline void QPSolver::Setup(int n_var, int n_const, double time_limit,
double absolute_tolerance, double relative_tolerance,
bool polish) {
impl_->SetupImpl(n_var, n_const, time_limit, absolute_tolerance, relative_tolerance, polish);
}
inline void QPSolver::InitFunction() {
impl_->InitFunctionImpl();
}
inline void QPSolver::AddCostFunction(const Eigen::MatrixXd &A,
const Eigen::VectorXd &b) {
impl_->AddCostFunctionImpl(A, b);
}
inline void QPSolver::SetCostFunction(const Eigen::MatrixXd &A,
const Eigen::VectorXd &b) {
impl_->SetCostFunctionImpl(A, b);
}
inline void QPSolver::SetConstraintsFunction(const Eigen::MatrixXd &A,
const Eigen::VectorXd &lb,
const Eigen::VectorXd &ub) {
impl_->SetConstraintsFunctionImpl(A, lb, ub);
}
inline void QPSolver::SetPrimalVariable(const Eigen::VectorXd &pv) {
impl_->SetPrimalVariableImpl(pv);
}
inline void QPSolver::ResetIsFirst() {
impl_->ResetIsFirstImpl();
}
inline Eigen::VectorXd QPSolver::Solve() {
return impl_->SolveImpl();
}
inline Eigen::MatrixXd QPSolver::GetACost() const {
return impl_->GetACostImpl();
}
inline Eigen::VectorXd QPSolver::GetBCost() const {
return impl_->GetBCostImpl();
}
inline Eigen::MatrixXd QPSolver::GetAConst() const {
return impl_->GetAConstImpl();
}
inline Eigen::VectorXd QPSolver::GetLowerBound() const {
return impl_->GetLowerBoundImpl();
}
inline Eigen::VectorXd QPSolver::GetUpperBound() const {
return impl_->GetUpperBoundImpl();
}
} // namespace cmvr::math
#endif // CMVR_MATH_QP_SOLVER_H