repo_id
stringclasses
205 values
file_path
stringlengths
33
141
content
stringlengths
1
307k
__index_level_0__
int64
0
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/csdp_solver_error_handling.h
#pragma once #include <csetjmp> namespace drake { namespace solvers { namespace internal { // Returns a reference to a thread-local setjmp buffer. std::jmp_buf& get_per_thread_csdp_jmp_buf(); } // namespace internal } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/solve.cc
#include "drake/solvers/solve.h" #include <memory> #include "drake/common/nice_type_name.h" #include "drake/common/text_logging.h" #include "drake/solvers/choose_best_solver.h" #include "drake/solvers/solver_interface.h" namespace drake { namespace solvers { MathematicalProgramResult Solve( const MathematicalProgram& prog, const std::optional<Eigen::VectorXd>& initial_guess, const std::optional<SolverOptions>& solver_options) { const SolverId solver_id = ChooseBestSolver(prog); drake::log()->debug("solvers::Solve will use {}", solver_id); std::unique_ptr<SolverInterface> solver = MakeSolver(solver_id); MathematicalProgramResult result{}; solver->Solve(prog, initial_guess, solver_options, &result); return result; } MathematicalProgramResult Solve( const MathematicalProgram& prog, const Eigen::Ref<const Eigen::VectorXd>& initial_guess) { const Eigen::VectorXd initial_guess_xd = initial_guess; return Solve(prog, initial_guess_xd, {}); } MathematicalProgramResult Solve(const MathematicalProgram& prog) { return Solve(prog, {}, {}); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/nlopt_solver.h
#pragma once #include <string> #include "drake/common/drake_copyable.h" #include "drake/solvers/solver_base.h" namespace drake { namespace solvers { /** * The NLopt solver details after calling Solve() function. The user can call * MathematicalProgramResult::get_solver_details<NloptSolver>() to obtain the * details. */ struct NloptSolverDetails { /// The return status of NLopt solver. Please refer to /// https://nlopt.readthedocs.io/en/latest/NLopt_Reference/#return-values. int status{}; }; class NloptSolver final : public SolverBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(NloptSolver) /// Type of details stored in MathematicalProgramResult. using Details = NloptSolverDetails; NloptSolver(); ~NloptSolver() final; /** The key name for the double-valued constraint tolerance.*/ static std::string ConstraintToleranceName(); /** The key name for double-valued x relative tolerance.*/ static std::string XRelativeToleranceName(); /** The key name for double-valued x absolute tolerance.*/ static std::string XAbsoluteToleranceName(); /** The key name for int-valued maximum number of evaluations. */ static std::string MaxEvalName(); /** The key name for the string-valued algorithm. */ static std::string AlgorithmName(); /// @name Static versions of the instance methods with similar names. //@{ static SolverId id(); static bool is_available(); static bool is_enabled(); static bool ProgramAttributesSatisfied(const MathematicalProgram&); //@} // A using-declaration adds these methods into our class's Doxygen. using SolverBase::Solve; private: void DoSolve(const MathematicalProgram&, const Eigen::VectorXd&, const SolverOptions&, MathematicalProgramResult*) const final; }; } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/sos_basis_generator.h
#pragma once #include <vector> #include <Eigen/Core> #include "drake/common/symbolic/polynomial.h" namespace drake { namespace solvers { /** * Given input polynomial p, outputs a set M of monomials with the following * guarantee: if p = f1*f1 + f2*f2 + ... + fn*fn for some (unknown) polynomials * f1, f2, ..., fn, then the span of M contains f1, f2, ..., fn, Given M, one * can then find the polynomials fi using semidefinite programming; see, * e.g., Chapter 3 of Semidefinite Optimization and Convex Algebraic Geometry * by G. Blekherman, P. Parrilo, R. Thomas. * @param p A polynomial * @return A vector whose entries are the elements of M */ [[nodiscard]] drake::VectorX<symbolic::Monomial> ConstructMonomialBasis( const drake::symbolic::Polynomial& p); } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/moby_lcp_solver.cc
// TODO(jwnimmer-tri) Rewrite the logging in this file to use spdlog. #undef EIGEN_NO_IO #include "drake/solvers/moby_lcp_solver.h" #include <algorithm> #include <cmath> #include <functional> #include <iostream> #include <limits> #include <memory> #include <sstream> #include <stdexcept> #include <vector> #include <Eigen/LU> #include <Eigen/SparseCore> #include <Eigen/SparseLU> #include <unsupported/Eigen/AutoDiff> #include "drake/common/drake_assert.h" #include "drake/common/never_destroyed.h" #include "drake/common/text_logging.h" namespace drake { namespace solvers { namespace { template <typename Scalar> bool CheckLemkeTrivial(int n, const Scalar& zero_tol, const VectorX<Scalar>& q, VectorX<Scalar>* z) { // see whether trivial solution exists if (q.minCoeff() > -zero_tol) { z->resize(n); z->fill(0); return true; } return false; } // AutoDiff-supported linear system solver for performing principle pivoting // transformations. The matrix is supposed to be a linear basis, but it's // possible that the basis becomes degenerate (meaning that the matrix becomes // singular) due to accumulated roundoff error from pivoting. Recovering from // a degenerate basis is currently an open problem; // see http://www.optimization-online.org/DB_FILE/2011/03/2948.pdf, for // example. The caller would ideally terminate at this point, but // compilation of householderQr().rank() with AutoDiff currently generates // template errors. Continuing on blindly means that the calling pivoting // algorithm might continue on for some time. template <class T> VectorX<T> LinearSolve(const MatrixX<T>& M, const VectorX<T>& b) { // Special case necessary because Eigen doesn't always handle empty matrices // properly. if (M.rows() == 0) { DRAKE_ASSERT(b.size() == 0); return VectorX<T>(0); } return M.householderQr().solve(b); } // Linear system solver, specialized for double types. This method is faster // than the QR factorization necessary for AutoDiff support. It is assumed that // the matrix is full rank (see notes for generic LinearSolve() above). template <> VectorX<double> LinearSolve(const MatrixX<double>& M, const VectorX<double>& b) { // Special case necessary because Eigen doesn't always handle empty matrices // properly. if (M.rows() == 0) { DRAKE_ASSERT(b.size() == 0); return VectorX<double>(0); } return M.partialPivLu().solve(b); } // Utility function for copying part of a matrix (designated by the indices // in rows and cols) from in to a target matrix, out. This template approach // allows selecting parts of both sparse and dense matrices for input; only // a dense matrix is returned. template <typename Derived, typename T> void selectSubMat(const Eigen::MatrixBase<Derived>& in, const std::vector<unsigned>& rows, const std::vector<unsigned>& cols, MatrixX<T>* out) { const int num_rows = rows.size(); const int num_cols = cols.size(); out->resize(num_rows, num_cols); if (out->size() == 0) { return; } for (int i = 0; i < num_rows; i++) { const auto row_in = in.row(rows[i]); auto row_out = out->row(i); for (int j = 0; j < num_cols; j++) { row_out(j) = row_in(cols[j]); } } } // TODO(sammy-tri) this could also use a more efficient implementation. template <typename T> void selectSubVec(const VectorX<T>& in, const std::vector<unsigned>& rows, VectorX<T>* out) { const int num_rows = rows.size(); out->resize(num_rows); for (int i = 0; i < num_rows; i++) { (*out)(i) = in(rows[i]); } } template <typename Derived> Eigen::SparseVector<double> makeSparseVector( const Eigen::MatrixBase<Derived>& in) { DRAKE_ASSERT(in.cols() == 1); Eigen::SparseVector<double> out(in.rows()); for (int i = 0; i < in.rows(); i++) { if (in(i) != 0.0) { out.coeffRef(i) = in(i); } } return out; } template <typename Derived> Eigen::Index minCoeffIdx(const Eigen::MatrixBase<Derived>& in) { Eigen::Index idx; in.minCoeff(&idx); return idx; } const double kSqrtEps = std::sqrt(std::numeric_limits<double>::epsilon()); } // namespace template <typename T> void MobyLCPSolver<T>::SetLoggingEnabled(bool enabled) { log_enabled_ = enabled; } template <typename T> std::ostream& MobyLCPSolver<T>::Log() const { if (log_enabled_) { return std::cerr; } return null_stream_; } template <typename T> void MobyLCPSolver<T>::ClearIndexVectors() const { // clear all vectors all_.clear(); tlist_.clear(); bas_.clear(); nonbas_.clear(); j_.clear(); } template <> void MobyLCPSolver<Eigen::AutoDiffScalar<Vector1d>>::DoSolve( const MathematicalProgram&, const Eigen::VectorXd&, const SolverOptions&, MathematicalProgramResult*) const { throw std::logic_error( "MobyLCPSolver cannot yet be used in a MathematicalProgram " "while templatized as an AutoDiff"); } // TODO(edrumwri): Break the following code out into a special // MobyLcpMathematicalProgram class. template <typename T> void MobyLCPSolver<T>::DoSolve(const MathematicalProgram& prog, const Eigen::VectorXd& initial_guess, const SolverOptions& merged_options, MathematicalProgramResult* result) const { if (!prog.GetVariableScaling().empty()) { static const logging::Warn log_once( "MobyLCPSolver doesn't support the feature of variable scaling."); } // Moby doesn't use initial guess or the solver options. unused(initial_guess); unused(merged_options); // Solve each individual LCP, writing the result back to the decision // variables through the binding and returning true iff all LCPs are // feasible. // // If any is infeasible, returns false and does not alter the decision // variables. // // TODO(ggould-tri) This could also be solved by constructing a single large // square matrix and vector, and then copying the elements of the individual // Ms and qs into the appropriate places. That would be equivalent to this // implementation but might perform better if the solver were to parallelize // internally. const auto& bindings = prog.linear_complementarity_constraints(); Eigen::VectorXd x_sol(prog.num_vars()); for (const auto& binding : bindings) { Eigen::VectorXd constraint_solution(binding.GetNumElements()); const std::shared_ptr<LinearComplementarityConstraint> constraint = binding.evaluator(); bool solved = SolveLcpLemkeRegularized(constraint->M(), constraint->q(), &constraint_solution); if (!solved) { result->set_solution_result(SolutionResult::kSolverSpecificError); return; } for (int i = 0; i < binding.evaluator()->num_vars(); ++i) { const int variable_index = prog.FindDecisionVariableIndex(binding.variables()(i)); x_sol(variable_index) = constraint_solution(i); } } result->set_optimal_cost(0.0); result->set_x_val(x_sol); result->set_solution_result(SolutionResult::kSolutionFound); } template <typename T> bool MobyLCPSolver<T>::SolveLcpFast(const MatrixX<T>& M, const VectorX<T>& q, VectorX<T>* z, const T& zero_tol) const { using std::abs; // Variables that will be reused multiple times, thus hopefully allowing // Eigen to keep from freeing/reallocating memory repeatedly. VectorX<T> zz, w, qbas; MatrixX<T> Mmix, Msub; const unsigned N = q.rows(); const unsigned UINF = std::numeric_limits<unsigned>::max(); if (M.rows() != N || M.cols() != N) throw std::logic_error("M's dimensions do not match that of q."); Log() << "MobyLCPSolver::SolveLcpFast() entered" << std::endl; // look for trivial solution if (N == 0) { Log() << "MobyLCPSolver::SolveLcpFast() - empty problem" << std::endl; z->resize(0); return true; } // set zero tolerance if necessary T mod_zero_tol = zero_tol; if (mod_zero_tol < 0) mod_zero_tol = ComputeZeroTolerance(M); // prepare to setup basic and nonbasic variable indices for z nonbas_.clear(); bas_.clear(); // see whether to warm-start if (z->size() == q.size()) { Log() << "MobyLCPSolver::SolveLcpFast() - warm starting activated" << std::endl; for (unsigned i = 0; i < z->size(); i++) { if (abs((*z)[i]) < mod_zero_tol) { bas_.push_back(i); } else { nonbas_.push_back(i); } } if (log_enabled_) { std::ostringstream str; str << " -- non-basic indices:"; for (unsigned i = 0; i < nonbas_.size(); i++) str << " " << nonbas_[i]; Log() << str.str() << std::endl; } } else { // get minimum element of q (really w) Eigen::Index minw; const T minw_val = q.minCoeff(&minw); if (minw_val > -mod_zero_tol) { Log() << "MobyLCPSolver::SolveLcpFast() - trivial solution found" << std::endl; z->resize(N); z->fill(0); return true; } // setup basic and nonbasic variable indices nonbas_.push_back(minw); bas_.resize(N - 1); for (unsigned i = 0, j = 0; i < N; i++) { if (i != minw) { bas_[j++] = i; } } } // Loop for the maximum number of pivots. const unsigned MAX_PIV = 2 * N; for (pivots_ = 1; pivots_ <= MAX_PIV; pivots_++) { // select nonbasic indices selectSubMat(M, nonbas_, nonbas_, &Msub); selectSubMat(M, bas_, nonbas_, &Mmix); selectSubVec(q, nonbas_, &zz); selectSubVec(q, bas_, &qbas); zz *= -1; // Solve for nonbasic z. zz = LinearSolve(Msub, zz.eval()); // Eigen doesn't handle empty matrices properly, which causes the code // below to abort in the absence of the conditional. unsigned minw; if (Mmix.rows() == 0) { w = VectorX<T>(); minw = UINF; } else { w = Mmix * zz; w += qbas; minw = minCoeffIdx(w); } // TODO(sammy-tri) this log can't print when minw is UINF. // LOG() << "MobyLCPSolver::SolveLcpFast() - minimum w after pivot: " // << _w[minw] << std::endl; // if w >= 0, check whether any component of z < 0 if (minw == UINF || w[minw] > -mod_zero_tol) { // find the (a) minimum of z unsigned minz = (zz.rows() > 0) ? minCoeffIdx(zz) : UINF; if (log_enabled_ && zz.rows() > 0) { Log() << "MobyLCPSolver::SolveLcpFast() - minimum z after pivot: " << zz[minz] << std::endl; } if (minz < UINF && zz[minz] < -mod_zero_tol) { // get the original index and remove it from the nonbasic set unsigned idx = nonbas_[minz]; nonbas_.erase(nonbas_.begin() + minz); // move index to basic set and continue looping bas_.push_back(idx); std::sort(bas_.begin(), bas_.end()); } else { // found the solution z->resize(N); z->fill(0); // set values of z corresponding to _z for (unsigned i = 0, j = 0; j < nonbas_.size(); i++, j++) { (*z)[nonbas_[j]] = zz[i]; } Log() << "MobyLCPSolver::SolveLcpFast() - solution found!" << std::endl; return true; } } else { Log() << "(minimum w too negative)" << std::endl; // one or more components of w violating w >= 0 // move component of w from basic set to nonbasic set unsigned idx = bas_[minw]; bas_.erase(bas_.begin() + minw); nonbas_.push_back(idx); std::sort(nonbas_.begin(), nonbas_.end()); // look whether any component of z needs to move to basic set unsigned minz = (zz.rows() > 0) ? minCoeffIdx(zz) : UINF; if (log_enabled_ && zz.rows() > 0) { Log() << "MobyLCPSolver::SolveLcpFast() - minimum z after pivot: " << zz[minz] << std::endl; } if (minz < UINF && zz[minz] < -mod_zero_tol) { // move index to basic set and continue looping unsigned k = nonbas_[minz]; Log() << "MobyLCPSolver::SolveLcpFast() - moving index " << k << " to basic set" << std::endl; nonbas_.erase(nonbas_.begin() + minz); bas_.push_back(k); std::sort(bas_.begin(), bas_.end()); } } } Log() << "MobyLCPSolver::SolveLcpFast() - maximum allowable pivots exceeded" << std::endl; // if we're here, then the maximum number of pivots has been exceeded z->setZero(N); return false; } template <typename T> bool MobyLCPSolver<T>::SolveLcpFastRegularized(const MatrixX<T>& M, const VectorX<T>& q, VectorX<T>* z, int min_exp, unsigned step_exp, int max_exp, const T& zero_tol) const { Log() << "MobyLCPSolver::SolveLcpFastRegularized() entered" << std::endl; // Variables that will be reused multiple times, thus hopefully allowing // Eigen to keep from freeing/reallocating memory repeatedly. VectorX<T> wx; MatrixX<T> MM; // look for fast exit if (q.size() == 0) { z->resize(0); return true; } // copy MM MM = M; // A discourse on the zero tolerance in the context of regularization: // The zero tolerance is used to determine when an element of w or z is // effectively zero though its floating point value is negative. The question // is whether the regularization process will change the zero tolerance // necessary to solve the problem numerically. In such a case, the infinity // norm of M would be small while the infinity norm of MM (regularized M) // would be large. Consider the case of a symmetric, indefinite matrix with // maximum and minimum eigenvalues of a and -a, respectively. The matrix could // be made positive definite (and thereby guaranteed to possess a solution to // the linear complementarity problem) by adding an identity matrix times // (a+ε) to the LCP matrix, where ε > 0 (its magnitude will depend upon the // magnitude of a). The infinity norm (and hence the zero tolerance) could // then be expected to grow by a factor of approximately two during the // regularization process. In other words, recomputing the zero tolerance // for each regularization update to the LCP matrix appears wasteful. For // this reason, we compute it only once below, but a practical effect is // not discernible at this time. // Assign value for zero tolerance, if necessary. const T mod_zero_tol = (zero_tol > 0) ? zero_tol : ComputeZeroTolerance(M); Log() << " zero tolerance: " << mod_zero_tol << std::endl; // store the total pivots unsigned total_piv = 0; // try non-regularized version first bool result = SolveLcpFast(MM, q, z, mod_zero_tol); if (result) { // verify that solution truly is a solution -- check z if (z->minCoeff() >= -mod_zero_tol) { // check w wx = (M * (*z)) + q; if (wx.minCoeff() >= -mod_zero_tol) { // Check element-wise operation of z*wx. wx = z->array() * wx.eval().array(); const T wx_min = wx.minCoeff(); const T wx_max = wx.maxCoeff(); if (wx_min >= -mod_zero_tol && wx_max < mod_zero_tol) { Log() << " solved with no regularization necessary!" << std::endl; Log() << " pivots / total pivots: " << pivots_ << " " << pivots_ << std::endl; Log() << "MobyLCPSolver::SolveLcpFastRegularized() exited" << std::endl; return true; } else { Log() << "MobyLCPSolver::SolveLcpFastRegularized() - " << "'<w, z> not within tolerance(min value: " << wx_min << " max value: " << wx_max << ")" << std::endl; } } else { Log() << " MobyLCPSolver::SolveLcpFastRegularized() - " << "'w' not solved to desired tolerance" << std::endl; Log() << " minimum w: " << wx.minCoeff() << std::endl; } } else { Log() << " MobyLCPSolver::SolveLcpFastRegularized() - " << "'z' not solved to desired tolerance" << std::endl; Log() << " minimum z: " << z->minCoeff() << std::endl; } } else { Log() << " MobyLCPSolver::SolveLcpFastRegularized() " << "- solver failed with zero regularization" << std::endl; } // update the pivots total_piv += pivots_; // start the regularization process int rf = min_exp; while (rf < max_exp) { // setup regularization factor double lambda = std::pow(static_cast<double>(10.0), static_cast<double>(rf)); Log() << " trying to solve LCP with regularization factor: " << lambda << std::endl; // regularize M MM = M; for (unsigned i = 0; i < M.rows(); i++) { MM(i, i) += lambda; } // try to solve the LCP result = SolveLcpFast(MM, q, z, mod_zero_tol); // update total pivots total_piv += pivots_; if (result) { // verify that solution truly is a solution -- check z if (z->minCoeff() > -mod_zero_tol) { // check w wx = (MM * (*z)) + q; if (wx.minCoeff() > -mod_zero_tol) { // Check element-wise operation of z*wx. wx = z->array() * wx.eval().array(); const T wx_min = wx.minCoeff(); const T wx_max = wx.maxCoeff(); if (wx_min > -mod_zero_tol && wx_max < mod_zero_tol) { Log() << " solved with regularization factor: " << lambda << std::endl; Log() << " pivots / total pivots: " << pivots_ << " " << total_piv << std::endl; Log() << "MobyLCPSolver::SolveLcpFastRegularized() exited" << std::endl; pivots_ = total_piv; return true; } else { Log() << "MobyLCPSolver::SolveLcpFastRegularized() - " << "'<w, z> not within tolerance(min value: " << wx_min << " max value: " << wx_max << ")" << std::endl; } } else { Log() << " MobyLCPSolver::SolveLcpFastRegularized() - " << "'w' not solved to desired tolerance" << std::endl; Log() << " minimum w: " << wx.minCoeff() << std::endl; } } else { Log() << " MobyLCPSolver::SolveLcpFastRegularized() - " << "'z' not solved to desired tolerance" << std::endl; Log() << " minimum z: " << z->minCoeff() << std::endl; } } // increase rf rf += step_exp; } Log() << " unable to solve given any regularization!" << std::endl; Log() << "MobyLCPSolver::SolveLcpFastRegularized() exited" << std::endl; // store total pivots pivots_ = total_piv; // still here? failure... return false; } // Retrieves the solution computed by Lemke's Algorithm. // T is irrelevant for this method (necessary only for the member function). // MatrixType allows both dense and sparse matrices to be used. // Scalar allows this method to be used for when the T is AutoDiffXd but // the caller wants to use sparse methods. // TODO(edrumwri): Address this kludge when calling sparse LCP solves from // MobyLCPSolver<AutoDiffXd> has been prevented. template <typename T> template <typename MatrixType, typename Scalar> void MobyLCPSolver<T>::FinishLemkeSolution(const MatrixType& M, const VectorX<Scalar>& q, const VectorX<Scalar>& x, VectorX<Scalar>* z) const { using std::abs; using std::max; std::vector<unsigned>::iterator iiter; int idx; for (idx = 0, iiter = bas_.begin(); iiter != bas_.end(); iiter++, idx++) { (*z)(*iiter) = x(idx); } // TODO(sammy-tri) Is there a more efficient way to resize and // preserve the data? z->conservativeResize(q.size()); // check to see whether tolerances are satisfied if (log_enabled_) { VectorX<T> wl = (M * (*z)) + q; const T minw = wl.minCoeff(); const T w_dot_z = abs(wl.dot(*z)); Log() << " z: " << z << std::endl; Log() << " w: " << wl << std::endl; Log() << " minimum w: " << minw << std::endl; Log() << " w'z: " << w_dot_z << std::endl; } } template <typename T> bool MobyLCPSolver<T>::SolveLcpLemke(const MatrixX<T>& M, const VectorX<T>& q, VectorX<T>* z, const T& piv_tol, const T& zero_tol) const { using std::max; // Variables that will be reused multiple times, thus hopefully allowing // Eigen to keep from freeing/reallocating memory repeatedly. VectorX<T> result, dj, dl, x, xj, Be, u, z0; MatrixX<T> Bl, t1, t2; if (log_enabled_) { Log() << "MobyLCPSolver::SolveLcpLemke() entered" << std::endl; Log() << " M: " << std::endl << M; Log() << " q: " << q << std::endl; } const unsigned n = q.size(); const unsigned max_iter = std::min(unsigned{1000}, 50 * n); if (M.rows() != n || M.cols() != n) throw std::logic_error("M's dimensions do not match that of q."); // update the pivots pivots_ = 0; // look for immediate exit if (n == 0) { z->resize(0); return true; } // come up with a sensible value for zero tolerance if none is given T mod_zero_tol = zero_tol; if (mod_zero_tol <= 0) mod_zero_tol = ComputeZeroTolerance(M); if (CheckLemkeTrivial(n, mod_zero_tol, q, z)) { Log() << " -- trivial solution found" << std::endl; Log() << "MobyLCPSolver::SolveLcpLemke() exited" << std::endl; return true; } // Lemke's algorithm doesn't seem to like warmstarting // // TODO(sammy-tri) this is not present in the sparse solver, and it // causes subtle dead code below. z->fill(0); // copy z to z0 z0 = *z; ClearIndexVectors(); // initialize variables z->resize(n * 2); z->fill(0); unsigned t = 2 * n; unsigned entering = t; unsigned leaving = 0; for (unsigned i = 0; i < n; i++) { all_.push_back(i); } unsigned lvindex; unsigned idx; std::vector<unsigned>::iterator iiter; // determine initial basis if (z0.size() != n) { // setup the nonbasic indices for (unsigned i = 0; i < n; i++) nonbas_.push_back(i); } else { for (unsigned i = 0; i < n; i++) { if (z0[i] > 0) { bas_.push_back(i); } else { nonbas_.push_back(i); } } } // determine initial values if (!bas_.empty()) { Log() << "-- initial basis not empty (warmstarting)" << std::endl; // start from good initial basis Bl.resize(n, n); Bl.setIdentity(); Bl *= -1; // select columns of M corresponding to z vars in the basis selectSubMat(M, all_, bas_, &t1); // select columns of I corresponding to z vars not in the basis selectSubMat(Bl, all_, nonbas_, &t2); // setup the basis matrix Bl.resize(n, t1.cols() + t2.cols()); Bl.block(0, 0, t1.rows(), t1.cols()) = t1; Bl.block(0, t1.cols(), t2.rows(), t2.cols()) = t2; // Solve B*x = -q. x = LinearSolve(Bl, q); } else { Log() << "-- using basis of -1 (no warmstarting)" << std::endl; // use standard initial basis Bl.resize(n, n); Bl.setIdentity(); Bl *= -1; x = q; } // check whether initial basis provides a solution if (x.minCoeff() >= 0.0) { Log() << " -- initial basis provides a solution!" << std::endl; FinishLemkeSolution(M, q, x, z); Log() << "MobyLCPSolver::SolveLcpLemke() exited" << std::endl; return true; } // use a new pivot tolerance if necessary const T naive_piv_tol = n * max(T(1), M.template lpNorm<Eigen::Infinity>()) * std::numeric_limits<double>::epsilon(); const T mod_piv_tol = (piv_tol > 0) ? piv_tol : naive_piv_tol; // determine initial leaving variable Eigen::Index min_x; const T min_x_val = x.topRows(n).minCoeff(&min_x); const T tval = -min_x_val; for (size_t i = 0; i < nonbas_.size(); i++) { bas_.push_back(nonbas_[i] + n); } lvindex = min_x; iiter = bas_.begin(); std::advance(iiter, lvindex); leaving = *iiter; Log() << " -- x: " << x << std::endl; Log() << " -- first pivot: leaving index=" << lvindex << " entering index=" << entering << " minimum value: " << tval << std::endl; // pivot in the artificial variable *iiter = t; // replace w var with _z0 in basic indices u.resize(n); for (unsigned i = 0; i < n; i++) { u[i] = (x[i] < 0) ? 1 : 0; } Be = (Bl * u) * -1; u *= tval; x += u; x[lvindex] = tval; Bl.col(lvindex) = Be; Log() << " new q: " << x << std::endl; // main iterations begin here for (pivots_ = 0; pivots_ < max_iter; pivots_++) { if (log_enabled_) { std::ostringstream basic; for (unsigned i = 0; i < bas_.size(); i++) { basic << " " << bas_[i]; } Log() << "basic variables:" << basic.str() << std::endl; Log() << "leaving: " << leaving << " t:" << t << std::endl; } // check whether done; if not, get new entering variable if (leaving == t) { Log() << "-- solved LCP successfully!" << std::endl; FinishLemkeSolution(M, q, x, z); Log() << "MobyLCPSolver::SolveLcpLemke() exited" << std::endl; return true; } else if (leaving < n) { entering = n + leaving; Be.resize(n); Be.fill(0); Be[leaving] = -1; } else { entering = leaving - n; Be = M.col(entering); } dl = Be; // See comments above on the possibility of this solve failing. dl = LinearSolve(Bl, dl.eval()); // ** find new leaving variable j_.clear(); for (unsigned i = 0; i < dl.size(); i++) { if (dl[i] > mod_piv_tol) { j_.push_back(i); } } // check for no new pivots; ray termination if (j_.empty()) { Log() << "MobyLCPSolver::SolveLcpLemke() - no new pivots (ray termination)" << std::endl; Log() << "MobyLCPSolver::SolveLcpLemke() exiting" << std::endl; z->setZero(n); return false; } if (log_enabled_) { std::ostringstream j; for (unsigned i = 0; i < j_.size(); i++) j << " " << j_[i]; Log() << "d: " << dl << std::endl; Log() << "j (before min ratio):" << j.str() << std::endl; } // select elements j from x and d selectSubVec(x, j_, &xj); selectSubVec(dl, j_, &dj); // compute minimal ratios x(j) + EPS_DOUBLE ./ d(j), d > 0 result.resize(xj.size()); result.fill(mod_zero_tol); result = xj.eval().array() + result.array(); result = result.eval().array() / dj.array(); const T theta = result.minCoeff(); // NOTE: lexicographic ordering is not used here to prevent // cycling (see [Cottle 1992], pp. 340-342). Cycling is indirectly prevented // by (a) limiting the maximum number of pivots and (b) using // regularized solvers, as necessary. In other words, cycling may cause // solver to fail when the LCP is theoretically solvable, but wrapping the // solver with regularization practically addresses the problem (albeit, // at the cost of additional computation). // find indices of minimal ratios, d> 0 // divide _x(j) ./ d(j) -- remove elements above the minimum ratio for (int i = 0; i < result.size(); i++) { result(i) = xj(i) / dj(i); } for (iiter = j_.begin(), idx = 0; iiter != j_.end();) { if (result[idx++] <= theta) { iiter++; } else { iiter = j_.erase(iiter); } } if (log_enabled_) { std::ostringstream j; for (unsigned i = 0; i < j_.size(); i++) { j << " " << j_[i]; } Log() << "j (after min ratio):" << j.str() << std::endl; } // if j is empty, then likely the zero tolerance is too low if (j_.empty()) { Log() << "zero tolerance too low?" << std::endl; Log() << "MobyLCPSolver::SolveLcpLemke() exited" << std::endl; z->setZero(n); return false; } // check whether artificial index among these tlist_.clear(); for (size_t i = 0; i < j_.size(); i++) { tlist_.push_back(bas_[j_[i]]); } if (std::find(tlist_.begin(), tlist_.end(), t) != tlist_.end()) { iiter = std::find(bas_.begin(), bas_.end(), t); lvindex = iiter - bas_.begin(); } else { // several indices pass the minimum ratio test, pick one randomly // lvindex = _j[rand() % _j.size()]; // NOTE: solver seems *much* more capable of solving when we pick the // first // element rather than picking a random one lvindex = j_[0]; } // set leaving = bas(lvindex) iiter = bas_.begin(); std::advance(iiter, lvindex); leaving = *iiter; // ** perform pivot const T ratio = x[lvindex] / dl[lvindex]; dl *= ratio; x -= dl; x[lvindex] = ratio; Bl.col(lvindex) = Be; *iiter = entering; Log() << " -- pivoting: leaving index=" << lvindex << " entering index=" << entering << std::endl; } Log() << " -- maximum number of iterations exceeded (n=" << n << ", max=" << max_iter << ")" << std::endl; Log() << "MobyLCPSolver::SolveLcpLemke() exited" << std::endl; z->setZero(n); return false; } template <class T> bool MobyLCPSolver<T>::SolveLcpLemkeRegularized( const MatrixX<T>& M, const VectorX<T>& q, VectorX<T>* z, int min_exp, unsigned step_exp, int max_exp, const T& piv_tol, const T& zero_tol) const { // Variables that will be reused multiple times, thus hopefully allowing // Eigen to keep from freeing/reallocating memory repeatedly. VectorX<T> wx; Log() << "MobyLCPSolver::SolveLcpLemkeRegularized() entered" << std::endl; // look for fast exit if (q.size() == 0) { z->resize(0); return true; } // copy MM MatrixX<T> MM = M; // Assign value for zero tolerance, if necessary. See discussion in // SolveLcpFastRegularized() to see why this tolerance is computed here once, // rather than for each regularized version of M. const T mod_zero_tol = (zero_tol > 0) ? zero_tol : ComputeZeroTolerance(M); Log() << " zero tolerance: " << mod_zero_tol << std::endl; // store the total pivots unsigned total_piv = 0; // try non-regularized version first bool result = SolveLcpLemke(MM, q, z, piv_tol, mod_zero_tol); if (result) { // verify that solution truly is a solution -- check z if (z->minCoeff() >= -mod_zero_tol) { // check w wx = (M * (*z)) + q; if (wx.minCoeff() >= -mod_zero_tol) { // Check element-wise operation of z*wx. wx = z->array() * wx.eval().array(); const T wx_min = wx.minCoeff(); const T wx_max = wx.maxCoeff(); if (wx_min >= -mod_zero_tol && wx_max < mod_zero_tol) { Log() << " solved with no regularization necessary!" << std::endl; Log() << "MobyLCPSolver::SolveLcpLemkeRegularized() exited" << std::endl; return true; } else { Log() << "MobyLCPSolver::SolveLcpLemke() - " << "'<w, z> not within tolerance(min value: " << wx_min << " max value: " << wx_max << ")" << std::endl; } } else { Log() << " MobyLCPSolver::SolveLcpLemke() - 'w' not solved to desired " "tolerance" << std::endl; Log() << " minimum w: " << wx.minCoeff() << std::endl; } } else { Log() << " MobyLCPSolver::SolveLcpLemke() - 'z' not solved to desired " "tolerance" << std::endl; Log() << " minimum z: " << z->minCoeff() << std::endl; } } // update the pivots total_piv += pivots_; // start the regularization process int rf = min_exp; while (rf < max_exp) { // setup regularization factor double lambda = std::pow(static_cast<double>(10.0), static_cast<double>(rf)); Log() << " trying to solve LCP with regularization factor: " << lambda << std::endl; // regularize M MM = M; for (unsigned i = 0; i < M.rows(); i++) { MM(i, i) += lambda; } // try to solve the LCP result = SolveLcpLemke(MM, q, z, piv_tol, mod_zero_tol); // update total pivots total_piv += pivots_; if (result) { // verify that solution truly is a solution -- check z if (z->minCoeff() > -mod_zero_tol) { // check w wx = (MM * (*z)) + q; if (wx.minCoeff() > -mod_zero_tol) { // Check element-wise operation of z*wx. wx = z->array() * wx.eval().array(); const T wx_min = wx.minCoeff(); const T wx_max = wx.maxCoeff(); if (wx_min > -mod_zero_tol && wx_max < mod_zero_tol) { Log() << " solved with regularization factor: " << lambda << std::endl; Log() << "MobyLCPSolver::SolveLcpLemkeRegularized() exited" << std::endl; pivots_ = total_piv; return true; } else { Log() << "MobyLCPSolver::SolveLcpLemke() - " << "'<w, z> not within tolerance(min value: " << wx_min << " max value: " << wx_max << ")" << std::endl; } } else { Log() << " MobyLCPSolver::SolveLcpLemke() - 'w' not solved to " "desired tolerance" << std::endl; Log() << " minimum w: " << wx.minCoeff() << std::endl; } } else { Log() << " MobyLCPSolver::SolveLcpLemke() - 'z' not solved to desired " "tolerance" << std::endl; Log() << " minimum z: " << z->minCoeff() << std::endl; } } // increase rf rf += step_exp; } Log() << " unable to solve given any regularization!" << std::endl; Log() << "MobyLCPSolver::SolveLcpLemkeRegularized() exited" << std::endl; // store total pivots pivots_ = total_piv; // still here? failure... return false; } template <typename T> MobyLCPSolver<T>::MobyLCPSolver() : SolverBase(id(), &is_available, &is_enabled, &ProgramAttributesSatisfied) {} template <typename T> MobyLCPSolver<T>::~MobyLCPSolver() = default; SolverId MobyLcpSolverId::id() { static const never_destroyed<SolverId> singleton{"Moby LCP"}; return singleton.access(); } template <typename T> SolverId MobyLCPSolver<T>::id() { return MobyLcpSolverId::id(); } template <typename T> bool MobyLCPSolver<T>::is_available() { return true; } template <typename T> bool MobyLCPSolver<T>::is_enabled() { return true; } template <typename T> bool MobyLCPSolver<T>::ProgramAttributesSatisfied( const MathematicalProgram& prog) { // This solver currently imposes restrictions that its problem: // // (1) Contains only linear complementarity constraints, // (2) Has no element of any decision variable appear in more than one // constraint, and // (3) Has every element of every decision variable in a constraint. // // Restriction 1 could reasonably be relaxed by reformulating other // constraint types that can be expressed as LCPs (eg, convex QLPs), // although this would also entail adding an output stage to convert // the LCP results back to the desired form. See eg. @RussTedrake on // how to convert a linear equality constraint of n elements to an // LCP of 2n elements. // // There is no obvious way to relax restriction 2. // // Restriction 3 could reasonably be relaxed to simply let unbound // variables sit at 0. if (prog.required_capabilities() != ProgramAttributes({ProgramAttribute::kLinearComplementarityConstraint})) { return false; } // Check that the available LCPs cover the program and no two LCPs cover the // same variable. const auto& bindings = prog.linear_complementarity_constraints(); for (int i = 0; i < static_cast<int>(prog.num_vars()); ++i) { int coverings = 0; for (const auto& binding : bindings) { if (binding.ContainsVariable(prog.decision_variable(i))) { coverings++; } } if (coverings != 1) { return false; } } return true; } // Instantiate templates. template class MobyLCPSolver<double>; template class MobyLCPSolver<Eigen::AutoDiffScalar<Vector1d>>; } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/scs_solver_common.cc
/* clang-format off to disable clang-format-includes */ #include "drake/solvers/scs_solver.h" /* clang-format on */ #include "drake/common/never_destroyed.h" #include "drake/solvers/aggregate_costs_constraints.h" #include "drake/solvers/mathematical_program.h" namespace drake { namespace solvers { ScsSolver::ScsSolver() : SolverBase(id(), &is_available, &is_enabled, &ProgramAttributesSatisfied, &UnsatisfiedProgramAttributes) {} ScsSolver::~ScsSolver() = default; SolverId ScsSolver::id() { static const never_destroyed<SolverId> singleton{"SCS"}; return singleton.access(); } bool ScsSolver::is_enabled() { return true; } namespace { // If the program is compatible with this solver, returns true and clears the // explanation. Otherwise, returns false and sets the explanation. In either // case, the explanation can be nullptr in which case it is ignored. bool CheckAttributes(const MathematicalProgram& prog, std::string* explanation) { static const never_destroyed<ProgramAttributes> solver_capabilities( std::initializer_list<ProgramAttribute>{ ProgramAttribute::kLinearEqualityConstraint, ProgramAttribute::kLinearConstraint, ProgramAttribute::kLorentzConeConstraint, ProgramAttribute::kRotatedLorentzConeConstraint, ProgramAttribute::kPositiveSemidefiniteConstraint, ProgramAttribute::kExponentialConeConstraint, ProgramAttribute::kLinearCost, ProgramAttribute::kQuadraticCost, ProgramAttribute::kL2NormCost}); return internal::CheckConvexSolverAttributes( prog, solver_capabilities.access(), "ScsSolver", explanation); } } // namespace bool ScsSolver::ProgramAttributesSatisfied(const MathematicalProgram& prog) { return CheckAttributes(prog, nullptr); } std::string ScsSolver::UnsatisfiedProgramAttributes( const MathematicalProgram& prog) { std::string explanation; CheckAttributes(prog, &explanation); return explanation; } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/mixed_integer_rotation_constraint_internal.h
#pragma once #include <vector> #include <Eigen/Core> // This file only exists to expose some internal methods for unit testing. It // should NOT be included in user code. // The API documentation for these functions lives in // mixed_integer_rotation_constraint_internal.cc, where they are implemented. namespace drake { namespace solvers { namespace internal { /** * Given an axis-aligned box in the first orthant, computes and returns all the * intersecting points between the edges of the box and the unit sphere. * @param bmin The vertex of the box closest to the origin. * @param bmax The vertex of the box farthest from the origin. */ std::vector<Eigen::Vector3d> ComputeBoxEdgesAndSphereIntersection( const Eigen::Vector3d& bmin, const Eigen::Vector3d& bmax); /* * For the intersection region between the surface of the unit sphere, and the * interior of a box aligned with the axes, use a half space relaxation for * the intersection region as nᵀ * v >= d * @param[in] pts. The vertices containing the intersecting points between edges * of the box and the surface of the unit sphere. * @param[out] n. The unit length normal vector of the halfspace, pointing * outward. * @param[out] d. The intercept of the halfspace. */ void ComputeHalfSpaceRelaxationForBoxSphereIntersection( const std::vector<Eigen::Vector3d>& pts, Eigen::Vector3d* n, double* d); /** * For the vertices in `pts`, determine if these vertices are co-planar. If they * are, then compute that plane nᵀ * x = d. * @param pts The vertices to be checked. * @param n The unit length normal vector of the plane, points outward from the * origin. If the vertices are not co-planar, leave `n` to 0. * @param d The intersecpt of the plane. If the vertices are not co-planar, set * this to 0. * @return If the vertices are co-planar, set this to true. Otherwise set to * false. */ bool AreAllVerticesCoPlanar(const std::vector<Eigen::Vector3d>& pts, Eigen::Vector3d* n, double* d); /** * For the intersection region between the surface of the unit sphere, and the * interior of a box aligned with the axes, relax this nonconvex intersection * region to its convex hull. This convex hull has some planar facets (formed * by the triangles connecting the vertices of the intersection region). This * function computes these planar facets. It is guaranteed that any point x on * the intersection region, satisfies A * x <= b. * @param[in] pts The vertices of the intersection region. Same as the `pts` in * ComputeHalfSpaceRelaxationForBoxSphereIntersection() * @param[out] A The rows of A are the normal vector of facets. Each row of A is * a unit length vector. * @param b b(i) is the interscept of the i'th facet. * @pre pts[i] are all in the first orthant, namely (pts[i].array() >=0).all() * should be true. */ void ComputeInnerFacetsForBoxSphereIntersection( const std::vector<Eigen::Vector3d>& pts, Eigen::Matrix<double, Eigen::Dynamic, 3>* A, Eigen::VectorXd* b); } // namespace internal } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/integer_inequality_solver.h
#pragma once #include <Eigen/Core> namespace drake { namespace solvers { /** * Finds all integer solutions x to the linear inequalities * <pre> * Ax <= b, * x <= upper_bound, * x >= lower_bound. * </pre> * @param A An (m x n) integer matrix. * @param b An (m x 1) integer vector. * @param upper_bound A (n x 1) integer vector. * @param lower_bound A (n x 1) integer vector. * @return A (p x n) matrix whose rows are the solutions. */ Eigen::Matrix<int, -1, -1, Eigen::RowMajor> EnumerateIntegerSolutions( const Eigen::Ref<const Eigen::MatrixXi>& A, const Eigen::Ref<const Eigen::VectorXi>& b, const Eigen::Ref<const Eigen::VectorXi>& lower_bound, const Eigen::Ref<const Eigen::VectorXi>& upper_bound); } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/mathematical_program_result.cc
#include "drake/solvers/mathematical_program_result.h" #include <fmt/format.h> #include "drake/common/never_destroyed.h" namespace drake { namespace solvers { namespace { SolverId UnknownId() { static const never_destroyed<SolverId> result(SolverId({})); return result.access(); } } // namespace MathematicalProgramResult::MathematicalProgramResult() : decision_variable_index_{}, solution_result_{SolutionResult::kSolutionResultNotSet}, x_val_{0}, optimal_cost_{NAN}, solver_id_{UnknownId()}, solver_details_{nullptr} {} const AbstractValue& MathematicalProgramResult::get_abstract_solver_details() const { if (!solver_details_) { throw std::logic_error("The solver_details has not been set yet."); } return *solver_details_; } bool MathematicalProgramResult::is_success() const { return solution_result_ == SolutionResult::kSolutionFound; } void MathematicalProgramResult::set_x_val(const Eigen::VectorXd& x_val) { DRAKE_DEMAND(decision_variable_index_.has_value()); if (x_val.size() != static_cast<int>(decision_variable_index_->size())) { std::stringstream oss; oss << "MathematicalProgramResult::set_x_val, the dimension of x_val is " << x_val.size() << ", expected " << decision_variable_index_->size(); throw std::invalid_argument(oss.str()); } x_val_ = x_val; } double GetVariableValue( const symbolic::Variable& var, const std::optional<std::unordered_map<symbolic::Variable::Id, int>>& variable_index, const Eigen::Ref<const Eigen::VectorXd>& variable_values) { DRAKE_ASSERT(variable_index.has_value()); DRAKE_ASSERT(variable_values.rows() == static_cast<int>(variable_index->size())); auto it = variable_index->find(var.get_id()); if (it == variable_index->end()) { throw std::invalid_argument(fmt::format( "GetVariableValue: {} is not captured by the variable_index map.", var.get_name())); } return variable_values(it->second); } double MathematicalProgramResult::GetSolution( const symbolic::Variable& var) const { return GetVariableValue(var, decision_variable_index_, x_val_); } void MathematicalProgramResult::SetSolution(const symbolic::Variable& var, double value) { x_val_(decision_variable_index_->at(var.get_id())) = value; } symbolic::Expression MathematicalProgramResult::GetSolution( const symbolic::Expression& e) const { DRAKE_ASSERT(decision_variable_index_.has_value()); symbolic::Environment env; for (const auto& var : e.GetVariables()) { const auto it = decision_variable_index_->find(var.get_id()); // We do not expect every variable to be in GetSolution (e.g. not the // indeterminates). if (it != decision_variable_index_->end()) { env.insert(var, x_val_(it->second)); } } return e.EvaluatePartial(env); } symbolic::Polynomial MathematicalProgramResult::GetSolution( const symbolic::Polynomial& p) const { DRAKE_ASSERT(decision_variable_index_.has_value()); for (const auto& indeterminate : p.indeterminates()) { if (decision_variable_index_->contains(indeterminate.get_id())) { throw std::invalid_argument( fmt::format("GetSolution: {} is an indeterminate in the polynomial, " "but result stores its value as a decision variable.", indeterminate.get_name())); } } symbolic::Environment env; symbolic::Polynomial::MapType monomial_to_coefficient_result_map; for (const auto& [monomial, coefficient] : p.monomial_to_coefficient_map()) { for (const auto& var : coefficient.GetVariables()) { const auto it = decision_variable_index_->find(var.get_id()); if (it != decision_variable_index_->end()) { env.insert(var, x_val_(it->second)); } } // Evaluate the coefficient using env, and then add the pair (monomial, // coefficient_evaluate_result) to the new map. monomial_to_coefficient_result_map.emplace_hint( monomial_to_coefficient_result_map.end(), monomial, coefficient.EvaluatePartial(env)); } return symbolic::Polynomial(monomial_to_coefficient_result_map); } double MathematicalProgramResult::GetSuboptimalSolution( const symbolic::Variable& var, int solution_number) const { return GetVariableValue(var, decision_variable_index_, suboptimal_x_val_[solution_number]); } void MathematicalProgramResult::AddSuboptimalSolution( double suboptimal_objective, const Eigen::VectorXd& suboptimal_x) { suboptimal_x_val_.push_back(suboptimal_x); suboptimal_objectives_.push_back(suboptimal_objective); } std::vector<std::string> MathematicalProgramResult::GetInfeasibleConstraintNames( const MathematicalProgram& prog, std::optional<double> tolerance) const { std::vector<std::string> descriptions; if (!tolerance) { // TODO(russt): Extract the constraint tolerance from the solver. This // value was used successfully for some time in MATLAB Drake, so I've // ported it as the default here. tolerance = 1e-4; } for (const auto& binding : prog.GetAllConstraints()) { const Eigen::VectorXd val = this->EvalBinding(binding); const std::shared_ptr<Constraint>& constraint = binding.evaluator(); std::string d = constraint->get_description(); if (d.empty()) { d = NiceTypeName::Get(*constraint); } for (int i = 0; i < val.rows(); i++) { if (std::isnan(val(i)) || val[i] < constraint->lower_bound()[i] - *tolerance || val[i] > constraint->upper_bound()[i] + *tolerance) { descriptions.push_back(d + "[" + std::to_string(i) + "]: " + std::to_string(constraint->lower_bound()[i]) + " <= " + std::to_string(val[i]) + " <= " + std::to_string(constraint->upper_bound()[i])); } } } return descriptions; } std::vector<Binding<Constraint>> MathematicalProgramResult::GetInfeasibleConstraints( const MathematicalProgram& prog, std::optional<double> tolerance) const { std::vector<Binding<Constraint>> infeasible_bindings; if (!tolerance) { // TODO(russt): Extract the constraint tolerance from the solver. This // value was used successfully for some time in MATLAB Drake, so I've // ported it as the default here. tolerance = 1e-4; } for (const auto& binding : prog.GetAllConstraints()) { const Eigen::VectorXd val = this->EvalBinding(binding); const std::shared_ptr<Constraint>& constraint = binding.evaluator(); for (int i = 0; i < constraint->num_constraints(); ++i) { if (std::isnan(val(i)) || val(i) > constraint->upper_bound()(i) + *tolerance || val(i) < constraint->lower_bound()(i) - *tolerance) { infeasible_bindings.push_back(binding); break; } } } return infeasible_bindings; } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/no_clp.cc
/* clang-format off to disable clang-format-includes */ #include "drake/solvers/clp_solver.h" /* clang-format on */ #include <stdexcept> namespace drake { namespace solvers { bool ClpSolver::is_available() { return false; } void ClpSolver::DoSolve(const MathematicalProgram&, const Eigen::VectorXd&, const SolverOptions&, MathematicalProgramResult*) const { throw std::runtime_error( "The CLP bindings were not compiled. You'll need to use a different " "solver."); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/sdpa_free_format.h
#pragma once #include <string> #include <unordered_map> #include <variant> #include <vector> #include <Eigen/Core> #include <Eigen/Sparse> #include "drake/common/drake_copyable.h" #include "drake/common/fmt.h" #include "drake/common/type_safe_index.h" #include "drake/solvers/mathematical_program.h" namespace drake { namespace solvers { namespace internal { /** * X is a block diagonal matrix in SDPA format. EntryInX stores the information * of one entry in this block-diagonal matrix X. */ struct EntryInX { EntryInX(int block_index_in, int row_index_in_block_in, int column_index_in_block_in, int X_start_row_in) : block_index{block_index_in}, row_index_in_block(row_index_in_block_in), column_index_in_block(column_index_in_block_in), X_start_row(X_start_row_in) {} // block_index is 0-indexed. int block_index; // The row and column indices of the entry in this block. Both row/column // indices are 0-indexed. int row_index_in_block; int column_index_in_block; // The starting row index of this block in X. This is 0-indexed. int X_start_row; }; enum class BlockType { kMatrix, kDiagonal, }; struct BlockInX { BlockInX(BlockType block_type_in, int num_rows_in) : block_type{block_type_in}, num_rows{num_rows_in} {} BlockType block_type; int num_rows; }; /** * Refer to @ref map_decision_variable_to_sdpa * When the decision variable either (or both) finite lower or upper bound (with * the two bounds not equal), we need to record the sign of the coefficient * before y. */ enum class Sign { kPositive, kNegative, }; /** * @anchor map_decision_variable_to_sdpa Map decision variable to SDPA * When MathematicalProgram formulates a semidefinite program (SDP), we can * convert MathematicalProgram to a standard format for SDP, namely the SDPA * format. Each of the variable x in MathematicalProgram might be mapped to a * variable in the SDPA free format, depending on the following conditions. * 1. If the variable x has no lower nor upper bound, it is mapped to a free * variable in SDPA free format. * 2. If the variable x only has a finite lower bound, and an infinite upper * bound, then we will replace x by lower + y, where y is a diagonal entry * in X in SDPA free format. * 3. If the variable x only has a finite upper bound, and an infinite lower * bound, then we will replace x by upper - y, where y is a diagonal entry * in X in SDPA free format. * 4. If the variable x has both finite upper and lower bounds, and these bounds * are not equal, then we replace x by lower + y1, and introduce another * constraint y1 + y2 = upper - lower, where both y1 and y2 are diagonal * entries in X in SDPA free format. * 5. If the variable x has equal lower and upper bound, then we replace x with * the double value of lower bound. * A MathematicalProgram decision variable can be replaced by coeff_sign * y + * offset, where y is a diagonal entry in SDPA X matrix. */ struct DecisionVariableInSdpaX { DecisionVariableInSdpaX(Sign coeff_sign_m, double offset_m, EntryInX entry_in_X_m) : coeff_sign{coeff_sign_m}, offset{offset_m}, entry_in_X{entry_in_X_m} {} DecisionVariableInSdpaX(Sign coeff_sign_m, double offset_m, int block_index, int row_index_in_block, int col_index_in_block, int block_start_row) : coeff_sign(coeff_sign_m), offset(offset_m), entry_in_X(block_index, row_index_in_block, col_index_in_block, block_start_row) {} Sign coeff_sign; double offset; EntryInX entry_in_X; }; /** * SDPA format with free variables. * * max tr(C * X) + dᵀs * s.t tr(Aᵢ*X) + bᵢᵀs = gᵢ * X ≽ 0 * s is free. */ class SdpaFreeFormat { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SdpaFreeFormat) explicit SdpaFreeFormat(const MathematicalProgram& prog); ~SdpaFreeFormat(); [[nodiscard]] const std::vector<BlockInX>& X_blocks() const { return X_blocks_; } using FreeVariableIndex = TypeSafeIndex<class FreeVariableTag>; [[nodiscard]] const std::vector<std::variant< DecisionVariableInSdpaX, FreeVariableIndex, double, std::nullptr_t>>& prog_var_in_sdpa() const { return prog_var_in_sdpa_; } [[nodiscard]] const std::vector<std::vector<Eigen::Triplet<double>>>& A_triplets() const { return A_triplets_; } [[nodiscard]] const std::vector<Eigen::Triplet<double>>& B_triplets() const { return B_triplets_; } /** The right-hand side of the linear equality constraints. */ [[nodiscard]] const Eigen::VectorXd& g() const { return g_; } int num_X_rows() const { return num_X_rows_; } [[nodiscard]] int num_free_variables() const { return num_free_variables_; } [[nodiscard]] const std::vector<Eigen::Triplet<double>>& C_triplets() const { return C_triplets_; } [[nodiscard]] const std::vector<Eigen::Triplet<double>>& d_triplets() const { return d_triplets_; } [[nodiscard]] const std::vector<Eigen::SparseMatrix<double>>& A() const { return A_; } [[nodiscard]] const Eigen::SparseMatrix<double>& B() const { return B_; } [[nodiscard]] const Eigen::SparseMatrix<double>& C() const { return C_; } [[nodiscard]] const Eigen::SparseMatrix<double>& d() const { return d_; } /** The SDPA format doesn't include the constant term in the cost, but * MathematicalProgram does. We store the constant cost term here. */ [[nodiscard]] double constant_min_cost_term() const { return constant_min_cost_term_; } /** * For the following problem * * max tr(C * X) + dᵀs * s.t tr(Aᵢ*X) + bᵢᵀs = aᵢ * X ≽ 0 * s is free, * * remove the free variable s by considering the nullspace of Bᵀ, where bᵢᵀ * is the i'th row of B. * * max tr((C-∑ᵢ ŷᵢAᵢ)*X̂) + aᵀŷ * s.t tr(FᵢX̂) = (Nᵀa)(i) * X̂ ≽ 0, * * where Fᵢ = ∑ⱼ NⱼᵢAⱼ, N is the null space of Bᵀ. Bᵀ * ŷ = d. * For more information, refer to RemoveFreeVariableMethod for the * derivation. * @param C_hat[out] C_hat is (C-∑ᵢ ŷᵢAᵢ) in the documentation. * @param A_hat[out] A_hat[i] is Fᵢ in the documentation. * @param rhs_hat[out] rhs_hat is (Nᵀa) * @param y_hat[out] ŷ in the documentation. * @param QR_B[out] The QR decomposition of B. */ void RemoveFreeVariableByNullspaceApproach( Eigen::SparseMatrix<double>* C_hat, std::vector<Eigen::SparseMatrix<double>>* A_hat, Eigen::VectorXd* rhs_hat, Eigen::VectorXd* y_hat, Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>* QR_B) const; /** * For the problem * * max tr(C * X) + dᵀs * s.t tr(Aᵢ*X) + bᵢᵀs = aᵢ * X ≽ 0 * s is free. * * Remove the free variable s by introducing two slack variables y⁺ ≥ 0 and y⁻ * ≥ 0, and the constraint y⁺ - y⁻ = s. We get a new program without free * variables. * * max tr(Ĉ * X̂) * s.t tr(Âᵢ*X̂) = aᵢ * X̂ ≽ 0 * where Ĉ = diag(C, diag(d), -diag(d)) * X̂ = diag(X, diag(y⁺), diag(y⁻)) * Âᵢ = diag(Aᵢ, diag(bᵢ), -diag(bᵢ)) * * @param[out] X_hat_blocks The block matrix recording X̂. * @param[out] A_hat A_hat[i] is Âᵢ in the documentation. * @param[out] C_hat Ĉ in the documentation. */ void RemoveFreeVariableByTwoSlackVariablesApproach( std::vector<internal::BlockInX>* X_hat_blocks, std::vector<Eigen::SparseMatrix<double>>* A_hat, Eigen::SparseMatrix<double>* C_hat) const; /** * For the problem * * max tr(C * X) + dᵀs * s.t tr(Aᵢ*X) + bᵢᵀs = aᵢ * X ≽ 0 * s is free. * * Remove the free variable s by introducing a slack variable t with the * Lorentz cone constraint t ≥ sqrt(sᵀs). We get a new program without free * variables. * The Lorentz cone constraint t ≥ sqrt(sᵀs) is equivalent to the following * matrix being positive semidefinite (LMI constraint on t and s). * * ⎡ t s(1) s(2) ... s(n)⎤ * ⎢s(1) t 0 ... 0⎥ * ⎢ ... ⎥ * ⎣s(n) 0 0 t⎦ * * To write this LMI in SDPA format, we can introduce a new matrix variable Y * with the constraint Y ≽ 0 * Y(1, 1) is set to t, Y(1, i+1) is set to s(i) * We also introduce the linear equality constraints * Y(i, i) = Y(1, 1) if i >= 1 * Y(i, j) = 0 if i > j >=1 * * After removing the free variables with Y, the SDP problem can be formulated * as below: * * max tr(Ĉ * X̂) * s.t tr(Âᵢ*X̂) = âᵢ * X̂ ≽ 0 * where Ĉ = diag(C, D) * X̂ = diag(X, Y) * Âᵢ = diag(Aᵢ, B̂ᵢ) * and the extra linear equality constraint * Y(i, i) = Y(1, 1) if i >= 1 * Y(i, j) = 0 if i > j >= 1 * where D = ⎡0 dᵀ/2⎤ * ⎣d/2 0⎦ * B̂ᵢ = ⎡0 bᵢᵀ/2⎤ * ⎣bᵢ/2 0⎦ * in both D and B̂ᵢ, the top left 0 is a scalar, while the bottom right 0 is * a matrix of size s.rows() x s.rows() * * @param[out] X_hat_blocks The block matrix recording X̂. * @param[out] A_hat A_hat[i] is Âᵢ in the documentation. * @param[out] rhs_hat rhs_hat[i] is âᵢ in the documentation. * @param[out] C_hat Ĉ in the documentation. */ void RemoveFreeVariableByLorentzConeSlackApproach( std::vector<internal::BlockInX>* X_hat_blocks, std::vector<Eigen::SparseMatrix<double>>* A_hat, Eigen::VectorXd* rhs_hat, Eigen::SparseMatrix<double>* C_hat) const; private: // Go through all the positive semidefinite constraint in @p prog, and // register the corresponding blocks in matrix X for the bound variables of // each PositiveSemidefiniteConstraint. It is possible for two // PositiveSemidefiniteConstraint bindings to have overlapping decision // variables, or for a single PositiveSemidefiniteConstraint to have duplicate // decision variables. We need to impose equality constraints on these entries // in X. We use entries_in_X_for_same_decision_variable to record these // entries in X, so that we can impose the equality constraints later. void DeclareXforPositiveSemidefiniteConstraints( const MathematicalProgram& prog, std::unordered_map<symbolic::Variable::Id, std::vector<EntryInX>>* entries_in_X_for_same_decision_variable); // Some entries in X correspond to the same decision variables. We need to add // the equality constraint on these entries. void AddEqualityConstraintOnXEntriesForSameDecisionVariable( const std::unordered_map<symbolic::Variable::Id, std::vector<EntryInX>>& entries_in_X_for_same_decision_variable); // Adds a linear equality constraint // coeff_prog_vars' * prog_vars + coeff_X_entries' * X_entries + // coeff_free_vars' * free_vars = rhs. // @param coeff_prog_vars The coefficients for program decision variables that // appear in X. // @param prog_vars_indices The indices of the MathematicalProgram decision // variables in X that appear in this constraint. // @param coeff_X_entries The coefficients for @p X_entries. // @param X_entries The entries in X that show up in the linear equality // constraint, X_entries and prog_vars_indices should not overlap. // @param coeff_free_vars The coefficients of free variables. // @param free_vars_indices The indices of the free variables show up in this // constraint, these free variables are not the decision variables in the // MathematicalProgram. // @param rhs The right-hand side of the linear equality constraint. void AddLinearEqualityConstraint( const std::vector<double>& coeff_prog_vars, const std::vector<int>& prog_vars_indices, const std::vector<double>& coeff_X_entries, const std::vector<EntryInX>& X_entries, const std::vector<double>& coeff_free_vars, const std::vector<FreeVariableIndex>& free_vars_indices, double rhs); void RegisterMathematicalProgramDecisionVariables( const MathematicalProgram& prog); // Registers the program decision variable with index `variable_index` into // SDPA and adds lower and upper bounds on that variable. // This function should only be called within // RegisterMathematicalProgramDecisionVariables(). // We might need to add more slack variables into the block diagonal matrix X, // so as to incorporate the bounds as equality constraints. // @param block_index The index of the block in X that this new variable // belongs to. // @param[in/out] new_X_var_count The number of variables in this block before // and after registering this decision variable. void RegisterSingleMathematicalProgramDecisionVariable(double lower_bound, double upper_bound, int variable_index, int block_index, int* new_X_var_count); // Add the bounds on a variable that has been registered. // This function should only be called within // RegisterMathematicalProgramDecisionVariables(). // We might need to add more slack variables into the block diagonal matrix X, // so as to incorporate the bounds as equality constraints. // @param block_index The index of the block in X that the new slack variables // belongs to. // @param[in/out] new_X_var_count The number of variables in this block before // and after adding the variable bounds. void AddBoundsOnRegisteredDecisionVariable(double lower_bound, double upper_bound, int variable_index, int block_index, int* new_X_var_count); // Sum up all the linear costs in prog, store the result in SDPA free format. void AddLinearCostsFromProgram(const MathematicalProgram& prog); // Add both the linear constraints lower <= a'x <= upper and the linear // equality constraints a'x = rhs to SDPA free format. */ void AddLinearConstraintsFromProgram(const MathematicalProgram& prog); template <typename Constraint> void AddLinearConstraintsHelper( const MathematicalProgram& prog, const Binding<Constraint>& linear_constraint, bool is_equality_constraint, int* linear_constraint_slack_entry_in_X_count); void AddLinearMatrixInequalityConstraints(const MathematicalProgram& prog); void AddLorentzConeConstraints(const MathematicalProgram& prog); void AddRotatedLorentzConeConstraints(const MathematicalProgram& prog); // Called at the end of the constructor. void Finalize(); // X_blocks_ just stores the size and category of each block in the // block-diagonal matrix X. std::vector<BlockInX> X_blocks_; std::vector<Eigen::Triplet<double>> C_triplets_; std::vector<Eigen::Triplet<double>> d_triplets_; // gᵢ is the i-th entry of g. Eigen::VectorXd g_; // A_triplets_[i] describes the nonzero entries in Aᵢ std::vector<std::vector<Eigen::Triplet<double>>> A_triplets_; // bᵢ is the i-th column of B. B_triplets records the nonzero entries in B. std::vector<Eigen::Triplet<double>> B_triplets_; /** * Depending on the bounds and whether the variable appears in a PSD cone, a * MathematicalProgram decision variable can be either an entry in X, a free * variable, or a double constant in SDPA free format. * We use std::nullptr_t to indicate that this variable hasn't been registered * into SDPA free format yet. */ std::vector<std::variant<DecisionVariableInSdpaX, FreeVariableIndex, double, std::nullptr_t>> prog_var_in_sdpa_; int num_X_rows_{0}; int num_free_variables_{0}; double constant_min_cost_term_{0.0}; std::vector<Eigen::SparseMatrix<double>> A_; Eigen::SparseMatrix<double> C_; Eigen::SparseMatrix<double> B_; Eigen::SparseMatrix<double> d_; }; } // namespace internal /** * SDPA format doesn't accept free variables, namely the problem it solves is * in this form P1 * * max tr(C * X) * s.t tr(Aᵢ*X) = aᵢ * X ≽ 0. * * Notice that the decision variable X has to be in the proper cone X ≽ 0, and * it doesn't accept free variable (without the conic constraint). On the * other hand, most real-world applications require free variables, namely * problems in this form P2 * * max tr(C * X) + dᵀs * s.t tr(Aᵢ*X) + bᵢᵀs = aᵢ * X ≽ 0 * s is free. * * In order to remove the free variables, we consider three approaches. * 1. Replace a free variable s with two variables s = p - q, p ≥ 0, q ≥ 0. * 2. First write the dual of the problem P2 as D2 * * min aᵀy * s.t ∑ᵢ yᵢAᵢ - C = Z * Z ≽ 0 * Bᵀ * y = d, * * where bᵢᵀ is the i'th row of B. * The last constraint Bᵀ * y = d means y = ŷ + Nt, where Bᵀ * ŷ = d, and N * is the null space of Bᵀ. Hence, D2 is equivalent to the following * problem, D3 * * min aᵀNt + aᵀŷ * s.t ∑ᵢ tᵢFᵢ - (C -∑ᵢ ŷᵢAᵢ) = Z * Z ≽ 0, * * where Fᵢ = ∑ⱼ NⱼᵢAⱼ. D3 is the dual of the following primal problem P3 * without free variables * * max tr((C-∑ᵢ ŷᵢAᵢ)*X̂) + aᵀŷ * s.t tr(FᵢX̂) = (Nᵀa)(i) * X̂ ≽ 0. * * Then (X, s) = (X̂, B⁻¹(a - tr(Aᵢ X̂))) is the solution to the original * problem P2. * 3. Add a slack variable t, with the Lorentz cone constraint t ≥ sqrt(sᵀs). * */ enum class RemoveFreeVariableMethod { kTwoSlackVariables = 1, ///< Approach 1, replace a free variable s as ///< s = y⁺ - y⁻, y⁺ ≥ 0, y⁻ ≥ 0. kNullspace = 2, ///< Approach 2, reformulate the dual problem by considering ///< the nullspace of the linear constraint in the dual. kLorentzConeSlack = 3, ///< Approach 3, add a slack variable t with the ///< lorentz cone constraint t ≥ sqrt(sᵀs). }; std::string to_string(const RemoveFreeVariableMethod&); /** * SDPA is a format to record an SDP problem * * max tr(C*X) * s.t tr(Aᵢ*X) = gᵢ * X ≽ 0 * * or the dual of the problem * * min gᵀy * s.t ∑ᵢ yᵢAᵢ - C ≽ 0 * * where X is a symmetric block diagonal matrix. * The format is described in http://plato.asu.edu/ftp/sdpa_format.txt. Many * solvers, such as CSDP, DSDP, SDPA, sedumi and SDPT3, accept an SDPA format * file as the input. * This function reads a MathematicalProgram that can be formulated as above, * and write an SDPA file. * @param prog a program that contains an optimization program. * @param file_name The name of the file, note that the extension will be added * automatically. * @param method If @p prog contains free variables (i.e., variables without * bounds), then we need to remove these free variables to write the program * in the SDPA format. Please refer to RemoveFreeVariableMethod for details * on how to remove the free variables. @default is * RemoveFreeVariableMethod::kNullspace. * @retval is_success. Returns true if we can generate the SDPA file. The * failure could be * 1. @p prog cannot be captured by the formulation above. * 2. @p prog cannot create a file with the given name, etc. */ bool GenerateSDPA( const MathematicalProgram& prog, const std::string& file_name, RemoveFreeVariableMethod method = RemoveFreeVariableMethod::kNullspace); } // namespace solvers } // namespace drake DRAKE_FORMATTER_AS(, drake::solvers, RemoveFreeVariableMethod, x, drake::solvers::to_string(x))
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/solution_result.cc
#include "drake/solvers/solution_result.h" namespace drake { namespace solvers { std::string to_string(SolutionResult solution_result) { switch (solution_result) { case SolutionResult::kSolutionFound: return "SolutionFound"; case SolutionResult::kInvalidInput: return "InvalidInput"; case SolutionResult::kInfeasibleConstraints: return "InfeasibleConstraints"; case SolutionResult::kUnbounded: return "Unbounded"; case SolutionResult::kInfeasibleOrUnbounded: return "InfeasibleOrUnbounded"; case SolutionResult::kIterationLimit: return "IterationLimit"; case SolutionResult::kSolverSpecificError: return "SolverSpecificError"; case SolutionResult::kDualInfeasible: return "DualInfeasible"; case SolutionResult::kSolutionResultNotSet: return "SolutionResultNotSet"; } // The following lines should not be reached, we add this line due to a defect // in the compiler. throw std::runtime_error("Should not reach here"); } std::ostream& operator<<(std::ostream& os, SolutionResult solution_result) { os << to_string(solution_result); return os; } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/non_convex_optimization_util.h
#pragma once #include <tuple> #include <utility> #include <vector> #include <Eigen/Core> #include "drake/solvers/mathematical_program.h" namespace drake { namespace solvers { // TODO(hongkai.dai): templatize this function, to avoid dynamic memory // allocation. /** * For a non-convex homogeneous quadratic form xᵀQx, where Q is not necessarily * a positive semidefinite matrix, we decompose it as a difference between two * convex homogeneous quadratic forms * xᵀQx = xᵀQ₁x - xᵀQ₂x, * Q₁, Q₂ are positive semidefinite. * To find the optimal Q₁ and Q₂, we solve the following semidefinite * programming problem * min s * s.t s >= trace(Q₁) * s >= trace(Q₂) * Q₁ - Q₂ = (Q + Qᵀ) / 2 * Q₁, Q₂ are positive semidefinite * The decomposition Q = Q₁ - Q₂ can be used later, to solve the non-convex * optimization problem involving a quadratic form xᵀQx. * For more information, please refer to the papers on difference of convex * decomposition, for example * Undominated d.c Decompositions of Quadratic Functions and Applications * to Branch-and-Bound Approaches * By I.M.Bomze and M. Locatelli * Computational Optimization and Applications, 2004 * DC Decomposition of Nonconvex Polynomials with Algebraic Techniques * By A. A. Ahmadi and G. Hall * Mathematical Programming, 2015 * @param Q A square matrix. * @throws std::exception if Q is not square. * @return The optimal decomposition (Q₁, Q₂) */ std::pair<Eigen::MatrixXd, Eigen::MatrixXd> DecomposeNonConvexQuadraticForm( const Eigen::Ref<const Eigen::MatrixXd>& Q); /** * For a non-convex quadratic constraint * lb ≤ xᵀQ₁x - xᵀQ₂x + pᵀy ≤ ub * where Q₁, Q₂ are both positive semidefinite matrices. `y` is a vector that * can overlap with `x`. We relax this non-convex constraint by several convex * constraints. The steps are * 1. Introduce two new variables z₁, z₂, to replace xᵀQ₁x and xᵀQ₂x * respectively. The constraint becomes * <pre> * lb ≤ z₁ - z₂ + pᵀy ≤ ub (1) * </pre> * 2. Ideally, we would like to enforce z₁ = xᵀQ₁x and z₂ = xᵀQ₂x through convex * constraints. To this end, we first bound z₁ and z₂ from below, as * <pre> * z₁ ≥ xᵀQ₁x (2) * z₂ ≥ xᵀQ₂x (3) * </pre> * These two constraints are second order cone * constraints. * 3. To bound z₁ and z₂ from above, we linearize the quadratic forms * xᵀQ₁x and xᵀQ₂x at a point x₀. Due to the convexity of the quadratic * form, we know that given a positive scalar d > 0, there exists a * neighbourhood N(x₀) * around x₀, s.t ∀ x ∈ N(x₀) * <pre> * xᵀQ₁x ≤ 2 x₀ᵀQ₁(x - x₀) + x₀ᵀQ₁x₀ + d (4) * xᵀQ₂x ≤ 2 x₀ᵀQ₂(x - x₀) + x₀ᵀQ₂x₀ + d (5) * </pre> * Notice N(x₀) is the intersection of two ellipsoids, as formulated in (4) * and (5). * Therefore, we also enforce the linear constraints * <pre> * z₁ ≤ 2 x₀ᵀQ₁(x - x₀) + x₀ᵀQ₁x₀ + d (6) * z₂ ≤ 2 x₀ᵀQ₂(x - x₀) + x₀ᵀQ₂x₀ + d (7) * </pre> * So we relax the original non-convex constraint, with the convex * constraints (1)-(3), (6) and (7). * * The trust region is the neighbourhood N(x₀) around x₀, such that the * inequalities (4), (5) are satisfied ∀ x ∈ N(x₀). * * The positive scalar d controls both how much the constraint relaxation is * (the original constraint can be violated by at most d), and how big the trust * region is. * * If there is a solution satisfying the relaxed constraint, this solution * can violate the original non-convex constraint by at most d; on the other * hand, if there is not a solution satisfying the relaxed constraint, it * proves that the original non-convex constraint does not have a solution * in the trust region. * * This approach is outlined in section III of * On Time Optimization of Centroidal Momentum Dynamics * by Brahayam Ponton, Alexander Herzog, Stefan Schaal and Ludovic Righetti, * ICRA, 2018 * * The special cases are when Q₁ = 0 or Q₂ = 0. * 1. When Q₁ = 0, the original constraint becomes * lb ≤ -xᵀQ₂x + pᵀy ≤ ub * If ub = +∞, then the original constraint is the convex rotated Lorentz * cone constraint xᵀQ₂x ≤ pᵀy - lb. The user should not call this function * to relax this convex constraint. * @throws std::exception if Q₁ = 0 and ub = +∞. * If ub < +∞, then we introduce a new variable z, with the constraints * lb ≤ -z + pᵀy ≤ ub * z ≥ xᵀQ₂x * z ≤ 2 x₀ᵀQ₂(x - x₀) + x₀ᵀQ₂x₀ + d * 2. When Q₂ = 0, the constraint becomes * lb ≤ xᵀQ₁x + pᵀy ≤ ub * If lb = -∞, then the original constraint is the convex rotated Lorentz * cone constraint xᵀQ₁x ≤ ub - pᵀy. The user should not call this function * to relax this convex constraint. * @throws std::exception if Q₂ = 0 and lb = -∞. * If lb > -∞, then we introduce a new variable z, with the constraints * lb ≤ z + pᵀy ≤ ub * z ≥ xᵀQ₁x * z ≤ 2 x₀ᵀQ₁(x - x₀) + x₀ᵀQ₁x₀ + d * 3. If both Q₁ and Q₂ are zero, then the original constraint is a convex * linear constraint lb ≤ pᵀx ≤ ub. The user should not call this function * to relax this convex constraint. Throw a runtime error. * @param prog The MathematicalProgram to which the relaxed constraints are * added. * @param x The decision variables which appear in the original non-convex * constraint. * @param Q1 A positive semidefinite matrix. * @param Q2 A positive semidefinite matrix. * @param y A vector, the variables in the linear term of the quadratic form. * @param p A vector, the linear coefficients of the quadratic form. * @param linearization_point The vector `x₀` in the documentation above. * @param lower_bound The left-hand side of the original non-convex constraint. * @param upper_bound The right-hand side of the original non-convex constraint. * @param trust_region_gap The user-specified positive scalar, `d` in * the documentation above. This gap determines both the maximal constraint * violation and the size of the trust region. * @retval <linear_constraint, rotated_lorentz_cones, z> * linear_constraint includes (1)(6)(7) * rotated_lorentz_cones are (2) (3) * When either Q1 or Q2 is zero, rotated_lorentz_cones contains only one rotated * Lorentz cone, either (2) or (3). * z is the newly added variable. * @pre 1. Q1, Q2 are positive semidefinite. * 2. d is positive. * 3. Q1, Q2, x, x₀ are all of the consistent size. * 4. p and y are of the consistent size. * 5. lower_bound ≤ upper_bound. * @throws std::exception when the precondition is not satisfied. * @ingroup solver_evaluators */ std::tuple<Binding<LinearConstraint>, std::vector<Binding<RotatedLorentzConeConstraint>>, VectorXDecisionVariable> AddRelaxNonConvexQuadraticConstraintInTrustRegion( MathematicalProgram* prog, const Eigen::Ref<const VectorXDecisionVariable>& x, const Eigen::Ref<const Eigen::MatrixXd>& Q1, const Eigen::Ref<const Eigen::MatrixXd>& Q2, const Eigen::Ref<const VectorXDecisionVariable>& y, const Eigen::Ref<const Eigen::VectorXd>& p, double lower_bound, double upper_bound, const Eigen::Ref<const Eigen::VectorXd>& linearization_point, double trust_region_gap); } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/solver_id.h
#pragma once #include <functional> #include <ostream> #include <string> #include "drake/common/drake_copyable.h" #include "drake/common/fmt_ostream.h" #include "drake/common/hash.h" #include "drake/common/reset_after_move.h" namespace drake { namespace solvers { /** Identifies a SolverInterface implementation. A moved-from instance is guaranteed to be empty and will not compare equal to any non-empty ID. */ class SolverId { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(SolverId) ~SolverId() = default; /** Constructs a specific, known solver type. Internally, a hidden integer is allocated and assigned to this instance; all instances that share an integer (including copies of this instance) are considered equal. The solver names are not enforced to be unique, though we recommend that they remain so in practice. For best performance, choose a name that is 15 characters or less, so that it fits within the libstdc++ "small string" optimization ("SSO"). */ explicit SolverId(std::string name); const std::string& name() const { return name_; } /** Implements the @ref hash_append concept. */ template <class HashAlgorithm> friend void hash_append(HashAlgorithm& hasher, const SolverId& item) noexcept { using drake::hash_append; hash_append(hasher, int{item.id_}); // We do not send the name_ to the hasher, because the id_ is already // unique across all instances. } private: friend bool operator==(const SolverId&, const SolverId&); friend bool operator!=(const SolverId&, const SolverId&); friend struct std::less<SolverId>; reset_after_move<int> id_; std::string name_; }; bool operator==(const SolverId&, const SolverId&); bool operator!=(const SolverId&, const SolverId&); std::ostream& operator<<(std::ostream&, const SolverId&); } // namespace solvers } // namespace drake namespace std { /* Provides std::less<drake::solvers::SolverId>. */ template <> struct less<drake::solvers::SolverId> { bool operator()(const drake::solvers::SolverId& lhs, const drake::solvers::SolverId& rhs) const { return lhs.id_ < rhs.id_; } }; /* Provides std::hash<drake::solvers::SolverId>. */ template <> struct hash<drake::solvers::SolverId> : public drake::DefaultHash {}; } // namespace std // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <> struct formatter<drake::solvers::SolverId> : drake::ostream_formatter {}; } // namespace fmt
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/unrevised_lemke_solver.h
#pragma once #include <algorithm> #include <fstream> #include <limits> #include <map> #include <string> #include <utility> #include <vector> #include <Eigen/SparseCore> #include "drake/common/drake_copyable.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solver_base.h" namespace drake { namespace solvers { /// Non-template class for UnrevisedLemkeSolver<T> constants. class UnrevisedLemkeSolverId { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(UnrevisedLemkeSolverId); UnrevisedLemkeSolverId() = delete; /// @return same as SolverInterface::solver_id() static SolverId id(); }; /// A class for the Unrevised Implementation of Lemke Algorithm's for solving /// Linear Complementarity Problems (LCPs). See MobyLcpSolver for a description /// of LCPs. This code makes extensive use of the following document: /// [Dai 2018] Dai, H. and Drumwright, E. Computing the Principal Pivoting /// Transform for Solving Linear Complementarity Problems with Lemke's /// Algorithm. (2018, located in doc/pivot_column.pdf). template <class T> class UnrevisedLemkeSolver final : public SolverBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(UnrevisedLemkeSolver) UnrevisedLemkeSolver(); ~UnrevisedLemkeSolver() final; /// Calculates the zero tolerance that the solver would compute if the user /// does not specify a tolerance. template <class U> static U ComputeZeroTolerance(const MatrixX<U>& M) { return M.rows() * M.template lpNorm<Eigen::Infinity>() * (2 * std::numeric_limits<double>::epsilon()); } /// Checks whether a given candidate solution to the LCP Mz + q = w, z ≥ 0, /// w ≥ 0, zᵀw = 0 is satisfied to a given tolerance. If the tolerance is /// non-positive, this method computes a reasonable tolerance using M. static bool IsSolution(const MatrixX<T>& M, const VectorX<T>& q, const VectorX<T>& z, T zero_tol = -1); /// Lemke's Algorithm for solving LCPs in the matrix class E, which contains /// all strictly semimonotone matrices, all P-matrices, and all strictly /// copositive matrices. The solver can be applied with occasional success to /// problems outside of its guaranteed matrix classes. Lemke's Algorithm is /// described in [Cottle 1992], Section 4.4. /// /// The solver will denote failure on return if it exceeds a problem-size /// dependent number of iterations. /// @param[in] M the LCP matrix. /// @param[in] q the LCP vector. /// @param[in,out] z the solution to the LCP on return (if the solver /// succeeds). If the length of z is equal to the length of q, /// the solver will attempt to use the basis from the last /// solution. This strategy can prove exceptionally /// fast if solutions differ little between successive calls. /// If the solver fails (returns `false`), /// `z` will be set to the zero vector on return. /// @param[out] num_pivots the number of pivots used, on return. /// @param[in] zero_tol The tolerance for testing against zero. If the /// tolerance is negative (default) the solver will determine a /// generally reasonable tolerance. /// @returns `true` if the solver computes a solution to floating point /// tolerances (i.e., if IsSolution() returns `true` on the problem) /// and `false` otherwise. /// @throws std::exception if M is not square or the dimensions of M do not /// match the length of q. /// /// * [Cottle 1992] R. Cottle, J.-S. Pang, and R. Stone. The Linear /// Complementarity Problem. Academic Press, 1992. bool SolveLcpLemke(const MatrixX<T>& M, const VectorX<T>& q, VectorX<T>* z, int* num_pivots, const T& zero_tol = T(-1)) const; /// @name Static versions of the instance methods with similar names. //@{ static SolverId id(); static bool is_available(); static bool is_enabled(); static bool ProgramAttributesSatisfied(const MathematicalProgram&); //@} // A using-declaration adds these methods into our class's Doxygen. using SolverBase::Solve; private: friend class UnrevisedLemkePrivateTests; friend class UnrevisedLemkePrivateTests_SelectSubMatrixWithCovering_Test; friend class UnrevisedLemkePrivateTests_SelectSubColumnWithCovering_Test; friend class UnrevisedLemkePrivateTests_SelectSubVector_Test; friend class UnrevisedLemkePrivateTests_SetSubVector_Test; friend class UnrevisedLemkePrivateTests_ValidateIndices_Test; friend class UnrevisedLemkePrivateTests_IsEachUnique_Test; friend class UnrevisedLemkePrivateTests_LemkePivot_Test; friend class UnrevisedLemkePrivateTests_ConstructLemkeSolution_Test; friend class UnrevisedLemkePrivateTests_DetermineIndexSets_Test; friend class UnrevisedLemkePrivateTests_FindBlockingIndex_Test; friend class UnrevisedLemkePrivateTests_FindBlockingIndexCycling_Test; friend class UnrevisedLemkePrivateTests_FindComplementIndex_Test; struct LemkeIndexSets { std::vector<int> alpha, alpha_prime; std::vector<int> alpha_bar, alpha_bar_prime; std::vector<int> beta, beta_prime; std::vector<int> beta_bar, beta_bar_prime; }; // A structure for holding a linear complementarity problem variable. class LCPVariable { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(LCPVariable) LCPVariable() {} LCPVariable(bool z, int index) : index_{index}, z_{z} {} bool is_z() const { return z_; } int index() const { return index_; } // Gets the complement of this variable. LCPVariable Complement() const { DRAKE_ASSERT(index_ >= 0); LCPVariable comp; comp.z_ = !z_; comp.index_ = index_; return comp; } // Compares two LCP variables for equality. bool operator==(const LCPVariable& v) const { DRAKE_ASSERT(index_ >= 0 && v.index_ >= 0); return (z_ == v.z_ && index_ == v.index_); } // Comparison operator for using LCPVariable as a key. bool operator<(const LCPVariable& v) const { DRAKE_ASSERT(index_ >= 0 && v.index_ >= 0); if (index_ < v.index_) { return true; } else { if (index_ > v.index_) { return false; } else { // If here, the indices are equal. We will arbitrarily order w before // z (alphabetical ordering). return (!z_ && v.z_); } } } private: int index_{-1}; // Index of the variable in the problem, 0...n. n // indicates that the variable is artificial. -1 // indicates that the index is uninitialized. bool z_{true}; // Is this a z variable or a w variable? }; void DoSolve(const MathematicalProgram&, const Eigen::VectorXd&, const SolverOptions&, MathematicalProgramResult*) const final; static void SelectSubMatrixWithCovering(const MatrixX<T>& in, const std::vector<int>& rows, const std::vector<int>& cols, MatrixX<T>* out); static void SelectSubColumnWithCovering(const MatrixX<T>& in, const std::vector<int>& rows, int column, VectorX<T>* out); static void SelectSubVector(const VectorX<T>& in, const std::vector<int>& rows, VectorX<T>* out); static void SetSubVector(const VectorX<T>& v_sub, const std::vector<int>& indices, VectorX<T>* v); static bool ValidateIndices(const std::vector<int>& row_indices, const std::vector<int>& col_indices, int num_rows, int num_cols); static bool ValidateIndices(const std::vector<int>& row_indices, int vector_size); static bool IsEachUnique(const std::vector<LCPVariable>& vars); bool LemkePivot(const MatrixX<T>& M, const VectorX<T>& q, int driving_index, T zero_tol, VectorX<T>* M_bar_col, VectorX<T>* q_bar) const; bool ConstructLemkeSolution(const MatrixX<T>& M, const VectorX<T>& q, int artificial_index, T zero_tol, VectorX<T>* z) const; int FindComplementIndex(const LCPVariable& query) const; void DetermineIndexSets() const; bool FindBlockingIndex(const T& zero_tol, const VectorX<T>& matrix_col, const VectorX<T>& ratios, int* blocking_index) const; bool IsArtificial(const LCPVariable& v) const; typedef std::vector<LCPVariable> LCPVariableVector; // Structure for mapping a vector of independent variables to a selection // index. class LCPVariableVectorComparator { public: // This does a lexicographic comparison. bool operator()(const LCPVariableVector& v1, const LCPVariableVector& v2) const { DRAKE_DEMAND(v1.size() == v2.size()); // Copy the vectors. sorted1_ = v1; sorted2_ = v2; // Determine the variables in sorted order because we want to consider // all permutations of a set of variables as the same. std::sort(sorted1_.begin(), sorted1_.end()); std::sort(sorted2_.begin(), sorted2_.end()); // Now do the lexicographic comparison. for (int i = 0; i < static_cast<int>(v1.size()); ++i) { if (sorted1_[i] < sorted2_[i]) { return true; } else { if (sorted2_[i] < sorted1_[i]) return false; } } // If still here, they're equal. return false; } private: // Two temporary vectors for storing sorted versions of vectors. mutable LCPVariableVector sorted1_, sorted2_; }; // Note: the mutable variables below are used in place of local variables both // to minimize heap allocations during the LCP solution process and to // facilitate warmstarting. // Temporary variable for determining index sets (i.e., α, α', α̅, α̅', etc. // from [Dai 2018]). The first int of each pair stores the // variable's own "internal" index and the second stores the index of the // variable in the requisite array ("independent w", "dependent w", // "independent z", and "dependent z") in [Dai 2018]. mutable std::vector<std::pair<int, int>> variable_and_array_indices_; // Mapping from an LCP variable to the index of that variable in // indep_variables. mutable std::map<LCPVariable, int> indep_variables_indices_; // Maps tuples of independent variables to the variable selected for pivoting // when multiple pivoting choices are possible. If the LCP algorithm pivots // such that a tuple of independent variables is detected that has been seen // before, we would call this "cycling". We eliminate cycling by never // selecting the same variable for pivoting twice *from a given pivot*. mutable std::map<LCPVariableVector, int, LCPVariableVectorComparator> selections_; // These temporary matrices and vectors are members to facilitate minimizing // memory allocations/deallocations. Changing their value between invocations // of the LCP solver will not change the resulting computation. mutable MatrixX<T> M_alpha_beta_, M_alpha_bar_beta_; mutable VectorX<T> q_alpha_, q_alpha_bar_, q_prime_beta_prime_, q_prime_alpha_bar_prime_, e_, M_prime_driving_beta_prime_, M_prime_driving_alpha_bar_prime_, g_alpha_, g_alpha_bar_; // The index sets for the Lemke Algorithm and is a member variable to // permit warmstarting. Changing the index set between invocations of the LCP // solver will not change the resulting computation. mutable LemkeIndexSets index_sets_; // The partitions of independent and dependent variables (denoted z' and w', // respectively, in [Dai 2018]. These have been made member // variables to permit warmstarting. Changing these sets between invocations // of the LCP solver will not change the resulting computation. mutable std::vector<LCPVariable> indep_variables_, dep_variables_; }; } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/choose_best_solver.h
#pragma once #include <memory> #include <set> #include <vector> #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solver_id.h" #include "drake/solvers/solver_interface.h" namespace drake { namespace solvers { /** * Choose the best solver given the formulation in the optimization program and * the availability of the solvers. * @throws std::exception if there is no available solver for @p prog. */ [[nodiscard]] SolverId ChooseBestSolver(const MathematicalProgram& prog); /** * Returns the set of solvers known to ChooseBestSolver. */ [[nodiscard]] const std::set<SolverId>& GetKnownSolvers(); /** * Given the solver ID, create the solver with the matching ID. * @throws std::exception if there is no matching solver. */ [[nodiscard]] std::unique_ptr<SolverInterface> MakeSolver(const SolverId& id); /** * Makes the first available and enabled solver. If no solvers are available, * throws a std::exception. */ [[nodiscard]] std::unique_ptr<SolverInterface> MakeFirstAvailableSolver( const std::vector<SolverId>& solver_ids); /** * Returns the list of available and enabled solvers that definitely accept all * programs of the given program type. * The order of the returned SolverIds reflects an approximate order of * preference, from most preferred (front) to least preferred (back). Because we * are analyzing only based on the program type rather than a specific program, * it's possible that solvers later in the list would perform better in certain * situations. To obtain the truly best solver, using ChooseBestSolver() * instead. * @note If a solver only accepts a subset of the program type, then that solver * is not included in the returned results. For example * EqualityConstrainedQPSolver doesn't accept programs with inequality linear * constraints, so it doesn't show up in the return of * GetAvailableSolvers(ProgramType::kQP). */ [[nodiscard]] std::vector<SolverId> GetAvailableSolvers(ProgramType prog_type); } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/solver_options.h
#pragma once #include <ostream> #include <string> #include <unordered_map> #include <unordered_set> #include <variant> #include "drake/common/drake_assert.h" #include "drake/common/drake_copyable.h" #include "drake/common/fmt_ostream.h" #include "drake/solvers/common_solver_option.h" #include "drake/solvers/solver_id.h" namespace drake { namespace solvers { /** * Stores options for multiple solvers. This interface does not * do any verification of solver parameters. It does not even verify that * the specified solver exists. Use this only when you have * particular knowledge of what solver is being invoked, and exactly * what tuning is required. * * Supported solver names/options: * * "SNOPT" -- Parameter names and values as specified in SNOPT * User's Guide section 7.7 "Description of the optional parameters", * used as described in section 7.5 for snSet(). * The SNOPT user guide can be obtained from * https://web.stanford.edu/group/SOL/guides/sndoc7.pdf * * "IPOPT" -- Parameter names and values as specified in IPOPT users * guide section "Options Reference" * https://coin-or.github.io/Ipopt/OPTIONS.html * * "NLOPT" -- Parameter names and values are specified in * https://nlopt.readthedocs.io/en/latest/NLopt_C-plus-plus_Reference/ (in the * Stopping criteria section). Besides these parameters, the user can specify * "algorithm" using a string of the algorithm name. The complete set of * algorithms is listed in "nlopt_algorithm_to_string()" function in * github.com/stevengj/nlopt/blob/master/src/api/general.c. If you would like to * use certain algorithm, for example NLOPT_LD_SLSQP, call * `SetOption(NloptSolver::id(), NloptSolver::AlgorithmName(), "LD_SLSQP");` * * "GUROBI" -- Parameter name and values as specified in Gurobi Reference * Manual, section 10.2 "Parameter Descriptions" * https://www.gurobi.com/documentation/10.0/refman/parameters.html * * "SCS" -- Parameter name and values as specified in the struct SCS_SETTINGS in * SCS header file https://github.com/cvxgrp/scs/blob/master/include/scs.h * Note that the SCS code on github master might be more up-to-date than the * version used in Drake. * * "MOSEK™" -- Parameter name and values as specified in Mosek Reference * https://docs.mosek.com/9.3/capi/parameters.html * * "OSQP" -- Parameter name and values as specified in OSQP Reference * https://osqp.org/docs/interfaces/solver_settings.html#solver-settings * * "Clarabel" -- Parameter name and values as specified in Clarabel * https://oxfordcontrol.github.io/ClarabelDocs/stable/api_settings/ * Note that `direct_solve_method` is not supported in Drake yet. * Clarabel's boolean options should be passed as integers (0 or 1). */ class SolverOptions { public: SolverOptions() = default; DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(SolverOptions) /** The values stored in SolverOptions can be double, int, or string. * In the future, we might re-order or add more allowed types without any * deprecation period, so be sure to use std::visit or std::get<T> to * retrieve the variant's value in a future-proof way. */ using OptionValue = std::variant<double, int, std::string>; /** Sets a double-valued solver option for a specific solver. * @pydrake_mkdoc_identifier{double_option} */ void SetOption(const SolverId& solver_id, const std::string& solver_option, double option_value); /** Sets an integer-valued solver option for a specific solver. * @pydrake_mkdoc_identifier{int_option} */ void SetOption(const SolverId& solver_id, const std::string& solver_option, int option_value); /** Sets a string-valued solver option for a specific solver. * @pydrake_mkdoc_identifier{str_option} */ void SetOption(const SolverId& solver_id, const std::string& solver_option, const std::string& option_value); /** Sets a common option for all solvers supporting that option (for example, * printing the progress in each iteration). If the solver doesn't support * the option, the option is ignored. * @pydrake_mkdoc_identifier{common_option} */ void SetOption(CommonSolverOption key, OptionValue value); const std::unordered_map<std::string, double>& GetOptionsDouble( const SolverId& solver_id) const; const std::unordered_map<std::string, int>& GetOptionsInt( const SolverId& solver_id) const; const std::unordered_map<std::string, std::string>& GetOptionsStr( const SolverId& solver_id) const; /** * Gets the common options for all solvers. Refer to CommonSolverOption for * more details. */ const std::unordered_map<CommonSolverOption, OptionValue>& common_solver_options() const { return common_solver_options_; } /** Returns the kPrintFileName set via CommonSolverOption, or else an empty * string if the option has not been set. */ std::string get_print_file_name() const; /** Returns the kPrintToConsole set via CommonSolverOption, or else false if * the option has not been set. */ bool get_print_to_console() const; template <typename T> const std::unordered_map<std::string, T>& GetOptions( const SolverId& solver_id) const { if constexpr (std::is_same_v<T, double>) { return GetOptionsDouble(solver_id); } else if constexpr (std::is_same_v<T, int>) { return GetOptionsInt(solver_id); } else if constexpr (std::is_same_v<T, std::string>) { return GetOptionsStr(solver_id); } DRAKE_UNREACHABLE(); } /** Returns the IDs that have any option set. */ std::unordered_set<SolverId> GetSolverIds() const; /** * Merges the other solver options into this. If `other` and `this` option * both define the same option for the same solver, we ignore then one from * `other` and keep the one from `this`. */ void Merge(const SolverOptions& other); /** * Returns true if `this` and `other` have exactly the same solvers, with * exactly the same keys and values for the options for each solver. */ bool operator==(const SolverOptions& other) const; /** * Negate operator==. */ bool operator!=(const SolverOptions& other) const; /** * Check if for a given solver_id, the option keys are included in * double_keys, int_keys and str_keys. * @param solver_id If this SolverOptions has set options for this solver_id, * then we check if the option keys are a subset of `double_keys`, `int_keys` * and `str_keys`. * @param double_keys The set of allowable keys for double options. * @param int_keys The set of allowable keys for int options. * @param str_keys The set of allowable keys for string options. * @throws std::exception if the solver contains un-allowed options. */ void CheckOptionKeysForSolver( const SolverId& solver_id, const std::unordered_set<std::string>& allowable_double_keys, const std::unordered_set<std::string>& allowable_int_keys, const std::unordered_set<std::string>& allowable_str_keys) const; private: std::unordered_map<SolverId, std::unordered_map<std::string, double>> solver_options_double_{}; std::unordered_map<SolverId, std::unordered_map<std::string, int>> solver_options_int_{}; std::unordered_map<SolverId, std::unordered_map<std::string, std::string>> solver_options_str_{}; std::unordered_map<CommonSolverOption, OptionValue> common_solver_options_{}; }; std::string to_string(const SolverOptions&); std::ostream& operator<<(std::ostream&, const SolverOptions&); } // namespace solvers } // namespace drake // TODO(jwnimmer-tri) Add a real formatter and deprecate the operator<<. namespace fmt { template <> struct formatter<drake::solvers::SolverOptions> : drake::ostream_formatter {}; } // namespace fmt
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/mixed_integer_optimization_util.cc
#include "drake/solvers/mixed_integer_optimization_util.h" #include "drake/math/gray_code.h" #include "drake/solvers/integer_optimization_util.h" using drake::symbolic::Expression; namespace drake { namespace solvers { std::string to_string(IntervalBinning binning) { switch (binning) { case IntervalBinning::kLinear: { return "linear_binning"; } case IntervalBinning::kLogarithmic: { return "logarithmic_binning"; } } DRAKE_UNREACHABLE(); } std::ostream& operator<<(std::ostream& os, const IntervalBinning& binning) { os << to_string(binning); return os; } void AddLogarithmicSos2Constraint( MathematicalProgram* prog, const Eigen::Ref<const VectorX<symbolic::Expression>>& lambda, const Eigen::Ref<const VectorX<symbolic::Expression>>& y) { const int num_lambda = lambda.rows(); for (int i = 0; i < num_lambda; ++i) { prog->AddLinearConstraint(lambda(i) >= 0); prog->AddLinearConstraint(lambda(i) <= 1); } prog->AddLinearConstraint(lambda.sum() == 1); const int num_interval = num_lambda - 1; const int num_binary_vars = CeilLog2(num_interval); DRAKE_DEMAND(y.rows() == num_binary_vars); const auto gray_codes = math::CalculateReflectedGrayCodes(num_binary_vars); DRAKE_ASSERT(y.rows() == num_binary_vars); for (int j = 0; j < num_binary_vars; ++j) { symbolic::Expression lambda_sum1 = gray_codes(0, j) == 1 ? lambda(0) : 0; symbolic::Expression lambda_sum2 = gray_codes(0, j) == 0 ? lambda(0) : 0; for (int i = 1; i < num_lambda - 1; ++i) { lambda_sum1 += (gray_codes(i - 1, j) == 1 && gray_codes(i, j) == 1) ? lambda(i) : 0; lambda_sum2 += (gray_codes(i - 1, j) == 0 && gray_codes(i, j) == 0) ? lambda(i) : 0; } lambda_sum1 += gray_codes(num_lambda - 2, j) == 1 ? lambda(num_lambda - 1) : 0; lambda_sum2 += gray_codes(num_lambda - 2, j) == 0 ? lambda(num_lambda - 1) : 0; prog->AddLinearConstraint(lambda_sum1 <= y(j)); prog->AddLinearConstraint(lambda_sum2 <= 1 - y(j)); } } void AddSos2Constraint( MathematicalProgram* prog, const Eigen::Ref<const VectorX<symbolic::Expression>>& lambda, const Eigen::Ref<const VectorX<symbolic::Expression>>& y) { if (lambda.rows() != y.rows() + 1) { throw std::runtime_error( "The size of y and lambda do not match when adding the SOS2 " "constraint."); } prog->AddLinearConstraint(lambda.sum() == 1); prog->AddLinearConstraint(lambda(0) <= y(0) && lambda(0) >= 0); for (int i = 1; i < y.rows(); ++i) { prog->AddLinearConstraint(lambda(i) <= y(i - 1) + y(i) && lambda(i) >= 0); } prog->AddLinearConstraint(lambda.tail<1>()(0) >= 0 && lambda.tail<1>()(0) <= y.tail<1>()(0)); prog->AddLinearConstraint(y.sum() == 1); } void AddLogarithmicSos1Constraint( MathematicalProgram* prog, const Eigen::Ref<const VectorX<symbolic::Expression>>& lambda, const Eigen::Ref<const VectorXDecisionVariable>& y, const Eigen::Ref<const Eigen::MatrixXi>& binary_encoding) { const int num_lambda = lambda.rows(); const int num_y = CeilLog2(num_lambda); DRAKE_DEMAND(binary_encoding.rows() == num_lambda && binary_encoding.cols() == num_y); DRAKE_DEMAND(y.rows() == num_y); for (int i = 0; i < num_y; ++i) { DRAKE_ASSERT(y(i).get_type() == symbolic::Variable::Type::BINARY); } for (int i = 0; i < num_lambda; ++i) { prog->AddLinearConstraint(lambda(i) >= 0); } prog->AddLinearConstraint(lambda.sum() == 1); for (int j = 0; j < num_y; ++j) { symbolic::Expression lambda_sum1{0}; symbolic::Expression lambda_sum2{0}; for (int k = 0; k < num_lambda; ++k) { if (binary_encoding(k, j) == 1) { lambda_sum1 += lambda(k); } else if (binary_encoding(k, j) == 0) { lambda_sum2 += lambda(k); } else { throw std::runtime_error( "The binary_encoding entry can be only 0 or 1."); } } prog->AddLinearConstraint(lambda_sum1 <= y(j)); prog->AddLinearConstraint(lambda_sum2 <= 1 - y(j)); } } std::pair<VectorX<symbolic::Variable>, VectorX<symbolic::Variable>> AddLogarithmicSos1Constraint(MathematicalProgram* prog, int num_lambda) { const int num_y = CeilLog2(num_lambda); const Eigen::MatrixXi binary_encoding = math::CalculateReflectedGrayCodes(num_y).topRows(num_lambda); auto lambda = prog->NewContinuousVariables(num_lambda); auto y = prog->NewBinaryVariables(num_y); AddLogarithmicSos1Constraint(prog, lambda.cast<symbolic::Expression>(), y, binary_encoding); return std::make_pair(lambda, y); } void AddBilinearProductMcCormickEnvelopeMultipleChoice( MathematicalProgram* prog, const symbolic::Variable& x, const symbolic::Variable& y, const symbolic::Expression& w, const Eigen::Ref<const Eigen::VectorXd>& phi_x, const Eigen::Ref<const Eigen::VectorXd>& phi_y, const Eigen::Ref<const VectorX<symbolic::Expression>>& Bx, const Eigen::Ref<const VectorX<symbolic::Expression>>& By) { const int m = phi_x.rows() - 1; const int n = phi_y.rows() - 1; DRAKE_ASSERT(Bx.rows() == m); DRAKE_ASSERT(By.rows() == n); const auto x_bar = prog->NewContinuousVariables(n, x.get_name() + "_x_bar"); const auto y_bar = prog->NewContinuousVariables(m, y.get_name() + "_y_bar"); prog->AddLinearEqualityConstraint(x_bar.cast<Expression>().sum() - x, 0); prog->AddLinearEqualityConstraint(y_bar.cast<Expression>().sum() - y, 0); const auto Bxy = prog->NewContinuousVariables( m, n, x.get_name() + "_" + y.get_name() + "_Bxy"); prog->AddLinearEqualityConstraint( Bxy.cast<Expression>().rowwise().sum().sum(), 1); for (int i = 0; i < m; ++i) { prog->AddLinearConstraint( y_bar(i) >= phi_y.head(n).dot(Bxy.row(i).transpose().cast<Expression>())); prog->AddLinearConstraint( y_bar(i) <= phi_y.tail(n).dot(Bxy.row(i).transpose().cast<Expression>())); } for (int j = 0; j < n; ++j) { prog->AddLinearConstraint(x_bar(j) >= phi_x.head(m).dot(Bxy.col(j).cast<Expression>())); prog->AddLinearConstraint(x_bar(j) <= phi_x.tail(m).dot(Bxy.col(j).cast<Expression>())); } // The right-hand side of the constraint on w, we will implement // w >= w_constraint_rhs(0) // w >= w_constraint_rhs(1) // w <= w_constraint_rhs(2) // w <= w_constraint_rhs(3) Vector4<symbolic::Expression> w_constraint_rhs(0, 0, 0, 0); w_constraint_rhs(0) = x_bar.cast<Expression>().dot(phi_y.head(n)) + y_bar.cast<Expression>().dot(phi_x.head(m)); w_constraint_rhs(1) = x_bar.cast<Expression>().dot(phi_y.tail(n)) + y_bar.cast<Expression>().dot(phi_x.tail(m)); w_constraint_rhs(2) = x_bar.cast<Expression>().dot(phi_y.head(n)) + y_bar.cast<Expression>().dot(phi_x.tail(m)); w_constraint_rhs(3) = x_bar.cast<Expression>().dot(phi_y.tail(n)) + y_bar.cast<Expression>().dot(phi_x.head(m)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { prog->AddConstraint( // +v converts a symbolic variable v to a symbolic expression. CreateLogicalAndConstraint(+Bx(i), +By(j), +Bxy(i, j))); w_constraint_rhs(0) -= phi_x(i) * phi_y(j) * Bxy(i, j); w_constraint_rhs(1) -= phi_x(i + 1) * phi_y(j + 1) * Bxy(i, j); w_constraint_rhs(2) -= phi_x(i + 1) * phi_y(j) * Bxy(i, j); w_constraint_rhs(3) -= phi_x(i) * phi_y(j + 1) * Bxy(i, j); } } prog->AddLinearConstraint(w >= w_constraint_rhs(0)); prog->AddLinearConstraint(w >= w_constraint_rhs(1)); prog->AddLinearConstraint(w <= w_constraint_rhs(2)); prog->AddLinearConstraint(w <= w_constraint_rhs(3)); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/gurobi_solver.cc
#include "drake/solvers/gurobi_solver.h" #include <algorithm> #include <charconv> #include <cmath> #include <fstream> #include <limits> #include <optional> #include <stdexcept> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <Eigen/Core> #include <Eigen/SparseCore> #include <fmt/format.h> // TODO(jwnimmer-tri) Eventually resolve these warnings. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" // NOLINTNEXTLINE(build/include) False positive due to weird include style. #include "gurobi_c.h" #include "drake/common/drake_assert.h" #include "drake/common/find_resource.h" #include "drake/common/scope_exit.h" #include "drake/common/scoped_singleton.h" #include "drake/common/text_logging.h" #include "drake/math/eigen_sparse_triplet.h" #include "drake/solvers/aggregate_costs_constraints.h" #include "drake/solvers/gurobi_solver_internal.h" #include "drake/solvers/mathematical_program.h" // TODO(hongkai.dai): GurobiSolver class should store data member such as // GRB_model, GRB_env, is_new_variables, etc. namespace drake { namespace solvers { namespace { // Returns the (base) URL for Gurobi's online reference manual. std::string refman() { return fmt::format("https://www.gurobi.com/documentation/{}.{}/refman", GRB_VERSION_MAJOR, GRB_VERSION_MINOR); } // Information to be passed through a Gurobi C callback to // grant it information about its problem (the host // MathematicalProgram prog, and which decision variables // are not represented in prog), and what user functions // are present for handling the callback. // TODO(gizatt) This struct can be replaced with a ptr to // the GurobiSolver class (or the callback can shell to a // method on that class) once the above TODO(hongkai.dai) is // completed. It might be able to be further reduced if // GurobiSolver subclasses GRBCallback in the Gurobi C++ API. struct GurobiCallbackInformation { const MathematicalProgram* prog{}; std::vector<bool> is_new_variable; // Used in callbacks to store raw Gurobi variable values. std::vector<double> solver_sol_vector; // Used in callbacks to store variable values that appear // in the MathematicalProgram (which are a subset of the // Gurobi variable values). Eigen::VectorXd prog_sol_vector; GurobiSolver::MipNodeCallbackFunction mip_node_callback; GurobiSolver::MipSolCallbackFunction mip_sol_callback; MathematicalProgramResult* result{}; }; // Utility that, given a raw Gurobi solution vector, a container // in which to populate the Mathematical Program solution vector, // and a mapping of which elements should be accepted from the Gurobi // solution vector, sets a MathematicalProgram's solution to the // Gurobi solution. void SetProgramSolutionVector(const std::vector<bool>& is_new_variable, const std::vector<double>& solver_sol_vector, Eigen::VectorXd* prog_sol_vector) { int k = 0; for (size_t i = 0; i < is_new_variable.size(); ++i) { if (!is_new_variable[i]) { (*prog_sol_vector)(k) = solver_sol_vector[i]; k++; } } } // @param gurobi_dual_solutions gurobi_dual_solutions(i) is the dual solution // for the variable bound lower <= gurobi_var(i) <= upper. This is extracted // from "RC" (stands for reduced cost) field from gurobi model. // @param bb_con_dual_indices Maps each bounding box constraint to the indices // of its dual variables for both lower and upper bounds. void SetBoundingBoxDualSolution( const MathematicalProgram& prog, const std::vector<double>& gurobi_dual_solutions, const std::unordered_map<Binding<BoundingBoxConstraint>, std::pair<std::vector<int>, std::vector<int>>>& bb_con_dual_indices, MathematicalProgramResult* result) { for (const auto& binding : prog.bounding_box_constraints()) { Eigen::VectorXd dual_sol = Eigen::VectorXd::Zero(binding.evaluator()->num_vars()); std::vector<int> lower_dual_indices, upper_dual_indices; std::tie(lower_dual_indices, upper_dual_indices) = bb_con_dual_indices.at(binding); for (int i = 0; i < binding.evaluator()->num_vars(); ++i) { if (lower_dual_indices[i] != -1 && gurobi_dual_solutions[lower_dual_indices[i]] >= 0) { // This lower bound is active since the reduced cost is non-negative. dual_sol(i) = gurobi_dual_solutions[lower_dual_indices[i]]; } else if (upper_dual_indices[i] != -1 && gurobi_dual_solutions[upper_dual_indices[i]] <= 0) { // This upper bound is active since the reduced cost is non-positive. dual_sol(i) = gurobi_dual_solutions[upper_dual_indices[i]]; } } result->set_dual_solution(binding, dual_sol); } } /** * Set the dual solution for each linear inequality and equality constraint. * @param gurobi_dual_solutions The dual solutions for each linear * inequality/equality constraint. This is extracted from "Pi" field from gurobi * model. * @param constraint_dual_start_row constraint_dual_start_row[constraint] maps * the linear inequality/equality constraint to the starting index of the * corresponding dual variable. */ void SetLinearConstraintDualSolutions( const MathematicalProgram& prog, const Eigen::VectorXd& gurobi_dual_solutions, const std::unordered_map<Binding<Constraint>, int>& constraint_dual_start_row, MathematicalProgramResult* result) { for (const auto& binding : prog.linear_equality_constraints()) { result->set_dual_solution( binding, gurobi_dual_solutions.segment(constraint_dual_start_row.at(binding), binding.evaluator()->num_constraints())); } for (const auto& binding : prog.linear_constraints()) { Eigen::VectorXd dual_solution = Eigen::VectorXd::Zero(binding.evaluator()->num_constraints()); int gurobi_constraint_index = constraint_dual_start_row.at(binding); const auto& lb = binding.evaluator()->lower_bound(); const auto& ub = binding.evaluator()->upper_bound(); for (int i = 0; i < binding.evaluator()->num_constraints(); ++i) { if (!std::isinf(ub(i)) || !std::isinf(lb(i))) { if (!std::isinf(lb(i)) && std::isinf(ub(i))) { dual_solution(i) = gurobi_dual_solutions(gurobi_constraint_index); gurobi_constraint_index++; } else if (!std::isinf(ub(i)) && std::isinf(lb(i))) { dual_solution(i) = gurobi_dual_solutions(gurobi_constraint_index); gurobi_constraint_index++; } else if (!std::isinf(ub(i)) && !std::isinf(lb(i))) { // When the constraint has both lower and upper bound, we know that if // the lower bound is active, then the dual solution >= 0. If the // upper bound is active, then the dual solution <= 0. const double lower_bound_dual = gurobi_dual_solutions(gurobi_constraint_index); const double upper_bound_dual = gurobi_dual_solutions(gurobi_constraint_index + 1); // Due to small numerical error, even if the bound is not active, // gurobi still reports that the dual variable has non-zero value. So // we compare the absolute value of the lower and upper bound, and // choose the one with the larger absolute value. dual_solution(i) = std::abs(lower_bound_dual) > std::abs(upper_bound_dual) ? lower_bound_dual : upper_bound_dual; gurobi_constraint_index += 2; } } } result->set_dual_solution(binding, dual_solution); } } template <typename C> void SetSecondOrderConeDualSolution( const std::vector<Binding<C>>& constraints, const Eigen::VectorXd& gurobi_qcp_dual_solutions, MathematicalProgramResult* result, int* soc_count) { for (const auto& binding : constraints) { const Vector1d dual_solution(gurobi_qcp_dual_solutions(*soc_count)); (*soc_count)++; result->set_dual_solution(binding, dual_solution); } } void SetAllSecondOrderConeDualSolution(const MathematicalProgram& prog, GRBmodel* model, MathematicalProgramResult* result) { const int num_soc = prog.lorentz_cone_constraints().size() + prog.rotated_lorentz_cone_constraints().size(); Eigen::VectorXd gurobi_qcp_dual_solutions(num_soc); GRBgetdblattrarray(model, GRB_DBL_ATTR_QCPI, 0, num_soc, gurobi_qcp_dual_solutions.data()); int soc_count = 0; SetSecondOrderConeDualSolution(prog.lorentz_cone_constraints(), gurobi_qcp_dual_solutions, result, &soc_count); SetSecondOrderConeDualSolution(prog.rotated_lorentz_cone_constraints(), gurobi_qcp_dual_solutions, result, &soc_count); } // Utility to extract Gurobi solve status information into // a struct to communicate to user callbacks. GurobiSolver::SolveStatusInfo GetGurobiSolveStatus(void* cbdata, int where) { GurobiSolver::SolveStatusInfo solve_status; GRBcbget(cbdata, where, GRB_CB_RUNTIME, &(solve_status.reported_runtime)); solve_status.current_objective = -1.0; GRBcbget(cbdata, where, GRB_CB_MIPNODE_OBJBST, &(solve_status.best_objective)); GRBcbget(cbdata, where, GRB_CB_MIPNODE_OBJBND, &(solve_status.best_bound)); GRBcbget(cbdata, where, GRB_CB_MIPNODE_SOLCNT, &(solve_status.feasible_solutions_count)); double explored_node_count_double{}; GRBcbget(cbdata, where, GRB_CB_MIPNODE_NODCNT, &explored_node_count_double); solve_status.explored_node_count = explored_node_count_double; return solve_status; } int gurobi_callback(GRBmodel* model, void* cbdata, int where, void* usrdata) { GurobiCallbackInformation* callback_info = reinterpret_cast<GurobiCallbackInformation*>(usrdata); if (where == GRB_CB_POLLING) { } else if (where == GRB_CB_PRESOLVE) { } else if (where == GRB_CB_SIMPLEX) { } else if (where == GRB_CB_MIP) { } else if (where == GRB_CB_MIPSOL && callback_info->mip_sol_callback != nullptr) { // Extract variable values from Gurobi, and set the current // solution of the MathematicalProgram to these values. int error = GRBcbget(cbdata, where, GRB_CB_MIPSOL_SOL, callback_info->solver_sol_vector.data()); if (error) { drake::log()->error("GRB error {} in MIPSol callback cbget: {}\n", error, GRBgeterrormsg(GRBgetenv(model))); return 0; } SetProgramSolutionVector(callback_info->is_new_variable, callback_info->solver_sol_vector, &(callback_info->prog_sol_vector)); callback_info->result->set_x_val(callback_info->prog_sol_vector); GurobiSolver::SolveStatusInfo solve_status = GetGurobiSolveStatus(cbdata, where); callback_info->mip_sol_callback(*(callback_info->prog), solve_status); } else if (where == GRB_CB_MIPNODE && callback_info->mip_node_callback != nullptr) { int sol_status; int error = GRBcbget(cbdata, where, GRB_CB_MIPNODE_STATUS, &sol_status); if (error) { drake::log()->error( "GRB error {} in MIPNode callback getting sol status: {}\n", error, GRBgeterrormsg(GRBgetenv(model))); return 0; } else if (sol_status == GRB_OPTIMAL) { // Extract variable values from Gurobi, and set the current // solution of the MathematicalProgram to these values. error = GRBcbget(cbdata, where, GRB_CB_MIPSOL_SOL, callback_info->solver_sol_vector.data()); if (error) { drake::log()->error("GRB error {} in MIPSol callback cbget: {}\n", error, GRBgeterrormsg(GRBgetenv(model))); return 0; } SetProgramSolutionVector(callback_info->is_new_variable, callback_info->solver_sol_vector, &(callback_info->prog_sol_vector)); callback_info->result->set_x_val(callback_info->prog_sol_vector); GurobiSolver::SolveStatusInfo solve_status = GetGurobiSolveStatus(cbdata, where); Eigen::VectorXd vals; VectorXDecisionVariable vars; callback_info->mip_node_callback(*(callback_info->prog), solve_status, &vals, &vars); // The callback may return an assignment of some number of variables // as a new heuristic solution seed. If so, feed those back to Gurobi. if (vals.size() > 0) { std::vector<double> new_sol(callback_info->prog->num_vars(), GRB_UNDEFINED); for (int i = 0; i < vals.size(); i++) { double val = vals[i]; int k = callback_info->prog->FindDecisionVariableIndex(vars[i]); new_sol[k] = val; } double objective_solution; error = GRBcbsolution(cbdata, new_sol.data(), &objective_solution); if (error) { drake::log()->error("GRB error {} in injection: {}\n", error, GRBgeterrormsg(GRBgetenv(model))); } } } } else if (where == GRB_CB_BARRIER) { } else if (where == GRB_CB_MESSAGE) { } return 0; } // Checks if the number of variables in the Gurobi model is as expected. This // operation can be EXPENSIVE, since it requires calling GRBupdatemodel // (Gurobi typically adopts lazy update, where it does not update the model // until calling the optimize function). // This function should only be used in DEBUG mode as a sanity check. __attribute__((unused)) bool HasCorrectNumberOfVariables( GRBmodel* model, int num_vars_expected) { int error = GRBupdatemodel(model); if (error) return false; int num_vars{}; error = GRBgetintattr(model, "NumVars", &num_vars); if (error) return false; return (num_vars == num_vars_expected); } /* * Add quadratic or linear costs to the optimization problem. */ int AddLinearAndQuadraticCosts(GRBmodel* model, double* pconstant_cost, const MathematicalProgram& prog) { // Aggregates the quadratic costs and linear costs in the form // 0.5 * x' * Q_all * x + linear_term' * x. using std::abs; // record the non-zero entries in the cost 0.5*x'*Q*x + b'*x. std::vector<Eigen::Triplet<double>> Q_nonzero_coefs; std::vector<Eigen::Triplet<double>> b_nonzero_coefs; double& constant_cost = *pconstant_cost; constant_cost = 0; for (const auto& binding : prog.quadratic_costs()) { const auto& constraint = binding.evaluator(); const int constraint_variable_dimension = binding.GetNumElements(); const Eigen::MatrixXd& Q = constraint->Q(); const Eigen::VectorXd& b = constraint->b(); constant_cost += constraint->c(); DRAKE_ASSERT(Q.rows() == constraint_variable_dimension); // constraint_variable_index[i] is the index of the i'th decision variable // binding.GetFlattendSolution(i). std::vector<int> constraint_variable_index(constraint_variable_dimension); for (int i = 0; i < static_cast<int>(binding.GetNumElements()); ++i) { constraint_variable_index[i] = prog.FindDecisionVariableIndex(binding.variables()(i)); } for (int i = 0; i < Q.rows(); i++) { const double Qii = 0.5 * Q(i, i); if (Qii != 0) { Q_nonzero_coefs.push_back(Eigen::Triplet<double>( constraint_variable_index[i], constraint_variable_index[i], Qii)); } for (int j = i + 1; j < Q.cols(); j++) { const double Qij = 0.5 * (Q(i, j) + Q(j, i)); if (Qij != 0) { Q_nonzero_coefs.push_back(Eigen::Triplet<double>( constraint_variable_index[i], constraint_variable_index[j], Qij)); } } } for (int i = 0; i < b.size(); i++) { if (b(i) != 0) { b_nonzero_coefs.push_back( Eigen::Triplet<double>(constraint_variable_index[i], 0, b(i))); } } } // Add linear cost in prog.linear_costs() to the aggregated cost. for (const auto& binding : prog.linear_costs()) { const auto& constraint = binding.evaluator(); const auto& a = constraint->a(); constant_cost += constraint->b(); for (int i = 0; i < static_cast<int>(binding.GetNumElements()); ++i) { b_nonzero_coefs.push_back(Eigen::Triplet<double>( prog.FindDecisionVariableIndex(binding.variables()(i)), 0, a(i))); } } Eigen::SparseMatrix<double> Q_all(prog.num_vars(), prog.num_vars()); Eigen::SparseMatrix<double> linear_terms(prog.num_vars(), 1); Q_all.setFromTriplets(Q_nonzero_coefs.begin(), Q_nonzero_coefs.end()); linear_terms.setFromTriplets(b_nonzero_coefs.begin(), b_nonzero_coefs.end()); std::vector<Eigen::Index> Q_all_row; std::vector<Eigen::Index> Q_all_col; std::vector<double> Q_all_val; drake::math::SparseMatrixToRowColumnValueVectors(Q_all, Q_all_row, Q_all_col, Q_all_val); std::vector<int> Q_all_row_indices_int(Q_all_row.size()); std::vector<int> Q_all_col_indices_int(Q_all_col.size()); for (int i = 0; i < static_cast<int>(Q_all_row_indices_int.size()); i++) { Q_all_row_indices_int[i] = static_cast<int>(Q_all_row[i]); Q_all_col_indices_int[i] = static_cast<int>(Q_all_col[i]); } std::vector<Eigen::Index> linear_row; std::vector<Eigen::Index> linear_col; std::vector<double> linear_val; drake::math::SparseMatrixToRowColumnValueVectors(linear_terms, linear_row, linear_col, linear_val); std::vector<int> linear_row_indices_int(linear_row.size()); for (int i = 0; i < static_cast<int>(linear_row_indices_int.size()); i++) { linear_row_indices_int[i] = static_cast<int>(linear_row[i]); } const int QPtermsError = GRBaddqpterms( model, static_cast<int>(Q_all_row.size()), Q_all_row_indices_int.data(), Q_all_col_indices_int.data(), Q_all_val.data()); if (QPtermsError) { return QPtermsError; } for (int i = 0; i < static_cast<int>(linear_row.size()); i++) { const int LinearTermError = GRBsetdblattrarray( model, "Obj", linear_row_indices_int[i], 1, linear_val.data() + i); if (LinearTermError) { return LinearTermError; } } // If loop completes, no errors exist so the value '0' must be returned. return 0; } // Add both LinearConstraints and LinearEqualityConstraints to gurobi // TODO(#2274) Fix NOLINTNEXTLINE(runtime/references). int ProcessLinearConstraints( GRBmodel* model, const MathematicalProgram& prog, int* num_gurobi_linear_constraints, std::unordered_map<Binding<Constraint>, int>* constraint_dual_start_row) { for (const auto& binding : prog.linear_equality_constraints()) { const auto& constraint = binding.evaluator(); constraint_dual_start_row->emplace(binding, *num_gurobi_linear_constraints); const int error = internal::AddLinearConstraint( prog, model, constraint->get_sparse_A(), constraint->lower_bound(), constraint->upper_bound(), binding.variables(), true, num_gurobi_linear_constraints); if (error) { return error; } } for (const auto& binding : prog.linear_constraints()) { const auto& constraint = binding.evaluator(); constraint_dual_start_row->emplace(binding, *num_gurobi_linear_constraints); const int error = internal::AddLinearConstraint( prog, model, constraint->get_sparse_A(), constraint->lower_bound(), constraint->upper_bound(), binding.variables(), false, num_gurobi_linear_constraints); if (error) { return error; } } // If loop completes, no errors exist so the value '0' must be returned. return 0; } template <typename T> void SetOptionOrThrow(GRBenv* model_env, const std::string& option, const T& val) { static_assert(std::is_same_v<T, int> || std::is_same_v<T, double> || std::is_same_v<T, std::string>, "Option values must be int, double, or string"); // Set the parameter as requested, returning immediately in case of success. const char* actual_type; int error = 0; if constexpr (std::is_same_v<T, int>) { actual_type = "integer"; error = GRBsetintparam(model_env, option.c_str(), val); } else if constexpr (std::is_same_v<T, double>) { actual_type = "floating-point"; error = GRBsetdblparam(model_env, option.c_str(), val); } else if constexpr (std::is_same_v<T, std::string>) { actual_type = "string"; error = GRBsetstrparam(model_env, option.c_str(), val.c_str()); } if (!error) { return; } // Report range errors (i.e., the parameter name is known, but `val` is bad). if (error == GRB_ERROR_VALUE_OUT_OF_RANGE) { throw std::runtime_error(fmt::format( "GurobiSolver(): '{}' is outside the parameter {}'s valid range", val, option)); } // In case of "unknown", it could either be truly unknown or else just the // wrong data type. if (error == GRB_ERROR_UNKNOWN_PARAMETER) { // For the expected param_type, we have: // 1: INT param // 2: DBL param // 3: STR param const int param_type = GRBgetparamtype(model_env, option.c_str()); // If the user provided an int for a double param, treat it as a double // without any complaint. This is especially helpful for Python users. if constexpr (std::is_same_v<T, int>) { if (param_type == 2) { SetOptionOrThrow<double>(model_env, option, val); return; } } // Otherwise, identify all other cases of type-mismatches. const char* expected_type = nullptr; switch (param_type) { case 1: { expected_type = "integer"; break; } case 2: { expected_type = "floating-point"; break; } case 3: { expected_type = "string"; break; } } if (expected_type != nullptr) { throw std::runtime_error( fmt::format("GurobiSolver(): parameter {} should be a {} not a {}", option, expected_type, actual_type)); } // Otherwise, it was truly unknown not just wrongly-typed. throw std::runtime_error(fmt::format( "GurobiSolver(): '{}' is an unknown parameter in Gurobi, check " "{}/parameters.html for allowable parameters", option, refman())); } // The error code should always be UNKNOWN_PARAMETER or VALUE_OUT_OF_RANGE, // but just in case we'll handle other errors with a fallback. This is // untested because it's thought to be unreachable in practice. throw std::runtime_error(fmt::format( "GurobiSolver(): error code {}, cannot set option '{}' to value '{}', " "check {}/parameters.html for all allowable options and values.", error, option, val, refman())); } void SetSolution( GRBmodel* model, GRBenv* model_env, const MathematicalProgram& prog, const std::vector<bool>& is_new_variable, int num_prog_vars, bool is_mip, int num_gurobi_linear_constraints, double constant_cost, const std::unordered_map<Binding<Constraint>, int>& constraint_dual_start_row, const std::unordered_map<Binding<BoundingBoxConstraint>, std::pair<std::vector<int>, std::vector<int>>>& bb_con_dual_indices, MathematicalProgramResult* result, GurobiSolverDetails* solver_details) { int num_total_variables = is_new_variable.size(); // Gurobi has solved not only for the decision variables in // MathematicalProgram prog, but also for any extra decision variables // that this GurobiSolver injected to craft certain constraints, such as // Lorentz cones. We therefore filter out the optimized values for // injected variables, and report back values for the MathematicalProgram // variables only. // solver_sol_vector includes the potentially newly added variables, i.e., // variables not in MathematicalProgram prog, but added to Gurobi by // GurobiSolver. // prog_sol_vector only includes the original variables in // MathematicalProgram prog. std::vector<double> solver_sol_vector(num_total_variables); GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, num_total_variables, solver_sol_vector.data()); Eigen::VectorXd prog_sol_vector(num_prog_vars); SetProgramSolutionVector(is_new_variable, solver_sol_vector, &prog_sol_vector); result->set_x_val(prog_sol_vector); // If QCPDual is 0 and the program has quadratic constraints (including // both Lorentz cone and rotated Lorentz cone constraints), then the dual // variables are not computed. int qcp_dual; int error = GRBgetintparam(model_env, "QCPDual", &qcp_dual); DRAKE_DEMAND(!error); int num_q_constrs = 0; error = GRBgetintattr(model, "NumQConstrs", &num_q_constrs); DRAKE_DEMAND(!error); const bool compute_dual = !(num_q_constrs > 0 && qcp_dual == 0); // Set dual solutions. if (!is_mip && compute_dual) { // Gurobi only provides dual solution for continuous models. // Gurobi stores its dual solution for each variable bounds in "reduced // cost". std::vector<double> reduced_cost(num_total_variables); GRBgetdblattrarray(model, GRB_DBL_ATTR_RC, 0, num_total_variables, reduced_cost.data()); SetBoundingBoxDualSolution(prog, reduced_cost, bb_con_dual_indices, result); Eigen::VectorXd gurobi_dual_solutions = Eigen::VectorXd::Zero(num_gurobi_linear_constraints); GRBgetdblattrarray(model, GRB_DBL_ATTR_PI, 0, num_gurobi_linear_constraints, gurobi_dual_solutions.data()); SetLinearConstraintDualSolutions(prog, gurobi_dual_solutions, constraint_dual_start_row, result); SetAllSecondOrderConeDualSolution(prog, model, result); } // Obtain optimal cost. double optimal_cost = std::numeric_limits<double>::quiet_NaN(); GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &optimal_cost); // Provide Gurobi's computed cost in addition to the constant cost. result->set_optimal_cost(optimal_cost + constant_cost); if (is_mip) { // The program wants to retrieve sub-optimal solutions int sol_count{0}; GRBgetintattr(model, "SolCount", &sol_count); for (int solution_number = 0; solution_number < sol_count; ++solution_number) { error = GRBsetintparam(model_env, "SolutionNumber", solution_number); DRAKE_DEMAND(!error); double suboptimal_obj{1.0}; error = GRBgetdblattrarray(model, "Xn", 0, num_total_variables, solver_sol_vector.data()); DRAKE_DEMAND(!error); error = GRBgetdblattr(model, "PoolObjVal", &suboptimal_obj); DRAKE_DEMAND(!error); SetProgramSolutionVector(is_new_variable, solver_sol_vector, &prog_sol_vector); result->AddSuboptimalSolution(suboptimal_obj, prog_sol_vector); } // If the problem is a mixed-integer optimization program, provide // Gurobi's lower bound. double lower_bound; error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJBOUND, &lower_bound); if (error) { drake::log()->error("GRB error {} getting lower bound: {}\n", error, GRBgeterrormsg(GRBgetenv(model))); solver_details->error_code = error; } else { solver_details->objective_bound = lower_bound; } } } std::optional<int> ParseInt(std::string_view s) { int result{}; const char* begin = s.data(); const char* end = s.data() + s.size(); auto [past, ec] = std::from_chars(begin, end, result); if ((ec == std::errc()) && (past == end)) { return result; } return std::nullopt; } } // namespace bool GurobiSolver::is_available() { return true; } /* * Implements RAII for a Gurobi license / environment. */ class GurobiSolver::License { public: License() { if (!GurobiSolver::is_enabled()) { throw std::runtime_error( "Could not locate Gurobi license key file because GRB_LICENSE_FILE " "environment variable was not set."); } if (const char* filename = std::getenv("GRB_LICENSE_FILE")) { // For unit testing, we employ a hack to keep env_ uninitialized so that // we don't need a valid license file. if (std::string_view{filename}.find("DRAKE_UNIT_TEST_NO_LICENSE") != std::string_view::npos) { return; } } const int num_tries = 3; int grb_load_env_error = 1; for (int i = 0; grb_load_env_error && i < num_tries; ++i) { grb_load_env_error = GRBloadenv(&env_, nullptr); } if (grb_load_env_error) { const char* grb_msg = GRBgeterrormsg(env_); throw std::runtime_error( "Could not create Gurobi environment because " "Gurobi returned code " + std::to_string(grb_load_env_error) + " with message \"" + grb_msg + "\"."); } DRAKE_DEMAND(env_ != nullptr); } ~License() { GRBfreeenv(env_); env_ = nullptr; } GRBenv* GurobiEnv() { return env_; } private: GRBenv* env_ = nullptr; }; namespace { bool IsGrbLicenseFileLocalHost() { // We use the existence of the string HOSTID in the license file as // confirmation that the license is associated with the local host. const char* grb_license_file = std::getenv("GRB_LICENSE_FILE"); if (grb_license_file == nullptr) { return false; } const std::optional<std::string> contents = ReadFile(grb_license_file); if (!contents) { return false; } return contents->find("HOSTID") != std::string::npos; } } // namespace std::shared_ptr<GurobiSolver::License> GurobiSolver::AcquireLicense() { // Gurobi recommends acquiring the license only once per program to avoid // overhead from acquiring the license (and console spew for academic license // users; see #19657). However, if users are using a shared network license // from a limited pool, then we risk them checking out the license and not // giving it back (e.g., if they are working in a jupyter notebook). As a // compromise, we extend license beyond the lifetime of the GurobiSolver iff // we can confirm that the license is associated with the local host. // // The first time the anyone calls GurobiSolver::AcquireLicense, we check // whether the license is local. If yes, the local_host_holder keeps the // license's use_count lower bounded to 1. If no, the local_hold_holder is // null and the usual GetScopedSingleton workflow applies. static never_destroyed<std::shared_ptr<void>> local_host_holder{ IsGrbLicenseFileLocalHost() ? GetScopedSingleton<GurobiSolver::License>() : nullptr}; return GetScopedSingleton<GurobiSolver::License>(); } // TODO([email protected]): break this large DoSolve function to smaller // ones. void GurobiSolver::DoSolve(const MathematicalProgram& prog, const Eigen::VectorXd& initial_guess, const SolverOptions& merged_options, MathematicalProgramResult* result) const { if (!prog.GetVariableScaling().empty()) { static const logging::Warn log_once( "GurobiSolver doesn't support the feature of variable scaling."); } if (!license_) { license_ = AcquireLicense(); } GRBenv* env = license_->GurobiEnv(); const int num_prog_vars = prog.num_vars(); int num_gurobi_vars = num_prog_vars; // Potentially Gurobi can add variables on top of the variables in // MathematicalProgram prog. // is_new_variable[i] is true if the i'th variable in Gurobi environment is // not stored in MathematicalProgram, but added by the GurobiSolver. // For example, for Lorentz cone and rotated Lorentz cone constraint,to impose // that A*x+b lies in the (rotated) Lorentz cone, we add decision variable z // to Gurobi, defined as z = A*x + b. // The size of is_new_variable should increase if we add new decision // variables to Gurobi model. // The invariant is // EXPECT_TRUE(HasCorrectNumberOfVariables(model, is_new_variables.size())) std::vector<bool> is_new_variable(num_prog_vars, false); std::vector<char> gurobi_var_type(num_prog_vars); bool is_mip{false}; for (int i = 0; i < num_prog_vars; ++i) { switch (prog.decision_variable(i).get_type()) { case MathematicalProgram::VarType::CONTINUOUS: gurobi_var_type[i] = GRB_CONTINUOUS; break; case MathematicalProgram::VarType::BINARY: gurobi_var_type[i] = GRB_BINARY; is_mip = true; break; case MathematicalProgram::VarType::INTEGER: gurobi_var_type[i] = GRB_INTEGER; is_mip = true; break; case MathematicalProgram::VarType::BOOLEAN: throw std::runtime_error( "Boolean variables should not be used with Gurobi solver."); case MathematicalProgram::VarType::RANDOM_UNIFORM: case MathematicalProgram::VarType::RANDOM_GAUSSIAN: case MathematicalProgram::VarType::RANDOM_EXPONENTIAL: throw std::runtime_error( "Random variables should not be used with Gurobi solver."); } } std::vector<double> xlow; std::vector<double> xupp; AggregateBoundingBoxConstraints(prog, &xlow, &xupp); // bb_con_dual_indices[constraint] returns the pair (lower_dual_indices, // upper_dual_indices), where lower_dual_indices are the indices of the dual // variables associated with the lower bound side (x >= lower) of the bounding // box constraint; upper_dual_indices are the indices of the dual variables // associated with the upper bound side (x <= upper) of the bounding box // constraint. If the index is -1, then it means there is not an associated // dual variable (because that row in the bounding box constraint can never // be active, as there are other bounding box constraint that imposes tighter // bounds on that variable). std::unordered_map<Binding<BoundingBoxConstraint>, std::pair<std::vector<int>, std::vector<int>>> bb_con_dual_indices; // Now loop over all of the bounding box constraints again, if a bounding box // constraint has its lower or upper bound equals to xlow or xupp, then that // bounding box constraint has an associated dual variable. for (const auto& binding : prog.bounding_box_constraints()) { const auto& constraint = binding.evaluator(); const Eigen::VectorXd& lower_bound = constraint->lower_bound(); const Eigen::VectorXd& upper_bound = constraint->upper_bound(); std::vector<int> upper_dual_indices(constraint->num_vars(), -1); std::vector<int> lower_dual_indices(constraint->num_vars(), -1); for (int k = 0; k < static_cast<int>(binding.GetNumElements()); ++k) { const int idx = prog.FindDecisionVariableIndex(binding.variables()(k)); if (xlow[idx] == lower_bound(k)) { lower_dual_indices[k] = idx; } if (xupp[idx] == upper_bound(k)) { upper_dual_indices[k] = idx; } } bb_con_dual_indices.emplace( binding, std::make_pair(lower_dual_indices, upper_dual_indices)); } // constraint_dual_start_row[constraint] returns the starting index of the // dual variable corresponding to this constraint std::unordered_map<Binding<Constraint>, int> constraint_dual_start_row; // Our second order cone constraints imposes A*x+b lies within the (rotated) // Lorentz cone. Unfortunately Gurobi only supports a vector z lying within // the (rotated) Lorentz cone. So we create new variable z, with the // constraint z - A*x = b and z being within the (rotated) Lorentz cone. // Here lorentz_cone_new_varaible_indices and // rotated_lorentz_cone_new_variable_indices // record the indices of the newly created variable z in the Gurobi program. std::vector<std::vector<int>> lorentz_cone_new_variable_indices; internal::AddSecondOrderConeVariables( prog.lorentz_cone_constraints(), &is_new_variable, &num_gurobi_vars, &lorentz_cone_new_variable_indices, &gurobi_var_type, &xlow, &xupp); std::vector<std::vector<int>> rotated_lorentz_cone_new_variable_indices; internal::AddSecondOrderConeVariables( prog.rotated_lorentz_cone_constraints(), &is_new_variable, &num_gurobi_vars, &rotated_lorentz_cone_new_variable_indices, &gurobi_var_type, &xlow, &xupp); std::vector<std::vector<int>> l2norm_costs_lorentz_cone_variable_indices; internal::AddL2NormCostVariables(prog.l2norm_costs(), &is_new_variable, &num_gurobi_vars, &l2norm_costs_lorentz_cone_variable_indices, &gurobi_var_type, &xlow, &xupp); GRBmodel* model = nullptr; GRBnewmodel(env, &model, "gurobi_model", num_gurobi_vars, nullptr, &xlow[0], &xupp[0], gurobi_var_type.data(), nullptr); ScopeExit guard([model]() { GRBfreemodel(model); }); int error = 0; double constant_cost = 0; if (!error) { error = AddLinearAndQuadraticCosts(model, &constant_cost, prog); } int num_gurobi_linear_constraints = 0; if (!error) { error = internal::AddL2NormCosts(prog, l2norm_costs_lorentz_cone_variable_indices, model, &num_gurobi_linear_constraints); } if (!error) { error = ProcessLinearConstraints(model, prog, &num_gurobi_linear_constraints, &constraint_dual_start_row); } // Add Lorentz cone constraints. if (!error) { error = internal::AddSecondOrderConeConstraints( prog, prog.lorentz_cone_constraints(), lorentz_cone_new_variable_indices, model, &num_gurobi_linear_constraints); } // Add rotated Lorentz cone constraints. if (!error) { error = internal::AddSecondOrderConeConstraints( prog, prog.rotated_lorentz_cone_constraints(), rotated_lorentz_cone_new_variable_indices, model, &num_gurobi_linear_constraints); } DRAKE_ASSERT(HasCorrectNumberOfVariables(model, is_new_variable.size())); // The new model gets a copy of the Gurobi environment, so when we set // parameters, we have to be sure to set them on the model's environment, // not the global Gurobi environment. // See: FAQ #11: https://www.gurobi.com/support/faqs // Note that it is not necessary to free this environment; rather, // we just have to call GRBfreemodel(model). GRBenv* model_env = GRBgetenv(model); DRAKE_DEMAND(model_env != nullptr); // Handle common solver options before gurobi-specific options stored in // merged_options, so that gurobi-specific options can overwrite common solver // options. // Gurobi creates a new log file every time we set "LogFile" parameter through // GRBsetstrparam(). So in order to avoid creating log files repeatedly, we // store the log file name in @p log_file variable, and only call // GRBsetstrparam(model_env, "LogFile", log_file) for once. std::string log_file = merged_options.get_print_file_name(); if (!error) { SetOptionOrThrow(model_env, "LogToConsole", static_cast<int>(merged_options.get_print_to_console())); } // Default the option for number of threads based on an environment variable // (but only if the user hasn't set the option directly already). if (!merged_options.GetOptionsInt(id()).contains("Threads")) { if (char* num_threads_str = std::getenv("GUROBI_NUM_THREADS")) { const std::optional<int> num_threads = ParseInt(num_threads_str); if (num_threads.has_value()) { SetOptionOrThrow(model_env, "Threads", *num_threads); log()->debug("Using GUROBI_NUM_THREADS={}", *num_threads); } else { static const logging::Warn log_once( "Ignoring unparseable value '{}' for GUROBI_NUM_THREADS", num_threads_str); } } } for (const auto& it : merged_options.GetOptionsDouble(id())) { if (!error) { SetOptionOrThrow(model_env, it.first, it.second); } } bool compute_iis = false; for (const auto& it : merged_options.GetOptionsInt(id())) { if (!error) { if (it.first == "GRBcomputeIIS") { compute_iis = static_cast<bool>(it.second); if (!(it.second == 0 || it.second == 1)) { throw std::runtime_error(fmt::format( "GurobiSolver(): option GRBcomputeIIS should be either " "0 or 1, but is incorrectly set to {}", it.second)); } } else { SetOptionOrThrow(model_env, it.first, it.second); } } } std::optional<std::string> grb_write; for (const auto& it : merged_options.GetOptionsStr(id())) { if (!error) { if (it.first == "GRBwrite") { if (it.second != "") { grb_write = it.second; } } else if (it.first == "LogFile") { log_file = it.second; } else { SetOptionOrThrow(model_env, it.first, it.second); } } } SetOptionOrThrow(model_env, "LogFile", log_file); for (int i = 0; i < static_cast<int>(prog.num_vars()); ++i) { if (!error && !std::isnan(initial_guess(i))) { error = GRBsetdblattrelement(model, "Start", i, initial_guess(i)); } } GRBupdatemodel(model); int num_gurobi_linear_constraints_expected; GRBgetintattr(model, GRB_INT_ATTR_NUMCONSTRS, &num_gurobi_linear_constraints_expected); DRAKE_DEMAND(num_gurobi_linear_constraints == num_gurobi_linear_constraints_expected); // If we have been supplied a callback, // register it with Gurobi. // We initialize callback_info outside of the if() scope // so that it persists until after GRBoptimize() has been // called and completed. We need this struct to survive // throughout the solve process. GurobiCallbackInformation callback_info; if (mip_node_callback_ != nullptr || mip_sol_callback_ != nullptr) { callback_info.prog = &prog; callback_info.is_new_variable = is_new_variable; callback_info.solver_sol_vector.resize(is_new_variable.size()); callback_info.prog_sol_vector.resize(num_prog_vars); callback_info.mip_node_callback = mip_node_callback_; callback_info.mip_sol_callback = mip_sol_callback_; callback_info.result = result; if (!error) { error = GRBsetcallbackfunc(model, &gurobi_callback, &callback_info); } } if (!error) { error = GRBoptimize(model); } if (!error) { if (compute_iis) { int optimstatus = 0; GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus); if (optimstatus == GRB_INF_OR_UNBD || optimstatus == GRB_INFEASIBLE) { // Only compute IIS when the problem is infeasible. error = GRBcomputeIIS(model); } } } if (!error) { if (grb_write.has_value()) { error = GRBwrite(model, grb_write.value().c_str()); if (error) { const std::string gurobi_version = fmt::format("{}.{}", GRB_VERSION_MAJOR, GRB_VERSION_MINOR); throw std::runtime_error(fmt::format( "GurobiSolver(): setting GRBwrite to {}, this is not supported. " "Check {}/py_model_write.html for more details.", grb_write.value(), refman())); } } } SolutionResult solution_result = SolutionResult::kSolverSpecificError; GurobiSolverDetails& solver_details = result->SetSolverDetailsType<GurobiSolverDetails>(); if (error) { solution_result = SolutionResult::kInvalidInput; drake::log()->info("Gurobi returns code {}, with message \"{}\".\n", error, GRBgeterrormsg(env)); solver_details.error_code = error; } else { // Always set the primal and dual solution for any non-error gurobi status. SetSolution(model, model_env, prog, is_new_variable, num_prog_vars, is_mip, num_gurobi_linear_constraints, constant_cost, constraint_dual_start_row, bb_con_dual_indices, result, &solver_details); int optimstatus = 0; GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus); solver_details.optimization_status = optimstatus; if (optimstatus != GRB_OPTIMAL && optimstatus != GRB_SUBOPTIMAL) { switch (optimstatus) { case GRB_INF_OR_UNBD: { solution_result = SolutionResult::kInfeasibleOrUnbounded; break; } case GRB_UNBOUNDED: { result->set_optimal_cost(MathematicalProgram::kUnboundedCost); solution_result = SolutionResult::kUnbounded; break; } case GRB_INFEASIBLE: { result->set_optimal_cost(MathematicalProgram::kGlobalInfeasibleCost); solution_result = SolutionResult::kInfeasibleConstraints; break; } } } else { solution_result = SolutionResult::kSolutionFound; } } error = GRBgetdblattr(model, GRB_DBL_ATTR_RUNTIME, &(solver_details.optimizer_time)); if (error && !solver_details.error_code) { // Only overwrite the error code if no error happened before getting the // runtime. solver_details.error_code = error; } result->set_solution_result(solution_result); } } // namespace solvers } // namespace drake #pragma GCC diagnostic pop // "-Wunused-parameter"
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/csdp_solver.h
#pragma once #include "drake/common/drake_copyable.h" #include "drake/solvers/sdpa_free_format.h" #include "drake/solvers/solver_base.h" namespace drake { namespace solvers { /** * The CSDP solver details after calling Solve() function. The user can call * MathematicalProgramResult::get_solver_details<CsdpSolver>() to obtain the * details. */ struct CsdpSolverDetails { /** Refer to the Return Codes section of CSDP 6.2.0 User's Guide for * explanation on the return code. Some of the common return codes are * * 0 Problem is solved to optimality. * 1 Problem is primal infeasible. * 2 Problem is dual infeasible. * 3 Problem solved to near optimality. * 4 Maximum iterations reached. * 5 Stuck at edge of primal feasibility. * 6 Stuck at edge of dual feasibility. * 7 Lack of progress. * 8 X, Z, or O is singular. * 9 NaN or Inf values encountered. */ int return_code{}; /** The primal objective value. */ double primal_objective{}; /** The dual objective value. */ double dual_objective{}; /** * CSDP solves a primal problem of the form * * max tr(C*X) * s.t tr(Aᵢ*X) = aᵢ * X ≽ 0 * * The dual form is * * min aᵀy * s.t ∑ᵢ yᵢAᵢ - C = Z * Z ≽ 0 * * y, Z are the variables for the dual problem. * y_val, Z_val are the solutions to the dual problem. */ Eigen::VectorXd y_val; Eigen::SparseMatrix<double> Z_val; }; /** * Wrap CSDP solver such that it can solve a * drake::solvers::MathematicalProgram. * @note CSDP doesn't accept free variables, while * drake::solvers::MathematicalProgram does. In order to convert * MathematicalProgram into CSDP format, we provide several approaches to remove * free variables. You can set the approach through * @code{cc} * SolverOptions solver_options; * solver_options.SetOption(CsdpSolver::id(), * "drake::RemoveFreeVariableMethod", * static_cast<int>(RemoveFreeVariableMethod::kNullspace)); * CsdpSolver solver; * auto result = solver.Solve(prog, std::nullopt, solver_options); * @endcode * For more details, check out RemoveFreeVariableMethod. */ class CsdpSolver final : public SolverBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(CsdpSolver) /** Default constructor */ CsdpSolver(); ~CsdpSolver() final; /// @name Static versions of the instance methods with similar names. //@{ static SolverId id(); static bool is_available(); static bool is_enabled(); static bool ProgramAttributesSatisfied(const MathematicalProgram&); //@} // A using-declaration adds these methods into our class's Doxygen. using SolverBase::Solve; using Details = CsdpSolverDetails; private: void DoSolve(const MathematicalProgram&, const Eigen::VectorXd&, const SolverOptions&, MathematicalProgramResult*) const final; }; } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/scs_solver.cc
#include "drake/solvers/scs_solver.h" #include <optional> #include <unordered_map> #include <utility> #include <vector> #include <Eigen/Sparse> #include <fmt/format.h> // clang-format off #include <scs.h> #include <cones.h> #include <linalg.h> #include <util.h> // clang-format on #include "drake/common/scope_exit.h" #include "drake/common/text_logging.h" #include "drake/math/eigen_sparse_triplet.h" #include "drake/math/quadratic_form.h" #include "drake/solvers/aggregate_costs_constraints.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/mathematical_program_result.h" #include "drake/solvers/scs_clarabel_common.h" namespace drake { namespace solvers { namespace { void ParseQuadraticCostWithRotatedLorentzCone( const MathematicalProgram& prog, std::vector<double>* c, std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b, int* A_row_count, std::vector<int>* second_order_cone_length, int* num_x) { // A QuadraticCost encodes cost of the form // 0.5 zᵀQz + pᵀz + r // We introduce a new slack variable y as the upper bound of the cost, with // the rotated Lorentz cone constraint // 2(y - r - pᵀz) ≥ zᵀQz. // We only need to minimize y then. for (const auto& cost : prog.quadratic_costs()) { // We will convert the expression 2(y - r - pᵀz) ≥ zᵀQz, to the constraint // that the vector A_cone * x + b_cone is in the rotated Lorentz cone, where // x = [z; y], and A_cone * x + b_cone is // [y - r - pᵀz] // [ 2] // [ C*z] // where C satisfies Cᵀ*C = Q const VectorXDecisionVariable& z = cost.variables(); const int y_index = z.rows(); // Ai_triplets are the non-zero entries in the matrix A_cone. std::vector<Eigen::Triplet<double>> Ai_triplets; Ai_triplets.emplace_back(0, y_index, 1); for (int i = 0; i < z.rows(); ++i) { Ai_triplets.emplace_back(0, i, -cost.evaluator()->b()(i)); } // Decompose Q to Cᵀ*C const Eigen::MatrixXd& Q = cost.evaluator()->Q(); const Eigen::MatrixXd C = math::DecomposePSDmatrixIntoXtransposeTimesX(Q, 1E-10); for (int i = 0; i < C.rows(); ++i) { for (int j = 0; j < C.cols(); ++j) { if (C(i, j) != 0) { Ai_triplets.emplace_back(2 + i, j, C(i, j)); } } } // append the variable y to the end of x (*num_x)++; std::vector<int> Ai_var_indices = prog.FindDecisionVariableIndices(z); Ai_var_indices.push_back(*num_x - 1); // Set b_cone Eigen::VectorXd b_cone = Eigen::VectorXd::Zero(2 + C.rows()); b_cone(0) = -cost.evaluator()->c(); b_cone(1) = 2; // Add the rotated Lorentz cone constraint internal::ParseRotatedLorentzConeConstraint( Ai_triplets, b_cone, Ai_var_indices, A_triplets, b, A_row_count, second_order_cone_length, std::nullopt); // Add the cost y. c->push_back(1); } } void ParseBoundingBoxConstraint( const MathematicalProgram& prog, std::vector<Eigen::Triplet<double>>* A_triplets, std::vector<double>* b, int* A_row_count, ScsCone* cone, std::vector<std::vector<std::pair<int, int>>>* bbcon_dual_indices) { // A bounding box constraint lb ≤ x ≤ ub is converted to the SCS form as // x + s1 = ub, -x + s2 = -lb, s1, s2 in the positive cone. // TODO(hongkai.dai) : handle the special case l = u, such that we can convert // it to x + s = l, s in zero cone. int num_bounding_box_constraint_rows = 0; bbcon_dual_indices->reserve(prog.bounding_box_constraints().size()); for (const auto& bounding_box_constraint : prog.bounding_box_constraints()) { int num_scs_new_constraint = 0; const VectorXDecisionVariable& xi = bounding_box_constraint.variables(); const int num_xi_rows = xi.rows(); A_triplets->reserve(A_triplets->size() + 2 * num_xi_rows); b->reserve(b->size() + 2 * num_xi_rows); bbcon_dual_indices->emplace_back(num_xi_rows); for (int i = 0; i < num_xi_rows; ++i) { std::pair<int, int> dual_index = {-1, -1}; if (!std::isinf(bounding_box_constraint.evaluator()->upper_bound()(i))) { // if ub != ∞, then add the constraint x + s1 = ub, s1 in the positive // cone. A_triplets->emplace_back(num_scs_new_constraint + *A_row_count, prog.FindDecisionVariableIndex(xi(i)), 1); b->push_back(bounding_box_constraint.evaluator()->upper_bound()(i)); dual_index.second = num_scs_new_constraint + *A_row_count; ++num_scs_new_constraint; } if (!std::isinf(bounding_box_constraint.evaluator()->lower_bound()(i))) { // if lb != -∞, then add the constraint -x + s2 = -lb, s2 in the // positive cone. A_triplets->emplace_back(num_scs_new_constraint + *A_row_count, prog.FindDecisionVariableIndex(xi(i)), -1); b->push_back(-bounding_box_constraint.evaluator()->lower_bound()(i)); dual_index.first = num_scs_new_constraint + *A_row_count; ++num_scs_new_constraint; } bbcon_dual_indices->back()[i] = dual_index; } *A_row_count += num_scs_new_constraint; num_bounding_box_constraint_rows += num_scs_new_constraint; } cone->l += num_bounding_box_constraint_rows; } std::string Scs_return_info(scs_int scs_status) { switch (scs_status) { case SCS_INFEASIBLE_INACCURATE: return "SCS infeasible inaccurate"; case SCS_UNBOUNDED_INACCURATE: return "SCS unbounded inaccurate"; case SCS_SIGINT: return "SCS sigint"; case SCS_FAILED: return "SCS failed"; case SCS_INDETERMINATE: return "SCS indeterminate"; case SCS_INFEASIBLE: return "SCS primal infeasible, dual unbounded"; case SCS_UNBOUNDED: return "SCS primal unbounded, dual infeasible"; case SCS_UNFINISHED: return "SCS unfinished"; case SCS_SOLVED: return "SCS solved"; case SCS_SOLVED_INACCURATE: return "SCS solved inaccurate"; default: throw std::runtime_error("Unknown scs status."); } } void SetScsProblemData( int A_row_count, int num_vars, const Eigen::SparseMatrix<double>& A, const std::vector<double>& b, const std::vector<Eigen::Triplet<double>>& P_upper_triplets, const std::vector<double>& c, ScsData* scs_problem_data) { scs_problem_data->m = A_row_count; scs_problem_data->n = num_vars; scs_problem_data->A = static_cast<ScsMatrix*>(malloc(sizeof(ScsMatrix))); // This scs_calloc doesn't need to accompany a ScopeExit since // scs_problem_data->A->x will be cleaned up recursively by freeing up // scs_problem_data in scs_free_data() scs_problem_data->A->x = static_cast<scs_float*>(scs_calloc(A.nonZeros(), sizeof(scs_float))); // This scs_calloc doesn't need to accompany a ScopeExit since // scs_problem_data->A->i will be cleaned up recursively by freeing up // scs_problem_data in scs_free_data() scs_problem_data->A->i = static_cast<scs_int*>(scs_calloc(A.nonZeros(), sizeof(scs_int))); // This scs_calloc doesn't need to accompany a ScopeExit since // scs_problem_data->A->p will be cleaned up recursively by freeing up // scs_problem_data in scs_free_data() scs_problem_data->A->p = static_cast<scs_int*>( scs_calloc(scs_problem_data->n + 1, sizeof(scs_int))); // TODO(hongkai.dai): should I use memcpy for the assignment in the for loop? for (int i = 0; i < A.nonZeros(); ++i) { scs_problem_data->A->x[i] = *(A.valuePtr() + i); scs_problem_data->A->i[i] = *(A.innerIndexPtr() + i); } for (int i = 0; i < scs_problem_data->n + 1; ++i) { scs_problem_data->A->p[i] = *(A.outerIndexPtr() + i); } scs_problem_data->A->m = scs_problem_data->m; scs_problem_data->A->n = scs_problem_data->n; // This scs_calloc doesn't need to accompany a ScopeExit since // scs_problem_data->b will be cleaned up recursively by freeing up // scs_problem_data in scs_free_data() scs_problem_data->b = static_cast<scs_float*>(scs_calloc(b.size(), sizeof(scs_float))); for (int i = 0; i < static_cast<int>(b.size()); ++i) { scs_problem_data->b[i] = b[i]; } if (P_upper_triplets.empty()) { scs_problem_data->P = SCS_NULL; } else { Eigen::SparseMatrix<double> P_upper(num_vars, num_vars); P_upper.setFromTriplets(P_upper_triplets.begin(), P_upper_triplets.end()); scs_problem_data->P = static_cast<ScsMatrix*>(malloc(sizeof(ScsMatrix))); // This scs_calloc doesn't need to accompany a ScopeExit since // scs_problem_data->P->x will be cleaned up recursively by freeing up // scs_problem_data in scs_free_data() scs_problem_data->P->x = static_cast<scs_float*>( scs_calloc(P_upper.nonZeros(), sizeof(scs_float))); // This scs_calloc doesn't need to accompany a ScopeExit since // scs_problem_data->P->i will be cleaned up recursively by freeing up // scs_problem_data in scs_free_data() scs_problem_data->P->i = static_cast<scs_int*>(scs_calloc(P_upper.nonZeros(), sizeof(scs_int))); // This scs_calloc doesn't need to accompany a ScopeExit since // scs_problem_data->P->p will be cleaned up recursively by freeing up // scs_problem_data in scs_free_data() scs_problem_data->P->p = static_cast<scs_int*>( scs_calloc(scs_problem_data->n + 1, sizeof(scs_int))); for (int i = 0; i < P_upper.nonZeros(); ++i) { scs_problem_data->P->x[i] = *(P_upper.valuePtr() + i); scs_problem_data->P->i[i] = *(P_upper.innerIndexPtr() + i); } for (int i = 0; i < scs_problem_data->n + 1; ++i) { scs_problem_data->P->p[i] = *(P_upper.outerIndexPtr() + i); } scs_problem_data->P->m = scs_problem_data->n; scs_problem_data->P->n = scs_problem_data->n; } // This scs_calloc doesn't need to accompany a ScopeExit since // scs_problem_data->c will be cleaned up recursively by freeing up // scs_problem_data in scs_free_data() scs_problem_data->c = static_cast<scs_float*>(scs_calloc(num_vars, sizeof(scs_float))); for (int i = 0; i < num_vars; ++i) { scs_problem_data->c[i] = c[i]; } } } // namespace bool ScsSolver::is_available() { return true; } namespace { // This should be invoked only once on each unique instance of ScsSettings. // Namely, only call this function for once in DoSolve. void SetScsSettings(std::unordered_map<std::string, int>* solver_options_int, const bool print_to_console, ScsSettings* scs_settings) { auto it = solver_options_int->find("normalize"); if (it != solver_options_int->end()) { scs_settings->normalize = it->second; solver_options_int->erase(it); } it = solver_options_int->find("adaptive_scale;"); if (it != solver_options_int->end()) { scs_settings->adaptive_scale = it->second; solver_options_int->erase(it); } it = solver_options_int->find("max_iters"); if (it != solver_options_int->end()) { scs_settings->max_iters = it->second; solver_options_int->erase(it); } it = solver_options_int->find("verbose"); if (it != solver_options_int->end()) { // The solver specific option has the highest priority. scs_settings->verbose = it->second; solver_options_int->erase(it); } else { // The common option has the second highest priority. scs_settings->verbose = print_to_console ? 1 : 0; } it = solver_options_int->find("warm_start"); if (it != solver_options_int->end()) { scs_settings->warm_start = it->second; solver_options_int->erase(it); } it = solver_options_int->find("acceleration_lookback"); if (it != solver_options_int->end()) { scs_settings->acceleration_lookback = it->second; solver_options_int->erase(it); } it = solver_options_int->find("acceleration_interval"); if (it != solver_options_int->end()) { scs_settings->acceleration_interval = it->second; solver_options_int->erase(it); } if (!solver_options_int->empty()) { throw std::invalid_argument("Unsupported SCS solver options."); } } // This should be invoked only once on each unique instance of ScsSettings. // Namely, only call this function for once in DoSolve. void SetScsSettings( std::unordered_map<std::string, double>* solver_options_double, ScsSettings* scs_settings) { auto it = solver_options_double->find("scale"); if (it != solver_options_double->end()) { scs_settings->scale = it->second; solver_options_double->erase(it); } it = solver_options_double->find("rho_x"); if (it != solver_options_double->end()) { scs_settings->rho_x = it->second; solver_options_double->erase(it); } it = solver_options_double->find("eps_abs"); if (it != solver_options_double->end()) { scs_settings->eps_abs = it->second; solver_options_double->erase(it); } else { // SCS 3.0 uses 1E-4 as the default value, see // https://www.cvxgrp.org/scs/api/settings.html?highlight=eps_abs). This // tolerance is too loose. We set the default tolerance to 1E-5 for better // accuracy. scs_settings->eps_abs = 1E-5; } it = solver_options_double->find("eps_rel"); if (it != solver_options_double->end()) { scs_settings->eps_rel = it->second; solver_options_double->erase(it); } else { // SCS 3.0 uses 1E-4 as the default value, see // https://www.cvxgrp.org/scs/api/settings.html?highlight=eps_rel). This // tolerance is too loose. We set the default tolerance to 1E-5 for better // accuracy. scs_settings->eps_rel = 1E-5; } it = solver_options_double->find("eps_infeas"); if (it != solver_options_double->end()) { scs_settings->eps_infeas = it->second; solver_options_double->erase(it); } it = solver_options_double->find("alpha"); if (it != solver_options_double->end()) { scs_settings->alpha = it->second; solver_options_double->erase(it); } it = solver_options_double->find("time_limit_secs"); if (it != solver_options_double->end()) { scs_settings->time_limit_secs = it->second; solver_options_double->erase(it); } if (!solver_options_double->empty()) { throw std::invalid_argument("Unsupported SCS solver options."); } } void SetBoundingBoxDualSolution( const MathematicalProgram& prog, const Eigen::Ref<const Eigen::VectorXd>& y, const std::vector<std::vector<std::pair<int, int>>>& bbcon_dual_indices, MathematicalProgramResult* result) { for (int i = 0; i < static_cast<int>(prog.bounding_box_constraints().size()); ++i) { Eigen::VectorXd bbcon_dual = Eigen::VectorXd::Zero( prog.bounding_box_constraints()[i].variables().rows()); for (int j = 0; j < prog.bounding_box_constraints()[i].variables().rows(); ++j) { if (bbcon_dual_indices[i][j].first != -1) { // lower bound is not infinity. // The shadow price for the lower bound is positive. SCS dual for the // positive cone is also positive, so we add the SCS dual. bbcon_dual[j] += y(bbcon_dual_indices[i][j].first); } if (bbcon_dual_indices[i][j].second != -1) { // upper bound is not infinity. // The shadow price for the upper bound is negative. SCS dual for the // positive cone is positive, so we subtract the SCS dual. bbcon_dual[j] -= y(bbcon_dual_indices[i][j].second); } } result->set_dual_solution(prog.bounding_box_constraints()[i], bbcon_dual); } } } // namespace void ScsSolver::DoSolve(const MathematicalProgram& prog, const Eigen::VectorXd& initial_guess, const SolverOptions& merged_options, MathematicalProgramResult* result) const { if (!prog.GetVariableScaling().empty()) { static const logging::Warn log_once( "ScsSolver doesn't support the feature of variable scaling."); } // TODO(hongkai.dai): allow warm starting SCS with initial guess on // primal/dual variables and primal residues. unused(initial_guess); // The initial guess for SCS is unused. // SCS solves the problem in this form // min 0.5xᵀPx + cᵀx // s.t A x + s = b // s in K // where K is a Cartesian product of some primitive cones. // The cones have to be in this order // Zero cone {x | x = 0 } // Positive orthant {x | x ≥ 0 } // Second-order cone {(t, x) | |x|₂ ≤ t } // Positive semidefinite cone { X | min(eig(X)) ≥ 0, X = Xᵀ } // There are more types that are supported by SCS, after the Positive // semidefinite cone. Please refer to https://github.com/cvxgrp/scs for more // details on the cone types. // Notice that due to the special problem form supported by SCS, we need to // convert our generic constraints to SCS form. For example, a linear // inequality constraint // A x ≤ b // will be converted as // A x + s = b // s in positive orthant cone. // by introducing the slack variable s. // num_x is the number of variables in `x`. It can contain more variables // than in prog. For some constraint/cost, we need to append slack variables // to convert the constraint/cost to the SCS form. For example, SCS does not // support un-constrained QP. So when we have an un-constrained QP, we need to // convert the quadratic cost // min 0.5zᵀQz + bᵀz + d // to the form // min y // s.t 2(y - bᵀz - d) ≥ zᵀQz (1) // now the cost is a linear function of y, with a rotated Lorentz cone // constraint(1). So we need to append the slack variable `y` to the variables // in `prog`. int num_x = prog.num_vars(); // We need to construct a sparse matrix in Column Compressed Storage (CCS) // format. On the other hand, we add the constraint row by row, instead of // column by column, as preferred by CCS. As a result, we use Eigen sparse // matrix to construct a sparse matrix in column order first, and then // compress it to get CCS. std::vector<Eigen::Triplet<double>> A_triplets; // We need to construct a sparse matrix in Column Compressed Storage (CCS) // format. Since we add an array of quadratic cost, each cost has its own // associated variables, we use Eigen sparse matrix to aggregate the quadratic // cost Hessian matrices. SCS only takes the upper triangular entries of the // symmetric Hessian. std::vector<Eigen::Triplet<double>> P_upper_triplets; // cone stores all the cones K in the problem. ScsCone* cone = static_cast<ScsCone*>(scs_calloc(1, sizeof(ScsCone))); ScsData* scs_problem_data = static_cast<ScsData*>(scs_calloc(1, sizeof(ScsData))); ScsSettings* scs_stgs = static_cast<ScsSettings*>(scs_calloc(1, sizeof(ScsSettings))); // This guard will free cone, scs_problem_data, and scs_stgs (together with // their instantiated members) upon return from the DoSolve function. ScopeExit scs_free_guard([&cone, &scs_problem_data, &scs_stgs]() { SCS(free_cone)(cone); SCS(free_data)(scs_problem_data); scs_free(scs_stgs); }); // Set the parameters to default values. scs_set_default_settings(scs_stgs); // A_row_count will increment, when we add each constraint. int A_row_count = 0; std::vector<double> b; // `c` is the coefficient in the linear cost cᵀx std::vector<double> c(num_x, 0.0); // Our cost (LinearCost, QuadraticCost, etc) also allows a constant term, we // add these constant terms to `cost_constant`. double cost_constant{0}; // Parse linear cost internal::ParseLinearCosts(prog, &c, &cost_constant); // Parse linear equality constraint // linear_eq_y_start_indices[i] is the starting index of the dual // variable for the constraint prog.linear_equality_constraints()[i]. Namely // y[linear_eq_y_start_indices[i]: // linear_eq_y_start_indices[i] + // prog.linear_equality_constraints()[i].evaluator()->num_constraints] are the // dual variables for the linear equality constraint // prog.linear_equality_constraint()(i), where y is the vector containing all // dual variables. std::vector<int> linear_eq_y_start_indices; int num_linear_equality_constraints_rows; internal::ParseLinearEqualityConstraints( prog, &A_triplets, &b, &A_row_count, &linear_eq_y_start_indices, &num_linear_equality_constraints_rows); cone->z += num_linear_equality_constraints_rows; // Parse bounding box constraint // bbcon_dual_indices[i][j][0]/bbcon_dual_indices[i][j][1] is the dual // variable for the lower/upper bound of the j'th row in the bounding box // constraint prog.bounding_box_constraint()[i], we use -1 to indicate that // the lower or upper bound is infinity. std::vector<std::vector<std::pair<int, int>>> bbcon_dual_indices; ParseBoundingBoxConstraint(prog, &A_triplets, &b, &A_row_count, cone, &bbcon_dual_indices); // Parse linear constraint // linear_constraint_dual_indices[i][j][0]/linear_constraint_dual_indices[i][j][1] // is the dual variable for the lower/upper bound of the j'th row in the // linear constraint prog.linear_constraint()[i], we use -1 to indicate that // the lower or upper bound is infinity. std::vector<std::vector<std::pair<int, int>>> linear_constraint_dual_indices; int num_linear_constraint_rows = 0; internal::ParseLinearConstraints(prog, &A_triplets, &b, &A_row_count, &linear_constraint_dual_indices, &num_linear_constraint_rows); cone->l += num_linear_constraint_rows; // Parse Lorentz cone and rotated Lorentz cone constraint std::vector<int> second_order_cone_length; // y[lorentz_cone_y_start_indices[i]: // lorentz_cone_y_start_indices[i] + second_order_cone_length[i]] // are the dual variables for prog.lorentz_cone_constraints()[i]. std::vector<int> lorentz_cone_y_start_indices; // y[rotated_lorentz_cone_y_start_indices[i]: // rotated_lorentz_cone_y_start_indices[i] + // prog.rotate_lorentz_cone()[i].evaluator().A().rows] are the y variables for // prog.rotated_lorentz_cone_constraints()[i]. Note that SCS doesn't have a // rotated Lorentz cone constraint, instead we convert the rotated Lorentz // cone constraint to the Lorentz cone constraint through a linear // transformation. Hence we need to apply the transpose of that linear // transformation on the y variable to get the dual variable in the dual cone // of rotated Lorentz cone. std::vector<int> rotated_lorentz_cone_y_start_indices; internal::ParseSecondOrderConeConstraints( prog, &A_triplets, &b, &A_row_count, &second_order_cone_length, &lorentz_cone_y_start_indices, &rotated_lorentz_cone_y_start_indices); // Add L2NormCost. L2NormCost should be parsed together with the other second // order cone constraints, since we introduce new second order cone // constraints to formulate the L2 norm cost. std::vector<int> l2norm_costs_lorentz_cone_y_start_indices; std::vector<int> l2norm_costs_t_slack_indices; internal::ParseL2NormCosts(prog, &num_x, &A_triplets, &b, &A_row_count, &second_order_cone_length, &l2norm_costs_lorentz_cone_y_start_indices, &c, &l2norm_costs_t_slack_indices); // Parse quadratic cost. This MUST be called after parsing the second order // cone constraint, as we might convert quadratic cost to second order cone // constraint. if (A_triplets.empty() && prog.positive_semidefinite_constraints().empty() && prog.linear_matrix_inequality_constraints().empty() && prog.exponential_cone_constraints().empty()) { // A_triplets.empty() = true means that up to now (after looping through // box, linear and second-order cone constraints) no constraints have been // added to SCS. Combining this with the fact that the // positive semidefinite, linear matrix inequality and exponential cone // constraints are all empty, this means that `prog` is un-constrained. If // the program is un-constrained but with a quadratic cost, since SCS // doesn't handle un-constrained QP, we convert this un-constrained QP to a // program with linear cost and rotated Lorentz cone constraint. ParseQuadraticCostWithRotatedLorentzCone(prog, &c, &A_triplets, &b, &A_row_count, &second_order_cone_length, &num_x); } else { internal::ParseQuadraticCosts(prog, &P_upper_triplets, &c, &cost_constant); } // Set the lorentz cone length in the SCS cone. cone->qsize = second_order_cone_length.size(); cone->q = static_cast<scs_int*>(scs_calloc(cone->qsize, sizeof(scs_int))); for (int i = 0; i < cone->qsize; ++i) { cone->q[i] = second_order_cone_length[i]; } // Parse PositiveSemidefiniteConstraint and LinearMatrixInequalityConstraint. std::vector<int> psd_cone_length; internal::ParsePositiveSemidefiniteConstraints( prog, /* upper_triangular = */ false, &A_triplets, &b, &A_row_count, &psd_cone_length); // Set the psd cone length in the SCS cone. cone->ssize = psd_cone_length.size(); // This scs_calloc doesn't need to accompany a ScopeExit since cone->s will be // cleaned up recursively by freeing up cone in scs_free_data() cone->s = static_cast<scs_int*>(scs_calloc(cone->ssize, sizeof(scs_int))); for (int i = 0; i < cone->ssize; ++i) { cone->s[i] = psd_cone_length[i]; } // Parse ExponentialConeConstraint. internal::ParseExponentialConeConstraints(prog, &A_triplets, &b, &A_row_count); cone->ep = static_cast<int>(prog.exponential_cone_constraints().size()); Eigen::SparseMatrix<double> A(A_row_count, num_x); A.setFromTriplets(A_triplets.begin(), A_triplets.end()); A.makeCompressed(); SetScsProblemData(A_row_count, num_x, A, b, P_upper_triplets, c, scs_problem_data); std::unordered_map<std::string, int> input_solver_options_int = merged_options.GetOptionsInt(id()); std::unordered_map<std::string, double> input_solver_options_double = merged_options.GetOptionsDouble(id()); SetScsSettings(&input_solver_options_int, merged_options.get_print_to_console(), scs_stgs); SetScsSettings(&input_solver_options_double, scs_stgs); ScsInfo scs_info{0}; ScsSolution* scs_sol = static_cast<ScsSolution*>(scs_calloc(1, sizeof(ScsSolution))); ScopeExit sol_guard([&scs_sol]() { SCS(free_sol)(scs_sol); }); ScsSolverDetails& solver_details = result->SetSolverDetailsType<ScsSolverDetails>(); solver_details.scs_status = scs(scs_problem_data, cone, scs_stgs, scs_sol, &scs_info); solver_details.iter = scs_info.iter; solver_details.primal_objective = scs_info.pobj; solver_details.dual_objective = scs_info.dobj; solver_details.primal_residue = scs_info.res_pri; solver_details.residue_infeasibility = scs_info.res_infeas; solver_details.residue_unbounded_a = scs_info.res_unbdd_a; solver_details.residue_unbounded_p = scs_info.res_unbdd_p; solver_details.duality_gap = scs_info.gap; solver_details.scs_setup_time = scs_info.setup_time; solver_details.scs_solve_time = scs_info.solve_time; SolutionResult solution_result{SolutionResult::kSolverSpecificError}; solver_details.y.resize(A_row_count); solver_details.s.resize(A_row_count); for (int i = 0; i < A_row_count; ++i) { solver_details.y(i) = scs_sol->y[i]; solver_details.s(i) = scs_sol->s[i]; } // Always set the primal and dual solution. result->set_x_val( (Eigen::Map<VectorX<scs_float>>(scs_sol->x, prog.num_vars())) .cast<double>()); SetBoundingBoxDualSolution(prog, solver_details.y, bbcon_dual_indices, result); internal::SetDualSolution( prog, solver_details.y, linear_constraint_dual_indices, linear_eq_y_start_indices, lorentz_cone_y_start_indices, rotated_lorentz_cone_y_start_indices, result); // Set the solution_result enum and the optimal cost based on SCS status. if (solver_details.scs_status == SCS_SOLVED || solver_details.scs_status == SCS_SOLVED_INACCURATE) { solution_result = SolutionResult::kSolutionFound; result->set_optimal_cost(scs_info.pobj + cost_constant); } else if (solver_details.scs_status == SCS_UNBOUNDED || solver_details.scs_status == SCS_UNBOUNDED_INACCURATE) { solution_result = SolutionResult::kUnbounded; result->set_optimal_cost(MathematicalProgram::kUnboundedCost); } else if (solver_details.scs_status == SCS_INFEASIBLE || solver_details.scs_status == SCS_INFEASIBLE_INACCURATE) { solution_result = SolutionResult::kInfeasibleConstraints; result->set_optimal_cost(MathematicalProgram::kGlobalInfeasibleCost); } if (solver_details.scs_status != SCS_SOLVED) { drake::log()->info("SCS returns code {}, with message \"{}\".\n", solver_details.scs_status, Scs_return_info(solver_details.scs_status)); } result->set_solution_result(solution_result); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake
/home/johnshepherd/drake/solvers/ipopt_solver_common.cc
/* clang-format off to disable clang-format-includes */ #include "drake/solvers/ipopt_solver.h" /* clang-format on */ #include "drake/common/never_destroyed.h" #include "drake/solvers/mathematical_program.h" namespace drake { namespace solvers { IpoptSolver::IpoptSolver() : SolverBase(id(), &is_available, &is_enabled, &ProgramAttributesSatisfied) {} IpoptSolver::~IpoptSolver() = default; SolverId IpoptSolver::id() { static const never_destroyed<SolverId> singleton{"IPOPT"}; return singleton.access(); } bool IpoptSolver::is_enabled() { return true; } bool IpoptSolver::ProgramAttributesSatisfied(const MathematicalProgram& prog) { static const never_destroyed<ProgramAttributes> solver_capabilities( std::initializer_list<ProgramAttribute>{ ProgramAttribute::kGenericConstraint, ProgramAttribute::kLinearEqualityConstraint, ProgramAttribute::kLinearConstraint, ProgramAttribute::kQuadraticConstraint, ProgramAttribute::kLorentzConeConstraint, ProgramAttribute::kRotatedLorentzConeConstraint, ProgramAttribute::kGenericCost, ProgramAttribute::kLinearCost, ProgramAttribute::kL2NormCost, ProgramAttribute::kQuadraticCost, ProgramAttribute::kCallback}); return AreRequiredAttributesSupported(prog.required_capabilities(), solver_capabilities.access()); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test_utilities/check_constraint_eval_nonsymbolic.h
#pragma once #include <Eigen/Dense> #include "drake/common/autodiff.h" #include "drake/solvers/constraint.h" namespace drake { namespace solvers { namespace test { /** Compare the result between Eval<double>() and Eval<AutoDiffXd>(). Also compare the gradient in Eval<AutoDiffXd>() with a finite difference approximation. @param constraint The constraint object to test. @param x_autodiff The point at which the Eval() methods are tested. @param tol Tolerance on the comparison of the results from Eval<double>() and Eval<AutoDiffXd>(). The tolerance on the comparison between the autodiff gradient and the finite difference approximation is sqrt(tolerance) to account for approximation error. */ void CheckConstraintEvalNonsymbolic( const Constraint& constraint, const Eigen::Ref<const AutoDiffVecXd>& x_autodiff, double tol); } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test_utilities/BUILD.bazel
load("//tools/lint:lint.bzl", "add_lint_tests") load( "//tools/skylark:drake_cc.bzl", "drake_cc_library", "drake_cc_package_library", ) package(default_visibility = ["//visibility:public"]) # This should encompass every cc_library in this package, except for items that # should only ever be linked into main() programs. drake_cc_package_library( name = "test_utilities", testonly = 1, visibility = ["//visibility:public"], deps = [ ":check_constraint_eval_nonsymbolic", ], ) drake_cc_library( name = "check_constraint_eval_nonsymbolic", testonly = 1, srcs = ["check_constraint_eval_nonsymbolic.cc"], hdrs = ["check_constraint_eval_nonsymbolic.h"], deps = [ "//common/test_utilities", "//math:compute_numerical_gradient", "//math:gradient", "//solvers:constraint", ], ) add_lint_tests()
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test_utilities/check_constraint_eval_nonsymbolic.cc
#include "drake/solvers/test_utilities/check_constraint_eval_nonsymbolic.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/autodiff_gradient.h" #include "drake/math/compute_numerical_gradient.h" namespace drake { namespace solvers { namespace test { /** Compare the result between Eval<double> and Eval<AutoDiffXd>. Also compare the gradient in Eval<AutoDiffXd> with a numerical approximation. */ void CheckConstraintEvalNonsymbolic( const Constraint& constraint, const Eigen::Ref<const AutoDiffVecXd>& x_autodiff, double tol) { const Eigen::VectorXd x_double{math::ExtractValue(x_autodiff)}; Eigen::VectorXd y_double; constraint.Eval(x_double, &y_double); AutoDiffVecXd y_autodiff; constraint.Eval(x_autodiff, &y_autodiff); EXPECT_TRUE(CompareMatrices(y_double, math::ExtractValue(y_autodiff), tol)); std::function<void(const Eigen::Ref<const Eigen::VectorXd>&, Eigen::VectorXd*)> constraint_eval = [&constraint](const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) { return constraint.Eval(x, y); }; const auto J = math::ComputeNumericalGradient( constraint_eval, x_double, math::NumericalGradientOption{math::NumericalGradientMethod::kCentral}); EXPECT_TRUE(CompareMatrices(J * math::ExtractGradient(x_autodiff), math::ExtractGradient(y_autodiff), std::sqrt(tol))); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/minimum_value_constraint_test.cc
#include "drake/solvers/minimum_value_constraint.h" #include <limits> #include <gtest/gtest.h> #include "drake/common/symbolic/expression.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/autodiff_gradient.h" #include "drake/solvers/test_utilities/check_constraint_eval_nonsymbolic.h" namespace drake { namespace solvers { namespace { const double kInf = std::numeric_limits<double>::infinity(); const double kEps = std::numeric_limits<double>::epsilon(); // Returns the element-wise square of it's input. template <typename T> VectorX<T> SquareAndReturnAll(const Eigen::Ref<const VectorX<T>>& x, double) { return x.array().square(); } // Returns the elements of the element-wise square of its input // that are less than `influence_value`. template <typename T> VectorX<T> SquareAndReturnLessThanInfluenceValue( const Eigen::Ref<const VectorX<T>>& x, double influence_value) { int max_num_values = static_cast<int>(x.size()); VectorX<T> values(max_num_values); int value_count{0}; double sqrt_influence_value = std::sqrt(influence_value); for (int i = 0; i < max_num_values; ++i) { if (x(i) < sqrt_influence_value) { values(value_count++) = x(i) * x(i); } } values.conservativeResize(value_count); return values; } // Returns a zero-element vector. template <typename T> VectorX<T> ReturnNoValues(const Eigen::Ref<const VectorX<T>>&, double) { return VectorX<T>(0); } // Verify that the constructor works as expected. GTEST_TEST(MinimumValueLowerBoundConstraintTests, ConstructorTest) { // Constructor with only minimum_value_lower int expected_num_vars{5}; int expected_max_num_values{3}; double expected_minimum_value{0.1}; double expected_influence_value{0.2}; MinimumValueLowerBoundConstraint dut( expected_num_vars, expected_minimum_value, expected_influence_value - expected_minimum_value, expected_max_num_values, &SquareAndReturnAll<AutoDiffXd>); EXPECT_EQ(dut.num_vars(), expected_num_vars); EXPECT_EQ(dut.max_num_values(), expected_max_num_values); EXPECT_EQ(dut.minimum_value_lower(), expected_minimum_value); EXPECT_EQ(dut.influence_value(), expected_influence_value); EXPECT_EQ(dut.num_constraints(), 1); EXPECT_EQ(dut.upper_bound()(0), 1); EXPECT_EQ(dut.lower_bound()(0), -kInf); } GTEST_TEST(MinimumValueUpperBoundConstraintTest, ConstructorTest) { int expected_num_vars{5}; int expected_max_num_values{3}; double expected_minimum_value_upper{0.1}; double expected_influence_value{0.2}; MinimumValueUpperBoundConstraint dut( expected_num_vars, expected_minimum_value_upper, expected_influence_value - expected_minimum_value_upper, expected_max_num_values, &SquareAndReturnAll<AutoDiffXd>); EXPECT_EQ(dut.num_vars(), expected_num_vars); EXPECT_EQ(dut.max_num_values(), expected_max_num_values); EXPECT_EQ(dut.minimum_value_upper(), expected_minimum_value_upper); EXPECT_EQ(dut.influence_value(), expected_influence_value); EXPECT_EQ(dut.num_constraints(), 1); EXPECT_EQ(dut.lower_bound()(0), 1); EXPECT_FALSE(std::isfinite(dut.upper_bound()(0))); } // Verify that the non-symbolic versions of Eval() behave as expected. GTEST_TEST(MinimumValueLowerBoundConstraintTests, EvalNonsymbolicTest) { int num_vars{5}; int max_num_values{5}; double minimum_value_lower{0.1}; double influence_value{0.2}; MinimumValueLowerBoundConstraint dut_return_all( num_vars, minimum_value_lower, influence_value - minimum_value_lower, max_num_values, &SquareAndReturnAll<AutoDiffXd>, &SquareAndReturnAll<double>); MinimumValueLowerBoundConstraint dut_return_less_than_influence_value( num_vars, minimum_value_lower, influence_value - minimum_value_lower, max_num_values, &SquareAndReturnLessThanInfluenceValue<AutoDiffXd>); double tol = kEps; AutoDiffVecXd x_0 = AutoDiffVecXd::Zero(num_vars); AutoDiffVecXd x_0_to_twice_sqrt_influence_value = AutoDiffVecXd::LinSpaced(num_vars, 0, 2 * std::sqrt(influence_value)); AutoDiffVecXd x_sqrt_min_value_to_twice_sqrt_influence_value = AutoDiffVecXd::LinSpaced(num_vars, std::sqrt(minimum_value_lower), 2 * std::sqrt(influence_value)); auto check_constraints = [&](std::vector<AutoDiffVecXd> inputs, bool should_constraints_be_satisfied) { for (const AutoDiffVecXd& x : inputs) { test::CheckConstraintEvalNonsymbolic(dut_return_all, x, tol); test::CheckConstraintEvalNonsymbolic(dut_return_less_than_influence_value, x, tol); AutoDiffVecXd y_return_all, y_return_less_than_influence_value; dut_return_all.Eval(x, &y_return_all); dut_return_less_than_influence_value.Eval( x, &y_return_less_than_influence_value); ASSERT_EQ(y_return_all.size(), 1); ASSERT_EQ(y_return_less_than_influence_value.size(), 1); EXPECT_EQ(y_return_all(0), y_return_less_than_influence_value(0)); EXPECT_EQ(dut_return_all.CheckSatisfied(x, kEps), should_constraints_be_satisfied); EXPECT_EQ(dut_return_less_than_influence_value.CheckSatisfied(x, kEps), should_constraints_be_satisfied); } }; // Check with inputs that should violate the constraints. check_constraints({x_0, x_0_to_twice_sqrt_influence_value, x_sqrt_min_value_to_twice_sqrt_influence_value - AutoDiffVecXd::Constant(num_vars, kEps)}, false); // Check with inputs that should satisfy the constraints. check_constraints({x_sqrt_min_value_to_twice_sqrt_influence_value}, true); // All value are larger than influence_value. AutoDiffVecXd x_sqrt_influence_value_to_twice_sqrt_influence_value = AutoDiffVecXd::LinSpaced(num_vars, 1.1 * std::sqrt(influence_value), 2 * std::sqrt(influence_value)); check_constraints({x_sqrt_influence_value_to_twice_sqrt_influence_value}, true); } // Verify that the non-symbolic versions of Eval() behave as expected. GTEST_TEST(MinimumValueUpperBoundConstraintTests, EvalNonsymbolicTest) { // The constraint is constructed only with the upper bound on its minimal // value, no lower bound. int num_vars{5}; int max_num_values{5}; double minimum_value_upper{0.1}; double influence_value{0.2}; MinimumValueUpperBoundConstraint dut_return_all( num_vars, minimum_value_upper, influence_value - minimum_value_upper, max_num_values, &SquareAndReturnAll<AutoDiffXd>, &SquareAndReturnAll<double>); MinimumValueUpperBoundConstraint dut_return_less_than_influence_value( num_vars, minimum_value_upper, influence_value - minimum_value_upper, max_num_values, &SquareAndReturnLessThanInfluenceValue<AutoDiffXd>); double tol = kEps; AutoDiffVecXd x_0 = AutoDiffVecXd::Zero(num_vars); AutoDiffVecXd x_0_to_twice_sqrt_influence_value = AutoDiffVecXd::LinSpaced(num_vars, 0, 2 * std::sqrt(influence_value)); AutoDiffVecXd x_sqrt_min_value_to_twice_sqrt_influence_value = AutoDiffVecXd::LinSpaced(num_vars, std::sqrt(minimum_value_upper), 2 * std::sqrt(influence_value)); AutoDiffVecXd x_sqrt_min_value_plus_eps_to_twice_sqrt_influence_value = AutoDiffVecXd::LinSpaced(num_vars, std::sqrt(minimum_value_upper + 0.01), 2 * std::sqrt(influence_value)); auto check_constraints = [&](std::vector<AutoDiffVecXd> inputs, bool should_constraints_be_satisfied) { for (const AutoDiffVecXd& x : inputs) { test::CheckConstraintEvalNonsymbolic(dut_return_all, x, tol); test::CheckConstraintEvalNonsymbolic(dut_return_less_than_influence_value, x, tol); AutoDiffVecXd y_return_all, y_return_less_than_influence_value; dut_return_all.Eval(x, &y_return_all); dut_return_less_than_influence_value.Eval( x, &y_return_less_than_influence_value); ASSERT_EQ(y_return_all.size(), 1); ASSERT_EQ(y_return_less_than_influence_value.size(), 1); EXPECT_EQ(y_return_all(0), y_return_less_than_influence_value(0)); EXPECT_EQ(dut_return_all.CheckSatisfied(x, kEps), should_constraints_be_satisfied); EXPECT_EQ(dut_return_less_than_influence_value.CheckSatisfied(x, kEps), should_constraints_be_satisfied); } }; // Check with inputs that should satisfy the constraints. check_constraints({x_0, x_0_to_twice_sqrt_influence_value, x_sqrt_min_value_to_twice_sqrt_influence_value - AutoDiffVecXd::Constant(num_vars, kEps)}, true); // Check with inputs that is on the boundary of satisfying the constraints. check_constraints({x_sqrt_min_value_to_twice_sqrt_influence_value}, true); // Check with inputs that should violate the constraints. check_constraints({x_sqrt_min_value_plus_eps_to_twice_sqrt_influence_value}, false); // All value are larger than influence_value. AutoDiffVecXd x_sqrt_influence_value_to_twice_sqrt_influence_value = AutoDiffVecXd::LinSpaced(num_vars, 1.1 * std::sqrt(influence_value), 2 * std::sqrt(influence_value)); check_constraints({x_sqrt_influence_value_to_twice_sqrt_influence_value}, false); // Now make sure the gradient is continuous across influence_value. const AutoDiffVecXd x_below_influence = math::InitializeAutoDiff(Eigen::VectorXd::LinSpaced( num_vars, std::sqrt(minimum_value_upper * 0.99), std::sqrt(influence_value - 1E-5))); AutoDiffVecXd x_above_influence = x_below_influence; x_above_influence(num_vars - 1).value() = std::sqrt(influence_value + 1E-5); AutoDiffVecXd y_below_influence; AutoDiffVecXd y_above_influence; for (const auto* constraint : {&dut_return_all, &dut_return_less_than_influence_value}) { constraint->Eval(x_below_influence, &y_below_influence); constraint->Eval(x_above_influence, &y_above_influence); EXPECT_NEAR(y_below_influence(0).value(), y_above_influence(0).value(), 1E-10); EXPECT_TRUE(CompareMatrices(y_below_influence(0).derivatives(), y_above_influence(0).derivatives(), 1E-10)); } } GTEST_TEST(MinimumValueLowerBoundConstraintTests, EvalNoValuesTest) { // Test with only lower bound on the minimal value, no upper bound. int num_vars{5}; int max_num_values{0}; double minimum_value_lower{0.1}; double influence_value{0.2}; MinimumValueLowerBoundConstraint dut_no_values( num_vars, minimum_value_lower, influence_value - minimum_value_lower, max_num_values, &ReturnNoValues<AutoDiffXd>); test::CheckConstraintEvalNonsymbolic(dut_no_values, AutoDiffVecXd::Zero(num_vars), kEps); } GTEST_TEST(MinimumValueUpperBoundConstraintTests, EvalNoValuesTest) { // Test with only upper bound on the minimal value, no lower bound. int num_vars{5}; int max_num_values{0}; double minimum_value_upper{0.1}; double influence_value{0.2}; MinimumValueUpperBoundConstraint dut_no_values( num_vars, minimum_value_upper, influence_value - minimum_value_upper, max_num_values, &ReturnNoValues<AutoDiffXd>); test::CheckConstraintEvalNonsymbolic(dut_no_values, AutoDiffVecXd::Zero(num_vars), kEps); } // Verify that Eval() throws for symbolic inputs. GTEST_TEST(MinimumValueLowerBoundConstraintTests, EvalSymbolicTest) { int num_vars{5}; int max_num_values{5}; double minimum_value_lower{0.1}; double influence_value{0.2}; MinimumValueLowerBoundConstraint dut( num_vars, minimum_value_lower, influence_value - minimum_value_lower, max_num_values, &SquareAndReturnAll<AutoDiffXd>); VectorX<symbolic::Variable> x{num_vars}; VectorX<symbolic::Expression> y; EXPECT_THROW(dut.Eval(x, &y), std::logic_error); } // Verify that Eval() throws for symbolic inputs. GTEST_TEST(MinimumValueUpperBoundConstraintTests, EvalSymbolicTest) { int num_vars{5}; int max_num_values{5}; double minimum_value_upper{0.1}; double influence_value{0.2}; MinimumValueUpperBoundConstraint dut( num_vars, minimum_value_upper, influence_value - minimum_value_upper, max_num_values, &SquareAndReturnAll<AutoDiffXd>); VectorX<symbolic::Variable> x{num_vars}; VectorX<symbolic::Expression> y; EXPECT_THROW(dut.Eval(x, &y), std::logic_error); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/mixed_integer_rotation_constraint_internal_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/solvers/mixed_integer_rotation_constraint_internal.h" /* clang-format on */ #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/random_rotation.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solve.h" using Eigen::Vector3d; namespace drake { namespace solvers { namespace { void CompareIntersectionResults(const std::vector<Vector3d>& desired, const std::vector<Vector3d>& actual) { EXPECT_EQ(desired.size(), actual.size()); Eigen::Matrix<bool, Eigen::Dynamic, 1> used = Eigen::Matrix<bool, Eigen::Dynamic, 1>::Constant(desired.size(), false); double tol = 1e-8; for (int i = 0; i < static_cast<int>(desired.size()); i++) { // need not be in the same order. bool found_match = false; for (int j = 0; j < static_cast<int>(desired.size()); j++) { if (used(j)) continue; if ((desired[i] - actual[j]).lpNorm<2>() < tol) { used(j) = true; found_match = true; break; } } EXPECT_TRUE(found_match); } } // For 2 binary variable per half axis, we know it cuts the first orthant into // 7 regions. 3 of these regions have 4 co-planar vertices; 3 of these regions // have 4 non-coplanar vertices, and one region has 3 vertices. GTEST_TEST(RotationTest, TestAreAllVerticesCoPlanar) { Eigen::Vector3d n; double d; // 4 co-planar vertices. std::array<std::pair<Eigen::Vector3d, Eigen::Vector3d>, 3> bmin_bmax_coplanar{ {{Eigen::Vector3d(0.5, 0.5, 0), Eigen::Vector3d(1, 1, 0.5)}, {Eigen::Vector3d(0.5, 0, 0.5), Eigen::Vector3d(1, 0.5, 1)}, {Eigen::Vector3d(0, 0.5, 0.5), Eigen::Vector3d(0.5, 1, 1)}}}; for (const auto& bmin_bmax : bmin_bmax_coplanar) { auto pts = internal::ComputeBoxEdgesAndSphereIntersection(bmin_bmax.first, bmin_bmax.second); EXPECT_TRUE(internal::AreAllVerticesCoPlanar(pts, &n, &d)); for (int i = 0; i < 4; ++i) { EXPECT_NEAR(n.norm(), 1, 1E-10); EXPECT_NEAR(n.dot(pts[i]), d, 1E-10); EXPECT_TRUE((n.array() > 0).all()); } } // 4 non co-planar vertices. std::array<std::pair<Eigen::Vector3d, Eigen::Vector3d>, 3> bmin_bmax_non_coplanar{ {{Eigen::Vector3d(0.5, 0, 0), Eigen::Vector3d(1, 0.5, 0.5)}, {Eigen::Vector3d(0, 0.5, 0), Eigen::Vector3d(0.5, 1, 0.5)}, {Eigen::Vector3d(0, 0, 0.5), Eigen::Vector3d(0.5, 0.5, 1)}}}; for (const auto& bmin_bmax : bmin_bmax_non_coplanar) { auto pts = internal::ComputeBoxEdgesAndSphereIntersection(bmin_bmax.first, bmin_bmax.second); EXPECT_FALSE(internal::AreAllVerticesCoPlanar(pts, &n, &d)); EXPECT_TRUE(CompareMatrices(n, Eigen::Vector3d::Zero())); EXPECT_EQ(d, 0); } // 3 vertices Eigen::Vector3d bmin(0.5, 0.5, 0.5); Eigen::Vector3d bmax(1, 1, 1); auto pts = internal::ComputeBoxEdgesAndSphereIntersection(bmin, bmax); EXPECT_TRUE(internal::AreAllVerticesCoPlanar(pts, &n, &d)); EXPECT_TRUE(CompareMatrices(n, Eigen::Vector3d::Constant(1.0 / std::sqrt(3)), 1E-10, MatrixCompareType::absolute)); EXPECT_NEAR(pts[0].dot(n), d, 1E-10); } void CheckInnerFacets(const std::vector<Vector3d>& pts) { // Compute the inner facets of the convex hull of pts. Make sure for each // facet, there are three points on the facet, and the facet points // outward from the origin. Eigen::Matrix<double, Eigen::Dynamic, 3> A; Eigen::VectorXd b; internal::ComputeInnerFacetsForBoxSphereIntersection(pts, &A, &b); for (int i = 0; i < A.rows(); ++i) { for (const auto& pt : pts) { EXPECT_LE((A.row(i) * pt)(0), b(i) + 1E-10); } EXPECT_NEAR(A.row(i).norm(), 1, 1E-10); // A.row(i) is the inverse of the facet normal, that points outward from the // origin. EXPECT_TRUE((A.row(i).array() <= 0).all()); int num_pts_on_plane = 0; for (const auto& pt : pts) { if (std::abs((A.row(i) * pt)(0) - b(i)) < 1E-10) { ++num_pts_on_plane; } } EXPECT_GE(num_pts_on_plane, 3); } } void CompareHalfspaceRelaxation(const std::vector<Vector3d>& pts) { // Computes a possibly less tight n and d analytically. For each triangle with // vertices pts[i], pts[j] and pts[k], determine if the halfspace coinciding // with the triangle is a cutting plane (namely all vertices in pts are on one // side of the halfspace). Compute the farthest distance from the cutting // planes to the origin. DRAKE_DEMAND(pts.size() >= 3); double d = -1; for (int i = 0; i < static_cast<int>(pts.size()); ++i) { for (int j = i + 1; j < static_cast<int>(pts.size()); ++j) { for (int k = j + 1; k < static_cast<int>(pts.size()); ++k) { // Find the normal of the triangle. Eigen::Vector3d normal_tmp = (pts[k] - pts[i]).cross(pts[j] - pts[i]); normal_tmp.normalize(); if (normal_tmp(0) < 0) { normal_tmp = -normal_tmp; } double d_tmp = normal_tmp.transpose() * pts[i]; bool is_cutting_plane = true; for (const auto& pt : pts) { if (pt.transpose() * normal_tmp < d_tmp - 1E-10) { is_cutting_plane = false; break; } } if (is_cutting_plane) { d = std::max(d, d_tmp); } } } } Eigen::Vector3d n_expected; double d_expected; internal::ComputeHalfSpaceRelaxationForBoxSphereIntersection(pts, &n_expected, &d_expected); if (pts.size() == 3) { EXPECT_NEAR(d_expected, d, 1E-6); } EXPECT_GE(d_expected, d - 1E-8); for (const auto& pt : pts) { EXPECT_GE(pt.transpose() * n_expected - d_expected, -1E-6); } } GTEST_TEST(RotationTest, TestHalfSpaceRelaxation) { // In some cases, the half space relaxation can be computed analytically. We // compare the analytical result, against // ComputeHalfSpaceRelaxationForBoxSphereIntersection() std::vector<Eigen::Vector3d> pts; Eigen::Vector3d n; double d; // For three points case, the half space relaxation is just the plane // coinciding with the three points. pts.emplace_back(1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0); pts.emplace_back(2.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0); pts.emplace_back(2.0 / 3.0, 2.0 / 3.0, 1.0 / 3.0); internal::ComputeHalfSpaceRelaxationForBoxSphereIntersection(pts, &n, &d); EXPECT_TRUE(CompareMatrices(n, Eigen::Vector3d::Constant(1 / std::sqrt(3)), 10 * std::numeric_limits<double>::epsilon(), MatrixCompareType::absolute)); EXPECT_NEAR(d, std::sqrt(3) * 5 / 9, 1E-10); // Four points, symmetric about the plane x = y. The tightest half space // relaxation is not the plane coinciding with any three of the points, but // just coinciding with two of the points. pts.clear(); // The first two points are on the x = y plane. pts.emplace_back(1.0 / 3.0, 1.0 / 3.0, std::sqrt(7) / 3.0); pts.emplace_back(2.0 / 3.0, 2.0 / 3.0, 1.0 / 3.0); // The last two points are symmetric about the x = y plane. pts.emplace_back(1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0); pts.emplace_back(2.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0); internal::ComputeHalfSpaceRelaxationForBoxSphereIntersection(pts, &n, &d); // The normal vector should be on the x = y plane. EXPECT_NEAR(n(0), n(1), 1E-8); EXPECT_NEAR(n.dot(pts[0]), d, 1E-8); EXPECT_NEAR(n.dot(pts[1]), d, 1E-8); } GTEST_TEST(RotationTest, TestInnerFacetsAndHalfSpace) { // We show that the inner facet is tighter than the half space for some case. // To this end, we show that for a box [0 0.5 0] <= x <= [0.5 1 0.5], there is // some point that does not satisfy the inner facets constraint A*x<=b, but // satisfies the half space constraint nᵀ*x>=d. const Eigen::Vector3d bmin(0, 0.5, 0); const Eigen::Vector3d bmax(0.5, 1, 0.5); const auto intersection_pts = internal::ComputeBoxEdgesAndSphereIntersection(bmin, bmax); DRAKE_DEMAND(intersection_pts.size() == 4); Eigen::Vector3d n; double d; internal::ComputeHalfSpaceRelaxationForBoxSphereIntersection(intersection_pts, &n, &d); Eigen::Matrix<double, Eigen::Dynamic, 3> A; Eigen::VectorXd b; internal::ComputeInnerFacetsForBoxSphereIntersection(intersection_pts, &A, &b); // Now form the optimization program // A.row(i) * x > b(i) + epsilon for at least one i // nᵀ * x >= d // bmin <= x <= bmax // We will show that there is a feasible solution to this program. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>("x"); auto z = prog.NewBinaryVariables(b.rows(), "z"); for (int i = 0; i < b.rows(); ++i) { prog.AddLinearConstraint((A.row(i) * x)(0) >= b(i) + 1E-5 + (z(i) - 1) * 2); } prog.AddLinearConstraint(z.cast<symbolic::Expression>().sum() >= 1); prog.AddLinearConstraint(n.dot(x) >= d); prog.AddBoundingBoxConstraint(bmin, bmax, x); const MathematicalProgramResult result = Solve(prog); EXPECT_TRUE(result.is_success()); } // Test a number of closed-form solutions for the intersection of a box in the // positive orthant with the unit circle. GTEST_TEST(RotationTest, TestIntersectBoxWithCircle) { std::vector<Vector3d> desired; // Entire first octant. Vector3d box_min(0, 0, 0); Vector3d box_max(1, 1, 1); desired.push_back(Vector3d(1, 0, 0)); desired.push_back(Vector3d(0, 1, 0)); desired.push_back(Vector3d(0, 0, 1)); CompareIntersectionResults( desired, internal::ComputeBoxEdgesAndSphereIntersection(box_min, box_max)); CompareHalfspaceRelaxation(desired); CheckInnerFacets(desired); // Lifts box bottom (in z). Still has 3 solutions. box_min << 0, 0, 1.0 / 3.0; desired[0] << std::sqrt(8) / 3.0, 0, 1.0 / 3.0; desired[1] << 0, std::sqrt(8) / 3.0, 1.0 / 3.0; CompareIntersectionResults( desired, internal::ComputeBoxEdgesAndSphereIntersection(box_min, box_max)); CompareHalfspaceRelaxation(desired); CheckInnerFacets(desired); // Lowers box top (in z). Now we have four solutions. box_max << 1, 1, 2.0 / 3.0; desired[2] << std::sqrt(5) / 3.0, 0, 2.0 / 3.0; desired.push_back(Vector3d(0, std::sqrt(5) / 3.0, 2.0 / 3.0)); CompareIntersectionResults( desired, internal::ComputeBoxEdgesAndSphereIntersection(box_min, box_max)); CompareHalfspaceRelaxation(desired); CheckInnerFacets(desired); // Gets a different four edges by shortening the box (in x). box_max(0) = .5; desired[0] << .5, std::sqrt(23.0) / 6.0, 1.0 / 3.0; desired[2] << .5, std::sqrt(11.0) / 6.0, 2.0 / 3.0; CompareIntersectionResults( desired, internal::ComputeBoxEdgesAndSphereIntersection(box_min, box_max)); CompareHalfspaceRelaxation(desired); CheckInnerFacets(desired); // Now three edges again as we shorten the box (in y). box_max(1) = .6; desired.pop_back(); desired[0] << .5, std::sqrt(11.0) / 6.0, 2.0 / 3.0; desired[1] << 2 * std::sqrt(11.0) / 15.0, .6, 2.0 / 3.0; desired[2] << .5, .6, std::sqrt(39.0) / 10.0; CompareIntersectionResults( desired, internal::ComputeBoxEdgesAndSphereIntersection(box_min, box_max)); CompareHalfspaceRelaxation(desired); CheckInnerFacets(desired); // All four intersections are on the vertical edges. box_min << 1.0 / 3.0, 1.0 / 3.0, 0; box_max << 2.0 / 3.0, 2.0 / 3.0, 1; desired[0] << 1.0 / 3.0, 1.0 / 3.0, std::sqrt(7.0) / 3.0; desired[1] << 2.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0; desired[2] << 1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0; desired.push_back(Vector3d(2.0 / 3.0, 2.0 / 3.0, 1.0 / 3.0)); CompareIntersectionResults( desired, internal::ComputeBoxEdgesAndSphereIntersection(box_min, box_max)); CompareHalfspaceRelaxation(desired); CheckInnerFacets(desired); // box_max right on the unit sphere. box_max << 1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0; box_min << 0, 1.0 / 3.0, 0; // Should return just the single point. desired.erase(desired.begin() + 1, desired.end()); desired[0] = box_max; CompareIntersectionResults( desired, internal::ComputeBoxEdgesAndSphereIntersection(box_min, box_max)); CheckInnerFacets(desired); // Multiple vertices are on the sphere. box_min << 1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0; box_max << 2.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0; desired.clear(); desired.push_back(Eigen::Vector3d(1.0 / 3, 2.0 / 3, 2.0 / 3)); desired.push_back(Eigen::Vector3d(2.0 / 3, 1.0 / 3, 2.0 / 3)); desired.push_back(Eigen::Vector3d(2.0 / 3, 2.0 / 3, 1.0 / 3)); CompareIntersectionResults( desired, internal::ComputeBoxEdgesAndSphereIntersection(box_min, box_max)); CheckInnerFacets(desired); // Six intersections. box_min = Eigen::Vector3d::Constant(1.0 / 3.0); box_max = Eigen::Vector3d::Constant(sqrt(6) / 3.0); desired.clear(); // The intersecting points are the 6 permutations of // (1.0 / 3.0, sqrt(2) / 3.0, sqrt(6) / 3.0) desired.resize(6); desired[0] << 1.0 / 3.0, sqrt(2) / 3.0, sqrt(6) / 3.0; desired[1] << 1.0 / 3.0, sqrt(6) / 3.0, sqrt(2) / 3.0; desired[2] << sqrt(2) / 3.0, 1.0 / 3.0, sqrt(6) / 3.0; desired[3] << sqrt(2) / 3.0, sqrt(6) / 3.0, 1.0 / 3.0; desired[4] << sqrt(6) / 3.0, 1.0 / 3.0, sqrt(2) / 3.0; desired[5] << sqrt(6) / 3.0, sqrt(2) / 3.0, 1.0 / 3.0; CompareIntersectionResults( desired, internal::ComputeBoxEdgesAndSphereIntersection(box_min, box_max)); CompareHalfspaceRelaxation(desired); CheckInnerFacets(desired); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/mixed_integer_rotation_constraint_limit_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/solvers/mixed_integer_rotation_constraint.h" /* clang-format on */ #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/gurobi_solver.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/rotation_constraint.h" namespace drake { namespace solvers { // The goal of this class is to measure how well we can approximate the // constraint on SO(3). To do so, we choose to compute the closest distance // between R.col(0) and R.col(1), where `R` satisfies our relaxation. // If `R` satisfies the SO(3) constraint exactly, then the closest distance // is sqrt(2). Due to the relaxation, we should see the closest distance // being smaller than sqrt(2). // This test records how well we can approximate the rotation matrix on SO(3). // If in the future we improved our relaxation and get a larger minimal // distance, please update this test. class TestMinimumDistance : public testing::TestWithParam< std::tuple<MixedIntegerRotationConstraintGenerator::Approach, int>> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(TestMinimumDistance) TestMinimumDistance() : prog_(), R_(NewRotationMatrixVars(&prog_)), d_(prog_.NewContinuousVariables<1>("d")), approach_(std::get<0>(GetParam())), num_intervals_per_half_axis_(std::get<1>(GetParam())), minimal_distance_expected_(0) { MixedIntegerRotationConstraintGenerator rotation_generator( approach_, num_intervals_per_half_axis_, IntervalBinning::kLogarithmic); rotation_generator.AddToProgram(R_, &prog_); // Add the constraint that d_ >= |R_.col(0) - R_.col(1)| Vector4<symbolic::Expression> s; s << d_(0), R_.col(0) - R_.col(1); prog_.AddLorentzConeConstraint(s); // Minimize the distance. prog_.AddCost(d_(0)); } ~TestMinimumDistance() override {} void SetMinimumDistanceExpected() { DoSetMinimumDistanceExpected(); } void SolveAndCheckSolution() { GurobiSolver gurobi_solver; if (gurobi_solver.available()) { prog_.SetSolverOption(GurobiSolver::id(), "OutputFlag", true); auto result = gurobi_solver.Solve(prog_, {}, {}); EXPECT_TRUE(result.is_success()); double d_val = result.GetSolution(d_(0)); EXPECT_NEAR(d_val, minimal_distance_expected_, 1E-2); } } protected: MathematicalProgram prog_; MatrixDecisionVariable<3, 3> R_; VectorDecisionVariable<1> d_; MixedIntegerRotationConstraintGenerator::Approach approach_; int num_intervals_per_half_axis_; double minimal_distance_expected_; private: virtual void DoSetMinimumDistanceExpected() { // Update the expected minimal distance, when we improve the relaxation on // SO(3). std::array<double, 3> min_distance; // Record the global minimal for // different number of intervals per // half axis {1, 2, 3}. switch (approach_) { case MixedIntegerRotationConstraintGenerator::Approach:: kBoxSphereIntersection: { min_distance = {{0.069166, 0.974, 1.0823199}}; break; } case MixedIntegerRotationConstraintGenerator::Approach:: kBilinearMcCormick: { min_distance = {{0.60229, 1.22474, 1.32667}}; break; } case MixedIntegerRotationConstraintGenerator::Approach::kBoth: { min_distance = {{0.60302, 1.25649, 1.33283}}; break; } } minimal_distance_expected_ = min_distance[num_intervals_per_half_axis_ - 1]; } }; class TestMinimumDistanceWOrthonormalSocp : public TestMinimumDistance { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(TestMinimumDistanceWOrthonormalSocp) TestMinimumDistanceWOrthonormalSocp() : TestMinimumDistance() { AddRotationMatrixOrthonormalSocpConstraint(&prog_, R_); } ~TestMinimumDistanceWOrthonormalSocp() override {} private: void DoSetMinimumDistanceExpected() override { // Update the expected minimal distance, when we improve the relaxation on // SO(3). switch (num_intervals_per_half_axis_) { case 1: { minimal_distance_expected_ = 0.06916; break; } case 2: { minimal_distance_expected_ = 1.19452; break; } case 3: { minimal_distance_expected_ = 1.3056; break; } default: { throw std::runtime_error( "Have not attempted this number of binary variables yet."); } } } }; TEST_P(TestMinimumDistance, Test) { SetMinimumDistanceExpected(); SolveAndCheckSolution(); } TEST_P(TestMinimumDistanceWOrthonormalSocp, Test) { SetMinimumDistanceExpected(); SolveAndCheckSolution(); } INSTANTIATE_TEST_SUITE_P( RotationTest, TestMinimumDistance, ::testing::Combine( ::testing::ValuesIn< std::vector<MixedIntegerRotationConstraintGenerator::Approach>>( {MixedIntegerRotationConstraintGenerator::Approach:: kBoxSphereIntersection, MixedIntegerRotationConstraintGenerator::Approach:: kBilinearMcCormick}), ::testing::ValuesIn<std::vector<int>>( {1, 2, 3}))); // number of binary variables per half axis INSTANTIATE_TEST_SUITE_P( RotationTest, TestMinimumDistanceWOrthonormalSocp, ::testing::Combine( ::testing::ValuesIn< std::vector<MixedIntegerRotationConstraintGenerator::Approach>>( {MixedIntegerRotationConstraintGenerator::Approach:: kBoxSphereIntersection}), ::testing::ValuesIn<std::vector<int>>( {1, 2, 3}))); // number of binary variables per half axis } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/linear_system_solver_test.cc
#include "drake/solvers/linear_system_solver.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/solvers/solve.h" #include "drake/solvers/test/mathematical_program_test_util.h" #include "drake/solvers/test/optimization_examples.h" using ::testing::HasSubstr; namespace drake { namespace solvers { namespace test { namespace { void TestLinearSystemExample(LinearSystemExample1* example) { const MathematicalProgram& prog = *example->prog(); EXPECT_TRUE(LinearSystemSolver::ProgramAttributesSatisfied(prog)); EXPECT_EQ(LinearSystemSolver::UnsatisfiedProgramAttributes(prog), ""); const MathematicalProgramResult result = Solve(prog); EXPECT_TRUE(result.is_success()); example->CheckSolution(result); } } // namespace GTEST_TEST(testLinearSystemSolver, trivialExample) { LinearSystemExample1 example1{}; TestLinearSystemExample(&example1); LinearSystemExample2 example2{}; TestLinearSystemExample(&example2); LinearSystemExample3 example3{}; TestLinearSystemExample(&example3); } GTEST_TEST(testLinearSystemSolver, EmptyProblem) { MathematicalProgram prog; EXPECT_FALSE(LinearSystemSolver::ProgramAttributesSatisfied(prog)); EXPECT_THAT(LinearSystemSolver::UnsatisfiedProgramAttributes(prog), HasSubstr("LinearEqualityConstraint is required")); LinearSystemSolver solver; DRAKE_EXPECT_THROWS_MESSAGE(solver.Solve(prog), ".*LinearEqualityConstraint is required.*"); } GTEST_TEST(testLinearSystemSolver, QuadraticProblem) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<1>(); prog.AddQuadraticCost(x(0) * x(0)); EXPECT_FALSE(LinearSystemSolver::ProgramAttributesSatisfied(prog)); EXPECT_THAT(LinearSystemSolver::UnsatisfiedProgramAttributes(prog), HasSubstr("QuadraticCost was declared")); LinearSystemSolver solver; DRAKE_EXPECT_THROWS_MESSAGE(solver.Solve(prog), ".*QuadraticCost was declared.*"); } /** * Simple linear system without a solution * 3 * x = 1 * 2 * x + y = 2 * x - y = 0 */ GTEST_TEST(testLinearSystemSolver, InfeasibleProblem) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint(3 * x(0) == 1 && 2 * x(0) + x(1) == 2 && x(0) - x(1) == 0); const MathematicalProgramResult result = Solve(prog); EXPECT_FALSE(result.is_success()); // The solution should minimize the error ||b - A * x||₂ // x_expected is computed as (Aᵀ*A)⁻¹*(Aᵀ*b) Eigen::Vector2d x_expected(12.0 / 27, 21.0 / 27); EXPECT_TRUE(CompareMatrices(result.GetSolution(x), x_expected, 1E-12, MatrixCompareType::absolute)); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kGlobalInfeasibleCost); } /** * Under-determined linear system * 3 * x + y = 1 * x + z = 2 */ GTEST_TEST(testLinearSystemSolver, UnderDeterminedProblem) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); prog.AddLinearConstraint(3 * x(0) + x(1) == 1 && x(0) + x(2) == 2); const MathematicalProgramResult result = Solve(prog); EXPECT_TRUE(result.is_success()); // The solution should minimize the norm ||x||₂ // x_expected is computed as the solution to // [2*I -Aᵀ] * [x] = [0] // [ A 0 ] [λ] [b] Eigen::Vector3d x_expected(5.0 / 11, -4.0 / 11, 17.0 / 11); EXPECT_TRUE(CompareMatrices(result.GetSolution(x), x_expected, 1E-12, MatrixCompareType::absolute)); } GTEST_TEST(testLinearSystemSolver, linearMatrixEqualityExample) { LinearMatrixEqualityExample example{}; const auto result = Solve(*(example.prog())); EXPECT_EQ(result.get_solver_id(), LinearSystemSolver::id()); example.CheckSolution(result); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/sos_constraint_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/solvers/mathematical_program.h" /* clang-format on */ #include <gtest/gtest.h> #include "drake/common/symbolic/expression.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/test_utilities/symbolic_test_util.h" #include "drake/solvers/solve.h" namespace drake { namespace solvers { namespace { using drake::symbolic::Expression; using drake::symbolic::Monomial; using drake::symbolic::Variable; using drake::symbolic::Variables; using drake::symbolic::internal::DegreeType; class SosConstraintTest : public ::testing::Test { public: void CheckNewFreePolynomial(const symbolic::Polynomial& p, const Variables& indeterminates, const int degree, DegreeType degree_type) { const drake::VectorX<symbolic::Monomial> monomial_basis{ symbolic::internal::ComputeMonomialBasis<Eigen::Dynamic>( indeterminates, degree, degree_type)}; switch (degree_type) { case DegreeType::kAny: { EXPECT_EQ(p.TotalDegree(), degree); break; } case DegreeType::kEven: { // p.TotalDegree() should be the largest even number that is no // larger than @p degree. EXPECT_EQ(p.TotalDegree(), degree % 2 == 0 ? degree : degree - 1); break; } case DegreeType::kOdd: { // p.TotalDegree() should be the largest odd number that is no // larger than @p degree. EXPECT_EQ(p.TotalDegree(), degree % 2 == 1 ? degree : degree - 1); break; } } EXPECT_EQ(p.monomial_to_coefficient_map().size(), monomial_basis.size()); EXPECT_EQ(p.monomial_to_coefficient_map().size(), p.decision_variables().size()); for (const auto& pair : p.monomial_to_coefficient_map()) { // Each coefficient is a single decision variable. const Expression& coeff_i{pair.second}; ASSERT_TRUE(is_variable(coeff_i)); const Variable& decision_variable_i{get_variable(coeff_i)}; // This decision_variable_i in the polynomial should be a decision // variable in the MathematicalProgram. DRAKE_EXPECT_NO_THROW( unused(prog_.FindDecisionVariableIndex(decision_variable_i))); switch (degree_type) { case DegreeType::kAny: { break; } case DegreeType::kEven: { EXPECT_EQ(pair.first.total_degree() % 2, 0); break; } case DegreeType::kOdd: { EXPECT_EQ(pair.first.total_degree() % 2, 1); break; } } } } void TestNewFreePolynomial(const Variables& indeterminates, int degree) { const symbolic::Polynomial poly1{ prog_.NewFreePolynomial(indeterminates, degree)}; CheckNewFreePolynomial(poly1, indeterminates, degree, DegreeType::kAny); const symbolic::Polynomial poly2{ prog_.NewEvenDegreeFreePolynomial(indeterminates, degree)}; CheckNewFreePolynomial(poly2, indeterminates, degree, DegreeType::kEven); const symbolic::Polynomial poly3{ prog_.NewOddDegreeFreePolynomial(indeterminates, degree)}; CheckNewFreePolynomial(poly3, indeterminates, degree, DegreeType::kOdd); } void CheckNewSosPolynomial(const symbolic::Polynomial& p, const MatrixXDecisionVariable& Q, const Variables& indeterminates, const int degree) { // p = xᵀ*Q*x. // where x = monomial_basis(indeterminates, degree) and // Q is p.s.d. const drake::VectorX<symbolic::Monomial> monomial_basis{ symbolic::MonomialBasis(indeterminates, degree / 2)}; EXPECT_EQ(p.TotalDegree(), degree); // Number of coefficients == number of distinct entries in a symmetric // matrix of size n x n where n = monomial_basis.size(). EXPECT_EQ(p.decision_variables().size(), monomial_basis.size() * (monomial_basis.size() + 1) / 2); // Q is the coefficient matrix of p. VectorXDecisionVariable Q_flat(Q.size()); for (int i = 0; i < Q.cols(); ++i) { Q_flat.segment(i * Q.rows(), Q.rows()) = Q.col(i); } EXPECT_EQ(p.decision_variables(), Variables(Q_flat)); result_ = Solve(prog_); CheckPositiveDefiniteMatrix(Q, monomial_basis, p.ToExpression()); } // Checks Q has all eigen values as approximately non-negatives. // Precondition: result_ = Solve(prog_) has been called. void CheckPositiveDefiniteMatrix( const MatrixXDecisionVariable& Q, const Eigen::Ref<const VectorX<symbolic::Monomial>>& monomial_basis, const symbolic::Expression& sos_poly_expected, const double eps = 1e-07) { const Eigen::MatrixXd Q_val = result_.GetSolution(Q); Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(Q_val); EXPECT_TRUE((es.eigenvalues().array() >= -eps).all()); // Compute mᵀ * Q * m; symbolic::Polynomial sos_poly{}; for (int i = 0; i < Q_val.rows(); ++i) { sos_poly.AddProduct(Q_val(i, i), pow(monomial_basis(i), 2)); for (int j = i + 1; j < Q_val.cols(); ++j) { sos_poly.AddProduct(Q_val(i, j) + Q_val(j, i), monomial_basis(i) * monomial_basis(j)); } } symbolic::Polynomial diff_poly = sos_poly - symbolic::Polynomial(result_.GetSolution(sos_poly_expected)); diff_poly = diff_poly.RemoveTermsWithSmallCoefficients(eps); const symbolic::Polynomial zero_poly{}; EXPECT_PRED2(symbolic::test::PolyEqual, diff_poly, zero_poly); } protected: void SetUp() override { x_ = prog_.NewIndeterminates<3>(); c_ = prog_.NewContinuousVariables<1>(); } MathematicalProgram prog_; VectorIndeterminate<3> x_; VectorDecisionVariable<1> c_; MathematicalProgramResult result_; }; TEST_F(SosConstraintTest, NewFreePolynomialUnivariateDegree) { const auto& x = x_(0); const Variables indeterminates{x}; TestNewFreePolynomial(indeterminates, 1); TestNewFreePolynomial(indeterminates, 2); TestNewFreePolynomial(indeterminates, 3); } TEST_F(SosConstraintTest, NewFreePolynomialMultivariateDegree) { const auto& x0 = x_(0); const auto& x1 = x_(1); const Variables indeterminates{x0, x1}; TestNewFreePolynomial(indeterminates, 1); TestNewFreePolynomial(indeterminates, 2); TestNewFreePolynomial(indeterminates, 3); } TEST_F(SosConstraintTest, NewSosPolynomialUnivariate1) { const auto& x = x_(0); const Variables indeterminates{x}; const int degree{2}; const auto p = prog_.NewSosPolynomial(indeterminates, degree); const symbolic::Polynomial& poly{p.first}; const MatrixXDecisionVariable& Q{p.second}; CheckNewSosPolynomial(poly, Q, indeterminates, degree); } TEST_F(SosConstraintTest, NewSosPolynomialUnivariate2) { const auto& x = x_(0); const Variables indeterminates{x}; const int degree{4}; const auto p = prog_.NewSosPolynomial(indeterminates, degree); const symbolic::Polynomial& poly{p.first}; const MatrixXDecisionVariable& Q{p.second}; CheckNewSosPolynomial(poly, Q, indeterminates, degree); } TEST_F(SosConstraintTest, NewSosPolynomialMultivariate1) { const auto& x0 = x_(0); const auto& x1 = x_(1); const Variables indeterminates{x0, x1}; const int degree{2}; const auto p = prog_.NewSosPolynomial(indeterminates, degree); const symbolic::Polynomial& poly{p.first}; const MatrixXDecisionVariable& Q{p.second}; CheckNewSosPolynomial(poly, Q, indeterminates, degree); } TEST_F(SosConstraintTest, NewSosPolynomialMultivariate2) { const auto& x0 = x_(0); const auto& x1 = x_(1); const auto& x2 = x_(2); const Variables indeterminates{x0, x1, x2}; const int degree{4}; const auto p = prog_.NewSosPolynomial(indeterminates, degree); const symbolic::Polynomial& poly{p.first}; const MatrixXDecisionVariable& Q{p.second}; CheckNewSosPolynomial(poly, Q, indeterminates, degree); } TEST_F(SosConstraintTest, NewSosPolynomialViaMonomialBasis) { const auto& x0 = x_(0); const auto& x1 = x_(1); Vector2<Monomial> basis{x0, x1}; const auto p = prog_.NewSosPolynomial(basis); const symbolic::Polynomial& poly{p.first}; const MatrixXDecisionVariable& Q = p.second; const symbolic::Polynomial expected_poly{ Q(0, 0) * x0 * x0 + 2 * Q(0, 1) * x0 * x1 + Q(1, 1) * x1 * x1, symbolic::Variables({x0, x1})}; EXPECT_TRUE(poly.EqualTo(expected_poly)); } // Shows that f(x) = 2x² + 2x + 1 is SOS. TEST_F(SosConstraintTest, AddSosConstraintUnivariate1) { const auto& x = x_(0); const symbolic::Expression e = 2 * pow(x, 2) + 2 * x + 1; MatrixXDecisionVariable Q; VectorX<symbolic::Monomial> m; std::tie(Q, m) = prog_.AddSosConstraint(e); result_ = Solve(prog_); ASSERT_TRUE(result_.is_success()); CheckPositiveDefiniteMatrix(Q, m, e); } // Finds the global minimum of f(x) = x⁶ − 10x⁵ + 51x⁴ − 166x³ + 342x² − 400x + // 200, which should be close to zero. The example is taken from page 12 of // http://www.mit.edu/~parrilo/cdc03_workshop/08_sum_of_squares_2003_12_07_07_screen.pdf. TEST_F(SosConstraintTest, AddSosConstraintUnivariate2) { const auto& x = x_(0); const auto& c = c_(0); prog_.AddCost(-c); const symbolic::Expression e = pow(x, 6) - 10 * pow(x, 5) + 51 * pow(x, 4) - 166 * pow(x, 3) + 342 * pow(x, 2) - 400 * x + 200 - c; MatrixXDecisionVariable Q; VectorX<symbolic::Monomial> m; std::tie(Q, m) = prog_.AddSosConstraint(e); result_ = Solve(prog_); ASSERT_TRUE(result_.is_success()); EXPECT_LE(result_.GetSolution(c), 1E-4); // Fails with tolerance 1E-6 with solver MOSEK when run under Valgrind. CheckPositiveDefiniteMatrix(Q, m, e, 1.03E-6 /* eps */); } // Shows that f(x₀, x₁) = 2x₀⁴ + 2x₀³x₁ - x₀²x₁² + 5x₁⁴ is SOS. TEST_F(SosConstraintTest, AddSosConstraintMultivariate1) { const auto& x0 = x_(0); const auto& x1 = x_(1); const symbolic::Expression e = 2 * pow(x0, 4) + 2 * pow(x0, 3) * x1 - pow(x0, 2) * pow(x1, 2) + 5 * pow(x1, 4); MatrixXDecisionVariable Q; VectorX<symbolic::Monomial> m; std::tie(Q, m) = prog_.AddSosConstraint(e); result_ = Solve(prog_); ASSERT_TRUE(result_.is_success()); CheckPositiveDefiniteMatrix(Q, m, e); } TEST_F(SosConstraintTest, AddSosPolynomialViaMonomialBasis) { const auto& x = x_(0); Vector2<Monomial> basis{1, x}; const symbolic::Expression e = 2 * pow(x, 2) + 2 * x + 1; const auto Q = prog_.AddSosConstraint(e, basis); result_ = Solve(prog_); ASSERT_TRUE(result_.is_success()); CheckPositiveDefiniteMatrix(Q, basis, e); } // Finds the global minimum of the non-convex polynomial f(x₀, x₁) = 4 * x₀² − // 21 / 10 * x₀⁴ + 1 / 3 * x₀⁶ + x₀ * x₁ − 4 * x₁² + 4 * x₁⁴ through the // following convex program max c s.t f(x₀, x₁) - c is sum-of-squares. The // global minimum value is -1.0316. The example is taken from page 19 of // https://stanford.edu/class/ee364b/lectures/sos_slides.pdf TEST_F(SosConstraintTest, AddSosConstraintMultivariate2) { const auto& x0 = x_(0); const auto& x1 = x_(1); const auto& c = c_(0); prog_.AddCost(-c); const symbolic::Expression e = 4 * pow(x0, 2) - 2.1 * pow(x0, 4) + 1.0 / 3.0 * pow(x0, 6) + x0 * x1 - 4 * x1 * x1 + 4 * pow(x1, 4) - c; MatrixXDecisionVariable Q; VectorX<symbolic::Monomial> m; std::tie(Q, m) = prog_.AddSosConstraint(e); result_ = Solve(prog_); ASSERT_TRUE(result_.is_success()); EXPECT_NEAR(result_.GetSolution(c), -1.0316, 1E-4); CheckPositiveDefiniteMatrix(Q, m, e); } TEST_F(SosConstraintTest, SynthesizeLyapunovFunction) { // Find the Lyapunov function V(x) for system: // // ẋ₀ = -x₁ + 1.5x₀² - 0.5x₀³ // ẋ₁ = 3x₀ - x₁ // // by solving sum-of-squared problems: // // V(x) is sum-of-squares // -V̇(x) is sum-of-squares VectorX<Variable> x = prog_.NewIndeterminates<2>(); const auto& x0 = x(0); const auto& x1 = x(1); // Form the dynamics of the system. Vector2<symbolic::Polynomial> dynamics; // clang-format off dynamics << symbolic::Polynomial{-x1 + 1.5 * x0 * x0 - 0.5 * pow(x0, 3)}, symbolic::Polynomial{3 * x0 - x1}; // clang-format on // Adds V(x) as a 4th order sum-of-squares polynomial. const symbolic::Polynomial V{prog_.NewSosPolynomial({x0, x1}, 4).first}; // Computes Vdot. const symbolic::Polynomial Vdot = V.Jacobian(x).transpose().dot(dynamics); // -Vdot is sum-of-squares. prog_.AddSosConstraint(-Vdot); result_ = Solve(prog_); ASSERT_TRUE(result_.is_success()); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/quadratic_program_examples.h
#pragma once #include <memory> #include <ostream> #include <tuple> #include <vector> #include "drake/solvers/test/optimization_examples.h" namespace drake { namespace solvers { namespace test { enum class QuadraticProblems { kQuadraticProgram0 = 0, kQuadraticProgram1 = 1, kQuadraticProgram2 = 2, kQuadraticProgram3 = 3, kQuadraticProgram4 = 4, }; std::ostream& operator<<(std::ostream& os, QuadraticProblems value); class QuadraticProgramTest : public ::testing::TestWithParam< std::tuple<CostForm, ConstraintForm, QuadraticProblems>> { public: QuadraticProgramTest(); OptimizationProgram* prob() const { return prob_.get(); } private: std::unique_ptr<OptimizationProgram> prob_; }; std::vector<QuadraticProblems> quadratic_problems(); // Test a simple Quadratic Program. // The example is taken from // http://cvxopt.org/examples/tutorial/qp.html // min 2x1^2 + x2^2 + x1x2 + x1 + x2 // s.t x1 >= 0 // x2 >= 0 // x1 + x2 = 1 class QuadraticProgram0 : public OptimizationProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(QuadraticProgram0) QuadraticProgram0(CostForm cost_form, ConstraintForm constraint_form); ~QuadraticProgram0() override = default; void CheckSolution(const MathematicalProgramResult& result) const override; private: VectorDecisionVariable<2> x_; Eigen::Vector2d x_expected_; }; // Adapted from the simple test on the Gurobi documentation. // min x^2 + x*y + y^2 + y*z + z^2 + 2 x // subj to 4 <= x + 2 y + 3 z <= inf // -inf <= -x - y <= -1 // -20 <= y + 2 z <= 100 // -inf <= x + y + 2 z <= inf // 3 x + y + 3 z = 3 // x, y, z >= 0 // The optimal solution is (0, 1, 2/3) class QuadraticProgram1 : public OptimizationProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(QuadraticProgram1) QuadraticProgram1(CostForm cost_form, ConstraintForm constraint_form); ~QuadraticProgram1() override = default; void CheckSolution(const MathematicalProgramResult& result) const override; private: VectorDecisionVariable<3> x_; Eigen::Vector3d x_expected_; }; // Closed form (exact) solution test of QP problem. // Note that for any Positive Semi Definite matrix Q : // min 0.5x'Qx + bx = -Q^(-1) * b // The values were chosen at random but were hardcoded // to enable test reproducibility. // The test also verifies the quadratic program works when // matrix Q has off-diagonal terms. class QuadraticProgram2 : public OptimizationProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(QuadraticProgram2) QuadraticProgram2(CostForm cost_form, ConstraintForm constraint_form); ~QuadraticProgram2() override = default; void CheckSolution(const MathematicalProgramResult& result) const override; private: VectorDecisionVariable<5> x_; Eigen::Matrix<double, 5, 1> x_expected_; }; // Closed form (exact) solution test of QP problem. // Added as multiple QP cost terms // Note that for any Positive Semi Definite matrix Q : // min 0.5x'Qx + bx = -Q^(-1) * b // The values were chosen at random but were hardcoded // to enable test reproducibility. // We impose the cost // 0.5 * x.head<4>()'*Q1 * x.head<4>() + b1'*x.head<4>() // + 0.5 * x.tail<4>()'*Q2 * x.tail<4>() + b2'*x.tail<4>() // This is to test that we can add multiple costs for the same variables (in // this case, the quadratic costs on x(2), x(3) are added for twice). class QuadraticProgram3 : public OptimizationProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(QuadraticProgram3); QuadraticProgram3(CostForm cost_form, ConstraintForm constraint_form); ~QuadraticProgram3() override = default; void CheckSolution(const MathematicalProgramResult& result) const override; private: VectorDecisionVariable<6> x_; Vector6d x_expected_; }; // Test the simple QP // min x(0)^2 + x(1)^2 + 2 * x(2)^2 // s.t x(0) + x(1) = 1 // x(0) + 2*x(2) = 2 // The optimal solution should be // x(0) = 4/5, x(1) = 1/5, x(2) = 3/5 class QuadraticProgram4 : public OptimizationProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(QuadraticProgram4) QuadraticProgram4(CostForm cost_form, ConstraintForm constraint_form); ~QuadraticProgram4() override = default; void CheckSolution(const MathematicalProgramResult& result) const override; private: VectorDecisionVariable<3> x_; Eigen::Vector3d x_expected_; }; // Solve a series of QPs with the objective being the Euclidean distance // from a desired point which moves along the unit circle (L2 ball), to a point // constrained to lie inside the L1 ball. Implemented in 2D, so that the // active set moves along 4 faces of the L1 ball. void TestQPonUnitBallExample(const SolverInterface& solver); /** * Test getting the dual solution for a QP problem. * This QP problem has active linear equality constraints. */ void TestQPDualSolution1(const SolverInterface& solver, const SolverOptions& solver_options = {}, double tol = 1e-6); /** * Test getting the dual solution for a QP problem. * This QP problem has active linear inequality constraints. */ void TestQPDualSolution2(const SolverInterface& solver); /** * Test getting the dual solution for a QP problem. * This QP problem has active bounding box constraints. * @param tol The tolerance on checking the solution. * @param sensitivity_tol The tolerance on checking the constraint sensitivity. */ void TestQPDualSolution3(const SolverInterface& solver, double tol = 1e-6, double sensitivity_tol = 2e-5); /** * Test getting the dual solution for an equality constrained QP. */ void TestEqualityConstrainedQPDualSolution1(const SolverInterface& solver); /** * Test getting the dual solution for an equality constrained QP. */ void TestEqualityConstrainedQPDualSolution2(const SolverInterface& solver); /** * Test nonconvex QP. */ void TestNonconvexQP(const SolverInterface& solver, bool convex_solver, double tol = 1E-5); /** Test formulating a QP where adding costs or constraints where the `vars` vector will have repeated entries for given variables. */ void TestDuplicatedVariableQuadraticProgram(const SolverInterface& solver, double tol = 1E-7); /** This program is reported in https://github.com/RobotLocomotion/drake/issues/19524 This program has infinitely many equally good optimal solution. */ void TestEqualityConstrainedQP1(const SolverInterface& solver, double tol = 1E-7); } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/sos_basis_generator_test.cc
#include "drake/solvers/sos_basis_generator.h" #include <gtest/gtest.h> #include "drake/common/symbolic/monomial_util.h" #include "drake/solvers/mathematical_program.h" namespace drake { namespace solvers { namespace { using drake::symbolic::Expression; using drake::symbolic::Monomial; using drake::symbolic::Variable; using drake::symbolic::Variables; typedef std::set<Monomial, drake::symbolic::GradedReverseLexOrder<std::less<Variable>>> MonomialSet; MonomialSet VectorToSet(const drake::VectorX<Monomial>& x) { MonomialSet x_set; for (int i = 0; i < x.size(); i++) { x_set.insert(x(i)); } return x_set; } class SosBasisGeneratorTest : public ::testing::Test { public: MonomialSet GetMonomialBasis(const symbolic::Polynomial& poly) { drake::VectorX<Monomial> basis = ConstructMonomialBasis(poly); MonomialSet basis_set = VectorToSet(basis); return basis_set; } protected: void SetUp() override { x_ = prog_.NewIndeterminates<3>(); } MathematicalProgram prog_; VectorIndeterminate<3> x_; }; TEST_F(SosBasisGeneratorTest, MotzkinPoly) { const symbolic::Polynomial poly{pow(x_(0), 2) * pow(x_(1), 4) + pow(x_(0), 4) * pow(x_(1), 2) + pow(x_(0), 2) * pow(x_(1), 2) + +1}; MonomialSet basis_ref; basis_ref.insert(Monomial()); basis_ref.insert(Monomial(pow(x_(0), 1) * pow(x_(1), 1))); basis_ref.insert(Monomial(pow(x_(0), 2) * pow(x_(1), 1))); basis_ref.insert(Monomial(pow(x_(0), 1) * pow(x_(1), 2))); EXPECT_EQ(basis_ref, GetMonomialBasis(poly)); } TEST_F(SosBasisGeneratorTest, Univariate) { const symbolic::Polynomial poly{1 + pow(x_(0), 1) + pow(x_(0), 2) + pow(x_(0), 8)}; MonomialSet basis_ref; basis_ref.insert(Monomial()); basis_ref.insert(Monomial(pow(x_(0), 1))); basis_ref.insert(Monomial(pow(x_(0), 2))); basis_ref.insert(Monomial(pow(x_(0), 3))); basis_ref.insert(Monomial(pow(x_(0), 4))); EXPECT_EQ(basis_ref, GetMonomialBasis(poly)); } TEST_F(SosBasisGeneratorTest, Empty) { const symbolic::Polynomial poly{pow(x_(0), 3)}; MonomialSet basis_ref; EXPECT_EQ(basis_ref, GetMonomialBasis(poly)); } TEST_F(SosBasisGeneratorTest, NewtonPolytopeEmptyInterior) { const symbolic::Polynomial poly{pow(x_(0), 2) * pow(x_(1), 2) + pow(x_(0), 3) * pow(x_(1), 3) + pow(x_(0), 4) * pow(x_(1), 4)}; MonomialSet basis_ref; basis_ref.insert(Monomial(pow(x_(0), 1) * pow(x_(1), 1))); basis_ref.insert(Monomial(pow(x_(0), 2) * pow(x_(1), 2))); EXPECT_EQ(basis_ref, GetMonomialBasis(poly)); } TEST_F(SosBasisGeneratorTest, Singleton) { const symbolic::Polynomial poly{1 + pow(x_(0), 1)}; MonomialSet basis_ref; basis_ref.insert(Monomial()); EXPECT_EQ(basis_ref, GetMonomialBasis(poly)); } TEST_F(SosBasisGeneratorTest, Constant) { { // Generate the monomial basis for a constant polynomial const symbolic::Polynomial poly{1}; MonomialSet basis_ref; basis_ref.insert(Monomial()); EXPECT_EQ(basis_ref, GetMonomialBasis(poly)); } { // The polynomial p is constant after expansion. const symbolic::Polynomial poly{{{Monomial(), 1}, {Monomial(x_(0), 2), 0}}}; MonomialSet basis_ref; basis_ref.insert(Monomial()); EXPECT_EQ(basis_ref, GetMonomialBasis(poly)); } } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/quadratic_program_examples.cc
#include "drake/solvers/test/quadratic_program_examples.h" #include <limits> #include <optional> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/drake_assert.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/clp_solver.h" #include "drake/solvers/gurobi_solver.h" #include "drake/solvers/mathematical_program_result.h" #include "drake/solvers/mosek_solver.h" #include "drake/solvers/scs_solver.h" #include "drake/solvers/snopt_solver.h" #include "drake/solvers/test/mathematical_program_test_util.h" using drake::symbolic::Expression; using Eigen::Matrix2d; using Eigen::Matrix3d; using Eigen::Matrix4d; using Eigen::RowVector2d; using Eigen::Vector2d; using Eigen::Vector3d; using Eigen::Vector4d; using std::numeric_limits; using ::testing::HasSubstr; namespace drake { namespace solvers { namespace test { const double kInf = std::numeric_limits<double>::infinity(); std::ostream& operator<<(std::ostream& os, QuadraticProblems value) { os << "QuadraticProblems::"; switch (value) { case QuadraticProblems::kQuadraticProgram0: { os << "kQuadraticProgram0"; return os; } case QuadraticProblems::kQuadraticProgram1: { os << "kQuadraticProgram1"; return os; } case QuadraticProblems::kQuadraticProgram2: { os << "kQuadraticProgram2"; return os; } case QuadraticProblems::kQuadraticProgram3: { os << "kQuadraticProgram3"; return os; } case QuadraticProblems::kQuadraticProgram4: { os << "kQuadraticProgram4"; return os; } } DRAKE_UNREACHABLE(); } QuadraticProgramTest::QuadraticProgramTest() { auto cost_form = std::get<0>(GetParam()); auto constraint_form = std::get<1>(GetParam()); switch (std::get<2>(GetParam())) { case QuadraticProblems::kQuadraticProgram0: { prob_ = std::make_unique<QuadraticProgram0>(cost_form, constraint_form); break; } case QuadraticProblems::kQuadraticProgram1: { prob_ = std::make_unique<QuadraticProgram1>(cost_form, constraint_form); break; } case QuadraticProblems::kQuadraticProgram2: { prob_ = std::make_unique<QuadraticProgram2>(cost_form, constraint_form); break; } case QuadraticProblems::kQuadraticProgram3: { prob_ = std::make_unique<QuadraticProgram3>(cost_form, constraint_form); break; } case QuadraticProblems::kQuadraticProgram4: { prob_ = std::make_unique<QuadraticProgram4>(cost_form, constraint_form); break; } default: throw std::runtime_error("Un-recognized quadratic problem."); } } std::vector<QuadraticProblems> quadratic_problems() { return std::vector<QuadraticProblems>{QuadraticProblems::kQuadraticProgram0, QuadraticProblems::kQuadraticProgram1, QuadraticProblems::kQuadraticProgram2, QuadraticProblems::kQuadraticProgram3, QuadraticProblems::kQuadraticProgram4}; } QuadraticProgram0::QuadraticProgram0(CostForm cost_form, ConstraintForm constraint_form) : OptimizationProgram(cost_form, constraint_form), x_(), x_expected_(0.25, 0.75) { x_ = prog()->NewContinuousVariables<2>(); switch (cost_form) { case CostForm::kNonSymbolic: { Matrix2d Q; // clang-format off Q << 4, 2, 0, 2; // clang-format on const Vector2d b(1, 0); const double c = 3; prog()->AddQuadraticCost(Q, b, c, x_); prog()->AddLinearCost(Vector1d(1.0), x_.segment<1>(1)); break; } case CostForm::kSymbolic: { prog()->AddQuadraticCost(2 * x_(0) * x_(0) + x_(0) * x_(1) + x_(1) * x_(1) + x_(0) + x_(1) + 3); break; } default: { throw std::runtime_error("Unsupported cost form."); } } switch (constraint_form) { case ConstraintForm::kNonSymbolic: { prog()->AddBoundingBoxConstraint(0, numeric_limits<double>::infinity(), x_); prog()->AddBoundingBoxConstraint(-1, numeric_limits<double>::infinity(), x_(1)); prog()->AddLinearEqualityConstraint(RowVector2d(1, 1), 1, x_); break; } case ConstraintForm::kSymbolic: { prog()->AddBoundingBoxConstraint(0, numeric_limits<double>::infinity(), x_); prog()->AddLinearEqualityConstraint(x_(0) + x_(1), 1); break; } case ConstraintForm::kFormula: { prog()->AddLinearConstraint(x_(0) >= 0); prog()->AddLinearConstraint(x_(1) >= 0); prog()->AddLinearConstraint(x_(0) + x_(1) == 1); break; } default: { throw std::runtime_error("Unsupported constraint form."); } } } void QuadraticProgram0::CheckSolution( const MathematicalProgramResult& result) const { double tol = GetSolverSolutionDefaultCompareTolerance(result.get_solver_id()); if (result.get_solver_id() == GurobiSolver::id()) { tol = 1E-8; } else if (result.get_solver_id() == MosekSolver::id()) { // TODO(hongkai.dai): the default parameter in Mosek 8 generates low // accuracy solution. We should set the accuracy tolerance // MSK_DPARAM_INTPNT_QO_REL_TOL_GAP to 1E-10 to improve the accuracy. tol = 3E-5; } EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), x_expected_, tol, MatrixCompareType::absolute)); ExpectSolutionCostAccurate(*prog(), result, tol); } QuadraticProgram1::QuadraticProgram1(CostForm cost_form, ConstraintForm constraint_form) : OptimizationProgram(cost_form, constraint_form), x_{}, x_expected_(0, 1, 2.0 / 3) { x_ = prog()->NewContinuousVariables<3>(); switch (cost_form) { case CostForm::kNonSymbolic: { Matrix3d Q = 2 * Matrix3d::Identity(); Q(0, 1) = 1; Q(1, 2) = 1; Q(1, 0) = 1; Q(2, 1) = 1; Vector3d b{}; b << 2.0, 0.0, 0.0; prog()->AddQuadraticCost(Q, b, x_); break; } case CostForm::kSymbolic: { prog()->AddQuadraticCost(x_(0) * x_(0) + x_(0) * x_(1) + x_(1) * x_(1) + x_(1) * x_(2) + x_(2) * x_(2) + 2 * x_(0)); break; } default: throw std::runtime_error("Unsupported cost form."); } Vector4d b_lb(4, -numeric_limits<double>::infinity(), -20, -numeric_limits<double>::infinity()); Vector4d b_ub(numeric_limits<double>::infinity(), -1, 100, numeric_limits<double>::infinity()); switch (constraint_form) { case ConstraintForm::kNonSymbolic: { prog()->AddBoundingBoxConstraint(0, numeric_limits<double>::infinity(), x_); Eigen::Matrix<double, 4, 3> A1; A1 << 1, 2, 3, -1, -1, 0, 0, 1, 2, 1, 1, 2; prog()->AddLinearConstraint(A1, b_lb, b_ub, x_); // This test also handles linear equality constraint prog()->AddLinearEqualityConstraint(Eigen::RowVector3d(3, 1, 3), 3, x_); break; } case ConstraintForm::kSymbolic: { prog()->AddBoundingBoxConstraint(0, numeric_limits<double>::infinity(), x_); Vector4<Expression> expr; // clang-format off expr << x_(0) + 2 * x_(1) + 3 * x_(2), -x_(0) - x_(1), x_(1) + 2 * x_(2), x_(0) + x_(1) + 2 * x_(2); // clang-format on prog()->AddLinearConstraint(expr, b_lb, b_ub); prog()->AddLinearEqualityConstraint(3 * x_(0) + x_(1) + 3 * x_(2), 3); break; } case ConstraintForm::kFormula: { for (int i = 0; i < 3; ++i) { prog()->AddLinearConstraint(x_(i) >= 0); } prog()->AddLinearConstraint(x_(0) + 2 * x_(1) + 3 * x_(2) >= 4); prog()->AddLinearConstraint(-x_(0) - x_(1) <= -1); prog()->AddLinearConstraint(x_(1) + 2 * x_(2), -20, 100); // TODO(hongkai.dai): Uncomment the next line, when we resolve the error // with infinity on the right handside of a formula. // prog()->AddLinearConstraint(x_(0) + x_(1) + 2 * x_(2) <= // numeric_limits<double>::infinity()); prog()->AddLinearConstraint(3 * x_(0) + x_(1) + 3 * x_(2) == 3); break; } default: throw std::runtime_error("Unsupported constraint form."); } } void QuadraticProgram1::CheckSolution( const MathematicalProgramResult& result) const { double tol = GetSolverSolutionDefaultCompareTolerance(result.get_solver_id()); if (result.get_solver_id() == GurobiSolver::id()) { tol = 1E-8; } else if (result.get_solver_id() == MosekSolver::id()) { tol = 1E-7; } EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), x_expected_, tol, MatrixCompareType::absolute)); ExpectSolutionCostAccurate(*prog(), result, tol); } QuadraticProgram2::QuadraticProgram2(CostForm cost_form, ConstraintForm constraint_form) : OptimizationProgram(cost_form, constraint_form), x_{}, x_expected_{} { x_ = prog()->NewContinuousVariables<5>(); Eigen::Matrix<double, 5, 1> Q_diag{}; Q_diag << 5.5, 6.5, 6.0, 5.3, 7.5; Eigen::Matrix<double, 5, 5> Q = Q_diag.asDiagonal(); Q(2, 3) = 0.2; Eigen::Matrix<double, 5, 1> b; b << 3.2, 1.3, 5.6, 9.0, 1.2; switch (cost_form) { case CostForm::kNonSymbolic: { prog()->AddQuadraticCost(Q, b, x_); break; } case CostForm::kSymbolic: { prog()->AddQuadraticCost(0.5 * x_.dot(Q * x_) + b.dot(x_)); break; } default: throw std::runtime_error("Unsupported cost form."); } Eigen::Matrix<double, 5, 5> Q_symmetric = 0.5 * (Q + Q.transpose()); x_expected_ = -Q_symmetric.llt().solve(b); } void QuadraticProgram2::CheckSolution( const MathematicalProgramResult& result) const { double tol = GetSolverSolutionDefaultCompareTolerance(result.get_solver_id()); if (result.get_solver_id() == MosekSolver::id()) { tol = 1E-8; } else if (result.get_solver_id() == SnoptSolver::id()) { tol = 1E-6; } else if (result.get_solver_id() == ClpSolver::id()) { tol = 2E-8; } EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), x_expected_, tol, MatrixCompareType::absolute)); ExpectSolutionCostAccurate(*prog(), result, tol); } QuadraticProgram3::QuadraticProgram3(CostForm cost_form, ConstraintForm constraint_form) : OptimizationProgram(cost_form, constraint_form), x_{}, x_expected_{} { x_ = prog()->NewContinuousVariables<6>(); Vector4d Q1_diag; Q1_diag << 5.5, 6.5, 6.0, 7.0; Eigen::Matrix4d Q1 = Q1_diag.asDiagonal(); Q1(1, 2) = 0.1; Vector4d Q2_diag; Q2_diag << 7.0, 2.2, 1.1, 1.3; Matrix4d Q2 = Q2_diag.asDiagonal(); Q2(0, 2) = -0.02; Vector4d b1(3.1, -1.4, -5.6, 0.6); Vector4d b2(2.3, -5.8, 6.7, 2.3); switch (cost_form) { case CostForm::kNonSymbolic: { prog()->AddQuadraticCost(Q1, b1, x_.head<4>()); prog()->AddQuadraticCost(Q2, b2, x_.tail<4>()); break; } case CostForm::kSymbolic: { prog()->AddQuadraticCost( 0.5 * x_.head<4>().dot(Q1 * x_.head<4>()) + b1.dot(x_.head<4>()) + 0.5 * x_.tail<4>().dot(Q2 * x_.tail<4>()) + b2.dot(x_.tail<4>())); break; } default: throw std::runtime_error("Unsupported cost form."); } Eigen::Matrix<double, 6, 6> Q; Q.setZero(); Q.topLeftCorner<4, 4>() = Q1; Q.bottomRightCorner<4, 4>() += Q2; Eigen::Matrix<double, 6, 6> Q_symmetric = 0.5 * (Q + Q.transpose()); Vector6d b; b.setZero(); b.head<4>() = b1; b.tail<4>() += b2; x_expected_ = -Q_symmetric.llt().solve(b); } void QuadraticProgram3::CheckSolution( const MathematicalProgramResult& result) const { double tol = GetSolverSolutionDefaultCompareTolerance(result.get_solver_id()); if (result.get_solver_id() == MosekSolver::id()) { tol = 1E-8; } EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), x_expected_, tol, MatrixCompareType::absolute)); ExpectSolutionCostAccurate(*prog(), result, tol); } QuadraticProgram4::QuadraticProgram4(CostForm cost_form, ConstraintForm constraint_form) : OptimizationProgram(cost_form, constraint_form), x_{}, x_expected_(0.8, 0.2, 0.6) { x_ = prog()->NewContinuousVariables<3>(); switch (cost_form) { case CostForm::kNonSymbolic: { Matrix3d Q = Matrix3d::Identity(); Q(2, 2) = 2.0; Vector3d b = Vector3d::Zero(); prog()->AddQuadraticCost(2 * Q, b, x_); break; } case CostForm::kSymbolic: { prog()->AddQuadraticCost(x_(0) * x_(0) + x_(1) * x_(1) + 2 * x_(2) * x_(2)); break; } default: throw std::runtime_error("Unsupported cost form."); } switch (constraint_form) { case ConstraintForm::kNonSymbolic: { prog()->AddLinearEqualityConstraint(RowVector2d(1, 1), 1, x_.head<2>()); prog()->AddLinearEqualityConstraint(RowVector2d(1, 2), 2, {x_.segment<1>(0), x_.segment<1>(2)}); break; } case ConstraintForm::kSymbolic: { prog()->AddLinearEqualityConstraint(x_(0) + x_(1), 1); prog()->AddLinearEqualityConstraint(x_(0) + 2 * x_(2), 2); break; } case ConstraintForm::kFormula: { prog()->AddLinearConstraint(x_(0) + x_(1) == 1); prog()->AddLinearConstraint(x_(0) + 2 * x_(2) == 2); break; } default: throw std::runtime_error("Unsupported constraint form."); } } void QuadraticProgram4::CheckSolution( const MathematicalProgramResult& result) const { double tol = GetSolverSolutionDefaultCompareTolerance(result.get_solver_id()); if (result.get_solver_id() == MosekSolver::id()) { tol = 1E-8; } EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), x_expected_, tol, MatrixCompareType::absolute)); ExpectSolutionCostAccurate(*prog(), result, tol); } void TestQPonUnitBallExample(const SolverInterface& solver) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(2); Eigen::Matrix2d Q = Eigen::Matrix2d::Identity(); Eigen::Vector2d x_desired; x_desired << 1.0, 0.0; auto objective = prog.AddQuadraticErrorCost(Q, x_desired, x).evaluator(); Eigen::Matrix2d A; A << 1.0, 1.0, -1.0, 1.0; Eigen::Vector2d ub = Eigen::Vector2d::Constant(1.0); Eigen::Vector2d lb = Eigen::Vector2d::Constant(-1.0); auto constraint = prog.AddLinearConstraint(A, lb, ub, x).evaluator(); Eigen::Vector2d x_expected; const int N = 40; // number of points to test around the circle for (int i = 0; i < N; i++) { double theta = 2.0 * M_PI * i / N; x_desired << sin(theta), cos(theta); objective->UpdateCoefficients(2.0 * Q, -2.0 * Q * x_desired); if (theta <= M_PI_2) { // simple lagrange multiplier problem: // min (x-x_d)^2 + (y-y_d)^2 s.t. x+y=1 x_expected << (x_desired(0) - x_desired(1) + 1.0) / 2.0, (x_desired(1) - x_desired(0) + 1.0) / 2.0; } else if (theta <= M_PI) { // min (x-x_d)^2 + (y-y_d)^2 s.t. x-y=1 x_expected << (x_desired(0) + x_desired(1) + 1.0) / 2.0, (x_desired(0) + x_desired(1) - 1.0) / 2.0; } else if (theta <= 3.0 * M_PI_2) { // min (x-x_d)^2 + (y-y_d)^2 s.t. x+y=-1 x_expected << (x_desired(0) - x_desired(1) - 1.0) / 2.0, (x_desired(1) - x_desired(0) - 1.0) / 2.0; } else { // min (x-x_d)^2 + (y-y_d)^2 s.t. x-y=-1 x_expected << (x_desired(0) + x_desired(1) - 1.0) / 2.0, (x_desired(0) + x_desired(1) + 1.0) / 2.0; } std::optional<Eigen::VectorXd> initial_guess; if (solver.solver_id() == SnoptSolver::id()) { initial_guess.emplace(Eigen::VectorXd::Zero(2)); } const MathematicalProgramResult result = RunSolver(prog, solver, initial_guess); const auto& x_value = result.GetSolution(x); double tol = 1E-4; if (result.get_solver_id() == MosekSolver::id()) { // Regression from MOSEK 8.1 to MOSEK 9.2. tol = 2E-4; } EXPECT_TRUE( CompareMatrices(x_value, x_expected, tol, MatrixCompareType::absolute)); } // provide some test coverage for changing Q // { // now 2(x-xd)^2 + (y-yd)^2 s.t. x+y=1 x_desired << 1.0, 1.0; Q(0, 0) = 2.0; objective->UpdateCoefficients(2.0 * Q, -2.0 * Q * x_desired); x_expected << 2.0 / 3.0, 1.0 / 3.0; prog.SetSolverOption(GurobiSolver::id(), "BarConvTol", 1E-9); // The default accuracy in SCS isn't enough, we set it to 1E-6. prog.SetSolverOption(ScsSolver::id(), "eps_abs", 1E-6); prog.SetSolverOption(ScsSolver::id(), "eps_rel", 1E-6); MathematicalProgramResult result; ASSERT_NO_THROW(result = RunSolver(prog, solver)); const auto& x_value = result.GetSolution(x); EXPECT_TRUE(CompareMatrices(x_value, x_expected, 1e-5, MatrixCompareType::absolute)); ExpectSolutionCostAccurate(prog, result, 1E-5); } } void TestQPDualSolution1(const SolverInterface& solver, const SolverOptions& solver_options, double tol) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); auto constraint1 = prog.AddLinearConstraint(2 * x[0] + 3 * x[1], -2, 3); auto constraint2 = prog.AddLinearEqualityConstraint(x[1] + 4 * x[2] == 3); auto constraint3 = prog.AddBoundingBoxConstraint(0, 3, x); prog.AddQuadraticCost(x[0] * x[0] + 2 * x[1] * x[1] + x[2] * x[2]); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, {}, solver_options, &result); EXPECT_TRUE(result.is_success()); EXPECT_TRUE(CompareMatrices(result.GetSolution(x), Eigen::Vector3d(0, 1. / 11, 8. / 11.), tol)); // At the optimal solution, the active constraints are // x[0] >= 0 // x[1] + 4 * x[2] == 3 // Solving the KKT condition, we get the dual solution as // dual solution for x[0] >= 0 is 0 // dual solution for x[1] + 4 * x[2] == 3 is 0.363636 EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint1), Vector1d(0.), tol)); const double dual_solution_expected = 0.363636; EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint2), Vector1d(dual_solution_expected), tol)); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint3), Eigen::Vector3d::Zero(), tol)); // Now update the equality constraint right-hand side with a small amount, // check the optimal cost of the updated QP. The change in the optimal cost // should be equal to dual variable solution. const double delta = 1e-5; constraint2.evaluator()->set_bounds(Vector1d(3 + delta), Vector1d(3 + delta)); MathematicalProgramResult result_updated; solver.Solve(prog, {}, solver_options, &result_updated); EXPECT_NEAR( (result_updated.get_optimal_cost() - result.get_optimal_cost()) / delta, dual_solution_expected, tol); } } void TestQPDualSolution2(const SolverInterface& solver) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); auto constraint1 = prog.AddLinearConstraint(2 * x[0] + 4 * x[1], 0, 3); auto constraint2 = prog.AddLinearEqualityConstraint(x[1] - 4 * x[2] == -2); auto constraint3 = prog.AddBoundingBoxConstraint(-1, 2, x); prog.AddQuadraticCost(x[0] * x[0] + 2 * x[1] * x[1] + x[2] * x[2] + 2 * x[1] * x[2] + 4 * x[2]); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); // At the optimal solution, the active constraints are // 2 * x[0] + 4 * x[1] >= 0 // x[1] - 4 * x[2] == -2 // Solving the KKT condition, we get the dual solution as // dual solution for 2 * x[0] + 4 * x[1] >= 0 is 0.34285714 // dual solution for x[1] - 4 * x[2] == -2 is -1.14285714 const double dual_solution_expected = 0.34285714; EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint1), Vector1d(dual_solution_expected), 1e-6)); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint2), Vector1d(-1.14285714), 1e-6)); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint3), Eigen::Vector3d::Zero(), 1e-6)); // Now perturb the lower bound of the inequality by a little bit, the change // of the optimal cost should be equal to the dual solution. const double delta = 1e-5; constraint1.evaluator()->UpdateLowerBound(Vector1d(delta)); MathematicalProgramResult result_updated; solver.Solve(prog, {}, {}, &result_updated); EXPECT_NEAR( (result_updated.get_optimal_cost() - result.get_optimal_cost()) / delta, dual_solution_expected, 1e-5); } } void TestQPDualSolution3(const SolverInterface& solver, double tol, double sensitivity_tol) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto constraint = prog.AddBoundingBoxConstraint(-1, 2, x); prog.AddQuadraticCost(x[0] * x[0] + 2 * x[1] * x[1] + 2 * x[0] * x[1] - 8 * x[0] + 6 * x[1]); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.GetSolution(x), Eigen::Vector2d(2, -1), tol)); // At the optimal solution, the active constraints are // x[0] <= 2 // x[1] >= -1 // Solving the KKT condition, we get the dual solution as // dual solution for x[0] <= 2 is -6 // dual solution for x[1] >= -1 is 6 EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint), Eigen::Vector2d(-6, 6), tol)); // Now perturb the bounds a bit, the change of the optimal cost should match // with the dual solution. const double delta = 1e-5; constraint.evaluator()->UpdateUpperBound(Eigen::Vector2d(2 + delta, 2)); MathematicalProgramResult result1; solver.Solve(prog, {}, {}, &result1); EXPECT_NEAR( (result1.get_optimal_cost() - result.get_optimal_cost()) / delta, -6, sensitivity_tol); constraint.evaluator()->UpdateUpperBound(Eigen::Vector2d(2, 2 + delta)); MathematicalProgramResult result2; solver.Solve(prog, {}, {}, &result2); // The dual solution for x[1] <= 2 is 0. EXPECT_NEAR(result2.get_optimal_cost(), result.get_optimal_cost(), sensitivity_tol); constraint.evaluator()->set_bounds(Eigen::Vector2d(-1 + delta, -1), Eigen::Vector2d(2, 2)); MathematicalProgramResult result3; solver.Solve(prog, {}, {}, &result3); // The dual solution for x[0] >= -1 is 0. EXPECT_NEAR(result3.get_optimal_cost(), result.get_optimal_cost(), sensitivity_tol); constraint.evaluator()->UpdateLowerBound(Eigen::Vector2d(-1, -1 + delta)); MathematicalProgramResult result4; solver.Solve(prog, {}, {}, &result4); EXPECT_NEAR( (result4.get_optimal_cost() - result.get_optimal_cost()) / delta, 6, sensitivity_tol); // Now add more bounding box constraints (but with looser bounds than the -1 // <= x <= 2 bound already imposed). The dual solution for these bounds // should be zero. constraint.evaluator()->set_bounds(Eigen::Vector2d(-1, -1), Eigen::Vector2d(2, 2)); auto constraint1 = prog.AddBoundingBoxConstraint(-2, 3, x[0]); auto constraint2 = prog.AddBoundingBoxConstraint(-1.5, 3.5, x[1]); MathematicalProgramResult result5; solver.Solve(prog, {}, {}, &result5); EXPECT_TRUE(CompareMatrices(result5.GetDualSolution(constraint), Eigen::Vector2d(-6, 6), tol)); EXPECT_TRUE( CompareMatrices(result5.GetDualSolution(constraint1), Vector1d(0))); EXPECT_TRUE( CompareMatrices(result5.GetDualSolution(constraint2), Vector1d(0))); } } void TestEqualityConstrainedQPDualSolution1(const SolverInterface& solver) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto constraint = prog.AddLinearEqualityConstraint(x[0] + x[1] == 1); prog.AddQuadraticCost(x[0] * x[0] + x[1] * x[1]); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.GetDualSolution(constraint), Vector1d(1), 1e-5)); } } void TestEqualityConstrainedQPDualSolution2(const SolverInterface& solver) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); Eigen::Matrix<double, 2, 3> A; A << 1, 0, 3, 0, 2, 1; auto constraint = prog.AddLinearEqualityConstraint(A, Eigen::Vector2d(1, 2), x); prog.AddQuadraticCost(x[0] * x[0] + 2 * x[1] * x[1] + x[2] * x[2] + 4 * x[1]); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); EXPECT_TRUE(CompareMatrices( result.GetSolution(x), Eigen::Vector3d(-0.42857143, 0.76190476, 0.47619048), 1e-5)); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint), Eigen::Vector2d(-0.85714286, 3.52380952), 1e-5)); } } void TestNonconvexQP(const SolverInterface& solver, bool convex_solver, double tol) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto nonconvex_cost = prog.AddQuadraticCost(-x(0) * x(0) + x(1) * x(1) + 2); // Use a description that would never be mistaken as any other part of the // error message. const std::string description{"lorem ipsum"}; nonconvex_cost.evaluator()->set_description(description); prog.AddBoundingBoxConstraint(0, 1, x); if (convex_solver) { EXPECT_FALSE(solver.AreProgramAttributesSatisfied(prog)); EXPECT_THAT(solver.ExplainUnsatisfiedProgramAttributes(prog), HasSubstr("is non-convex")); EXPECT_THAT(solver.ExplainUnsatisfiedProgramAttributes(prog), HasSubstr(description)); } else { MathematicalProgramResult result; // Use a non-zero initial guess, since at x = [0, 0], the gradient is 0. solver.Solve(prog, Eigen::Vector2d(0.1, 0.1), std::nullopt, &result); EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.GetSolution(x), Eigen::Vector2d(1, 0), tol)); EXPECT_NEAR(result.get_optimal_cost(), 1., tol); } } void TestDuplicatedVariableQuadraticProgram(const SolverInterface& solver, double tol) { // min x0*x0 + 5*x1*x1 + 2*x2*x2+ x0*x1 // s.t x0 + 2 * x1 + x2 <= 3 // x0 + 2 * x2 = 1 // 1 <= 2 * x0 + x1 <= 3 // x0 + 2x1 + 3x2 >= 0 MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); Eigen::Matrix2d Q1; Q1 << 2, 1, 1, 2; prog.AddQuadraticCost(Q1, Eigen::Vector2d::Zero(), x.head<2>()); Eigen::Matrix3d Q2 = Eigen::Vector3d(8, 2, 2).asDiagonal(); // Repeating x(2) const Vector3<symbolic::Variable> x_1_2_2(x(1), x(2), x(2)); prog.AddQuadraticCost(Q2, Eigen::Vector3d::Zero(), x_1_2_2); const Vector3<symbolic::Variable> x_0_2_0(x(0), x(2), x(0)); prog.AddLinearEqualityConstraint(Eigen::RowVector3d(2, 2, -1), Vector1d(1), x_0_2_0); Eigen::Matrix<double, 2, 5> A; // A * vars = [x0 + 2*x1 + x2] // [2*x0 + x1 ] // clang-format off A << -1, 1, 3, 2, -1, 2, 2, -1, 1, -1; // clang-format on Eigen::Matrix<symbolic::Variable, 5, 1> x_2_0_2_1_2; x_2_0_2_1_2 << x(2), x(0), x(2), x(1), x(2); prog.AddLinearConstraint(A, Eigen::Vector2d(-kInf, 1), Eigen::Vector2d(3, 3), x_2_0_2_1_2); const Vector4<symbolic::Variable> x_1_2_0_0(x(1), x(2), x(0), x(0)); prog.AddLinearConstraint(Eigen::RowVector4d(2, 3, 2, -1), Vector1d(0), Vector1d(kInf), x_1_2_0_0); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, std::nullopt, std::nullopt, &result); ASSERT_TRUE(result.is_success()); const Eigen::Vector3d x_sol = result.GetSolution(x); EXPECT_NEAR(result.get_optimal_cost(), x_sol(0) * x_sol(0) + 5 * x_sol(1) * x_sol(1) + 2 * x_sol(2) * x_sol(2) + x_sol(0) * x_sol(1), tol); EXPECT_LE(x_sol(0) + 2 * x_sol(1) + x_sol(2), 3 + tol); EXPECT_NEAR(x_sol(0) + 2 * x_sol(2), 1, tol); EXPECT_GE(2 * x_sol(0) + x_sol(1), 1 - tol); EXPECT_LE(2 * x_sol(0) + x_sol(1), 3 + tol); EXPECT_GE(x_sol(0) + 2 * x_sol(1) + 3 * x_sol(2), -tol); } } void TestEqualityConstrainedQP1(const SolverInterface& solver, double tol) { MathematicalProgram prog{}; auto x = prog.NewContinuousVariables<2, 6>(); prog.AddQuadraticCost(0.5 * x(0, 5) * x(0, 5)); prog.AddLinearEqualityConstraint(x(0, 0) + 3 * x(0, 1) + 9 * x(0, 2) + 27 * x(0, 3) + 81 * x(0, 4) + 243 * x(0, 5) - x(1, 0), 0); prog.AddLinearEqualityConstraint(x(0, 1) + 6 * x(0, 2) + 27 * x(0, 3) + 108 * x(0, 4) + 405 * x(0, 5) - x(1, 1), 0); prog.AddLinearEqualityConstraint(x(0, 0), 0); prog.AddLinearEqualityConstraint(x(0, 1), 0); prog.AddLinearEqualityConstraint(x(1, 0), 6); prog.AddLinearEqualityConstraint(x(1, 1), 0); MathematicalProgramResult result; solver.Solve(prog, std::nullopt, std::nullopt, &result); EXPECT_TRUE(result.is_success()); const auto x_sol = result.GetSolution(x); EXPECT_NEAR(x_sol(0, 5), 0, tol); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/quadratic_constrained_program_examples.h
#pragma once #include <memory> #include <optional> #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solver_interface.h" #include "drake/solvers/solver_options.h" namespace drake { namespace solvers { namespace test { // min x0 + x1 // s.t 4x0²+9x1² ≤ 1 void TestEllipsoid1(const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol); // min x0 + x1 // s.t x0²+ x0*x1 + x1² ≤ 1 // x0²+ 2*x0*x1 + 4x1² ≤ 9 // x0 +x1 <= 0 void TestEllipsoid2(const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol); } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/mosek_solver_test.cc
#include "drake/solvers/mosek_solver.h" #include <filesystem> #include <gtest/gtest.h> #include "drake/common/temp_directory.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/mixed_integer_optimization_util.h" #include "drake/solvers/test/exponential_cone_program_examples.h" #include "drake/solvers/test/l2norm_cost_examples.h" #include "drake/solvers/test/linear_program_examples.h" #include "drake/solvers/test/quadratic_constrained_program_examples.h" #include "drake/solvers/test/quadratic_program_examples.h" #include "drake/solvers/test/second_order_cone_program_examples.h" #include "drake/solvers/test/semidefinite_program_examples.h" #include "drake/solvers/test/sos_examples.h" namespace drake { namespace solvers { namespace test { const double kInf = std::numeric_limits<double>::infinity(); TEST_P(LinearProgramTest, TestLP) { MosekSolver solver; prob()->RunProblem(&solver); } INSTANTIATE_TEST_SUITE_P( MosekTest, LinearProgramTest, ::testing::Combine(::testing::ValuesIn(linear_cost_form()), ::testing::ValuesIn(linear_constraint_form()), ::testing::ValuesIn(linear_problems()))); TEST_F(UnboundedLinearProgramTest0, Test) { MosekSolver solver; if (solver.available()) { const MathematicalProgram& const_prog = *prog_; MathematicalProgramResult result; solver.Solve(const_prog, {}, {}, &result); // Mosek can only detect dual infeasibility, not primal unboundedness. EXPECT_FALSE(result.is_success()); EXPECT_EQ(result.get_solution_result(), SolutionResult::kDualInfeasible); const MosekSolverDetails& mosek_solver_details = result.get_solver_details<MosekSolver>(); EXPECT_EQ(mosek_solver_details.rescode, 0); // This problem status is defined in // https://docs.mosek.com/10.1/capi/constants.html#mosek.prosta const int MSK_SOL_STA_DUAL_INFEAS_CER = 6; EXPECT_EQ(mosek_solver_details.solution_status, MSK_SOL_STA_DUAL_INFEAS_CER); const auto x_sol = result.GetSolution(x_); EXPECT_FALSE(std::isnan(x_sol(0))); EXPECT_FALSE(std::isnan(x_sol(1))); } } TEST_F(UnboundedLinearProgramTest1, Test) { MosekSolver solver; if (solver.available()) { MathematicalProgramResult result; solver.Solve(*prog_, {}, {}, &result); // Mosek can only detect dual infeasibility, not primal unboundedness. EXPECT_EQ(result.get_solution_result(), SolutionResult::kDualInfeasible); } } TEST_F(DuplicatedVariableLinearProgramTest1, Test) { MosekSolver solver; if (solver.available()) { CheckSolution(solver); } } TEST_P(QuadraticProgramTest, TestQP) { MosekSolver solver; prob()->RunProblem(&solver); } INSTANTIATE_TEST_SUITE_P( MosekTest, QuadraticProgramTest, ::testing::Combine(::testing::ValuesIn(quadratic_cost_form()), ::testing::ValuesIn(linear_constraint_form()), ::testing::ValuesIn(quadratic_problems()))); GTEST_TEST(QPtest, TestUnitBallExample) { MosekSolver solver; if (solver.available()) { TestQPonUnitBallExample(solver); } } TEST_P(TestEllipsoidsSeparation, TestSOCP) { MosekSolver mosek_solver; if (mosek_solver.available()) { SolveAndCheckSolution(mosek_solver); } } INSTANTIATE_TEST_SUITE_P( MosekTest, TestEllipsoidsSeparation, ::testing::ValuesIn(GetEllipsoidsSeparationProblems())); GTEST_TEST(TestDuplicatedVariableQuadraticProgram, Test) { MosekSolver solver; if (solver.available()) { TestDuplicatedVariableQuadraticProgram(solver); } } TEST_P(TestQPasSOCP, TestSOCP) { MosekSolver mosek_solver; if (mosek_solver.available()) { SolveAndCheckSolution(mosek_solver); } } INSTANTIATE_TEST_SUITE_P(MosekTest, TestQPasSOCP, ::testing::ValuesIn(GetQPasSOCPProblems())); TEST_P(TestFindSpringEquilibrium, TestSOCP) { MosekSolver mosek_solver; if (mosek_solver.available()) { SolveAndCheckSolution(mosek_solver); } } INSTANTIATE_TEST_SUITE_P( MosekTest, TestFindSpringEquilibrium, ::testing::ValuesIn(GetFindSpringEquilibriumProblems())); GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem1) { MaximizeGeometricMeanTrivialProblem1 prob; MosekSolver solver; if (solver.available()) { const auto result = solver.Solve(prob.prog(), {}, {}); prob.CheckSolution(result, 1E-7); } } GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem2) { MaximizeGeometricMeanTrivialProblem2 prob; MosekSolver solver; if (solver.available()) { const auto result = solver.Solve(prob.prog(), {}, {}); prob.CheckSolution(result, 1E-7); } } GTEST_TEST(TestSOCP, SmallestEllipsoidCoveringProblem) { MosekSolver solver; // Mosek 10 returns a solution that is accurate up to 1.3E-5 for this specific // problem. Might need to change the tolerance when we upgrade Mosek. SolveAndCheckSmallestEllipsoidCoveringProblems(solver, {}, 1.3E-5); } GTEST_TEST(TestSOCP, TestSocpDuplicatedVariable1) { MosekSolver solver; TestSocpDuplicatedVariable1(solver, std::nullopt, 1E-6); } GTEST_TEST(TestSOCP, TestSocpDuplicatedVariable2) { MosekSolver solver; TestSocpDuplicatedVariable2(solver, std::nullopt, 1E-6); } GTEST_TEST(TestL2NormCost, ShortestDistanceToThreePoints) { MosekSolver solver; ShortestDistanceToThreePoints tester{}; tester.CheckSolution(solver, std::nullopt, 1E-4); } GTEST_TEST(TestL2NormCost, ShortestDistanceFromCylinderToPoint) { MosekSolver solver; ShortestDistanceFromCylinderToPoint tester{}; tester.CheckSolution(solver); } GTEST_TEST(TestL2NormCost, ShortestDistanceFromPlaneToTwoPoints) { MosekSolver solver; ShortestDistanceFromPlaneToTwoPoints tester{}; tester.CheckSolution(solver, std::nullopt, 5E-4); } GTEST_TEST(TestSemidefiniteProgram, TrivialSDP) { MosekSolver mosek_solver; if (mosek_solver.available()) { TestTrivialSDP(mosek_solver, 1E-8); } } GTEST_TEST(TestSemidefiniteProgram, CommonLyapunov) { MosekSolver mosek_solver; if (mosek_solver.available()) { FindCommonLyapunov(mosek_solver, {}, 1E-8); } } GTEST_TEST(TestSemidefiniteProgram, OuterEllipsoid) { MosekSolver mosek_solver; if (mosek_solver.available()) { FindOuterEllipsoid(mosek_solver, {}, 1E-6); } } GTEST_TEST(TestSemidefiniteProgram, EigenvalueProblem) { MosekSolver mosek_solver; if (mosek_solver.available()) { SolveEigenvalueProblem(mosek_solver, {}, 1E-7); } } GTEST_TEST(TestSemidefiniteProgram, SolveSDPwithSecondOrderConeExample1) { MosekSolver mosek_solver; if (mosek_solver.available()) { SolveSDPwithSecondOrderConeExample1(mosek_solver, 1E-7); } } GTEST_TEST(TestSemidefiniteProgram, SolveSDPwithSecondOrderConeExample2) { MosekSolver mosek_solver; if (mosek_solver.available()) { SolveSDPwithSecondOrderConeExample2(mosek_solver, 1E-7); } } GTEST_TEST(TestSemidefiniteProgram, SolveSDPwithOverlappingVariables) { MosekSolver mosek_solver; if (mosek_solver.available()) { SolveSDPwithOverlappingVariables(mosek_solver, 1E-7); } } GTEST_TEST(TestExponentialConeProgram, ExponentialConeTrivialExample) { MosekSolver solver; if (solver.available()) { ExponentialConeTrivialExample(solver, 1E-5, true); } } GTEST_TEST(TestExponentialConeProgram, MinimizeKLDivengence) { MosekSolver solver; if (solver.available()) { MinimizeKLDivergence(solver, 2E-5); } } GTEST_TEST(TestExponentialConeProgram, MinimalEllipsoidConveringPoints) { MosekSolver solver; if (solver.available()) { MinimalEllipsoidCoveringPoints(solver, 1E-6); } } GTEST_TEST(TestExponentialConeProgram, MatrixLogDeterminantLower) { MosekSolver mosek_solver; if (mosek_solver.available()) { MatrixLogDeterminantLower(mosek_solver, 1E-6); } } GTEST_TEST(MosekTest, TestLogging) { // Test if we can print the logging info to a log file. MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint(x(0) + x(1) == 1); const std::string log_file = temp_directory() + "/mosek_logging.log"; EXPECT_FALSE(std::filesystem::exists({log_file})); MosekSolver solver; MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); // By default, no logging file. EXPECT_FALSE(std::filesystem::exists({log_file})); // Print to console. We can only test this doesn't cause any runtime error. We // can't test if the logging message is actually printed to the console. SolverOptions solver_options; solver_options.SetOption(CommonSolverOption::kPrintToConsole, 1); solver.Solve(prog, {}, solver_options, &result); solver_options.SetOption(CommonSolverOption::kPrintToConsole, 0); // Output the logging to the console solver_options.SetOption(CommonSolverOption::kPrintFileName, log_file); solver.Solve(prog, {}, solver_options, &result); EXPECT_TRUE(std::filesystem::exists({log_file})); // Now set both print to console and the log file. This will cause an error. solver_options.SetOption(CommonSolverOption::kPrintToConsole, 1); DRAKE_EXPECT_THROWS_MESSAGE( solver.Solve(prog, {}, solver_options, &result), ".* cannot print to both the console and the log file."); } GTEST_TEST(MosekTest, SolverOptionsTest) { // We test that passing solver options change the behavior of // MosekSolver::Solve(). MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint(100 * x(0) + 100 * x(1) <= 1); prog.AddConstraint(x(0) >= 0); prog.AddConstraint(x(1) >= 0); prog.AddLinearCost(1E5 * x(0) + x(1)); SolverOptions solver_options; solver_options.SetOption(MosekSolver::id(), "MSK_DPAR_DATA_TOL_C_HUGE", 1E3); MathematicalProgramResult result; MosekSolver mosek_solver; mosek_solver.Solve(prog, {}, solver_options, &result); EXPECT_FALSE(result.is_success()); // This response code is defined in // https://docs.mosek.com/10.1/capi/response-codes.html#mosek.rescode const int MSK_RES_ERR_HUGE_C{1375}; EXPECT_EQ(result.get_solver_details<MosekSolver>().rescode, MSK_RES_ERR_HUGE_C); solver_options.SetOption(MosekSolver::id(), "MSK_DPAR_DATA_TOL_C_HUGE", 1E6); mosek_solver.Solve(prog, {}, solver_options, &result); EXPECT_TRUE(result.is_success()); } GTEST_TEST(MosekSolver, SolverOptionsErrorTest) { // Set a non-existing option. Mosek should report error. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint(x(0) + x(1) >= 0); MathematicalProgramResult result; MosekSolver mosek_solver; SolverOptions solver_options; solver_options.SetOption(MosekSolver::id(), "non-existing options", 42); DRAKE_EXPECT_THROWS_MESSAGE( mosek_solver.Solve(prog, {}, solver_options, &result), ".*cannot set Mosek option \'non-existing options\' to value \'42\'.*"); } GTEST_TEST(MosekTest, Write) { // Write model to a file. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddLinearEqualityConstraint(x(0) + x(1) == 1); prog.AddQuadraticCost(x(0) * x(0) + x(1) * x(1), true /* is_convex */); MosekSolver mosek_solver; SolverOptions solver_options; const std::string file = temp_directory() + "mosek.mps"; EXPECT_FALSE(std::filesystem::exists(file)); solver_options.SetOption(MosekSolver::id(), "writedata", file); mosek_solver.Solve(prog, {}, solver_options); EXPECT_TRUE(std::filesystem::exists(file)); std::filesystem::remove(file); // Set "writedata" to "". Now expect no model file. solver_options.SetOption(MosekSolver::id(), "writedata", ""); mosek_solver.Solve(prog, {}, solver_options); EXPECT_FALSE(std::filesystem::exists(file)); } GTEST_TEST(MosekSolver, TestInitialGuess) { // Mosek allows to set initial guess for integer/binary variables. // Solve the following mixed-integer problem // Find a point C on one of the line segment A1A2, A2A3, A3A4, A4A1 such that // the distance from the point C to the point D = (0, 0) is minimized, where // A1 = (-1, 0), A2 = (0, 1), A3 = (2, 0), A4 = (1, -0.5) MathematicalProgram prog; auto lambda = prog.NewContinuousVariables<5>(); auto y = prog.NewBinaryVariables<4>(); AddSos2Constraint(&prog, lambda.cast<symbolic::Expression>(), y.cast<symbolic::Expression>()); Eigen::Matrix<double, 2, 5> pts_A; pts_A.col(0) << -1, 0; pts_A.col(1) << 0, 1; pts_A.col(2) << 2, 0; pts_A.col(3) << 1, -0.5; pts_A.col(4) = pts_A.col(0); // point C in the documentation above. auto pt_C = prog.NewContinuousVariables<2>(); prog.AddLinearEqualityConstraint(pt_C == pts_A * lambda); prog.AddQuadraticCost(pt_C(0) * pt_C(0) + pt_C(1) * pt_C(1)); MosekSolver solver; SolverOptions solver_options; // Allow only one solution (the one corresponding to the initial guess). solver_options.SetOption(solver.id(), "MSK_IPAR_MIO_MAX_NUM_SOLUTIONS", 1); // By setting y = (0, 1, 0, 0), pt_C = (0, 1), lambda = (0, 1, 0, 0, 0) point // C is on the line segment A2A3. This is a valid integral solution with // distance to origin = 1. prog.SetInitialGuess(pt_C, Eigen::Vector2d(0, 1)); prog.SetInitialGuess( lambda, (Eigen::Matrix<double, 5, 1>() << 0, 1, 0, 0, 0).finished()); prog.SetInitialGuess(y, Eigen::Vector4d(0, 1, 0, 0)); MathematicalProgramResult result; solver.Solve(prog, prog.initial_guess(), solver_options, &result); const double tol = 1E-8; EXPECT_TRUE(result.is_success()); EXPECT_NEAR(result.get_optimal_cost(), 1, tol); // By setting MSK_IPAR_MIO_CONSTRUCT_SOL=1, Mosek will first try to construct // the continuous solution given the initial binary variable solutions. In // this case it searches the point on line segment A2A3 that is closest // to the origin, which is (0.4, 0.8). solver_options.SetOption(solver.id(), "MSK_IPAR_MIO_CONSTRUCT_SOL", 1); solver.Solve(prog, prog.initial_guess(), solver_options, &result); EXPECT_TRUE(result.is_success()); EXPECT_NEAR(result.get_optimal_cost(), 0.8, tol); // By setting y = (0, 0, 0, 1), point C is on the line segment A4A1. The // minimal squared distance is 1.0 / 17 prog.SetInitialGuess(y, Eigen::Vector4d(0, 0, 0, 1)); solver.Solve(prog, prog.initial_guess(), solver_options, &result); EXPECT_TRUE(result.is_success()); EXPECT_NEAR(result.get_optimal_cost(), 1.0 / 17, tol); } GTEST_TEST(MosekTest, UnivariateQuarticSos) { UnivariateQuarticSos dut; MosekSolver solver; if (solver.available()) { const auto result = solver.Solve(dut.prog()); dut.CheckResult(result, 1E-10); } } GTEST_TEST(MosekTest, BivariateQuarticSos) { BivariateQuarticSos dut; MosekSolver solver; if (solver.available()) { const auto result = solver.Solve(dut.prog()); dut.CheckResult(result, 1E-10); } } GTEST_TEST(MosekTest, SimpleSos1) { SimpleSos1 dut; MosekSolver solver; if (solver.available()) { const auto result = solver.Solve(dut.prog()); dut.CheckResult(result, 2E-9); } } GTEST_TEST(MosekTest, MotzkinPolynomial) { MotzkinPolynomial dut; MosekSolver solver; if (solver.available()) { const auto result = solver.Solve(dut.prog()); dut.CheckResult(result, 1E-8); } } GTEST_TEST(MosekTest, UnivariateNonnegative1) { UnivariateNonnegative1 dut; MosekSolver solver; if (solver.available()) { const auto result = solver.Solve(dut.prog()); dut.CheckResult(result, 1E-9); } } GTEST_TEST(MosekTest, MinimalDistanceFromSphereProblem) { for (bool with_linear_cost : {true, false}) { MinimalDistanceFromSphereProblem<3> dut1(Eigen::Vector3d(0, 0, 0), Eigen::Vector3d(0, 0, 0), 1, with_linear_cost); MinimalDistanceFromSphereProblem<3> dut2(Eigen::Vector3d(0, 0, 1), Eigen::Vector3d(0, 0, 0), 1, with_linear_cost); MinimalDistanceFromSphereProblem<3> dut3(Eigen::Vector3d(0, 1, 1), Eigen::Vector3d(0, 0, 0), 1, with_linear_cost); MinimalDistanceFromSphereProblem<3> dut4(Eigen::Vector3d(0, 1, 1), Eigen::Vector3d(-1, -1, 0), 1, with_linear_cost); MosekSolver solver; if (solver.available()) { const double tol = 1E-4; dut1.SolveAndCheckSolution(solver, tol); dut2.SolveAndCheckSolution(solver, tol); dut3.SolveAndCheckSolution(solver, tol); dut4.SolveAndCheckSolution(solver, tol); } } } GTEST_TEST(MosekTest, SolveSDPwithQuadraticCosts) { MosekSolver solver; if (solver.available()) { SolveSDPwithQuadraticCosts(solver, 1E-8); } } GTEST_TEST(MosekTest, LPDualSolution1) { MosekSolver solver; if (solver.available()) { TestLPDualSolution1(solver, 1E-8); } } GTEST_TEST(MosekTest, LPDualSolution2) { MosekSolver solver; if (solver.available()) { TestLPDualSolution2(solver, 1E-8); } } GTEST_TEST(MosekTest, LPDualSolution2Scaled) { MosekSolver solver; if (solver.available()) { TestLPDualSolution2Scaled(solver, 1E-8); } } GTEST_TEST(MosekTest, LPDualSolution3) { MosekSolver solver; if (solver.available()) { TestLPDualSolution3(solver, 1E-8); } } GTEST_TEST(MosekTest, LPDualSolution4) { MosekSolver solver; if (solver.available()) { TestLPDualSolution4(solver, 1E-8); } } GTEST_TEST(MosekTest, LPDualSolution5) { MosekSolver solver; TestLPDualSolution5(solver, 1E-8); } GTEST_TEST(MosekTest, QPDualSolution1) { MosekSolver solver; if (solver.available()) { SolverOptions solver_options; // The default tolerance is 1E-8, and one entry of the optimal solution is // 0. This means the error on the primal and dual solution is in the order // of 1E-4, that is too large. solver_options.SetOption(solver.id(), "MSK_DPAR_INTPNT_QO_TOL_REL_GAP", 1e-12); TestQPDualSolution1(solver, solver_options, 6E-6); } } GTEST_TEST(MosekTest, QPDualSolution2) { MosekSolver solver; if (solver.available()) { TestQPDualSolution2(solver); } } GTEST_TEST(MosekTest, QPDualSolution3) { MosekSolver solver; if (solver.available()) { TestQPDualSolution3(solver, 1E-6, 3E-4); } } GTEST_TEST(MosekTest, EqualityConstrainedQPDualSolution1) { MosekSolver solver; if (solver.available()) { TestEqualityConstrainedQPDualSolution1(solver); } } GTEST_TEST(MosekTest, EqualityConstrainedQPDualSolution2) { MosekSolver solver; if (solver.available()) { TestEqualityConstrainedQPDualSolution2(solver); } } GTEST_TEST(MosekSolver, SocpDualSolution1) { MosekSolver solver; if (solver.available()) { SolverOptions solver_options{}; TestSocpDualSolution1(solver, solver_options, 1E-7); } } GTEST_TEST(MosekSolver, SocpDualSolution2) { MosekSolver solver; if (solver.available()) { SolverOptions solver_options{}; TestSocpDualSolution2(solver, solver_options, 1E-6); } } GTEST_TEST(MosekTest, SDPDualSolution1) { MosekSolver solver; if (solver.available()) { TestSDPDualSolution1(solver, 3E-6); } } GTEST_TEST(MosekTest, TestEllipsoid1) { // Test quadratically constrained program. MosekSolver solver; if (solver.available()) { TestEllipsoid1(solver, std::nullopt, 1E-6); } } GTEST_TEST(MosekTest, TestEllipsoid2) { // Test quadratically constrained program. MosekSolver solver; if (solver.available()) { TestEllipsoid2(solver, std::nullopt, 1E-5); } } GTEST_TEST(MosekTest, TestNonconvexQP) { MosekSolver solver; if (solver.available()) { TestNonconvexQP(solver, true); } } template <typename C> void CheckDualSolutionNotNan(const MathematicalProgramResult& result, const Binding<C>& constraint) { const auto dual_sol = result.GetDualSolution(constraint); for (int i = 0; i < dual_sol.rows(); ++i) { EXPECT_FALSE(std::isnan(dual_sol(i))); } } GTEST_TEST(MosekTest, InfeasibleLinearProgramTest) { // Solve an infeasible LP, make sure the infeasible solution is returned. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto constraint1 = prog.AddLinearConstraint(x(0) + x(1) >= 3); auto constraint2 = prog.AddBoundingBoxConstraint(0, 1, x); prog.AddLinearCost(x(0) + 2 * x(1)); MosekSolver solver; if (solver.available()) { const auto result = solver.Solve(prog); ASSERT_FALSE(result.is_success()); // Check that the primal solutions are not NAN. for (int i = 0; i < x.rows(); ++i) { EXPECT_FALSE(std::isnan(result.GetSolution(x(i)))); } // Check that the dual solutions are not NAN. CheckDualSolutionNotNan(result, constraint1); CheckDualSolutionNotNan(result, constraint2); // Check that the optimal cost is not NAN. EXPECT_FALSE(std::isnan(result.get_optimal_cost())); } } GTEST_TEST(MosekTest, InfeasibleSemidefiniteProgramTest) { // Solve an infeasible SDP, make sure the infeasible solution is returned. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); auto constraint1 = prog.AddPositiveSemidefiniteConstraint(X); auto constraint2 = prog.AddLinearConstraint(X(0, 0) + X(1, 1) + X(2, 2) <= -1); prog.AddLinearCost(X(1, 2)); MosekSolver solver; if (solver.available()) { const auto result = solver.Solve(prog); ASSERT_FALSE(result.is_success()); // Check that the primal solutions are not NAN. const auto X_sol = result.GetSolution(X); for (int i = 0; i < X.rows(); ++i) { for (int j = 0; j < X.cols(); ++j) { EXPECT_FALSE(std::isnan(X_sol(i, j))); } } // Check that the dual solutions are not NAN. CheckDualSolutionNotNan(result, constraint1); CheckDualSolutionNotNan(result, constraint2); // Check that the optimal cost is not NAN. EXPECT_FALSE(std::isnan(result.get_optimal_cost())); } } GTEST_TEST(MosekTest, LPNoBasisSelection) { // We solve an LP using interior point method (IPM), but don't do basis // identification (which cleans the solution) after IPM finishes. Hence the // basis solution is not available and Mosek can only acquire the IPM // solution. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddBoundingBoxConstraint(0, kInf, x); prog.AddLinearConstraint(x(0) + x(1) <= 1); prog.AddLinearCost(-x(0) - 2 * x(1)); SolverOptions solver_options; solver_options.SetOption(MosekSolver::id(), "MSK_IPAR_INTPNT_BASIS", 0); MosekSolver solver; if (solver.available()) { auto result = solver.Solve(prog, std::nullopt, solver_options); EXPECT_TRUE(result.is_success()); const auto x_sol = result.GetSolution(x); const double tol = 1E-6; EXPECT_TRUE(CompareMatrices(x_sol, Eigen::Vector2d(0, 1), tol)); } } } // namespace test } // namespace solvers } // namespace drake int main(int argc, char** argv) { // Ensure that we have the MOSEK license for the entire duration of this test, // so that we do not have to release and re-acquire the license for every // test. auto mosek_license = drake::solvers::MosekSolver::AcquireLicense(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/solve_test.cc
#include "drake/solvers/solve.h" #include <regex> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/solvers/choose_best_solver.h" #include "drake/solvers/gurobi_solver.h" #include "drake/solvers/linear_system_solver.h" #include "drake/solvers/scs_solver.h" #include "drake/solvers/snopt_solver.h" namespace drake { namespace solvers { GTEST_TEST(SolveTest, LinearSystemSolverTest) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddLinearEqualityConstraint(Eigen::Matrix2d::Identity(), Eigen::Vector2d(1, 2), x); auto result = Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.get_x_val(), Eigen::Vector2d(1, 2), 1E-12)); EXPECT_EQ(result.get_optimal_cost(), 0); EXPECT_EQ(result.get_solver_id(), LinearSystemSolver::id()); // Now add an inconsistent constraint prog.AddLinearEqualityConstraint(x(0) + x(1), 5); result = Solve(prog, {}, {}); EXPECT_FALSE(result.is_success()); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kGlobalInfeasibleCost); EXPECT_EQ(result.get_solver_id(), LinearSystemSolver::id()); } GTEST_TEST(SolveTest, TestInitialGuessAndOptions) { // Test with gurobi solver, which accepts both initial guess and solver // options. MathematicalProgram prog; auto x = prog.NewBinaryVariables<1>(); auto y = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint(y(0) + y(1) == 1); if (GurobiSolver::is_available()) { ASSERT_TRUE(ChooseBestSolver(prog) == GurobiSolver::id()); SolverOptions solver_options; // Presolve and Heuristics would each independently solve // this problem inside of the Gurobi solver, but without // consulting the initial guess. solver_options.SetOption(GurobiSolver::id(), "Presolve", 0); solver_options.SetOption(GurobiSolver::id(), "Heuristics", 0.0); Eigen::VectorXd vars_init(3); vars_init << 1, 0, 1; MathematicalProgramResult result = Solve(prog, vars_init, solver_options); EXPECT_NEAR(result.GetSolution(x)(0), vars_init(0), 1E-6); } } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/nlopt_solver_test.cc
#include "drake/solvers/nlopt_solver.h" #include <gtest/gtest.h> #include "drake/solvers/mathematical_program.h" #include "drake/solvers/test/linear_program_examples.h" #include "drake/solvers/test/mathematical_program_test_util.h" #include "drake/solvers/test/quadratic_program_examples.h" namespace drake { namespace solvers { namespace test { TEST_F(UnboundedLinearProgramTest0, TestNlopt) { prog_->SetInitialGuessForAllVariables(Eigen::Vector2d::Zero()); NloptSolver solver; if (solver.available()) { MathematicalProgramResult result; solver.Solve(*prog_, {}, {}, &result); EXPECT_FALSE(result.is_success()); EXPECT_EQ(result.get_optimal_cost(), -std::numeric_limits<double>::infinity()); SolverOptions solver_options; solver_options.SetOption(solver.solver_id(), NloptSolver::MaxEvalName(), 1); solver.Solve(*prog_, {}, solver_options, &result); const int NLOPT_MAXEVAL_REACHED = 5; EXPECT_EQ(result.get_solver_details<NloptSolver>().status, NLOPT_MAXEVAL_REACHED); } } GTEST_TEST(QPtest, TestUnitBallExample) { NloptSolver solver; if (solver.available()) { TestQPonUnitBallExample(solver); } } GTEST_TEST(NloptSolverTest, TestNonconvexQP) { NloptSolver solver; if (solver.available()) { TestNonconvexQP(solver, false); } } GTEST_TEST(NloptSolverTest, SetAlgorithm) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddQuadraticCost(Eigen::Matrix2d::Identity(), Eigen::Vector2d::Ones(), x, true /*is_convex */); prog.AddBoundingBoxConstraint(1, 2, x); NloptSolver solver; SolverOptions solver_options; solver_options.SetOption(solver.id(), NloptSolver::AlgorithmName(), "LD_CCSAQ"); const auto result = solver.Solve(prog, Eigen::VectorXd::Ones(2), solver_options); ASSERT_TRUE(result.is_success()); } TEST_F(QuadraticEqualityConstrainedProgram1, Test) { NloptSolver solver; if (solver.is_available()) { CheckSolution(solver, Eigen::Vector2d(0.5, 0.8), std::nullopt, 1E-4, false /* check dual */); } } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/csdp_solver_test.cc
#include "drake/solvers/csdp_solver.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/test/csdp_test_examples.h" #include "drake/solvers/test/linear_program_examples.h" #include "drake/solvers/test/second_order_cone_program_examples.h" #include "drake/solvers/test/semidefinite_program_examples.h" #include "drake/solvers/test/sos_examples.h" namespace drake { namespace solvers { namespace test { GTEST_TEST(TestSemidefiniteProgram, SolveSDPwithOverlappingVariables) { CsdpSolver solver; if (solver.available()) { test::SolveSDPwithOverlappingVariables(solver, 1E-7); } } TEST_F(CsdpDocExample, Solve) { CsdpSolver solver; if (solver.available()) { MathematicalProgramResult result; solver.Solve(*prog_, {}, {}, &result); EXPECT_TRUE(result.is_success()); const double tol = 5E-7; EXPECT_NEAR(result.get_optimal_cost(), -2.75, tol); Eigen::Matrix2d X1_expected; X1_expected << 0.125, 0.125, 0.125, 0.125; EXPECT_TRUE(CompareMatrices(result.GetSolution(X1_), X1_expected, tol)); Eigen::Matrix3d X2_expected; X2_expected.setZero(); X2_expected(0, 0) = 2.0 / 3; EXPECT_TRUE(CompareMatrices(result.GetSolution(X2_), X2_expected, tol)); EXPECT_TRUE( CompareMatrices(result.GetSolution(y_), Eigen::Vector2d::Zero(), tol)); const CsdpSolverDetails& solver_details = result.get_solver_details<CsdpSolver>(); EXPECT_EQ(solver_details.return_code, 0); EXPECT_NEAR(solver_details.primal_objective, 2.75, tol); EXPECT_NEAR(solver_details.dual_objective, 2.75, tol); EXPECT_TRUE( CompareMatrices(solver_details.y_val, Eigen::Vector2d(0.75, 1), tol)); Eigen::Matrix<double, 7, 7> Z_expected; Z_expected.setZero(); Z_expected(0, 0) = 0.25; Z_expected(0, 1) = -0.25; Z_expected(1, 0) = -0.25; Z_expected(1, 1) = 0.25; Z_expected(3, 3) = 2.0; Z_expected(4, 4) = 2.0; Z_expected(5, 5) = 0.75; Z_expected(6, 6) = 1.0; EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(solver_details.Z_val), Z_expected, tol)); // Now add an empty constraint to the program and solve it again, there // should be no error. prog_->AddLinearEqualityConstraint(Eigen::RowVector2d(0, 0), 0, y_); solver.Solve(*prog_, {}, {}, &result); EXPECT_TRUE(result.is_success()); EXPECT_NEAR(result.get_optimal_cost(), -2.75, tol); } } TEST_F(TrivialSDP1, Solve) { CsdpSolver solver; if (solver.available()) { MathematicalProgramResult result; solver.Solve(*prog_, {}, {}, &result); EXPECT_TRUE(result.is_success()); const double tol = 1E-7; EXPECT_NEAR(result.get_optimal_cost(), -2.0 / 3.0, tol); const Eigen::Matrix3d X1_expected = Eigen::Matrix3d::Constant(1.0 / 3); EXPECT_TRUE(CompareMatrices(result.GetSolution(X1_), X1_expected, tol)); } } std::vector<RemoveFreeVariableMethod> GetRemoveFreeVariableMethods() { return {RemoveFreeVariableMethod::kNullspace, RemoveFreeVariableMethod::kTwoSlackVariables, RemoveFreeVariableMethod::kLorentzConeSlack}; } TEST_F(LinearProgramBoundingBox1, Solve) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); MathematicalProgramResult result; solver.Solve(*prog_, {}, solver_options, &result); EXPECT_TRUE(result.is_success()); const double tol = 2E-7; EXPECT_NEAR(result.get_optimal_cost(), -43, 2 * tol); Eigen::Matrix<double, 7, 1> x_expected; x_expected << 0, 5, -1, 10, 5, 0, 1; EXPECT_TRUE( CompareMatrices(result.GetSolution(x_).head<7>(), x_expected, tol)); } } } TEST_F(CsdpLinearProgram2, Solve) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); MathematicalProgramResult result; solver.Solve(*prog_, {}, solver_options, &result); EXPECT_TRUE(result.is_success()); const double tol = 1E-7; EXPECT_NEAR(result.get_optimal_cost(), 28.0 / 13, tol); EXPECT_TRUE( CompareMatrices(result.GetSolution(x_), Eigen::Vector3d(5.0 / 13, -2.0 / 13, 9.0 / 13), tol)); } } } TEST_F(CsdpLinearProgram3, Solve) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); MathematicalProgramResult result; solver.Solve(*prog_, {}, solver_options, &result); EXPECT_TRUE(result.is_success()); const double tol = 1E-7; EXPECT_NEAR(result.get_optimal_cost(), -121.0 / 9, tol); EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), Eigen::Vector3d(10, -2.0 / 3, -17.0 / 9), tol)); } } } TEST_F(DuplicatedVariableLinearProgramTest1, Test) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.is_available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); CheckSolution(solver, solver_options); } } } TEST_F(TrivialSDP2, Solve) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); MathematicalProgramResult result; solver.Solve(*prog_, {}, solver_options, &result); EXPECT_TRUE(result.is_success()); const double tol = 1E-7; EXPECT_NEAR(result.get_optimal_cost(), -1.0 / 3, tol); EXPECT_TRUE(CompareMatrices(result.GetSolution(X1_), Eigen::Matrix2d::Zero(), tol)); EXPECT_NEAR(result.GetSolution(y_), 1.0 / 3, tol); } } } TEST_F(TrivialSOCP1, Solve) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); MathematicalProgramResult result; solver.Solve(*prog_, {}, solver_options, &result); EXPECT_TRUE(result.is_success()); const double tol = 1E-7; EXPECT_NEAR(result.get_optimal_cost(), -10, tol); EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), Eigen::Vector3d(10, 0, 0), tol)); } } } TEST_F(TrivialSOCP2, Solve) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); MathematicalProgramResult result; solver.Solve(*prog_, {}, solver_options, &result); EXPECT_TRUE(result.is_success()); // CSDP does not have high accuracy for solving an SOCP. const double tol = 3.8E-5; EXPECT_NEAR(result.get_optimal_cost(), -1, tol); EXPECT_TRUE( CompareMatrices(result.GetSolution(x_), Eigen::Vector2d(0, 1), tol)); } } } TEST_F(TrivialSOCP3, Solve) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); MathematicalProgramResult result; solver.Solve(*prog_, {}, solver_options, &result); EXPECT_TRUE(result.is_success()); // The accuracy for this test on the Mac machine is 5E-6. const double tol = 5.E-6; EXPECT_NEAR(result.get_optimal_cost(), 2 - std::sqrt(7.1), tol); EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), Eigen::Vector2d(-0.1, 2 - std::sqrt(7.1)), tol)); } } } GTEST_TEST(TestSOCP, TestSocpDuplicatedVariable1) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); TestSocpDuplicatedVariable1(solver, solver_options, 1E-6); } } } GTEST_TEST(TestSOCP, TestSocpDuplicatedVariable2) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); // Loosen the tolerances a bit (otherwise macOS is sad). solver_options.SetOption(solver.id(), "axtol", 1e-6); solver_options.SetOption(solver.id(), "objtol", 1e-6); TestSocpDuplicatedVariable2(solver, solver_options, 1E-5); } } } } // namespace test namespace test { TEST_F(InfeasibleLinearProgramTest0, TestInfeasible) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); auto result = solver.Solve(*prog_, {}, solver_options); EXPECT_EQ(result.get_solution_result(), SolutionResult::kInfeasibleConstraints); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kGlobalInfeasibleCost); } } } TEST_F(UnboundedLinearProgramTest0, TestUnbounded) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); auto result = solver.Solve(*prog_, {}, solver_options); EXPECT_EQ(result.get_solution_result(), SolutionResult::kDualInfeasible); } } } GTEST_TEST(TestSemidefiniteProgram, CommonLyapunov) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); FindCommonLyapunov(solver, solver_options, 1E-6); } } } GTEST_TEST(TestSemidefiniteProgram, OuterEllipsoid) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); FindOuterEllipsoid(solver, solver_options, 1E-6); } } } GTEST_TEST(TestSemidefiniteProgram, EigenvalueProblem) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); SolveEigenvalueProblem(solver, solver_options, 1E-6); } } } TEST_P(TestEllipsoidsSeparation, TestSOCP) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); SolveAndCheckSolution(solver, solver_options, 1E-6); } } } INSTANTIATE_TEST_SUITE_P( CsdpTest, TestEllipsoidsSeparation, ::testing::ValuesIn(GetEllipsoidsSeparationProblems())); TEST_P(TestFindSpringEquilibrium, TestSOCP) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); SolveAndCheckSolution(solver, solver_options, 7E-5); } } } INSTANTIATE_TEST_SUITE_P( CsdpTest, TestFindSpringEquilibrium, ::testing::ValuesIn(GetFindSpringEquilibriumProblems())); GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem1) { MaximizeGeometricMeanTrivialProblem1 prob; for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); const auto result = solver.Solve(prob.prog(), {}, solver_options); prob.CheckSolution(result, 1E-6); } } } GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem2) { MaximizeGeometricMeanTrivialProblem2 prob; for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); const auto result = solver.Solve(prob.prog(), {}, solver_options); prob.CheckSolution(result, 1E-6); } } } GTEST_TEST(TestSOCP, SmallestEllipsoidCoveringProblem) { for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); SolveAndCheckSmallestEllipsoidCoveringProblems(solver, solver_options, 1E-6); } } GTEST_TEST(TestSOS, UnivariateQuarticSos) { UnivariateQuarticSos dut; for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); const auto result = solver.Solve(dut.prog(), {}, solver_options); dut.CheckResult(result, 1E-10); } } } GTEST_TEST(TestSOS, BivariateQuarticSos) { BivariateQuarticSos dut; for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); const auto result = solver.Solve(dut.prog(), {}, solver_options); dut.CheckResult(result, 1E-10); } } } GTEST_TEST(TestSOS, SimpleSos1) { SimpleSos1 dut; for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); const auto result = solver.Solve(dut.prog(), {}, solver_options); dut.CheckResult(result, 1E-10); } } } GTEST_TEST(TestSOS, MotzkinPolynomial) { MotzkinPolynomial dut; for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); const auto result = solver.Solve(dut.prog(), {}, solver_options); dut.CheckResult(result, 1.5E-8); } } } GTEST_TEST(TestSOS, UnivariateNonnegative1) { UnivariateNonnegative1 dut; for (auto method : GetRemoveFreeVariableMethods()) { SCOPED_TRACE(fmt::format("method = {}", method)); CsdpSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "drake::RemoveFreeVariableMethod", static_cast<int>(method)); const auto result = solver.Solve(dut.prog(), std::nullopt, solver_options); dut.CheckResult(result, 6E-9); } } } // This is a code coverage test, not a functional test. If the code that // handles verbosity options has a segfault or always throws an exception, // then this would catch it. TEST_F(TrivialSDP1, SolveVerbose) { SolverOptions options; options.SetOption(CommonSolverOption::kPrintToConsole, 1); CsdpSolver solver; if (solver.available()) { solver.Solve(*prog_, {}, options); } } // Confirm that setting solver options has an effect on the solve. TEST_F(TrivialSDP1, SolverOptionsPropagation) { CsdpSolver solver; if (!solver.available()) { return; } // Solving with default options works fine. { SolverOptions options; auto result = solver.Solve(*prog_, {}, options); EXPECT_TRUE(result.is_success()); } // Setting an absurd `int` option causes a failure. { SolverOptions options; options.SetOption(CsdpSolver::id(), "maxiter", 0); auto result = solver.Solve(*prog_, {}, options); EXPECT_EQ(result.get_solution_result(), kIterationLimit); } // Setting an absurd `double` option causes a failure. { SolverOptions options; options.SetOption(CsdpSolver::id(), "axtol", 1e-100); auto result = solver.Solve(*prog_, {}, options); EXPECT_EQ(result.get_solution_result(), kSolverSpecificError); } } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/complementary_problem_test.cc
#include <gtest/gtest.h> #include "drake/solvers/mathematical_program.h" #include "drake/solvers/snopt_solver.h" #include "drake/solvers/solve.h" namespace drake { namespace solvers { namespace { // A problem from J.F. Bard, Convex two-level optimization, // Mathematical Programming 40(1), 15-27, 1988. // min (x-5)² + (2*y + 1)² // s.t 2*(y-1) - 1.5*x + l(0) - 0.5*l(1) + l(2) = 0 // 0 <= l(0) ⊥ 3 * x - y - 3 >= 0 // 0 <= l(1) ⊥ -x + 0.5*y + 4 >= 0 // 0 <= l(2) ⊥ -x - y + 7 >= 0 // x >= 0, y >= 0 GTEST_TEST(TestComplementaryProblem, bard1) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<1>(); auto y = prog.NewContinuousVariables<1>(); auto l = prog.NewContinuousVariables<3>(); prog.AddCost(pow(x(0) - 5, 2) + pow(2 * y(0) + 1, 2)); prog.AddLinearConstraint( 2 * (y(0) - 1) - 1.5 * x(0) + l(0) - 0.5 * l(1) + l(2) == 0); // TODO(hongkai.dai): write this linear complementarity constraint in symbolic // form. // z = [x;y;l] // M = [3, -1, 0, 0, 0] // [-1, 0.5, 0, 0, 0] // [-1, -1, 0, 0, 0] // [0, 0, 0, 0, 0] // [0, 0, 0, 0, 0] // q = [-3; 4; 7; 0; 0] // 0 <= z ⊥ M*z + q >= 0 Eigen::Matrix<double, 5, 5> M; // clang-format off M << 3, -1, 0, 0, 0, -1, 0.5, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0; // clang-format on Eigen::Matrix<double, 5, 1> q; q << -3, 4, 7, 0, 0; prog.AddLinearComplementarityConstraint(M, q, {x, y, l}); SnoptSolver snopt_solver; if (snopt_solver.available() && snopt_solver.enabled()) { auto result = snopt_solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); auto x_val = result.GetSolution(x); auto y_val = result.GetSolution(y); EXPECT_NEAR(x_val(0), 1, 1E-6); EXPECT_NEAR(y_val(0), 0, 1E-6); } } // Problem 2 from Fukushima, M. Luo, Z.-Q.Pang, J.-S., // "A globally convergent Sequential Quadratic Programming // Algorithm for Mathematical Programs with Linear Complementarity // Constraints", Computational Optimization and Applications, 10(1), // pp. 5-34, 1998. // min 0.5(x(0) + x(1) + y(0) - 15)² + 0.5(x(0) + x(1) + y(1) - 15)² // s.t 0 <= y(0) ⊥ 8/3 * x(0) + 2 * x(1) + 2 * y(0) + 8 / 3 * y(1) - 36 >= 0 // 0 <= y(1) ⊥ 2 * x(0) + 5/4 * x(1) + 5/4 * y(0) + 2 * y(1) - 25 >= 0 // 0 <= x <= 10 GTEST_TEST(TestComplementaryProblem, flp2) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto y = prog.NewContinuousVariables<2>(); prog.AddCost(0.5 * pow(x(0) + x(1) + y(0) - 15, 2) + 0.5 * (x(0) + x(1) + y(1) - 15, 2)); Eigen::Matrix4d M; // clang-format off M << 0, 0, 0, 0, 0, 0, 0, 0, 8.0 / 3, 2, 2, 8.0/3, 2, 5.0/4, 5.0/4, 2; // clang-format on Eigen::Vector4d q(0, 0, -36, -25); prog.AddLinearComplementarityConstraint(M, q, {x, y}); prog.AddBoundingBoxConstraint(0, 10, x); SnoptSolver snopt_solver; if (snopt_solver.available() && snopt_solver.enabled()) { MathematicalProgramResult result = Solve(prog); EXPECT_TRUE(result.is_success()); const auto x_val = result.GetSolution(x); const auto y_val = result.GetSolution(y); // Choose 1e-6 as the precision, since that is the default minor feasibility // tolerance of SNOPT. double precision = 1E-6; EXPECT_TRUE((x_val.array() >= -precision).all()); EXPECT_TRUE((x_val.array() <= 10 + precision).all()); EXPECT_TRUE((y_val.array() >= -precision).all()); Eigen::Vector4d z_val; z_val << x_val, y_val; const Eigen::Vector2d Mz_plus_q = (M * z_val + q).bottomRows<2>(); EXPECT_TRUE((Mz_plus_q.array() >= -precision).all()); EXPECT_NEAR(y_val.dot(Mz_plus_q), 0, precision); } } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/linear_complementary_problem_test.cc
#include "drake/common/test_utilities/expect_no_throw.h" /* clang-format off to disable clang-format-includes */ #include "drake/solvers/mathematical_program.h" /* clang-format on */ #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/solve.h" using Eigen::Vector2d; namespace drake { namespace solvers { namespace test { // Simple linear complementarity problem example. // @brief a hand-created LCP easily solved. // // Note: This test is meant to test that MathematicalProgram.Solve() works in // this case; tests of the correctness of the Moby LCP solver itself live in // testMobyLCP. GTEST_TEST(testMathematicalProgram, simpleLCP) { MathematicalProgram prog; Eigen::Matrix<double, 2, 2> M; // clang-format off M << 1, 4, 3, 1; // clang-format on Eigen::Vector2d q(-16, -15); auto x = prog.NewContinuousVariables<2>(); prog.AddLinearComplementarityConstraint(M, q, x); MathematicalProgramResult result; DRAKE_EXPECT_NO_THROW(result = Solve(prog)); const auto& x_value = result.GetSolution(x); EXPECT_TRUE(CompareMatrices(x_value, Vector2d(16, 0), 1e-4, MatrixCompareType::absolute)); } // Multiple LC constraints in a single optimization problem // @brief Just two copies of the simpleLCP example, to make sure that the // write-through of LCP results to the solution vector works correctly. GTEST_TEST(testMathematicalProgram, multiLCP) { MathematicalProgram prog; Eigen::Matrix<double, 2, 2> M; // clang-format off M << 1, 4, 3, 1; // clang-format on Eigen::Vector2d q(-16, -15); auto x = prog.NewContinuousVariables<2>(); auto y = prog.NewContinuousVariables<2>(); prog.AddLinearComplementarityConstraint(M, q, x); prog.AddLinearComplementarityConstraint(M, q, y); MathematicalProgramResult result; DRAKE_EXPECT_NO_THROW(result = Solve(prog)); const auto& x_value = result.GetSolution(x); const auto& y_value = result.GetSolution(y); EXPECT_TRUE(CompareMatrices(x_value, Vector2d(16, 0), 1e-4, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(y_value, Vector2d(16, 0), 1e-4, MatrixCompareType::absolute)); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/csdp_test_examples.cc
#include "drake/solvers/test/csdp_test_examples.h" #include <limits> #include <vector> namespace drake { namespace solvers { const double kInf = std::numeric_limits<double>::infinity(); SDPwithOverlappingVariables1::SDPwithOverlappingVariables1() : prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<3>()} { prog_->AddLinearCost(2 * x_(0) + x_(2)); prog_->AddBoundingBoxConstraint(1, 1, x_(1)); prog_->AddBoundingBoxConstraint(0.5, kInf, x_(0)); prog_->AddBoundingBoxConstraint(-kInf, 2, x_(2)); prog_->AddPositiveSemidefiniteConstraint( (Matrix2<symbolic::Variable>() << x_(0), x_(1), x_(1), x_(0)).finished()); prog_->AddPositiveSemidefiniteConstraint( (Matrix2<symbolic::Variable>() << x_(0), x_(2), x_(2), x_(0)).finished()); } SDPwithOverlappingVariables2::SDPwithOverlappingVariables2() : prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<2>()} { prog_->AddLinearCost(2 * x_(0) + x_(1)); prog_->AddBoundingBoxConstraint(Eigen::Vector2d(2, 1), Eigen::Vector2d(3, kInf), x_); prog_->AddPositiveSemidefiniteConstraint( (Matrix2<symbolic::Variable>() << x_(0), x_(1), x_(1), x_(0)).finished()); } CsdpDocExample::CsdpDocExample() : prog_{new MathematicalProgram()}, X1_{prog_->NewSymmetricContinuousVariables<2>()}, X2_{prog_->NewSymmetricContinuousVariables<3>()}, y_{prog_->NewContinuousVariables<2>()} { prog_->AddPositiveSemidefiniteConstraint(X1_); prog_->AddPositiveSemidefiniteConstraint(X2_); prog_->AddBoundingBoxConstraint(Eigen::Vector2d(0, 0), Eigen::Vector2d(kInf, kInf), y_); prog_->AddLinearCost(-(2 * X1_(0, 0) + 2 * X1_(0, 1) + 2 * X1_(1, 1) + 3 * X2_(0, 0) + 2 * X2_(1, 1) + 2 * X2_(0, 2) + 3 * X2_(2, 2))); prog_->AddLinearEqualityConstraint( 3 * X1_(0, 0) + 2 * X1_(0, 1) + 3 * X1_(1, 1) + y_(0), 1); prog_->AddLinearEqualityConstraint( 3 * X2_(0, 0) + 4 * X2_(1, 1) + 2 * X2_(0, 2) + 5 * X2_(2, 2) + y_(1), 2); } LinearProgramBoundingBox1::LinearProgramBoundingBox1() : prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<8>()} { Eigen::Matrix<double, 8, 1> lower, upper; lower << 0, 0, -1, -kInf, -2, 0, 1, -kInf; upper << kInf, 5, kInf, 10, 5, 0, 1, kInf; prog_->AddBoundingBoxConstraint(lower, upper, x_); prog_->AddLinearCost(-(-x_(0) + x_(1) - 2 * x_(2) + 3 * x_(3) + x_(4) + 1)); } CsdpLinearProgram2::CsdpLinearProgram2() : prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<3>()} { prog_->AddLinearEqualityConstraint(2 * x_(0) + 3 * x_(1) + x_(2), 1); Eigen::Matrix<double, 4, 3> A; // clang-format off A << 1, 0, -2, 1, 2, 0, -1, 0, 3, 1, 1, 4; // clang-format on Eigen::Vector4d lower(-kInf, -2, -2, 3); Eigen::Vector4d upper(-1, kInf, 3, 3); prog_->AddLinearConstraint(A, lower, upper, x_); prog_->AddLinearCost(x_(0) + 2 * x_(1) + 3 * x_(2)); } CsdpLinearProgram3::CsdpLinearProgram3() : prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<3>()} { prog_->AddBoundingBoxConstraint(Eigen::Vector2d(-1, -kInf), Eigen::Vector2d(10, 8), x_.head<2>()); Eigen::Matrix<double, 4, 3> A; // clang-format off A << 1, 2, 3, 2, 0, -1, 0, 1, -3, 1, 0, 1; // clang-format on prog_->AddLinearConstraint(A, Eigen::Vector4d(3, -1, -kInf, -4), Eigen::Vector4d(3, kInf, 5, 9), x_); prog_->AddLinearCost(-(2 * x_(0) + 3 * x_(1) + 4 * x_(2) + 3)); } TrivialSDP1::TrivialSDP1() : prog_{new MathematicalProgram()}, X1_{prog_->NewSymmetricContinuousVariables<3>()} { prog_->AddPositiveSemidefiniteConstraint(X1_); prog_->AddLinearEqualityConstraint(X1_(0, 0) + X1_(1, 1) + X1_(2, 2), 1); prog_->AddLinearConstraint(X1_(0, 1) + X1_(1, 2) - 2 * X1_(0, 2), -kInf, 0); prog_->AddLinearCost(-(X1_(0, 1) + X1_(1, 2))); } TrivialSDP2::TrivialSDP2() : prog_{new MathematicalProgram()}, X1_{prog_->NewSymmetricContinuousVariables<2>()}, y_{prog_->NewContinuousVariables<1>()(0)} { prog_->AddPositiveSemidefiniteConstraint(X1_); Eigen::Matrix2d F0 = Eigen::Matrix2d::Identity(); Eigen::Matrix2d F1; F1 << 1, 2, 2, 3; Eigen::Matrix2d F2; F2 << 2, 0, 0, 4; prog_->AddConstraint(std::make_shared<LinearMatrixInequalityConstraint>( std::vector<Eigen::MatrixXd>{F0, F1, F2}), Vector2<symbolic::Variable>(y_, X1_(0, 0))); prog_->AddLinearEqualityConstraint(X1_(0, 0) + 2 * X1_(1, 1) + 3 * y_, 1); prog_->AddLinearCost(-y_); } TrivialSOCP1::TrivialSOCP1() : prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<3>()} { prog_->AddBoundingBoxConstraint(Eigen::Vector2d::Zero(), Eigen::Vector2d(kInf, kInf), x_.tail<2>()); prog_->AddLinearEqualityConstraint(x_(0) + x_(1) + x_(2), 10); Eigen::Matrix3d A; // clang-format off A << 2, 0, 0, 0, 3, 0, 1, 0, 1; // clang-format on Eigen::Vector3d b(1, 2, 3); prog_->AddLorentzConeConstraint(A, b, x_); prog_->AddLinearCost(-x_(0)); } TrivialSOCP2::TrivialSOCP2() : prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<2>()} { prog_->AddLinearCost(-x_(1)); Eigen::Matrix<double, 3, 2> A; // clang-format off A << 1, 0, 1, 1, 1, -1; // clang-format on Eigen::Vector3d b(2, 1, 1); prog_->AddLorentzConeConstraint(A, b, x_); } TrivialSOCP3::TrivialSOCP3() : prog_{new MathematicalProgram()}, x_{prog_->NewContinuousVariables<2>()} { prog_->AddLinearCost(x_(1)); Eigen::Matrix<double, 4, 2> A; // clang-format off A << 2, 0, 0, 3, 1, 0, 3, 1; // clang-format on Eigen::Vector4d b(2, 4, 2, 1); prog_->AddRotatedLorentzConeConstraint(A, b, x_); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/clarabel_solver_test.cc
#include "drake/solvers/clarabel_solver.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/test/exponential_cone_program_examples.h" #include "drake/solvers/test/l2norm_cost_examples.h" #include "drake/solvers/test/linear_program_examples.h" #include "drake/solvers/test/mathematical_program_test_util.h" #include "drake/solvers/test/quadratic_program_examples.h" #include "drake/solvers/test/second_order_cone_program_examples.h" #include "drake/solvers/test/semidefinite_program_examples.h" #include "drake/solvers/test/sos_examples.h" namespace drake { namespace solvers { namespace test { const double kTol = 1E-5; GTEST_TEST(LinearProgramTest, TestGeneralLP) { // Test a linear program with only equality constraint. // min x(0) + 2 * x(1) // s.t x(0) + x(1) = 2 // The problem is unbounded. MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>("x"); prog.AddLinearCost(x(0) + 2 * x(1)); prog.AddLinearConstraint(x(0) + x(1) == 2); ClarabelSolver solver; if (solver.available()) { auto result = solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kDualInfeasible); } // Now add the constraint x(1) <= 1. The problem is // min x(0) + 2 * x(1) // s.t x(0) + x(1) = 2 // x(1) <= 1 // the problem should still be unbounded. prog.AddBoundingBoxConstraint(-std::numeric_limits<double>::infinity(), 1, x(1)); if (solver.available()) { auto result = solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kDualInfeasible); } // Now add the constraint x(0) <= 5. The problem is // min x(0) + 2x(1) // s.t x(0) + x(1) = 2 // x(1) <= 1 // x(0) <= 5 // the problem should be feasible. The optimal cost is -1, with x = (5, -3) prog.AddBoundingBoxConstraint(-std::numeric_limits<double>::infinity(), 5, x(0)); if (solver.available()) { auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); EXPECT_NEAR(result.get_optimal_cost(), -1, kTol); const Eigen::Vector2d x_expected(5, -3); EXPECT_TRUE(CompareMatrices(result.GetSolution(x), x_expected, kTol, MatrixCompareType::absolute)); } // Now change the cost to 3x(0) - x(1) + 5, and add the constraint 2 <= x(0) // The problem is // min 3x(0) - x(1) + 5 // s.t x(0) + x(1) = 2 // 2 <= x(0) <= 5 // x(1) <= 1 // The optimal cost is 11, the optimal solution is x = (2, 0) prog.AddLinearCost(2 * x(0) - 3 * x(1) + 5); prog.AddBoundingBoxConstraint( 2, 6 /* this upper bound = 6 is intentionally redundant.*/, x(0)); if (solver.available()) { auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); EXPECT_NEAR(result.get_optimal_cost(), 11, kTol); const Eigen::Vector2d x_expected(2, 0); EXPECT_TRUE(CompareMatrices(result.GetSolution(x), x_expected, kTol, MatrixCompareType::absolute)); } } GTEST_TEST(LinearProgramTest, TestInfeasibleEqualityOnlyLP) { // Test a linear program with only equality constraints // min x(0) + 2 * x(1) // s.t x(0) + x(1) = 1 // 2x(0) + x(1) = 2 // x(0) - 2x(1) = 3 // This problem is infeasible. MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>("x"); prog.AddLinearCost(x(0) + 2 * x(1)); prog.AddLinearEqualityConstraint(x(0) + x(1) == 1 && 2 * x(0) + x(1) == 2); prog.AddLinearEqualityConstraint(x(0) - 2 * x(1) == 3); ClarabelSolver clarabel_solver; if (clarabel_solver.available()) { auto result = clarabel_solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kInfeasibleConstraints); } } GTEST_TEST(LinearProgramTest, TestAllLPConstraintTypes) { // Test a linear program with bounding box, linear equality and inequality // constraints // min x(0) + 2 * x(1) + 3 * x(2) + 2 // s.t x(0) + x(1) = 2 // x(0) + 2x(2) = 3 // -2 <= x(0) + 4x(1) <= 10 // -5 <= x(1) + 2x(2) <= 9 // -x(0) + 2x(2) <= 7 // -x(1) + 3x(2) >= -10 // x(0) <= 10 // 1 <= x(2) <= 9 // The optimal cost is 8, with x = (1, 1, 1) MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); prog.AddLinearCost(x(0) + 2 * x(1) + 3 * x(2) + 2); prog.AddLinearEqualityConstraint(x(0) + x(1) == 2 && x(0) + 2 * x(2) == 3); Eigen::Matrix<double, 3, 3> A; // clang-format off A << 1, 4, 0, 0, 1, 2, -1, 0, 2; // clang-format on prog.AddLinearConstraint( A, Eigen::Vector3d(-2, -5, -std::numeric_limits<double>::infinity()), Eigen::Vector3d(10, 9, 7), x); prog.AddLinearConstraint(-x(1) + 3 * x(2) >= -10); prog.AddBoundingBoxConstraint(-std::numeric_limits<double>::infinity(), 10, x(0)); prog.AddBoundingBoxConstraint(1, 9, x(2)); ClarabelSolver clarabel_solver; if (clarabel_solver.available()) { auto result = clarabel_solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); EXPECT_NEAR(result.get_optimal_cost(), 8, kTol); EXPECT_TRUE(CompareMatrices(result.GetSolution(x), Eigen::Vector3d(1, 1, 1), kTol, MatrixCompareType::absolute)); } } TEST_P(LinearProgramTest, TestLP) { ClarabelSolver solver; prob()->RunProblem(&solver); } INSTANTIATE_TEST_SUITE_P( ClarabelTest, LinearProgramTest, ::testing::Combine(::testing::ValuesIn(linear_cost_form()), ::testing::ValuesIn(linear_constraint_form()), ::testing::ValuesIn(linear_problems()))); TEST_F(InfeasibleLinearProgramTest0, TestInfeasible) { ClarabelSolver solver; if (solver.available()) { auto result = solver.Solve(*prog_, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kInfeasibleConstraints); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kGlobalInfeasibleCost); } } TEST_F(UnboundedLinearProgramTest0, TestUnbounded) { ClarabelSolver solver; if (solver.available()) { auto result = solver.Solve(*prog_, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kDualInfeasible); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kUnboundedCost); // Make sure that we have written Clarabel's variable value into `result`. EXPECT_TRUE(result.GetSolution(prog_->decision_variables()) .array() .isFinite() .all()); } } TEST_F(DuplicatedVariableLinearProgramTest1, Test) { ClarabelSolver solver; if (solver.is_available()) { CheckSolution(solver, std::nullopt, kTol); } } GTEST_TEST(TestLPDualSolution1, Test) { ClarabelSolver solver; if (solver.is_available()) { TestLPDualSolution1(solver, kTol); } } GTEST_TEST(TestLPDualSolution2, Test) { ClarabelSolver solver; if (solver.available()) { TestLPDualSolution2(solver, kTol); } } GTEST_TEST(TestLPDualSolution3, Test) { ClarabelSolver solver; if (solver.available()) { TestLPDualSolution3(solver, kTol); } } GTEST_TEST(TestLPDualSolution4, Test) { ClarabelSolver solver; if (solver.available()) { TestLPDualSolution4(solver, kTol); } } GTEST_TEST(TestLPDualSolution5, Test) { ClarabelSolver solver; if (solver.available()) { TestLPDualSolution5(solver, kTol); } } TEST_P(QuadraticProgramTest, TestQP) { ClarabelSolver solver; if (solver.available()) { prob()->RunProblem(&solver); } } INSTANTIATE_TEST_SUITE_P( ClarabelTest, QuadraticProgramTest, ::testing::Combine(::testing::ValuesIn(quadratic_cost_form()), ::testing::ValuesIn(linear_constraint_form()), ::testing::ValuesIn(quadratic_problems()))); GTEST_TEST(QPtest, TestUnitBallExample) { ClarabelSolver solver; if (solver.available()) { TestQPonUnitBallExample(solver); } } GTEST_TEST(TestDuplicatedVariableQuadraticProgram, Test) { ClarabelSolver solver; if (solver.available()) { TestDuplicatedVariableQuadraticProgram(solver, 1E-5); } } TEST_P(TestEllipsoidsSeparation, TestSOCP) { ClarabelSolver clarabel_solver; if (clarabel_solver.available()) { SolveAndCheckSolution(clarabel_solver, {}, kTol); } } INSTANTIATE_TEST_SUITE_P( ClarabelTest, TestEllipsoidsSeparation, ::testing::ValuesIn(GetEllipsoidsSeparationProblems())); TEST_P(TestQPasSOCP, TestSOCP) { ClarabelSolver clarabel_solver; if (clarabel_solver.available()) { SolveAndCheckSolution(clarabel_solver, kTol); } } INSTANTIATE_TEST_SUITE_P(ClarabelTest, TestQPasSOCP, ::testing::ValuesIn(GetQPasSOCPProblems())); TEST_P(TestFindSpringEquilibrium, TestSOCP) { ClarabelSolver clarabel_solver; if (clarabel_solver.available()) { SolveAndCheckSolution(clarabel_solver, {}, 3E-4); } } INSTANTIATE_TEST_SUITE_P( ClarabelTest, TestFindSpringEquilibrium, ::testing::ValuesIn(GetFindSpringEquilibriumProblems())); GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem1) { MaximizeGeometricMeanTrivialProblem1 prob; ClarabelSolver solver; if (solver.available()) { const auto result = solver.Solve(prob.prog(), {}, {}); // Practically I observe Clarabel requires looser tolerance for this test. I // don't know why. prob.CheckSolution(result, 3 * kTol); } } GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem2) { MaximizeGeometricMeanTrivialProblem2 prob; ClarabelSolver solver; if (solver.available()) { const auto result = solver.Solve(prob.prog(), {}, {}); prob.CheckSolution(result, kTol); } } GTEST_TEST(TestSOCP, SmallestEllipsoidCoveringProblem) { ClarabelSolver solver; SolveAndCheckSmallestEllipsoidCoveringProblems(solver, {}, kTol); } GTEST_TEST(TestSOCP, LorentzConeDual) { ClarabelSolver solver; SolverOptions solver_options; TestSocpDualSolution1(solver, solver_options, kTol); } GTEST_TEST(TestSOCP, RotatedLorentzConeDual) { ClarabelSolver solver; SolverOptions solver_options; TestSocpDualSolution2(solver, solver_options, kTol); } GTEST_TEST(TestSOCP, TestSocpDuplicatedVariable1) { ClarabelSolver solver; TestSocpDuplicatedVariable1(solver, std::nullopt, 1E-6); } GTEST_TEST(TestSOCP, TestSocpDuplicatedVariable2) { ClarabelSolver solver; TestSocpDuplicatedVariable2(solver, std::nullopt, 1E-6); } GTEST_TEST(TestL2NormCost, ShortestDistanceToThreePoints) { ClarabelSolver solver; ShortestDistanceToThreePoints tester{}; tester.CheckSolution(solver); } GTEST_TEST(TestL2NormCost, ShortestDistanceFromCylinderToPoint) { ClarabelSolver solver; ShortestDistanceFromCylinderToPoint tester{}; tester.CheckSolution(solver); } GTEST_TEST(TestL2NormCost, ShortestDistanceFromPlaneToTwoPoints) { ClarabelSolver solver; ShortestDistanceFromPlaneToTwoPoints tester{}; tester.CheckSolution(solver, std::nullopt, 5E-4); } GTEST_TEST(TestExponentialConeProgram, ExponentialConeTrivialExample) { ClarabelSolver solver; if (solver.available()) { // Currently we don't support retrieving dual solution for exponential cone // constraints from Clarabel yet. ExponentialConeTrivialExample(solver, 2E-4, false); } } GTEST_TEST(TestExponentialConeProgram, MinimizeKLDivengence) { ClarabelSolver clarabel_solver; if (clarabel_solver.available()) { MinimizeKLDivergence(clarabel_solver, 1E-4); } } GTEST_TEST(TestExponentialConeProgram, MinimalEllipsoidConveringPoints) { ClarabelSolver clarabel_solver; if (clarabel_solver.available()) { MinimalEllipsoidCoveringPoints(clarabel_solver, 1E-4); } } GTEST_TEST(TestExponentialConeProgram, MatrixLogDeterminantLower) { ClarabelSolver scs_solver; if (scs_solver.available()) { MatrixLogDeterminantLower(scs_solver, kTol); } } GTEST_TEST(TestSos, UnivariateQuarticSos) { UnivariateQuarticSos dut; ClarabelSolver solver; if (solver.available()) { const auto result = solver.Solve(dut.prog()); dut.CheckResult(result, kTol); } } GTEST_TEST(TestSos, BivariateQuarticSos) { BivariateQuarticSos dut; ClarabelSolver solver; if (solver.available()) { const auto result = solver.Solve(dut.prog()); dut.CheckResult(result, kTol); } } GTEST_TEST(TestSos, SimpleSos1) { SimpleSos1 dut; ClarabelSolver solver; if (solver.available()) { const auto result = solver.Solve(dut.prog()); dut.CheckResult(result, kTol); } } GTEST_TEST(TestSos, MotzkinPolynomial) { MotzkinPolynomial dut; ClarabelSolver solver; if (solver.is_available()) { const auto result = solver.Solve(dut.prog()); dut.CheckResult(result, kTol); } } GTEST_TEST(TestSos, UnivariateNonnegative1) { UnivariateNonnegative1 dut; ClarabelSolver solver; if (solver.is_available()) { const auto result = solver.Solve(dut.prog()); dut.CheckResult(result, kTol); } } GTEST_TEST(TestOptions, SetMaxIter) { SimpleSos1 dut; ClarabelSolver solver; if (solver.available()) { SolverOptions solver_options; auto result = solver.Solve(dut.prog(), std::nullopt, solver_options); EXPECT_TRUE(result.is_success()); ASSERT_GT(result.get_solver_details<ClarabelSolver>().iterations, 1); // Now change the max iteration to 1. solver_options.SetOption(solver.id(), "max_iter", 1); result = solver.Solve(dut.prog(), std::nullopt, solver_options); EXPECT_FALSE(result.is_success()); EXPECT_EQ(result.get_solution_result(), SolutionResult::kIterationLimit); } } GTEST_TEST(TestOptions, unrecognized) { SimpleSos1 dut; ClarabelSolver solver; if (solver.available()) { SolverOptions solver_options; solver_options.SetOption(solver.id(), "bad_unrecognized", 1); DRAKE_EXPECT_THROWS_MESSAGE( solver.Solve(dut.prog(), std::nullopt, solver_options), ".*unrecognized solver options bad_unrecognized.*"); } } GTEST_TEST(TestZeroStepSize, ZeroStepSize) { // This is a program configuration that causes Clarabel to crash (and hence // crash Drake) in version 0.6.0. In version 0.7.1, this configuration causes // the solver to report InsufficientProgress. ClarabelSolver solver; MathematicalProgram prog; const auto y = prog.NewContinuousVariables<2>("y"); MatrixX<symbolic::Expression> mat(2, 2); mat << y(0, 0), 0.5, 0.5, y(1); prog.AddPositiveSemidefiniteConstraint(mat); prog.AddLogDeterminantLowerBoundConstraint(mat, 1); prog.AddLinearCost(-y(0)); SolverOptions options; options.SetOption(solver.id(), "max_step_fraction", 1e-10); options.SetOption(CommonSolverOption::kPrintToConsole, true); if (solver.available()) { auto result = solver.Solve(prog, std::nullopt, options); // The program has cost unbounded above and so the dual is infeasible, but // the step size fraction forces the solver to make insufficient progress. EXPECT_EQ(result.get_solution_result(), SolutionResult::kSolverSpecificError); EXPECT_EQ(result.get_solver_details<ClarabelSolver>().status, "InsufficientProgress"); } } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/ipopt_solver_test.cc
#include "drake/solvers/ipopt_solver.h" #include <filesystem> #include <gtest/gtest.h> #include "drake/common/temp_directory.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/test/linear_program_examples.h" #include "drake/solvers/test/mathematical_program_test_util.h" #include "drake/solvers/test/quadratic_program_examples.h" #include "drake/solvers/test/second_order_cone_program_examples.h" #ifdef DRAKE_IPOPT_SOLVER_TEST_HAS_IPOPT #include <IpAlgTypes.hpp> namespace { constexpr int kIpoptMaxiterExceeded = Ipopt::MAXITER_EXCEEDED; constexpr int kIpoptStopAtAcceptablePoint = Ipopt::STOP_AT_ACCEPTABLE_POINT; constexpr int kIpoptLocalInfeasibility = Ipopt::LOCAL_INFEASIBILITY; } // namespace #else namespace { constexpr int kIpoptMaxiterExceeded = -1; constexpr int kIpoptStopAtAcceptablePoint = -1; constexpr int kIpoptLocalInfeasibility = -1; } // namespace #endif namespace drake { namespace solvers { namespace test { TEST_P(LinearProgramTest, TestLP) { IpoptSolver solver; prob()->RunProblem(&solver); } INSTANTIATE_TEST_SUITE_P( IpoptTest, LinearProgramTest, ::testing::Combine(::testing::ValuesIn(linear_cost_form()), ::testing::ValuesIn(linear_constraint_form()), ::testing::ValuesIn(linear_problems()))); TEST_F(InfeasibleLinearProgramTest0, TestIpopt) { prog_->SetInitialGuessForAllVariables(Eigen::Vector2d(1, 2)); IpoptSolver solver; if (solver.available()) { auto result = solver.Solve(*prog_, {}, {}); EXPECT_FALSE(result.is_success()); EXPECT_EQ(result.get_solution_result(), SolutionResult::kInfeasibleConstraints); EXPECT_EQ(result.get_solver_details<IpoptSolver>().status, kIpoptLocalInfeasibility); const Eigen::Vector2d x_val = result.GetSolution(prog_->decision_variables()); EXPECT_NEAR(result.get_optimal_cost(), -x_val(0) - x_val(1), 1E-7); } } TEST_F(UnboundedLinearProgramTest0, TestIpopt) { prog_->SetInitialGuessForAllVariables(Eigen::Vector2d(1, 2)); prog_->SetSolverOption(IpoptSolver::id(), "diverging_iterates_tol", 1E3); prog_->SetSolverOption(IpoptSolver::id(), "max_iter", 1000); IpoptSolver solver; if (solver.available()) { auto result = solver.Solve(*prog_, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded); EXPECT_EQ(result.get_optimal_cost(), -std::numeric_limits<double>::infinity()); } } TEST_F(DuplicatedVariableLinearProgramTest1, Test) { IpoptSolver solver; if (solver.available()) { CheckSolution(solver); } } TEST_P(QuadraticProgramTest, TestQP) { IpoptSolver solver; prob()->RunProblem(&solver); } INSTANTIATE_TEST_SUITE_P( IpoptTest, QuadraticProgramTest, ::testing::Combine(::testing::ValuesIn(quadratic_cost_form()), ::testing::ValuesIn(linear_constraint_form()), ::testing::ValuesIn(quadratic_problems()))); GTEST_TEST(QPtest, TestUnitBallExample) { IpoptSolver solver; if (solver.available()) { TestQPonUnitBallExample(solver); } } class NoisyQuadraticCost { public: explicit NoisyQuadraticCost(const double max_noise) : max_noise_(max_noise) {} int numInputs() const { return 1; } int numOutputs() const { return 1; } template <typename T> void eval(internal::VecIn<T> const& x, internal::VecOut<T>* y) const { // Parabola with minimum at (-1, 1) with some deterministic noise applied to // the input so derivatives will be correctish but not easily followable to // the minimum. // The sign of the noise alternates between calls. The magnitude of the // noise increases from 0 to max_noise_ over the course of // 2 * noise_counter_limit_ calls, after which it resets to 0. double noise = std::pow(-1., noise_counter_) * max_noise_ * noise_counter_ / noise_counter_limit_; if (noise_counter_ >= 0) { noise_counter_ = (noise_counter_ + 1) % noise_counter_limit_; noise_counter_ *= -1; } else { noise_counter_ *= -1; } auto noisy_x = x(0) + noise; y->resize(1); (*y)(0) = (noisy_x + 1) * (noisy_x + 1) + 1; } private: double max_noise_{}; mutable int noise_counter_{}; const int noise_counter_limit_{10}; }; GTEST_TEST(IpoptSolverTest, AcceptableResult) { IpoptSolver solver; SolverOptions options; options.SetOption(IpoptSolver::id(), "tol", 1e-6); options.SetOption(IpoptSolver::id(), "dual_inf_tol", 1e-6); options.SetOption(IpoptSolver::id(), "max_iter", 10); const VectorX<double> x_initial_guess = VectorX<double>::Ones(1); if (solver.available()) { double max_noise = 1e-2; { // Set up a program and give it a relatively large amount of noise for // the specified tolerance. MathematicalProgram prog; auto x = prog.NewContinuousVariables(1); prog.AddCost(NoisyQuadraticCost(max_noise), x); auto result = solver.Solve(prog, x_initial_guess, options); // Expect to hit iteration limit EXPECT_FALSE(result.is_success()); EXPECT_EQ(result.get_solution_result(), SolutionResult::kIterationLimit); EXPECT_EQ(result.get_solver_details<IpoptSolver>().status, kIpoptMaxiterExceeded); } options.SetOption(IpoptSolver::id(), "acceptable_tol", 1e-3); options.SetOption(IpoptSolver::id(), "acceptable_dual_inf_tol", 1e-3); options.SetOption(IpoptSolver::id(), "acceptable_iter", 3); { // Set up the same program, but provide acceptability criteria that // should be feasible with even with the noise. MathematicalProgram prog; auto x = prog.NewContinuousVariables(1); prog.AddCost(NoisyQuadraticCost(max_noise), x); auto result = solver.Solve(prog, x_initial_guess, options); EXPECT_EQ(result.get_solver_details<IpoptSolver>().status, kIpoptStopAtAcceptablePoint); // Expect Ipopt's "STOP_AT_ACCEPTABLE_POINT" to be translated to success. EXPECT_TRUE(result.is_success()); } } } GTEST_TEST(IpoptSolverTest, QPDualSolution1) { IpoptSolver solver; TestQPDualSolution1(solver, {} /* solver_options */, 1e-5); } GTEST_TEST(IpoptSolverTest, QPDualSolution2) { IpoptSolver solver; TestQPDualSolution2(solver); } GTEST_TEST(IpoptSolverTest, QPDualSolution3) { IpoptSolver solver; TestQPDualSolution3(solver); } GTEST_TEST(IpoptSolverTest, EqualityConstrainedQPDualSolution1) { IpoptSolver solver; TestEqualityConstrainedQPDualSolution1(solver); } GTEST_TEST(IpoptSolverTest, EqualityConstrainedQPDualSolution2) { IpoptSolver solver; TestEqualityConstrainedQPDualSolution2(solver); } GTEST_TEST(IpoptSolverTest, LPDualSolution1) { IpoptSolver solver; TestLPDualSolution1(solver); } GTEST_TEST(IpoptSolverTest, LPDualSolution2) { IpoptSolver solver; TestLPDualSolution2(solver); } GTEST_TEST(IpoptSolverTest, LPDualSolution3) { IpoptSolver solver; TestLPDualSolution3(solver); } GTEST_TEST(IpoptSolverTest, LPDualSolution4) { IpoptSolver solver; TestLPDualSolution4(solver); } GTEST_TEST(IpoptSolverTest, LPDualSolution5) { IpoptSolver solver; TestLPDualSolution5(solver); } GTEST_TEST(IpoptSolverTest, EckhardtDualSolution) { IpoptSolver solver; TestEckhardtDualSolution(solver, Eigen::Vector3d(1., 1., 5.)); } GTEST_TEST(IpoptSolverTest, TestNonconvexQP) { IpoptSolver solver; if (solver.available()) { TestNonconvexQP(solver, false); } } GTEST_TEST(IpoptSolverTest, TestL2NormCost) { IpoptSolver solver; TestL2NormCost(solver, 1e-6); } /* Tests the solver's processing of the verbosity options. With multiple ways to request verbosity (common options and solver-specific options), we simply apply a smoke test that none of the means causes runtime errors. Note, we don't test the case where we configure the mathematical program itself; that is resolved in SolverBase. We only need to test the options passed into Solve(). The possible configurations are: - No verbosity set at all (this is implicitly tested in all other tests). - Common option explicitly set (on & off) - Solver option explicitly set (on & off) - Both options explicitly set (with all permutations of (on, on), etc.) */ GTEST_TEST(IpoptSolverTest, SolverOptionsVerbosity) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(1); prog.AddLinearConstraint(x(0) <= 3); prog.AddLinearConstraint(x(0) >= -3); prog.AddLinearCost(x(0)); IpoptSolver solver; if (solver.is_available()) { // Setting common options. for (int print_to_console : {0, 1}) { SolverOptions options; options.SetOption(CommonSolverOption::kPrintToConsole, print_to_console); solver.Solve(prog, {}, options); } // Setting solver options. for (int print_to_console : {0, 2}) { SolverOptions options; options.SetOption(IpoptSolver::id(), "print_level", print_to_console); solver.Solve(prog, {}, options); } // Setting both. for (int common_print_to_console : {0, 1}) { for (int solver_print_to_console : {0, 2}) { SolverOptions options; options.SetOption(CommonSolverOption::kPrintToConsole, common_print_to_console); options.SetOption(IpoptSolver::id(), "print_level", solver_print_to_console); solver.Solve(prog, {}, options); } } } } // This is to verify we can set the print out file through CommonSolverOption. GTEST_TEST(IpoptSolverTest, PrintToFile) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(1); prog.AddLinearConstraint(x(0) <= 3); prog.AddLinearConstraint(x(0) >= -3); prog.AddLinearCost(x(0)); const std::string filename = temp_directory() + "/ipopt.log"; EXPECT_FALSE(std::filesystem::exists({filename})); SolverOptions solver_options; solver_options.SetOption(CommonSolverOption::kPrintFileName, filename); IpoptSolver solver; if (solver.is_available()) { const auto result = solver.Solve(prog, {}, solver_options); EXPECT_TRUE(result.is_success()); EXPECT_TRUE(std::filesystem::exists({filename})); } } TEST_P(TestEllipsoidsSeparation, TestSOCP) { IpoptSolver ipopt_solver; if (ipopt_solver.available()) { SolveAndCheckSolution(ipopt_solver, {}, 1.E-8); } } INSTANTIATE_TEST_SUITE_P( IpoptSolverTest, TestEllipsoidsSeparation, ::testing::ValuesIn({EllipsoidsSeparationProblem::kProblem0, EllipsoidsSeparationProblem::kProblem1, EllipsoidsSeparationProblem::kProblem3})); TEST_P(TestQPasSOCP, TestSOCP) { IpoptSolver ipopt_solver; if (ipopt_solver.available()) { SolveAndCheckSolution(ipopt_solver); } } INSTANTIATE_TEST_SUITE_P(IpoptSolverTest, TestQPasSOCP, ::testing::ValuesIn(GetQPasSOCPProblems())); TEST_P(TestFindSpringEquilibrium, TestSOCP) { IpoptSolver ipopt_solver; if (ipopt_solver.available()) { SolveAndCheckSolution(ipopt_solver, {}, 2E-3); } } INSTANTIATE_TEST_SUITE_P( IpoptSolverTest, TestFindSpringEquilibrium, ::testing::ValuesIn(GetFindSpringEquilibriumProblems())); GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem1) { MaximizeGeometricMeanTrivialProblem1 prob; IpoptSolver solver; if (solver.available()) { const auto result = solver.Solve(prob.prog(), {}, {}); prob.CheckSolution(result, 4E-6); } } GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem2) { MaximizeGeometricMeanTrivialProblem2 prob; IpoptSolver solver; if (solver.available()) { const auto result = solver.Solve(prob.prog(), {}, {}); prob.CheckSolution(result, 1.E-6); } } GTEST_TEST(TestSOCP, SmallestEllipsoidCoveringProblem) { IpoptSolver solver; SolveAndCheckSmallestEllipsoidCoveringProblems(solver, {}, 1E-6); } GTEST_TEST(TestLP, PoorScaling) { IpoptSolver solver; TestLPPoorScaling1(solver, true, 1E-6); TestLPPoorScaling2(solver, true, 1E-4); } TEST_F(QuadraticEqualityConstrainedProgram1, test) { IpoptSolver solver; if (solver.available()) { CheckSolution(solver, Eigen::Vector2d(0.5, 0.8), std::nullopt, 1E-6); } } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/mosek_solver_internal_test.cc
#include "drake/solvers/mosek_solver_internal.h" #include <limits> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/symbolic_test_util.h" #include "drake/math/quadratic_form.h" #include "drake/solvers/mosek_solver.h" namespace drake { namespace solvers { namespace internal { const double kInf = std::numeric_limits<double>::infinity(); using BarFType = std::vector<std::unordered_map< MSKint64t, std::pair<std::vector<MSKint64t>, std::vector<MSKrealt>>>>; // By default, the newly appended variables in Mosek are fixed to 0. Hence, // their bounds need to be explicitly set to -inf and inf. void AppendFreeVariable(MSKtask_t task, int num_vars) { int num_existing_vars; MSK_getnumvar(task, &num_existing_vars); MSK_appendvars(task, num_vars); for (int i = 0; i < num_vars; ++i) { MSK_putvarbound(task, num_existing_vars + i, MSK_BK_FR, -MSK_INFINITY, MSK_INFINITY); } } void CheckParseLinearExpression( const MosekSolverProgram& dut, const MathematicalProgram& prog, const Eigen::SparseMatrix<double>& A, const Eigen::SparseMatrix<double>& B, const VectorX<symbolic::Variable>& decision_vars, const std::vector<MSKint32t>& slack_vars_mosek_indices, const std::vector<MSKint32t>& F_subi, const std::vector<MSKint32t>& F_subj, const std::vector<MSKrealt>& F_valij, const BarFType& bar_F) { VectorX<symbolic::Variable> slack_vars(slack_vars_mosek_indices.size()); for (int i = 0; i < slack_vars.rows(); ++i) { slack_vars(i) = symbolic::Variable("slack" + std::to_string(i)); } VectorX<symbolic::Expression> linear_exprs_expected = A * decision_vars + B * slack_vars; std::vector<Eigen::Triplet<double>> F_triplets(F_subi.size()); for (int i = 0; i < static_cast<int>(F_triplets.size()); ++i) { F_triplets[i] = Eigen::Triplet<double>(F_subi[i], F_subj[i], F_valij[i]); } int num_mosek_vars; const auto rescode = MSK_getnumvar(dut.task(), &num_mosek_vars); ASSERT_EQ(rescode, MSK_RES_OK); Eigen::SparseMatrix<double> F(A.rows(), num_mosek_vars); F.setFromTriplets(F_triplets.begin(), F_triplets.end()); // mosek_vars are the non-matrix variables stored inside Mosek. VectorX<symbolic::Variable> mosek_vars(num_mosek_vars); // bar_X are Mosek matrix variables. int num_barvar = 0; MSK_getnumbarvar(dut.task(), &num_barvar); std::vector<MatrixX<symbolic::Variable>> bar_X(num_barvar); // Now set up mosek_vars and bar_X. for (int i = 0; i < slack_vars.rows(); ++i) { mosek_vars(slack_vars_mosek_indices[i]) = slack_vars(i); } for (int i = 0; i < prog.num_vars(); ++i) { auto it1 = dut.decision_variable_to_mosek_nonmatrix_variable().find(i); if (it1 != dut.decision_variable_to_mosek_nonmatrix_variable().end()) { mosek_vars(it1->second) = prog.decision_variable(i); } else { auto it2 = dut.decision_variable_to_mosek_matrix_variable().find(i); ASSERT_NE(it2, dut.decision_variable_to_mosek_matrix_variable().end()); bar_X[it2->second.bar_matrix_index()].resize( it2->second.num_matrix_rows(), it2->second.num_matrix_rows()); bar_X[it2->second.bar_matrix_index()](it2->second.row_index(), it2->second.col_index()) = prog.decision_variable(i); bar_X[it2->second.bar_matrix_index()](it2->second.col_index(), it2->second.row_index()) = prog.decision_variable(i); } } for (int i = 0; i < mosek_vars.rows(); ++i) { if (mosek_vars(i).is_dummy()) { mosek_vars(i) = symbolic::Variable("unused_slack"); } } // Compute the linear expression. VectorX<symbolic::Expression> linear_exprs = F * mosek_vars; if (!bar_F.empty()) { // For each row i, compute ∑ⱼ <F̅ᵢⱼ, X̅ⱼ> EXPECT_EQ(bar_F.size(), A.rows()); for (int i = 0; i < A.rows(); ++i) { for (const auto& [j, sub_weights] : bar_F[i]) { const std::vector<MSKint64t>& sub = sub_weights.first; const std::vector<MSKrealt>& weights = sub_weights.second; Eigen::MatrixXd F_bar_ij = Eigen::MatrixXd::Zero(bar_X[j].rows(), bar_X[j].cols()); ASSERT_EQ(sub.size(), weights.size()); for (int k = 0; k < static_cast<int>(sub.size()); ++k) { // First construct the selection matrix E from the index sub[k]. // I know the selection matrix E always has 1 non-zero entry in the // lower triangular part. MSKint32t subi{0}; MSKint32t subj{0}; MSKrealt valij{0}; MSK_getsparsesymmat(dut.task(), sub[k], 1, &subi, &subj, &valij); F_bar_ij(subi, subj) += valij * weights[k]; if (subi != subj) { F_bar_ij(subj, subi) += valij * weights[k]; } } linear_exprs(i) += (F_bar_ij.transpose() * bar_X[j]).trace(); } } } EXPECT_EQ(linear_exprs.rows(), linear_exprs_expected.rows()); for (int i = 0; i < linear_exprs.rows(); ++i) { EXPECT_PRED2(symbolic::test::ExprEqual, linear_exprs(i).Expand(), linear_exprs_expected(i).Expand()); } } GTEST_TEST(ParseLinearExpression, Test1) { // Test with non-empty A matrix and empty B matrix, no Mosek matrix variable. MathematicalProgram prog; auto dummy = prog.NewContinuousVariables<2>(); auto x = prog.NewContinuousVariables<3>(); Eigen::Matrix<double, 3, 2> A_dense; A_dense << 1, 2, 0, 1, 3, 0; Eigen::SparseMatrix<double> A_sparse = A_dense.sparseView(); Eigen::SparseMatrix<double> B(3, 0); MSKenv_t env; MSK_makeenv(&env, nullptr); MosekSolverProgram dut(prog, env); AppendFreeVariable( dut.task(), dut.decision_variable_to_mosek_nonmatrix_variable().size()); std::vector<MSKint32t> F_subi; std::vector<MSKint32t> F_subj; std::vector<MSKrealt> F_valij; BarFType bar_F; const auto rescode = dut.ParseLinearExpression( prog, A_sparse, B, x.tail<2>(), {}, &F_subi, &F_subj, &F_valij, &bar_F); ASSERT_EQ(rescode, MSK_RES_OK); EXPECT_EQ(F_subi.size(), A_sparse.nonZeros()); EXPECT_EQ(F_subj.size(), A_sparse.nonZeros()); EXPECT_EQ(F_valij.size(), A_sparse.nonZeros()); EXPECT_TRUE(bar_F.empty()); CheckParseLinearExpression(dut, prog, A_sparse, B, x.tail<2>(), {}, F_subi, F_subj, F_valij, bar_F); MSK_deleteenv(&env); } GTEST_TEST(ParseLinearExpression, Test2) { // Test with non-empty A matrix and empty B matrix, with only Mosek matrix // variable and no non-matrix variable. MathematicalProgram prog; auto X1 = prog.NewSymmetricContinuousVariables<2>(); auto X2 = prog.NewSymmetricContinuousVariables<3>(); auto X3 = prog.NewSymmetricContinuousVariables<4>(); prog.AddPositiveSemidefiniteConstraint(X1); prog.AddPositiveSemidefiniteConstraint(X2); prog.AddPositiveSemidefiniteConstraint(X3); Eigen::Matrix<double, 3, 3> A_dense; A_dense << 1, 2, 0, -1, 3, 0, 0, 2, -1; Eigen::SparseMatrix<double> A_sparse = A_dense.sparseView(); Eigen::SparseMatrix<double> B(3, 0); MSKenv_t env; MSK_makeenv(&env, nullptr); MosekSolverProgram dut(prog, env); std::vector<MSKint32t> bar_var_dimension = {2, 3, 4}; MSK_appendbarvars(dut.task(), 3, bar_var_dimension.data()); Vector3<symbolic::Variable> decision_vars(X2(0, 1), X3(1, 1), X3(1, 2)); std::vector<MSKint32t> F_subi; std::vector<MSKint32t> F_subj; std::vector<MSKrealt> F_valij; BarFType bar_F; const auto rescode = dut.ParseLinearExpression( prog, A_sparse, B, decision_vars, {}, &F_subi, &F_subj, &F_valij, &bar_F); ASSERT_EQ(rescode, MSK_RES_OK); EXPECT_TRUE(F_subi.empty()); EXPECT_TRUE(F_subj.empty()); EXPECT_TRUE(F_valij.empty()); EXPECT_FALSE(bar_F.empty()); CheckParseLinearExpression(dut, prog, A_sparse, B, decision_vars, {}, F_subi, F_subj, F_valij, bar_F); MSK_deleteenv(&env); } GTEST_TEST(ParseLinearExpression, Test3) { // Test with non-empty A matrix and non-empty B matrix, with both Mosek matrix // variable and non-matrix variable. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto y = prog.NewContinuousVariables<4>(); auto X1 = prog.NewSymmetricContinuousVariables<2>(); auto X2 = prog.NewSymmetricContinuousVariables<3>(); prog.AddPositiveSemidefiniteConstraint(X1); prog.AddPositiveSemidefiniteConstraint(X2); Eigen::Matrix<double, 3, 3> A_dense; A_dense << 1, 2, 0, -1, 3, 0, 0, 2, -1; Eigen::SparseMatrix<double> A_sparse = A_dense.sparseView(); Eigen::Matrix<double, 3, 2> B_dense; B_dense << 1, 3, -2, 1, 0, 2; Eigen::SparseMatrix<double> B_sparse = B_dense.sparseView(); MSKenv_t env; MSK_makeenv(&env, nullptr); MosekSolverProgram dut(prog, env); std::vector<MSKint32t> bar_var_dimension = {2, 3, 4}; MSK_appendbarvars(dut.task(), 3, bar_var_dimension.data()); const int num_slack_vars = 3; AppendFreeVariable( dut.task(), dut.decision_variable_to_mosek_nonmatrix_variable().size() + num_slack_vars); std::vector<MSKint32t> slack_vars_mosek_indices = { static_cast<int>( dut.decision_variable_to_mosek_nonmatrix_variable().size()) + 1, static_cast<int>( dut.decision_variable_to_mosek_nonmatrix_variable().size()) + 2}; Vector3<symbolic::Variable> decision_vars(X2(0, 1), X1(1, 1), y(2)); std::vector<MSKint32t> F_subi; std::vector<MSKint32t> F_subj; std::vector<MSKrealt> F_valij; BarFType bar_F; const auto rescode = dut.ParseLinearExpression( prog, A_sparse, B_sparse, decision_vars, slack_vars_mosek_indices, &F_subi, &F_subj, &F_valij, &bar_F); ASSERT_EQ(rescode, MSK_RES_OK); EXPECT_FALSE(F_subi.empty()); EXPECT_FALSE(F_subj.empty()); EXPECT_FALSE(F_valij.empty()); EXPECT_FALSE(bar_F.empty()); CheckParseLinearExpression(dut, prog, A_sparse, B_sparse, decision_vars, slack_vars_mosek_indices, F_subi, F_subj, F_valij, bar_F); MSK_deleteenv(&env); } /** * @param slack_vars Mosek can create variables that are not * prog.decision_variables(). We call them "slack variables". `slack_vars` maps * the index of the variables in Mosek to its symbolic form. Returns all of the * affine expressions stored inside dut.task(). */ VectorX<symbolic::Expression> GetAffineExpression( const MathematicalProgram& prog, const MosekSolverProgram& dut, const std::unordered_map<MSKint32t, symbolic::Variable>& slack_vars) { // First set up mosek variable. int num_mosek_vars; MSK_getnumvar(dut.task(), &num_mosek_vars); // mosek_vars are the non-matrix variables stored inside Mosek. VectorX<symbolic::Variable> mosek_vars(num_mosek_vars); // bar_X are Mosek matrix variables. int num_barvar = 0; MSK_getnumbarvar(dut.task(), &num_barvar); std::vector<MatrixX<symbolic::Variable>> bar_X(num_barvar); // Now set up mosek_vars and bar_X. for (int i = 0; i < prog.num_vars(); ++i) { auto it1 = dut.decision_variable_to_mosek_nonmatrix_variable().find(i); if (it1 != dut.decision_variable_to_mosek_nonmatrix_variable().end()) { mosek_vars(it1->second) = prog.decision_variable(i); } else { auto it2 = dut.decision_variable_to_mosek_matrix_variable().find(i); EXPECT_NE(it2, dut.decision_variable_to_mosek_matrix_variable().end()); bar_X[it2->second.bar_matrix_index()].resize( it2->second.num_matrix_rows(), it2->second.num_matrix_rows()); bar_X[it2->second.bar_matrix_index()](it2->second.row_index(), it2->second.col_index()) = prog.decision_variable(i); bar_X[it2->second.bar_matrix_index()](it2->second.col_index(), it2->second.row_index()) = prog.decision_variable(i); } } for (int i = 0; i < mosek_vars.rows(); ++i) { if (mosek_vars(i).is_dummy()) { mosek_vars(i) = slack_vars.at(i); } } MSKint64t afe_f_nnz; MSK_getafefnumnz(dut.task(), &afe_f_nnz); std::vector<MSKint64t> afe_idx(afe_f_nnz); std::vector<MSKint32t> var_idx(afe_f_nnz); std::vector<MSKrealt> val(afe_f_nnz); MSK_getafeftrip(dut.task(), afe_idx.data(), var_idx.data(), val.data()); std::vector<Eigen::Triplet<double>> F_triplets(afe_f_nnz); for (int i = 0; i < afe_f_nnz; ++i) { F_triplets[i] = Eigen::Triplet<double>(afe_idx[i], var_idx[i], val[i]); } MSKint64t num_afe; MSK_getnumafe(dut.task(), &num_afe); Eigen::SparseMatrix<double> F(num_afe, num_mosek_vars); F.setFromTriplets(F_triplets.begin(), F_triplets.end()); Eigen::VectorXd g(num_afe); MSK_getafegslice(dut.task(), 0, num_afe, g.data()); // The affine expression is F*x + <bar_F, bar_X> + g. We first compute the // part F*x+g. VectorX<symbolic::Expression> affine_expressions = F * mosek_vars + g; // Compute <bar_F, bar_X>. for (MSKint64t i = 0; i < num_afe; ++i) { MSKint32t num_entry; MSKint64t num_term_total; MSK_getafebarfrowinfo(dut.task(), i, &num_entry, &num_term_total); std::vector<MSKint32t> barvar_idx(num_entry); std::vector<MSKint64t> ptr_term(num_entry); std::vector<MSKint64t> num_term(num_entry); std::vector<MSKint64t> term_idx(num_term_total); std::vector<MSKrealt> term_weight(num_term_total); MSK_getafebarfrow(dut.task(), i, barvar_idx.data(), ptr_term.data(), num_term.data(), term_idx.data(), term_weight.data()); for (int k = 0; k < num_entry; ++k) { const MSKint32t j = barvar_idx[k]; Eigen::MatrixXd bar_F_ij = Eigen::MatrixXd::Zero(bar_X[j].rows(), bar_X[j].rows()); for (int l = ptr_term[k]; l < ptr_term[k] + num_term[k]; ++l) { // I know the selection matrix E always has 1 non-zero entry in the // lower triangular part. MSKint32t subi{0}; MSKint32t subj{0}; MSKrealt valij{0}; MSK_getsparsesymmat(dut.task(), term_idx[l], 1, &subi, &subj, &valij); bar_F_ij(subi, subj) += valij * term_weight[l]; if (subi != subj) { bar_F_ij(subj, subi) += valij * term_weight[l]; } } affine_expressions(i) += (bar_F_ij.transpose() * bar_X[j]).trace(); } } return affine_expressions; } GTEST_TEST(AddConeConstraings, Test1) { // Test Lorentz cone constraint. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); Eigen::Matrix<double, 4, 2> A1; A1 << 1, 2, -1, 3, 0, 2, 1, 0; Eigen::Vector4d b1(1, 0, -2, 3); auto constraint1 = prog.AddLorentzConeConstraint(A1, b1, x.tail<2>()); Eigen::Matrix<double, 3, 2> A2; A2 << 1, 2, -1, 3, 0, 1; Eigen::Vector3d b2(2, 1, 0); auto constraint2 = prog.AddLorentzConeConstraint(A2, b2, x.head<2>()); MSKenv_t env; MSK_makeenv(&env, nullptr); MosekSolverProgram dut(prog, env); AppendFreeVariable( dut.task(), dut.decision_variable_to_mosek_nonmatrix_variable().size()); std::unordered_map<Binding<LorentzConeConstraint>, MSKint64t> acc_indices; auto rescode = dut.AddConeConstraints(prog, prog.lorentz_cone_constraints(), &acc_indices); // Check the number of affine expressions, affine cone constraints, domains. ASSERT_EQ(rescode, MSK_RES_OK); MSKint64t num_afe; MSK_getnumafe(dut.task(), &num_afe); EXPECT_EQ(num_afe, 7); MSKint64t num_acc; MSK_getnumacc(dut.task(), &num_acc); EXPECT_EQ(num_acc, 2); MSKint64t acc_total; MSK_getaccntot(dut.task(), &acc_total); EXPECT_EQ(acc_total, 7); EXPECT_EQ(acc_indices.size(), 2); EXPECT_EQ(acc_indices.at(constraint1), 0); EXPECT_EQ(acc_indices.at(constraint2), 1); MSKint64t num_domain; MSK_getnumdomain(dut.task(), &num_domain); EXPECT_EQ(num_domain, 2); // Check domain types. for (MSKint64t i = 0; i < num_domain; ++i) { MSKdomaintypee domain_type; MSK_getdomaintype(dut.task(), i, &domain_type); EXPECT_EQ(domain_type, MSK_DOMAIN_QUADRATIC_CONE); } // Checks the affine expressions. MSKint64t afe_f_nnz; MSK_getafefnumnz(dut.task(), &afe_f_nnz); EXPECT_EQ(afe_f_nnz, constraint1.evaluator()->A().nonZeros() + constraint2.evaluator()->A().nonZeros()); const VectorX<symbolic::Expression> affine_expressions = GetAffineExpression(prog, dut, {}); VectorX<symbolic::Expression> affine_expressions_expected(7); affine_expressions_expected.head<4>() = A1 * x.tail<2>() + b1; affine_expressions_expected.tail<3>() = A2 * x.head<2>() + b2; EXPECT_EQ(affine_expressions.rows(), affine_expressions_expected.rows()); for (int i = 0; i < affine_expressions.rows(); ++i) { EXPECT_PRED2(symbolic::test::ExprEqual, affine_expressions(i).Expand(), affine_expressions_expected(i).Expand()); } MSK_deleteenv(&env); } GTEST_TEST(AddConeConstraints, Test2) { // Test rotated Lorentz cone constraint. // This program has positive semidefinite constraints, hence Mosek has matrix // variables. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); auto X1 = prog.NewSymmetricContinuousVariables<3>(); auto X2 = prog.NewSymmetricContinuousVariables<4>(); prog.AddPositiveSemidefiniteConstraint(X1); prog.AddPositiveSemidefiniteConstraint(X2); Eigen::Matrix<double, 4, 2> A1; A1 << 1, 2, -1, 3, 0, 2, 1, 0; Eigen::Vector4d b1(1, 0, -2, 3); auto constraint1 = prog.AddRotatedLorentzConeConstraint( A1, b1, Vector2<symbolic::Variable>(x(0), X1(1, 1))); Eigen::Matrix<double, 3, 3> A2; A2 << 1, 2, -1, 3, 0, 1, 0, 1, -4; Eigen::Vector3d b2(2, 1, 0); auto constraint2 = prog.AddRotatedLorentzConeConstraint( A2, b2, Vector3<symbolic::Variable>(x(2), X1(0, 1), X2(2, 1))); MSKenv_t env; MSK_makeenv(&env, nullptr); MosekSolverProgram dut(prog, env); AppendFreeVariable( dut.task(), dut.decision_variable_to_mosek_nonmatrix_variable().size()); std::vector<MSKint32t> bar_var_dimension = {3, 4}; MSK_appendbarvars(dut.task(), 2, bar_var_dimension.data()); std::unordered_map<Binding<RotatedLorentzConeConstraint>, MSKint64t> acc_indices; auto rescode = dut.AddConeConstraints( prog, prog.rotated_lorentz_cone_constraints(), &acc_indices); ASSERT_EQ(rescode, MSK_RES_OK); // Check acc_indices. EXPECT_EQ(acc_indices.size(), 2); EXPECT_EQ(acc_indices.at(constraint1), 0); EXPECT_EQ(acc_indices.at(constraint2), 1); // Check domain types. MSKint64t num_domain; MSK_getnumdomain(dut.task(), &num_domain); EXPECT_EQ(num_domain, 2); for (MSKint64t i = 0; i < num_domain; ++i) { MSKdomaintypee domain_type; MSK_getdomaintype(dut.task(), i, &domain_type); EXPECT_EQ(domain_type, MSK_DOMAIN_RQUADRATIC_CONE); } // Check affine expressions in Mosek. const VectorX<symbolic::Expression> affine_expressions = GetAffineExpression(prog, dut, {}); VectorX<symbolic::Expression> affine_expressions_expected(A1.rows() + A2.rows()); affine_expressions_expected.head(A1.rows()) = A1 * constraint1.variables() + b1; affine_expressions_expected(0) *= 0.5; affine_expressions_expected.tail(A2.rows()) = A2 * constraint2.variables() + b2; affine_expressions_expected(A1.rows()) *= 0.5; EXPECT_EQ(affine_expressions.rows(), affine_expressions_expected.rows()); for (int i = 0; i < affine_expressions.rows(); ++i) { EXPECT_PRED2(symbolic::test::ExprEqual, affine_expressions(i).Expand(), affine_expressions_expected(i).Expand()); } MSK_deleteenv(&env); } GTEST_TEST(AddQuadraticCostAsLinearCost, Test) { // Test AddQuadraticCostAsLinearCost. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); MSKenv_t env; MSK_makeenv(&env, nullptr); MosekSolverProgram dut(prog, env); AppendFreeVariable(dut.task(), x.rows()); Eigen::Matrix2d Q; Q << 1, 2, 2, 5; Eigen::SparseMatrix<double> Q_sparse = Q.sparseView(); MSKrescodee rescode = dut.AddQuadraticCostAsLinearCost(Q_sparse, x, prog); ASSERT_EQ(rescode, MSK_RES_OK); MSKint32t num_vars; MSK_getnumvar(dut.task(), &num_vars); EXPECT_EQ(num_vars, x.rows() + 1); MSKint64t num_acc; MSK_getnumacc(dut.task(), &num_acc); EXPECT_EQ(num_acc, 1); MSKint64t num_afe; MSK_getnumafe(dut.task(), &num_afe); EXPECT_EQ(num_afe, Q.rows() + 2); MSKdomaintypee domain_type; MSK_getdomaintype(dut.task(), 0, &domain_type); EXPECT_EQ(domain_type, MSK_DOMAIN_RQUADRATIC_CONE); // Check cost. Eigen::VectorXd c(x.rows() + 1); MSK_getc(dut.task(), c.data()); EXPECT_TRUE( CompareMatrices(c.head(x.rows()), Eigen::VectorXd::Zero(x.rows()))); EXPECT_EQ(c(c.rows() - 1), 1); // Check the affine expression. const Eigen::MatrixXd L = math::DecomposePSDmatrixIntoXtransposeTimesX( Q, std::numeric_limits<double>::epsilon()); std::unordered_map<MSKint32t, symbolic::Variable> slack_vars; symbolic::Variable s("s"); slack_vars.emplace(x.rows(), s); VectorX<symbolic::Expression> affine_expressions = GetAffineExpression(prog, dut, slack_vars); EXPECT_PRED2(symbolic::test::ExprEqual, (2 * affine_expressions(0) * affine_expressions(1)).Expand(), 2 * s); // The sum-of-squares for affine_expressions(i), i> 1 is x'*Q*x. EXPECT_PRED3(symbolic::test::PolynomialEqual, symbolic::Polynomial( affine_expressions.tail(affine_expressions.rows() - 2) .array() .square() .sum()), symbolic::Polynomial(x.cast<symbolic::Expression>().dot(Q * x)), 1E-10); // Add an arbitrary linear cost. const Eigen::SparseMatrix<double> linear_coeff = Eigen::Vector2d(1, 2).sparseView(); dut.AddLinearCost(linear_coeff, x, prog); MSK_getc(dut.task(), c.data()); EXPECT_TRUE(CompareMatrices(c.head(x.rows()), linear_coeff.toDense())); EXPECT_EQ(c(c.rows() - 1), 1); MSKrescodee terminal_code; MSK_optimizetrm(dut.task(), &terminal_code); MSKsoltypee solution_type = MSK_SOL_ITR; MSKsolstae solution_status; MSK_getsolsta(dut.task(), solution_type, &solution_status); EXPECT_EQ(solution_status, MSK_SOL_STA_OPTIMAL); Eigen::VectorXd acc_val(2 + Q.rows()); MSK_evaluateacc(dut.task(), solution_type, 0, acc_val.data()); Eigen::Vector3d mosek_var_sol; MSK_getxx(dut.task(), solution_type, mosek_var_sol.data()); const Eigen::Vector2d x_sol = mosek_var_sol.head<2>(); const double s_sol = mosek_var_sol(2); // Check the cost value. EXPECT_NEAR(0.5 * x_sol.dot(Q * x_sol), s_sol, 1E-8); // Check the optimality condition, the gradient of the cost is 0. EXPECT_TRUE(CompareMatrices(Q * x_sol + linear_coeff.toDense(), Eigen::VectorXd::Zero(x.rows()), 1E-10)); MSK_deleteenv(&env); } GTEST_TEST(AddQuadraticConstraint, Test) { MathematicalProgram prog; MSKenv_t env; MSK_makeenv(&env, nullptr); auto x = prog.NewContinuousVariables<3>(); MosekSolverProgram dut(prog, env); AppendFreeVariable( dut.task(), dut.decision_variable_to_mosek_nonmatrix_variable().size()); // Add a linear constraint. prog.AddLinearConstraint(Eigen::RowVector2d(1, 2), -10, 20, x.head<2>()); std::unordered_map<Binding<LinearConstraint>, ConstraintDualIndices> linear_con_dual_indices; std::unordered_map<Binding<LinearEqualityConstraint>, ConstraintDualIndices> linear_eq_con_dual_indices; MSKrescodee rescode = dut.AddLinearConstraints(prog, &linear_con_dual_indices, &linear_eq_con_dual_indices); // Add a quadratic constraint on a subset of variables. const Eigen::Matrix2d Q0 = Eigen::Vector2d(1, 2).asDiagonal(); const Eigen::Vector2d b0(2, -3); const auto quadratic_con0 = prog.AddQuadraticConstraint( Q0, b0, -kInf, 10, Vector2<symbolic::Variable>(x(2), x(0))); // Add a quadratic constraint on duplicated variables. // I intentially use a non-symmetric Q. Eigen::Matrix2d Q1; // clang-format off Q1 << -1, -3, -1, -5; // clang-format on const Eigen::Vector2d b1(1, -2); const auto quadratic_con1 = prog.AddQuadraticConstraint( Q1, b1, -2, kInf, Vector2<symbolic::Variable>(x(1), x(1))); std::unordered_map<Binding<QuadraticConstraint>, MSKint64t> quadratic_constraint_dual_indices; rescode = dut.AddQuadraticConstraints(prog, &quadratic_constraint_dual_indices); EXPECT_EQ(rescode, MSK_RES_OK); EXPECT_EQ(quadratic_constraint_dual_indices.size(), 2); EXPECT_EQ(quadratic_constraint_dual_indices.at(quadratic_con0), 1); EXPECT_EQ(quadratic_constraint_dual_indices.at(quadratic_con1), 2); { // Check the Hessian in the first quadratic constraint. MSKint32t maxnumqcnz = 3; int numqcnz{0}; std::vector<MSKint32t> qcsubi(maxnumqcnz); std::vector<MSKint32t> qcsubj(maxnumqcnz); std::vector<MSKrealt> qcval(maxnumqcnz); MSK_getqconk(dut.task(), 1, maxnumqcnz, &numqcnz, qcsubi.data(), qcsubj.data(), qcval.data()); EXPECT_EQ(numqcnz, 2); Eigen::Matrix3d Q0_mosek; Q0_mosek.setZero(); for (int i = 0; i < numqcnz; ++i) { Q0_mosek(qcsubi[i], qcsubj[i]) = qcval[i]; } Eigen::Matrix3d Q0_mosek_expected = Eigen::Vector3d(2, 0, 1).asDiagonal(); EXPECT_TRUE(CompareMatrices(Q0_mosek, Q0_mosek_expected)); } { // Check the Hessian in the second quadratic constraint. MSKint32t maxnumqcnz = 3; int numqcnz{0}; std::vector<MSKint32t> qcsubi(maxnumqcnz); std::vector<MSKint32t> qcsubj(maxnumqcnz); std::vector<MSKrealt> qcval(maxnumqcnz); MSK_getqconk(dut.task(), 2, maxnumqcnz, &numqcnz, qcsubi.data(), qcsubj.data(), qcval.data()); EXPECT_EQ(numqcnz, 1); Eigen::Matrix3d Q1_mosek; Q1_mosek.setZero(); for (int i = 0; i < numqcnz; ++i) { Q1_mosek(qcsubi[i], qcsubj[i]) = qcval[i]; } Eigen::Matrix3d Q1_mosek_expected = Eigen::Vector3d(0, -10, 0).asDiagonal(); EXPECT_TRUE(CompareMatrices(Q1_mosek, Q1_mosek_expected)); } // Check the bound of the quadratic constraint. { MSKboundkeye bound_key; MSKrealt bl; MSKrealt bu; // Test the bound of the first quadratic constraint. MSK_getconbound(dut.task(), 1, &bound_key, &bl, &bu); EXPECT_EQ(bound_key, MSK_BK_UP); EXPECT_EQ(bu, quadratic_con0.evaluator()->upper_bound()(0)); EXPECT_EQ(bl, -MSK_INFINITY); // Test the bound of the second quadratic constraint. MSK_getconbound(dut.task(), 2, &bound_key, &bl, &bu); EXPECT_EQ(bound_key, MSK_BK_LO); EXPECT_EQ(bl, quadratic_con1.evaluator()->lower_bound()(0)); EXPECT_EQ(bu, MSK_INFINITY); } // Test the linear coefficient. { MSKint32t nzi; std::vector<MSKint32t> subi(prog.num_vars()); std::vector<MSKrealt> vali(prog.num_vars()); // Test the linear coefficient of the first quadratic constraint MSK_getarow(dut.task(), 1, &nzi, subi.data(), vali.data()); EXPECT_EQ(nzi, 2); Eigen::VectorXd a = Eigen::VectorXd::Zero(prog.num_vars()); for (int i = 0; i < nzi; ++i) { a(subi[i]) = vali[i]; } EXPECT_TRUE(CompareMatrices(a, Eigen::Vector3d(b0(1), 0, b0(0)))); // Test the linear coefficient of the second quadratic constraint MSK_getarow(dut.task(), 2, &nzi, subi.data(), vali.data()); EXPECT_EQ(nzi, 1); EXPECT_EQ(subi[0], 1); EXPECT_EQ(vali[0], b1(0) + b1(1)); } // Solve the optimization problem MSKrescodee terminal_code; MSK_optimizetrm(dut.task(), &terminal_code); MSKsoltypee solution_type = MSK_SOL_ITR; MSKsolstae solution_status; MSK_getsolsta(dut.task(), solution_type, &solution_status); EXPECT_EQ(solution_status, MSK_SOL_STA_OPTIMAL); Eigen::Vector3d mosek_var_sol; MSK_getxx(dut.task(), solution_type, mosek_var_sol.data()); const Eigen::Vector3d x_sol = mosek_var_sol; EXPECT_TRUE(quadratic_con0.evaluator()->CheckSatisfied( Eigen::Vector2d(x_sol(2), x_sol(0)))); EXPECT_TRUE(quadratic_con1.evaluator()->CheckSatisfied( Eigen::Vector2d(x_sol(1), x_sol(1)))); MSK_deleteenv(&env); } template <typename Derived> Eigen::MatrixXd ToSymmetric(const Eigen::MatrixBase<Derived>& X) { return (X.eval() + X.eval().transpose()) / 2; } GTEST_TEST(AddLinearMatrixInequalityConstraint, LMIonly) { // Test a program with only LMI constraint MathematicalProgram prog; auto x = prog.NewContinuousVariables(2); std::vector<Eigen::MatrixXd> F; F.push_back( ToSymmetric((Eigen::Matrix3d() << 0, 1, 0, 1, 2, 1, 0, 2, 1).finished())); F.push_back(ToSymmetric( (Eigen::Matrix3d() << 1, -1, 2, 0, 1, 1, 0, 1, -1).finished())); F.push_back(ToSymmetric( (Eigen::Matrix3d() << 2, 0, 1, 0, 2, -1, 0, 2, -1).finished())); auto lmi0 = prog.AddLinearMatrixInequalityConstraint(F, x.head<2>()); F.clear(); F.push_back(ToSymmetric( (Eigen::Matrix3d() << 1, 3, 1, 2, -4, 1, 0, 1, 0).finished())); F.push_back(ToSymmetric( (Eigen::Matrix3d() << -1, 0, 1, 1, -2, 1, 0, 1, 0).finished())); auto lmi1 = prog.AddLinearMatrixInequalityConstraint(F, x.head<1>()); MSKenv_t env; MSK_makeenv(&env, nullptr); MosekSolverProgram dut(prog, env); AppendFreeVariable( dut.task(), dut.decision_variable_to_mosek_nonmatrix_variable().size()); std::unordered_map<Binding<LinearMatrixInequalityConstraint>, MSKint64t> acc_indices; auto rescode = dut.AddLinearMatrixInequalityConstraint(prog, &acc_indices); EXPECT_EQ(rescode, MSK_RES_OK); EXPECT_EQ(acc_indices.size(), 2); EXPECT_EQ(acc_indices.at(lmi0), 0); EXPECT_EQ(acc_indices.at(lmi1), 1); MSKint64t num_acc; MSK_getnumacc(dut.task(), &num_acc); EXPECT_EQ(num_acc, 2); // An LMI with 3 x 3 psd matrix has 6 affine cone constraints (the lower // triangular part of the psd matrix). MSKint64t accn0, accn1; MSK_getaccn(dut.task(), 0, &accn0); MSK_getaccn(dut.task(), 1, &accn1); EXPECT_EQ(accn0, 6); EXPECT_EQ(accn1, 6); MSKint64t num_domain; MSK_getnumdomain(dut.task(), &num_domain); EXPECT_EQ(num_domain, 2); // Check domain types. for (MSKint64t i = 0; i < num_domain; ++i) { MSKdomaintypee domain_type; MSK_getdomaintype(dut.task(), i, &domain_type); EXPECT_EQ(domain_type, MSK_DOMAIN_SVEC_PSD_CONE); } // Check the affine expressions. const VectorX<symbolic::Expression> affine_expressions = GetAffineExpression(prog, dut, {}); EXPECT_EQ(affine_expressions.rows(), 12); VectorX<symbolic::Expression> affine_expressions_expected(12); int affine_expression_count = 0; for (int j = 0; j < 3; ++j) { for (int i = j; i < 3; ++i) { const double scaling_factor = i == j ? 1.0 : std::sqrt(2); affine_expressions_expected(affine_expression_count++) = scaling_factor * (lmi0.evaluator()->F()[0](i, j) + lmi0.evaluator()->F()[1](i, j) * lmi0.variables()(0) + lmi0.evaluator()->F()[2](i, j) * lmi0.variables()(1)); } } for (int j = 0; j < 3; ++j) { for (int i = j; i < 3; ++i) { const double scaling_factor = i == j ? 1.0 : std::sqrt(2); affine_expressions_expected(affine_expression_count++) = scaling_factor * (lmi1.evaluator()->F()[0](i, j) + lmi1.evaluator()->F()[1](i, j) * lmi1.variables()(0)); } } for (int i = 0; i < 12; ++i) { EXPECT_PRED2(symbolic::test::ExprEqual, affine_expressions_expected(i).Expand(), affine_expressions(i).Expand()); } MSK_deleteenv(&env); } GTEST_TEST(AddLinearMatrixInequalityConstraint, LMIandPSD) { // Test a program with both LMI and PSD constraints. Some of the variables in // the PSD matrix also show up in LMI. MathematicalProgram prog; auto x = prog.NewContinuousVariables(2); auto X = prog.NewSymmetricContinuousVariables(3); prog.AddPositiveSemidefiniteConstraint(X); std::vector<Eigen::MatrixXd> F; F.push_back( ToSymmetric((Eigen::Matrix3d() << 0, 1, 0, 1, 2, 1, 0, 2, 1).finished())); F.push_back(ToSymmetric( (Eigen::Matrix3d() << 1, -1, 2, 0, 1, 1, 0, 1, -1).finished())); F.push_back(ToSymmetric( (Eigen::Matrix3d() << 2, 0, 1, 0, 2, -1, 0, 2, -1).finished())); auto lmi0 = prog.AddLinearMatrixInequalityConstraint( F, Vector2<symbolic::Variable>(X(0, 1), x(0))); MSKenv_t env; MSK_makeenv(&env, nullptr); MosekSolverProgram dut(prog, env); std::vector<MSKint32t> bar_var_dimension = {3}; MSK_appendbarvars(dut.task(), 1, bar_var_dimension.data()); AppendFreeVariable( dut.task(), dut.decision_variable_to_mosek_nonmatrix_variable().size()); std::unordered_map<Binding<LinearMatrixInequalityConstraint>, MSKint64t> acc_indices; auto rescode = dut.AddLinearMatrixInequalityConstraint(prog, &acc_indices); EXPECT_EQ(rescode, MSK_RES_OK); EXPECT_EQ(acc_indices.size(), 1); EXPECT_EQ(acc_indices.at(lmi0), 0); MSKint64t num_acc; MSK_getnumacc(dut.task(), &num_acc); EXPECT_EQ(num_acc, 1); // An LMI with a 3 x 3 psd matrix has an affine cone constraints of dimension // 6 (the lower triangular part of the psd matrix). MSKint64t accn0; MSK_getaccn(dut.task(), 0, &accn0); EXPECT_EQ(accn0, 6); MSKint64t num_domain; MSK_getnumdomain(dut.task(), &num_domain); EXPECT_EQ(num_domain, 1); // Check domain types. MSKdomaintypee domain_type; MSK_getdomaintype(dut.task(), 0, &domain_type); EXPECT_EQ(domain_type, MSK_DOMAIN_SVEC_PSD_CONE); // Check the affine cone expression. const VectorX<symbolic::Expression> affine_expressions = GetAffineExpression(prog, dut, {}); EXPECT_EQ(affine_expressions.rows(), 6); VectorX<symbolic::Expression> affine_expressions_expected(6); int affine_expression_count = 0; for (int j = 0; j < 3; ++j) { for (int i = j; i < 3; ++i) { const double scaling_factor = i == j ? 1.0 : std::sqrt(2); affine_expressions_expected(affine_expression_count++) = scaling_factor * (lmi0.evaluator()->F()[0](i, j) + lmi0.evaluator()->F()[1](i, j) * lmi0.variables()(0) + lmi0.evaluator()->F()[2](i, j) * lmi0.variables()(1)); } } for (int i = 0; i < affine_expressions.rows(); ++i) { EXPECT_PRED2(symbolic::test::ExprEqual, affine_expressions(i).Expand(), affine_expressions_expected(i).Expand()); } MSK_deleteenv(&env); } } // namespace internal } // namespace solvers } // namespace drake int main(int argc, char** argv) { // Ensure that we have the MOSEK license for the entire duration of this test, // so that we do not have to release and re-acquire the license for every // test. auto mosek_license = drake::solvers::MosekSolver::AcquireLicense(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/mathematical_program_test.cc
#include "drake/solvers/mathematical_program.h" #include <algorithm> #include <cstddef> #include <functional> #include <limits> #include <map> #include <memory> #include <set> #include <stdexcept> #include <string> #include <type_traits> #include <utility> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/drake_assert.h" #include "drake/common/drake_copyable.h" #include "drake/common/polynomial.h" #include "drake/common/ssize.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/test_utilities/is_dynamic_castable.h" #include "drake/common/test_utilities/symbolic_test_util.h" #include "drake/math/matrix_util.h" #include "drake/solvers/constraint.h" #include "drake/solvers/decision_variable.h" #include "drake/solvers/program_attribute.h" #include "drake/solvers/snopt_solver.h" #include "drake/solvers/solve.h" #include "drake/solvers/test/generic_trivial_constraints.h" #include "drake/solvers/test/generic_trivial_costs.h" #include "drake/solvers/test/mathematical_program_test_util.h" using Eigen::Dynamic; using Eigen::Matrix; using Eigen::Matrix2d; using Eigen::Matrix3d; using Eigen::Matrix4d; using Eigen::MatrixXd; using Eigen::Ref; using Eigen::Vector2d; using Eigen::Vector3d; using Eigen::Vector4d; using Eigen::VectorXd; using drake::Vector1d; using drake::solvers::internal::VecIn; using drake::solvers::internal::VecOut; using drake::symbolic::Expression; using drake::symbolic::Formula; using drake::symbolic::Variable; using drake::symbolic::test::ExprEqual; using drake::symbolic::test::PolyEqual; using drake::symbolic::test::PolyNotEqual; using drake::symbolic::test::TupleVarEqual; using std::all_of; using std::cref; using std::endl; using std::is_permutation; using std::is_same_v; using std::make_shared; using std::map; using std::numeric_limits; using std::pair; using std::runtime_error; using std::set; using std::shared_ptr; using std::static_pointer_cast; using std::string; using std::unique_ptr; using std::vector; namespace drake { namespace solvers { namespace test { namespace { constexpr double kNaN = std::numeric_limits<double>::quiet_NaN(); constexpr double kInf = std::numeric_limits<double>::infinity(); } // namespace struct Movable { Movable() = default; Movable(Movable&&) = default; Movable(Movable const&) = delete; static size_t numInputs() { return 1; } static size_t numOutputs() { return 1; } template <typename ScalarType> void eval(VecIn<ScalarType> const&, VecOut<ScalarType>*) const {} }; struct Copyable { Copyable() = default; Copyable(Copyable&&) = delete; Copyable(Copyable const&) = default; static size_t numInputs() { return 1; } static size_t numOutputs() { return 1; } template <typename ScalarType> void eval(VecIn<ScalarType> const&, VecOut<ScalarType>*) const {} }; struct Unique { Unique() = default; Unique(Unique&&) = delete; Unique(Unique const&) = delete; static size_t numInputs() { return 1; } static size_t numOutputs() { return 1; } template <typename ScalarType> void eval(VecIn<ScalarType> const&, VecOut<ScalarType>*) const {} }; // Check the index, type and name etc of the newly added variables. // This function only works if the only variables contained in @p prog are @p // var. template <typename ExpectedType, typename T> void CheckAddedVariable(const MathematicalProgram& prog, const T& var, int rows, int cols, const string& var_name, bool is_symmetric, MathematicalProgram::VarType type_expected) { static_assert(is_same_v<T, ExpectedType>, "Type not match"); EXPECT_EQ(var.rows(), rows); EXPECT_EQ(var.cols(), cols); // Checks the name of the newly added variables. EXPECT_EQ(fmt::to_string(fmt_eigen(var)), var_name); // Checks num_vars() function. const int num_new_vars = is_symmetric ? var.rows() * (var.rows() + 1) / 2 : var.size(); EXPECT_EQ(prog.num_vars(), num_new_vars); // Checks if the newly added variable is symmetric. EXPECT_EQ(math::IsSymmetric(var), is_symmetric); // Checks the indices of the newly added variables. if (is_symmetric) { int var_count = 0; for (int j = 0; j < var.cols(); ++j) { for (int i = j; i < var.rows(); ++i) { EXPECT_EQ(prog.FindDecisionVariableIndex(var(i, j)), var_count); ++var_count; } } } else { for (int i = 0; i < var.rows(); ++i) { for (int j = 0; j < var.cols(); ++j) { EXPECT_EQ(prog.FindDecisionVariableIndex(var(i, j)), j * var.rows() + i); } } } // Checks the type of the newly added variables. for (int i = 0; i < var.rows(); ++i) { for (int j = 0; j < var.cols(); ++j) { EXPECT_EQ(var(i, j).get_type(), type_expected); } } } template <typename Derived> void CheckAddedIndeterminates(const MathematicalProgram& prog, const Eigen::MatrixBase<Derived>& indeterminates, const string& indeterminates_name) { // Checks the name of the newly added indeterminates. EXPECT_EQ(fmt::to_string(fmt_eigen(indeterminates)), indeterminates_name); // Checks num_indeterminates() function. const int num_new_indeterminates = indeterminates.size(); EXPECT_EQ(prog.num_indeterminates(), num_new_indeterminates); // Checks the indices of the newly added indeterminates. for (int i = 0; i < indeterminates.rows(); ++i) { for (int j = 0; j < indeterminates.cols(); ++j) { EXPECT_EQ(prog.FindIndeterminateIndex(indeterminates(i, j)), j * indeterminates.rows() + i); } } // Checks if the indeterminate is of type // MathematicalProgram::VarType::CONTINUOUS variable (by default). This test // should always be true (by defaults), but keep it to make sure everything // works as it is supposed to be. for (int i = 0; i < indeterminates.rows(); ++i) { for (int j = 0; j < indeterminates.cols(); ++j) { EXPECT_EQ(indeterminates(i, j).get_type(), MathematicalProgram::VarType::CONTINUOUS); } } } GTEST_TEST(TestMathematicalProgram, TestConstructor) { MathematicalProgram prog; EXPECT_EQ(prog.initial_guess().rows(), 0); EXPECT_EQ(prog.num_vars(), 0); } GTEST_TEST(TestAddVariable, TestAddContinuousVariables1) { // Adds a dynamic-sized matrix of continuous variables. MathematicalProgram prog; auto X = prog.NewContinuousVariables(2, 3, "X"); CheckAddedVariable<MatrixXDecisionVariable>( prog, X, 2, 3, "X(0,0) X(0,1) X(0,2)\nX(1,0) X(1,1) X(1,2)", false, MathematicalProgram::VarType::CONTINUOUS); } GTEST_TEST(TestAddVariable, TestAddContinuousVariable2) { // Adds a static-sized matrix of continuous variables. MathematicalProgram prog; auto X = prog.NewContinuousVariables<2, 3>("X"); CheckAddedVariable<MatrixDecisionVariable<2, 3>>( prog, X, 2, 3, "X(0,0) X(0,1) X(0,2)\nX(1,0) X(1,1) X(1,2)", false, MathematicalProgram::VarType::CONTINUOUS); } GTEST_TEST(TestAddVariable, TestAddContinuousVariable3) { // Adds a dynamic-sized vector of continuous variables. MathematicalProgram prog; auto x = prog.NewContinuousVariables(4, "x"); CheckAddedVariable<VectorXDecisionVariable>( prog, x, 4, 1, "x(0)\nx(1)\nx(2)\nx(3)", false, MathematicalProgram::VarType::CONTINUOUS); } GTEST_TEST(TestAddVariable, TestAddContinuousVariable4) { // Adds a static-sized vector of continuous variables. MathematicalProgram prog; auto x = prog.NewContinuousVariables<4>("y"); CheckAddedVariable<VectorDecisionVariable<4>>( prog, x, 4, 1, "y(0)\ny(1)\ny(2)\ny(3)", false, MathematicalProgram::VarType::CONTINUOUS); } GTEST_TEST(TestAddVariable, TestAddContinuousVariable5) { // Adds a static-sized matrix of continuous variables. MathematicalProgram prog; auto X = prog.NewContinuousVariables<2, 3>(2, 3, "Y"); CheckAddedVariable<MatrixDecisionVariable<2, 3>>( prog, X, 2, 3, "Y(0,0) Y(0,1) Y(0,2)\nY(1,0) Y(1,1) Y(1,2)", false, MathematicalProgram::VarType::CONTINUOUS); } GTEST_TEST(TestAddVariable, TestAddContinuousVariables6) { // Adds a dynamic-sized matrix of continuous variables. MathematicalProgram prog; auto X = prog.NewContinuousVariables<Eigen::Dynamic, Eigen::Dynamic>(2, 3, "Y"); CheckAddedVariable<MatrixXDecisionVariable>( prog, X, 2, 3, "Y(0,0) Y(0,1) Y(0,2)\nY(1,0) Y(1,1) Y(1,2)", false, MathematicalProgram::VarType::CONTINUOUS); } GTEST_TEST(TestAddVariable, TestAddContinuousVariables7) { // Adds a dynamic-sized matrix of continuous variables. MathematicalProgram prog; auto X = prog.NewContinuousVariables<2, Eigen::Dynamic>(2, 3, "Y"); CheckAddedVariable<MatrixDecisionVariable<2, Eigen::Dynamic>>( prog, X, 2, 3, "Y(0,0) Y(0,1) Y(0,2)\nY(1,0) Y(1,1) Y(1,2)", false, MathematicalProgram::VarType::CONTINUOUS); } GTEST_TEST(TestAddVariable, TestAddContinuousVariables8) { // Adds a dynamic-sized matrix of continuous variables. MathematicalProgram prog; auto X = prog.NewContinuousVariables<Eigen::Dynamic, 3>(2, 3, "Y"); CheckAddedVariable<MatrixDecisionVariable<Eigen::Dynamic, 3>>( prog, X, 2, 3, "Y(0,0) Y(0,1) Y(0,2)\nY(1,0) Y(1,1) Y(1,2)", false, MathematicalProgram::VarType::CONTINUOUS); } GTEST_TEST(TestAddVariable, TestAddContinuousVariables9) { // Adds continuous variables with default variable name. const std::string X_names = "X(0,0) X(0,1) X(0,2)\nX(1,0) X(1,1) X(1,2)"; MathematicalProgram prog1; auto X1 = prog1.NewContinuousVariables(2, 3); CheckAddedVariable<MatrixXDecisionVariable>( prog1, X1, 2, 3, X_names, false, MathematicalProgram::VarType::CONTINUOUS); MathematicalProgram prog2; auto X2 = prog2.NewContinuousVariables<Eigen::Dynamic, 3>(2, 3); CheckAddedVariable<MatrixDecisionVariable<Eigen::Dynamic, 3>>( prog2, X2, 2, 3, X_names, false, MathematicalProgram::VarType::CONTINUOUS); MathematicalProgram prog3; auto X3 = prog3.NewContinuousVariables<2, 3>(2, 3); CheckAddedVariable<MatrixDecisionVariable<2, 3>>( prog3, X3, 2, 3, X_names, false, MathematicalProgram::VarType::CONTINUOUS); } GTEST_TEST(TestAddVariable, TestAddSymmetricVariable1) { // Adds a static-sized symmetric matrix of continuous variables. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>("X"); CheckAddedVariable<MatrixDecisionVariable<3, 3>>( prog, X, 3, 3, "X(0,0) X(1,0) X(2,0)\nX(1,0) X(1,1) X(2,1)\nX(2,0) X(2,1) X(2,2)", true, MathematicalProgram::VarType::CONTINUOUS); } GTEST_TEST(TestAddVariable, TestAddSymmetricVariable2) { // Adds a dynamic-sized symmetric matrix of continuous variables. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables(3, "X"); CheckAddedVariable<MatrixXDecisionVariable>( prog, X, 3, 3, "X(0,0) X(1,0) X(2,0)\nX(1,0) X(1,1) X(2,1)\nX(2,0) X(2,1) X(2,2)", true, MathematicalProgram::VarType::CONTINUOUS); } GTEST_TEST(TestAddVariable, TestAddBinaryVariable1) { // Adds a dynamic-sized matrix of binary variables. MathematicalProgram prog; auto X = prog.NewBinaryVariables(2, 3, "B"); CheckAddedVariable<MatrixXDecisionVariable>( prog, X, 2, 3, "B(0,0) B(0,1) B(0,2)\nB(1,0) B(1,1) B(1,2)", false, MathematicalProgram::VarType::BINARY); } GTEST_TEST(TestAddVariable, TestAddBinaryVariable2) { // Adds a dynamic-sized matrix of binary variables. MathematicalProgram prog; auto X = prog.NewBinaryVariables<Eigen::Dynamic, Eigen::Dynamic>(2, 3, "B"); CheckAddedVariable<MatrixXDecisionVariable>( prog, X, 2, 3, "B(0,0) B(0,1) B(0,2)\nB(1,0) B(1,1) B(1,2)", false, MathematicalProgram::VarType::BINARY); } GTEST_TEST(TestAddVariable, TestAddBinaryVariable3) { // Adds dynamic-sized vector of binary variables. MathematicalProgram prog; auto X = prog.NewBinaryVariables(4, "B"); CheckAddedVariable<VectorXDecisionVariable>( prog, X, 4, 1, "B(0)\nB(1)\nB(2)\nB(3)", false, MathematicalProgram::VarType::BINARY); } GTEST_TEST(TestAddVariable, TestAddBinaryVariable4) { // Adds static-sized vector of binary variables. MathematicalProgram prog; auto X = prog.NewBinaryVariables<4>("B"); CheckAddedVariable<VectorDecisionVariable<4>>( prog, X, 4, 1, "B(0)\nB(1)\nB(2)\nB(3)", false, MathematicalProgram::VarType::BINARY); } GTEST_TEST(TestAddVariable, TestAddBinaryVariable5) { // Adds a static-sized matrix of binary variables. MathematicalProgram prog; auto X = prog.NewBinaryVariables<2, 3>("B"); CheckAddedVariable<MatrixDecisionVariable<2, 3>>( prog, X, 2, 3, "B(0,0) B(0,1) B(0,2)\nB(1,0) B(1,1) B(1,2)", false, MathematicalProgram::VarType::BINARY); } GTEST_TEST(TestAddVariable, TestAddBinaryVariable6) { // Adds a static-sized matrix of binary variables. MathematicalProgram prog; auto X = prog.NewBinaryVariables<2, 3>(2, 3, "B"); CheckAddedVariable<MatrixDecisionVariable<2, 3>>( prog, X, 2, 3, "B(0,0) B(0,1) B(0,2)\nB(1,0) B(1,1) B(1,2)", false, MathematicalProgram::VarType::BINARY); } GTEST_TEST(TestAddVariable, TestAddBinaryVariable7) { // Adds a dynamic-sized matrix of binary variables. MathematicalProgram prog; auto X = prog.NewBinaryVariables<2, Eigen::Dynamic>(2, 3, "B"); CheckAddedVariable<MatrixDecisionVariable<2, Eigen::Dynamic>>( prog, X, 2, 3, "B(0,0) B(0,1) B(0,2)\nB(1,0) B(1,1) B(1,2)", false, MathematicalProgram::VarType::BINARY); } GTEST_TEST(TestAddVariable, TestAddBinaryVariable8) { // Adds a dynamic-sized matrix of binary variables. MathematicalProgram prog; auto X = prog.NewBinaryVariables<Eigen::Dynamic, 3>(2, 3, "B"); CheckAddedVariable<MatrixDecisionVariable<Eigen::Dynamic, 3>>( prog, X, 2, 3, "B(0,0) B(0,1) B(0,2)\nB(1,0) B(1,1) B(1,2)", false, MathematicalProgram::VarType::BINARY); } GTEST_TEST(TestAddDecisionVariables, AddDecisionVariables1) { // Call AddVariable on an empty program. MathematicalProgram prog; const Variable x0("x0", Variable::Type::CONTINUOUS); const Variable x1("x1", Variable::Type::CONTINUOUS); const Variable x2("x2", Variable::Type::BINARY); prog.AddDecisionVariables(VectorDecisionVariable<3>(x0, x1, x2)); EXPECT_EQ(prog.num_vars(), 3); EXPECT_EQ(prog.FindDecisionVariableIndex(x0), 0); EXPECT_EQ(prog.FindDecisionVariableIndex(x1), 1); EXPECT_EQ(prog.FindDecisionVariableIndex(x2), 2); EXPECT_EQ(prog.initial_guess().rows(), 3); EXPECT_EQ(prog.decision_variables().rows(), 3); EXPECT_TRUE( prog.required_capabilities().contains(ProgramAttribute::kBinaryVariable)); const auto decision_variable_index = prog.decision_variable_index(); { const auto it = decision_variable_index.find(x0.get_id()); ASSERT_TRUE(it != decision_variable_index.end()); EXPECT_EQ(it->second, prog.FindDecisionVariableIndex(x0)); } { const auto it = decision_variable_index.find(x1.get_id()); ASSERT_TRUE(it != decision_variable_index.end()); EXPECT_EQ(it->second, prog.FindDecisionVariableIndex(x1)); } { const auto it = decision_variable_index.find(x2.get_id()); ASSERT_TRUE(it != decision_variable_index.end()); EXPECT_EQ(it->second, prog.FindDecisionVariableIndex(x2)); } } GTEST_TEST(TestAddDecisionVariables, AddVariable2) { // Call AddDecisionVariables on a program that has some existing variables. MathematicalProgram prog; auto y = prog.NewContinuousVariables<3>("y"); const Variable x0("x0", Variable::Type::CONTINUOUS); const Variable x1("x1", Variable::Type::CONTINUOUS); const Variable x2("x2", Variable::Type::BINARY); prog.AddDecisionVariables(VectorDecisionVariable<3>(x0, x1, x2)); EXPECT_EQ(prog.num_vars(), 6); EXPECT_EQ(prog.num_indeterminates(), 0); EXPECT_EQ(prog.FindDecisionVariableIndex(x0), 3); EXPECT_EQ(prog.FindDecisionVariableIndex(x1), 4); EXPECT_EQ(prog.FindDecisionVariableIndex(x2), 5); EXPECT_EQ(prog.initial_guess().rows(), 6); } GTEST_TEST(TestAddDecisionVariables, AddVariable3) { // Call AddDecisionVariables on a program that has some existing variables. // and the new variable overlap with the old variables. MathematicalProgram prog; auto y = prog.NewContinuousVariables<3>("y"); const Variable x0("x0", Variable::Type::CONTINUOUS); const Variable x1("x1", Variable::Type::CONTINUOUS); prog.AddDecisionVariables(VectorDecisionVariable<3>(x0, y(1), x1)); EXPECT_EQ(prog.num_vars(), 5); EXPECT_EQ(prog.num_indeterminates(), 0); EXPECT_EQ(prog.FindDecisionVariableIndex(x0), 3); EXPECT_EQ(prog.FindDecisionVariableIndex(x1), 4); EXPECT_EQ(prog.initial_guess().rows(), 5); } GTEST_TEST(TestAddDecisionVariables, AddVariableError) { // Test the error inputs. MathematicalProgram prog; auto z = prog.NewIndeterminates<2>("z"); // Call AddDecisionVariables on a program that has some indeterminates, and // the new variables intersects with the indeterminates. const Variable x0("x0", Variable::Type::CONTINUOUS); EXPECT_THROW(prog.AddDecisionVariables(VectorDecisionVariable<2>(x0, z(0))), std::runtime_error); // Call AddDecisionVariables with unsupported variable type. for (symbolic::Variable::Type unsupported_type : {symbolic::Variable::Type::BOOLEAN, symbolic::Variable::Type::RANDOM_UNIFORM, symbolic::Variable::Type::RANDOM_GAUSSIAN, symbolic::Variable::Type::RANDOM_EXPONENTIAL}) { const symbolic::Variable unsupported_var("b", unsupported_type); DRAKE_EXPECT_THROWS_MESSAGE( prog.AddDecisionVariables(VectorDecisionVariable<1>(unsupported_var)), "MathematicalProgram does not support .* variables."); } } GTEST_TEST(TestAddDecisionVariables, TestMatrixInput) { // AddDecisionVariables with a matrix of variables instead of a vector. Eigen::Matrix<symbolic::Variable, 2, 3> vars; for (int i = 0; i < vars.rows(); ++i) { for (int j = 0; j < vars.cols(); ++j) { vars(i, j) = symbolic::Variable(fmt::format("x({},{})", i, j)); } } MathematicalProgram prog; prog.NewContinuousVariables<1>(); const int num_existing_decision_vars = prog.num_vars(); prog.AddDecisionVariables(vars); EXPECT_EQ(prog.num_vars(), 6 + num_existing_decision_vars); EXPECT_EQ(prog.GetInitialGuess(vars).rows(), 2); EXPECT_EQ(prog.GetInitialGuess(vars).cols(), 3); EXPECT_TRUE(prog.GetInitialGuess(vars).array().isNaN().all()); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { // Make sure that the variable has been registered in prog. EXPECT_NO_THROW(unused(prog.FindDecisionVariableIndex(vars(i, j)))); } } } GTEST_TEST(NewIndeterminates, DynamicSizeMatrix) { // Adds a dynamic-sized matrix of Indeterminates. MathematicalProgram prog; auto X = prog.NewIndeterminates(2, 3, "X"); static_assert(is_same_v<decltype(X), MatrixXIndeterminate>, "should be a dynamic sized matrix"); EXPECT_EQ(X.rows(), 2); EXPECT_EQ(X.cols(), 3); CheckAddedIndeterminates(prog, X, "X(0,0) X(0,1) X(0,2)\nX(1,0) X(1,1) X(1,2)"); } GTEST_TEST(NewIndeterminates, StaticSizeMatrix) { // Adds a static-sized matrix of Indeterminates. MathematicalProgram prog; auto X = prog.NewIndeterminates<2, 3>("X"); static_assert(is_same_v<decltype(X), MatrixIndeterminate<2, 3>>, "should be a static sized matrix"); CheckAddedIndeterminates(prog, X, "X(0,0) X(0,1) X(0,2)\nX(1,0) X(1,1) X(1,2)"); } GTEST_TEST(NewIndeterminates, DynamicSizeVector) { // Adds a dynamic-sized vector of Indeterminates. MathematicalProgram prog; auto x = prog.NewIndeterminates(4, "x"); static_assert(is_same_v<decltype(x), VectorXIndeterminate>, "Should be a VectorXDecisionVariable object."); EXPECT_EQ(x.rows(), 4); CheckAddedIndeterminates(prog, x, "x(0)\nx(1)\nx(2)\nx(3)"); } GTEST_TEST(NewIndeterminates, StaticSizeVector) { // Adds a static-sized vector of Indeterminate variables. MathematicalProgram prog; auto x = prog.NewIndeterminates<4>("x"); static_assert(is_same_v<decltype(x), VectorIndeterminate<4>>, "Should be a VectorXDecisionVariable object."); CheckAddedIndeterminates(prog, x, "x(0)\nx(1)\nx(2)\nx(3)"); } GTEST_TEST(TestAddIndeterminate, AddIndeterminate1) { // Call AddIndeterminate on an empty program. MathematicalProgram prog; const Variable x("x", Variable::Type::CONTINUOUS); int var_index = prog.AddIndeterminate(x); EXPECT_EQ(prog.indeterminates().rows(), 1); EXPECT_EQ(var_index, 0); EXPECT_TRUE(prog.indeterminates()(0).equal_to(x)); EXPECT_EQ(prog.FindIndeterminateIndex(x), 0); const auto it = prog.indeterminates_index().find(x.get_id()); EXPECT_TRUE(it != prog.indeterminates_index().end()); EXPECT_EQ(it->second, prog.FindIndeterminateIndex(x)); } GTEST_TEST(TestAddIndeterminate, AddIndeterminate2) { // Call AddIndeterminate on a program with some indeterminates MathematicalProgram prog; auto y = prog.NewIndeterminates<2>("y"); const Variable x("x", Variable::Type::CONTINUOUS); int var_index = prog.AddIndeterminate(x); EXPECT_EQ(prog.indeterminates().rows(), 3); EXPECT_EQ(var_index, 2); VectorIndeterminate<3> indeterminates_expected; indeterminates_expected << y(0), y(1), x; for (int i = 0; i < 3; ++i) { EXPECT_TRUE(prog.indeterminates()(i).equal_to(indeterminates_expected(i))); EXPECT_EQ(prog.FindIndeterminateIndex(indeterminates_expected(i)), i); } } GTEST_TEST(TestAddIndeterminate, AddIndeterminate3) { // prog already contains some indeterminates, and we call AddIndeterminate on // an old indeterminate. MathematicalProgram prog; auto y = prog.NewIndeterminates<3>(); auto var_index = prog.AddIndeterminate(y(1)); EXPECT_EQ(var_index, prog.FindIndeterminateIndex(y(1))); EXPECT_EQ(prog.indeterminates().size(), 3); EXPECT_EQ(prog.indeterminates_index().size(), 3); } GTEST_TEST(TestAddIndeterminate, AddIndeterminateError) { // Call with erroneous inputs. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); auto y = prog.NewIndeterminates<2>("y"); const Variable z("z", Variable::Type::BINARY); // Call AddIndeterminate with an input that intersects with old decision // variables. DRAKE_EXPECT_THROWS_MESSAGE(prog.AddIndeterminate(x(0)), ".*is a decision variable.*"); // Call AddIndeterminate with an input of type BINARY. DRAKE_EXPECT_THROWS_MESSAGE(prog.AddIndeterminate(z), ".*should be of type CONTINUOUS.*"); } GTEST_TEST(TestAddIndeterminates, AddIndeterminatesVec1) { // Call AddIndeterminates on an empty program. MathematicalProgram prog; const Variable x0("x0", Variable::Type::CONTINUOUS); const Variable x1("x1", Variable::Type::CONTINUOUS); const Variable x2("x2", Variable::Type::CONTINUOUS); prog.AddIndeterminates(VectorIndeterminate<3>(x0, x1, x2)); const VectorIndeterminate<3> indeterminates_expected(x0, x1, x2); EXPECT_EQ(prog.indeterminates().rows(), 3); const auto indeterminates_index = prog.indeterminates_index(); for (int i = 0; i < 3; ++i) { EXPECT_TRUE(prog.indeterminates()(i).equal_to(indeterminates_expected(i))); EXPECT_EQ(prog.FindIndeterminateIndex(indeterminates_expected(i)), i); const auto it = indeterminates_index.find(indeterminates_expected(i).get_id()); ASSERT_TRUE(it != indeterminates_index.end()); EXPECT_EQ(it->second, prog.FindIndeterminateIndex(indeterminates_expected(i))); } } GTEST_TEST(TestAddIndeterminates, AddIndeterminatesVec2) { // Call AddIndeterminates on a program with some indeterminates. MathematicalProgram prog; auto y = prog.NewIndeterminates<2>("y"); const Variable x0("x0", Variable::Type::CONTINUOUS); const Variable x1("x1", Variable::Type::CONTINUOUS); const Variable x2("x2", Variable::Type::CONTINUOUS); prog.AddIndeterminates(VectorIndeterminate<3>(x0, x1, x2)); VectorIndeterminate<5> indeterminates_expected; indeterminates_expected << y(0), y(1), x0, x1, x2; EXPECT_EQ(prog.indeterminates().rows(), 5); for (int i = 0; i < 5; ++i) { EXPECT_TRUE(prog.indeterminates()(i).equal_to(indeterminates_expected(i))); EXPECT_EQ(prog.FindIndeterminateIndex(indeterminates_expected(i)), i); } } GTEST_TEST(TestAddIndeterminates, AddIndeterminatesVec3) { // The program already constains some indeterminates, call AddIndeterminates() // with some of the old indeterminates. MathematicalProgram prog; auto y = prog.NewIndeterminates<3>(); const symbolic::Variable x0("x0", Variable::Type::CONTINUOUS); prog.AddIndeterminates(Vector2<symbolic::Variable>(y(1), x0)); EXPECT_EQ(prog.indeterminates().size(), 4); EXPECT_EQ(prog.indeterminates_index().size(), 4); EXPECT_EQ(prog.FindIndeterminateIndex(x0), 3); EXPECT_EQ(prog.FindIndeterminateIndex(y(1)), 1); // AddIndeterminates with duplicated variables. const symbolic::Variable x1("x1", Variable::Type::CONTINUOUS); prog.AddIndeterminates(Vector3<symbolic::Variable>(x1, x0, x1)); EXPECT_EQ(prog.indeterminates().size(), 5); EXPECT_EQ(prog.indeterminates_index().size(), 5); EXPECT_EQ(prog.FindIndeterminateIndex(x1), 4); } GTEST_TEST(TestAddIndeterminates, AddIndeterminatesVecError) { // Call with erroneous inputs. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); auto y = prog.NewIndeterminates<2>("y"); const Variable x0("x0", Variable::Type::CONTINUOUS); const Variable x1("x1", Variable::Type::BINARY); // Call AddIndeterminates with an input that intersects with old decision // variables. DRAKE_EXPECT_THROWS_MESSAGE( prog.AddIndeterminates(VectorIndeterminate<2>(x(0), x0)), ".*is a decision variable.*"); // Call AddIndeterminates with an input of type BINARY. DRAKE_EXPECT_THROWS_MESSAGE( prog.AddIndeterminates(VectorIndeterminate<2>(x1, x0)), ".*should be of type CONTINUOUS.*"); } GTEST_TEST(TestAddIndeterminates, AddIndeterminatesVars1) { // Call AddIndeterminates on an empty program. MathematicalProgram prog; const Variable x0("x0", Variable::Type::CONTINUOUS); const Variable x1("x1", Variable::Type::CONTINUOUS); const Variable x2("x2", Variable::Type::CONTINUOUS); prog.AddIndeterminates(symbolic::Variables({x0, x1, x2})); const VectorIndeterminate<3> indeterminates_expected(x0, x1, x2); EXPECT_EQ(prog.indeterminates().rows(), 3); const auto indeterminates_index = prog.indeterminates_index(); for (int i = 0; i < 3; ++i) { // the indeterminate is in the program, but in arbitrary place so we don't // test its index. const auto it = indeterminates_index.find(indeterminates_expected(i).get_id()); ASSERT_TRUE(it != indeterminates_index.end()); EXPECT_EQ(it->second, prog.FindIndeterminateIndex(indeterminates_expected(i))); } } GTEST_TEST(TestAddIndeterminates, AddIndeterminatesVars2) { // Call AddIndeterminates on a program with some indeterminates. MathematicalProgram prog; auto y = prog.NewIndeterminates<2>("y"); const Variable x0("x0", Variable::Type::CONTINUOUS); const Variable x1("x1", Variable::Type::CONTINUOUS); const Variable x2("x2", Variable::Type::CONTINUOUS); prog.AddIndeterminates(symbolic::Variables({x0, x1, x2})); VectorIndeterminate<5> indeterminates_expected; indeterminates_expected << y(0), y(1), x0, x1, x2; EXPECT_EQ(prog.indeterminates().rows(), 5); const auto indeterminates_index = prog.indeterminates_index(); for (int i = 0; i < 5; ++i) { if (i < 3) { // The variables already in the program should be in order. EXPECT_TRUE( prog.indeterminates()(i).equal_to(indeterminates_expected(i))); EXPECT_EQ(prog.FindIndeterminateIndex(indeterminates_expected(i)), i); } else { // The remaining variables were added using an unordered set so we can't // expect an order. const auto it = indeterminates_index.find(indeterminates_expected(i).get_id()); ASSERT_TRUE(it != indeterminates_index.end()); EXPECT_EQ(it->second, prog.FindIndeterminateIndex(indeterminates_expected(i))); } } } GTEST_TEST(TestAddIndeterminates, AddIndeterminatesVars3) { // Call AddIndeterminates that overlaps with the old indeterminates. MathematicalProgram prog; auto y = prog.NewIndeterminates<3>(); const Variable x0("x0", Variable::Type::CONTINUOUS); const Variable x1("x1", Variable::Type::CONTINUOUS); const symbolic::Variables var_set{{x0, x1, y(1)}}; prog.AddIndeterminates(var_set); EXPECT_EQ(prog.num_indeterminates(), 5); EXPECT_EQ(prog.indeterminates().size(), 5); EXPECT_EQ(prog.indeterminates_index().size(), 5); EXPECT_GT(prog.FindIndeterminateIndex(x0), 2); EXPECT_GT(prog.FindIndeterminateIndex(x1), 2); } GTEST_TEST(TestAddIndeterminates, AddIndeterminatesVarsError) { // Call with erroneous inputs. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); auto y = prog.NewIndeterminates<2>("y"); const Variable x0("x0", Variable::Type::CONTINUOUS); const Variable x1("x1", Variable::Type::BINARY); // Call AddIndeterminates with an input that intersects with old decision // variables. DRAKE_EXPECT_THROWS_MESSAGE( prog.AddIndeterminates(symbolic::Variables({x0, x(0)})), ".*is a decision variable.*"); // Call AddIndeterminates with an input of type BINARY. DRAKE_EXPECT_THROWS_MESSAGE( prog.AddIndeterminates(symbolic::Variables({x0, x1})), ".*should be of type CONTINUOUS.*"); } GTEST_TEST(TestAddIndeterminates, MatrixInput) { Eigen::Matrix<symbolic::Variable, 2, 3, Eigen::RowMajor> vars; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { vars(i, j) = symbolic::Variable(fmt::format("x({},{})", i, j)); } } MathematicalProgram prog; prog.NewIndeterminates<2>(); const int num_existing_indeterminates = prog.num_indeterminates(); prog.AddIndeterminates(vars); EXPECT_EQ(prog.num_indeterminates(), num_existing_indeterminates + 6); EXPECT_EQ(prog.num_vars(), 0); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { EXPECT_NO_THROW(unused(prog.FindIndeterminateIndex(vars(i, j)))); } } } namespace { // Overloads to permit `ExpectBadVar` call `AddItem` for both `Cost` and // `Constraint`. void AddItem(MathematicalProgram* prog, const Binding<Constraint>& binding) { prog->AddConstraint(binding); } void AddItem(MathematicalProgram* prog, const Binding<Cost>& binding) { prog->AddCost(binding); } // Expect that adding a given constraint with bad variables (those that have // not been added to MathematicalProgram) will throw an exception. template <typename C, typename... Args> void ExpectBadVar(MathematicalProgram* prog, int num_var, Args&&... args) { using internal::CreateBinding; auto c = make_shared<C>(std::forward<Args>(args)...); VectorXDecisionVariable x(num_var); for (int i = 0; i < num_var; ++i) x(i) = Variable("bad" + std::to_string(i)); // Use minimal call site (directly on adding Binding<C>). // TODO(eric.cousineau): Check if there is a way to parse the error text to // ensure that we are capturing the correct error. DRAKE_EXPECT_THROWS_MESSAGE(AddItem(prog, CreateBinding(c, x)), ".*is not a decision variable.*"); } // Returns True if all the elements of the matrix m1 and m2 are EqualTo as // Expressions. bool MatrixExprAllEqual(const MatrixX<Expression>& m1, const MatrixX<Expression>& m2) { return m1 .binaryExpr(m2, [](const Expression& u, const Expression& v) { return u.EqualTo(v); }) .all(); } } // namespace GTEST_TEST(TestMathematicalProgram, TestMakePolynomial) { MathematicalProgram prog; const auto x = prog.NewIndeterminates<2>("x"); const auto a = prog.NewContinuousVariables<2>("a"); // A decision variable that does not belong // to this mathematical program. const symbolic::Variable b{"b"}; // e = a₀x₀ + (a₁ + b)x₀x₁ + (a₁b). const Expression e{a(0) * x(0) + (a(1) + b) * x(0) * x(1) + (a(1) * b)}; const symbolic::Polynomial p{prog.MakePolynomial(e)}; // We check the constructed polynomial has the following internal mapping. // x₀ ↦ a₀ // x₀x₁ ↦ (a₁ + b) // 1 ↦ a₁b const auto& coeff_map = p.monomial_to_coefficient_map(); EXPECT_EQ(coeff_map.size(), 3); const symbolic::Monomial x0{x(0)}; const symbolic::Monomial x0x1{{{x(0), 1}, {x(1), 1}}}; const symbolic::Monomial one; EXPECT_PRED2(ExprEqual, coeff_map.at(x0), a(0)); EXPECT_PRED2(ExprEqual, coeff_map.at(x0x1), a(1) + b); EXPECT_PRED2(ExprEqual, coeff_map.at(one), a(1) * b); } GTEST_TEST(TestMathematicalProgram, TestBadBindingVariable) { // Attempt to add a binding that does not have a valid decision variable. MathematicalProgram prog; const int num_var = 3; Eigen::Matrix3d A; A.setIdentity(); Eigen::Vector3d f, lb, ub; f.setConstant(2); lb.setConstant(0); ub.setConstant(1); vector<MatrixXd> F{A, 2 * A}; shared_ptr<EvaluatorBase> func = MakeFunctionEvaluator(Movable()); // Test each constraint type. ExpectBadVar<LinearConstraint>(&prog, num_var, A, lb, ub); ExpectBadVar<LinearEqualityConstraint>(&prog, num_var, A, lb); ExpectBadVar<BoundingBoxConstraint>(&prog, num_var, lb, ub); ExpectBadVar<LorentzConeConstraint>(&prog, num_var, A, f); ExpectBadVar<RotatedLorentzConeConstraint>(&prog, num_var, A, f); ExpectBadVar<PositiveSemidefiniteConstraint>(&prog, num_var * num_var, num_var); ExpectBadVar<LinearMatrixInequalityConstraint>(&prog, F.size() - 1, F); ExpectBadVar<ExponentialConeConstraint>( &prog, num_var, Eigen::MatrixXd::Ones(3, num_var).sparseView(), Eigen::Vector3d::Zero()); ExpectBadVar<LinearComplementarityConstraint>(&prog, num_var, A, f); // Use this as a test for nonlinear constraints. ExpectBadVar<EvaluatorConstraint<>>(&prog, 1, func, lb.head(1), ub.head(1)); // Test each cost type. ExpectBadVar<LinearCost>(&prog, num_var, f); ExpectBadVar<QuadraticCost>(&prog, num_var, A, f); ExpectBadVar<EvaluatorCost<>>(&prog, 1, func); } GTEST_TEST(TestMathematicalProgram, TestAddFunction) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<1>(); Movable movable; prog.AddCost(std::move(movable), x); prog.AddCost(Movable(), x); Copyable copyable; prog.AddCost(copyable, x); Unique unique; prog.AddCost(cref(unique), x); prog.AddCost(make_shared<Unique>(), x); prog.AddCost(unique_ptr<Unique>(new Unique), x); } GTEST_TEST(TestMathematicalProgram, BoundingBoxTest2) { // Test the scalar version of the bounding box constraint methods. MathematicalProgram prog; auto x1 = prog.NewContinuousVariables<2, 2>("x1"); MatrixXDecisionVariable x2(2, 2); x2 = x1; VectorDecisionVariable<4> x3; x3 << x1.col(0), x1.col(1); VectorXDecisionVariable x4(4); x4 = x3; // Six different ways to construct an equivalent constraint. // 1. Imposes constraint on a static-sized matrix of decision variables. // 2. Imposes constraint on a list of vectors of decision variables. // 3. Imposes constraint on a dynamic-sized matrix of decision variables. // 4. Imposes constraint on a static-sized vector of decision variables. // 5. Imposes constraint on a dynamic-sized vector of decision variables. // 6. Imposes constraint using a vector of lower/upper bound, as compared // to the previous three cases which use a scalar lower/upper bound. auto constraint1 = prog.AddBoundingBoxConstraint(0, 1, x1).evaluator(); auto constraint2 = prog.AddBoundingBoxConstraint(0, 1, {x1.col(0), x1.col(1)}).evaluator(); auto constraint3 = prog.AddBoundingBoxConstraint(0, 1, x2).evaluator(); auto constraint4 = prog.AddBoundingBoxConstraint(0, 1, x3).evaluator(); auto constraint5 = prog.AddBoundingBoxConstraint(0, 1, x4).evaluator(); auto constraint6 = prog.AddBoundingBoxConstraint(Eigen::Vector4d::Zero(), Eigen::Vector4d::Ones(), x3) .evaluator(); // Checks that the bound variables are correct. for (const auto& binding : prog.bounding_box_constraints()) { EXPECT_EQ(binding.GetNumElements(), 4u); VectorDecisionVariable<4> x_expected; x_expected << x1(0, 0), x1(1, 0), x1(0, 1), x1(1, 1); for (int i = 0; i < 4; ++i) { EXPECT_EQ(binding.variables()(i), x_expected(i)); } } EXPECT_TRUE( CompareMatrices(constraint1->lower_bound(), constraint2->lower_bound())); EXPECT_TRUE( CompareMatrices(constraint2->lower_bound(), constraint3->lower_bound())); EXPECT_TRUE( CompareMatrices(constraint3->lower_bound(), constraint4->lower_bound())); EXPECT_TRUE( CompareMatrices(constraint4->lower_bound(), constraint5->lower_bound())); EXPECT_TRUE( CompareMatrices(constraint5->lower_bound(), constraint6->lower_bound())); EXPECT_TRUE( CompareMatrices(constraint1->upper_bound(), constraint2->upper_bound())); EXPECT_TRUE( CompareMatrices(constraint2->upper_bound(), constraint3->upper_bound())); EXPECT_TRUE( CompareMatrices(constraint3->upper_bound(), constraint4->upper_bound())); EXPECT_TRUE( CompareMatrices(constraint4->upper_bound(), constraint5->upper_bound())); EXPECT_TRUE( CompareMatrices(constraint5->upper_bound(), constraint6->upper_bound())); } GTEST_TEST(TestMathematicalProgram, BoundingBoxTest3) { // The bounds and variables are matrices. MathematicalProgram prog; auto X = prog.NewContinuousVariables(3, 2, "X"); Eigen::MatrixXd X_lo(3, 2); X_lo << 1, 2, 3, 4, 5, 6; // Use a row-major matrix to make sure that our code works for different types // of matrix. Eigen::Matrix<double, 3, 2, Eigen::RowMajor> X_up = (X_lo.array() + 1).matrix(); auto cnstr = prog.AddBoundingBoxConstraint(X_lo, X_up, X); EXPECT_EQ(cnstr.evaluator()->num_constraints(), 6); std::unordered_map<symbolic::Variable, std::pair<double, double>> X_bounds; for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { X_bounds.emplace(X(i, j), std::make_pair(X_lo(i, j), X_up(i, j))); } } for (int i = 0; i < 6; ++i) { EXPECT_EQ(cnstr.evaluator()->lower_bound()(i), X_bounds.at(cnstr.variables()(i)).first); EXPECT_EQ(cnstr.evaluator()->upper_bound()(i), X_bounds.at(cnstr.variables()(i)).second); } // Now add constraint on X.topRows<2>(). It doesn't occupy contiguous memory. auto cnstr2 = prog.AddBoundingBoxConstraint( X_lo.topRows<2>(), X_up.topRows<2>(), X.topRows<2>()); EXPECT_EQ(cnstr2.variables().rows(), 4); X_bounds.clear(); for (int i = 0; i < 2; ++i) { for (int j = 0; j < X.cols(); j++) { X_bounds.emplace(X(i, j), std::make_pair(X_lo(i, j), X_up(i, j))); } } for (int i = 0; i < cnstr2.variables().rows(); ++i) { const auto it = X_bounds.find(cnstr2.variables()(i)); EXPECT_NE(it, X_bounds.end()); EXPECT_EQ(it->second.first, cnstr2.evaluator()->lower_bound()(i)); EXPECT_EQ(it->second.second, cnstr2.evaluator()->upper_bound()(i)); } } // Verifies if the added cost evaluates the same as the original cost. // This function is supposed to test these costs added as a derived class // from Constraint. void VerifyAddedCost1(const MathematicalProgram& prog, const shared_ptr<Cost>& cost, const Eigen::Ref<const Eigen::VectorXd>& x_value, int num_generic_costs_expected) { EXPECT_EQ(static_cast<int>(prog.generic_costs().size()), num_generic_costs_expected); Eigen::VectorXd y, y_expected; prog.generic_costs().back().evaluator()->Eval(x_value, &y); cost->Eval(x_value, &y_expected); EXPECT_TRUE(CompareMatrices(y, y_expected)); } // Verifies if the added cost evaluates the same as the original cost. // This function is supposed to test these costs added by converting // a class to ConstraintImpl through MakeCost. void VerifyAddedCost2(const MathematicalProgram& prog, const GenericTrivialCost2& cost, const shared_ptr<Cost>& returned_cost, const Eigen::Ref<const Eigen::Vector2d>& x_value, int num_generic_costs_expected) { EXPECT_EQ(static_cast<int>(prog.generic_costs().size()), num_generic_costs_expected); Eigen::VectorXd y(1), y_expected(1), y_returned; prog.generic_costs().back().evaluator()->Eval(x_value, &y); cost.eval<double>(x_value, &y_expected); EXPECT_TRUE(CompareMatrices(y, y_expected)); returned_cost->Eval(x_value, &y_returned); EXPECT_TRUE(CompareMatrices(y, y_returned)); } GTEST_TEST(TestMathematicalProgram, AddCostTest) { // Test if the costs are added correctly. // There are ways to add a generic cost // 1. Add Binding<Constraint> // 2. Add shared_ptr<Constraint> on a VectorDecisionVariable object. // 3. Add shared_ptr<Constraint> on a VariableRefList. // 4. Add a ConstraintImpl object on a VectorDecisionVariable object. // 5. Add a ConstraintImpl object on a VariableRefList object. // 6. Add a unique_ptr of object that can be converted to a ConstraintImpl MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); auto y = prog.NewContinuousVariables<2>("y"); // No cost yet. int num_generic_costs = 0; EXPECT_EQ(static_cast<int>(prog.generic_costs().size()), num_generic_costs); EXPECT_EQ(prog.linear_costs().size(), 0u); shared_ptr<Cost> generic_trivial_cost1 = make_shared<GenericTrivialCost1>(); // Adds Binding<Constraint> prog.AddCost(Binding<Cost>(generic_trivial_cost1, VectorDecisionVariable<3>(x(0), x(1), y(1)))); ++num_generic_costs; VerifyAddedCost1(prog, generic_trivial_cost1, Eigen::Vector3d(1, 3, 5), num_generic_costs); // Adds a std::shared_ptr<Constraint> on a VectorDecisionVariable object. prog.AddCost(generic_trivial_cost1, VectorDecisionVariable<3>(x(0), x(1), y(1))); ++num_generic_costs; VerifyAddedCost1(prog, generic_trivial_cost1, Eigen::Vector3d(1, 2, 3), num_generic_costs); // Adds a std::shared_ptr<Constraint> on a VariableRefList object. prog.AddCost(generic_trivial_cost1, {x, y.tail<1>()}); ++num_generic_costs; VerifyAddedCost1(prog, generic_trivial_cost1, Eigen::Vector3d(2, 3, 4), num_generic_costs); GenericTrivialCost2 generic_trivial_cost2; // Add an object that can be converted to a ConstraintImpl object on a // VectorDecisionVariable object. auto returned_cost3 = prog.AddCost(generic_trivial_cost2, VectorDecisionVariable<2>(x(0), y(1))) .evaluator(); ++num_generic_costs; VerifyAddedCost2(prog, generic_trivial_cost2, returned_cost3, Eigen::Vector2d(1, 2), num_generic_costs); // Add an object that can be converted to a ConstraintImpl object on a // VariableRefList object. auto returned_cost4 = prog.AddCost(generic_trivial_cost2, {x.head<1>(), y.tail<1>()}) .evaluator(); ++num_generic_costs; VerifyAddedCost2(prog, generic_trivial_cost2, returned_cost4, Eigen::Vector2d(1, 2), num_generic_costs); } class EmptyConstraint final : public Constraint { public: EmptyConstraint() : Constraint(0, 2, Eigen::VectorXd(0), Eigen::VectorXd(0), "empty_constraint") {} ~EmptyConstraint() {} private: void DoEval(const Eigen::Ref<const Eigen::VectorXd>&, VectorXd*) const {} void DoEval(const Eigen::Ref<const AutoDiffVecXd>&, AutoDiffVecXd*) const {} void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&, VectorX<symbolic::Expression>*) const {} }; GTEST_TEST(TestMathematicalProgram, AddEmptyConstraint) { // MathematicalProgram::AddFooConstraint with empty constraint. solvers::MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto binding1 = prog.AddConstraint(std::make_shared<EmptyConstraint>(), x); EXPECT_TRUE(prog.GetAllConstraints().empty()); EXPECT_EQ(binding1.evaluator()->get_description(), "empty_constraint"); auto binding2 = prog.AddConstraint( std::make_shared<LinearConstraint>( Eigen::MatrixXd(0, 2), Eigen::VectorXd(0), Eigen::VectorXd(0)), x); EXPECT_TRUE(prog.GetAllConstraints().empty()); EXPECT_EQ(binding2.evaluator()->num_constraints(), 0); auto binding3 = prog.AddConstraint(std::make_shared<LinearEqualityConstraint>( Eigen::MatrixXd(0, 2), Eigen::VectorXd(0)), x); EXPECT_TRUE(prog.GetAllConstraints().empty()); EXPECT_EQ(binding3.evaluator()->num_constraints(), 0); auto binding4 = prog.AddConstraint(std::make_shared<BoundingBoxConstraint>( Eigen::VectorXd(0), Eigen::VectorXd(0)), VectorX<symbolic::Variable>(0)); EXPECT_TRUE(prog.GetAllConstraints().empty()); EXPECT_EQ(binding4.evaluator()->num_constraints(), 0); auto binding5 = prog.AddConstraint(std::make_shared<LinearComplementarityConstraint>( Eigen::MatrixXd(0, 0), Eigen::VectorXd(0)), VectorX<symbolic::Variable>(0)); EXPECT_TRUE(prog.GetAllConstraints().empty()); auto binding6 = prog.AddConstraint(internal::CreateBinding( std::make_shared<PositiveSemidefiniteConstraint>(0), VectorXDecisionVariable(0))); EXPECT_TRUE(prog.GetAllConstraints().empty()); auto binding7 = prog.AddConstraint(std::make_shared<LinearMatrixInequalityConstraint>( std::vector<Eigen::MatrixXd>( {Eigen::MatrixXd(0, 0), Eigen::MatrixXd(0, 0), Eigen::MatrixXd(0, 0)})), x); EXPECT_TRUE(prog.GetAllConstraints().empty()); } void CheckAddedSymbolicLinearCostUserFun(const MathematicalProgram& prog, const Expression& e, const Binding<Cost>& binding, int num_linear_costs) { EXPECT_EQ(prog.linear_costs().size(), num_linear_costs); EXPECT_EQ(prog.linear_costs().back().evaluator(), binding.evaluator()); EXPECT_TRUE(CheckStructuralEquality(prog.linear_costs().back().variables(), binding.variables())); EXPECT_EQ(binding.evaluator()->num_outputs(), 1); auto cnstr = prog.linear_costs().back().evaluator(); auto vars = prog.linear_costs().back().variables(); const Expression cx{cnstr->a().dot(vars)}; double constant_term{0}; if (is_addition(e)) { constant_term = get_constant_in_addition(e); } else if (is_constant(e)) { constant_term = get_constant_value(e); } EXPECT_TRUE((e - cx).EqualTo(constant_term)); } void CheckAddedSymbolicLinearCost(MathematicalProgram* prog, const Expression& e) { int num_linear_costs = prog->linear_costs().size(); auto binding1 = prog->AddLinearCost(e); CheckAddedSymbolicLinearCostUserFun(*prog, e, binding1, ++num_linear_costs); auto binding2 = prog->AddCost(e); CheckAddedSymbolicLinearCostUserFun(*prog, e, binding2, ++num_linear_costs); } GTEST_TEST(TestMathematicalProgram, AddLinearCostSymbolic) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); // Add linear cost 2 * x(0) + 3 * x(1) CheckAddedSymbolicLinearCost(&prog, 2 * x(0) + 3 * x(1)); // Add linear cost x(1) CheckAddedSymbolicLinearCost(&prog, +x(1)); // Add linear cost x(0) + 2 CheckAddedSymbolicLinearCost(&prog, x(0) + 2); // Add linear cost 2 * x(0) + 3 * x(1) + 2 CheckAddedSymbolicLinearCost(&prog, 2 * x(0) + 3 * x(1) + 2); // Add linear cost 2 * x(1) CheckAddedSymbolicLinearCost(&prog, 2 * x(1)); // Add linear (constant) cost 3 CheckAddedSymbolicLinearCost(&prog, 3); // Add linear cost -x(0) CheckAddedSymbolicLinearCost(&prog, -x(0)); // Add linear cost -(x(1) + 3 * x(0)) CheckAddedSymbolicLinearCost(&prog, -(x(1) + 3 * x(0))); // Add linear cost x(1)*x(1) + x(0) - x(1)*x(1) CheckAddedSymbolicLinearCost(&prog, x(1) * x(1) + x(0) - x(1) * x(1)); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintMatrixVectorVariablesTest) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(4, "x"); Matrix4d A; // clang-format off A << 1, 2, 3, 4, 5, 6, 7, 8, -9, -10, -11, -12, 13, 14, 15, 16; // clang-format on const Vector4d lb{-10, -11, -12, -13}; const Vector4d ub{3, 7, 11, 17}; const auto binding = prog.AddLinearConstraint(A, lb, ub, x); // Check if the binding includes the correct linear constraint. const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); EXPECT_EQ(constraint_ptr->num_constraints(), 4); const MatrixX<Expression> Ax{(constraint_ptr->GetDenseA() * var_vec)}; const VectorX<Expression> lb_in_constraint{constraint_ptr->lower_bound()}; const VectorX<Expression> ub_in_constraint{constraint_ptr->upper_bound()}; EXPECT_TRUE(MatrixExprAllEqual(A * x - lb, Ax - lb_in_constraint)); EXPECT_TRUE(MatrixExprAllEqual(A * x - ub, Ax - ub_in_constraint)); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintMatrixVariableRefListTest) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(1, "x"); auto y = prog.NewContinuousVariables(3, "y"); VariableRefList vars{x, y}; VectorXDecisionVariable vars_as_vec{ConcatenateVariableRefList(vars)}; Matrix4d A; // clang-format off A << 1, 2, 3, 4, 5, 6, 7, 8, -9, -10, -11, -12, 13, 14, 15, 16; // clang-format on const Vector4d lb{-10, -11, -12, -13}; const Vector4d ub{3, 7, 11, 17}; const auto binding = prog.AddLinearConstraint(A, lb, ub, vars); // Check if the binding includes the correct linear constraint. const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); EXPECT_EQ(constraint_ptr->num_constraints(), 4); const MatrixX<Expression> Ax{(constraint_ptr->GetDenseA() * var_vec)}; const VectorX<Expression> lb_in_constraint{constraint_ptr->lower_bound()}; const VectorX<Expression> ub_in_constraint{constraint_ptr->upper_bound()}; EXPECT_TRUE(MatrixExprAllEqual(A * vars_as_vec - lb, Ax - lb_in_constraint)); EXPECT_TRUE(MatrixExprAllEqual(A * vars_as_vec - ub, Ax - ub_in_constraint)); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSparseMatrixVectorVariablesTest) { MathematicalProgram prog; const int n = 4; auto x = prog.NewContinuousVariables(n, "x"); std::vector<Eigen::Triplet<double>> A_triplet_list; A_triplet_list.reserve(3 * (n - 2) + 4); double count = 1; for (int i = 0; i < n; ++i) { for (int j = std::max(0, i - 1); j < std::min(n, i + 1); ++j) { A_triplet_list.emplace_back(i, j, count); ++count; } } Eigen::SparseMatrix<double> A(n, n); A.setFromTriplets(A_triplet_list.begin(), A_triplet_list.end()); const Vector4d lb{-10, -11, -12, -13}; const Vector4d ub{3, 7, 11, 17}; const auto binding = prog.AddLinearConstraint(A, lb, ub, x); // Check if the binding called the sparse matrix constructor by checking that // a dense A has not been computed yet. EXPECT_FALSE(binding.evaluator()->is_dense_A_constructed()); // Check if the binding includes the correct linear constraint. const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); EXPECT_EQ(constraint_ptr->num_constraints(), 4); const MatrixX<Expression> Ax{(constraint_ptr->GetDenseA() * var_vec)}; const VectorX<Expression> lb_in_constraint{constraint_ptr->lower_bound()}; const VectorX<Expression> ub_in_constraint{constraint_ptr->upper_bound()}; EXPECT_TRUE(MatrixExprAllEqual((A * x - lb), Ax - lb_in_constraint)); EXPECT_TRUE(MatrixExprAllEqual((A * x - ub), Ax - ub_in_constraint)); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSparseMatrixVariableRefListTest) { MathematicalProgram prog; const int n = 4; auto x = prog.NewContinuousVariables(1, "x"); auto y = prog.NewContinuousVariables(n - 1, "y"); VariableRefList vars{x, y}; VectorXDecisionVariable vars_as_vec{ConcatenateVariableRefList(vars)}; std::vector<Eigen::Triplet<double>> A_triplet_list; A_triplet_list.reserve(3 * (n - 2) + 4); double count = 1; for (int i = 0; i < n; ++i) { for (int j = std::max(0, i - 1); j < std::min(n, i + 1); ++j) { A_triplet_list.emplace_back(i, j, count); ++count; } } Eigen::SparseMatrix<double> A(n, n); A.setFromTriplets(A_triplet_list.begin(), A_triplet_list.end()); const Vector4d lb{-10, -11, -12, -13}; const Vector4d ub{3, 7, 11, 17}; const auto binding = prog.AddLinearConstraint(A, lb, ub, vars); // Check if the binding called the sparse matrix constructor by checking that // a dense A has not been computed yet. EXPECT_FALSE(binding.evaluator()->is_dense_A_constructed()); // Check if the binding includes the correct linear constraint. const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); EXPECT_EQ(constraint_ptr->num_constraints(), 4); const MatrixX<Expression> Ax{(constraint_ptr->GetDenseA() * var_vec)}; const VectorX<Expression> lb_in_constraint{constraint_ptr->lower_bound()}; const VectorX<Expression> ub_in_constraint{constraint_ptr->upper_bound()}; EXPECT_TRUE( MatrixExprAllEqual((A * vars_as_vec - lb), Ax - lb_in_constraint)); EXPECT_TRUE( MatrixExprAllEqual((A * vars_as_vec - ub), Ax - ub_in_constraint)); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintRowVectorVectorVariablesTest) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(4, "x"); const Eigen::RowVector4d a{1, 2, 3, 4}; const double lb = -10; const double ub = 3; const auto binding = prog.AddLinearConstraint(a, lb, ub, x); // Check if the binding includes the correct linear constraint. const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); EXPECT_EQ(constraint_ptr->num_constraints(), 1); const MatrixX<Expression> ax{(constraint_ptr->GetDenseA() * var_vec)}; const VectorX<Expression> lb_in_constraint{constraint_ptr->lower_bound()}; const VectorX<Expression> ub_in_constraint{constraint_ptr->upper_bound()}; EXPECT_TRUE((a * x - lb).EqualTo((ax - lb_in_constraint)(0))); EXPECT_TRUE((a * x - ub).EqualTo((ax - ub_in_constraint)(0))); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintRowVectorVariableRefListTest) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(1, "x"); auto y = prog.NewContinuousVariables(3, "y"); VariableRefList vars{x, y}; VectorXDecisionVariable vars_as_vec{ConcatenateVariableRefList(vars)}; const Eigen::RowVector4d a{1, 2, 3, 4}; const double lb = -10; const double ub = 3; const auto binding = prog.AddLinearConstraint(a, lb, ub, vars); // Check if the binding includes the correct linear constraint. const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); EXPECT_EQ(constraint_ptr->num_constraints(), 1); const MatrixX<Expression> ax{(constraint_ptr->GetDenseA() * var_vec)}; const VectorX<Expression> lb_in_constraint{constraint_ptr->lower_bound()}; const VectorX<Expression> ub_in_constraint{constraint_ptr->upper_bound()}; EXPECT_TRUE((a * vars_as_vec - lb).EqualTo((ax - lb_in_constraint)(0))); EXPECT_TRUE((a * vars_as_vec - ub).EqualTo((ax - ub_in_constraint)(0))); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolic1) { // Add linear constraint: -10 <= 3 - 5*x0 + 10*x2 - 7*y1 <= 10 MathematicalProgram prog; auto x = prog.NewContinuousVariables(3, "x"); auto y = prog.NewContinuousVariables(3, "y"); const Expression e{3 - 5 * x(0) + 10 * x(2) - 7 * y(1)}; const double lb{-10}; const double ub{+10}; const auto binding = prog.AddLinearConstraint(e, lb, ub); // Check if the binding includes the correct linear constraint. const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); EXPECT_EQ(constraint_ptr->num_constraints(), 1); const Expression Ax{(constraint_ptr->GetDenseA() * var_vec)(0, 0)}; const Expression lb_in_constraint{constraint_ptr->lower_bound()[0]}; const Expression ub_in_constraint{constraint_ptr->upper_bound()[0]}; EXPECT_TRUE((e - lb).EqualTo(Ax - lb_in_constraint)); EXPECT_TRUE((e - ub).EqualTo(Ax - ub_in_constraint)); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolic2) { // Add linear constraint: -10 <= x0 <= 10 // Note that this constraint is a bounding-box constraint which is a sub-class // of linear-constraint. MathematicalProgram prog; auto x = prog.NewContinuousVariables(3, "x"); const Expression e{x(0)}; const auto binding = prog.AddLinearConstraint(e, -10, 10); // Check that the constraint in the binding is of BoundingBoxConstraint. ASSERT_TRUE(is_dynamic_castable<BoundingBoxConstraint>(binding.evaluator())); const shared_ptr<BoundingBoxConstraint> constraint_ptr{ static_pointer_cast<BoundingBoxConstraint>(binding.evaluator())}; EXPECT_EQ(constraint_ptr->num_constraints(), 1); // Check if the binding includes the correct linear constraint. const VectorXDecisionVariable& var_vec{binding.variables()}; const Expression Ax{(constraint_ptr->GetDenseA() * var_vec)(0, 0)}; const Expression lb_in_constraint{constraint_ptr->lower_bound()[0]}; const Expression ub_in_constraint{constraint_ptr->upper_bound()[0]}; EXPECT_TRUE((e - -10).EqualTo(Ax - lb_in_constraint)); EXPECT_TRUE((e - 10).EqualTo(Ax - ub_in_constraint)); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolic3) { // Add linear constraints // 3 <= 3 - 5*x0 + + 10*x2 - 7*y1 <= 9 // -10 <= x2 <= 10 // -7 <= -5 + 2*x0 + 3*x2 + 3*y0 - 2*y1 + 6*y2 <= 12 // 2 <= 2*x2 <= 3 // 1 <= - y1 <= 3 // // Note: the second, fourth and fifth rows are actually a bounding-box // constraints but we still process the five symbolic-constraints into a // single linear-constraint whose coefficient matrix is the following. // // [-5 0 10 0 -7 0] // [ 0 0 1 0 0 0] // [ 2 3 0 3 -2 6] // [ 0 0 2 0 0 0] // [ 0 0 0 0 -1 0] MathematicalProgram prog; auto x = prog.NewContinuousVariables(3, "x"); auto y = prog.NewContinuousVariables(3, "y"); Matrix<Expression, 5, 1> M_e; Matrix<double, 5, 1> M_lb; Matrix<double, 5, 1> M_ub; // clang-format off M_e << 3 - 5 * x(0) + 10 * x(2) - 7 * y(1), +x(2), -5 + 2 * x(0) + 3 * x(2) + 3 * y(0) - 2 * y(1) + 6 * y(2), 2 * x(2), -y(1); M_lb << 3, -10, -7, 2, 1; M_ub << 9, 10, 12, 3, 3; // clang-format on // Check if the binding includes the correct linear constraint. const auto binding = prog.AddLinearConstraint(M_e, M_lb, M_ub); const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); EXPECT_EQ(constraint_ptr->num_constraints(), 5); const auto Ax = constraint_ptr->GetDenseA() * var_vec; const auto lb_in_constraint = constraint_ptr->lower_bound(); const auto ub_in_constraint = constraint_ptr->upper_bound(); for (int i = 0; i < M_e.size(); ++i) { EXPECT_PRED2(ExprEqual, M_e(i) - M_lb(i), Ax(i) - lb_in_constraint(i)); EXPECT_PRED2(ExprEqual, M_e(i) - M_ub(i), Ax(i) - ub_in_constraint(i)); } } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolic4) { // Check the linear constraint 2 <= 2 * x <= 4. // Note: this is a bounding box constraint MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); const Expression e(2 * x(1)); const auto& binding = prog.AddLinearConstraint(e, 2, 4); EXPECT_TRUE(prog.linear_constraints().empty()); EXPECT_EQ(prog.bounding_box_constraints().size(), 1u); EXPECT_EQ(prog.bounding_box_constraints().back().evaluator(), binding.evaluator()); EXPECT_EQ(prog.bounding_box_constraints().back().variables(), binding.variables()); EXPECT_EQ(binding.variables(), VectorDecisionVariable<1>(x(1))); EXPECT_TRUE(CompareMatrices(binding.evaluator()->lower_bound(), Vector1d(1))); EXPECT_TRUE(CompareMatrices(binding.evaluator()->upper_bound(), Vector1d(2))); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolic5) { // Check the linear constraint 2 <= -2 * x <= 4. // Note: this is a bounding box constraint MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); const Expression e(-2 * x(1)); const auto& binding = prog.AddLinearConstraint(e, 2, 4); EXPECT_TRUE(prog.linear_constraints().empty()); EXPECT_EQ(prog.bounding_box_constraints().size(), 1u); EXPECT_EQ(prog.bounding_box_constraints().back().evaluator(), binding.evaluator()); EXPECT_EQ(prog.bounding_box_constraints().back().variables(), binding.variables()); EXPECT_EQ(binding.variables(), VectorDecisionVariable<1>(x(1))); EXPECT_TRUE( CompareMatrices(binding.evaluator()->lower_bound(), Vector1d(-2))); EXPECT_TRUE( CompareMatrices(binding.evaluator()->upper_bound(), Vector1d(-1))); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolic6) { // Checks the linear constraint 1 <= -x <= 3. // Note: this is a bounding box constraint. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); const Expression e(-x(0)); const auto& binding = prog.AddLinearConstraint(e, 1, 3); EXPECT_TRUE(prog.linear_constraints().empty()); EXPECT_EQ(prog.bounding_box_constraints().size(), 1); EXPECT_EQ(prog.bounding_box_constraints().back().evaluator(), binding.evaluator()); EXPECT_EQ(prog.bounding_box_constraints().back().variables(), binding.variables()); EXPECT_EQ(binding.variables(), VectorDecisionVariable<1>(x(0))); EXPECT_TRUE( CompareMatrices(binding.evaluator()->lower_bound(), Vector1d(-3))); EXPECT_TRUE( CompareMatrices(binding.evaluator()->upper_bound(), Vector1d(-1))); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolic7) { // Checks the linear constraints // 1 <= -2 * x0 <= 3 // 3 <= 4 * x0 + 2<= 5 // 2 <= x1 + 2 * (x2 - 0.5*x1) + 3 <= 4; // 3 <= -4 * x1 + 3 <= inf // Note: these are all bounding box constraints. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); Vector4<Expression> e; // clang-format off e << -2 * x(0), 4 * x(0) + 2, x(1) + 2 * (x(2) - 0.5 * x(1)) + 3, -4 * x(1) + 3; // clang-format on prog.AddLinearConstraint( e, Vector4d(1, 3, 2, 3), Vector4d(3, 5, 4, numeric_limits<double>::infinity())); EXPECT_EQ(prog.bounding_box_constraints().size(), 1); const auto& binding = prog.bounding_box_constraints().back(); EXPECT_EQ(binding.variables(), VectorDecisionVariable<4>(x(0), x(0), x(2), x(1))); EXPECT_TRUE(CompareMatrices( binding.evaluator()->lower_bound(), Vector4d(-1.5, 0.25, -0.5, -numeric_limits<double>::infinity()))); EXPECT_TRUE(CompareMatrices(binding.evaluator()->upper_bound(), Vector4d(-0.5, 0.75, 0.5, 0))); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolic8) { // Test the failure cases for adding linear constraint. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); // Non-polynomial. EXPECT_THROW(prog.AddLinearConstraint(sin(x(0)), 1, 2), runtime_error); // Non-linear. EXPECT_THROW(prog.AddLinearConstraint(x(0) * x(0), 1, 2), runtime_error); // Trivial (and infeasible) case 1 <= 0 <= 2 EXPECT_THROW(prog.AddLinearConstraint(x(0) - x(0), 1, 2), runtime_error); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolic9) { // Test trivial constraint with no variables, such as 1 <= 2 <= 3 MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint(Expression(2), 1, 3); EXPECT_EQ(prog.linear_constraints().size(), 1); auto binding = prog.linear_constraints().back(); EXPECT_EQ(binding.evaluator()->GetDenseA().rows(), 1); EXPECT_EQ(binding.evaluator()->GetDenseA().cols(), 0); Vector2<Expression> expr; expr << 2, x(0); prog.AddLinearConstraint(expr, Vector2d(1, 2), Vector2d(3, 4)); EXPECT_EQ(prog.linear_constraints().size(), 2); binding = prog.linear_constraints().back(); EXPECT_TRUE( CompareMatrices(binding.evaluator()->GetDenseA(), Eigen::Vector2d(0, 1))); EXPECT_TRUE(CompareMatrices(binding.evaluator()->lower_bound(), Eigen::Vector2d(-1, 2))); EXPECT_TRUE(CompareMatrices(binding.evaluator()->upper_bound(), Eigen::Vector2d(1, 4))); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormula1) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); int num_bounding_box_constraint = 0; // x(0) <= 3 vector<Formula> f; f.push_back(x(0) <= 3); f.push_back(3 >= x(0)); f.push_back(x(0) + 2 <= 5); f.push_back(4 + x(0) >= 1 + 2 * x(0)); f.push_back(2 * x(0) + 1 <= 4 + x(0)); f.push_back(3 * x(0) + x(1) <= 6 + x(0) + x(1)); for (const auto& fi : f) { prog.AddLinearConstraint(fi); EXPECT_EQ(++num_bounding_box_constraint, prog.bounding_box_constraints().size()); EXPECT_EQ(prog.linear_constraints().size(), 0); EXPECT_EQ(prog.linear_equality_constraints().size(), 0); auto binding = prog.bounding_box_constraints().back(); EXPECT_EQ(binding.variables(), VectorDecisionVariable<1>(x(0))); EXPECT_TRUE( CompareMatrices(binding.evaluator()->upper_bound(), Vector1d(3))); EXPECT_TRUE(CompareMatrices(binding.evaluator()->lower_bound(), Vector1d(-numeric_limits<double>::infinity()))); } } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormula2) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); int num_bounding_box_constraint = 0; // x0 >= 2 vector<Formula> f; f.push_back(x(0) >= 2); f.push_back(2 <= x(0)); f.push_back(-x(0) <= -2); f.push_back(-2 >= -x(0)); f.push_back(2 + 2 * x(0) >= x(0) + 4); f.push_back(3 + 3 * x(0) >= x(0) + 7); f.push_back(x(0) + 7 + 2 * x(1) <= 3 * x(0) + 3 + 2 * x(1)); for (const auto& fi : f) { prog.AddLinearConstraint(fi); EXPECT_EQ(++num_bounding_box_constraint, prog.bounding_box_constraints().size()); EXPECT_EQ(prog.linear_constraints().size(), 0); EXPECT_EQ(prog.linear_equality_constraints().size(), 0); auto binding = prog.bounding_box_constraints().back(); EXPECT_EQ(binding.variables(), VectorDecisionVariable<1>(x(0))); EXPECT_TRUE( CompareMatrices(binding.evaluator()->lower_bound(), Vector1d(2))); EXPECT_TRUE(CompareMatrices(binding.evaluator()->upper_bound(), Vector1d(numeric_limits<double>::infinity()))); } } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormula3) { // x(0) + x(2) == 1 MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); int num_linear_equality_constraint = 0; vector<Formula> f; f.push_back(x(0) + x(2) == 1); f.push_back(x(0) + 2 * x(2) == 1 + x(2)); for (const auto& fi : f) { prog.AddLinearConstraint(fi); EXPECT_EQ(++num_linear_equality_constraint, prog.linear_equality_constraints().size()); EXPECT_EQ(prog.linear_constraints().size(), 0); EXPECT_EQ(prog.bounding_box_constraints().size(), 0); auto binding = prog.linear_equality_constraints().back(); EXPECT_TRUE( CompareMatrices(binding.evaluator()->lower_bound(), Vector1d(1))); VectorX<Expression> expr = binding.evaluator()->GetDenseA() * binding.variables() - binding.evaluator()->lower_bound(); EXPECT_EQ(expr.size(), 1); EXPECT_PRED2(ExprEqual, expr(0), x(0) + x(2) - 1); } } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormula4) { // x(0) + 2 * x(2) <= 1 MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); int num_linear_constraint = 0; vector<Formula> f; f.push_back(x(0) + 2 * x(2) <= 1); f.push_back(x(0) + 3 * x(2) <= 1 + x(2)); f.push_back(-1 <= -x(0) - 2 * x(2)); f.push_back(-1 - x(2) <= -x(0) - 3 * x(2)); f.push_back(2 * (x(0) + x(2)) - x(0) <= 1); f.push_back(1 >= x(0) + 2 * x(2)); f.push_back(1 + x(2) >= x(0) + 3 * x(2)); f.push_back(-x(0) - 2 * x(2) >= -1); f.push_back(-x(0) - 3 * x(2) >= -1 - x(2)); f.push_back(1 >= 2 * (x(0) + x(2)) - x(0)); for (const auto& fi : f) { prog.AddLinearConstraint(fi); EXPECT_EQ(++num_linear_constraint, prog.linear_constraints().size()); EXPECT_EQ(prog.linear_equality_constraints().size(), 0); EXPECT_EQ(prog.bounding_box_constraints().size(), 0); auto binding = prog.linear_constraints().back(); EXPECT_TRUE(CompareMatrices(binding.evaluator()->lower_bound(), Vector1d(-numeric_limits<double>::infinity()))); EXPECT_TRUE( CompareMatrices(binding.evaluator()->upper_bound(), Vector1d(1))); const VectorX<Expression> expr = binding.evaluator()->upper_bound() - binding.evaluator()->GetDenseA() * binding.variables(); EXPECT_EQ(expr.size(), 1); EXPECT_PRED2(ExprEqual, expr(0), 1 - x(0) - 2 * x(2)); } } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormula5) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<1>(); const double inf = std::numeric_limits<double>::infinity(); // This test checks all of the following formula is translated into the // bounding constraint, x ∈ [-∞, ∞]. // clang-format off const vector<Formula> f{x(0) <= inf, 2 * x(0) <= inf, -3 * x(0) <= inf, 2 * x(0) + 1 <= inf, -7 * x(0) + 1 <= inf, -inf <= x(0), -inf <= 2 * x(0), -inf <= -7 * x(0) + 9}; // clang-format on for (const auto& f_i : f) { const auto binding = prog.AddLinearConstraint(f_i); const VectorX<Expression> expr = binding.evaluator()->GetDenseA() * binding.variables(); EXPECT_EQ(binding.evaluator()->lower_bound()(0), -inf); EXPECT_EQ(binding.evaluator()->upper_bound()(0), inf); EXPECT_PRED2(ExprEqual, expr(0), x(0)); } } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormula6) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>(); const double inf = std::numeric_limits<double>::infinity(); // This test checks that all of the following formula is translated into // linear constraints. // clang-format off const vector<Formula> f{x(0) + x(1) <= inf, 2 * x(0) + x(1) <= inf, -3 * x(0) - 7 * x(1) <= inf}; // clang-format on for (const auto& f_i : f) { const auto binding = prog.AddLinearConstraint(f_i); EXPECT_TRUE(is_dynamic_castable<LinearConstraint>(binding.evaluator())); const VectorX<Expression> expr = binding.evaluator()->GetDenseA() * binding.variables(); EXPECT_EQ(binding.evaluator()->lower_bound()(0), -inf); EXPECT_EQ(binding.evaluator()->upper_bound()(0), inf); EXPECT_PRED2(ExprEqual, expr(0), get_lhs_expression(f_i)); } } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormula7) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>(); const double inf = std::numeric_limits<double>::infinity(); // This test checks that all of the following formula is translated into // linear constraints. // clang-format off const vector<Formula> f{x(0) + x(1) >= -inf, 2 * x(0) + x(1) >= -inf, -3 * x(0) - 7 * x(1) >= -inf}; // clang-format on for (const auto& f_i : f) { const auto binding = prog.AddLinearConstraint(f_i); EXPECT_TRUE(is_dynamic_castable<LinearConstraint>(binding.evaluator())); const VectorX<Expression> expr = binding.evaluator()->GetDenseA() * binding.variables(); EXPECT_EQ(binding.evaluator()->lower_bound()(0), -inf); EXPECT_EQ(binding.evaluator()->upper_bound()(0), inf); EXPECT_PRED2(ExprEqual, expr(0), -get_lhs_expression(f_i)); } } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormulaException1) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>(); const double inf = std::numeric_limits<double>::infinity(); EXPECT_THROW(prog.AddLinearConstraint(x(0) + inf <= x(1)), runtime_error); EXPECT_THROW(prog.AddLinearConstraint(x(0) - inf <= x(1)), runtime_error); EXPECT_THROW(prog.AddLinearConstraint(x(0) <= x(1) + inf), runtime_error); EXPECT_THROW(prog.AddLinearConstraint(x(0) <= x(1) - inf), runtime_error); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormulaException2) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>(); // (x₀ + 1)² - x₀² -2x₀ -1 => 0 (by Expand()). const Expression zero_after_expansion0 = pow(x(0) + 1, 2) - pow(x(0), 2) - 2 * x(0) - 1; // (x₁ + 1)² - x₁² -2x₁ -1 => 0 (by Expand()). const Expression zero_after_expansion1 = pow(x(1) + 1, 2) - pow(x(1), 2) - 2 * x(1) - 1; const double inf = std::numeric_limits<double>::infinity(); // +∞ <= -∞ --> Exception. // +∞ <= +∞ --> Exception. // -∞ <= +∞ --> Exception. // -∞ <= -∞ --> Exception. EXPECT_THROW(prog.AddLinearConstraint(zero_after_expansion0 + inf <= zero_after_expansion1 + -inf), runtime_error); EXPECT_THROW(prog.AddLinearConstraint(zero_after_expansion0 + inf <= zero_after_expansion1 + inf), runtime_error); EXPECT_THROW(prog.AddLinearConstraint(zero_after_expansion0 - inf <= zero_after_expansion1 + inf), runtime_error); EXPECT_THROW(prog.AddLinearConstraint(zero_after_expansion0 - inf <= zero_after_expansion1 - inf), runtime_error); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormulaAnd1) { // Add linear constraints // // (A*x == b) = |1 2| * |x0| == |5| // |3 4| |x1| |6| // // = | x0 + 2*x1 == 5| // |3*x0 + 4*x1 == 6| // // where A = |1 2|, x = |x0|, b = |5| // |3 4| |x1| |6|. // MathematicalProgram prog; auto x = prog.NewContinuousVariables(2, "x"); Matrix<Expression, 2, 2> A; Eigen::Vector2d b; // clang-format off A << 1, 2, 3, 4; b << 5, 6; // clang-format on const auto binding = prog.AddLinearConstraint(A * x == b); const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); // Checks that we have LinearEqualityConstraint instead of LinearConstraint. EXPECT_TRUE(is_dynamic_castable<LinearEqualityConstraint>(constraint_ptr)); EXPECT_EQ(constraint_ptr->num_constraints(), b.size()); const auto Ax = constraint_ptr->GetDenseA() * var_vec; const auto lb_in_constraint = constraint_ptr->lower_bound(); const auto ub_in_constraint = constraint_ptr->upper_bound(); set<Expression> constraint_set; constraint_set.emplace(x(0) + 2 * x(1) - 5); constraint_set.emplace(3 * x(0) + 4 * x(1) - 6); EXPECT_TRUE(constraint_set.contains(Ax(0) - lb_in_constraint(0))); EXPECT_TRUE(constraint_set.contains(Ax(0) - ub_in_constraint(0))); EXPECT_TRUE(constraint_set.contains(Ax(1) - lb_in_constraint(1))); EXPECT_TRUE(constraint_set.contains(Ax(1) - ub_in_constraint(1))); } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormulaAnd2) { // Add linear constraints f1 && f2 && f3 where // f1 := (x0 + 2*x1 >= 3) // f2 := (3*x0 + 4*x1 <= 5) // f3 := (7*x0 + 2*x1 == 9). MathematicalProgram prog; auto x = prog.NewContinuousVariables(2, "x"); const Expression e11{x(0) + 2 * x(1)}; const Expression e12{3}; const Formula f1{e11 >= e12}; const Expression e21{3 * x(0) + 4 * x(1)}; const Expression e22{5}; const Formula f2{e21 <= e22}; const Expression e31{7 * x(0) + 2 * x(1)}; const Expression e32{9}; const Formula f3{e31 == e32}; const auto binding = prog.AddLinearConstraint(f1 && f2 && f3); const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); // Checks that we do not have LinearEqualityConstraint. EXPECT_FALSE(is_dynamic_castable<LinearEqualityConstraint>(constraint_ptr)); EXPECT_EQ(constraint_ptr->num_constraints(), 3); const auto Ax = constraint_ptr->GetDenseA() * var_vec; const auto lb_in_constraint = constraint_ptr->lower_bound(); const auto ub_in_constraint = constraint_ptr->upper_bound(); set<Expression> constraint_set; constraint_set.emplace(e11 - e12); constraint_set.emplace(e21 - e22); constraint_set.emplace(e31 - e32); for (int i = 0; i < 3; ++i) { if (!std::isinf(lb_in_constraint(i))) { // Either `Ax - lb` or `-(Ax - lb)` should be in the constraint set. EXPECT_NE(constraint_set.contains(Ax(i) - lb_in_constraint(i)), constraint_set.contains(-(Ax(i) - lb_in_constraint(i)))); } if (!std::isinf(ub_in_constraint(i))) { // Either `Ax - ub` or `-(Ax - ub)` should be in the constraint set. EXPECT_NE(constraint_set.contains(Ax(i) - ub_in_constraint(i)), constraint_set.contains(-(Ax(i) - ub_in_constraint(i)))); } } } GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicFormulaAndException) { // Add linear constraints: // (x0 + 2*x1 > 3) // (3*x0 + 4*x1 < 5) // (7*x0 + 2*x1 == 9) // // It includes relational formulas with strict inequalities (> and <). It will // throw std::runtime_error. MathematicalProgram prog; auto x = prog.NewContinuousVariables(2, "x"); const Expression e11{x(0) + 2 * x(1)}; const Expression e12{3}; const Formula f1{e11 > e12}; const Expression e21{3 * x(0) + 4 * x(1)}; const Expression e22{5}; const Formula f2{e21 < e22}; const Expression e31{7 * x(0) + 2 * x(1)}; const Expression e32{9}; const Formula f3{e31 == e32}; EXPECT_THROW(prog.AddLinearConstraint(f1 && f2 && f3), runtime_error); } // Checks AddLinearConstraint function which takes an Eigen::Array<Formula>. GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicArrayFormula1) { // Add linear constraints // 3 - 5*x0 + + 10*x2 - 7*y1 >= 3 // x2 >= -10 // -5 + 2*x0 + 3*x1 + 3*y0 - 2*y1 + 6*y2 <= -7 // 2*x2 == 2 // - y1 >= 1 // // Note: the second, fourth and fifth rows are actually a bounding-box // constraints but we still process the five symbolic-constraints into a // single linear-constraint whose coefficient matrix is the following. // // [-5 0 10 0 -7 0] // [ 0 0 1 0 0 0] // [ 2 3 0 3 -2 6] // [ 0 0 2 0 0 0] // [ 0 0 0 0 -1 0] MathematicalProgram prog; auto x = prog.NewContinuousVariables(3, "x"); auto y = prog.NewContinuousVariables(3, "y"); Matrix<Formula, 5, 1> M_f; // clang-format off M_f << (3 - 5 * x(0) + 10 * x(2) - 7 * y(1) >= 3), x(2) >= -10, -5 + 2 * x(0) + 3 * x(1) + 3 * y(0) - 2 * y(1) + 6 * y(2) <= -7, 2 * x(2) == 2, -y(1) >= 1; // clang-format on // Check if the binding includes the correct linear constraint. const auto binding = prog.AddLinearConstraint(M_f.array()); const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); EXPECT_EQ(constraint_ptr->num_constraints(), 5); const auto Ax = constraint_ptr->GetDenseA() * var_vec; const auto lb_in_constraint = constraint_ptr->lower_bound(); const auto ub_in_constraint = constraint_ptr->upper_bound(); for (int i{0}; i < M_f.size(); ++i) { if (!std::isinf(lb_in_constraint(i))) { EXPECT_PRED2(ExprEqual, get_lhs_expression(M_f(i)) - get_rhs_expression(M_f(i)), Ax(i) - lb_in_constraint(i)); } if (!std::isinf(ub_in_constraint(i))) { EXPECT_PRED2(ExprEqual, get_lhs_expression(M_f(i)) - get_rhs_expression(M_f(i)), Ax(i) - ub_in_constraint(i)); } } } // Checks AddLinearConstraint function which takes an Eigen::Array<Formula>. // This test uses operator>= provided for Eigen::Array<Expression> and // Eigen::Array<double>. GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicArrayFormula2) { // Add linear constraints // // M_f = |f1 f2| // |f3 f4| // // where // f1 = 3 - 5*x0 +10*x2 - 7*y1 >= 3 // f2 = x2 >= -10 // f3 = -5 + 2*x0 + 3*x1 + 3*y0 - 2*y1 + 6*y2 >= -7 // f4 = 2*x2 >= 2 MathematicalProgram prog; auto x = prog.NewContinuousVariables(3, "x"); auto y = prog.NewContinuousVariables(3, "y"); Matrix<Expression, 2, 2> M_e; Matrix<double, 2, 2> M_lb; // clang-format off M_e << 3 - 5 * x(0) + 10 * x(2) - 7 * y(1), x(2), -5 + 2 * x(0) + 3 * x(1) + 3 * y(0) - 2 * y(1) + 6 * y(2), 2 * x(2); M_lb << 3, -10, -7, 2; // clang-format on Eigen::Array<Formula, 2, 2> M_f{M_e.array() >= M_lb.array()}; // Check if the binding includes the correct linear constraint. const auto binding = prog.AddLinearConstraint(M_f); const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); EXPECT_EQ(constraint_ptr->num_constraints(), M_e.rows() * M_e.cols()); const auto Ax = constraint_ptr->GetDenseA() * var_vec; const auto lb_in_constraint = constraint_ptr->lower_bound(); const auto ub_in_constraint = constraint_ptr->upper_bound(); int k{0}; for (int j{0}; j < M_e.cols(); ++j) { for (int i{0}; i < M_e.rows(); ++i) { EXPECT_PRED2(ExprEqual, M_e(i, j) - M_lb(i, j), Ax(k) - lb_in_constraint(k)); ++k; } } } // Checks AddLinearConstraint function which takes an Eigen::Array<Formula>. GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicArrayFormula3) { // Add linear constraints // // (A*x >= b) = |1 2| * |x0| >= |5| // |3 4| |x1| |6| // // = | x0 + 2*x1 >= 5| // |3*x0 + 4*x1 >= 6| // // where A = |1 2|, x = |x0|, b = |5| // |3 4| |x1| |6|. // MathematicalProgram prog; auto x = prog.NewContinuousVariables(2, "x"); Matrix<Expression, 2, 2> A; Eigen::Vector2d b; // clang-format off A << 1, 2, 3, 4; b << 5, 6; // clang-format on const auto binding = prog.AddLinearConstraint((A * x).array() >= b.array()); const VectorXDecisionVariable& var_vec{binding.variables()}; const auto constraint_ptr = binding.evaluator(); EXPECT_EQ(constraint_ptr->num_constraints(), b.size()); const auto Ax = constraint_ptr->GetDenseA() * var_vec; const auto lb_in_constraint = constraint_ptr->lower_bound(); const auto ub_in_constraint = constraint_ptr->upper_bound(); EXPECT_PRED2(ExprEqual, x(0) + 2 * x(1) - 5, Ax(0) - lb_in_constraint(0)); EXPECT_PRED2(ExprEqual, 3 * x(0) + 4 * x(1) - 6, Ax(1) - lb_in_constraint(1)); } // Checks AddLinearConstraint function which takes an Eigen::Array<Formula>. GTEST_TEST(TestMathematicalProgram, AddLinearConstraintSymbolicArrayFormulaException) { // Add linear constraints // 3 - 5*x0 + 10*x2 - 7*y1 > 3 // x2 > -10 // Note that this includes strict inequality (>) and results in an exception. MathematicalProgram prog; auto x = prog.NewContinuousVariables(3, "x"); auto y = prog.NewContinuousVariables(3, "y"); Matrix<Formula, 2, 1> M_f; // clang-format off M_f << (3 - 5 * x(0) + 10 * x(2) - 7 * y(1) > 3), x(2) > -10; // clang-format on EXPECT_THROW(prog.AddLinearConstraint(M_f.array()), runtime_error); } namespace { void CheckAddedLinearEqualityConstraintCommon( const Binding<LinearEqualityConstraint>& binding, const MathematicalProgram& prog, int num_linear_eq_cnstr) { // Checks if the number of linear equality constraints get incremented by 1. EXPECT_EQ(prog.linear_equality_constraints().size(), num_linear_eq_cnstr + 1); // Checks if the newly added linear equality constraint in prog is the same as // that returned from AddLinearEqualityConstraint. EXPECT_EQ(prog.linear_equality_constraints().back().evaluator(), binding.evaluator()); // Checks if the bound variables of the newly added linear equality constraint // in prog is the same as that returned from AddLinearEqualityConstraint. EXPECT_EQ(prog.linear_equality_constraints().back().variables(), binding.variables()); } template <typename DerivedV, typename DerivedB> void CheckAddedNonSymmetricSymbolicLinearEqualityConstraint( MathematicalProgram* prog, const Eigen::MatrixBase<DerivedV>& v, const Eigen::MatrixBase<DerivedB>& b) { const int num_linear_eq_cnstr = prog->linear_equality_constraints().size(); auto binding = prog->AddLinearEqualityConstraint(v, b); CheckAddedLinearEqualityConstraintCommon(binding, *prog, num_linear_eq_cnstr); // Checks if the number of rows in the newly added constraint is the same as // the input expression. int num_constraints_expected = v.size(); EXPECT_EQ(binding.evaluator()->num_constraints(), num_constraints_expected); // Check if the newly added linear equality constraint matches with the input // expression. VectorX<Expression> flat_V = binding.evaluator()->GetDenseA() * binding.variables() - binding.evaluator()->lower_bound(); EXPECT_EQ(flat_V.size(), v.size()); MatrixX<Expression> v_resize = flat_V; v_resize.resize(v.rows(), v.cols()); for (int i = 0; i < v.rows(); ++i) { for (int j = 0; j < v.cols(); ++j) { EXPECT_EQ(v_resize(i, j).Expand(), (v(i, j) - b(i, j)).Expand()); } } } template <typename DerivedV, typename DerivedB> void CheckAddedSymmetricSymbolicLinearEqualityConstraint( MathematicalProgram* prog, const Eigen::MatrixBase<DerivedV>& v, const Eigen::MatrixBase<DerivedB>& b) { const int num_linear_eq_cnstr = prog->linear_equality_constraints().size(); auto binding = prog->AddLinearEqualityConstraint(v, b, true); CheckAddedLinearEqualityConstraintCommon(binding, *prog, num_linear_eq_cnstr); // Checks if the number of rows in the newly added constraint is the same as // the input expression. int num_constraints_expected = v.rows() * (v.rows() + 1) / 2; EXPECT_EQ(binding.evaluator()->num_constraints(), num_constraints_expected); // Check if the newly added linear equality constraint matches with the input // expression. VectorX<Expression> flat_V = binding.evaluator()->GetDenseA() * binding.variables() - binding.evaluator()->lower_bound(); EXPECT_EQ(math::ToSymmetricMatrixFromLowerTriangularColumns(flat_V), v - b); } void CheckAddedNonSymmetricSymbolicLinearEqualityConstraint( MathematicalProgram* prog, const Expression& e, double b) { CheckAddedNonSymmetricSymbolicLinearEqualityConstraint( prog, Vector1<Expression>(e), Vector1d(b)); } } // namespace GTEST_TEST(TestMathematicalProgram, AddLinearEqualityConstraintMatrixVectorVariablesTest) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(4, "x"); Matrix4d A; // clang-format off A << 1, 2, 3, 4, 5, 6, 7, 8, -9, -10, -11, -12, 13, 14, 15, 16; // clang-format on const Vector4d b{-10, -11, -12, -13}; const auto binding = prog.AddLinearEqualityConstraint(A, b, x); CheckAddedLinearEqualityConstraintCommon(binding, prog, 0); } GTEST_TEST(TestMathematicalProgram, AddLinearEqualityConstraintMatrixVariableRefListTest) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(1, "x"); auto y = prog.NewContinuousVariables(3, "y"); VariableRefList vars{x, y}; Matrix4d A; // clang-format off A << 1, 2, 3, 4, 5, 6, 7, 8, -9, -10, -11, -12, 13, 14, 15, 16; // clang-format on const Vector4d b{-10, -11, -12, -13}; const auto binding = prog.AddLinearEqualityConstraint(A, b, vars); CheckAddedLinearEqualityConstraintCommon(binding, prog, 0); } GTEST_TEST(TestMathematicalProgram, AddLinearEqualityConstraintSparseMatrixVariableRefListTest) { MathematicalProgram prog; const int n = 4; auto x = prog.NewContinuousVariables(1, "x"); auto y = prog.NewContinuousVariables(3, "y"); VariableRefList vars{x, y}; std::vector<Eigen::Triplet<double>> A_triplet_list; A_triplet_list.reserve(3 * (n - 2) + 4); double count = 1; for (int i = 0; i < n; ++i) { for (int j = std::max(0, i - 1); j < std::min(n, i + 1); ++j) { A_triplet_list.emplace_back(i, j, count); ++count; } } Eigen::SparseMatrix<double> A(n, n); A.setFromTriplets(A_triplet_list.begin(), A_triplet_list.end()); const Vector4d b{-10, -11, -12, -13}; const auto binding = prog.AddLinearEqualityConstraint(A, b, vars); // Check if the binding called the sparse matrix constructor by checking that // a dense A has not been computed yet. EXPECT_FALSE(binding.evaluator()->is_dense_A_constructed()); CheckAddedLinearEqualityConstraintCommon(binding, prog, 0); } GTEST_TEST(TestMathematicalProgram, AddLinearEqualityConstraintSparseMatrixVectorVariablesTest) { MathematicalProgram prog; const int n = 4; auto x = prog.NewContinuousVariables(n, "x"); std::vector<Eigen::Triplet<double>> A_triplet_list; A_triplet_list.reserve(3 * (n - 2) + 4); double count = 1; for (int i = 0; i < n; ++i) { for (int j = std::max(0, i - 1); j < std::min(n, i + 1); ++j) { A_triplet_list.emplace_back(i, j, count); ++count; } } Eigen::SparseMatrix<double> A(n, n); A.setFromTriplets(A_triplet_list.begin(), A_triplet_list.end()); const Vector4d b{-10, -11, -12, -13}; const auto binding = prog.AddLinearEqualityConstraint(A, b, x); // Check if the binding called the sparse matrix constructor by checking that // a dense A has not been computed yet. EXPECT_FALSE(binding.evaluator()->is_dense_A_constructed()); CheckAddedLinearEqualityConstraintCommon(binding, prog, 0); } GTEST_TEST(TestMathematicalProgram, AddLinearEqualityConstraintRowVectorVectorVariablesTest) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(4, "x"); const Eigen::RowVector4d a{1, 2, 3, 4}; const double b = -10; const auto binding = prog.AddLinearEqualityConstraint(a, b, x); CheckAddedLinearEqualityConstraintCommon(binding, prog, 0); } GTEST_TEST(TestMathematicalProgram, AddLinearEqualityConstraintRowVectorVariableRefListTest) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(1, "x"); auto y = prog.NewContinuousVariables(3, "y"); VariableRefList vars{x, y}; VectorXDecisionVariable vars_as_vec{ConcatenateVariableRefList(vars)}; const Eigen::RowVector4d a{1, 2, 3, 4}; const double b = -10; const auto binding = prog.AddLinearEqualityConstraint(a, b, vars); CheckAddedLinearEqualityConstraintCommon(binding, prog, 0); } GTEST_TEST(TestMathematicalProgram, AddSymbolicLinearEqualityConstraint1) { // Checks the single row linear equality constraint one by one: MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>("x"); // Checks x(0) = 1 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, +x(0), 1); // Checks x(1) = 1 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, +x(1), 1); // Checks x(0) + x(1) = 1 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, x(0) + x(1), 1); // Checks x(0) + 2 * x(1) = 1 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, x(0) + 2 * x(1), 1); // Checks 3 * x(0) - 2 * x(1) = 2 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint( &prog, 3 * x(0) - 2 * x(1), 2); // Checks 2 * x(0) = 2 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, 2 * x(0), 2); // Checks x(0) + 3 * x(2) = 3 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, x(0) + 3 * x(2), 3); // Checks 2 * x(1) - 3 * x(2) = 4 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint( &prog, 2 * x(1) - 3 * x(2), 4); // Checks x(0) + 2 = 1 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, x(0) + 2, 1); // Checks x(1) - 2 = 1 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, x(1) - 2, 1); // Checks 3 * x(1) + 4 = 1 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, 3 * x(1) + 4, 1); // Checks x(0) + x(2) + 3 = 1 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, x(0) + x(2) + 3, 1); // Checks 2 * x(0) + x(2) - 3 = 1 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint( &prog, 2 * x(0) + x(2) - 3, 1); // Checks 3 * x(0) + x(1) + 4 * x(2) + 1 = 2 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint( &prog, 3 * x(0) + x(1) + 4 * x(2) + 1, 2); // Checks -x(1) = 3 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, -x(1), 3); // Checks -(x(0) + 2 * x(1)) = 2 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, -(x(0) + 2 * x(1)), 2); CheckAddedNonSymmetricSymbolicLinearEqualityConstraint( &prog, x(0) + 2 * (x(0) + x(2)) + 3 * (x(0) - x(1)), 3); } GTEST_TEST(TestMathematicalProgram, AddSymbolicLinearEqualityConstraint2) { // Checks adding multiple rows of linear equality constraints. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>("x"); // Checks x(1) = 2 // x(0) = 1 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint( &prog, Vector2<Expression>(+x(1), +x(0)), Eigen::Vector2d(2, 1)); // Checks 2 * x(1) = 3 // x(0) + x(2) = 4 // x(0) + 3 * x(1) + 7 = 1 Vector3<Expression> v{}; v << 2 * x(1), x(0) + x(2), x(0) + 3 * x(1) + 7; CheckAddedNonSymmetricSymbolicLinearEqualityConstraint( &prog, v, Eigen::Vector3d(3, 4, 1)); // Checks x(0) = 4 // 1 = 1 // -x(1) = 2 CheckAddedNonSymmetricSymbolicLinearEqualityConstraint( &prog, Vector3<Expression>(+x(0), 1, -x(1)), Eigen::Vector3d(4, 1, 2)); } GTEST_TEST(TestMathematicalProgram, AddSymbolicLinearEqualityConstraint3) { // Checks adding a matrix of linear equality constraints. This matrix is not // symmetric. MathematicalProgram prog; auto X = prog.NewContinuousVariables<2, 2>("X"); // Checks A * X = [1, 2; 3, 4], both A * X and B are static sized. Eigen::Matrix2d A{}; A << 1, 3, 4, 2; Eigen::Matrix2d B{}; B << 1, 2, 3, 4; CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, A * X, B); // Checks A * X = B, with A*X being dynamic sized, and B being static sized. MatrixX<Expression> A_times_X = A * X; CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, A_times_X, B); // Checks A * X = B, with A*X being static sized, and B being dynamic sized. Eigen::MatrixXd B_dynamic = B; CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, A * X, B_dynamic); // Checks A * X = B, with both A*X and B being dynamic sized. CheckAddedNonSymmetricSymbolicLinearEqualityConstraint(&prog, A_times_X, B_dynamic); } GTEST_TEST(TestMathematicalProgram, AddSymbolicLinearEqualityConstraint4) { // Checks adding a symmetric matrix of linear equality constraints. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<2>("X"); Eigen::Matrix2d A{}; A << 1, 3, 4, 2; Eigen::Matrix2d B{}; B << 1, 2, 2, 1; Eigen::MatrixXd B_dynamic = B; Matrix2<Expression> M = A.transpose() * X + X * A; MatrixX<Expression> M_dynamic = M; // Checks Aᵀ * X + X * A = B, both the left and right hand-side are static // sized. CheckAddedSymmetricSymbolicLinearEqualityConstraint(&prog, M, B); // Checks Aᵀ * X + X * A = B, the left hand-side being static sized, while the // right hand-side being dynamic sized. CheckAddedSymmetricSymbolicLinearEqualityConstraint(&prog, M, B_dynamic); // Checks Aᵀ * X + X * A = B, the left hand-side being dynamic sized, while // the // right hand-side being static sized. CheckAddedSymmetricSymbolicLinearEqualityConstraint(&prog, M_dynamic, B); // Checks Aᵀ * X + X * A = B, bot the left and right hand-side are dynamic // sized. CheckAddedSymmetricSymbolicLinearEqualityConstraint(&prog, M_dynamic, B_dynamic); // Checks Aᵀ * X + X * A = E. CheckAddedSymmetricSymbolicLinearEqualityConstraint( &prog, M, Eigen::Matrix2d::Identity()); } // Tests `AddLinearEqualityConstraint(const symbolic::Formula& f)` method with a // case where `f` is a linear-equality formula (instead of a conjunction of // them). GTEST_TEST(TestMathematicalProgram, AddSymbolicLinearEqualityConstraint5) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>("x"); // f = (3x₀ + 2x₁ + 3 == 5). const Formula f{3 * x(0) + 2 * x(1) + 3 == 5}; const Binding<LinearEqualityConstraint> binding{ prog.AddLinearEqualityConstraint(f)}; EXPECT_EQ(prog.linear_equality_constraints().size(), 1u); const Expression expr_in_added_constraint{ (binding.evaluator()->GetDenseA() * binding.variables() - binding.evaluator()->lower_bound())(0)}; // expr_in_added_constraint should be: // lhs(f) - rhs(f) // = (3x₀ + 2x₁ + 3) - 5 // = 3x₀ + 2x₁ - 2. EXPECT_PRED2(ExprEqual, expr_in_added_constraint, 3 * x(0) + 2 * x(1) - 2); EXPECT_PRED2(ExprEqual, expr_in_added_constraint, get_lhs_expression(f) - get_rhs_expression(f)); } // Tests `AddLinearEqualityConstraint(const symbolic::Formula& f)` method with a // case where `f` is a conjunction of linear-equality formulas . GTEST_TEST(TestMathematicalProgram, AddSymbolicLinearEqualityConstraint6) { // Test problem: Ax = b where // // A = |-3.0 0.0 2.0| x = |x0| b = | 9.0| // | 0.0 7.0 -3.0| |x1| | 3.0| // | 2.0 5.0 0.0| |x2| |-5.0| MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>("x"); Eigen::Matrix3d A; Vector3d b; // clang-format off A << -3.0, 0.0, 2.0, 0.0, 7.0, -3.0, 2.0, 5.0, 0.0; b << 9.0, 3.0, -5.0; // clang-format on const Formula f{A * x == b}; const Binding<LinearEqualityConstraint> binding{ prog.AddLinearEqualityConstraint(f)}; EXPECT_EQ(prog.linear_equality_constraints().size(), 1u); // Checks if AddLinearEqualityConstraint added the constraint correctly. const Eigen::Matrix<Expression, 3, 1> exprs_in_added_constraint{ binding.evaluator()->GetDenseA() * binding.variables() - binding.evaluator()->lower_bound()}; const Eigen::Matrix<Expression, 3, 1> expected_exprs{A * x - b}; // Since a conjunctive symbolic formula uses `std::set` as an internal // representation, we need to check if `exprs_in_added_constraint` is a // permutation of `expected_exprs`. EXPECT_TRUE(is_permutation( exprs_in_added_constraint.data(), exprs_in_added_constraint.data() + 3, expected_exprs.data(), expected_exprs.data() + 3, ExprEqual)); } // Checks if `AddLinearEqualityConstraint(f)` throws std::runtime_error if `f` // is a non-linear equality formula. GTEST_TEST(TestMathematicalProgram, AddSymbolicLinearEqualityConstraintException1) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); // f = (3x₀² + 2x₁ + 3 == 5). const Formula f{3 * x(0) * x(0) + 2 * x(1) + 3 == 5}; EXPECT_THROW(prog.AddLinearEqualityConstraint(f), runtime_error); } // Checks if `AddLinearEqualityConstraint(f)` throws std::runtime_error if a // conjunctive formula `f` includes a relational formula other than equality. GTEST_TEST(TestMathematicalProgram, AddSymbolicLinearEqualityConstraintException2) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); // f = (3x₀ + 2x₁ + 3 >= 5 && 7x₀ - 5x₁ == 0). const Formula f{3 * x(0) + 2 * x(1) + 3 >= 5 && 7 * x(0) - 5 * x(1) == 0}; EXPECT_THROW(prog.AddLinearEqualityConstraint(f), runtime_error); } // Checks if `AddLinearEqualityConstraint(f)` throws std::runtime_error if `f` // is neither a linear-equality formula nor a conjunctive formula. GTEST_TEST(TestMathematicalProgram, AddSymbolicLinearEqualityConstraintException3) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); // f = (3x₀ + 2x₁ + 3 == 5 || 7x₀ - 5x₁ == 0). const Formula f{3 * x(0) + 2 * x(1) + 3 == 5 || 7 * x(0) - 5 * x(1) == 0}; EXPECT_THROW(prog.AddLinearEqualityConstraint(f), runtime_error); } namespace { bool AreTwoPolynomialsNear( const symbolic::Polynomial& p1, const symbolic::Polynomial& p2, const double tol = numeric_limits<double>::epsilon()) { symbolic::Polynomial diff{p1 - p2}; const auto& monomial_to_coeff_map = diff.monomial_to_coefficient_map(); return all_of(monomial_to_coeff_map.begin(), monomial_to_coeff_map.end(), [tol](const auto& p) { return std::abs(symbolic::get_constant_value(p.second)) <= tol; }); } // namespace void CheckParsedSymbolicLorentzConeConstraint( MathematicalProgram* prog, const Expression& linear_expr, const Expression& quadratic_expr, LorentzConeConstraint::EvalType eval_type) { const auto& binding1 = prog->AddLorentzConeConstraint( linear_expr, quadratic_expr, 0., eval_type); EXPECT_EQ(binding1.evaluator()->eval_type(), eval_type); const auto& binding2 = prog->lorentz_cone_constraints().back(); EXPECT_EQ(binding1.evaluator(), binding2.evaluator()); EXPECT_EQ(binding1.variables(), binding2.variables()); // Now check if the linear and quadratic constraints are parsed correctly. const VectorX<Expression> e_parsed = binding1.evaluator()->A() * binding1.variables() + binding1.evaluator()->b(); EXPECT_PRED2(ExprEqual, (e_parsed(0) * e_parsed(0)).Expand(), (linear_expr * linear_expr).Expand()); Expression quadratic_expr_parsed = e_parsed.tail(e_parsed.rows() - 1).squaredNorm(); // Due to the small numerical error, quadratic_expr and quadratic_expr_parsed // do not match exactly.So we will compare each term in the two polynomials, // and regard them to be equal if the error in the coefficient is sufficiently // small. const symbolic::Polynomial poly_parsed{quadratic_expr_parsed}; const symbolic::Polynomial poly{quadratic_expr}; const double tol{100 * numeric_limits<double>::epsilon()}; EXPECT_TRUE(AreTwoPolynomialsNear(poly_parsed, poly, tol)); } void CheckParsedSymbolicLorentzConeConstraint( MathematicalProgram* prog, const Eigen::Ref<const Eigen::Matrix<Expression, Eigen::Dynamic, 1>>& e) { for (const auto eval_type : {LorentzConeConstraint::EvalType::kConvex, LorentzConeConstraint::EvalType::kConvexSmooth, LorentzConeConstraint::EvalType::kNonconvex}) { const auto& binding1 = prog->AddLorentzConeConstraint(e, eval_type); EXPECT_EQ(binding1.evaluator()->eval_type(), eval_type); const auto& binding2 = prog->lorentz_cone_constraints().back(); EXPECT_EQ(binding1.evaluator(), binding2.evaluator()); EXPECT_EQ(binding1.evaluator()->A() * binding1.variables() + binding1.evaluator()->b(), e); EXPECT_EQ(binding2.evaluator()->A() * binding2.variables() + binding2.evaluator()->b(), e); CheckParsedSymbolicLorentzConeConstraint( prog, e(0), e.tail(e.rows() - 1).squaredNorm(), eval_type); } } void CheckParsedSymbolicRotatedLorentzConeConstraint( MathematicalProgram* prog, const Eigen::Ref<const VectorX<Expression>>& e) { const auto& binding1 = prog->AddRotatedLorentzConeConstraint(e); const auto& binding2 = prog->rotated_lorentz_cone_constraints().back(); EXPECT_EQ(binding1.evaluator(), binding2.evaluator()); EXPECT_EQ(binding1.evaluator()->A() * binding1.variables() + binding1.evaluator()->b(), e); EXPECT_EQ(binding2.evaluator()->A() * binding2.variables() + binding2.evaluator()->b(), e); } } // namespace class SymbolicLorentzConeTest : public ::testing::Test { public: SymbolicLorentzConeTest() : prog_(), x_() { x_ = prog_.NewContinuousVariables<3>("x"); } protected: MathematicalProgram prog_; VectorDecisionVariable<3> x_; }; TEST_F(SymbolicLorentzConeTest, Test1) { // Add Lorentz cone constraint: // x is in Lorentz cone Matrix<Expression, 3, 1> e; e << 1 * x_(0), 1.0 * x_(1), 1.0 * x_(2); CheckParsedSymbolicLorentzConeConstraint(&prog_, e); } TEST_F(SymbolicLorentzConeTest, Test2) { // Add Lorentz cone constraint: // x + [1, 2, 0] is in Lorentz cone. Matrix<Expression, 3, 1> e; e << x_(0) + 1, x_(1) + 2, +x_(2); CheckParsedSymbolicLorentzConeConstraint(&prog_, e); } TEST_F(SymbolicLorentzConeTest, Test3) { // Add Lorentz cone constraint: // [2 * x(0) + 3 * x(2)] // [ - x(0) + 2 * x(2)] is in Lorentz cone // [ x(2)] // [ -x(1) ] Matrix<Expression, 4, 1> e; e << 2 * x_(0) + 3 * x_(2), -x_(0) + 2 * x_(2), +x_(2), -x_(1); CheckParsedSymbolicLorentzConeConstraint(&prog_, e); } TEST_F(SymbolicLorentzConeTest, Test4) { // Add Lorentz cone constraint: // [ 2 * x(0) + 3 * x(1) + 5] // [ 4 * x(0) + 4 * x(2) - 7] // [ 10] // [ 2 * x(2) ] Matrix<Expression, 4, 1> e; // clang-format off e << 2 * x_(0) + 3 * x_(1) + 5, 4 * x_(0) + 4 * x_(2) - 7, 10, 2 * x_(2); // clang-format on CheckParsedSymbolicLorentzConeConstraint(&prog_, e); } TEST_F(SymbolicLorentzConeTest, Test5) { // Add Lorentz cone constraint: // [x(0); x(1); x(2); 0] is in the Lorentz cone. Vector4<Expression> e; e << x_(0), x_(1), x_(2), 0; CheckParsedSymbolicLorentzConeConstraint(&prog_, e); } TEST_F(SymbolicLorentzConeTest, Test6) { // Add Lorentz cone constraint: // [x(0); x(1) + x(2)] is in the Lorentz cone. Vector2<Expression> e; e << x_(0), x_(1) + x_(2); CheckParsedSymbolicLorentzConeConstraint(&prog_, e); } TEST_F(SymbolicLorentzConeTest, Test7) { CheckParsedSymbolicLorentzConeConstraint( &prog_, x_(0) + 2, pow(x_(0), 2) + 4 * x_(0) * x_(1) + 4 * pow(x_(1), 2), LorentzConeConstraint::EvalType::kConvex); CheckParsedSymbolicLorentzConeConstraint( &prog_, x_(0) + 2, pow(x_(0), 2) + 4 * x_(0) * x_(1) + 4 * pow(x_(1), 2), LorentzConeConstraint::EvalType::kConvexSmooth); } TEST_F(SymbolicLorentzConeTest, Test8) { CheckParsedSymbolicLorentzConeConstraint( &prog_, x_(0) + 2, pow(x_(0), 2) - (x_(0) - x_(1)) * (x_(0) + x_(1)) + 2 * x_(1) + 3, LorentzConeConstraint::EvalType::kConvex); CheckParsedSymbolicLorentzConeConstraint( &prog_, x_(0) + 2, pow(x_(0), 2) - (x_(0) - x_(1)) * (x_(0) + x_(1)) + 2 * x_(1) + 3, LorentzConeConstraint::EvalType::kConvexSmooth); } TEST_F(SymbolicLorentzConeTest, Test9) { CheckParsedSymbolicLorentzConeConstraint( &prog_, 2, pow(x_(0), 2) + pow(x_(1), 2), LorentzConeConstraint::EvalType::kConvex); CheckParsedSymbolicLorentzConeConstraint( &prog_, 2, pow(x_(0), 2) + pow(x_(1), 2), LorentzConeConstraint::EvalType::kConvexSmooth); } TEST_F(SymbolicLorentzConeTest, TestLinearConstraint) { // Actually adding linear constraint, that the quadratic expression is // actually a constant. CheckParsedSymbolicLorentzConeConstraint( &prog_, x_(0) + 2, 1, LorentzConeConstraint::EvalType::kConvexSmooth); CheckParsedSymbolicLorentzConeConstraint( &prog_, x_(0) + 2, x_(0) - 2 * (0.5 * x_(0) + 1) + 3, LorentzConeConstraint::EvalType::kConvexSmooth); } TEST_F(SymbolicLorentzConeTest, TestError) { // Check the cases to add with invalid quadratic expression. // Check polynomial with order no smaller than 2 EXPECT_THROW(prog_.AddLorentzConeConstraint(2 * x_(0) + 3, pow(x_(1), 3)), runtime_error); // The quadratic expression is actually affine. EXPECT_THROW(prog_.AddLorentzConeConstraint(2 * x_(0), 3 * x_(1) + 2), runtime_error); EXPECT_THROW( prog_.AddLorentzConeConstraint( 2 * x_(0), x_(1) * x_(1) - (x_(1) - x_(0)) * (x_(1) + x_(0)) - x_(0) * x_(0) + 2 * x_(1) + 3), runtime_error); // The Hessian matrix is not positive semidefinite. EXPECT_THROW(prog_.AddLorentzConeConstraint(2 * x_(0) + 3, x_(1) * x_(1) - x_(2) * x_(2)), runtime_error); EXPECT_THROW( prog_.AddLorentzConeConstraint( 2 * x_(0) + 3, x_(1) * x_(1) + x_(2) * x_(2) + 3 * x_(1) * x_(2)), runtime_error); EXPECT_THROW( prog_.AddLorentzConeConstraint( 2 * x_(0) + 3, x_(1) * x_(1) + x_(2) * x_(2) + 3 * x_(0) * x_(2)), runtime_error); // The quadratic expression is not always non-negative. EXPECT_THROW(prog_.AddLorentzConeConstraint( 2 * x_(0) + 3, x_(1) * x_(1) + x_(2) * x_(2) - 1), runtime_error); EXPECT_THROW(prog_.AddLorentzConeConstraint( 2 * x_(0) + 3, pow(2 * x_(0) + 3 * x_(1) + 2, 2) - 1), runtime_error); // The quadratic expression is a negative constant. EXPECT_THROW(prog_.AddLorentzConeConstraint( 2 * x_(0) + 3, pow(x_(0), 2) - pow(x_(1), 2) - (x_(0) + x_(1)) * (x_(0) - x_(1)) - 1), runtime_error); // The first expression is not actually linear. EXPECT_THROW(prog_.AddLorentzConeConstraint(2 * x_(0) * x_(1), pow(x_(0), 2)), runtime_error); } GTEST_TEST(TestMathematicalProgram, AddSymbolicRotatedLorentzConeConstraint1) { // Add rotated Lorentz cone constraint: // x is in the rotated Lorentz cone constraint. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>("x"); Matrix<Expression, 3, 1> e; e << +x(0), +x(1), +x(2); CheckParsedSymbolicRotatedLorentzConeConstraint(&prog, e); } GTEST_TEST(TestMathematicalProgram, AddSymbolicRotatedLorentzConeConstraint2) { // Add rotated Lorentz cone constraint: // [x(0) + 2 * x(2)] // [x(0) ] is in the rotated Lorentz cone // [ x(2)] MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>("x"); Matrix<Expression, 3, 1> e; e << x(0) + 2 * x(2), +x(0), +x(2); CheckParsedSymbolicRotatedLorentzConeConstraint(&prog, e); } GTEST_TEST(TestMathematicalProgram, AddSymbolicRotatedLorentzConeConstraint3) { // Add rotated Lorentz cone constraint: // [x(0) + 1] // [x(1) + 2] is in the rotated Lorentz cone // [x(2) ] // [x(3) - 1] // [-x(1) ] MathematicalProgram prog; auto x = prog.NewContinuousVariables<4>("x"); Matrix<Expression, 5, 1> e; e << x(0) + 1, x(1) + 2, +x(2), x(3) - 1, -x(1); CheckParsedSymbolicRotatedLorentzConeConstraint(&prog, e); } GTEST_TEST(TestMathematicalProgram, AddSymbolicRotatedLorentzConeConstraint4) { // Add rotated Lorentz cone constraint: // [2 * x(0) + 3 * x(2) + 3] // [ x(0) - 4 * x(2) ] is in the rotated Lorentz cone // [ 2 * x(2) ] // [3 * x(0) + 1] // [ 4] MathematicalProgram prog; auto x = prog.NewContinuousVariables<4>("x"); Matrix<Expression, 5, 1> e; e << 2 * x(0) + 3 * x(2) + 3, x(0) - 4 * x(2), 2 * x(2), 3 * x(0) + 1, 4; CheckParsedSymbolicRotatedLorentzConeConstraint(&prog, e); } GTEST_TEST(TestMathematicalProgram, AddSymbolicRotatedLorentzConeConstraint5) { // Add rotated Lorentz cone constraint, using quadratic expression. MathematicalProgram prog; const auto x = prog.NewContinuousVariables<4>("x"); Expression linear_expression1 = x(0) + 1; Expression linear_expression2 = x(1) - x(2); Eigen::Matrix2d Q; Eigen::Vector2d b; const double c{5}; Q << 1, 0.5, 0.5, 1; b << 0, 0.1; const Expression quadratic_expression = x.head<2>().cast<Expression>().dot(Q * x.head<2>() + b) + c; const auto binding = prog.AddRotatedLorentzConeConstraint( linear_expression1, linear_expression2, quadratic_expression); EXPECT_EQ(binding.evaluator(), prog.rotated_lorentz_cone_constraints().back().evaluator()); const VectorX<Expression> z = binding.evaluator()->A() * binding.variables() + binding.evaluator()->b(); const double tol{1E-10}; EXPECT_TRUE( symbolic::test::PolynomialEqual(symbolic::Polynomial(linear_expression1), symbolic::Polynomial(z(0)), tol)); EXPECT_TRUE( symbolic::test::PolynomialEqual(symbolic::Polynomial(linear_expression2), symbolic::Polynomial(z(1)), tol)); EXPECT_TRUE(symbolic::test::PolynomialEqual( symbolic::Polynomial(quadratic_expression), symbolic::Polynomial(z.tail(z.rows() - 2).squaredNorm()), tol)); } GTEST_TEST(TestMathematicalProgram, TestAddQuadraticAsRotatedLorentzConeConstraint) { solvers::MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto check = [&prog, &x](const Eigen::Matrix2d& Q, const Eigen::Vector2d& b, double c) { auto dut = prog.AddQuadraticAsRotatedLorentzConeConstraint(Q, b, c, x); auto z = dut.evaluator()->A() * x + dut.evaluator()->b(); double tol = 1E-10; // Make sure that the rotated Lorentz cone constraint is the same as the // quadratic constraint expression. EXPECT_TRUE(symbolic::test::PolynomialEqual( symbolic::Polynomial(z.tail(z.rows() - 2).squaredNorm() - z(0) * z(1)), symbolic::Polynomial(0.5 * x.cast<symbolic::Expression>().dot(Q * x) + b.dot(x) + c), tol)); EXPECT_EQ(prog.rotated_lorentz_cone_constraints().back().evaluator().get(), dut.evaluator().get()); }; Eigen::Matrix2d Q; Q << 2, 1, 3, 2; Eigen::Vector2d b(2, 3); double c = -0.5; check(Q, b, c); Q << 2, 2, 2, 6; check(Q, b, c); } namespace { template <typename Derived> typename std::enable_if_t<is_same_v<typename Derived::Scalar, Expression>> CheckAddedSymbolicPositiveSemidefiniteConstraint( MathematicalProgram* prog, const Eigen::MatrixBase<Derived>& V) { int num_psd_cnstr = prog->positive_semidefinite_constraints().size(); int num_lin_eq_cnstr = prog->linear_equality_constraints().size(); auto binding = prog->AddPositiveSemidefiniteConstraint(V); // Check if number of linear equality constraints and positive semidefinite // constraints are both incremented by 1. EXPECT_EQ(num_psd_cnstr + 1, prog->positive_semidefinite_constraints().size()); EXPECT_EQ(num_lin_eq_cnstr + 1, prog->linear_equality_constraints().size()); // Check if the returned binding is the correct one. EXPECT_EQ(binding.evaluator().get(), prog->positive_semidefinite_constraints().back().evaluator().get()); // Check if the added linear constraint is correct. M is the newly added // variables representing the psd matrix. const Eigen::Map<const MatrixX<Variable>> M(&binding.variables()(0), V.rows(), V.cols()); // The linear equality constraint is only imposed on the lower triangular // part of the psd matrix. const auto& new_lin_eq_cnstr = prog->linear_equality_constraints().back(); auto V_minus_M = math::ToSymmetricMatrixFromLowerTriangularColumns( new_lin_eq_cnstr.evaluator()->GetDenseA() * new_lin_eq_cnstr.variables() - new_lin_eq_cnstr.evaluator()->lower_bound()); EXPECT_EQ(V_minus_M, V - M); } } // namespace GTEST_TEST(TestMathematicalProgram, AddPositiveSemidefiniteConstraint) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<4>("X"); auto psd_cnstr = prog.AddPositiveSemidefiniteConstraint(X).evaluator(); EXPECT_EQ(prog.positive_semidefinite_constraints().size(), 1); EXPECT_EQ(prog.GetAllConstraints().size(), 1); const auto& new_psd_cnstr = prog.positive_semidefinite_constraints().back(); EXPECT_EQ(psd_cnstr.get(), new_psd_cnstr.evaluator().get()); Eigen::Map<Eigen::Matrix<Variable, 16, 1>> X_flat(&X(0, 0)); EXPECT_TRUE(CheckStructuralEquality(X_flat, new_psd_cnstr.variables())); // Adds X is psd. CheckAddedSymbolicPositiveSemidefiniteConstraint(&prog, Matrix4d::Identity() * X); // Adds 2 * X + Identity() is psd. CheckAddedSymbolicPositiveSemidefiniteConstraint( &prog, 2.0 * X + Matrix4d::Identity()); // Adds a linear matrix expression Aᵀ * X + X * A is psd. Matrix4d A{}; // clang-format off A << 1, 2, 3, 4, 0, 1, 2, 3, 0, 0, 2, 3, 0, 0, 0, 1; // clang-format on CheckAddedSymbolicPositiveSemidefiniteConstraint(&prog, A.transpose() * X + X * A); // Test the MatrixX<Expression> version. MatrixX<Expression> M = A.transpose() * X + X * A; CheckAddedSymbolicPositiveSemidefiniteConstraint(&prog, M); // Adds [X.topLeftCorner<2, 2>() 0 ] is psd // [ 0 X.bottomRightCorner<2, 2>()] Eigen::Matrix<Expression, 4, 4> Y{}; // clang-format off Y << Matrix2d::Identity() * X.topLeftCorner<2, 2>(), Matrix2d::Zero(), Matrix2d::Zero(), Matrix2d::Identity() * X.bottomRightCorner<2, 2>(); // clang-format on CheckAddedSymbolicPositiveSemidefiniteConstraint(&prog, Y); } GTEST_TEST(TestMathematicalProgram, AddPrincipalSubmatrixIsPsdConstraintVariable) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<4>("X"); std::set<int> minor_indices{0, 1, 3}; MatrixXDecisionVariable minor_manual(3, 3); // clang-format off minor_manual << X(0, 0), X(0, 1), X(0, 3), X(1, 0), X(1, 1), X(1, 3), X(3, 0), X(3, 1), X(3, 3); // clang-format on auto psd_cnstr = prog.AddPrincipalSubmatrixIsPsdConstraint(X, minor_indices) .evaluator(); EXPECT_EQ(prog.positive_semidefinite_constraints().size(), 1); EXPECT_EQ(prog.GetAllConstraints().size(), 1); const auto& new_psd_cnstr = prog.positive_semidefinite_constraints().back(); EXPECT_EQ(psd_cnstr.get(), new_psd_cnstr.evaluator().get()); Eigen::Map<Eigen::Matrix<Variable, 9, 1>> minor_flat(&minor_manual(0, 0)); EXPECT_TRUE(CheckStructuralEquality(minor_flat, new_psd_cnstr.variables())); } GTEST_TEST(TestMathematicalProgram, AddPrincipalSubmatrixIsPsdConstraintExpression) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<4>("X"); std::set<int> minor_indices{0, 1, 3}; MatrixXDecisionVariable minor_manual(3, 3); // clang-format off minor_manual << X(0, 0), X(0, 1), X(0, 3), X(1, 0), X(1, 1), X(1, 3), X(3, 0), X(3, 1), X(3, 3); // clang-format on auto psd_cnstr = prog.AddPrincipalSubmatrixIsPsdConstraint( 2 * Matrix4d::Identity() * X, minor_indices) .evaluator(); EXPECT_EQ(prog.positive_semidefinite_constraints().size(), 1); EXPECT_EQ(prog.GetAllConstraints().size(), 2); const auto& new_psd_cnstr = prog.positive_semidefinite_constraints().back(); EXPECT_EQ(psd_cnstr.get(), new_psd_cnstr.evaluator().get()); MathematicalProgram prog_manual; prog_manual.AddDecisionVariables(minor_manual); auto psd_cnstr_manual = prog_manual .AddPositiveSemidefiniteConstraint( 2 * Matrix3d::Identity() * minor_manual) .evaluator(); const auto& new_psd_cnstr_manual = prog.positive_semidefinite_constraints().back(); EXPECT_TRUE(CheckStructuralEquality(new_psd_cnstr_manual.variables(), new_psd_cnstr.variables())); EXPECT_EQ(prog.positive_semidefinite_constraints().size(), prog_manual.positive_semidefinite_constraints().size()); EXPECT_EQ(prog.linear_equality_constraints().size(), prog_manual.linear_equality_constraints().size()); EXPECT_EQ(prog.linear_equality_constraints().size(), 1); EXPECT_EQ(prog.GetAllConstraints().size(), prog_manual.GetAllConstraints().size()); EXPECT_TRUE(CompareMatrices( prog.linear_equality_constraints()[0].evaluator()->upper_bound(), prog_manual.linear_equality_constraints()[0].evaluator()->upper_bound())); EXPECT_TRUE(CompareMatrices( prog.linear_equality_constraints()[0].evaluator()->lower_bound(), prog_manual.linear_equality_constraints()[0].evaluator()->lower_bound())); } GTEST_TEST(TestMathematicalProgram, TestExponentialConeConstraint) { MathematicalProgram prog; EXPECT_EQ(prog.required_capabilities().count( ProgramAttribute::kExponentialConeConstraint), 0); auto x = prog.NewContinuousVariables<4>(); const Vector3<symbolic::Expression> expr(2 * x(0) + x(1) + 2, 1, -2 * x(0) + 3); auto binding = prog.AddExponentialConeConstraint(expr); EXPECT_GT(prog.required_capabilities().count( ProgramAttribute::kExponentialConeConstraint), 0); EXPECT_EQ(prog.GetAllConstraints().size(), 1); const VectorX<symbolic::Expression> expr_reconstructed = binding.evaluator()->A() * binding.variables() + binding.evaluator()->b(); EXPECT_EQ(expr_reconstructed.rows(), 3); for (int i = 0; i < 3; ++i) { EXPECT_PRED2(ExprEqual, expr(i), expr_reconstructed(i)); } } void CheckAddedQuadraticCost(MathematicalProgram* prog, const Eigen::MatrixXd& Q, const Eigen::VectorXd& b, const VectorXDecisionVariable& x, std::optional<bool> is_convex = std::nullopt) { int num_quadratic_cost = prog->quadratic_costs().size(); auto cnstr = prog->AddQuadraticCost(Q, b, x, is_convex).evaluator(); EXPECT_EQ(++num_quadratic_cost, prog->quadratic_costs().size()); // Check if the newly added quadratic constraint, and the returned // quadratic constraint, both match 0.5 * x' * Q * x + b' * x EXPECT_EQ(cnstr, prog->quadratic_costs().back().evaluator()); EXPECT_EQ(cnstr->Q(), Q); EXPECT_EQ(cnstr->b(), b); } GTEST_TEST(TestMathematicalProgram, AddQuadraticCost) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); CheckAddedQuadraticCost(&prog, Matrix3d::Identity(), Vector3d::Zero(), x); CheckAddedQuadraticCost(&prog, Matrix3d::Identity(), Vector3d(1, 2, 3), x); CheckAddedQuadraticCost(&prog, Matrix3d::Identity(), Vector3d(1, 2, 3), x, true); CheckAddedQuadraticCost(&prog, -Matrix3d::Identity(), Vector3d(1, 2, 3), x, false); // Now check AddQuadraticCost(Q, b, x) without passing is_convex flag. auto cost1 = prog.AddQuadraticCost(Matrix3d::Identity(), Vector3d(1, 2, 3), x); EXPECT_TRUE(cost1.evaluator()->is_convex()); EXPECT_TRUE(prog.quadratic_costs().back().evaluator()->is_convex()); // Intentionlly pass the wrong is_convex flag. MathematicalProgram will // use this wrong flag in the added cost. cost1 = prog.AddQuadraticCost(Matrix3d::Identity(), Vector3d(1, 2, 3), x, false); EXPECT_FALSE(cost1.evaluator()->is_convex()); auto cost2 = prog.AddQuadraticCost(-Matrix3d::Identity(), Vector3d(1, 2, 3), x); EXPECT_FALSE(cost2.evaluator()->is_convex()); EXPECT_FALSE(prog.quadratic_costs().back().evaluator()->is_convex()); // Test with x being a VariableRefList. auto cost3 = prog.AddQuadraticCost(Matrix3d::Identity(), Vector3d(1, 2, 3), {x.tail<2>(), x.head<1>()}); EXPECT_TRUE(cost3.evaluator()->is_convex()); VectorX<symbolic::Expression> cost_eval_sym; cost3.evaluator()->Eval(cost3.variables(), &cost_eval_sym); EXPECT_PRED2(ExprEqual, cost_eval_sym(0).Expand(), (0.5 * (x(0) * x(0) + x(1) * x(1) + x(2) * x(2)) + x(1) + 2 * x(2) + 3 * x(0)) .Expand()); auto cost4 = prog.AddQuadraticCost(Matrix3d(Vector3d(-1, -2, -3).asDiagonal()), Vector3d(1, 2, 3), {x.tail<2>(), x.head<1>()}); EXPECT_FALSE(cost4.evaluator()->is_convex()); cost4.evaluator()->Eval(cost4.variables(), &cost_eval_sym); EXPECT_PRED2(ExprEqual, cost_eval_sym(0).Expand(), (-0.5 * (x(1) * x(1) + 2 * x(2) * x(2) + 3 * x(0) * x(0)) + x(1) + 2 * x(2) + 3 * x(0)) .Expand()); // Intentionlly pass the wrong is_convex flag. MathematicalProgram will // use this wrong flag in the added cost. cost4 = prog.AddQuadraticCost(Matrix3d(Vector3d(-1, -2, -3).asDiagonal()), Vector3d(1, 2, 3), {x.tail<2>(), x.head<1>()}, true); EXPECT_TRUE(cost4.evaluator()->is_convex()); // Now check AddQuadraticCost(Q, b, c, x) without passing is_convex flag. auto cost5 = prog.AddQuadraticCost(Eigen::Matrix3d::Identity(), Vector3d(1, 2, 3), 1.5, x); EXPECT_TRUE(cost5.evaluator()->is_convex()); EXPECT_EQ(cost5.evaluator()->c(), 1.5); auto cost6 = prog.AddQuadraticCost(-Eigen::Matrix3d::Identity(), Vector3d(1, 2, 3), 2.5, x); EXPECT_FALSE(cost6.evaluator()->is_convex()); EXPECT_EQ(cost6.evaluator()->c(), 2.5); // Intentionlly pass the wrong is_convex flag. MathematicalProgram will // use this wrong flag in the added cost. cost6 = prog.AddQuadraticCost(-Eigen::Matrix3d::Identity(), Vector3d(1, 2, 3), 2.5, x, true); EXPECT_TRUE(cost6.evaluator()->is_convex()); } void CheckAddedSymbolicQuadraticCostUserFun(const MathematicalProgram& prog, const Expression& e, const Binding<Cost>& binding, int num_quadratic_cost) { EXPECT_EQ(num_quadratic_cost, prog.quadratic_costs().size()); EXPECT_EQ(binding.evaluator(), prog.quadratic_costs().back().evaluator()); EXPECT_EQ(binding.variables(), prog.quadratic_costs().back().variables()); auto cnstr = prog.quadratic_costs().back().evaluator(); // Check the added cost is 0.5 * x' * Q * x + b' * x + c const auto& x_bound = binding.variables(); const Expression e_added = 0.5 * x_bound.dot(cnstr->Q() * x_bound) + cnstr->b().dot(x_bound) + cnstr->c(); EXPECT_PRED2(ExprEqual, e_added.Expand(), e.Expand()); } void CheckAddedSymbolicQuadraticCost(MathematicalProgram* prog, const Expression& e, bool is_convex_expected) { int num_quadratic_cost = prog->quadratic_costs().size(); auto binding1 = prog->AddQuadraticCost(e); EXPECT_EQ(binding1.evaluator()->is_convex(), is_convex_expected); CheckAddedSymbolicQuadraticCostUserFun(*prog, e, binding1, ++num_quadratic_cost); auto binding2 = prog->AddCost(e); CheckAddedSymbolicQuadraticCostUserFun(*prog, e, binding2, ++num_quadratic_cost); } GTEST_TEST(TestMathematicalProgram, AddSymbolicQuadraticCost) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); // Identity diagonal term. Expression e1 = x.transpose() * x; CheckAddedSymbolicQuadraticCost(&prog, e1, true); EXPECT_TRUE(prog.quadratic_costs().back().evaluator()->is_convex()); // Identity diagonal term. Expression e2 = x.transpose() * x + 1; CheckAddedSymbolicQuadraticCost(&prog, e2, true); EXPECT_TRUE(prog.quadratic_costs().back().evaluator()->is_convex()); // Confirm that const terms are respected. auto b = prog.AddQuadraticCost(e2); VectorXd y(1); b.evaluator()->Eval(Vector3d::Zero(), &y); EXPECT_EQ(y[0], 1); // Identity diagonal term. Expression e3 = x(0) * x(0) + x(1) * x(1) + 2; CheckAddedSymbolicQuadraticCost(&prog, e3, true); EXPECT_TRUE(prog.quadratic_costs().back().evaluator()->is_convex()); // Non-identity diagonal term. Expression e4 = x(0) * x(0) + 2 * x(1) * x(1) + 3 * x(2) * x(2) + 3; CheckAddedSymbolicQuadraticCost(&prog, e4, true); EXPECT_TRUE(prog.quadratic_costs().back().evaluator()->is_convex()); // Cross terms. Expression e5 = x(0) * x(0) + 2 * x(1) * x(1) + 4 * x(0) * x(1) + 2; CheckAddedSymbolicQuadraticCost(&prog, e5, false); EXPECT_FALSE(prog.quadratic_costs().back().evaluator()->is_convex()); // Linear terms. Expression e6 = x(0) * x(0) + 2 * x(1) * x(1) + 4 * x(0); CheckAddedSymbolicQuadraticCost(&prog, e6, true); // Cross terms and linear terms. Expression e7 = (x(0) + 2 * x(1) + 3) * (x(0) + x(1) + 4) + 3 * x(0) * x(0) + 6 * pow(x(1) + 1, 2); CheckAddedSymbolicQuadraticCost(&prog, e7, true); // Cubic polynomial case. Expression e8 = pow(x(0), 3) + 1; EXPECT_THROW(prog.AddQuadraticCost(e8), runtime_error); // Call AddQuadraticCost with user-specified is_convex flag. const Expression e9 = x(0) * x(0) + 2 * x(1); auto cost9 = prog.AddQuadraticCost(e9, true); EXPECT_TRUE(cost9.evaluator()->is_convex()); // We lie about the convexity of this cost, that we set is_convex=false. The // returned cost should also report is_convex=false. cost9 = prog.AddQuadraticCost(e9, false); EXPECT_FALSE(cost9.evaluator()->is_convex()); const Expression e10 = -x(0) * x(0) + x(1) * x(1); auto cost10 = prog.AddQuadraticCost(e10, false); EXPECT_FALSE(cost10.evaluator()->is_convex()); } GTEST_TEST(TestMathematicalProgram, Test2NormSquaredCost) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); // |Ax - b|^2 = (x-xd)'Q(x-xd) => Q = A'*A and b = A*xd. Eigen::Matrix2d A; A << 1, 2, 3, 4; Eigen::Matrix2d Q = A.transpose() * A; Eigen::Vector2d x_desired; x_desired << 5, 6; Eigen::Vector2d b = A * x_desired; auto obj1 = prog.AddQuadraticErrorCost(Q, x_desired, x).evaluator(); auto obj2 = prog.Add2NormSquaredCost(A, b, x).evaluator(); // Test the objective at a 6 arbitrary values (to guarantee correctness // of the six-parameter quadratic form. Eigen::Vector2d x0; Eigen::VectorXd y1, y2; x0 << 7, 8; for (int i = 0; i < 6; i++) { obj1->Eval(x0, &y1); obj2->Eval(x0, &y2); EXPECT_TRUE(CompareMatrices(y1, y2)); EXPECT_TRUE(CompareMatrices(y2, (A * x0 - b).transpose() * (A * x0 - b))); x0 += Eigen::Vector2d::Constant(2); } } GTEST_TEST(TestMathematicalProgram, AddL2NormCost) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); Eigen::Matrix2d A; A << 1, 2, 3, 4; Eigen::Vector2d b(2, 3); auto obj1 = prog.AddCost(Binding<L2NormCost>(std::make_shared<L2NormCost>(A, b), x)); EXPECT_TRUE(prog.required_capabilities().contains( ProgramAttribute::kL2NormCost)); EXPECT_EQ(prog.l2norm_costs().size(), 1u); EXPECT_EQ(prog.GetAllCosts().size(), 1u); auto obj2 = prog.AddL2NormCost(A, b, x); EXPECT_EQ(prog.l2norm_costs().size(), 2u); symbolic::Expression e = (A * x + b).norm(); auto obj3 = prog.AddL2NormCost(e, 1e-8, 1e-8); EXPECT_EQ(prog.l2norm_costs().size(), 3u); // Test that the AddCost method correctly recognizes the L2norm. auto obj4 = prog.AddCost(e); EXPECT_EQ(prog.l2norm_costs().size(), 4u); prog.RemoveCost(obj1); prog.RemoveCost(obj2); prog.RemoveCost(obj3); prog.RemoveCost(obj4); EXPECT_EQ(prog.l2norm_costs().size(), 0u); EXPECT_FALSE(prog.required_capabilities().contains( ProgramAttribute::kL2NormCost)); prog.AddL2NormCost(A, b, {x.head<1>(), x.tail<1>()}); EXPECT_EQ(prog.l2norm_costs().size(), 1u); EXPECT_TRUE(prog.required_capabilities().contains( ProgramAttribute::kL2NormCost)); auto new_prog = prog.Clone(); EXPECT_EQ(new_prog->l2norm_costs().size(), 1u); // AddL2NormCost(Expression) can throw. e = (A*x + b).squaredNorm(); DRAKE_EXPECT_THROWS_MESSAGE(prog.AddL2NormCost(e), ".*is not an L2 norm.*"); } GTEST_TEST(TestMathematicalProgram, AddQuadraticConstraint) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); auto constraint1 = prog.AddConstraint(Binding<QuadraticConstraint>( std::make_shared<QuadraticConstraint>(Eigen::Matrix2d::Identity(), Eigen::Vector2d::Ones(), 0, 1), x.head<2>())); EXPECT_GT(prog.required_capabilities().count( ProgramAttribute::kQuadraticConstraint), 0); ASSERT_EQ(prog.quadratic_constraints().size(), 1); EXPECT_EQ(prog.quadratic_constraints()[0].evaluator().get(), constraint1.evaluator().get()); EXPECT_EQ(prog.quadratic_constraints()[0].variables(), x.head<2>()); auto constraint2 = prog.AddQuadraticConstraint( -Eigen::Matrix2d::Identity(), Eigen::Vector2d::Ones(), 0, 1, x.tail<2>(), QuadraticConstraint::HessianType::kNegativeSemidefinite); EXPECT_GT(prog.required_capabilities().count( ProgramAttribute::kQuadraticConstraint), 0); EXPECT_EQ(prog.quadratic_constraints().size(), 2); auto constraint3 = prog.AddQuadraticConstraint(x(0) * x(0) - x(1) * x(1), 0, 1); EXPECT_GT(prog.required_capabilities().count( ProgramAttribute::kQuadraticConstraint), 0); EXPECT_EQ(prog.quadratic_constraints().size(), 3); EXPECT_EQ(constraint3.evaluator()->hessian_type(), QuadraticConstraint::HessianType::kIndefinite); prog.RemoveConstraint(constraint2); EXPECT_GT(prog.required_capabilities().count( ProgramAttribute::kQuadraticConstraint), 0); EXPECT_EQ(prog.quadratic_constraints().size(), 2); prog.RemoveConstraint(constraint1); prog.RemoveConstraint(constraint3); EXPECT_TRUE(prog.quadratic_constraints().empty()); EXPECT_EQ(prog.required_capabilities().count( ProgramAttribute::kQuadraticConstraint), 0); } GTEST_TEST(TestMathematicalProgram, AddL2NormCostUsingConicConstraint) { MathematicalProgram prog{}; auto x = prog.NewContinuousVariables<2>(); Eigen::Matrix2d A; A << 1, 2, 3, 4; const Eigen::Vector2d b(2, 3); const auto ret = prog.AddL2NormCostUsingConicConstraint(A, b, x); const symbolic::Variable& s = std::get<0>(ret); const Binding<LinearCost>& linear_cost = std::get<1>(ret); const Binding<LorentzConeConstraint>& lorentz_cone_constraint = std::get<2>(ret); EXPECT_GE(prog.FindDecisionVariableIndex(s), 0); EXPECT_EQ(linear_cost.variables().rows(), 1); EXPECT_EQ(linear_cost.variables(), Vector1<symbolic::Variable>(s)); EXPECT_EQ(linear_cost.evaluator()->a(), Vector1d(1)); EXPECT_EQ(linear_cost.evaluator()->b(), 0); EXPECT_EQ(prog.linear_costs().size(), 1u); EXPECT_EQ(prog.lorentz_cone_constraints().size(), 1u); EXPECT_EQ(lorentz_cone_constraint.variables().rows(), 3); EXPECT_EQ(lorentz_cone_constraint.variables(), Vector3<symbolic::Variable>(s, x(0), x(1))); Vector3<symbolic::Expression> lorentz_eval_expected; lorentz_eval_expected << s, A * x + b; EXPECT_EQ(lorentz_cone_constraint.evaluator()->A() * lorentz_cone_constraint.variables() + lorentz_cone_constraint.evaluator()->b(), lorentz_eval_expected); } // Helper function for ArePolynomialIsomorphic. // // Transforms a monomial into an isomorphic one up to a given map (Variable::Id // → Variable). Consider an example where monomial is "x³y⁴" and var_id_to_var // is {x.get_id() ↦ z, y.get_id() ↦ w}. We have transform(x³y⁴, {x.get_id() ↦ z, // y.get_id() ↦ w}) = z³w⁴. // // @pre `var_id_to_var` is 1-1. // @pre The domain of `var_id_to_var` includes all variables in `monomial`. // @pre `var_id_to_var` should be chain-free. Formally, for all variable v in // the image of var_id_to_var, its ID, id(v) should not be in the domain of // var_id_to_var. For example, {x.get_id() -> y, y.get_id() -> z} is not // allowed. symbolic::Monomial transform(const symbolic::Monomial& monomial, const map<Variable::Id, Variable>& var_id_to_var) { // var_id_to_var should be chain-free. for (const pair<const Variable::Id, Variable>& p : var_id_to_var) { const Variable& var{p.second}; DRAKE_DEMAND(var_id_to_var.find(var.get_id()) == var_id_to_var.end()); } map<Variable, int> new_powers; for (const pair<Variable, int> p : monomial.get_powers()) { const Variable& var_in_monomial{p.first}; const int exponent{p.second}; const auto it = var_id_to_var.find(var_in_monomial.get_id()); // There should be a mapping for the ID in var_id_to_var. DRAKE_DEMAND(it != var_id_to_var.end()); const Variable new_var{it->second}; // var_id_to_var should be 1-1. DRAKE_DEMAND(new_powers.find(new_var) == new_powers.end()); new_powers.emplace(new_var, exponent); } return symbolic::Monomial{new_powers}; } // Helper function for ArePolynomialIsomorphic. // // Transforms a Polynomial into an isomorphic one up to a given map // (Variable::Id → Variable). Consider an example where poly = x³y⁴ + 2x² and // var_id_to_var is {x.get_id() ↦ z, y.get_id() ↦ w}. We have transform(poly, // var_id_to_var) = z³w⁴ + 2z². // // @pre `var_id_to_var` is 1-1. // @pre The domain of `var_id_to_var` includes all variables in `m`. // @pre `var_id_to_var` should be chain-free. symbolic::Polynomial transform( const symbolic::Polynomial& poly, const map<Variable::Id, Variable>& var_id_to_var) { symbolic::Polynomial::MapType new_map; for (const pair<const symbolic::Monomial, symbolic::Expression>& p : poly.monomial_to_coefficient_map()) { new_map.emplace(transform(p.first, var_id_to_var), p.second); } return symbolic::Polynomial{new_map}; } // Helper function for CheckAddedPolynomialCost. // // Checks if two Polynomial `p1` and `p2` are isomorphic with respect to a // bijection `var_id_to_var`. // // @pre `var_id_to_var` is 1-1. // @pre The domain of `var_id_to_var` includes all variables in `m`. // @pre `var_id_to_var` should be chain-free. bool ArePolynomialIsomorphic(const symbolic::Polynomial& p1, const symbolic::Polynomial& p2, const map<Variable::Id, Variable>& var_id_to_var) { return transform(p1, var_id_to_var).EqualTo(p2); } void CheckAddedPolynomialCost(MathematicalProgram* prog, const Expression& e) { int num_cost = prog->generic_costs().size(); const auto binding = prog->AddPolynomialCost(e); EXPECT_EQ(prog->generic_costs().size(), ++num_cost); EXPECT_EQ(binding.evaluator(), prog->generic_costs().back().evaluator()); // Now reconstruct the symbolic expression from `binding`. const auto polynomial = binding.evaluator()->polynomials()(0); // var_id_to_var : Variable::Id → Variable. It keeps the relation between a // variable in a Polynomial<double> and symbolic::Monomial. symbolic::Polynomial poly_expected; map<Variable::Id, Variable> var_id_to_var; for (const Polynomial<double>::Monomial& m : polynomial.GetMonomials()) { map<Variable, int> map_var_to_power; for (const Polynomial<double>::Term& term : m.terms) { auto it = var_id_to_var.find(term.var); if (it == var_id_to_var.end()) { Variable var{std::to_string(term.var)}; var_id_to_var.emplace_hint(it, term.var, var); map_var_to_power.emplace(var, term.power); } else { map_var_to_power.emplace(it->second, term.power); } } poly_expected += symbolic::Monomial(map_var_to_power) * m.coefficient; } // Checks if the two polynomials, `poly` and `poly_expected` are isomorphic // with respect to `var_id_to_var`. const symbolic::Polynomial poly{e}; EXPECT_TRUE(ArePolynomialIsomorphic(poly, poly_expected, var_id_to_var)); } GTEST_TEST(TestMathematicalProgram, TestAddPolynomialCost) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); // Add a cubic cost CheckAddedPolynomialCost(&prog, pow(x(0), 3)); // Add a cubic cost CheckAddedPolynomialCost(&prog, pow(x(0), 2) * x(1)); // Add a 4th order cost CheckAddedPolynomialCost( &prog, x(0) * x(0) * x(1) * x(1) + pow(x(0), 3) * x(1) + 2 * x(1)); } GTEST_TEST(TestMathematicalProgram, TestAddCostThrowError) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); // Add a cost containing variable not included in the mathematical program. Variable y("y"); DRAKE_EXPECT_THROWS_MESSAGE(prog.AddCost(x(0) + y), ".*is not a decision variable.*"); DRAKE_EXPECT_THROWS_MESSAGE(prog.AddCost(x(0) * x(0) + y), ".*is not a decision variable.*"); } GTEST_TEST(TestMathematicalProgram, TestAddGenericCost) { using GenericPtr = shared_ptr<Cost>; using Matrix1d = Vector1d; MathematicalProgram prog; auto x = prog.NewContinuousVariables<1>(); GenericPtr linear_cost(new LinearCost(Matrix1d(1))); prog.AddCost(linear_cost, x); EXPECT_EQ(prog.linear_costs().size(), 1); GenericPtr quadratic_cost(new QuadraticCost(Matrix1d(1), Vector1d(1))); prog.AddCost(quadratic_cost, x); EXPECT_EQ(prog.quadratic_costs().size(), 1); } GTEST_TEST(TestMathematicalProgram, TestAddGenericCostExpression) { MathematicalProgram prog; Variable x = prog.NewContinuousVariables<1>()[0]; Variable y = prog.NewContinuousVariables<1>()[0]; using std::atan2; auto b = prog.AddCost(atan2(y, x)); EXPECT_EQ(prog.generic_costs().size(), 1); Vector2d x_test(0.5, 0.2); Vector1d y_expected(atan2(0.2, 0.5)); EXPECT_TRUE(CompareMatrices(prog.EvalBinding(b, x_test), y_expected)); } // Confirm that even constant costs are supported. GTEST_TEST(TestMathematicalProgram, TestAddCostConstant) { MathematicalProgram prog; auto b = prog.AddCost(Expression(0.5)); EXPECT_EQ(prog.linear_costs().size(), 1); } GTEST_TEST(TestMathematicalProgram, TestClone) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>("x"); auto y = prog.NewIndeterminates<2>("y"); auto X = prog.NewSymmetricContinuousVariables<3>("X"); // Add costs shared_ptr<Cost> generic_trivial_cost1 = make_shared<GenericTrivialCost1>(); prog.AddCost(Binding<Cost>(generic_trivial_cost1, VectorDecisionVariable<3>(x(0), x(1), x(2)))); GenericTrivialCost2 generic_trivial_cost2; prog.AddCost(generic_trivial_cost2, VectorDecisionVariable<2>(x(2), x(1))); prog.AddLinearCost(x(0) + 2); prog.AddQuadraticCost(x(0) * x(0) + 2 * x(1) * x(1), true); prog.AddLinearCost(x(0) + 2 * x(2)); prog.AddQuadraticCost(x(1) * x(1) + 1); // Add constraints shared_ptr<Constraint> generic_trivial_constraint1 = make_shared<GenericTrivialConstraint1>(); prog.AddConstraint( Binding<Constraint>(generic_trivial_constraint1, VectorDecisionVariable<3>(x(0), x(1), x(2)))); prog.AddConstraint( Binding<Constraint>(generic_trivial_constraint1, VectorDecisionVariable<3>(x(2), x(1), x(0)))); prog.AddLinearConstraint(x(0) + x(1) <= 2); prog.AddLinearConstraint(x(1) + x(2) <= 1); prog.AddLinearEqualityConstraint(x(0) + x(2) == 0); prog.AddLinearEqualityConstraint(x(0) + x(1) + 3 * x(2) == 1); prog.AddBoundingBoxConstraint(-10, 10, x(0)); prog.AddBoundingBoxConstraint(-4, 5, x(1)); prog.AddLorentzConeConstraint( Vector3<symbolic::Expression>(+x(0), +x(1), x(2) - 0.5 * x(1)), LorentzConeConstraint::EvalType::kConvexSmooth); prog.AddLorentzConeConstraint( Vector3<symbolic::Expression>(x(0) + x(1), +x(0), x(2) - x(1)), LorentzConeConstraint::EvalType::kConvexSmooth); prog.AddRotatedLorentzConeConstraint(Vector4<symbolic::Expression>( +x(0), +x(1), 0.5 * (x(0) + x(1)), 0.5 * x(2))); prog.AddRotatedLorentzConeConstraint( Vector4<symbolic::Expression>(x(0) + x(1), x(1) + x(2), +x(0), +x(1))); prog.AddPositiveSemidefiniteConstraint(X); prog.AddPositiveSemidefiniteConstraint(X - Eigen::Matrix3d::Ones()); int num_all_constraints = prog.GetAllConstraints().size(); prog.AddLinearMatrixInequalityConstraint( {Eigen::Matrix2d::Identity(), Eigen::Matrix2d::Ones(), 2 * Eigen::Matrix2d::Ones()}, x.head<2>()); EXPECT_EQ(prog.GetAllConstraints().size(), num_all_constraints + 1); num_all_constraints++; prog.AddLinearComplementarityConstraint(Eigen::Matrix2d::Identity(), Eigen::Vector2d::Ones(), x.head<2>()); EXPECT_EQ(prog.GetAllConstraints().size(), num_all_constraints + 1); num_all_constraints++; prog.AddLinearComplementarityConstraint(2 * Eigen::Matrix2d::Identity(), Eigen::Vector2d::Ones(), x.tail<2>()); EXPECT_EQ(prog.GetAllConstraints().size(), num_all_constraints + 1); num_all_constraints++; prog.AddExponentialConeConstraint(Eigen::Matrix3d::Identity().sparseView(), Eigen::Vector3d::Ones(), x.head<3>()); EXPECT_EQ(prog.GetAllConstraints().size(), num_all_constraints + 1); num_all_constraints++; // Set initial guess prog.SetInitialGuessForAllVariables(Eigen::VectorXd::Ones(prog.num_vars())); auto new_prog = prog.Clone(); // Cloned program should have the same variables and indeterminates. EXPECT_EQ(prog.num_vars(), new_prog->num_vars()); EXPECT_EQ(prog.num_indeterminates(), new_prog->num_indeterminates()); for (int i = 0; i < prog.num_vars(); ++i) { EXPECT_TRUE( prog.decision_variable(i).equal_to(new_prog->decision_variable(i))); EXPECT_EQ(prog.FindDecisionVariableIndex(prog.decision_variable(i)), new_prog->FindDecisionVariableIndex(prog.decision_variable(i))); } for (int i = 0; i < prog.num_indeterminates(); ++i) { EXPECT_TRUE(prog.indeterminate(i).equal_to(new_prog->indeterminate(i))); EXPECT_EQ(prog.FindIndeterminateIndex(prog.indeterminate((i))), new_prog->FindIndeterminateIndex(prog.indeterminate(i))); } // Cloned program should have the same costs. EXPECT_TRUE( IsVectorOfBindingEqual(prog.generic_costs(), new_prog->generic_costs())); EXPECT_TRUE( IsVectorOfBindingEqual(prog.linear_costs(), new_prog->linear_costs())); EXPECT_TRUE(IsVectorOfBindingEqual(prog.quadratic_costs(), new_prog->quadratic_costs())); // Cloned program should have the same constraints. EXPECT_TRUE(IsVectorOfBindingEqual(prog.generic_constraints(), new_prog->generic_constraints())); EXPECT_TRUE(IsVectorOfBindingEqual(prog.linear_constraints(), new_prog->linear_constraints())); EXPECT_TRUE(IsVectorOfBindingEqual(prog.linear_equality_constraints(), new_prog->linear_equality_constraints())); EXPECT_TRUE(IsVectorOfBindingEqual(prog.bounding_box_constraints(), new_prog->bounding_box_constraints())); EXPECT_TRUE(IsVectorOfBindingEqual(prog.lorentz_cone_constraints(), new_prog->lorentz_cone_constraints())); EXPECT_TRUE( IsVectorOfBindingEqual(prog.rotated_lorentz_cone_constraints(), new_prog->rotated_lorentz_cone_constraints())); EXPECT_TRUE( IsVectorOfBindingEqual(prog.positive_semidefinite_constraints(), new_prog->positive_semidefinite_constraints())); EXPECT_TRUE( IsVectorOfBindingEqual(prog.linear_matrix_inequality_constraints(), new_prog->linear_matrix_inequality_constraints())); EXPECT_TRUE( IsVectorOfBindingEqual(prog.linear_matrix_inequality_constraints(), new_prog->linear_matrix_inequality_constraints())); EXPECT_TRUE(IsVectorOfBindingEqual(prog.exponential_cone_constraints(), new_prog->exponential_cone_constraints())); EXPECT_TRUE( IsVectorOfBindingEqual(prog.linear_complementarity_constraints(), new_prog->linear_complementarity_constraints())); EXPECT_TRUE(CompareMatrices(new_prog->initial_guess(), prog.initial_guess())); } GTEST_TEST(TestMathematicalProgram, TestEvalBinding) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); // Add linear constraint x(0) + 2x(1) = 2 auto linear_constraint = prog.AddLinearEqualityConstraint( Eigen::RowVector2d(1, 2), Vector1d(2), x.head<2>()); // Add constraint 0 ≤ x(1)² + 2x(2)² + x(1) + 2x(2) ≤ 1 auto quadratic_constraint = prog.AddConstraint(std::make_shared<QuadraticConstraint>( (Eigen::Matrix2d() << 2, 0, 0, 4).finished(), Eigen::Vector2d(1, 2), 0, 1), x.tail<2>()); auto quadratic_cost = prog.AddQuadraticCost(x(1) * x(1) + x(2)); const Eigen::Vector3d x_val(1, 2, 3); // The linear constraint should evaluate to 5. // The quadratic constraint should evaluate to 30. // The quadratic cost should evaluate to 7. EXPECT_TRUE(CompareMatrices(prog.EvalBinding(linear_constraint, x_val), Vector1d(5), 1E-15, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(prog.EvalBinding(quadratic_constraint, x_val), Vector1d(30), 1E-15, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(prog.EvalBinding(quadratic_cost, x_val), Vector1d(7), 1E-15, MatrixCompareType::absolute)); EXPECT_TRUE( CompareMatrices(prog.EvalBindings(prog.GetAllConstraints(), x_val), Vector2d(30, 5), 1E-15, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(prog.EvalBindings(prog.GetAllCosts(), x_val), Vector1d(7), 1E-15, MatrixCompareType::absolute)); // Pass in an incorrect size input. EXPECT_THROW(prog.EvalBinding(linear_constraint, Eigen::Vector2d::Zero()), std::logic_error); // Pass in some variable not registered in the program. symbolic::Variable y("y"); Binding<QuadraticCost> quadratic_cost_y( std::make_shared<QuadraticCost>(Vector1d(1), Vector1d(0)), VectorDecisionVariable<1>(y)); EXPECT_THROW(prog.EvalBinding(quadratic_cost_y, x_val), std::runtime_error); } GTEST_TEST(TestMathematicalProgram, TestGetBindingVariableValues) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); auto binding1 = prog.AddBoundingBoxConstraint(-1, 1, x(0)); auto binding2 = prog.AddLinearEqualityConstraint(x(0) + 2 * x(2), 2); const Eigen::Vector3d x_val(-2, 1, 2); EXPECT_TRUE(CompareMatrices(prog.GetBindingVariableValues(binding1, x_val), Vector1d(-2))); EXPECT_TRUE(CompareMatrices(prog.GetBindingVariableValues(binding2, x_val), Vector2d(-2, 2))); } GTEST_TEST(TestMathematicalProgram, TestCheckSatisfied) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); const auto y = prog.NewContinuousVariables<2>(); std::vector<Binding<Constraint>> bindings; bindings.emplace_back(prog.AddBoundingBoxConstraint(-.3, .4, x)); bindings.emplace_back(prog.AddBoundingBoxConstraint(-2, 5, y)); bindings.emplace_back( prog.AddLinearEqualityConstraint(y[0] == 3 * x[0] + 2 * x[1])); const double tol = std::numeric_limits<double>::epsilon(); Vector3d x_guess = Vector3d::Constant(.39); Vector2d y_guess = Vector2d::Constant(4.99); y_guess[0] = 3 * x_guess[0] + 2 * x_guess[1]; prog.SetInitialGuess(x, x_guess); prog.SetInitialGuess(y, y_guess); EXPECT_TRUE(prog.CheckSatisfied(bindings[0], prog.initial_guess(), 0)); EXPECT_TRUE(prog.CheckSatisfied(bindings[1], prog.initial_guess(), 0)); EXPECT_TRUE(prog.CheckSatisfied(bindings[2], prog.initial_guess(), tol)); EXPECT_TRUE(prog.CheckSatisfiedAtInitialGuess(bindings[0], 0)); EXPECT_TRUE(prog.CheckSatisfiedAtInitialGuess(bindings[1], 0)); EXPECT_TRUE(prog.CheckSatisfiedAtInitialGuess(bindings[2], tol)); EXPECT_TRUE(prog.CheckSatisfied(bindings, prog.initial_guess(), tol)); EXPECT_TRUE(prog.CheckSatisfiedAtInitialGuess(bindings, tol)); x_guess[2] = .41; prog.SetInitialGuess(x, x_guess); EXPECT_FALSE(prog.CheckSatisfied(bindings[0], prog.initial_guess(), 0)); EXPECT_FALSE(prog.CheckSatisfiedAtInitialGuess(bindings[0], 0)); EXPECT_FALSE(prog.CheckSatisfied(bindings, prog.initial_guess(), tol)); EXPECT_FALSE(prog.CheckSatisfiedAtInitialGuess(bindings, tol)); EXPECT_TRUE(prog.CheckSatisfiedAtInitialGuess(bindings[1], 0)); x_guess[2] = .39; y_guess[0] = 3 * x_guess[0] + 2 * x_guess[1] + 0.2; prog.SetInitialGuess(x, x_guess); prog.SetInitialGuess(y, y_guess); EXPECT_TRUE(prog.CheckSatisfiedAtInitialGuess(bindings[0], 0)); EXPECT_FALSE(prog.CheckSatisfied(bindings[2], prog.initial_guess(), tol)); EXPECT_FALSE(prog.CheckSatisfiedAtInitialGuess(bindings[2], tol)); EXPECT_FALSE(prog.CheckSatisfied(bindings, prog.initial_guess(), tol)); EXPECT_FALSE(prog.CheckSatisfiedAtInitialGuess(bindings, tol)); } GTEST_TEST(TestMathematicalProgram, TestSetAndGetInitialGuess) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); // Set initial guess for a single variable. prog.SetInitialGuess(x(1), 2); EXPECT_EQ(prog.GetInitialGuess(x(1)), 2); // Set initial guess for a vector of variables. prog.SetInitialGuess(x.tail<2>(), Eigen::Vector2d(3, 4)); EXPECT_TRUE(CompareMatrices(prog.GetInitialGuess(x.tail<2>()), Eigen::Vector2d(3, 4))); // Now set initial guess for a variable not registered. symbolic::Variable y("y"); EXPECT_THROW(prog.SetInitialGuess(y, 1), std::runtime_error); EXPECT_THROW(unused(prog.GetInitialGuess(y)), std::runtime_error); // Try the same things with an extrinsic guess. VectorXd guess = VectorXd::Constant(3, kNaN); prog.SetDecisionVariableValueInVector(x(2), 2, &guess); EXPECT_TRUE(std::isnan(guess[0])); EXPECT_EQ(guess[2], 2.0); prog.SetDecisionVariableValueInVector(x.head<2>(), Eigen::Vector2d(0.0, 1.0), &guess); EXPECT_EQ(guess[0], 0.0); EXPECT_EQ(guess[1], 1.0); EXPECT_EQ(guess[2], 2.0); EXPECT_THROW(prog.SetDecisionVariableValueInVector(y, 0.0, &guess), std::exception); } GTEST_TEST(TestMathematicalProgram, TestNonlinearExpressionConstraints) { // min ∑ x , subject to x'x = 1. MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>(); prog.AddConstraint(x.transpose() * x == 1.); if (SnoptSolver().available() && SnoptSolver().enabled()) { // Add equivalent constraints using all of the other entry points. // Note: restricted to SNOPT because IPOPT complains about the redundant // constraints. prog.AddConstraint(x.transpose() * x >= 1.); prog.AddConstraint(x.transpose() * x <= 1.); prog.AddConstraint((x.transpose() * x)(0), 1., 1.); prog.AddConstraint(x.transpose() * x, Vector1d{1.}, Vector1d{1.}); } prog.AddCost(x(0) + x(1)); const MathematicalProgramResult result = Solve(prog, Eigen::Vector2d(-0.5, -0.5)); EXPECT_TRUE(result.is_success()); EXPECT_TRUE(CompareMatrices(result.get_x_val(), Vector2d::Constant(-std::sqrt(2.) / 2.), 1e-6)); } GTEST_TEST(TestMathematicalProgram, TestAddVisualizationCallback) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); bool was_called = false; auto my_callback = [&was_called](const Eigen::Ref<const Eigen::VectorXd>& v) { EXPECT_EQ(v.size(), 2); EXPECT_EQ(v(0), 1.); EXPECT_EQ(v(1), 2.); was_called = true; }; Binding<VisualizationCallback> b = prog.AddVisualizationCallback(my_callback, x); EXPECT_EQ(prog.visualization_callbacks().size(), 1); const Vector2d test_x(1., 2.); // Call it via EvalVisualizationCallbacks. was_called = false; prog.EvalVisualizationCallbacks(test_x); EXPECT_TRUE(was_called); // Call it via EvalBinding. was_called = false; prog.EvalBinding(b, test_x); EXPECT_TRUE(was_called); // Call it directly via the double interface. VectorXd test_y(0); was_called = false; b.evaluator()->Eval(test_x, &test_y); EXPECT_TRUE(was_called); // Call it directly via the autodiff interface. const VectorX<AutoDiffXd> test_x_autodiff = math::InitializeAutoDiff(VectorXd{test_x}); VectorX<AutoDiffXd> test_y_autodiff(0); was_called = false; b.evaluator()->Eval(test_x_autodiff, &test_y_autodiff); EXPECT_TRUE(was_called); } GTEST_TEST(TestMathematicalProgram, TestSolverOptions) { MathematicalProgram prog; const SolverId solver_id("solver_id"); const SolverId wrong_solver_id("wrong_solver_id"); prog.SetSolverOption(solver_id, "double_name", 1.0); EXPECT_EQ(prog.GetSolverOptionsDouble(solver_id).at("double_name"), 1.0); EXPECT_EQ(prog.GetSolverOptionsDouble(wrong_solver_id).size(), 0); prog.SetSolverOption(solver_id, "int_name", 2); EXPECT_EQ(prog.GetSolverOptionsInt(solver_id).at("int_name"), 2); EXPECT_EQ(prog.GetSolverOptionsInt(wrong_solver_id).size(), 0); prog.SetSolverOption(solver_id, "string_name", "3"); EXPECT_EQ(prog.GetSolverOptionsStr(solver_id).at("string_name"), "3"); EXPECT_EQ(prog.GetSolverOptionsStr(wrong_solver_id).size(), 0); const SolverId dummy_id("dummy_id"); SolverOptions dummy_options; dummy_options.SetOption(dummy_id, "double_name", 10.0); dummy_options.SetOption(dummy_id, "int_name", 20); dummy_options.SetOption(dummy_id, "string_name", "30.0"); prog.SetSolverOptions(dummy_options); EXPECT_EQ(prog.GetSolverOptionsDouble(dummy_id).at("double_name"), 10.0); EXPECT_EQ(prog.GetSolverOptionsDouble(solver_id).size(), 0); EXPECT_EQ(prog.GetSolverOptionsInt(dummy_id).at("int_name"), 20); EXPECT_EQ(prog.GetSolverOptionsInt(solver_id).size(), 0); EXPECT_EQ(prog.GetSolverOptionsStr(dummy_id).at("string_name"), "30.0"); EXPECT_EQ(prog.GetSolverOptionsStr(solver_id).size(), 0); } void CheckNewSosPolynomial(MathematicalProgram::NonnegativePolynomial type) { // Check if the newly created nonnegative polynomial can be computed as m' * Q // * m. MathematicalProgram prog; auto t = prog.NewIndeterminates<4>(); const auto m = symbolic::MonomialBasis<4, 2>(symbolic::Variables(t)); const auto pair = prog.NewSosPolynomial(m, type, "TestGram"); const symbolic::Polynomial& p = pair.first; const MatrixXDecisionVariable& Q = pair.second; EXPECT_NE(Q(0, 0).get_name().find("TestGram"), std::string::npos); MatrixX<symbolic::Polynomial> Q_poly(m.rows(), m.rows()); const symbolic::Monomial monomial_one{}; for (int i = 0; i < Q_poly.rows(); ++i) { for (int j = 0; j < Q_poly.cols(); ++j) { Q_poly(i, j) = symbolic::Polynomial({{monomial_one, Q(j * Q_poly.rows() + i)}}); } } const symbolic::Polynomial p_expected(m.dot(Q_poly * m)); EXPECT_TRUE(p.EqualTo(p_expected)); const auto p2 = prog.NewSosPolynomial(Q, m, type); EXPECT_TRUE(p2.EqualTo(p_expected)); } GTEST_TEST(TestMathematicalProgram, NewSosPolynomial) { CheckNewSosPolynomial(MathematicalProgram::NonnegativePolynomial::kSos); CheckNewSosPolynomial(MathematicalProgram::NonnegativePolynomial::kSdsos); CheckNewSosPolynomial(MathematicalProgram::NonnegativePolynomial::kDsos); // Pass an uninitialized type to NewSosPolynomial method. EXPECT_THROW(CheckNewSosPolynomial( static_cast<MathematicalProgram::NonnegativePolynomial>(0)), std::runtime_error); // Check NewSosPolynomial with degree = 0 for (const auto type : {MathematicalProgram::NonnegativePolynomial::kSos, MathematicalProgram::NonnegativePolynomial::kSdsos, MathematicalProgram::NonnegativePolynomial::kDsos}) { solvers::MathematicalProgram prog; const auto x = prog.NewIndeterminates<2>(); symbolic::Polynomial p; MatrixXDecisionVariable gram; std::tie(p, gram) = prog.NewSosPolynomial(symbolic::Variables(x), 0, type); EXPECT_EQ(prog.bounding_box_constraints().size(), 1u); EXPECT_TRUE(CompareMatrices( prog.bounding_box_constraints()[0].evaluator()->lower_bound(), Vector1d::Constant(0))); EXPECT_TRUE(CompareMatrices( prog.bounding_box_constraints()[0].evaluator()->upper_bound(), Vector1d::Constant(kInf))); EXPECT_EQ(prog.bounding_box_constraints()[0].variables(), gram); EXPECT_EQ(p.TotalDegree(), 0); EXPECT_EQ(p.monomial_to_coefficient_map().size(), 1u); EXPECT_EQ(gram.rows(), 1); EXPECT_EQ(gram.cols(), 1); EXPECT_EQ(p.monomial_to_coefficient_map().at(symbolic::Monomial()), gram(0, 0)); } } void CheckNewEvenDegreeNonnegativePolynomial( MathematicalProgram::NonnegativePolynomial type) { // Check if the newly created nonnegative polynomial can be computed as m_e' * // Q_ee * m_e + m_o' * Q_oo * m_o * m. MathematicalProgram prog; auto t = prog.NewIndeterminates<2>(); const symbolic::Variables t_vars(t); const int degree{4}; const auto m_e = symbolic::EvenDegreeMonomialBasis(t_vars, degree / 2); const auto m_o = symbolic::OddDegreeMonomialBasis(t_vars, degree / 2); symbolic::Polynomial p; MatrixXDecisionVariable Q_oo, Q_ee; std::tie(p, Q_oo, Q_ee) = prog.NewEvenDegreeNonnegativePolynomial(t_vars, degree, type); symbolic::Polynomial p_expected{}; for (int i = 0; i < Q_ee.rows(); ++i) { for (int j = 0; j < Q_ee.cols(); ++j) { p_expected += m_e(i) * Q_ee(i, j) * m_e(j); } } for (int i = 0; i < Q_oo.rows(); ++i) { for (int j = 0; j < Q_oo.cols(); ++j) { p_expected += m_o(i) * Q_oo(i, j) * m_o(j); } } EXPECT_PRED2(PolyEqual, p, p_expected); EXPECT_EQ(p.TotalDegree(), degree); if (type == MathematicalProgram::NonnegativePolynomial::kSos) { EXPECT_EQ(prog.positive_semidefinite_constraints().size(), 2); } } GTEST_TEST(TestMathematicalProgram, NewEvenDegreeNonnegativePolynomial) { CheckNewEvenDegreeNonnegativePolynomial( MathematicalProgram::NonnegativePolynomial::kSos); CheckNewEvenDegreeNonnegativePolynomial( MathematicalProgram::NonnegativePolynomial::kSdsos); CheckNewEvenDegreeNonnegativePolynomial( MathematicalProgram::NonnegativePolynomial::kDsos); } GTEST_TEST(TestMathematicalProgram, AddEqualityConstraintBetweenPolynomials) { MathematicalProgram prog; auto x = prog.NewIndeterminates<1>()(0); auto a = prog.NewContinuousVariables<4>(); const symbolic::Polynomial p1(a(0) * x + a(1) + 2, {x}); const symbolic::Polynomial p2((a(2) + 1) * x + 2 * a(3), {x}); EXPECT_EQ(prog.linear_equality_constraints().size(), 0); const auto bindings = prog.AddEqualityConstraintBetweenPolynomials(p1, p2); EXPECT_EQ(prog.linear_equality_constraints().size(), 2); EXPECT_EQ(bindings.size(), 2u); for (int i = 0; i < 2; ++i) { EXPECT_EQ(bindings[i], prog.linear_equality_constraints()[i]); } // Test with different value of a, some satisfies the polynomial equality // constraints. auto is_satisfied = [&prog](const Eigen::Vector4d& a_val) { for (const auto& linear_eq_constraint : prog.linear_equality_constraints()) { const auto constraint_val = prog.EvalBinding(linear_eq_constraint, a_val); EXPECT_EQ(constraint_val.size(), 1); if (std::abs(constraint_val(0) - linear_eq_constraint.evaluator()->lower_bound()(0)) > 1E-12) { return false; } } return true; }; EXPECT_TRUE(is_satisfied(Eigen::Vector4d(1, 2, 0, 2))); EXPECT_FALSE(is_satisfied(Eigen::Vector4d(1, 2, 0, 1))); EXPECT_FALSE(is_satisfied(Eigen::Vector4d(1, 2, 1, 2))); // Test with a polynomial whose coefficients are not affine function of // decision variables. EXPECT_THROW(prog.AddEqualityConstraintBetweenPolynomials( p1, symbolic::Polynomial(a(0) * a(1) * x, {x})), std::runtime_error); // Test with a polynomial whose coefficients depend on variables that are not // decision variables of prog. symbolic::Variable b("b"); DRAKE_EXPECT_THROWS_MESSAGE(prog.AddEqualityConstraintBetweenPolynomials( p1, symbolic::Polynomial(b * x, {x})), ".*is not a decision variable.*"); // If we add `b` to prog as decision variable, then the code throws no // exceptions. prog.AddDecisionVariables(Vector1<symbolic::Variable>(b)); DRAKE_EXPECT_NO_THROW(prog.AddEqualityConstraintBetweenPolynomials( p1, symbolic::Polynomial(b * x, {x}))); } GTEST_TEST(TestMathematicalProgram, TestVariableScaling) { MathematicalProgram prog; EXPECT_EQ(prog.GetVariableScaling().size(), 0); auto x = prog.NewContinuousVariables<4>(); prog.SetVariableScaling(x(0), 1.0); prog.SetVariableScaling(x(1), 1.15); prog.SetVariableScaling(x(2), 1.15); prog.SetVariableScaling(x(3), 1.3); EXPECT_EQ(prog.GetVariableScaling().at(0), 1.0); EXPECT_EQ(prog.GetVariableScaling().at(1), 1.15); EXPECT_EQ(prog.GetVariableScaling().at(2), 1.15); EXPECT_EQ(prog.GetVariableScaling().at(3), 1.3); EXPECT_EQ(prog.GetVariableScaling().size(), 4); prog.SetVariableScaling(x(3), 3.0); EXPECT_EQ(prog.GetVariableScaling().at(0), 1.0); EXPECT_EQ(prog.GetVariableScaling().at(1), 1.15); EXPECT_EQ(prog.GetVariableScaling().at(2), 1.15); EXPECT_EQ(prog.GetVariableScaling().at(3), 3.0); EXPECT_EQ(prog.GetVariableScaling().size(), 4); } GTEST_TEST(TestMathematicalProgram, AddConstraintMatrix1) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); Eigen::Matrix<symbolic::Formula, 2, 2> formulas; // clang-format off formulas << (x(0) >= 0.0), (x(0) + x(1) <= 3.0), (x(1) == 2.0), (x(0) + x(1) >= -1.0); // clang-format on prog.AddConstraint(formulas); ASSERT_EQ(prog.GetAllConstraints().size(), 1); ASSERT_EQ(prog.GetAllLinearConstraints().size(), 1); const auto binding = prog.GetAllLinearConstraints()[0]; Eigen::Matrix<double, 4, 2> A_expected; Eigen::Matrix<double, 4, 1> lower_bound_expected; Eigen::Matrix<double, 4, 1> upper_bound_expected; const double inf{numeric_limits<double>::infinity()}; // clang-format off A_expected << 1, 0, // x0 >= 0 0, 1, // x1 == 2 1, 1, // x0 + x1 <= 3 1, 1; // x0 + x1 >= -1.0 lower_bound_expected << 0, // x0 >= 0 2, // x1 == 2 -inf, // x0 + x1 <= 3 -1; // x0 + x1 >= -1.0 upper_bound_expected << inf, // x0 >= 0 2, // x1 == 2 3, // x0 + x1 <= 3 inf; // x0 + x1 >= -1.0 // clang-format on ASSERT_TRUE(binding.evaluator()); EXPECT_EQ(binding.evaluator()->GetDenseA(), A_expected); EXPECT_EQ(binding.evaluator()->lower_bound(), lower_bound_expected); EXPECT_EQ(binding.evaluator()->upper_bound(), upper_bound_expected); } GTEST_TEST(TestMathematicalProgram, AddConstraintMatrix2) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); Eigen::Matrix<symbolic::Expression, 2, 2> exprs; // clang-format off exprs << x(0), x(0) + 2*x(1), x(1), x(0) + x(1); // clang-format on // This test relies on the pair (lb(i), ub(i)) being unique. Eigen::Matrix2d lb; lb << 0, -kInf, 2., -1.; Eigen::Matrix<double, 2, 2, Eigen::RowMajor> ub; ub(0, 0) = kInf; ub(0, 1) = 3; ub(1, 0) = 2; ub(1, 1) = kInf; prog.AddConstraint(exprs, lb, ub); ASSERT_EQ(prog.GetAllConstraints().size(), 1); ASSERT_EQ(prog.GetAllLinearConstraints().size(), 1); Eigen::Matrix<double, 4, 2> A_expected; Eigen::Matrix<double, 4, 1> lower_bound_expected; Eigen::Matrix<double, 4, 1> upper_bound_expected; std::array<std::array<Eigen::RowVector2d, 2>, 2> coeff; coeff[0][0] << 1, 0; coeff[0][1] << 1, 2; coeff[1][0] << 0, 1; coeff[1][1] << 1, 1; auto check_binding = [&lb, &ub, &coeff](const Binding<LinearConstraint>& binding) { EXPECT_EQ(binding.evaluator()->num_constraints(), 4); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { bool find_match = false; for (int k = 0; k < 4; ++k) { if (binding.evaluator()->lower_bound()(k) == lb(i, j) && binding.evaluator()->upper_bound()(k) == ub(i, j)) { EXPECT_TRUE(CompareMatrices(binding.evaluator()->GetDenseA().row(k), coeff[i][j])); find_match = true; } } EXPECT_TRUE(find_match); } } }; const auto binding1 = prog.GetAllLinearConstraints()[0]; check_binding(binding1); const auto binding2 = prog.AddLinearConstraint(exprs, lb, ub); check_binding(binding2); } GTEST_TEST(TestMathematicalProgram, ReparsePolynomial) { MathematicalProgram prog; EXPECT_EQ(prog.GetVariableScaling().size(), 0); const auto a = prog.NewContinuousVariables<2>("a"); const auto x = prog.NewIndeterminates<2>("x"); // Variable not declared in this MathematicalProgram. const auto b = Variable{"b"}; // a₀x₀ + a₁x₀ + x₁ + a₀ + b const Expression e = a(0) * x(0) + a(1) * x(0) + x(1) + a(0) + b; // (a₀ + a₁)x₀ + x₁ + (a₀ + b). const symbolic::Polynomial expected{prog.MakePolynomial(e)}; { // (a₀x₀ + a₁x₀ + x₁ + a₀ + b , {x₀, x₁, a₀, a₁, b}). symbolic::Polynomial p{e}; EXPECT_PRED2(PolyNotEqual, p, expected); prog.Reparse(&p); EXPECT_PRED2(PolyEqual, p, expected); } { // (a₀x₀ + a₁x₀ + x₁ + a₀ + b , {x₀, x₁}). symbolic::Polynomial p{e, {x(0), x(1)}}; EXPECT_PRED2(PolyEqual, p, expected); // Note that p == expected already. prog.Reparse(&p); EXPECT_PRED2(PolyEqual, p, expected); } { // (a₀x₀ + a₁x₀ + x₁ + a₀ + b , {x₀, a₀, b}). symbolic::Polynomial p{e, {x(0), a(0), b}}; EXPECT_PRED2(PolyNotEqual, p, expected); prog.Reparse(&p); EXPECT_PRED2(PolyEqual, p, expected); } { // (a₀x₀ + a₁x₀ + x₁ + a₀ + b , {a₀, a₁}. symbolic::Polynomial p{e, {a(0), a(1)}}; EXPECT_PRED2(PolyNotEqual, p, expected); prog.Reparse(&p); EXPECT_PRED2(PolyEqual, p, expected); } { // (a₀x₀ + a₁x₀ + x₁ + a₀ + b , {a₀, a₁, b}. symbolic::Polynomial p{e, {a(0), a(1), b}}; EXPECT_PRED2(PolyNotEqual, p, expected); prog.Reparse(&p); EXPECT_PRED2(PolyEqual, p, expected); } } GTEST_TEST(TestMathematicalProgram, AddSosConstraint) { MathematicalProgram prog{}; const auto x = prog.NewIndeterminates<1>()(0); const auto a = prog.NewContinuousVariables<1>()(0); // p1 has both a and x as indeterminates. So we need to reparse the polynomial // to have only x as the indeterminates. const symbolic::Polynomial p1(a + x * x); const Vector2<symbolic::Monomial> monomial_basis(symbolic::Monomial{}, symbolic::Monomial(x, 1)); const Matrix2<symbolic::Variable> Q_psd = prog.AddSosConstraint( p1, monomial_basis, MathematicalProgram::NonnegativePolynomial::kSos, "Q"); EXPECT_NE(Q_psd(0, 0).get_name().find("Q"), std::string::npos); EXPECT_EQ(prog.positive_semidefinite_constraints().size(), 1u); EXPECT_EQ(prog.lorentz_cone_constraints().size(), 0u); EXPECT_EQ(prog.rotated_lorentz_cone_constraints().size(), 0u); const int num_lin_con = prog.linear_constraints().size() + prog.linear_equality_constraints().size(); // Now call AddSosConstraint with type=kDsos. prog.AddSosConstraint(p1, monomial_basis, MathematicalProgram::NonnegativePolynomial::kDsos); // With dsos, the mathematical program adds more linear constraints than it // did with sos. EXPECT_GT(prog.linear_constraints().size() + prog.linear_equality_constraints().size(), 2 * num_lin_con); EXPECT_EQ(prog.positive_semidefinite_constraints().size(), 1u); // Now call AddSosConstraint with type=kSdsos. prog.AddSosConstraint(p1, monomial_basis, MathematicalProgram::NonnegativePolynomial::kSdsos); EXPECT_GT(prog.lorentz_cone_constraints().size() + prog.rotated_lorentz_cone_constraints().size(), 0u); EXPECT_EQ(prog.positive_semidefinite_constraints().size(), 1u); // p2 = (a+1)x² + 0 has some coefficient equal to 0. The constructed monomial // should remove that 0-term. Hence the returned monomial basis should only // contain [x]. const symbolic::Polynomial p2{ {{symbolic::Monomial(), 0}, {symbolic::Monomial(x, 2), a + 1}}}; const auto [gram2, monomial_basis2] = prog.AddSosConstraint(p2); EXPECT_EQ(monomial_basis2.rows(), 1); EXPECT_EQ(monomial_basis2(0), symbolic::Monomial(x)); EXPECT_EQ(gram2.rows(), 1); } template <typename C> void RemoveCostTest(MathematicalProgram* prog, const symbolic::Expression& cost1_expr, const std::vector<Binding<C>>* program_costs, ProgramAttribute affected_capability) { auto cost1 = prog->AddCost(cost1_expr); // cost1 and cost2 represent the same cost, but their evaluators point to // different objects. auto cost2 = prog->AddCost(cost1_expr); ASSERT_NE(cost1.evaluator().get(), cost2.evaluator().get()); EXPECT_EQ(program_costs->size(), 2u); EXPECT_EQ(prog->RemoveCost(cost1), 1); EXPECT_EQ(program_costs->size(), 1u); EXPECT_EQ(program_costs->at(0).evaluator().get(), cost2.evaluator().get()); EXPECT_TRUE(prog->required_capabilities().contains(affected_capability)); // Now add another cost2 to program. If we remove cost2, now we get a program // with empty linear cost. prog->AddCost(cost2); EXPECT_EQ(program_costs->size(), 2u); EXPECT_EQ(prog->RemoveCost(cost2), 2); EXPECT_EQ(program_costs->size(), 0u); EXPECT_FALSE(prog->required_capabilities().contains(affected_capability)); // Currently program_costs is empty. EXPECT_EQ(prog->RemoveCost(cost1), 0); EXPECT_FALSE(prog->required_capabilities().contains(affected_capability)); prog->AddCost(cost1); // prog doesn't contain cost2, removing cost2 from prog ends up as a no-opt. EXPECT_EQ(prog->RemoveCost(cost2), 0); EXPECT_EQ(program_costs->size(), 1u); EXPECT_TRUE(prog->required_capabilities().contains(affected_capability)); // cost3 and cost1 share the same evaluator, but the associated variables are // different. VectorX<symbolic::Variable> cost3_vars = cost1.variables(); cost3_vars[0] = cost1.variables()[1]; cost3_vars[1] = cost1.variables()[0]; auto cost3 = prog->AddCost(cost1.evaluator(), cost3_vars); EXPECT_EQ(prog->RemoveCost(cost1), 1); EXPECT_EQ(program_costs->size(), 1u); EXPECT_TRUE(prog->required_capabilities().contains(affected_capability)); EXPECT_EQ(program_costs->at(0).evaluator().get(), cost3.evaluator().get()); } GTEST_TEST(TestMathematicalProgram, RemoveLinearCost) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); RemoveCostTest<LinearCost>(&prog, x[0] + 2 * x[1], &(prog.linear_costs()), ProgramAttribute::kLinearCost); } GTEST_TEST(TestMathematicalProgram, RemoveQuadraticCost) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); RemoveCostTest(&prog, x[0] * x[0] + 2 * x[1] * x[1], &(prog.quadratic_costs()), ProgramAttribute::kQuadraticCost); } GTEST_TEST(TestMathematicalProgram, RemoveGenericCost) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); RemoveCostTest(&prog, x[0] * x[0] * x[1], &(prog.generic_costs()), ProgramAttribute::kGenericCost); } GTEST_TEST(TestMathematicalProgram, TestToString) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); auto y = prog.NewIndeterminates<1>("y"); prog.AddLinearCost(2 * x[0] + 3 * x[1]); prog.AddLinearConstraint(x[0] + x[1] <= 2.0); prog.AddSosConstraint(x[0] * y[0] * y[0]); std::string s = prog.to_string(); EXPECT_THAT(s, testing::HasSubstr("Decision variables")); EXPECT_THAT(s, testing::HasSubstr("Indeterminates")); EXPECT_THAT(s, testing::HasSubstr("Cost")); EXPECT_THAT(s, testing::HasSubstr("Constraint")); EXPECT_THAT(s, testing::HasSubstr("x")); EXPECT_THAT(s, testing::HasSubstr("y")); EXPECT_THAT(s, testing::HasSubstr("2")); EXPECT_THAT(s, testing::HasSubstr("3")); } GTEST_TEST(TestMathematicalProgram, RemoveDecisionVariable) { // A program where x(1) is not associated with any cost/constraint. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); prog.AddLinearCost(x(0) + x(2)); prog.AddBoundingBoxConstraint(0, 2, x(0)); prog.AddLinearConstraint(x(0) + 2 * x(2) <= 1); prog.SetInitialGuess(x, Eigen::Vector3d(0, 1, 2)); prog.SetVariableScaling(x(0), 0.5); prog.SetVariableScaling(x(1), 3.0); prog.SetVariableScaling(x(2), 4.0); // Remove x(1) and check that all accessors remain in sync. const int x1_index = prog.FindDecisionVariableIndex(x(1)); const int x1_index_removed = prog.RemoveDecisionVariable(x(1)); EXPECT_EQ(x1_index, x1_index_removed); EXPECT_EQ(prog.num_vars(), 2); EXPECT_EQ(prog.FindDecisionVariableIndex(x(0)), 0); EXPECT_EQ(prog.FindDecisionVariableIndex(x(2)), 1); EXPECT_THAT(prog.decision_variables(), testing::Pointwise(testing::Truly(TupleVarEqual), {x(0), x(2)})); EXPECT_TRUE(CompareMatrices(prog.initial_guess(), Eigen::Vector2d(0, 2))); EXPECT_THAT(prog.GetVariableScaling(), testing::WhenSorted(testing::ElementsAre( std::make_pair(0, 0.5), std::make_pair(1, 4.0)))); } GTEST_TEST(TestMathematicalProgram, RemoveDecisionVariableError) { // Test RemoveDecisionVariable with erroneous input. // Remove an indeterminate. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>("x"); auto y = prog.NewIndeterminates<2>("y"); DRAKE_EXPECT_THROWS_MESSAGE( prog.RemoveDecisionVariable(y(0)), ".*is not a decision variable of this MathematicalProgram."); // Remove a variable not in Mathematical program. const symbolic::Variable dummy("dummy"); DRAKE_EXPECT_THROWS_MESSAGE( prog.RemoveDecisionVariable(dummy), ".*is not a decision variable of this MathematicalProgram."); // Remove a variable associated with a cost. prog.AddLinearCost(x(0)); DRAKE_EXPECT_THROWS_MESSAGE(prog.RemoveDecisionVariable(x(0)), ".* is associated with a LinearCost.*"); // Remove a variable associated with a constraint. prog.AddLinearConstraint(x(0) + x(1) <= 1); DRAKE_EXPECT_THROWS_MESSAGE(prog.RemoveDecisionVariable(x(1)), ".* is associated with a LinearConstraint[^]*"); // Remove a variable associated with a visualization callback. prog.AddVisualizationCallback( [](const Eigen::VectorXd& vars) { drake::log()->info("{}", vars(0)); }, Vector1<symbolic::Variable>(x(2))); DRAKE_EXPECT_THROWS_MESSAGE( prog.RemoveDecisionVariable(x(2)), ".* is associated with a VisualizationCallback[^]*"); } GTEST_TEST(TestMathematicalProgram, TestToLatex) { MathematicalProgram prog; std::string empty_prog = prog.ToLatex(); EXPECT_EQ(empty_prog, "\\text{This MathematicalProgram has no decision variables.}"); auto x = prog.NewContinuousVariables<2>("x"); auto y = prog.NewIndeterminates<1>("y"); prog.AddLinearCost(2 * x[0] + 3 * x[1]); prog.AddLinearConstraint(x[0] + x[1] <= 2.0); prog.AddSosConstraint(x[0] * y[0] * y[0]); std::string s = prog.ToLatex(); EXPECT_THAT(s, testing::HasSubstr("\\min")); EXPECT_THAT(s, testing::HasSubstr("\\text{subject to}\\quad")); EXPECT_THAT(s, testing::HasSubstr("\\succeq 0.")); } GTEST_TEST(TestMathematicalProgram, RemoveLinearConstraint) { // ProgramAttribute::kLinearConstraint depends on both // prog.linear_constraints() and prog.bounding_box_constraints(). MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto lin_con1 = prog.AddLinearConstraint(x[0] + x[1] <= 1); auto lin_con2 = prog.AddLinearConstraint(x[0] + 2 * x[1] <= 1); EXPECT_EQ(prog.RemoveConstraint(lin_con1), 1); EXPECT_EQ(prog.linear_constraints().size(), 1u); EXPECT_TRUE(prog.required_capabilities().contains( ProgramAttribute::kLinearConstraint)); // Now the program contains 2 lin_con2 prog.AddConstraint(lin_con2); EXPECT_EQ(prog.RemoveConstraint(lin_con1), 0); EXPECT_EQ(prog.RemoveConstraint(lin_con2), 2); EXPECT_EQ(prog.linear_constraints().size(), 0u); EXPECT_FALSE(prog.required_capabilities().contains( ProgramAttribute::kLinearConstraint)); auto bbcon = prog.AddBoundingBoxConstraint(1, 2, x); EXPECT_TRUE(prog.required_capabilities().contains( ProgramAttribute::kLinearConstraint)); EXPECT_EQ(prog.RemoveConstraint(bbcon), 1); EXPECT_FALSE(prog.required_capabilities().contains( ProgramAttribute::kLinearConstraint)); } GTEST_TEST(TestMathematicalProgram, RemoveConstraintPSD) { // ProgramAttribute::kPositiveSemidefiniteConstraint depends on both // prog.positive_semidefinite_constraints() and // prog.linear_matrix_inequality_constraints(). MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); auto psd_con = prog.AddPositiveSemidefiniteConstraint(X); auto x = prog.NewContinuousVariables<2>(); auto lmi_con = prog.AddLinearMatrixInequalityConstraint( {Eigen::Matrix3d::Identity(), Eigen::Matrix3d::Ones(), 2 * Eigen::Matrix3d::Ones()}, x); EXPECT_EQ(prog.RemoveConstraint(psd_con), 1); EXPECT_EQ(prog.positive_semidefinite_constraints().size(), 0u); EXPECT_GT(prog.required_capabilities().count( ProgramAttribute::kPositiveSemidefiniteConstraint), 0); EXPECT_EQ(prog.RemoveConstraint(lmi_con), 1); EXPECT_EQ(prog.linear_matrix_inequality_constraints().size(), 0u); EXPECT_EQ(prog.required_capabilities().count( ProgramAttribute::kPositiveSemidefiniteConstraint), 0); } // Remove a constraint from @p prog. Before removing the constraint, @p // prog_constraints has only one entry. template <typename C> void TestRemoveConstraint(MathematicalProgram* prog, const Binding<C>& constraint, const std::vector<Binding<C>>* prog_constraints, ProgramAttribute removed_capability) { ASSERT_EQ(prog_constraints->size(), 1); ASSERT_TRUE(prog->required_capabilities().contains(removed_capability)); EXPECT_EQ(prog->RemoveConstraint(constraint), 1); EXPECT_EQ(prog_constraints->size(), 0u); EXPECT_FALSE(prog->required_capabilities().contains(removed_capability)); } GTEST_TEST(TestMathematicalProgram, RemoveConstraint) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); auto lin_eq_con = prog.AddLinearEqualityConstraint(x[0] + x[1] == 1); auto lorentz_con = prog.AddLorentzConeConstraint( x.cast<symbolic::Expression>(), LorentzConeConstraint::EvalType::kConvexSmooth); auto rotated_lorentz_con = prog.AddRotatedLorentzConeConstraint(x.cast<symbolic::Expression>()); Eigen::SparseMatrix<double> A(3, 3); A.setIdentity(); auto exponential_con = prog.AddExponentialConeConstraint(A, Eigen::Vector3d(1, 2, 3), x); auto generic_con = prog.AddConstraint(x(0) * x(0) * x(1) == 1); TestRemoveConstraint(&prog, lin_eq_con, &(prog.linear_equality_constraints()), ProgramAttribute::kLinearEqualityConstraint); TestRemoveConstraint(&prog, lorentz_con, &(prog.lorentz_cone_constraints()), ProgramAttribute::kLorentzConeConstraint); TestRemoveConstraint(&prog, rotated_lorentz_con, &(prog.rotated_lorentz_cone_constraints()), ProgramAttribute::kRotatedLorentzConeConstraint); TestRemoveConstraint(&prog, exponential_con, &(prog.exponential_cone_constraints()), ProgramAttribute::kExponentialConeConstraint); TestRemoveConstraint(&prog, generic_con, &(prog.generic_constraints()), ProgramAttribute::kGenericConstraint); auto lcp_con = prog.AddLinearComplementarityConstraint( Eigen::Matrix3d::Identity(), Eigen::Vector3d::Ones(), x); TestRemoveConstraint(&prog, lcp_con, &(prog.linear_complementarity_constraints()), ProgramAttribute::kLinearComplementarityConstraint); } GTEST_TEST(TestMathematicalProgram, RemoveVisualizationCallback) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); auto callback = prog.AddVisualizationCallback( [](const Eigen::VectorXd& vars) { drake::log()->info("{}", vars(0) + vars(1)); }, x); EXPECT_FALSE(prog.visualization_callbacks().empty()); EXPECT_TRUE( prog.required_capabilities().contains(ProgramAttribute::kCallback)); int count = prog.RemoveVisualizationCallback(callback); EXPECT_EQ(count, 1); EXPECT_TRUE(prog.visualization_callbacks().empty()); EXPECT_FALSE( prog.required_capabilities().contains(ProgramAttribute::kCallback)); } class ApproximatePSDConstraint : public ::testing::Test { // An arbitrary semidefinite program with 2 PSD constraints, 2 linear // constraints, and 1 equality constraint for testing the // Replace/TightenPsdConstraint methods. public: ApproximatePSDConstraint() : prog_(), X_{prog_.NewSymmetricContinuousVariables<3>()}, Y_{prog_.NewSymmetricContinuousVariables<4>()}, psd_constraint_X_{prog_.AddPositiveSemidefiniteConstraint(X_)}, psd_constraint_Y_{prog_.AddPositiveSemidefiniteConstraint(Y_)} { // Add an arbitrary linear constraint on X. Eigen::MatrixXd A(2, 3); // clang-format off A << 1, 0, 1, 0, -1, 1; // clang-format on Eigen::VectorXd lb(2); lb << -10, -7; Eigen::VectorXd ub(2); ub << 11, 9; prog_.AddLinearConstraint(A * X_ * Eigen::VectorXd::Ones(3) <= ub); prog_.AddLinearConstraint(A * X_ * Eigen::VectorXd::Ones(3) >= lb); prog_.AddLinearEqualityConstraint(Y_ == Eigen::MatrixXd::Identity(4, 4)); } protected: MathematicalProgram prog_; MatrixXDecisionVariable X_; MatrixXDecisionVariable Y_; Binding<PositiveSemidefiniteConstraint> psd_constraint_X_; Binding<PositiveSemidefiniteConstraint> psd_constraint_Y_; }; TEST_F(ApproximatePSDConstraint, TightenPsdConstraintToDd) { EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 2); EXPECT_EQ(ssize(prog_.linear_constraints()), 2); EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 1); auto dd_constraint_X = prog_.TightenPsdConstraintToDd(psd_constraint_X_); EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 1); EXPECT_EQ(ssize(prog_.linear_constraints()), X_.rows() * X_.rows() + 2); EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 1); auto dd_constraint_Y = prog_.TightenPsdConstraintToDd(psd_constraint_Y_); EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 0); EXPECT_EQ(ssize(prog_.linear_constraints()), Y_.rows() * Y_.rows() + X_.rows() * X_.rows() + 2); EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 1); } GTEST_TEST(TightenPsdConstraintToDd, UnregisteredVariableError) { MathematicalProgram prog1; auto X1 = prog1.NewSymmetricContinuousVariables<3>(); auto psd_constraint1 = prog1.AddPositiveSemidefiniteConstraint(X1); MathematicalProgram prog2; auto X2 = prog2.NewSymmetricContinuousVariables<3>(); auto psd_constraint2 = prog2.AddPositiveSemidefiniteConstraint(X2); DRAKE_EXPECT_THROWS_MESSAGE(prog1.TightenPsdConstraintToDd(psd_constraint2), ".*is not a decision variable.*"); } GTEST_TEST(TightenPsdConstraintToDd, NoConstraintToReplace) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); // A constraint not in the program. auto constraint = internal::CreateBinding( std::make_shared<PositiveSemidefiniteConstraint>(X.rows()), Eigen::Map<VectorXDecisionVariable>(X.data(), X.size())); EXPECT_EQ(ssize(prog.positive_semidefinite_constraints()), 0); prog.TightenPsdConstraintToDd(constraint); EXPECT_EQ(ssize(prog.positive_semidefinite_constraints()), 0); // Still adds the DD constraint even though the constraint was not found in // the program. EXPECT_EQ(ssize(prog.linear_constraints()), X.rows() * X.rows()); } TEST_F(ApproximatePSDConstraint, TightenPsdConstraintToSdd) { EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 2); EXPECT_EQ(ssize(prog_.linear_constraints()), 2); EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 1); prog_.TightenPsdConstraintToSdd(psd_constraint_X_); EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 1); EXPECT_EQ(ssize(prog_.linear_constraints()), 2); // An sdd constraint on X adds an equality constraints on the upper diagonal // of X to represent slack variables EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 2); // 3 choose 2 rotated lorentz cone constraints for constraint X to be sdd EXPECT_EQ(ssize(prog_.rotated_lorentz_cone_constraints()), 3); prog_.TightenPsdConstraintToSdd(psd_constraint_Y_); EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 0); EXPECT_EQ(ssize(prog_.linear_constraints()), 2); // An sdd constraint on Y adds an equality constraints on the upper diagonal // of Y to represent slack variables EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 3); // 3 choose 2 rotated lorentz cone constraints for the constraint that X be // sdd and 4 choose 2 for the constraint that Y be sdd. EXPECT_EQ(ssize(prog_.rotated_lorentz_cone_constraints()), 9); } GTEST_TEST(TightenPsdConstraintToSdd, UnregisteredVariableError) { MathematicalProgram prog1; auto X1 = prog1.NewSymmetricContinuousVariables<3>(); auto psd_constraint1 = prog1.AddPositiveSemidefiniteConstraint(X1); MathematicalProgram prog2; auto X2 = prog2.NewSymmetricContinuousVariables<3>(); auto psd_constraint2 = prog2.AddPositiveSemidefiniteConstraint(X2); DRAKE_EXPECT_THROWS_MESSAGE(prog1.TightenPsdConstraintToDd(psd_constraint2), ".*is not a decision variable.*"); } GTEST_TEST(TightenPsdConstraintToSdd, NoConstraintToReplace) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); // A constraint not in the program. auto constraint = internal::CreateBinding( std::make_shared<PositiveSemidefiniteConstraint>(X.rows()), Eigen::Map<VectorXDecisionVariable>(X.data(), X.size())); EXPECT_EQ(ssize(prog.positive_semidefinite_constraints()), 0); prog.TightenPsdConstraintToSdd(constraint); EXPECT_EQ(ssize(prog.positive_semidefinite_constraints()), 0); // Still adds the SDD constraint even though the constraint was not found in // the program. EXPECT_EQ(ssize(prog.rotated_lorentz_cone_constraints()), 3); } TEST_F(ApproximatePSDConstraint, RelaxPsdConstraintToDdDualCone) { EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 2); EXPECT_EQ(ssize(prog_.linear_constraints()), 2); EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 1); prog_.RelaxPsdConstraintToDdDualCone(psd_constraint_X_); EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 1); EXPECT_EQ(ssize(prog_.linear_constraints()), 3); EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 1); prog_.RelaxPsdConstraintToDdDualCone(psd_constraint_Y_); EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 0); EXPECT_EQ(ssize(prog_.linear_constraints()), 4); EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 1); } GTEST_TEST(RelaxPsdConstraintToDdDualCone, UnregisteredVariableError) { MathematicalProgram prog1; auto X1 = prog1.NewSymmetricContinuousVariables<3>(); auto psd_constraint1 = prog1.AddPositiveSemidefiniteConstraint(X1); MathematicalProgram prog2; auto X2 = prog2.NewSymmetricContinuousVariables<3>(); auto psd_constraint2 = prog2.AddPositiveSemidefiniteConstraint(X2); DRAKE_EXPECT_THROWS_MESSAGE( prog1.RelaxPsdConstraintToDdDualCone(psd_constraint2), ".*is not a decision variable.*"); } GTEST_TEST(RelaxPsdConstraintToDdDualCone, NoConstraintToReplace) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); // A constraint not in the program. auto constraint = internal::CreateBinding( std::make_shared<PositiveSemidefiniteConstraint>(X.rows()), Eigen::Map<VectorXDecisionVariable>(X.data(), X.size())); EXPECT_EQ(ssize(prog.positive_semidefinite_constraints()), 0); prog.RelaxPsdConstraintToDdDualCone(constraint); EXPECT_EQ(ssize(prog.positive_semidefinite_constraints()), 0); // Still adds the DD constraint even though the constraint was not found in // the program. EXPECT_EQ(ssize(prog.linear_constraints()), 1); } TEST_F(ApproximatePSDConstraint, RelaxPsdConstraintToSddDualCone) { EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 2); EXPECT_EQ(ssize(prog_.linear_constraints()), 2); EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 1); prog_.RelaxPsdConstraintToSddDualCone(psd_constraint_X_); EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 1); EXPECT_EQ(ssize(prog_.linear_constraints()), 2); EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 1); // 3 choose 2 rotated lorentz cone constraints for constraint X to be sdd EXPECT_EQ(ssize(prog_.rotated_lorentz_cone_constraints()), 3); prog_.RelaxPsdConstraintToSddDualCone(psd_constraint_Y_); EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 0); EXPECT_EQ(ssize(prog_.linear_constraints()), 2); EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 1); // 3 choose 2 rotated lorentz cone constraints for the constraint that X be // sdd and 4 choose 2 for the constraint that Y be sdd. EXPECT_EQ(ssize(prog_.rotated_lorentz_cone_constraints()), 9); } GTEST_TEST(RelaxPsdConstraintToSddDualCone, UnregisteredVariableError) { MathematicalProgram prog1; auto X1 = prog1.NewSymmetricContinuousVariables<3>(); auto psd_constraint1 = prog1.AddPositiveSemidefiniteConstraint(X1); MathematicalProgram prog2; auto X2 = prog2.NewSymmetricContinuousVariables<3>(); auto psd_constraint2 = prog2.AddPositiveSemidefiniteConstraint(X2); DRAKE_EXPECT_THROWS_MESSAGE( prog1.RelaxPsdConstraintToSddDualCone(psd_constraint2), ".*is not a decision variable.*"); } GTEST_TEST(RelaxPsdConstraintToSddDualCone, NoConstraintToReplace) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); // A constraint not in the program. auto constraint = internal::CreateBinding( std::make_shared<PositiveSemidefiniteConstraint>(X.rows()), Eigen::Map<VectorXDecisionVariable>(X.data(), X.size())); EXPECT_EQ(ssize(prog.positive_semidefinite_constraints()), 0); prog.RelaxPsdConstraintToSddDualCone(constraint); EXPECT_EQ(ssize(prog.positive_semidefinite_constraints()), 0); // Still adds the SDD dual cone constraint even though the constraint was not // found in the program. EXPECT_EQ(ssize(prog.rotated_lorentz_cone_constraints()), 3); } GTEST_TEST(MathematicalProgramTest, AddLogDeterminantLowerBoundConstraint) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>("X"); auto ret = prog.AddLogDeterminantLowerBoundConstraint( X.cast<symbolic::Expression>(), 1); const auto& constraint = std::get<0>(ret); const auto& t = std::get<1>(ret); EXPECT_TRUE(CompareMatrices(constraint.evaluator()->GetDenseA(), Eigen::RowVector3d::Ones())); EXPECT_TRUE( CompareMatrices(constraint.evaluator()->lower_bound(), Vector1d(1))); EXPECT_TRUE( CompareMatrices(constraint.evaluator()->upper_bound(), Vector1d(kInf))); EXPECT_EQ(constraint.variables().size(), 3); for (int i = 0; i < 3; ++i) { EXPECT_TRUE(constraint.variables()(i).equal_to(t(i))); } EXPECT_EQ(prog.exponential_cone_constraints().size(), 3); EXPECT_EQ(prog.positive_semidefinite_constraints().size(), 1); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/exponential_cone_program_examples.h
#pragma once #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solver_interface.h" namespace drake { namespace solvers { namespace test { /** * Solves a trivial problem with exponential cone constraint * min y*exp(z/y) * s.t y + z = 1 * y > 0 * @param check_dual If set to true, we will also check the dual solution. */ void ExponentialConeTrivialExample(const SolverInterface& solver, double tol, bool check_dual); /** * For a random variable x (assuming that the sample space of x is {0, 1, 2, * 3}), with a given probability p(x), find the other probability q(x), such * that the KL divergence KL(p(x) | q(x)) is minimized. The optimal probability * is q(x) = p(x). */ void MinimizeKLDivergence(const SolverInterface& solver, double tol); /** * Given several points, find the smallest ellipsoid that covers these points. * Mathematically, this problem can be formulated as * max log(det(S)) * s.t. ⌈S b/2⌉ is positive semidifinite. * ⌊bᵀ/2 c ⌋ * pᵀ * S * p + bᵀ * p + c <= 1 for all p. * where the ellipsoid is described as {x | xᵀ*S*x + bᵀ*x + c <= 1}, and p is * a point to be covered. */ void MinimalEllipsoidCoveringPoints(const SolverInterface& solver, double tol); /* Impose the constraint log(det(X)) >= 1 * Note that this requires both exponential cone and positive semidefinite * constraint. */ void MatrixLogDeterminantLower(const SolverInterface& solver, double tol); } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/mixed_integer_optimization_test.cc
#include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/gurobi_solver.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/mosek_solver.h" #include "drake/solvers/test/add_solver_util.h" #include "drake/solvers/test/mathematical_program_test_util.h" namespace drake { namespace solvers { namespace test { namespace { void GetMixedIntegerLinearProgramSolvers( std::list<std::unique_ptr<SolverInterface>>* solvers) { AddSolverIfAvailable<GurobiSolver>(solvers); AddSolverIfAvailable<MosekSolver>(solvers); } } // namespace // Take the example from Gurobi manual // https://www.gurobi.com/documentation/8.0/examples/mip1_c_c.html // min -x(0) - x(1) - 2*x(2) // s.t -inf <= x(0) + 2x(1) + 3*x(2) <= 4 // 1 <= x(0) + x(1) <= inf // x(0), x(1), x(2) are binary // The optimal solution is x(0) = 1, x(1) = 0, x(2) = 1; GTEST_TEST(TestMixedIntegerOptimization, TestMixedIntegerLinearProgram1) { std::list<std::unique_ptr<SolverInterface>> solvers; GetMixedIntegerLinearProgramSolvers(&solvers); for (const auto& solver : solvers) { MathematicalProgram prog; auto x = prog.NewBinaryVariables(3, "x"); Eigen::Vector3d c(-1, -1, -2); prog.AddLinearCost(c, x); Eigen::RowVector3d a1(1, 2, 3); prog.AddLinearConstraint(a1, -std::numeric_limits<double>::infinity(), 4, x); Eigen::RowVector2d a2(1, 1); prog.AddLinearConstraint(a2, 1, std::numeric_limits<double>::infinity(), x.head<2>()); const MathematicalProgramResult result = RunSolver(prog, *solver); Eigen::Vector3d x_expected(1, 0, 1); const auto& x_value = result.GetSolution(x); EXPECT_TRUE(CompareMatrices(x_value, x_expected, 1E-6, MatrixCompareType::absolute)); } } // Take the example from // http://www.cs.cmu.edu/~zkolter/course/15-780-s14/mip.pdf // min 2*z1 + z2 - 2*z3 // s.t 0.7*z1 + 0.5*z2+z3 >= 1.8 // z1, z2, z3 are integers. // The optimal solution is (1, 1, 1) GTEST_TEST(TestMixedIntegerOptimization, TestMixedIntegerLinearProgram2) { std::list<std::unique_ptr<SolverInterface>> solvers; GetMixedIntegerLinearProgramSolvers(&solvers); for (const auto& solver : solvers) { MathematicalProgram prog; auto x = prog.NewBinaryVariables<3>("x"); Eigen::Vector3d c(2, 1, -2); prog.AddLinearCost(c, x); Eigen::RowVector3d a1(0.7, 0.5, 1); prog.AddLinearConstraint(a1, 1.8, std::numeric_limits<double>::infinity(), x); const MathematicalProgramResult result = RunSolver(prog, *solver); Eigen::Vector3d x_expected(1, 1, 1); const auto& x_value = result.GetSolution(x); EXPECT_TRUE(CompareMatrices(x_value, x_expected, 1E-6, MatrixCompareType::absolute)); } } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/indeterminate_test.cc
#include "drake/solvers/indeterminate.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { namespace solvers { namespace test { using drake::symbolic::test::VarEqual; GTEST_TEST(TestIndeterminates, TestIndeterminatesListRef) { symbolic::Variable x1("x1"); symbolic::Variable x2("x2"); symbolic::Variable x3("x3"); symbolic::Variable x4("x4"); VectorIndeterminate<2> x_vec1(x3, x1); VectorIndeterminate<2> x_vec2(x2, x4); IndeterminatesRefList var_list{x_vec1, x_vec2}; VectorXIndeterminate stacked_vars = ConcatenateIndeterminatesRefList(var_list); EXPECT_EQ(stacked_vars.rows(), 4); EXPECT_PRED2(VarEqual, stacked_vars(0), x3); EXPECT_PRED2(VarEqual, stacked_vars(1), x1); EXPECT_PRED2(VarEqual, stacked_vars(2), x2); EXPECT_PRED2(VarEqual, stacked_vars(3), x4); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/solver_id_test.cc
#include "drake/solvers/solver_id.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/limit_malloc.h" namespace drake { namespace solvers { namespace { using test::LimitMalloc; GTEST_TEST(SolverId, Equality) { // An ID is equal to itself. // Use the EQ/NE form here to make sure gtest error reporting compiles okay. SolverId foo{"foo"}; EXPECT_EQ(foo, foo); EXPECT_NE(foo, SolverId{"bar"}); // Named objects are equal per their assigned IDs; same name is not enough. // Use the op==/op!= form here to be clear which operators are being tested. EXPECT_FALSE(SolverId{"x"} == SolverId{"x"}); EXPECT_TRUE(SolverId{"x"} != SolverId{"x"}); EXPECT_FALSE(SolverId{"a"} == SolverId{"b"}); EXPECT_TRUE(SolverId{"a"} != SolverId{"b"}); } GTEST_TEST(SolverId, Copy) { // Copies of objects are equal to each other. SolverId foo{"foo"}; EXPECT_TRUE(foo == foo); EXPECT_FALSE(foo != foo); SolverId foo2{foo}; EXPECT_TRUE(foo == foo2); EXPECT_FALSE(foo != foo2); } GTEST_TEST(SolverId, Move) { // Moved-from IDs become empty. SolverId old_bar{"bar"}; SolverId new_bar{std::move(old_bar)}; EXPECT_EQ(old_bar.name(), ""); EXPECT_EQ(new_bar.name(), "bar"); EXPECT_NE(new_bar, old_bar); } GTEST_TEST(SolverId, NoHeap) { // Solver names that are <= 15 characters do not allocate. LimitMalloc guard; SolverId foo{"123456789012345"}; SolverId bar(foo); } GTEST_TEST(SolverId, WarningForVeryLongName) { // Solver names that are > 15 characters will warn. // We'll just make sure nothing crashes. SolverId foo{"this_solver_name_is_way_too_long"}; } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/generic_trivial_constraints.h
#pragma once #include <cstddef> #include <limits> #include "drake/common/autodiff.h" #include "drake/common/drake_assert.h" #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/math/autodiff.h" #include "drake/solvers/constraint.h" #include "drake/solvers/function.h" namespace drake { namespace solvers { namespace test { // A generic constraint derived from Constraint class. This is meant for testing // adding a constraint to optimization program. // -1 <= x(0) * x(1) + x(2) / x(0) * private_val <= 2 // -2 <= x(1) * x(2) - x(0) <= 1 // This constraint stores that private_val internally, to detect object slicing. class GenericTrivialConstraint1 : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GenericTrivialConstraint1) GenericTrivialConstraint1() : Constraint(2, 3, Eigen::Vector2d(-1, -2), Eigen::Vector2d(2, 1)), private_val_{2} {} protected: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { DoEvalGeneric(x, y); } private: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const { y->resize(2); (*y)(0) = x(0) * x(1) + x(2) / x(0) * private_val_; (*y)(1) = x(1) * x(2) - x(0); } // Add a private data member to make sure no slicing on this class, derived // from Constraint. double private_val_{0}; }; } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/snopt_solver_test.cc
#include "drake/solvers/snopt_solver.h" #include <filesystem> #include <fstream> #include <iostream> #include <regex> #include <thread> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/find_resource.h" #include "drake/common/temp_directory.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/math/rotation_matrix.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/test/linear_program_examples.h" #include "drake/solvers/test/mathematical_program_test_util.h" #include "drake/solvers/test/optimization_examples.h" #include "drake/solvers/test/quadratic_program_examples.h" #include "drake/solvers/test/second_order_cone_program_examples.h" namespace drake { namespace solvers { namespace test { // SNOPT 7.6 has a known bug where it mis-handles the NIL terminator byte // when setting an debug log filename. This is fixed in newer releases. // Ideally we would add this function to the asan blacklist, but SNOPT // doesn't have symbols so we'll just disable any test code that uses the // "Print file" option. #if __has_feature(address_sanitizer) or defined(__SANITIZE_ADDRESS__) constexpr bool kUsingAsan = true; #else constexpr bool kUsingAsan = false; #endif TEST_P(LinearProgramTest, TestLP) { SnoptSolver solver; prob()->RunProblem(&solver); } INSTANTIATE_TEST_SUITE_P( SnoptTest, LinearProgramTest, ::testing::Combine(::testing::ValuesIn(linear_cost_form()), ::testing::ValuesIn(linear_constraint_form()), ::testing::ValuesIn(linear_problems()))); TEST_F(InfeasibleLinearProgramTest0, TestSnopt) { prog_->SetInitialGuessForAllVariables(Eigen::Vector2d(1, 2)); SnoptSolver solver; if (solver.available() && solver.enabled()) { auto result = solver.Solve(*prog_, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kInfeasibleConstraints); } } TEST_F(UnboundedLinearProgramTest0, TestSnopt) { prog_->SetInitialGuessForAllVariables(Eigen::Vector2d::Zero()); SnoptSolver solver; if (solver.available() && !solver.is_bounded_lp_broken()) { auto result = solver.Solve(*prog_, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded); EXPECT_EQ(result.get_optimal_cost(), -std::numeric_limits<double>::infinity()); } } TEST_F(DuplicatedVariableLinearProgramTest1, Test) { SnoptSolver solver; if (solver.available() && solver.enabled()) { CheckSolution(solver); } } TEST_P(QuadraticProgramTest, TestQP) { SnoptSolver solver; prob()->RunProblem(&solver); } INSTANTIATE_TEST_SUITE_P( SnoptTest, QuadraticProgramTest, ::testing::Combine(::testing::ValuesIn(quadratic_cost_form()), ::testing::ValuesIn(linear_constraint_form()), ::testing::ValuesIn(quadratic_problems()))); GTEST_TEST(QPtest, TestUnitBallExample) { SnoptSolver solver; if (solver.available() && solver.enabled()) { TestQPonUnitBallExample(solver); } } GTEST_TEST(SnoptTest, NameTest) { EXPECT_EQ(SnoptSolver::id().name(), "SNOPT"); } GTEST_TEST(SnoptTest, TestSetOption) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); // Solve a program // min x(0) + x(1) + x(2) // s.t xᵀx=1 prog.AddLinearCost(x.cast<symbolic::Expression>().sum()); prog.AddConstraint( std::make_shared<QuadraticConstraint>(2 * Eigen::Matrix3d::Identity(), Eigen::Vector3d::Zero(), 1, 1), x); // Arbitrary initial guess. Eigen::VectorXd x_init(3); x_init << 10, 20, 30; prog.SetInitialGuess(x, x_init); SnoptSolver solver; // Make sure the default setting can solve the problem. auto result = solver.Solve(prog, x_init, {}); EXPECT_TRUE(result.is_success()); SnoptSolverDetails solver_details = result.get_solver_details<SnoptSolver>(); EXPECT_TRUE(CompareMatrices(solver_details.F, Eigen::Vector2d(-std::sqrt(3), 1), 1E-6)); // The program is infeasible after one major iteration. prog.SetSolverOption(SnoptSolver::id(), "Major iterations limit", 1); solver.Solve(prog, x_init, {}, &result); EXPECT_EQ(result.get_solution_result(), SolutionResult::kIterationLimit); // This exit condition is defined in Snopt user guide. const int kMajorIterationLimitReached = 32; solver_details = result.get_solver_details<SnoptSolver>(); EXPECT_EQ(solver_details.info, kMajorIterationLimitReached); EXPECT_EQ(solver_details.xmul.size(), 3); EXPECT_EQ(solver_details.Fmul.size(), 2); EXPECT_EQ(solver_details.F.size(), 2); } GTEST_TEST(SnoptTest, TestPrintFile) { if (kUsingAsan) { std::cerr << "Skipping TestPrintFile under ASAN\n"; return; } MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint(x(0) + x(1) == 1); // This is to verify we can set the print out file through solver specific // option. const SnoptSolver solver; { const std::string print_file = temp_directory() + "/snopt.out"; EXPECT_FALSE(std::filesystem::exists({print_file})); SolverOptions solver_options; solver_options.SetOption(SnoptSolver::id(), "Print file", print_file); const auto result = solver.Solve(prog, {}, solver_options); EXPECT_TRUE(result.is_success()); EXPECT_TRUE(std::filesystem::exists({print_file})); } // This is to verify we can set the print out file through CommonSolverOption. { const std::string print_file_common = temp_directory() + "/snopt_common.out"; EXPECT_FALSE(std::filesystem::exists({print_file_common})); SolverOptions solver_options; solver_options.SetOption(CommonSolverOption::kPrintFileName, print_file_common); const auto result = solver.Solve(prog, {}, solver_options); EXPECT_TRUE(result.is_success()); EXPECT_TRUE(std::filesystem::exists({print_file_common})); } // Now set the solver option with both CommonSolverOption and solver specific // option. The solver specific option should win. { const std::string print_file_common = temp_directory() + "/snopt_common2.out"; const std::string print_file = temp_directory() + "/snopt2.out"; SolverOptions solver_options; solver_options.SetOption(solver.id(), "Print file", print_file); solver_options.SetOption(CommonSolverOption::kPrintFileName, print_file_common); EXPECT_FALSE(std::filesystem::exists({print_file_common})); EXPECT_FALSE(std::filesystem::exists({print_file})); solver.Solve(prog, {}, solver_options); EXPECT_TRUE(std::filesystem::exists({print_file})); EXPECT_FALSE(std::filesystem::exists({print_file_common})); } } GTEST_TEST(SnoptTest, TestStringOption) { const SnoptSolver solver; MathematicalProgram prog_minimize; const auto x_minimize = prog_minimize.NewContinuousVariables<1>(); prog_minimize.AddLinearConstraint(x_minimize(0) <= 1); prog_minimize.AddLinearConstraint(x_minimize(0) >= -1); prog_minimize.AddLinearCost(x_minimize(0)); prog_minimize.SetSolverOption(SnoptSolver::id(), "Minimize", ""); auto result_minimize = solver.Solve(prog_minimize, {}, {}); EXPECT_EQ(result_minimize.get_optimal_cost(), -1); MathematicalProgram prog_maximize; const auto x_maximize = prog_maximize.NewContinuousVariables<1>(); prog_maximize.AddLinearConstraint(x_maximize(0) <= 1); prog_maximize.AddLinearConstraint(x_maximize(0) >= -1); prog_maximize.AddLinearCost(x_maximize(0)); prog_maximize.SetSolverOption(SnoptSolver::id(), "Maximize", ""); auto result_maximize = solver.Solve(prog_maximize, {}, {}); EXPECT_EQ(result_maximize.get_optimal_cost(), 1); } GTEST_TEST(SnoptTest, TestSparseCost) { // Test nonlinear optimization problem, whose cost has sparse gradient. MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); // No cost, just constraint. prog.AddLinearConstraint(x(0) + x(1) + x(2) == 1); SnoptSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); const double tol{1E-5}; EXPECT_NEAR(result.GetSolution(x).sum(), 1, tol); EXPECT_EQ(result.get_optimal_cost(), 0); // Add a cost on x(1) only // min x(1) * x(1). // s.t x(0) + x(1) + x(2) = 1 prog.AddQuadraticCost(x(1) * x(1)); solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); EXPECT_NEAR(result.GetSolution(x(1)), 0, tol); EXPECT_NEAR(result.GetSolution(x).sum(), 1, tol); EXPECT_NEAR(result.get_optimal_cost(), 0, tol); // Add another cost on x(1) and x(2) // min x(1) * x(1) + 2 * x(1) + x(2) * x(2) - 2 * x(2) + 1 // s.t x(0) + x(1) + x(2) = 1 prog.AddQuadraticCost(2 * x(1) + x(2) * x(2) - 2 * x(2) + 1); solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.GetSolution(x), Eigen::Vector3d(1, -1, 1), tol)); EXPECT_NEAR(result.get_optimal_cost(), -1, tol); } GTEST_TEST(SnoptTest, DistanceToTetrahedron) { // This test fails in SNOPT 7.6 using C interface, but succeeds in SNOPT // 7.4.11 with f2c interface. const double distance_expected = 0.2; DistanceToTetrahedronExample prog(distance_expected); Eigen::Matrix<double, 18, 1> x0; x0 << 0, 0, 0, 0.7, 0.8, 0.9, 0.1, 0.2, 0.3, 1, 1, 1, 1, 0.4, 0.5, 0.6, 1.1, 1.2; // Setting x0(6) = 0.7 would enable SNOPT 7.6 to succeed. prog.SetInitialGuessForAllVariables(x0); SnoptSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); const auto x_sol = result.GetSolution(prog.x()); const Eigen::Vector3d p_WB_sol = x_sol.head<3>(); const Eigen::Vector3d p_WQ_sol = x_sol.segment<3>(3); const Eigen::Vector3d n_W_sol = x_sol.segment<3>(6); const Eigen::Vector4d quat_WB_sol = x_sol.segment<4>(9); const Eigen::Vector3d p_WP_sol = x_sol.segment<3>(13); const double tol = 1E-6; EXPECT_NEAR(n_W_sol.norm(), 1, tol); EXPECT_NEAR(quat_WB_sol.norm(), 1, tol); EXPECT_NEAR((p_WP_sol - p_WQ_sol).norm(), distance_expected, tol); const Eigen::Quaterniond quaternion_WB_sol(quat_WB_sol(0), quat_WB_sol(1), quat_WB_sol(2), quat_WB_sol(3)); const math::RotationMatrixd R_WB(quaternion_WB_sol); const Eigen::Vector3d p_BQ = R_WB.transpose() * (p_WQ_sol - p_WB_sol); EXPECT_TRUE( ((prog.A_tetrahedron() * p_BQ).array() <= prog.b_tetrahedron().array()) .all()); } // Test if we can run several snopt solvers simultaneously on multiple threads. // We create a convex QP problem with a unique global optimal, starting from // different initial guesses, snopt should output the same result. // min (x₀-1)² + (x₁-2)² // s.t x₀ + x₁ = 1 // The optimal solution is x*=(0, 1) GTEST_TEST(SnoptTest, MultiThreadTest) { // Formulate the problem (shared by all threads). MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); const Eigen::Vector2d c(1, 2); prog.AddQuadraticCost((x - c).squaredNorm()); prog.AddLinearConstraint(x(0) + x(1) == 1); const MathematicalProgram& const_prog = prog; // Each thread will have its own distinct data. struct PerThreadData { // Input Eigen::Vector2d x_init; std::string print_file; // Output MathematicalProgramResult result; }; // We first will solve each guess one at a time, and then solve them all in // parallel. The two sets of results should match. const int num_threads = 10; std::vector<PerThreadData> single_threaded(num_threads); std::vector<PerThreadData> multi_threaded(num_threads); // Set up the arbitrary initial guesses and print file names. const std::string temp_dir = temp_directory(); for (int i = 0; i < num_threads; ++i) { const Eigen::Vector2d guess_i(i + 1, (i - 2.0) / 10); single_threaded[i].x_init = guess_i; multi_threaded[i].x_init = guess_i; single_threaded[i].print_file = fmt::format("{}/snopt_single_thread_{}.out", temp_dir, i); multi_threaded[i].print_file = fmt::format("{}/snopt_multi_thread_{}.out", temp_dir, i); } if (kUsingAsan) { std::cerr << "Not checking 'Print file' option under ASAN\n"; } // Create a functor that solves the problem. const SnoptSolver snopt_solver; auto run_solver = [&snopt_solver, &const_prog](PerThreadData* thread_data) { SolverOptions options; if (!kUsingAsan) { options.SetOption(SnoptSolver::id(), "Print file", thread_data->print_file); } snopt_solver.Solve(const_prog, {thread_data->x_init}, options, &thread_data->result); }; // Solve without using threads. for (int i = 0; i < num_threads; ++i) { run_solver(&single_threaded[i]); } // Solve using threads. std::vector<std::thread> test_threads; for (int i = 0; i < num_threads; ++i) { test_threads.emplace_back(run_solver, &multi_threaded[i]); } for (int i = 0; i < num_threads; ++i) { test_threads[i].join(); } // All solutions should be the same. for (int i = 0; i < num_threads; ++i) { // The MathematicalProgramResult should meet tolerances. for (const auto& per_thread_data_vec : {single_threaded, multi_threaded}) { const auto& result = per_thread_data_vec[i].result; EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.get_x_val(), Eigen::Vector2d(0, 1), 1E-6)); EXPECT_NEAR(result.get_optimal_cost(), 2, 1E-6); EXPECT_EQ(result.get_solver_details<SnoptSolver>().info, 1); } if (!kUsingAsan) { // The print file contents should be the same for single vs multi. std::string contents_single = ReadFileOrThrow(single_threaded[i].print_file); std::string contents_multi = ReadFileOrThrow(multi_threaded[i].print_file); for (auto* contents : {&contents_single, &contents_multi}) { // Scrub some volatile text output. *contents = std::regex_replace(*contents, std::regex("..... seconds"), "##### seconds"); *contents = std::regex_replace( *contents, std::regex(".Printer........................\\d"), "(Printer).............. ####"); } EXPECT_EQ(contents_single, contents_multi); } } } class AutoDiffOnlyCost final : public drake::solvers::Cost { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(AutoDiffOnlyCost) AutoDiffOnlyCost() : drake::solvers::Cost(1) {} private: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { throw std::runtime_error("Does not support Eval with double."); } void DoEval(const Eigen::Ref<const drake::AutoDiffVecXd>& x, drake::AutoDiffVecXd* y) const override { (*y)(0) = x(0) * x(0) + 1; } void DoEval( const Eigen::Ref<const drake::VectorX<drake::symbolic::Variable>>& x, drake::VectorX<drake::symbolic::Expression>* y) const override { throw std::runtime_error("Does not support Eval with Expression."); } }; GTEST_TEST(SnoptTest, AutoDiffOnlyCost) { // Test a problem whose Cost only supports DoEval with AutoDiff. This helps // reassure us that in our snopt_solver.cc bindings when we are extracting // the GetOptimialCost result that we don't redundantly evaluate the cost // again at the solution, but rather that we fetch the objective value // directly at the last iteration before convergence. (An work-in-progress // draft of the snopt_solver bindings once exhibited such a bug.) MathematicalProgram prog; auto x = prog.NewContinuousVariables<1>(); prog.AddLinearConstraint(2 * x(0) >= 2); prog.AddCost(std::make_shared<AutoDiffOnlyCost>(), x); SnoptSolver solver; if (solver.available() && solver.enabled()) { auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); const double tol = 1E-6; EXPECT_NEAR(result.get_optimal_cost(), 2, tol); EXPECT_TRUE( CompareMatrices(result.GetSolution(x), drake::Vector1d(1), tol)); } } GTEST_TEST(SnoptTest, VariableScaling1) { // Linear cost and bounding box constraint MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint(x(0) >= -1000000000000); prog.AddLinearConstraint(x(1) >= -0.0001); prog.AddLinearCost(Eigen::Vector2d(1, 1), x); prog.SetVariableScaling(x(0), 1000000000000); prog.SetVariableScaling(x(1), 0.0001); SnoptSolver solver; if (solver.available() && solver.enabled()) { auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); const double tol = 1E-6; EXPECT_NEAR(result.get_optimal_cost(), -1000000000000.0001, tol); EXPECT_TRUE(CompareMatrices(result.GetSolution(x), Eigen::Vector2d(-1000000000000, -0.0001), tol)); } } GTEST_TEST(SnoptTest, VariableScaling2) { // Quadractic cost, linear and quadratic constraints double s = 100; MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint(4 * x(0) / s - 3 * x(1) >= 0); Eigen::Matrix2d Q = Eigen::Matrix2d::Identity(); Q(0, 0) /= (s * s); prog.AddConstraint(std::make_shared<QuadraticConstraint>( 2 * Q, Eigen::Vector2d::Zero(), 25, 25), x); prog.AddQuadraticCost((x(0) / s + 2) * (x(0) / s + 2)); prog.AddQuadraticCost((x(1) + 2) * (x(1) + 2)); prog.SetVariableScaling(x(0), s); SnoptSolver solver; if (solver.available() && solver.enabled()) { auto result = solver.Solve(prog, Eigen::Vector2d(1 * s, -1), {}); EXPECT_TRUE(result.is_success()); const double tol = 1E-6; EXPECT_NEAR(result.get_optimal_cost(), 5, tol); EXPECT_TRUE(CompareMatrices(result.GetSolution(x), Eigen::Vector2d(-3 * s, -4), tol)); } } GTEST_TEST(SnoptSolverTest, QPDualSolution1) { SnoptSolver solver; TestQPDualSolution1(solver, {} /* solver_options */, 1e-5); } GTEST_TEST(SnoptSolverTest, QPDualSolution2) { SnoptSolver solver; TestQPDualSolution2(solver); } GTEST_TEST(SnoptSolverTest, QPDualSolution3) { SnoptSolver solver; TestQPDualSolution3(solver); } GTEST_TEST(SnoptSolverTest, EqualityConstrainedQPDualSolution1) { SnoptSolver solver; TestEqualityConstrainedQPDualSolution1(solver); } GTEST_TEST(SnoptSolverTest, EqualityConstrainedQPDualSolution2) { SnoptSolver solver; TestEqualityConstrainedQPDualSolution2(solver); } GTEST_TEST(SnoptTest, TestLPDualSolution2) { SnoptSolver solver; TestLPDualSolution2(solver); } GTEST_TEST(SnoptTest, TestLPDualSolution2Scaled) { SnoptSolver solver; TestLPDualSolution2Scaled(solver); } GTEST_TEST(SnoptTest, TestLPDualSolution3) { SnoptSolver solver; TestLPDualSolution3(solver); } GTEST_TEST(SnoptTest, TestLPDualSolution4) { SnoptSolver solver; TestLPDualSolution4(solver); } GTEST_TEST(SnoptTest, TestLPDualSolution5) { SnoptSolver solver; TestLPDualSolution5(solver); } GTEST_TEST(SnoptSolverTest, EckhardtDualSolution) { SnoptSolver solver; TestEckhardtDualSolution(solver, Eigen::Vector3d(1., 1., 5.)); } GTEST_TEST(SnoptSolverTest, BadIntegerParameter) { SnoptSolver solver; MathematicalProgram prog; prog.SetSolverOption(solver.solver_id(), "not an option", 15); DRAKE_EXPECT_THROWS_MESSAGE( solver.Solve(prog), "Error setting Snopt integer parameter not an option"); } GTEST_TEST(SnoptSolverTest, BadDoubleParameter) { SnoptSolver solver; MathematicalProgram prog; prog.SetSolverOption(solver.solver_id(), "not an option", 15.0); DRAKE_EXPECT_THROWS_MESSAGE( solver.Solve(prog), "Error setting Snopt double parameter not an option"); } GTEST_TEST(SnoptSolverTest, BadStringParameter) { SnoptSolver solver; MathematicalProgram prog; prog.SetSolverOption(solver.solver_id(), "not an option", "test"); DRAKE_EXPECT_THROWS_MESSAGE( solver.Solve(prog), "Error setting Snopt string parameter not an option"); } GTEST_TEST(SnoptSolverTest, TestNonconvexQP) { SnoptSolver solver; if (solver.available() && solver.enabled()) { TestNonconvexQP(solver, false); } } GTEST_TEST(SnoptSolverTest, TestL2NormCost) { SnoptSolver solver; TestL2NormCost(solver, 1e-6); } TEST_P(TestEllipsoidsSeparation, TestSOCP) { SnoptSolver snopt_solver; if (snopt_solver.available()) { SolveAndCheckSolution(snopt_solver, {}, 1.E-8); } } INSTANTIATE_TEST_SUITE_P( SnoptTest, TestEllipsoidsSeparation, ::testing::ValuesIn(GetEllipsoidsSeparationProblems())); TEST_P(TestQPasSOCP, TestSOCP) { SnoptSolver snopt_solver; if (snopt_solver.available() && snopt_solver.enabled()) { SolveAndCheckSolution(snopt_solver); } } INSTANTIATE_TEST_SUITE_P(SnoptTest, TestQPasSOCP, ::testing::ValuesIn(GetQPasSOCPProblems())); TEST_P(TestFindSpringEquilibrium, TestSOCP) { SnoptSolver snopt_solver; if (snopt_solver.available() && snopt_solver.enabled()) { SolveAndCheckSolution(snopt_solver, {}, 2E-3); } } INSTANTIATE_TEST_SUITE_P( SnoptTest, TestFindSpringEquilibrium, ::testing::ValuesIn(GetFindSpringEquilibriumProblems())); GTEST_TEST(TestSOCP, MaximizeGeometricMeanTrivialProblem1) { MaximizeGeometricMeanTrivialProblem1 prob; SnoptSolver solver; if (solver.available() && solver.enabled()) { const auto result = solver.Solve(prob.prog(), {}, {}); prob.CheckSolution(result, 4E-6); } } class ThrowCost final : public Cost { public: ThrowCost() : Cost(1, "ThrowCost") {} private: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const final { EvalGeneric(); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const final { EvalGeneric(); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const final { EvalGeneric(); } void EvalGeneric() const { throw std::runtime_error("ThrowCost::EvalGeneric"); } }; GTEST_TEST(SnoptTest, TestCostExceptionHandling) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<1>(); prog.AddCost(std::make_shared<ThrowCost>(), x); SnoptSolver solver; if (solver.available() && solver.enabled()) { DRAKE_EXPECT_THROWS_MESSAGE(solver.Solve(prog), "Exception.*SNOPT.*ThrowCost.*"); } } TEST_F(QuadraticEqualityConstrainedProgram1, test) { SnoptSolver solver; if (solver.available() && solver.enabled()) { CheckSolution(solver, Eigen::Vector2d(0.5, 0.8), std::nullopt, 1E-6); } } class SnoptSolverEnabledTest : public ::testing::Test { protected: void SetUp() override { ASSERT_TRUE(solver_.available()); ASSERT_EQ(::getenv("DRAKE_SNOPT_SOLVER_ENABLED"), nullptr); prog_.NewContinuousVariables<1>(); } void TearDown() override { EXPECT_EQ(::unsetenv("DRAKE_SNOPT_SOLVER_ENABLED"), 0); } MathematicalProgram prog_; SnoptSolver solver_; }; TEST_F(SnoptSolverEnabledTest, DefaultBehavior) { EXPECT_EQ(solver_.enabled(), true); EXPECT_NO_THROW(solver_.Solve(prog_)); } TEST_F(SnoptSolverEnabledTest, ExplicitlyDisabled) { EXPECT_EQ(solver_.enabled(), true); ASSERT_EQ(::setenv("DRAKE_SNOPT_SOLVER_ENABLED", "0", 1), 0); EXPECT_EQ(solver_.enabled(), false); DRAKE_EXPECT_THROWS_MESSAGE( solver_.Solve(prog_), ".*SnoptSolver has not been properly configured.*"); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/csdp_solver_internal_test.cc
#include "drake/solvers/csdp_solver_internal.h" #include <limits> #include <utility> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/test/csdp_test_examples.h" namespace drake { namespace solvers { namespace internal { void CompareBlockrec(const csdp::blockrec& block, csdp::blockcat blockcategory, int blocksize, const std::vector<double>& value, double tol) { EXPECT_EQ(block.blockcategory, blockcategory); EXPECT_EQ(block.blocksize, blocksize); if (blockcategory == csdp::blockcat::MATRIX) { for (int j = 0; j < blocksize; ++j) { for (int i = 0; i < blocksize; ++i) { EXPECT_NEAR(block.data.mat[ijtok(i + 1, j + 1, blocksize)], value[j * blocksize + i], tol); } } } else if (blockcategory == csdp::blockcat::DIAG) { for (int i = 0; i < blocksize; ++i) { EXPECT_NEAR(block.data.vec[i + 1], value[i], tol); } } else { throw std::invalid_argument("Unknown block category."); } } void CheckSparseblock(const csdp::sparseblock& block, const std::vector<Eigen::Triplet<double>>& block_entries, int blocknum, int blocksize, int constraintnum) { for (int i = 0; i < static_cast<int>(block_entries.size()); ++i) { EXPECT_EQ(block.entries[i + 1], block_entries[i].value()); EXPECT_EQ(block.iindices[i + 1], block_entries[i].row() + 1); EXPECT_EQ(block.jindices[i + 1], block_entries[i].col() + 1); EXPECT_EQ(block.numentries, static_cast<int>(block_entries.size())); EXPECT_EQ(block.blocknum, blocknum); EXPECT_EQ(block.blocksize, blocksize); EXPECT_EQ(block.constraintnum, constraintnum); } } TEST_F(SDPwithOverlappingVariables1, GenerateCsdpProblemDataWithoutFreeVariables) { const SdpaFreeFormat dut(*prog_); struct csdp::blockmatrix C_csdp; double* rhs_csdp; struct csdp::constraintmatrix* constraints{nullptr}; GenerateCsdpProblemDataWithoutFreeVariables(dut, &C_csdp, &rhs_csdp, &constraints); // Check the cost min 2 * x0 + x2 EXPECT_EQ(C_csdp.nblocks, 3); CompareBlockrec(C_csdp.blocks[1], csdp::MATRIX, 2, {-2, 0, 0, 0}, 0); CompareBlockrec(C_csdp.blocks[2], csdp::MATRIX, 2, {0, -0.5, -0.5, 0}, 0); CompareBlockrec(C_csdp.blocks[3], csdp::DIAG, 2, {0, 0}, 0); // Check the equality constraint from // [x0 x1] is psd // [x1 x0] struct csdp::sparseblock* blockptr = constraints[1].blocks; std::vector<Eigen::Triplet<double>> block_entries; block_entries.emplace_back(0, 0, 1); block_entries.emplace_back(1, 1, -1); CheckSparseblock(*blockptr, block_entries, 1, 2, 1); EXPECT_EQ(blockptr->next, nullptr); EXPECT_EQ(rhs_csdp[1], 0); // Check the equality constraint from // [x0 x2] is psd // [x2 x0] // The equality constraint X(0, 0) - X(2, 2) = 0 blockptr = constraints[2].blocks; block_entries.clear(); block_entries.emplace_back(0, 0, 1); CheckSparseblock(*blockptr, block_entries, 1, 2, 2); blockptr = blockptr->next; block_entries.clear(); block_entries.emplace_back(0, 0, -1); CheckSparseblock(*blockptr, block_entries, 2, 2, 2); EXPECT_EQ(blockptr->next, nullptr); EXPECT_EQ(rhs_csdp[2], 0); // The equality constraint X(0, 0) - X(3, 3) = 0 blockptr = constraints[3].blocks; block_entries.clear(); block_entries.emplace_back(0, 0, 1); CheckSparseblock(*blockptr, block_entries, 1, 2, 3); blockptr = blockptr->next; block_entries.clear(); block_entries.emplace_back(1, 1, -1); CheckSparseblock(*blockptr, block_entries, 2, 2, 3); EXPECT_EQ(blockptr->next, nullptr); EXPECT_EQ(rhs_csdp[3], 0); // The equality constraint x0 - X(4, 4) = 0.5 blockptr = constraints[4].blocks; block_entries.clear(); block_entries.emplace_back(0, 0, 1); CheckSparseblock(*blockptr, block_entries, 1, 2, 4); blockptr = blockptr->next; block_entries.clear(); block_entries.emplace_back(0, 0, -1); CheckSparseblock(*blockptr, block_entries, 3, 2, 4); EXPECT_EQ(blockptr->next, nullptr); EXPECT_EQ(rhs_csdp[4], 0.5); // The equality constraint x1 = 1 blockptr = constraints[5].blocks; block_entries.clear(); block_entries.emplace_back(0, 1, 0.5); CheckSparseblock(*blockptr, block_entries, 1, 2, 5); EXPECT_EQ(blockptr->next, nullptr); EXPECT_EQ(rhs_csdp[5], 1); // To impose the inequality constraint x2 <= 2, we add the equality constraint // x2 + X(5, 5) = 2 blockptr = constraints[6].blocks; block_entries.clear(); block_entries.emplace_back(0, 1, 0.5); CheckSparseblock(*blockptr, block_entries, 2, 2, 6); blockptr = blockptr->next; block_entries.clear(); block_entries.emplace_back(1, 1, 1); CheckSparseblock(*blockptr, block_entries, 3, 2, 6); EXPECT_EQ(blockptr->next, nullptr); EXPECT_EQ(rhs_csdp[6], 2); FreeCsdpProblemData(6, C_csdp, rhs_csdp, constraints); } TEST_F(CsdpDocExample, GenerateCsdpProblemDataWithoutFreeVariables) { const SdpaFreeFormat dut(*prog_); struct csdp::blockmatrix C_csdp; double* rhs_csdp; struct csdp::constraintmatrix* constraints{nullptr}; GenerateCsdpProblemDataWithoutFreeVariables(dut, &C_csdp, &rhs_csdp, &constraints); // Check the cost. EXPECT_EQ(C_csdp.nblocks, 3); CompareBlockrec(C_csdp.blocks[1], csdp::MATRIX, 2, {2, 1, 1, 2}, 0); CompareBlockrec(C_csdp.blocks[2], csdp::MATRIX, 3, {3, 0, 1, 0, 2, 0, 1, 0, 3}, 0); CompareBlockrec(C_csdp.blocks[3], csdp::DIAG, 2, {0, 0}, 0); // Check constraints. // Constraint 1. struct csdp::sparseblock* blockptr = constraints[1].blocks; std::vector<Eigen::Triplet<double>> block_entries; block_entries.emplace_back(0, 0, 3); block_entries.emplace_back(0, 1, 1); block_entries.emplace_back(1, 1, 3); CheckSparseblock(*blockptr, block_entries, 1, 2, 1); blockptr = blockptr->next; block_entries.clear(); block_entries.emplace_back(0, 0, 1); CheckSparseblock(*blockptr, block_entries, 3, 2, 1); EXPECT_EQ(blockptr->next, nullptr); EXPECT_EQ(rhs_csdp[1], 1); // Constraint 2. blockptr = constraints[2].blocks; block_entries.clear(); block_entries.emplace_back(0, 0, 3); block_entries.emplace_back(1, 1, 4); block_entries.emplace_back(0, 2, 1); block_entries.emplace_back(2, 2, 5); CheckSparseblock(*blockptr, block_entries, 2, 3, 2); blockptr = blockptr->next; block_entries.clear(); CheckSparseblock(*blockptr, block_entries, 3, 2, 2); EXPECT_EQ(blockptr->next, nullptr); block_entries.emplace_back(1, 1, 1); EXPECT_EQ(rhs_csdp[2], 2); FreeCsdpProblemData(2, C_csdp, rhs_csdp, constraints); } TEST_F(TrivialSDP1, GenerateCsdpProblemDataWithoutFreeVariables) { const SdpaFreeFormat dut(*prog_); struct csdp::blockmatrix C_csdp; double* rhs_csdp; struct csdp::constraintmatrix* constraints{nullptr}; GenerateCsdpProblemDataWithoutFreeVariables(dut, &C_csdp, &rhs_csdp, &constraints); /** * A trivial SDP * max X1(0, 1) + X1(1, 2) * s.t X1 ∈ ℝ³ˣ³ is psd * X1(0, 0) + X1(1, 1) + X1(2, 2) = 1 * X1(0, 1) + X1(1, 2) - 2 * X1(0, 2) <= 0 */ // Check the cost EXPECT_EQ(C_csdp.nblocks, 2); CompareBlockrec(C_csdp.blocks[1], csdp::MATRIX, 3, {0, 0.5, 0, 0.5, 0, 0.5, 0, 0.5, 0}, 0); CompareBlockrec(C_csdp.blocks[2], csdp::DIAG, 1, {0}, 0); // Check the constraint X1(0, 0) + X1(1, 1) + X1(2, 2) = 1 struct csdp::sparseblock* blockptr = constraints[1].blocks; std::vector<Eigen::Triplet<double>> block_entries; block_entries.emplace_back(0, 0, 1); block_entries.emplace_back(1, 1, 1); block_entries.emplace_back(2, 2, 1); CheckSparseblock(*blockptr, block_entries, 1, 3, 1); EXPECT_EQ(blockptr->next, nullptr); EXPECT_EQ(rhs_csdp[1], 1); // Check the constraint X1(0, 1) + X1(1, 2) - 2 * X1(0, 2) <= 0 blockptr = constraints[2].blocks; block_entries.clear(); block_entries.emplace_back(0, 1, 0.5); block_entries.emplace_back(0, 2, -1); block_entries.emplace_back(1, 2, 0.5); CheckSparseblock(*blockptr, block_entries, 1, 3, 2); blockptr = blockptr->next; block_entries.clear(); block_entries.emplace_back(0, 0, 1); CheckSparseblock(*blockptr, block_entries, 2, 1, 2); EXPECT_EQ(blockptr->next, nullptr); EXPECT_EQ(rhs_csdp[2], 0); FreeCsdpProblemData(2, C_csdp, rhs_csdp, constraints); } TEST_F(SDPwithOverlappingVariables1, Solve) { const SdpaFreeFormat dut(*prog_); csdp::blockmatrix C; double* rhs; csdp::constraintmatrix* constraints{nullptr}; GenerateCsdpProblemDataWithoutFreeVariables(dut, &C, &rhs, &constraints); struct csdp::blockmatrix X, Z; double* y; csdp::cpp_initsoln(dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, &X, &y, &Z); double pobj, dobj; const int ret = csdp::cpp_easy_sdp( nullptr, dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, -dut.constant_min_cost_term(), &X, &y, &Z, &pobj, &dobj); EXPECT_EQ(ret, 0 /* 0 is for success */); const double tol = 1E-7; EXPECT_NEAR(pobj, -1, tol); EXPECT_NEAR(dobj, -1, tol); // Check the value of X EXPECT_EQ(X.nblocks, 3); CompareBlockrec(X.blocks[1], csdp::MATRIX, 2, {1, 1, 1, 1}, tol); CompareBlockrec(X.blocks[2], csdp::MATRIX, 2, {1, -1, -1, 1}, tol); CompareBlockrec(X.blocks[3], csdp::DIAG, 2, {0.5, 3}, tol); csdp::cpp_free_prob(dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, X, y, Z); } TEST_F(SDPwithOverlappingVariables2, Solve) { const SdpaFreeFormat dut(*prog_); csdp::blockmatrix C; double* rhs; csdp::constraintmatrix* constraints{nullptr}; GenerateCsdpProblemDataWithoutFreeVariables(dut, &C, &rhs, &constraints); struct csdp::blockmatrix X, Z; double* y; csdp::cpp_initsoln(dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, &X, &y, &Z); double pobj, dobj; const int ret = csdp::cpp_easy_sdp( nullptr, dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, -dut.constant_min_cost_term(), &X, &y, &Z, &pobj, &dobj); EXPECT_EQ(ret, 0 /* 0 is for success */); const double tol = 1E-7; EXPECT_NEAR(pobj, -5, tol); EXPECT_NEAR(dobj, -5, tol); // Check the value of X EXPECT_EQ(X.nblocks, 2); CompareBlockrec(X.blocks[1], csdp::MATRIX, 2, {2, 1, 1, 2}, tol); CompareBlockrec(X.blocks[2], csdp::DIAG, 3, {0, 1, 0}, tol); csdp::cpp_free_prob(dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, X, y, Z); } TEST_F(CsdpDocExample, Solve) { const SdpaFreeFormat dut(*prog_); csdp::blockmatrix C; double* rhs; csdp::constraintmatrix* constraints{nullptr}; GenerateCsdpProblemDataWithoutFreeVariables(dut, &C, &rhs, &constraints); struct csdp::blockmatrix X, Z; double* y; csdp::cpp_initsoln(dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, &X, &y, &Z); double pobj, dobj; const int ret = csdp::cpp_easy_sdp( nullptr, dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, -dut.constant_min_cost_term(), &X, &y, &Z, &pobj, &dobj); EXPECT_EQ(ret, 0 /* 0 is for success */); const double tol = 5E-7; EXPECT_NEAR(pobj, 2.75, tol); EXPECT_NEAR(y[1], 0.75, tol); EXPECT_NEAR(y[2], 1, tol); EXPECT_EQ(X.nblocks, 3); CompareBlockrec(X.blocks[1], csdp::MATRIX, 2, {0.125, 0.125, 0.125, 0.125}, tol); CompareBlockrec(X.blocks[2], csdp::MATRIX, 3, {2.0 / 3, 0, 0, 0, 0, 0, 0, 0, 0}, tol); CompareBlockrec(X.blocks[3], csdp::DIAG, 2, {0, 0}, tol); EXPECT_EQ(Z.nblocks, 3); CompareBlockrec(Z.blocks[1], csdp::MATRIX, 2, {0.25, -0.25, -0.25, 0.25}, tol); CompareBlockrec(Z.blocks[2], csdp::MATRIX, 3, {0, 0, 0, 0, 2, 0, 0, 0, 2}, tol); CompareBlockrec(Z.blocks[3], csdp::DIAG, 2, {0.75, 1}, tol); csdp::cpp_free_prob(dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, X, y, Z); } TEST_F(TrivialSDP1, Solve) { const SdpaFreeFormat dut(*prog_); csdp::blockmatrix C; double* rhs; csdp::constraintmatrix* constraints{nullptr}; GenerateCsdpProblemDataWithoutFreeVariables(dut, &C, &rhs, &constraints); struct csdp::blockmatrix X, Z; double* y; csdp::cpp_initsoln(dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, &X, &y, &Z); double pobj, dobj; const int ret = csdp::cpp_easy_sdp( nullptr, dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, -dut.constant_min_cost_term(), &X, &y, &Z, &pobj, &dobj); EXPECT_EQ(ret, 0 /* 0 is for success */); csdp::cpp_free_prob(dut.num_X_rows(), dut.g().rows(), C, rhs, constraints, X, y, Z); } } // namespace internal } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/nonlinear_program_test.cc
#include <array> // std::array #include <functional> // std::function #include <limits> // std::numeric_limits #include <map> // std::map #include <memory> // std::shared_ptr #include <stdexcept> // std::runtime_error #include <utility> // std::pair #include <vector> // std::vector #include <fmt/format.h> #include <gtest/gtest.h> #include "drake/common/drake_assert.h" #include "drake/common/drake_copyable.h" #include "drake/common/polynomial.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/test_utilities/is_dynamic_castable.h" #include "drake/solvers/constraint.h" #include "drake/solvers/ipopt_solver.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/nlopt_solver.h" #include "drake/solvers/snopt_solver.h" #include "drake/solvers/solver_interface.h" #include "drake/solvers/test/mathematical_program_test_util.h" #include "drake/solvers/test/optimization_examples.h" using Eigen::Matrix; using Eigen::Matrix2d; using Eigen::Matrix4d; using Eigen::MatrixXd; using Eigen::Vector2d; using Eigen::Vector3d; using Eigen::Vector4d; using Eigen::VectorXd; using drake::solvers::internal::VecIn; using drake::solvers::internal::VecOut; using std::numeric_limits; namespace drake { namespace solvers { namespace test { void RunNonlinearProgram(const MathematicalProgram& prog, const std::optional<Eigen::VectorXd>& x_init, std::function<void(void)> test_func, MathematicalProgramResult* result) { IpoptSolver ipopt_solver; NloptSolver nlopt_solver; SnoptSolver snopt_solver; std::pair<const char*, SolverInterface*> solvers[] = { std::make_pair("SNOPT", &snopt_solver), std::make_pair("NLopt", &nlopt_solver), std::make_pair("Ipopt", &ipopt_solver)}; for (const auto& solver : solvers) { SCOPED_TRACE(fmt::format("Using solver: {}", solver.first)); if (!(solver.second->available() && solver.second->enabled())) { continue; } DRAKE_ASSERT_NO_THROW(solver.second->Solve(prog, x_init, {}, result)); EXPECT_TRUE(result->is_success()); DRAKE_EXPECT_NO_THROW(test_func()); } } GTEST_TEST(testNonlinearProgram, BoundingBoxTest) { // A simple test program to test if the bounding box constraints are added // correctly. MathematicalProgram prog; auto x = prog.NewContinuousVariables(4); // Deliberately add two constraints on overlapped decision variables. // For x(1), the lower bound of the second constraint are used; while // the upper bound of the first variable is used. VectorDecisionVariable<2> variable_vec(x(1), x(3)); prog.AddBoundingBoxConstraint(Vector2d(-1, -2), Vector2d(-0.2, -1), variable_vec); prog.AddBoundingBoxConstraint(Vector3d(-1, -0.5, -3), Vector3d(2, 1, -0.1), {x.head<1>(), x.segment<2>(1)}); Vector4d lb(-1, -0.5, -3, -2); Vector4d ub(2, -0.2, -0.1, -1); const Eigen::VectorXd x_init = Eigen::Vector4d::Zero(); prog.SetInitialGuessForAllVariables(Vector4d::Zero()); MathematicalProgramResult result; RunNonlinearProgram( prog, x_init, [&]() { const auto& x_value = result.GetSolution(x); for (int i = 0; i < 4; ++i) { EXPECT_GE(x_value(i), lb(i) - 1E-10); EXPECT_LE(x_value(i), ub(i) + 1E-10); } }, &result); } GTEST_TEST(testNonlinearProgram, trivialLinearSystem) { LinearSystemExample1 example1{}; MathematicalProgramResult result; RunNonlinearProgram( *(example1.prog()), Eigen::VectorXd(example1.initial_guess()), [&]() { example1.CheckSolution(result); }, &result); LinearSystemExample2 example2{}; RunNonlinearProgram( *(example2.prog()), Eigen::VectorXd(example2.initial_guess()), [&]() { example2.CheckSolution(result); }, &result); LinearSystemExample3 example3{}; RunNonlinearProgram( *(example3.prog()), Eigen::VectorXd(example3.initial_guess()), [&]() { example3.CheckSolution(result); }, &result); } GTEST_TEST(testNonlinearProgram, trivialLinearEquality) { MathematicalProgram prog; auto vars = prog.NewContinuousVariables<2>(); // Use a non-square matrix to catch row/column mistakes in the solvers. prog.AddLinearEqualityConstraint(Eigen::RowVector2d(0, 1), Vector1d::Constant(1), vars); MathematicalProgramResult result; const Eigen::VectorXd x_init = Eigen::Vector2d(2, 2); RunNonlinearProgram( prog, x_init, [&]() { const auto& vars_value = result.GetSolution(vars); EXPECT_DOUBLE_EQ(vars_value(0), 2); EXPECT_DOUBLE_EQ(vars_value(1), 1); }, &result); } // Tests a quadratic optimization problem, with only quadratic cost // 0.5 *x'*Q*x + b'*x // The optimal solution is -inverse(Q)*b GTEST_TEST(testNonlinearProgram, QuadraticCost) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<4>(); Vector4d Qdiag(1.0, 2.0, 3.0, 4.0); Matrix4d Q = Qdiag.asDiagonal(); Q(1, 2) = 0.1; Q(2, 3) = -0.02; Vector4d b(1.0, -0.5, 1.3, 2.5); prog.AddQuadraticCost(Q, b, x); Matrix4d Q_transpose = Q; Q_transpose.transposeInPlace(); Matrix4d Q_symmetric = 0.5 * (Q + Q_transpose); Vector4d expected = -Q_symmetric.ldlt().solve(b); const Eigen::VectorXd x_init = Eigen::Vector4d::Zero(); MathematicalProgramResult result; RunNonlinearProgram( prog, x_init, [&]() { const auto& x_value = result.GetSolution(x); EXPECT_TRUE(CompareMatrices(x_value, expected, 1e-6, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices( prog.EvalBinding(prog.quadratic_costs().front(), result.GetSolution(prog.decision_variables())), 0.5 * x_value.transpose() * Q_symmetric * x_value + b.transpose() * x_value, 1E-14, MatrixCompareType::absolute)); }, &result); } GTEST_TEST(testNonlinearProgram, testNonConvexQPproblem1) { for (const auto& cost_form : NonConvexQPproblem1::cost_forms()) { for (const auto& constraint_form : NonConvexQPproblem1::constraint_forms()) { NonConvexQPproblem1 prob(cost_form, constraint_form); MathematicalProgramResult result; // Initialize decision variable close to the solution. RunNonlinearProgram( *(prob.prog()), Eigen::VectorXd(prob.initial_guess()), [&]() { prob.CheckSolution(result); }, &result); } } } GTEST_TEST(testNonlinearProgram, testNonConvexQPproblem2) { for (const auto& cost_form : NonConvexQPproblem2::cost_forms()) { for (const auto& constraint_form : NonConvexQPproblem2::constraint_forms()) { NonConvexQPproblem2 prob(cost_form, constraint_form); MathematicalProgramResult result; RunNonlinearProgram( *(prob.prog()), Eigen::VectorXd(prob.initial_guess()), [&]() { prob.CheckSolution(result); }, &result); } } } GTEST_TEST(testNonlinearProgram, testLowerBoundedProblem) { for (const auto& constraint_form : LowerBoundedProblem::constraint_forms()) { LowerBoundedProblem prob(constraint_form); MathematicalProgramResult result; RunNonlinearProgram( *(prob.prog()), Eigen::VectorXd(prob.initial_guess1()), [&]() { prob.CheckSolution(result); }, &result); RunNonlinearProgram( *(prob.prog()), Eigen::VectorXd(prob.initial_guess2()), [&]() { prob.CheckSolution(result); }, &result); } } class SixHumpCamelCost { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(SixHumpCamelCost) SixHumpCamelCost() = default; static size_t numInputs() { return 2; } static size_t numOutputs() { return 1; } template <typename ScalarType> void eval(VecIn<ScalarType> const& x, VecOut<ScalarType>* y) const { DRAKE_ASSERT(static_cast<size_t>(x.rows()) == numInputs()); DRAKE_ASSERT(static_cast<size_t>(y->rows()) == numOutputs()); (*y)(0) = x(0) * x(0) * (4 - 2.1 * x(0) * x(0) + x(0) * x(0) * x(0) * x(0) / 3) + x(0) * x(1) + x(1) * x(1) * (-4 + 4 * x(1) * x(1)); } }; GTEST_TEST(testNonlinearProgram, sixHumpCamel) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(2); auto cost = prog.AddCost(SixHumpCamelCost(), x).evaluator(); const Eigen::VectorXd x_init = Eigen::Vector2d(2, 4); MathematicalProgramResult result; RunNonlinearProgram( prog, x_init, [&]() { // check (numerically) if it is a local minimum VectorXd ystar, y; const auto& x_value = result.GetSolution(x); cost->Eval(x_value, &ystar); for (int i = 0; i < 10; i++) { cost->Eval(x_value + .01 * Matrix<double, 2, 1>::Random(), &y); if (y(0) < ystar(0)) throw std::runtime_error("not a local minima!"); } }, &result); } GTEST_TEST(testNonlinearProgram, testGloptiPolyConstrainedMinimization) { for (const auto& cost_form : GloptiPolyConstrainedMinimizationProblem::cost_forms()) { for (const auto& constraint_form : GloptiPolyConstrainedMinimizationProblem::constraint_forms()) { GloptiPolyConstrainedMinimizationProblem prob(cost_form, constraint_form); MathematicalProgramResult result; RunNonlinearProgram( *(prob.prog()), Eigen::VectorXd(prob.initial_guess()), [&]() { prob.CheckSolution(result); }, &result); } } } // // Test that linear polynomial constraints get turned into linear constraints. // TODO(hongkai.dai): move this example to optimization_program_examples, add // the constraint in the symbolic form. GTEST_TEST(testNonlinearProgram, linearPolynomialConstraint) { const Polynomiald x("x"); MathematicalProgram problem; static const double kEpsilon = 1e-7; const auto x_var = problem.NewContinuousVariables(1); const std::vector<Polynomiald::VarType> var_mapping = {x.GetSimpleVariable()}; std::shared_ptr<Constraint> resulting_constraint = problem .AddPolynomialConstraint(VectorXPoly::Constant(1, x), var_mapping, Vector1d::Constant(2), Vector1d::Constant(2), x_var) .evaluator(); // Check that the resulting constraint is a LinearConstraint. EXPECT_TRUE(is_dynamic_castable<LinearConstraint>(resulting_constraint)); // Check that it gives the correct answer as well. const Eigen::VectorXd initial_guess = (Vector1d() << 0).finished(); MathematicalProgramResult result; RunNonlinearProgram( problem, initial_guess, [&]() { EXPECT_NEAR(result.GetSolution(x_var(0)), 2, kEpsilon); }, &result); } // Simple test of polynomial constraints. // TODO(hongkai.dai): move the code to optimization_program_examples, add // the constraints using symbolic forms. GTEST_TEST(testNonlinearProgram, polynomialConstraint) { static const double kInf = numeric_limits<double>::infinity(); // Generic constraints in nlopt require a very generous epsilon. static const double kEpsilon = 1e-4; // Given a degenerate polynomial, get the trivial solution. { const Polynomiald x("x"); MathematicalProgram problem; const auto x_var = problem.NewContinuousVariables(1); const std::vector<Polynomiald::VarType> var_mapping = { x.GetSimpleVariable()}; problem.AddPolynomialConstraint(VectorXPoly::Constant(1, x), var_mapping, Vector1d::Constant(2), Vector1d::Constant(2), x_var); problem.SetInitialGuessForAllVariables(drake::Vector1d::Zero()); const Eigen::VectorXd initial_guess = Vector1d::Zero(); MathematicalProgramResult result; RunNonlinearProgram( problem, initial_guess, [&]() { EXPECT_NEAR(result.GetSolution(x_var(0)), 2, kEpsilon); // TODO(ggould-tri) test this with a two-sided // constraint, once // the nlopt wrapper supports those. }, &result); } // Given a small univariate polynomial, find a low point. { const Polynomiald x("x"); const Polynomiald poly = (x - 1) * (x - 1); MathematicalProgram problem; const auto x_var = problem.NewContinuousVariables(1); const std::vector<Polynomiald::VarType> var_mapping = { x.GetSimpleVariable()}; problem.AddPolynomialConstraint(VectorXPoly::Constant(1, poly), var_mapping, Eigen::VectorXd::Zero(1), Eigen::VectorXd::Zero(1), x_var); const VectorXd initial_guess = Vector1d::Zero(); MathematicalProgramResult result; RunNonlinearProgram( problem, initial_guess, [&]() { EXPECT_NEAR(result.GetSolution(x_var(0)), 1, 0.2); EXPECT_LE(poly.EvaluateUnivariate(result.GetSolution(x_var(0))), kEpsilon); }, &result); } // Given a small multivariate polynomial, find a low point. { const Polynomiald x("x"); const Polynomiald y("y"); const Polynomiald poly = (x - 1) * (x - 1) + (y + 2) * (y + 2); MathematicalProgram problem; const auto xy_var = problem.NewContinuousVariables(2); const std::vector<Polynomiald::VarType> var_mapping = { x.GetSimpleVariable(), y.GetSimpleVariable()}; problem.AddPolynomialConstraint(VectorXPoly::Constant(1, poly), var_mapping, Eigen::VectorXd::Zero(1), Eigen::VectorXd::Zero(1), xy_var); const Eigen::VectorXd initial_guess = Eigen::Vector2d::Zero(); MathematicalProgramResult result; RunNonlinearProgram( problem, initial_guess, [&]() { EXPECT_NEAR(result.GetSolution(xy_var(0)), 1, 0.2); EXPECT_NEAR(result.GetSolution(xy_var(1)), -2, 0.2); std::map<Polynomiald::VarType, double> eval_point = { {x.GetSimpleVariable(), result.GetSolution(xy_var(0))}, {y.GetSimpleVariable(), result.GetSolution(xy_var(1))}}; EXPECT_LE(poly.EvaluateMultivariate(eval_point), kEpsilon); }, &result); } // Given two polynomial constraints, satisfy both. { // (x^4 - x^2 + 0.2 has two minima, one at 0.5 and the other at -0.5; // constrain x < 0 and EXPECT that the solver finds the negative one.) const Polynomiald x("x"); const Polynomiald poly = x * x * x * x - x * x + 0.2; MathematicalProgram problem; const auto x_var = problem.NewContinuousVariables(1); const Eigen::VectorXd initial_guess = Vector1d::Constant(-0.1); const std::vector<Polynomiald::VarType> var_mapping = { x.GetSimpleVariable()}; VectorXPoly polynomials_vec(2, 1); polynomials_vec << poly, x; problem.AddPolynomialConstraint(polynomials_vec, var_mapping, Eigen::VectorXd::Constant(2, -kInf), Eigen::VectorXd::Zero(2), x_var); MathematicalProgramResult result; RunNonlinearProgram( problem, initial_guess, [&]() { EXPECT_NEAR(result.GetSolution(x_var(0)), -0.7, 0.2); EXPECT_LE(poly.EvaluateUnivariate(result.GetSolution(x_var(0))), kEpsilon); }, &result); } } GTEST_TEST(testNonlinearProgram, MinDistanceFromPlaneToOrigin) { std::array<MatrixXd, 2> A; std::array<VectorXd, 2> b; A[0] = Matrix<double, 1, 2>::Ones(); b[0] = Vector1d(2); A[1] = Matrix<double, 2, 3>::Zero(); A[1] << 0, 1, 2, -1, 2, 3; b[1] = Vector2d(1.0, 3.0); for (const auto& cost_form : MinDistanceFromPlaneToOrigin::cost_forms()) { for (const auto& constraint_form : MinDistanceFromPlaneToOrigin::constraint_forms()) { for (int k = 0; k < 2; ++k) { MinDistanceFromPlaneToOrigin prob(A[k], b[k], cost_form, constraint_form); MathematicalProgramResult result; RunNonlinearProgram( *(prob.prog_lorentz()), prob.prog_lorentz_initial_guess(), [&]() { prob.CheckSolution(result, false); }, &result); RunNonlinearProgram( *(prob.prog_rotated_lorentz()), prob.prog_rotated_lorentz_initial_guess(), [&]() { prob.CheckSolution(result, true); }, &result); } } } } GTEST_TEST(testNonlinearProgram, ConvexCubicProgramExample) { ConvexCubicProgramExample prob; prob.SetInitialGuessForAllVariables(Vector1d(1)); const VectorXd initial_guess = Vector1d(1); MathematicalProgramResult result; RunNonlinearProgram( prob, initial_guess, [&]() { prob.CheckSolution(result); }, &result); } GTEST_TEST(testNonlinearProgram, UnitLengthConstraint) { UnitLengthProgramExample prob; prob.SetInitialGuessForAllVariables(Vector4d(1, 0, 0, 0)); Eigen::VectorXd initial_guess = Eigen::Vector4d(1, 0, 0, 0); MathematicalProgramResult result; RunNonlinearProgram( prob, initial_guess, [&prob, &result]() { prob.CheckSolution(result, 1E-8); }, &result); // Try a different initial guess, that doesn't satisfy the unit length // constraint. initial_guess << 1, 2, 3, 4; RunNonlinearProgram( prob, initial_guess, [&prob, &result]() { prob.CheckSolution(result, 1E-8); }, &result); } GTEST_TEST(testNonlinearProgram, EckhardtProblemSparse) { // This tests a nonlinear optimization problem with sparse constraint // gradient. EckhardtProblem prob(true /* set gradient sparsity pattern */); const Eigen::VectorXd x_init = Eigen::Vector3d(2, 1.05, 2.9); MathematicalProgramResult result; RunNonlinearProgram( prob.prog(), x_init, [&prob, &result]() { prob.CheckSolution(result, 3E-7); }, &result); } GTEST_TEST(testNonlinearProgram, EckhardtProblemNonSparse) { // Test Eckhardt problem again without setting the sparsity pattern, to make // sure that the solver gives the same result as setting the sparsity pattern. EckhardtProblem prob(false /* not set gradient sparsity pattern */); const Eigen::VectorXd x_init = Eigen::Vector3d(2, 1.05, 2.9); MathematicalProgramResult result; RunNonlinearProgram( prob.prog(), x_init, [&prob, &result]() { prob.CheckSolution(result, 3E-7); }, &result); } GTEST_TEST(testNonlinearProgram, HeatExchangerDesignProblem) { // This tests a nonlinear optimization problem with sparse constraint // gradient. HeatExchangerDesignProblem prob; Eigen::VectorXd x_init(8); x_init << 4999.4, 5000, 5000, 200, 350, 150, 225, 425; MathematicalProgramResult result; // The optimal solution given in Hock's reference has low precision, and the // magnitude of the solution is large, so we choose a large tolerance 0.2. RunNonlinearProgram( prob.prog(), x_init, [&prob, &result]() { prob.CheckSolution(result, 0.2); }, &result); } GTEST_TEST(testNonlinearProgram, EmptyGradientProblem) { EmptyGradientProblem prob; MathematicalProgramResult result; Eigen::VectorXd x_init = Eigen::Vector2d(0, 0); RunNonlinearProgram( prob.prog(), x_init, [&prob, &result]() { prob.CheckSolution(result); }, &result); } GTEST_TEST(testNonlinearProgram, CallbackTest) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); // Solve a trivial feasibilty program // find x, s.t. xᵀx<=1 // Note: We intentionally do not add an objective here, because the solver // wrappers implement the EvalVisualizationCallbacks() alongside their // evaluation of any registered costs. We want to ensure that the callback // are still called, even if there are no registered costs. prog.AddConstraint(x.transpose() * x <= 1.0); int num_calls = 0; auto my_callback = [&num_calls](const Eigen::Ref<const Eigen::VectorXd>& v) { EXPECT_EQ(v.size(), 3); num_calls++; }; prog.AddVisualizationCallback(my_callback, x); IpoptSolver ipopt_solver; NloptSolver nlopt_solver; SnoptSolver snopt_solver; std::pair<const char*, SolverInterface*> solvers[] = { std::make_pair("SNOPT", &snopt_solver), std::make_pair("NLopt", &nlopt_solver), std::make_pair("Ipopt", &ipopt_solver)}; for (const auto& solver : solvers) { if (!(solver.second->available() && solver.second->enabled())) { continue; } MathematicalProgramResult result; num_calls = 0; SCOPED_TRACE(fmt::format("Using solver: {}", solver.first)); DRAKE_ASSERT_NO_THROW(solver.second->Solve(prog, {}, {}, &result)); EXPECT_TRUE(result.is_success()); EXPECT_GT(num_calls, 0); } } TEST_F(DuplicatedVariableNonlinearProgram1, Test) { SnoptSolver snopt_solver; CheckSolution(snopt_solver, Eigen::Vector2d(0.5, 0.5), std::nullopt, 1E-6); IpoptSolver ipopt_solver; CheckSolution(ipopt_solver, Eigen::Vector2d(0.5, 0.5), std::nullopt, 1E-6); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/branch_and_bound_test.cc
#include "drake/solvers/branch_and_bound.h" #include <algorithm> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/gurobi_solver.h" #include "drake/solvers/mixed_integer_optimization_util.h" #include "drake/solvers/scs_solver.h" namespace drake { namespace solvers { template <typename Scalar> using VectorUpTo4 = Eigen::Matrix<Scalar, Eigen::Dynamic, 1, 0, 4, 1>; // This class exposes the protected and private members of // MixedIntegerBranchAndBound, so that we can test its internal implementation. class MixedIntegerBranchAndBoundTester { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MixedIntegerBranchAndBoundTester) explicit MixedIntegerBranchAndBoundTester( const MathematicalProgram& prog, const SolverId& solver_id, MixedIntegerBranchAndBound::Options options = MixedIntegerBranchAndBound::Options{}) : bnb_{new MixedIntegerBranchAndBound(prog, solver_id, options)} {} MixedIntegerBranchAndBound* bnb() const { return bnb_.get(); } MixedIntegerBranchAndBoundNode* PickBranchingNode() const { return bnb_->PickBranchingNode(); } const symbolic::Variable* PickBranchingVariable( const MixedIntegerBranchAndBoundNode& node) const { return bnb_->PickBranchingVariable(node); } void UpdateIntegralSolution(const Eigen::Ref<const Eigen::VectorXd>& solution, double cost) { return bnb_->UpdateIntegralSolution(solution, cost); } void BranchAndUpdate(MixedIntegerBranchAndBoundNode* node, const symbolic::Variable& branching_variable) { return bnb_->BranchAndUpdate(node, branching_variable); } MixedIntegerBranchAndBoundNode* mutable_root() { return bnb_->root_.get(); } void SearchIntegralSolutionByRounding( const MixedIntegerBranchAndBoundNode& node) { bnb_->SearchIntegralSolutionByRounding(node); } bool HasConverged() const { return bnb_->HasConverged(); } private: std::unique_ptr<MixedIntegerBranchAndBound> bnb_; }; namespace { // Construct a mixed-integer linear program // min x₀ + 2x₁ - 3x₃ + 1 // s.t x₀ + x₁ + 2x₃ = 2 // x₁ - 3.1x₂ ≥ 1 // x₂ + 1.2x₃ - x₀ ≤ 5 // x₀ , x₂ are binary // At the root node, the optimizer should obtain an integral solution. So the // root node does not need to branch. // The optimal solution is (0, 1, 0, 0.5), the optimal cost is 1.5 std::unique_ptr<MathematicalProgram> ConstructMathematicalProgram1() { auto prog = std::make_unique<MathematicalProgram>(); VectorDecisionVariable<4> x; x(0) = symbolic::Variable("x0", symbolic::Variable::Type::BINARY); x(1) = symbolic::Variable("x1", symbolic::Variable::Type::CONTINUOUS); x(2) = symbolic::Variable("x2", symbolic::Variable::Type::BINARY); x(3) = symbolic::Variable("x3", symbolic::Variable::Type::CONTINUOUS); prog->AddDecisionVariables(x); prog->AddCost(x(0) + 2 * x(1) - 3 * x(3) + 1); prog->AddLinearEqualityConstraint(x(0) + x(1) + 2 * x(3) == 2); prog->AddLinearConstraint(x(1) - 3.1 * x(2) >= 1); prog->AddLinearConstraint(x(2) + 1.2 * x(3) - x(0) <= 5); return prog; } // Construct the problem data for the mixed-integer linear program // min x₀ + 2x₁ - 3x₂ - 4x₃ + 4.5x₄ + 1 // s.t 2x₀ + x₂ + 1.5x₃ + x₄ = 4.5 // 1 ≤ 2x₀ + 4x₃ + x₄ ≤ 7 // -2 ≤ 3x₁ + 2x₂ - 5x₃ + x₄ ≤ 7 // -5 ≤ x₁ + x₂ + 2x₃ ≤ 10 // -10 ≤ x₁ ≤ 10 // x₀, x₂, x₄ are binary variables. // The optimal solution is (1, 1/3, 1, 1, 0), with optimal cost -13/3. std::unique_ptr<MathematicalProgram> ConstructMathematicalProgram2() { auto prog = std::make_unique<MathematicalProgram>(); VectorDecisionVariable<5> x; x(0) = symbolic::Variable("x0", symbolic::Variable::Type::BINARY); x(1) = symbolic::Variable("x1", symbolic::Variable::Type::CONTINUOUS); x(2) = symbolic::Variable("x2", symbolic::Variable::Type::BINARY); x(3) = symbolic::Variable("x3", symbolic::Variable::Type::CONTINUOUS); x(4) = symbolic::Variable("x4", symbolic::Variable::Type::BINARY); prog->AddDecisionVariables(x); prog->AddCost(x(0) + 2 * x(1) - 3 * x(2) - 4 * x(3) + 4.5 * x(4) + 1); prog->AddLinearEqualityConstraint(2 * x(0) + x(2) + 1.5 * x(3) + x(4) == 4.5); prog->AddLinearConstraint(2 * x(0) + 4 * x(3) + x(4), 1, 7); prog->AddLinearConstraint(3 * x(1) + 2 * x(2) - 5 * x(3) + x(4), -2, 7); prog->AddLinearConstraint(x(1) + x(2) + 2 * x(3), -5, 10); prog->AddBoundingBoxConstraint(-10, 10, x(1)); return prog; } // Construct an unbounded mixed-integer optimization problem. // min x₀ + 2*x₁ + 3 * x₂ + 2.5*x₃ + 2 // s.t x₀ + x₁ - x₂ + x₃ ≤ 3 // 1 ≤ x₀ + 2 * x₁ - 2 * x₂ + 4 * x₃ ≤ 3 // x₀, x₂ are binary. std::unique_ptr<MathematicalProgram> ConstructMathematicalProgram3() { auto prog = std::make_unique<MathematicalProgram>(); VectorDecisionVariable<4> x; x(0) = symbolic::Variable("x0", symbolic::Variable::Type::BINARY); x(1) = symbolic::Variable("x1", symbolic::Variable::Type::CONTINUOUS); x(2) = symbolic::Variable("x2", symbolic::Variable::Type::BINARY); x(3) = symbolic::Variable("x3", symbolic::Variable::Type::CONTINUOUS); prog->AddDecisionVariables(x); prog->AddCost(x(0) + 2 * x(1) + 3 * x(2) + 2.5 * x(3) + 2); prog->AddLinearConstraint(x(0) + x(1) - x(2) + x(3) <= 3); prog->AddLinearConstraint(x(0) + 2 * x(1) - 2 * x(2) + 4 * x(3), 1, 3); return prog; } // An infeasible program. // Given points P0 = (0, 3), P1 = (1, 1), and P2 = (2, 2), and the line segments // connecting P0P1 and P1P2, we want to find if the point (1, 2) is on the // line segments, and optimize some cost. This problem can be formulated as // min x₀ + x₁ + 2 * x₂ // An arbitrary cost. // s.t x₀ ≤ y₀ // x₁ ≤ y₀ + y₁ // x₂ ≤ y₁ // x₀ + x₁ + x₂ = 1 // x₁ + 2 * x₂ = 1 // y₀ + y₁ = 1 // 3 * x₀ + x₁ + 2 * x₂ = 2 // y₀, y₁ are binary // x₀, x₁, x₂ ≥ 0 // This formulation is obtained by using the special ordered set constraint // with yᵢ being the indicator binary variable that the point is on the line // segment PᵢPᵢ₊₁ std::unique_ptr<MathematicalProgram> ConstructMathematicalProgram4() { auto prog = std::make_unique<MathematicalProgram>(); auto x = prog->NewContinuousVariables<3>("x"); auto y = prog->NewBinaryVariables<2>("y"); AddSos2Constraint(prog.get(), x.cast<symbolic::Expression>(), y.cast<symbolic::Expression>()); prog->AddLinearCost(x(0) + x(1) + 2 * x(2)); prog->AddLinearConstraint(x(1) + 2 * x(2) == 1); prog->AddLinearConstraint(3 * x(0) + x(1) + 2 * x(2) == 2); prog->AddBoundingBoxConstraint(0, 1, x); return prog; } void CheckNewRootNode( const MixedIntegerBranchAndBoundNode& root, const std::list<symbolic::Variable>& binary_vars_expected) { EXPECT_EQ(root.is_explored(), root.prog_result() != nullptr); // The left and right children are empty. EXPECT_FALSE(root.left_child()); EXPECT_FALSE(root.right_child()); EXPECT_EQ(root.NumExploredNodesInSubtree(), 1); // The parent node is empty. EXPECT_TRUE(root.IsRoot()); // None of the binary variables are fixed. EXPECT_TRUE(root.fixed_binary_variable().is_dummy()); EXPECT_EQ(root.fixed_binary_value(), -1); // Expect root.remaining_binary_variables() equal to binary_vars_expected. EXPECT_EQ(root.remaining_binary_variables().size(), binary_vars_expected.size()); EXPECT_TRUE(std::equal( root.remaining_binary_variables().begin(), root.remaining_binary_variables().end(), binary_vars_expected.begin(), [](const symbolic::Variable& v1, const symbolic::Variable& v2) { return v1.equal_to(v2); })); EXPECT_TRUE(root.IsLeaf()); } void CheckNodeSolution(const MixedIntegerBranchAndBoundNode& node, const Eigen::Ref<const VectorXDecisionVariable>& x, const Eigen::Ref<const Eigen::VectorXd>& x_expected, double optimal_cost, double tol = 1E-4) { const SolutionResult result = node.solution_result(); EXPECT_EQ(result, SolutionResult::kSolutionFound); EXPECT_TRUE(CompareMatrices(node.prog_result()->GetSolution(x), x_expected, tol, MatrixCompareType::absolute)); EXPECT_NEAR(node.prog_result()->get_optimal_cost(), optimal_cost, tol); } GTEST_TEST(MixedIntegerBranchAndBoundNodeTest, TestConstructRoot1) { // Test constructing root node for prog 1. auto prog = ConstructMathematicalProgram1(); std::unique_ptr<MixedIntegerBranchAndBoundNode> root; std::unordered_map<symbolic::Variable::Id, symbolic::Variable> map_old_vars_to_new_vars; std::tie(root, map_old_vars_to_new_vars) = MixedIntegerBranchAndBoundNode::ConstructRootNode(*prog, GurobiSolver::id()); VectorDecisionVariable<4> x; for (int i = 0; i < 4; ++i) { x(i) = map_old_vars_to_new_vars.at(prog->decision_variable(i).get_id()); EXPECT_TRUE(x(i).equal_to(root->prog()->decision_variable(i))); } CheckNewRootNode(*root, {x(0), x(2)}); const Eigen::Vector4d x_expected(0, 1, 0, 0.5); const double tol{1E-5}; const double cost_expected{1.5}; CheckNodeSolution(*root, x, x_expected, cost_expected, tol); EXPECT_TRUE(root->optimal_solution_is_integral()); } GTEST_TEST(MixedIntegerBranchAndBoundNodeTest, TestConstructRoot2) { // Test constructing root node for prog 2. auto prog = ConstructMathematicalProgram2(); std::unique_ptr<MixedIntegerBranchAndBoundNode> root; std::unordered_map<symbolic::Variable::Id, symbolic::Variable> map_old_vars_to_new_vars; std::tie(root, map_old_vars_to_new_vars) = MixedIntegerBranchAndBoundNode::ConstructRootNode(*prog, GurobiSolver::id()); VectorDecisionVariable<5> x; for (int i = 0; i < 5; ++i) { x(i) = map_old_vars_to_new_vars.at(prog->decision_variable(i).get_id()); EXPECT_TRUE(x(i).equal_to(root->prog()->decision_variable(i))); } CheckNewRootNode(*root, {x(0), x(2), x(4)}); Eigen::Matrix<double, 5, 1> x_expected; x_expected << 0.7, 1, 1, 1.4, 0; const double tol{1E-5}; const double cost_expected{-4.9}; CheckNodeSolution(*root, x, x_expected, cost_expected, tol); EXPECT_FALSE(root->optimal_solution_is_integral()); } GTEST_TEST(MixedIntegerBranchAndBoundNodeTest, TestConstructRoot3) { // Test constructing root node for prog 3. auto prog = ConstructMathematicalProgram3(); std::unique_ptr<MixedIntegerBranchAndBoundNode> root; std::unordered_map<symbolic::Variable::Id, symbolic::Variable> map_old_vars_to_new_vars; std::tie(root, map_old_vars_to_new_vars) = MixedIntegerBranchAndBoundNode::ConstructRootNode(*prog, GurobiSolver::id()); VectorDecisionVariable<4> x; for (int i = 0; i < 4; ++i) { x(i) = map_old_vars_to_new_vars.at(prog->decision_variable(i).get_id()); EXPECT_TRUE(x(i).equal_to(root->prog()->decision_variable(i))); } CheckNewRootNode(*root, {x(0), x(2)}); EXPECT_EQ(root->solution_result(), SolutionResult::kUnbounded); } GTEST_TEST(MixedIntegerBranchAndBoundNodeTest, TestConstructRoot4) { // Test constructing root node for prog 4. auto prog = ConstructMathematicalProgram4(); std::unique_ptr<MixedIntegerBranchAndBoundNode> root; std::unordered_map<symbolic::Variable::Id, symbolic::Variable> map_old_vars_to_new_vars; std::tie(root, map_old_vars_to_new_vars) = MixedIntegerBranchAndBoundNode::ConstructRootNode(*prog, GurobiSolver::id()); VectorDecisionVariable<5> x; for (int i = 0; i < 5; ++i) { x(i) = map_old_vars_to_new_vars.at(prog->decision_variable(i).get_id()); EXPECT_TRUE(x(i).equal_to(root->prog()->decision_variable(i))); } CheckNewRootNode(*root, {x(3), x(4)}); EXPECT_EQ(root->solution_result(), SolutionResult::kSolutionFound); Eigen::Matrix<double, 5, 1> x_expected; x_expected << 1.0 / 3, 1.0 / 3, 1.0 / 3, 2.0 / 3, 1.0 / 3; const double tol{1E-5}; const double cost_expected{4.0 / 3.0}; CheckNodeSolution(*root, x, x_expected, cost_expected, tol); EXPECT_FALSE(root->optimal_solution_is_integral()); } GTEST_TEST(MixedIntegerBranchAndBoundNodeTest, TestConstructRootError) { // The optimization program does not have a binary variable. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); prog.AddCost(x.cast<symbolic::Expression>().sum()); EXPECT_THROW(MixedIntegerBranchAndBoundNode::ConstructRootNode( prog, GurobiSolver::id()), std::runtime_error); } GTEST_TEST(MixedIntegerBranchAndBoundNodeTest, TestBranch1) { // Test branching on the root node for prog 1. auto prog = ConstructMathematicalProgram1(); std::unique_ptr<MixedIntegerBranchAndBoundNode> root; std::tie(root, std::ignore) = MixedIntegerBranchAndBoundNode::ConstructRootNode(*prog, GurobiSolver::id()); VectorDecisionVariable<4> x = root->prog()->decision_variables(); // Branch on variable x(0). root->Branch(x(0)); EXPECT_EQ(root->NumExploredNodesInSubtree(), 3); EXPECT_EQ(root->left_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->right_child()->NumExploredNodesInSubtree(), 1); const Eigen::Vector4d x_expected_l0(0, 1, 0, 0.5); const Eigen::Vector4d x_expected_r0(1, 1, 0, 0); const double tol{1E-5}; CheckNodeSolution(*(root->left_child()), x, x_expected_l0, 1.5, tol); CheckNodeSolution(*(root->right_child()), x, x_expected_r0, 4, tol); EXPECT_TRUE(root->left_child()->optimal_solution_is_integral()); EXPECT_TRUE(root->right_child()->optimal_solution_is_integral()); // Branch on variable x(2). The child nodes created by branching on x(0) will // be deleted. root->Branch(x(2)); EXPECT_EQ(root->NumExploredNodesInSubtree(), 3); EXPECT_EQ(root->left_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->right_child()->NumExploredNodesInSubtree(), 1); const Eigen::Vector4d x_expected_l2(0, 1, 0, 0.5); const Eigen::Vector4d x_expected_r2(0, 4.1, 1, -1.05); CheckNodeSolution(*(root->left_child()), x, x_expected_l2, 1.5, tol); CheckNodeSolution(*(root->right_child()), x, x_expected_r2, 12.35, tol); EXPECT_TRUE(root->left_child()->optimal_solution_is_integral()); EXPECT_TRUE(root->right_child()->optimal_solution_is_integral()); // Branch on variable x(1) and x(3). Since these two variables are continuous, // expect a runtime error thrown. EXPECT_THROW(root->Branch(x(1)), std::runtime_error); EXPECT_THROW(root->Branch(x(3)), std::runtime_error); } GTEST_TEST(MixedIntegerBranchAndBoundNodeTest, TestBranch2) { // Test branching on the root node for prog 2. auto prog = ConstructMathematicalProgram2(); std::unique_ptr<MixedIntegerBranchAndBoundNode> root; std::tie(root, std::ignore) = MixedIntegerBranchAndBoundNode::ConstructRootNode(*prog, GurobiSolver::id()); VectorDecisionVariable<5> x = root->prog()->decision_variables(); // Branch on x(0) root->Branch(x(0)); EXPECT_EQ(root->NumExploredNodesInSubtree(), 3); EXPECT_EQ(root->left_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->right_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->left_child()->solution_result(), SolutionResult::kInfeasibleConstraints); Eigen::Matrix<double, 5, 1> x_expected_r; x_expected_r << 1, 1.0 / 3.0, 1, 1, 0; const double tol{1E-5}; CheckNodeSolution(*(root->right_child()), x, x_expected_r, -13.0 / 3.0, tol); EXPECT_TRUE(root->right_child()->optimal_solution_is_integral()); // Branch on variable x(2). The child nodes created by branching on x(0) will // be deleted. root->Branch(x(2)); EXPECT_EQ(root->NumExploredNodesInSubtree(), 3); EXPECT_EQ(root->left_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->right_child()->NumExploredNodesInSubtree(), 1); Eigen::Matrix<double, 5, 1> x_expected_l; x_expected_l << 1, 2.0 / 3.0, 0, 1, 1; CheckNodeSolution(*(root->left_child()), x, x_expected_l, 23.0 / 6.0, tol); EXPECT_TRUE(root->left_child()->optimal_solution_is_integral()); x_expected_r << 0.7, 1, 1, 1.4, 0; CheckNodeSolution(*(root->right_child()), x, x_expected_r, -4.9, tol); EXPECT_FALSE(root->right_child()->optimal_solution_is_integral()); // Branch on x(4). The child nodes created by branching on x(2) will be // deleted. root->Branch(x(4)); EXPECT_EQ(root->NumExploredNodesInSubtree(), 3); EXPECT_EQ(root->left_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->right_child()->NumExploredNodesInSubtree(), 1); x_expected_l << 0.7, 1, 1, 1.4, 0; x_expected_r << 0.2, 2.0 / 3.0, 1, 1.4, 1; CheckNodeSolution(*(root->left_child()), x, x_expected_l, -4.9, tol); CheckNodeSolution(*(root->right_child()), x, x_expected_r, -47.0 / 30, tol); EXPECT_FALSE(root->left_child()->optimal_solution_is_integral()); EXPECT_FALSE(root->right_child()->optimal_solution_is_integral()); // x(1) and x(3) are continuous variables, expect runtime_error thrown when we // branch on them. EXPECT_THROW(root->Branch(x(1)), std::runtime_error); EXPECT_THROW(root->Branch(x(3)), std::runtime_error); } GTEST_TEST(MixedIntegerBranchAndBoundNodeTest, TestBranch3) { // Test branching on the root node for prog 3. auto prog = ConstructMathematicalProgram3(); std::unique_ptr<MixedIntegerBranchAndBoundNode> root; std::tie(root, std::ignore) = MixedIntegerBranchAndBoundNode::ConstructRootNode(*prog, GurobiSolver::id()); VectorDecisionVariable<4> x = root->prog()->decision_variables(); // Branch on x(0) and x(2), the child nodes are all unbounded. for (const auto& x_binary : {x(0), x(2)}) { root->Branch(x_binary); EXPECT_EQ(root->NumExploredNodesInSubtree(), 3); EXPECT_EQ(root->left_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->right_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->left_child()->solution_result(), SolutionResult::kUnbounded); EXPECT_EQ(root->right_child()->solution_result(), SolutionResult::kUnbounded); } // Expect to throw a runtime_error when branching on x(1) and x(3), as they // are continuous variables. EXPECT_THROW(root->Branch(x(1)), std::runtime_error); EXPECT_THROW(root->Branch(x(3)), std::runtime_error); } GTEST_TEST(MixedIntegerBranchAndBoundNodeTest, TestBranch4) { // Test branching on the root node for prog 4. auto prog = ConstructMathematicalProgram4(); std::unique_ptr<MixedIntegerBranchAndBoundNode> root; std::tie(root, std::ignore) = MixedIntegerBranchAndBoundNode::ConstructRootNode(*prog, GurobiSolver::id()); VectorDecisionVariable<5> x = root->prog()->decision_variables(); // Branch on x(3) root->Branch(x(3)); EXPECT_EQ(root->NumExploredNodesInSubtree(), 3); EXPECT_EQ(root->left_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->right_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->left_child()->solution_result(), SolutionResult::kInfeasibleConstraints); EXPECT_EQ(root->right_child()->solution_result(), SolutionResult::kInfeasibleConstraints); // Branch on x(4) root->Branch(x(4)); EXPECT_EQ(root->NumExploredNodesInSubtree(), 3); EXPECT_EQ(root->left_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->right_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(root->left_child()->solution_result(), SolutionResult::kInfeasibleConstraints); EXPECT_EQ(root->right_child()->solution_result(), SolutionResult::kInfeasibleConstraints); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestNewVariable) { // Test GetNewVariable() function. auto prog = ConstructMathematicalProgram1(); MixedIntegerBranchAndBound bnb(*prog, GurobiSolver::id()); const VectorDecisionVariable<4> prog_x = prog->decision_variables(); const VectorDecisionVariable<4> bnb_x = bnb.root()->prog()->decision_variables(); for (int i = 0; i < 4; ++i) { EXPECT_TRUE(bnb_x(i).equal_to(bnb.GetNewVariable(prog_x(i)))); } static_assert(std::is_same_v<decltype(bnb.GetNewVariables(prog_x.head<2>())), VectorDecisionVariable<2>>, "Should return VectorDecisionVariable<2> object.\n"); static_assert(std::is_same_v<decltype(bnb.GetNewVariables(prog_x.head(2))), VectorUpTo4<symbolic::Variable>>, "Should return VectorUpTo4<Variable> object.\n"); MatrixDecisionVariable<2, 2> X; X << prog_x(0), prog_x(1), prog_x(2), prog_x(3); static_assert(std::is_same_v<decltype(bnb.GetNewVariables(X)), MatrixDecisionVariable<2, 2>>, "Should return MatrixDecisionVariable<2, 2> object.\n"); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestConstructor1) { // Test the constructor for MixedIntegerBranchAndBound for prog 1. auto prog = ConstructMathematicalProgram1(); MixedIntegerBranchAndBound bnb(*prog, GurobiSolver::id()); // The root node of the tree has integral optimal cost (0, 1, 0, 0.5), with // cost 1.5. const double tol = 1E-3; EXPECT_NEAR(bnb.best_upper_bound(), 1.5, tol); EXPECT_NEAR(bnb.best_lower_bound(), 1.5, tol); const auto& best_solutions = bnb.solutions(); EXPECT_EQ(best_solutions.size(), 1); EXPECT_NEAR(best_solutions.begin()->first, 1.5, tol); const Eigen::Vector4d x_expected(0, 1, 0, 0.5); EXPECT_TRUE(CompareMatrices(best_solutions.begin()->second, x_expected, tol, MatrixCompareType::absolute)); EXPECT_TRUE(bnb.IsLeafNodeFathomed(*(bnb.root()))); EXPECT_EQ(bnb.root()->NumExploredNodesInSubtree(), 1); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestConstructor2) { // Test the constructor for MixedIntegerBranchAndBound for prog 2. auto prog = ConstructMathematicalProgram2(); MixedIntegerBranchAndBound bnb(*prog, GurobiSolver::id()); // The root node does not have an optimal integral solution. const double tol{1E-3}; EXPECT_NEAR(bnb.best_lower_bound(), -4.9, tol); EXPECT_EQ(bnb.best_upper_bound(), std::numeric_limits<double>::infinity()); EXPECT_TRUE(bnb.solutions().empty()); EXPECT_FALSE(bnb.IsLeafNodeFathomed(*(bnb.root()))); EXPECT_EQ(bnb.root()->NumExploredNodesInSubtree(), 1); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestConstructor3) { // Test the constructor for MixedIntegerBranchAndBound for prog 3. auto prog = ConstructMathematicalProgram3(); MixedIntegerBranchAndBound bnb(*prog, GurobiSolver::id()); // The root node is unbounded. EXPECT_EQ(bnb.best_lower_bound(), -std::numeric_limits<double>::infinity()); EXPECT_EQ(bnb.best_upper_bound(), std::numeric_limits<double>::infinity()); EXPECT_TRUE(bnb.solutions().empty()); EXPECT_FALSE(bnb.IsLeafNodeFathomed(*(bnb.root()))); EXPECT_EQ(bnb.root()->NumExploredNodesInSubtree(), 1); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestConstructor4) { // Test the constructor for MixedIntegerBranchAndBound for prog 4. auto prog = ConstructMathematicalProgram4(); MixedIntegerBranchAndBound bnb(*prog, GurobiSolver::id()); const double tol{1E-3}; EXPECT_NEAR(bnb.best_lower_bound(), 4.0 / 3.0, tol); EXPECT_EQ(bnb.best_upper_bound(), std::numeric_limits<double>::infinity()); EXPECT_TRUE(bnb.solutions().empty()); EXPECT_FALSE(bnb.IsLeafNodeFathomed(*(bnb.root()))); EXPECT_EQ(bnb.root()->NumExploredNodesInSubtree(), 1); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestLeafNodeFathomed1) { // Test IsLeafNodeFathomed for prog1. auto prog1 = ConstructMathematicalProgram1(); MixedIntegerBranchAndBoundTester dut(*prog1, GurobiSolver::id()); // The optimal solution to the root is integral. The node is fathomed. EXPECT_TRUE(dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()))); VectorDecisionVariable<4> x = dut.bnb()->root()->prog()->decision_variables(); dut.mutable_root()->Branch(x(0)); EXPECT_EQ(dut.mutable_root()->NumExploredNodesInSubtree(), 3); EXPECT_EQ(dut.mutable_root()->left_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(dut.mutable_root()->right_child()->NumExploredNodesInSubtree(), 1); // Both left and right children have integral optimal solution. Both nodes are // fathomed. EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->left_child()))); EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->right_child()))); dut.mutable_root()->Branch(x(2)); EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->left_child()))); EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->right_child()))); // The root node is not a leaf node. Expect a runtime error. EXPECT_THROW(unused(dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()))), std::runtime_error); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestLeafNodeFathomed2) { // Test IsLeafNodeFathomed for prog2. auto prog2 = ConstructMathematicalProgram2(); MixedIntegerBranchAndBoundTester dut(*prog2, GurobiSolver::id()); VectorDecisionVariable<5> x = dut.bnb()->root()->prog()->decision_variables(); // The optimal solution to the root is not integral, the node is not fathomed. // The optimal cost is -4.9. EXPECT_FALSE(dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()))); dut.mutable_root()->Branch(x(0)); // The left node is infeasible, thus fathomed. EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->left_child()))); // The right node has integral optimal solution, thus fathomed. EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->right_child()))); dut.mutable_root()->Branch(x(2)); // The solution to the left node is integral, with optimal cost 23.0 / 6.0. // The node is fathomed. EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->left_child()))); // The solution to the right node is not integral, with optimal cost -4.9. The // node is not fathomed. EXPECT_FALSE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->right_child()))); dut.mutable_root()->Branch(x(4)); // Neither the left nor the right child nodes has integral solution. // Neither of the nodes is fathomed. EXPECT_FALSE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->left_child()))); EXPECT_FALSE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->right_child()))); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestLeafNodeFathomed3) { // Test IsLeafNodeFathomed for prog3. auto prog = ConstructMathematicalProgram3(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); const VectorDecisionVariable<4> x = dut.bnb()->root()->prog()->decision_variables(); EXPECT_FALSE(dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()))); dut.mutable_root()->Branch(x(0)); EXPECT_EQ(dut.mutable_root()->NumExploredNodesInSubtree(), 3); EXPECT_EQ(dut.mutable_root()->left_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(dut.mutable_root()->right_child()->NumExploredNodesInSubtree(), 1); EXPECT_FALSE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->left_child()))); EXPECT_FALSE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->right_child()))); dut.mutable_root()->mutable_left_child()->Branch(x(2)); EXPECT_EQ(dut.mutable_root()->NumExploredNodesInSubtree(), 5); EXPECT_EQ(dut.mutable_root()->left_child()->NumExploredNodesInSubtree(), 3); EXPECT_EQ(dut.mutable_root()->right_child()->NumExploredNodesInSubtree(), 1); EXPECT_EQ(dut.mutable_root() ->left_child() ->left_child() ->NumExploredNodesInSubtree(), 1); EXPECT_EQ(dut.mutable_root() ->left_child() ->right_child() ->NumExploredNodesInSubtree(), 1); EXPECT_FALSE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->right_child()))); EXPECT_TRUE(dut.bnb()->IsLeafNodeFathomed( *(dut.bnb()->root()->left_child()->left_child()))); EXPECT_TRUE(dut.bnb()->IsLeafNodeFathomed( *(dut.bnb()->root()->left_child()->right_child()))); dut.mutable_root()->mutable_right_child()->Branch(x(2)); EXPECT_TRUE(dut.bnb()->IsLeafNodeFathomed( *(dut.bnb()->root()->right_child()->left_child()))); EXPECT_TRUE(dut.bnb()->IsLeafNodeFathomed( *(dut.bnb()->root()->right_child()->right_child()))); EXPECT_TRUE(dut.bnb()->IsLeafNodeFathomed( *(dut.bnb()->root()->left_child()->left_child()))); EXPECT_TRUE(dut.bnb()->IsLeafNodeFathomed( *(dut.bnb()->root()->left_child()->right_child()))); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestLeafNodeFathomed4) { // Test IsLeafNodeFathomed for prog4. auto prog = ConstructMathematicalProgram4(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); const VectorDecisionVariable<5> x = dut.bnb()->root()->prog()->decision_variables(); EXPECT_FALSE(dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()))); dut.mutable_root()->Branch(x(3)); EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->left_child()))); EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->right_child()))); dut.mutable_root()->Branch(x(4)); EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->left_child()))); EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->right_child()))); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestPickBranchingNode1) { // Test choosing the node with the minimal lower bound. auto prog = ConstructMathematicalProgram2(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); VectorDecisionVariable<5> x = dut.bnb()->root()->prog()->decision_variables(); // The root node has optimal cost -4.9. dut.bnb()->SetNodeSelectionMethod( MixedIntegerBranchAndBound::NodeSelectionMethod::kMinLowerBound); // Pick the root node. EXPECT_EQ(dut.PickBranchingNode(), dut.bnb()->root()); // The left node has optimal cost 23.0 / 6.0, the right node has optimal cost // -4.9 // Also the left node is fathomed. dut.mutable_root()->Branch(x(2)); EXPECT_EQ(dut.PickBranchingNode(), dut.bnb()->root()->right_child()); dut.mutable_root()->Branch(x(4)); // The left node has optimal cost -4.9, the right node has optimal cost -47.0 // / 30 EXPECT_EQ(dut.PickBranchingNode(), dut.bnb()->root()->left_child()); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestPickBranchingNode2) { // Test choosing the deepest non-fathomed leaf node. auto prog = ConstructMathematicalProgram2(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); VectorDecisionVariable<5> x = dut.bnb()->root()->prog()->decision_variables(); dut.bnb()->SetNodeSelectionMethod( MixedIntegerBranchAndBound::NodeSelectionMethod::kDepthFirst); EXPECT_EQ(dut.PickBranchingNode(), dut.bnb()->root()); dut.mutable_root()->Branch(x(2)); EXPECT_EQ(dut.PickBranchingNode(), dut.bnb()->root()->right_child()); dut.mutable_root()->Branch(x(4)); EXPECT_TRUE(dut.PickBranchingNode() == dut.bnb()->root()->left_child() || dut.PickBranchingNode() == dut.bnb()->root()->right_child()); dut.mutable_root()->mutable_left_child()->Branch(x(0)); // root->left->left is infeasible, root->left->right has integral solution. // The only non-fathomed leaf node is root->right EXPECT_EQ(dut.PickBranchingNode(), dut.bnb()->root()->right_child()); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestPickBranchingVariable1) { // Test picking branching variable for prog 2. auto prog = ConstructMathematicalProgram2(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); VectorDecisionVariable<5> x = dut.bnb()->root()->prog()->decision_variables(); // The optimal solution at the root is (0.7, 1, 1, 1.4, 0) dut.bnb()->SetVariableSelectionMethod( MixedIntegerBranchAndBound::VariableSelectionMethod::kMostAmbivalent); EXPECT_TRUE(dut.PickBranchingVariable(*(dut.bnb()->root()))->equal_to(x(0))); dut.bnb()->SetVariableSelectionMethod( MixedIntegerBranchAndBound::VariableSelectionMethod::kLeastAmbivalent); EXPECT_TRUE(dut.PickBranchingVariable(*(dut.bnb()->root()))->equal_to(x(2)) || dut.PickBranchingVariable(*(dut.bnb()->root()))->equal_to(x(4))); dut.BranchAndUpdate(dut.mutable_root(), x(0)); // The optimization at root->left is infeasible. dut.bnb()->SetVariableSelectionMethod( MixedIntegerBranchAndBound::VariableSelectionMethod::kMostAmbivalent); EXPECT_THROW(dut.PickBranchingVariable(*(dut.bnb()->root()->left_child())), std::runtime_error); dut.bnb()->SetVariableSelectionMethod( MixedIntegerBranchAndBound::VariableSelectionMethod::kLeastAmbivalent); EXPECT_THROW(dut.PickBranchingVariable(*(dut.bnb()->root()->left_child())), std::runtime_error); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestPickBranchingVariable2) { // Test picking branching variable for prog 3. auto prog = ConstructMathematicalProgram3(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); VectorDecisionVariable<4> x = dut.bnb()->root()->prog()->decision_variables(); // The problem is unbounded, any branching variable is acceptable. dut.bnb()->SetVariableSelectionMethod( MixedIntegerBranchAndBound::VariableSelectionMethod::kMostAmbivalent); EXPECT_TRUE(dut.PickBranchingVariable(*(dut.bnb()->root()))->equal_to(x(0)) || dut.PickBranchingVariable(*(dut.bnb()->root()))->equal_to(x(2))); dut.bnb()->SetVariableSelectionMethod( MixedIntegerBranchAndBound::VariableSelectionMethod::kLeastAmbivalent); EXPECT_TRUE(dut.PickBranchingVariable(*(dut.bnb()->root()))->equal_to(x(0)) || dut.PickBranchingVariable(*(dut.bnb()->root()))->equal_to(x(2))); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestBranchAndUpdate2) { // TestBranchAndUpdate for prog2. auto prog = ConstructMathematicalProgram2(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); EXPECT_TRUE(dut.bnb()->solutions().empty()); const double tol = 1E-3; EXPECT_NEAR(dut.bnb()->best_lower_bound(), -4.9, tol); EXPECT_EQ(dut.bnb()->best_upper_bound(), std::numeric_limits<double>::infinity()); VectorDecisionVariable<5> x = dut.bnb()->root()->prog()->decision_variables(); dut.BranchAndUpdate(dut.mutable_root(), x(2)); // The left node has optimal cost 23.0 / 6.0. with integral solution (1, 2 / // 3, 0, 1, 1,) // The right node has optimal cost -4.9, with non-integral solution (0.7, 1, // 1, 1.4, 0). EXPECT_NEAR(dut.bnb()->best_lower_bound(), -4.9, tol); EXPECT_NEAR(dut.bnb()->best_upper_bound(), 23.0 / 6.0, tol); EXPECT_EQ(dut.bnb()->solutions().size(), 1); EXPECT_NEAR(dut.bnb()->solutions().begin()->first, 23.0 / 6.0, tol); Eigen::Matrix<double, 5, 1> x_expected; x_expected << 1, 2.0 / 3.0, 0, 1, 1; EXPECT_TRUE(CompareMatrices(dut.bnb()->solutions().begin()->second, x_expected, tol, MatrixCompareType::absolute)); dut.BranchAndUpdate(dut.mutable_root(), x(4)); // The left node has optimal cost -4.9, with non-integral solution (0.7, 1, 1, // 1.4, 0). // The right node has optimal cost -47/30, with non-integral solution (0.2, // 2/3, 1, 1.4, 1). EXPECT_NEAR(dut.bnb()->best_lower_bound(), -4.9, tol); EXPECT_NEAR(dut.bnb()->best_upper_bound(), 23.0 / 6.0, tol); EXPECT_EQ(dut.bnb()->solutions().size(), 1); EXPECT_NEAR(dut.bnb()->solutions().begin()->first, 23.0 / 6.0, tol); EXPECT_TRUE(CompareMatrices(dut.bnb()->solutions().begin()->second, x_expected, tol, MatrixCompareType::absolute)); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestBranchAndUpdate3) { // TestBranchAndUpdate for prog3. auto prog = ConstructMathematicalProgram3(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); const VectorDecisionVariable<4> x = dut.bnb()->root()->prog()->decision_variables(); dut.BranchAndUpdate(dut.mutable_root(), x(0)); // Both left and right children are unbounded. EXPECT_EQ(dut.bnb()->best_upper_bound(), std::numeric_limits<double>::infinity()); EXPECT_EQ(dut.bnb()->best_lower_bound(), -std::numeric_limits<double>::infinity()); EXPECT_TRUE(dut.bnb()->solutions().empty()); EXPECT_FALSE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->left_child()))); dut.BranchAndUpdate(dut.mutable_root()->mutable_left_child(), x(2)); // Both root->l->l and root->l->r are unbounded. EXPECT_EQ(dut.bnb()->best_upper_bound(), std::numeric_limits<double>::infinity()); EXPECT_EQ(dut.bnb()->best_lower_bound(), -std::numeric_limits<double>::infinity()); EXPECT_TRUE(dut.bnb()->solutions().empty()); EXPECT_TRUE(dut.bnb()->IsLeafNodeFathomed( *(dut.bnb()->root()->left_child()->left_child()))); EXPECT_TRUE(dut.bnb()->IsLeafNodeFathomed( *(dut.bnb()->root()->left_child()->right_child()))); dut.BranchAndUpdate(dut.mutable_root()->mutable_right_child(), x(2)); // Both root->r->l and root->r->r are unbounded. EXPECT_EQ(dut.bnb()->best_upper_bound(), std::numeric_limits<double>::infinity()); EXPECT_EQ(dut.bnb()->best_lower_bound(), -std::numeric_limits<double>::infinity()); EXPECT_TRUE(dut.bnb()->solutions().empty()); EXPECT_TRUE(dut.bnb()->IsLeafNodeFathomed( *(dut.bnb()->root()->right_child()->left_child()))); EXPECT_TRUE(dut.bnb()->IsLeafNodeFathomed( *(dut.bnb()->root()->right_child()->right_child()))); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestBranchAndUpdate4) { // TestBranchAndUpdate for prog4. auto prog = ConstructMathematicalProgram4(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); const VectorDecisionVariable<5> x = dut.bnb()->root()->prog()->decision_variables(); dut.BranchAndUpdate(dut.mutable_root(), x(3)); EXPECT_EQ(dut.bnb()->best_upper_bound(), std::numeric_limits<double>::infinity()); EXPECT_EQ(dut.bnb()->best_lower_bound(), std::numeric_limits<double>::infinity()); dut.BranchAndUpdate(dut.mutable_root(), x(4)); EXPECT_EQ(dut.bnb()->best_upper_bound(), std::numeric_limits<double>::infinity()); EXPECT_EQ(dut.bnb()->best_lower_bound(), std::numeric_limits<double>::infinity()); } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestSolve1) { // Test Solve() function for prog 1. auto prog = ConstructMathematicalProgram1(); const VectorDecisionVariable<4> x = prog->decision_variables(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); const SolutionResult solution_result = dut.bnb()->Solve(); EXPECT_EQ(solution_result, SolutionResult::kSolutionFound); const Eigen::Vector4d x_expected(0, 1, 0, 0.5); const double tol{1E-3}; // The root node finds an optimal integral solution, and the bnb terminates. EXPECT_EQ(dut.bnb()->solutions().size(), 1); EXPECT_NEAR(dut.bnb()->GetOptimalCost(), 1.5, tol); EXPECT_TRUE(CompareMatrices(dut.bnb()->GetSolution(x, 0), x_expected, tol, MatrixCompareType::absolute)); } std::vector<MixedIntegerBranchAndBound::NodeSelectionMethod> NonUserDefinedPickNodeMethods() { return {MixedIntegerBranchAndBound::NodeSelectionMethod::kDepthFirst, MixedIntegerBranchAndBound::NodeSelectionMethod::kMinLowerBound}; } std::vector<MixedIntegerBranchAndBound::VariableSelectionMethod> NonUserDefinedPickVariableMethods() { return { MixedIntegerBranchAndBound::VariableSelectionMethod::kMostAmbivalent, MixedIntegerBranchAndBound::VariableSelectionMethod::kLeastAmbivalent}; } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestSolve2) { auto prog = ConstructMathematicalProgram2(); const VectorDecisionVariable<5> x = prog->decision_variables(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); for (auto pick_variable : NonUserDefinedPickVariableMethods()) { for (auto pick_node : NonUserDefinedPickNodeMethods()) { dut.bnb()->SetNodeSelectionMethod(pick_node); dut.bnb()->SetVariableSelectionMethod(pick_variable); const SolutionResult solution_result = dut.bnb()->Solve(); EXPECT_EQ(solution_result, SolutionResult::kSolutionFound); const double tol{1E-3}; EXPECT_NEAR(dut.bnb()->GetOptimalCost(), -13.0 / 3, tol); Eigen::Matrix<double, 5, 1> x_expected0; x_expected0 << 1, 1.0 / 3.0, 1, 1, 0; EXPECT_TRUE(CompareMatrices(dut.bnb()->GetSolution(x, 0), x_expected0, tol, MatrixCompareType::absolute)); // The costs are in the ascending order. double previous_cost = dut.bnb()->GetOptimalCost(); for (int i = 1; i < static_cast<int>(dut.bnb()->solutions().size()); ++i) { EXPECT_GE(dut.bnb()->GetSubOptimalCost(i - 1), previous_cost); previous_cost = dut.bnb()->GetSubOptimalCost(i - 1); } } } } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestSolve3) { auto prog = ConstructMathematicalProgram3(); const VectorDecisionVariable<4> x = prog->decision_variables(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); for (auto pick_variable : NonUserDefinedPickVariableMethods()) { for (auto pick_node : NonUserDefinedPickNodeMethods()) { dut.bnb()->SetNodeSelectionMethod(pick_node); dut.bnb()->SetVariableSelectionMethod(pick_variable); const SolutionResult solution_result = dut.bnb()->Solve(); EXPECT_EQ(solution_result, SolutionResult::kUnbounded); } } } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestSolve4) { auto prog = ConstructMathematicalProgram4(); const VectorDecisionVariable<5> x = prog->decision_variables(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); for (auto pick_variable : NonUserDefinedPickVariableMethods()) { for (auto pick_node : NonUserDefinedPickNodeMethods()) { dut.bnb()->SetNodeSelectionMethod(pick_node); dut.bnb()->SetVariableSelectionMethod(pick_variable); const SolutionResult solution_result = dut.bnb()->Solve(); EXPECT_EQ(solution_result, SolutionResult::kInfeasibleConstraints); } } } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestSteelBlendingProblem) { // This problem is taken from // "An application of Mixed Integer Programming in a Swedish Steel Mill" // by Carl-Henrik Westerberg, Bengt Bjorklund and Eskil Hultman // on Interfaces, 1977 // The formulation is // min 1750 * b₀ + 990 * b₁ + 1240 * b₂ + 1680 * b₃ + 550 * x₀ + // 450 * x₁ + 400 * x₂ + 100 * x₃ // s.t 5 * b₀ + 3 * b₁ + 4 * b₂ + 6 * b₃ + x₀ + x₁ + x₂ + x₃ // = 25 // 0.25 * b₀ + 0.12 * b₁ + 0.2 * b₂ + 0.18 * b₃ + 0.08 * x₀ + // 0.07 * x₁ + 0.06 * x₂ + 0.03 * x₃ = 1.25 // 0.15 * b₀ + 0.09 * b₁ + 0.16 * b₂ + 0.24 * b₃ + 0.06 * x₀ + // 0.07 * x₁ + 0.08 * x₂ + 0.09 * x₃ = 1.25 // x ≥ 0 // b are binary variables. MathematicalProgram prog; auto b = prog.NewBinaryVariables<4>("b"); auto x = prog.NewContinuousVariables<4>("x"); prog.AddLinearCost(1750 * b(0) + 990 * b(1) + 1240 * b(2) + 1680 * b(3) + 500 * x(0) + 450 * x(1) + 400 * x(2) + 100 * x(3)); prog.AddLinearConstraint(5 * b(0) + 3 * b(1) + 4 * b(2) + 6 * b(3) + x(0) + x(1) + x(2) + x(3) == 25); prog.AddLinearConstraint(0.25 * b(0) + 0.12 * b(1) + 0.2 * b(2) + 0.18 * b(3) + 0.08 * x(0) + 0.07 * x(1) + 0.06 * x(2) + 0.03 * x(3) == 1.25); prog.AddLinearConstraint(0.15 * b(0) + 0.09 * b(1) + 0.16 * b(2) + 0.24 * b(3) + 0.06 * x(0) + 0.07 * x(1) + 0.08 * x(2) + 0.09 * x(3) == 1.25); prog.AddBoundingBoxConstraint(0, std::numeric_limits<double>::infinity(), x); MixedIntegerBranchAndBound bnb(prog, GurobiSolver::id()); for (auto pick_variable : NonUserDefinedPickVariableMethods()) { for (auto pick_node : NonUserDefinedPickNodeMethods()) { bnb.SetNodeSelectionMethod(pick_node); bnb.SetVariableSelectionMethod(pick_variable); SolutionResult solution_result = bnb.Solve(); EXPECT_EQ(solution_result, SolutionResult::kSolutionFound); const double tol = 1E-3; const Eigen::Vector4d b_expected0(1, 1, 0, 1); const Eigen::Vector4d x_expected0(7.25, 0, 0.25, 3.5); EXPECT_TRUE(CompareMatrices(bnb.GetSolution(x), x_expected0, tol, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(bnb.GetSolution(b), b_expected0, tol, MatrixCompareType::absolute)); EXPECT_NEAR(bnb.GetOptimalCost(), 8495, tol); double previous_cost = bnb.GetOptimalCost(); for (int i = 1; i < static_cast<int>(bnb.solutions().size()); ++i) { EXPECT_GE(bnb.GetSubOptimalCost(i - 1), previous_cost); previous_cost = bnb.GetSubOptimalCost(i - 1); } } } } void CheckAllIntegralSolution( const MixedIntegerBranchAndBound& bnb, const Eigen::Ref<const VectorXDecisionVariable>& x, const std::vector<std::pair<double, Eigen::VectorXd>>& all_integral_solutions, double tol) { EXPECT_LE(bnb.solutions().size(), all_integral_solutions.size()); EXPECT_NEAR(bnb.GetOptimalCost(), all_integral_solutions[0].first, tol); EXPECT_TRUE(CompareMatrices(bnb.GetSolution(x), all_integral_solutions[0].second, tol)); double previous_cost = bnb.GetOptimalCost(); for (int i = 1; i < static_cast<int>(bnb.solutions().size()); ++i) { const double cost_i = bnb.GetSubOptimalCost(i - 1); EXPECT_GE(cost_i, previous_cost - tol); previous_cost = cost_i; bool found_match = false; for (int j = 1; j < static_cast<int>(all_integral_solutions.size()); ++j) { if (std::abs(cost_i - all_integral_solutions[j].first) < tol && (bnb.GetSolution(x, i) - all_integral_solutions[j].second).norm() < tol) { found_match = true; break; } } EXPECT_TRUE(found_match); } } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestMultipleIntegralSolution1) { // Test a program with multiple integral solutions. // Given points P1 = (0, 3), P2 = (1, 1), P3 = (2, 2), P4 = (4, 5), // P5 = (5, 1), and the line segments connecting P1P2, P2P3, P3P4, P4P5, // find the point with the smallest x coordinate, with y coordinate equal // to 4. // min x₁ + 2 * x₂ + 3 * x₃ + 4 * x(4) // s.t x₀ ≤ y₀ // x₁ ≤ y₀ + y₁ // x₂ ≤ y₁ + y₂ // x₃ ≤ y₂ + y₃ // x(4) ≤ y₃ // y₀ + y₁ + y₂ + y₃ = 1 // x₀ + x₁ + x₂ + x₃ + x(4) = 1 // 3*x₀ + x₁ + 2*x₂ + 5*x₃ + x(4) = 4 // x ≥ 0 // y are binary variables. // This formulation is obtained by using the special ordered set constraint // with yᵢ being the indicator binary variable that the point is on the line // segment PᵢPᵢ₊₁ // The optimal solution is x = (0, 0, 1/3, 2/3, 0), y = (0, 0, 1, 0), with // optimal cost 8/3. // There are other integral solutions, // x = (0, 0, 0, 0.25, 75), y = (0, 0, 0, 1), with cost 13/4 MathematicalProgram prog; auto x = prog.NewContinuousVariables<5>("x"); auto y = prog.NewBinaryVariables<4>("y"); AddSos2Constraint(&prog, x.cast<symbolic::Expression>(), y.cast<symbolic::Expression>()); prog.AddLinearCost(x(1) + 2 * x(2) + 3 * x(3) + 4 * x(4)); prog.AddLinearConstraint(3 * x(0) + x(1) + 2 * x(2) + 5 * x(3) + x(4) == 4); prog.AddBoundingBoxConstraint(0, 1, x); MixedIntegerBranchAndBound bnb(prog, GurobiSolver::id()); for (auto pick_variable : NonUserDefinedPickVariableMethods()) { for (auto pick_node : NonUserDefinedPickNodeMethods()) { bnb.SetNodeSelectionMethod(pick_node); bnb.SetVariableSelectionMethod(pick_variable); SolutionResult solution_result = bnb.Solve(); EXPECT_EQ(solution_result, SolutionResult::kSolutionFound); std::vector<std::pair<double, Eigen::VectorXd>> best_solutions; Eigen::Matrix<double, 9, 1> xy_expected; xy_expected << 0, 0, 1.0 / 3, 2.0 / 3, 0, 0, 0, 1, 0; best_solutions.emplace_back(8.0 / 3, xy_expected); xy_expected << 0, 0, 0, 0.25, 75, 0, 0, 0, 1; best_solutions.emplace_back(13.0 / 4, xy_expected); const double tol{1E-3}; VectorDecisionVariable<9> xy; xy << x, y; CheckAllIntegralSolution(bnb, xy, best_solutions, tol); } } } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestMultipleIntegralSolution2) { // Test a program with multiple integral solutions. // Given points P1 = (0, 3), P2 = (1, 1), P3 = (2, 4), P4 = (3, 2), and // the line segments connecting P1P2, P2P3, and P3P4. Find the closest point // on the line segment to the point (1.5, 2) // This problem can be formulated as // min (x₁ + 2*x₂+3*x₃ - 1.5)² + (3*x₀ + x₁ + 4*x₂ + 2*x₃)² // s.t x₀ ≤ y₀ // x₁ ≤ y₀ + y₁ // x₂ ≤ y₁ + y₂ // x₃ ≤ y₂ // y₀ + y₁ + y₂ = 1 // x₀ + x₁ + x₂ + x₃ = 1 // x ≥ 0 // y are binary variables. // This formulation is obtained by using the special ordered set constraint // with yᵢ being the indicator binary variable that the point is on the line // segment PᵢPᵢ₊₁ // The optimal solution is x = (0, 0.65, 0.35, 0), y = (0, 1, 0), with optimal // cost 0.025 // The other integral solutions are // x = (0.3, 0.7, 0, 0), y = (1, 0, 0), with cost 0.8 // x = (0, 0, 0.3, 0.7), y = (0, 0, 1), with cost 1.8 // Namely on each of the line segment, there is a closest point, corresponding // to one integral solution. MathematicalProgram prog; auto x = prog.NewContinuousVariables<4>("x"); auto y = prog.NewBinaryVariables<3>("y"); AddSos2Constraint(&prog, x.cast<symbolic::Expression>(), y.cast<symbolic::Expression>()); Eigen::Matrix<symbolic::Expression, 2, 1> pt; pt << x(1) + 2 * x(2) + 3 * x(3), 3 * x(0) + x(1) + 4 * x(2) + 2 * x(3); prog.AddQuadraticCost((pt - Eigen::Vector2d(1.5, 2)).squaredNorm()); MixedIntegerBranchAndBound bnb(prog, GurobiSolver::id()); for (auto pick_variable : NonUserDefinedPickVariableMethods()) { for (auto pick_node : NonUserDefinedPickNodeMethods()) { bnb.SetNodeSelectionMethod(pick_node); bnb.SetVariableSelectionMethod(pick_variable); const SolutionResult solution_result = bnb.Solve(); EXPECT_EQ(solution_result, SolutionResult::kSolutionFound); std::vector<std::pair<double, Eigen::VectorXd>> integral_solutions; Eigen::Matrix<double, 7, 1> xy_expected; xy_expected << 0, 0.65, 0.35, 0, 0, 1, 0; integral_solutions.emplace_back(0.025, xy_expected); xy_expected << 0.3, 0.7, 0, 0, 1, 0, 0; integral_solutions.emplace_back(0.8, xy_expected); xy_expected << 0, 0, 0.3, 0.7, 0, 0, 1; integral_solutions.emplace_back(1.8, xy_expected); const double tol{1E-3}; VectorDecisionVariable<7> xy; xy << x, y; CheckAllIntegralSolution(bnb, xy, integral_solutions, tol); } } } GTEST_TEST(MixedIntegerBranchAndBoundTest, SearchIntegralSolutionByRounding2) { // Test searching an integral solution by rounding the fractional solution to // binary values, and solve the continuous variables. // Test on prog2. auto prog = ConstructMathematicalProgram2(); VectorDecisionVariable<5> x = prog->decision_variables(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); // The solution to the root node is (0.7, 1, 1, 1.4, 0), with optimal cost // -4.9. We will add the constraint x₀ = 1, x₂ = 1, x₄ = 0, and then solve the // continuous variables. // The optimal solution to this new program is (1, 1/3, 1, 1, 0), with cost // -13 / 3. This is also the optimal solution to the MIP prog2. dut.SearchIntegralSolutionByRounding(*(dut.bnb()->root())); const double tol{1E-5}; EXPECT_NEAR(dut.bnb()->best_upper_bound(), -13.0 / 3, tol); // The best lower bound is unchanged after solving the new program with fixed // binary variables. EXPECT_NEAR(dut.bnb()->best_lower_bound(), -4.9, tol); Eigen::Matrix<double, 5, 1> x_expected; x_expected << 1, 1.0 / 3, 1, 1, 0; EXPECT_TRUE(CompareMatrices(dut.bnb()->GetSolution(x), x_expected, tol, MatrixCompareType::absolute)); // Now test to solve the mip with searching for integral solution by rounding. // The branch-and-bound should terminate at the root node, as it should find // the optimal integral solution at the root. MixedIntegerBranchAndBound bnb(*prog, GurobiSolver::id()); bnb.SetSearchIntegralSolutionByRounding(true); const SolutionResult result = bnb.Solve(); EXPECT_EQ(result, SolutionResult::kSolutionFound); } GTEST_TEST(MixedIntegerBranchAndBoundTest, SearchIntegralSolutionByRounding3) { // Test searching an integral solution by rounding the fractional solution to // binary values, and solve the continuous variables. // Test on prog3. auto prog = ConstructMathematicalProgram3(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); // The solution to the root node is unbounded. If we fix the binary variables // and search for the continuous variables, the new program is still // unbounded. dut.SearchIntegralSolutionByRounding(*(dut.bnb()->root())); EXPECT_EQ(dut.bnb()->best_upper_bound(), std::numeric_limits<double>::infinity()); EXPECT_EQ(dut.bnb()->best_lower_bound(), -std::numeric_limits<double>::infinity()); } GTEST_TEST(MixedIntegerBranchAndBoundTest, SearchIntegralSolutionByRounding4) { // Test searching an integral solution by rounding the fractional solution to // binary values, and solve the continuous variables. // Test on prog4. auto prog = ConstructMathematicalProgram4(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); // The optimal solution to the root node is (1/3, 1/3, 1/3, 2/3, 1/3), with // optimal cost 4/3. We will add the constraint y₀ = 1, y₁ = 0, and solve for // the continuous variable x. The new problem is infeasible. dut.SearchIntegralSolutionByRounding(*(dut.bnb()->root())); const double tol{1E-5}; EXPECT_EQ(dut.bnb()->best_upper_bound(), std::numeric_limits<double>::infinity()); // This best lower bound is unchanged, after we search for the integral // solution, since the new program is infeasible. EXPECT_NEAR(dut.bnb()->best_lower_bound(), 4.0 / 3, tol); } MixedIntegerBranchAndBoundNode* LeftMostNodeInSubTree( const MixedIntegerBranchAndBound& branch_and_bound, const MixedIntegerBranchAndBoundNode& subtree_root) { // Find the left most leaf node that is not fathomed. if (subtree_root.IsLeaf()) { if (branch_and_bound.IsLeafNodeFathomed(subtree_root)) { return nullptr; } else { return const_cast<MixedIntegerBranchAndBoundNode*>(&subtree_root); } } else { auto left_most_node_left_tree = LeftMostNodeInSubTree(branch_and_bound, *(subtree_root.left_child())); if (!left_most_node_left_tree) { return LeftMostNodeInSubTree(branch_and_bound, *(subtree_root.right_child())); } return left_most_node_left_tree; } } GTEST_TEST(MixedIntegerBranchAndBoundTest, TestSetUserDefinedNodeSelectionFunction) { // Test setting user defined node selection function. // Here we set to choose the left-most unfathomed node. auto prog = ConstructMathematicalProgram2(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); dut.bnb()->SetNodeSelectionMethod( MixedIntegerBranchAndBound::NodeSelectionMethod::kUserDefined); dut.bnb()->SetUserDefinedNodeSelectionFunction( [](const MixedIntegerBranchAndBound& branch_and_bound) { return LeftMostNodeInSubTree(branch_and_bound, *(branch_and_bound.root())); }); // There is only one root node, so bnb has to pick the root node. EXPECT_EQ(dut.PickBranchingNode(), dut.bnb()->root()); VectorDecisionVariable<5> x = dut.bnb()->root()->prog()->decision_variables(); dut.BranchAndUpdate(dut.mutable_root(), x(2)); // root->left has integral solution, so it is fathomed. // root->right has non-integral solution, so it is not fathomed. EXPECT_TRUE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->left_child()))); EXPECT_FALSE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->right_child()))); // The left-most un-fathomed node is root->right. EXPECT_EQ(dut.PickBranchingNode(), dut.bnb()->root()->right_child()); dut.BranchAndUpdate(dut.mutable_root(), x(4)); // root->left has non-integral solution, so it is not fathomed. // root->right has non-integral solution, so it is not fathomed. EXPECT_FALSE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->left_child()))); EXPECT_FALSE( dut.bnb()->IsLeafNodeFathomed(*(dut.bnb()->root()->right_child()))); // The left-most un-fathomed node is root->left. EXPECT_EQ(dut.PickBranchingNode(), dut.bnb()->root()->left_child()); } GTEST_TEST(MixedIntegerBranchAndBoundTest, NodeCallbackTest) { // Test node callback function. // In this trivial test, we just count how many nodes has been explored. int num_visited_nodes = 1; auto call_back_fun = [&num_visited_nodes]( const MixedIntegerBranchAndBoundNode& node, MixedIntegerBranchAndBound* bnb) { ++num_visited_nodes; }; auto prog = ConstructMathematicalProgram2(); MixedIntegerBranchAndBoundTester dut(*prog, GurobiSolver::id()); dut.bnb()->SetUserDefinedNodeCallbackFunction(call_back_fun); // Initially, only the root node has been visited. EXPECT_EQ(num_visited_nodes, 1); VectorDecisionVariable<5> x = dut.bnb()->root()->prog()->decision_variables(); // Every branch increments the number of visited nodes by 2. dut.BranchAndUpdate(dut.mutable_root(), x(0)); EXPECT_EQ(num_visited_nodes, 3); dut.BranchAndUpdate(dut.mutable_root(), x(2)); EXPECT_EQ(num_visited_nodes, 5); } GTEST_TEST(MixedIntegerBranchAndBoundTest, MaxNodesInTree) { // Test the option max_nodes_in_tree. auto prog = ConstructMathematicalProgram2(); MixedIntegerBranchAndBoundTester dut1(*prog, GurobiSolver::id()); dut1.bnb()->Solve(); const int dut1_num_nodes = dut1.bnb()->root()->NumExploredNodesInSubtree(); EXPECT_TRUE(dut1.HasConverged()); // Make sure that dut1 has more than one explored node in the tree. Otherwise // dut1_num_nodes-1 would be non-positive, which we regard as no upper limit // on the number of nodes. ASSERT_GT(dut1_num_nodes, 1); MixedIntegerBranchAndBound::Options options{}; options.max_explored_nodes = dut1_num_nodes - 1; MixedIntegerBranchAndBoundTester dut2(*prog, GurobiSolver::id(), options); const auto dut2_solution_result = dut2.bnb()->Solve(); EXPECT_LE(dut2.bnb()->root()->NumExploredNodesInSubtree(), options.max_explored_nodes); EXPECT_FALSE(dut2.HasConverged()); EXPECT_EQ(dut2_solution_result, SolutionResult::kIterationLimit); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/mathematical_program_test_util.h
#pragma once #include <optional> #include <utility> #include <vector> #include <gtest/gtest.h> #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solver_interface.h" namespace drake { namespace solvers { namespace test { /// Run solver.Solve() on the given @p prog. If the solver is absent or does /// not find a solution, stop immediately via an exception. (Were we to /// continue, testing statements that examine the results would be likely to /// fail with confusing messages, so best to avoid them entirely.) MathematicalProgramResult RunSolver( const MathematicalProgram& prog, const SolverInterface& solver, const std::optional<Eigen::VectorXd>& initial_guess = {}, const std::optional<SolverOptions>& solver_options = {}); /// Determine if two bindings are the same. Two bindings are the same if /// /// 1. They contain the same constraint pointer. /// 2. Their bound variables are the same. template <typename Constraint> ::testing::AssertionResult IsBindingEqual(const Binding<Constraint>& binding1, const Binding<Constraint>& binding2) { if (binding1.evaluator() != binding2.evaluator()) { return ::testing::AssertionFailure() << "Constraint pointers are not the same."; } if (binding1.variables().rows() != binding2.variables().rows()) { return ::testing::AssertionFailure() << "Constraint variable sizes are not the same."; } for (int i = 0; i < binding1.variables().rows(); ++i) { if (!binding1.variables()(i).equal_to(binding2.variables()(i))) { return ::testing::AssertionFailure() << "Constraint variable mismatch:(" << binding1.variables()(i) << " vs. " << binding2.variables()(i) << ")"; } } return ::testing::AssertionSuccess() << "Same binding."; } /// Determines if two vectors of bindings are the same. template <typename Constraint> ::testing::AssertionResult IsVectorOfBindingEqual( const std::vector<Binding<Constraint>>& bindings1, const std::vector<Binding<Constraint>>& bindings2) { if (bindings1.size() != bindings2.size()) { return ::testing::AssertionFailure() << "Size mismatches: (" << bindings1.size() << " vs. " << bindings2.size() << ")."; } for (int i = 0; i < static_cast<int>(bindings1.size()); ++i) { auto result = IsBindingEqual(bindings1[i], bindings2[i]); if (!result) return result; } return ::testing::AssertionSuccess() << " Same bindings."; } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/generic_trivial_costs.h
#pragma once #include <cstddef> #include <limits> #include "drake/common/autodiff.h" #include "drake/common/drake_assert.h" #include "drake/common/drake_copyable.h" #include "drake/common/eigen_types.h" #include "drake/math/autodiff.h" #include "drake/solvers/cost.h" #include "drake/solvers/function.h" namespace drake { namespace solvers { namespace test { // A generic cost derived from Constraint class. This is meant for testing // adding a cost to optimization program, and the cost is in the form of a // derived class of Constraint. class GenericTrivialCost1 : public Cost { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GenericTrivialCost1) GenericTrivialCost1() : Cost(3), private_val_(2) {} protected: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { DoEvalGeneric(x, y); } private: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const { y->resize(1); (*y)(0) = x(0) * x(1) + x(2) / x(0) * private_val_; } // Add a private data member to make sure no slicing on this class, derived // from Constraint. double private_val_{0}; }; // A generic cost. This class is meant for testing adding a cost to the // optimization program, by calling `MathematicalProgram::MakeCost` to // convert this class to a ConstraintImpl object. class GenericTrivialCost2 { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(GenericTrivialCost2) GenericTrivialCost2() = default; static size_t numInputs() { return 2; } static size_t numOutputs() { return 1; } template <typename ScalarType> void eval(internal::VecIn<ScalarType> const& x, internal::VecOut<ScalarType>* y) const { DRAKE_ASSERT(static_cast<size_t>(x.rows()) == numInputs()); DRAKE_ASSERT(static_cast<size_t>(y->rows()) == numOutputs()); (*y)(0) = x(0) * x(0) - x(1) * x(1) + 2; } }; } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/scaled_diagonally_dominant_dual_cone_matrix_test.cc
#include <gtest/gtest.h> #include "drake/common/ssize.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solve.h" namespace drake { namespace solvers { namespace { // Make all the generator of the SDD dual cone, namely the n x 2 matrices V // where each column has exactly one non-zero element equal to 1. std::vector<Eigen::MatrixX2d> MakeSDDDualConeGenerator(int n) { std::vector<Eigen::MatrixX2d> generators(n * n, Eigen::MatrixX2d::Zero(n, 2)); int ctr = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { generators.at(ctr)(i, 0) = 1; generators.at(ctr)(j, 1) = 1; ++ctr; } } return generators; } // Returns the first index of the extreme ray V for which VᵀXV is not positive // semidefinite. If no such index exists, returns -1 and X is in SDD*. int TestInDualConeByGenerators(const Eigen::MatrixXd& X) { DRAKE_DEMAND(X.rows() == X.cols()); const std::vector<Eigen::MatrixX2d> generators = MakeSDDDualConeGenerator(X.rows()); Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> solver; for (int i = 0; i < ssize(generators); ++i) { const Eigen::Matrix2d product = generators.at(i).transpose() * X * generators.at(i); solver.compute(product); if (!(solver.eigenvalues().array() >= -1e-12).all()) { return i; } } return -1; } GTEST_TEST(ScaledDiagonallyDominantMatrixDualConeConstraint, SizeOfReturnTest) { // Test the number of constraints added to the program. This should be n // choose 2 for any choice of matrix X of size n. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<5>(); auto dual_cone_constraints = prog.AddScaledDiagonallyDominantDualConeMatrixConstraint( X.cast<symbolic::Expression>()); EXPECT_EQ(dual_cone_constraints.size(), 10); auto X2 = prog.NewSymmetricContinuousVariables<7>(); auto dual_cone_constraints2 = prog.AddScaledDiagonallyDominantDualConeMatrixConstraint( X2.cast<symbolic::Expression>()); EXPECT_EQ(dual_cone_constraints2.size(), 21); } GTEST_TEST(ScaledDiagonallyDominantMatrixDualConeConstraint, FeasibilityCheck3by3Variable) { // SDD = PD = PD* = SDD* when n = 2, so the smallest meaningful test is 3. // Test that SDD* matrices are feasible. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); auto dual_cone_constraints = prog.AddScaledDiagonallyDominantDualConeMatrixConstraint(X); VectorXDecisionVariable x_flat(6); x_flat << X(0, 0), X(0, 1), X(0, 2), X(1, 1), X(1, 2), X(2, 2); auto X_constraint = prog.AddBoundingBoxConstraint( Eigen::VectorXd::Zero(6), Eigen::VectorXd::Zero(6), x_flat); auto set_X_value = [&X_constraint](const Eigen::Matrix3d& X_val) { Eigen::VectorXd x_upper_triangle(6); x_upper_triangle << X_val(0, 0), X_val(0, 1), X_val(0, 2), X_val(1, 1), X_val(1, 2), X_val(2, 2); X_constraint.evaluator()->UpdateLowerBound(x_upper_triangle); X_constraint.evaluator()->UpdateUpperBound(x_upper_triangle); }; // This matrix is in both PSD and SDD* Eigen::Matrix3d test1; // clang-format off test1 << 2., 1., 1., 1., 3., 1., 1., 1., 4.; // clang-format on set_X_value(test1); MathematicalProgramResult result = Solve(prog); EXPECT_TRUE(result.is_success()); EXPECT_EQ(TestInDualConeByGenerators(result.GetSolution(X)), -1); // This matrix is in both SDD* but not is not PSD. Eigen::Matrix3d test2; // clang-format off test2 << 32., 8., 0., 8., 2., 3., 0., 3., 8.; // clang-format on set_X_value(test2); result = Solve(prog); EXPECT_TRUE(result.is_success()); EXPECT_EQ(TestInDualConeByGenerators(result.GetSolution(X)), -1); // This matrix is in DD* but not SDD*. Eigen::Matrix3d test3; // clang-format off test3 << 32., 9., 0., 9., 2., 3., 0., 3., 8.; // clang-format on set_X_value(test3); result = Solve(prog); EXPECT_FALSE(result.is_success()); EXPECT_GE(TestInDualConeByGenerators(result.GetSolution(X)), -1); // Verifies that test3 matrix is in DD*. MathematicalProgram prog_dd = MathematicalProgram(); auto X_dd = prog_dd.NewSymmetricContinuousVariables<3>(); auto dd_dual_cone_constraints = prog_dd.AddPositiveDiagonallyDominantDualConeMatrixConstraint(X_dd); Eigen::VectorXd test3_flat(6); test3_flat << test3(0, 0), test3(0, 1), test3(0, 2), test3(1, 1), test3(1, 2), test3(2, 2); VectorXDecisionVariable x_dd_flat(6); x_dd_flat << X_dd(0, 0), X_dd(0, 1), X_dd(0, 2), X_dd(1, 1), X_dd(1, 2), X_dd(2, 2); auto X_dd_constraint = prog_dd.AddBoundingBoxConstraint(test3_flat, test3_flat, x_dd_flat); auto result_dd = Solve(prog_dd); EXPECT_TRUE(result_dd.is_success()); } GTEST_TEST(ScaledDiagonallyDominantMatrixDualConeConstraint, FeasibilityCheck3by3Expression) { // SDD = PD = PD* = SDD* when n = 2, so the smallest meaningful test is 3. // Test that SDD* matrices are feasible. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); auto Y = prog.NewSymmetricContinuousVariables<3>(); MatrixX<symbolic::Expression> Z(3, 3); Z = 2. * X + 3. * Y; auto GetZResult = [&Z](const MathematicalProgramResult& result) -> Eigen::MatrixXd { return result.GetSolution(Z).unaryExpr([](const symbolic::Expression& x) { return x.Evaluate(); }); }; VectorX<symbolic::Expression> z_upper(6); z_upper << Z(0, 0), Z(0, 1), Z(0, 2), Z(1, 1), Z(1, 2), Z(2, 2); auto dual_cone_constraints = prog.AddScaledDiagonallyDominantDualConeMatrixConstraint(Z); auto Z_constraint = prog.AddLinearEqualityConstraint(z_upper, Eigen::VectorXd::Zero(6)); auto set_Z_value = [&Z_constraint](const Eigen::Matrix3d& Z_val) { Eigen::VectorXd z_upper_triangle(6); z_upper_triangle << Z_val(0, 0), Z_val(0, 1), Z_val(0, 2), Z_val(1, 1), Z_val(1, 2), Z_val(2, 2); Z_constraint.evaluator()->UpdateLowerBound(z_upper_triangle); Z_constraint.evaluator()->UpdateUpperBound(z_upper_triangle); }; // This matrix is in both PSD and SDD* Eigen::Matrix3d test1; // clang-format off test1 << 2., 1., 1., 1., 3., 1., 1., 1., 4.; // clang-format on set_Z_value(test1); MathematicalProgramResult result = Solve(prog); EXPECT_TRUE(result.is_success()); EXPECT_EQ(TestInDualConeByGenerators(GetZResult(result)), -1); // This matrix is in both SDD* but not is not PSD. Eigen::Matrix3d test2; // clang-format off test2 << 32., 8., 0., 8., 2., 3., 0., 3., 8.; // clang-format on set_Z_value(test2); result = Solve(prog); EXPECT_TRUE(result.is_success()); EXPECT_EQ(TestInDualConeByGenerators(GetZResult(result)), -1); // This matrix is in DD* but not SDD*. Eigen::Matrix3d test3; // clang-format off test3 << 32., 9., 0., 9., 2., 3., 0., 3., 8.; // clang-format on set_Z_value(test3); result = Solve(prog); EXPECT_FALSE(result.is_success()); EXPECT_GE(TestInDualConeByGenerators(GetZResult(result)), -1); // Verifies that test3 matrix is in DD*. MathematicalProgram prog_dd = MathematicalProgram(); auto X_dd = prog_dd.NewSymmetricContinuousVariables<3>(); auto dd_dual_cone_constraints = prog_dd.AddPositiveDiagonallyDominantDualConeMatrixConstraint( X_dd.cast<symbolic::Expression>()); Eigen::VectorXd test3_flat(6); test3_flat << test3(0, 0), test3(0, 1), test3(0, 2), test3(1, 1), test3(1, 2), test3(2, 2); VectorXDecisionVariable x_dd_flat(6); x_dd_flat << X_dd(0, 0), X_dd(0, 1), X_dd(0, 2), X_dd(1, 1), X_dd(1, 2), X_dd(2, 2); auto X_dd_constraint = prog_dd.AddBoundingBoxConstraint(test3_flat, test3_flat, x_dd_flat); auto result_dd = Solve(prog_dd); EXPECT_TRUE(result_dd.is_success()); } GTEST_TEST(ScaledDiagonallyDominantMatrixDualConeConstraint, MaximizeOffDiagonalTest) { // For a matrix to be in SDD*, we have to have that XₖₖXⱼⱼ ≥ Xₖⱼ * Xⱼₖ // We consider the matrix // [1 a b c] // A = [a 2 d e] // [b d 3 f] // [c e f 4] // In this test we maximize x ∈ {a,b,c,d,e,f} while constraining all other // variables to be equal to 0 to obtain optimal solutions (√2, 0, 0, 0, 0, 0), // (0, √3, 0, 0, 0, 0), (0, 0, 2, 0, 0, 0), (0, 0, 0, √6, 0, 0), (0, 0, 0, 0, // √8, 0), (0, 0, 0, 0, 0, √12) // Tests // max A(i,j) subject to // A ∈ SDD* // A(r,c) = 0 if r > c and (r,c) ≠ (i,j) // The optimal solution should be A(i,j) = √(A(i,i)*A(j,j)) auto TestIdx = [](int i, int j) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<4>("X"); auto Y = prog.NewSymmetricContinuousVariables<4>("Y"); MatrixX<symbolic::Expression> Z(4, 4); Z = 2. * X + 3. * Y; prog.AddBoundingBoxConstraint(Eigen::Vector4d(1, 2, 3, 4), Eigen::Vector4d(1, 2, 3, 4), X.diagonal()); // Y is constrained to be 0 so we can control the value of Z. prog.AddLinearEqualityConstraint(Y == Eigen::Matrix4d::Zero()); auto dual_cone_constraints = prog.AddScaledDiagonallyDominantDualConeMatrixConstraint(X); auto dual_cone_constraints_Z = prog.AddScaledDiagonallyDominantDualConeMatrixConstraint(Z); for (int r = 0; r < X.rows(); ++r) { for (int c = r + 1; c < X.cols(); ++c) { if (r != i || c != j) { prog.AddLinearEqualityConstraint(X(r, c) == 0); } } } prog.AddLinearCost(-X(i, j)); MathematicalProgramResult result = Solve(prog); EXPECT_TRUE(result.is_success()); Eigen::Matrix4d X_res = result.GetSolution(X); Eigen::Matrix4d Z_res = result.GetSolution(Z).unaryExpr([](const symbolic::Expression& x) { return x.Evaluate(); }); Eigen::Matrix4d X_expected = Eigen::Matrix4d::Zero(); X_expected.diagonal() = Eigen::Vector4d(1, 2, 3, 4); X_expected(i, j) = sqrt(X_expected(i, i) * X_expected(j, j)); X_expected(j, i) = X_expected(i, j); EXPECT_TRUE(CompareMatrices(X_res, X_expected, 1e-8)); // Y is constrained to be 0 so we expect the value of Z = 2*X. EXPECT_TRUE(CompareMatrices(Z_res, 2 * X_expected, 1e-8)); EXPECT_EQ(TestInDualConeByGenerators(X_res), -1); EXPECT_EQ(TestInDualConeByGenerators(Z_res), -1); }; for (int i = 0; i < 4; ++i) { for (int j = i + 1; j < 4; ++j) { TestIdx(i, j); } } } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/evaluator_base_test.cc
#include "drake/solvers/evaluator_base.h" #include <iostream> #include <limits> #include <memory> #include <stdexcept> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/is_dynamic_castable.h" #include "drake/math/autodiff.h" #include "drake/math/autodiff_gradient.h" using std::cout; using std::endl; using std::make_shared; using std::make_unique; using std::numeric_limits; using std::runtime_error; using std::shared_ptr; using std::unique_ptr; using std::vector; using drake::Vector1d; using Eigen::MatrixXd; using Eigen::Ref; using Eigen::Vector2d; using Eigen::VectorXd; using ::testing::AssertionFailure; using ::testing::AssertionResult; using ::testing::AssertionSuccess; namespace drake { namespace solvers { namespace { // Generic dereferencing for a value type, or a managed pointer. template <typename T> const T& deref(const T& x) { return x; } template <typename T> const T& deref(const shared_ptr<T>& x) { return *x; } template <typename T> const T& deref(const unique_ptr<T>& x) { return *x; } struct GenericTrivialFunctor { DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(GenericTrivialFunctor) GenericTrivialFunctor() {} int numInputs() const { return 3; } int numOutputs() const { return 3; } template <typename T> void eval(const internal::VecIn<T>& x, internal::VecOut<T>* y) const { Eigen::Vector3d c(1, 2, 3); *y = c * x.transpose() * c; } }; AssertionResult CompareAutodiff(const AutoDiffVecXd& tx_expected, const AutoDiffVecXd& tx_actual, double tolerance = 0.0) { const VectorXd x_expected = math::ExtractValue(tx_expected); const VectorXd x_actual = math::ExtractValue(tx_actual); AssertionResult value_result = CompareMatrices(x_expected, x_actual, tolerance); if (!value_result) { return value_result << "(value)"; } const MatrixXd dx_expected = math::ExtractGradient(tx_expected); const MatrixXd dx_actual = math::ExtractGradient(tx_actual); AssertionResult grad_result = CompareMatrices(dx_expected, dx_actual, tolerance); if (!grad_result) { return grad_result << "(gradient)"; } return AssertionSuccess(); } // Verifies that FunctionEvaluator can be constructed correctly with // different callable objects (r/l-value, shared/unique_ptr). // TODO(eric.cousineau): Share these function-based test utilities with // cost_test. template <typename F> void VerifyFunctionEvaluator(F&& f, const VectorXd& x) { // Compute expected value prior to forwarding `f` (which may involve // move'ing `unique_ptr<>` or `shared_ptr<>`, making `f` a nullptr). Eigen::VectorXd y_expected(3); // Manually specialize the call to `eval` because compiler may have issues // inferring T from Eigen::Ref<VectorX<T>>. It works in FunctionEvaluator // because Ref<VectorX<T>> is already determined by the function signature. deref(f).template eval<double>(x, &y_expected); const AutoDiffVecXd tx = math::InitializeAutoDiff(x); AutoDiffVecXd ty_expected(3); deref(f).template eval<AutoDiffXd>(tx, &ty_expected); Eigen::MatrixXd dy_expected = math::ExtractGradient(ty_expected); // Construct evaluator, moving `f` if applicable. shared_ptr<EvaluatorBase> evaluator = MakeFunctionEvaluator(std::forward<F>(f)); EXPECT_TRUE(is_dynamic_castable<EvaluatorBase>(evaluator)); // Compare double. Eigen::VectorXd y(3); evaluator->Eval(x, &y); EXPECT_TRUE(CompareMatrices(y, y_expected)); // Check AutoDif. AutoDiffVecXd ty(3); evaluator->Eval(tx, &ty); EXPECT_TRUE(CompareAutodiff(ty, ty_expected)); } // Store generic callable (e.g. a lambda), and assign sizes to it manually. // TODO(eric.cousineau): Migrate this to function.h or evaluator_base.h. template <typename Callable> class FunctionWrapper { public: template <typename CallableF> FunctionWrapper(CallableF&& callable, int num_outputs, int num_vars) : num_outputs_(num_outputs), num_vars_(num_vars), callable_(std::forward<CallableF>(callable)) {} int numInputs() const { return num_vars_; } int numOutputs() const { return num_outputs_; } template <typename T> void eval(const internal::VecIn<T>& x, internal::VecOut<T>* y) const { callable_(x, y); } public: int num_outputs_{}; int num_vars_{}; Callable callable_; }; template <typename CallableF> auto MakeFunctionWrapped(CallableF&& c, int num_outputs, int num_vars) { using Callable = std::decay_t<CallableF>; using Wrapped = FunctionWrapper<Callable>; return Wrapped(std::forward<CallableF>(c), num_outputs, num_vars); } GTEST_TEST(EvaluatorBaseTest, FunctionEvaluatorTest) { // Test that we can construct FunctionCosts with different signatures. Eigen::Vector3d x(-10, -20, -30); VerifyFunctionEvaluator(GenericTrivialFunctor(), x); const GenericTrivialFunctor obj_const{}; VerifyFunctionEvaluator(obj_const, x); VerifyFunctionEvaluator(make_shared<GenericTrivialFunctor>(), x); VerifyFunctionEvaluator(make_unique<GenericTrivialFunctor>(), x); auto callable = [](const auto& x1, auto* y1) { Eigen::Vector3d c(1, 2, 3); *y1 = c * x1.transpose() * c; }; VerifyFunctionEvaluator(MakeFunctionWrapped(callable, 3, 3), x); } class SimpleEvaluator : public EvaluatorBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SimpleEvaluator) SimpleEvaluator() : EvaluatorBase(2, 3) { c_.resize(2, 3); c_ << 1, 2, 3, 4, 5, 6; } protected: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { DoEvalGeneric(x, y); } private: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const { *y = c_ * x.template cast<ScalarY>(); } Eigen::MatrixXd c_; }; GTEST_TEST(EvaluatorBaseTest, SetGradientSparsityPattern) { const VectorXd lb = VectorXd::Constant(2, -1); const VectorXd ub = VectorXd::Constant(2, 1); SimpleEvaluator evaluator; EXPECT_EQ(fmt::format("{}", evaluator), "SimpleEvaluator with 3 decision variables $(0) $(1) $(2)\n"); // The gradient sparsity pattern should be unset at evaluator construction. EXPECT_FALSE(evaluator.gradient_sparsity_pattern().has_value()); // Now set the gradient sparsity pattern. evaluator.SetGradientSparsityPattern( {{0, 0}, {0, 1}, {0, 2}, {1, 0}, {1, 1}, {1, 2}}); const auto& gradient_sparsity_pattern = evaluator.gradient_sparsity_pattern(); int gradient_entry_count = 0; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { EXPECT_EQ(gradient_sparsity_pattern.value()[gradient_entry_count].first, i); EXPECT_EQ(gradient_sparsity_pattern.value()[gradient_entry_count].second, j); ++gradient_entry_count; } } if (kDrakeAssertIsArmed) { // row index out of range. EXPECT_THROW(evaluator.SetGradientSparsityPattern({{-1, 0}}), std::invalid_argument); // column index out of range. EXPECT_THROW(evaluator.SetGradientSparsityPattern({{0, -1}}), std::invalid_argument); // repeated entries. EXPECT_THROW(evaluator.SetGradientSparsityPattern({{0, 0}, {0, 0}}), std::invalid_argument); } } /** * An evaluator with dynamic sized input. */ class DynamicSizedEvaluator : public EvaluatorBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DynamicSizedEvaluator) DynamicSizedEvaluator() : EvaluatorBase(1, Eigen::Dynamic) {} protected: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { DoEvalGeneric(x, y); } private: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const { (*y)(0) = x.template cast<ScalarY>().sum(); } }; GTEST_TEST(EvaluatorBaseTest, DynamicSizedEvaluatorTest) { DynamicSizedEvaluator evaluator{}; EXPECT_EQ(fmt::format("{}", evaluator), "DynamicSizedEvaluator with 1 decision variables " "dynamic_sized_variable\n"); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/cost_test.cc
#include "drake/solvers/cost.h" #include <iostream> #include <limits> #include <memory> #include <stdexcept> #include <gtest/gtest.h> #include "drake/common/symbolic/expression.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/is_dynamic_castable.h" #include "drake/common/test_utilities/symbolic_test_util.h" #include "drake/common/text_logging.h" #include "drake/math/autodiff.h" #include "drake/math/autodiff_gradient.h" #include "drake/solvers/constraint.h" #include "drake/solvers/create_cost.h" #include "drake/solvers/evaluator_base.h" #include "drake/solvers/test/generic_trivial_costs.h" using std::cout; using std::endl; using std::make_shared; using std::make_unique; using std::numeric_limits; using std::runtime_error; using std::shared_ptr; using std::unique_ptr; using std::vector; using drake::Vector1d; using drake::solvers::test::GenericTrivialCost2; using Eigen::Matrix; using Eigen::Matrix2d; using Eigen::Matrix3d; using Eigen::Ref; using Eigen::RowVector2d; using Eigen::Vector2d; using Eigen::Vector3d; using Eigen::Vector4d; using Eigen::VectorXd; namespace drake { using symbolic::Expression; using symbolic::Variable; using symbolic::test::ExprEqual; namespace solvers { namespace { // For a given Constraint, return the equivalent Cost type template <typename C> struct related_cost { using type = void; }; template <> struct related_cost<LinearConstraint> { using type = LinearCost; }; template <> struct related_cost<QuadraticConstraint> { using type = QuadraticCost; }; template <> struct related_cost<PolynomialConstraint> { using type = PolynomialCost; }; // Utility to explicitly pass a vector rather than an initializer list. // This must be done since you cannot forward std::initializer_list's via // parameter packs. (GCC 4.9.3 is non-standards compliant and permits this, // but this is fixed in GCC 4.9.4.) template <typename T> auto make_vector(std::initializer_list<T> items) { return vector<std::decay_t<T>>(items); } GTEST_TEST(testCost, testLinearCost) { const double tol = numeric_limits<double>::epsilon(); // Simple ground truth test. Eigen::Vector2d a(1, 2); const Eigen::Vector2d x0(3, 4); const double obj_expected = 11.; auto cost = make_shared<LinearCost>(a); Eigen::VectorXd y(1); cost->Eval(x0, &y); EXPECT_EQ(y.rows(), 1); EXPECT_NEAR(y(0), obj_expected, tol); // Test Eval with AutoDiff scalar. Eigen::Matrix2Xd x_grad(2, 1); x_grad << 5, 6; const AutoDiffVecXd x_autodiff = math::InitializeAutoDiff(x0, x_grad); AutoDiffVecXd y_autodiff; cost->Eval(x_autodiff, &y_autodiff); EXPECT_TRUE(CompareMatrices(math::ExtractValue(y_autodiff), Vector1<double>(obj_expected), tol)); EXPECT_TRUE(CompareMatrices(math::ExtractGradient(y_autodiff), a.transpose() * x_grad, tol)); // Test Eval with identity gradient. const AutoDiffVecXd x_autodiff_identity = math::InitializeAutoDiff(x0); AutoDiffVecXd y_autodiff_identity; cost->Eval(x_autodiff_identity, &y_autodiff_identity); EXPECT_TRUE(CompareMatrices(math::ExtractValue(y_autodiff_identity), Vector1<double>(obj_expected), tol)); EXPECT_TRUE(CompareMatrices(math::ExtractGradient(y_autodiff_identity), a.transpose(), tol)); // Test Eval with empty gradient. const AutoDiffVecXd x_autodiff_empty = x0.cast<AutoDiffXd>(); AutoDiffVecXd y_autodiff_empty; cost->Eval(x_autodiff_empty, &y_autodiff_empty); EXPECT_TRUE(CompareMatrices(math::ExtractValue(y_autodiff_empty), Vector1<double>(obj_expected), tol)); EXPECT_EQ(math::ExtractGradient(y_autodiff_empty).size(), 0); // Test Eval/CheckSatisfied using Expression. const VectorX<Variable> x_sym{symbolic::MakeVectorContinuousVariable(2, "x")}; VectorX<Expression> y_sym; cost->Eval(x_sym, &y_sym); EXPECT_EQ(y_sym.size(), 1); EXPECT_PRED2(ExprEqual, y_sym[0], 1 * x_sym[0] + 2 * x_sym[1]); // Update with a constant term. const double b = 100; cost->UpdateCoefficients(a, b); cost->Eval(x0, &y); EXPECT_NEAR(y(0), obj_expected + b, tol); EXPECT_THROW(cost->UpdateCoefficients(Eigen::Vector3d::Ones(), b), runtime_error); // Reconstruct the same cost with the constant term. auto new_cost = make_shared<LinearCost>(a, b); new_cost->Eval(x0, &y); EXPECT_NEAR(y(0), obj_expected + b, tol); new_cost->set_description("simple linear cost"); EXPECT_EQ( fmt::format("{}", *new_cost), "LinearCost (100 + $(0) + 2 * $(1)) described as 'simple linear cost'"); } GTEST_TEST(TestQuadraticCost, NonconvexCost) { const double tol = numeric_limits<double>::epsilon(); // Simple ground truth test. Eigen::Matrix2d Q; Q << 1, 2, 3, 4; const Eigen::Vector2d b(5, 6); const Eigen::Vector2d x0(7, 8); const double obj_expected = 375.5; auto cost = make_shared<QuadraticCost>(Q, b); Eigen::VectorXd y(1); EXPECT_FALSE(cost->is_convex()); EXPECT_TRUE(CompareMatrices(cost->Q(), (Q + Q.transpose()) / 2, 1E-10, MatrixCompareType::absolute)); cost->Eval(x0, &y); EXPECT_EQ(y.rows(), 1); EXPECT_NEAR(y(0), obj_expected, tol); // Test Eval with AutoDiff scalar. Eigen::Matrix2Xd x_grad(2, 1); x_grad << 5, 6; const AutoDiffVecXd x_autodiff = math::InitializeAutoDiff(x0, x_grad); AutoDiffVecXd y_autodiff; cost->Eval(x_autodiff, &y_autodiff); const AutoDiffXd y_autodiff_expected = 0.5 * x_autodiff.dot(Q * x_autodiff) + b.dot(x_autodiff); EXPECT_TRUE(CompareMatrices(math::ExtractValue(y_autodiff), Vector1<double>(obj_expected), tol)); EXPECT_TRUE(CompareMatrices(math::ExtractGradient(y_autodiff), y_autodiff_expected.derivatives(), tol)); // Test Eval with identity gradient. const AutoDiffVecXd x_autodiff_identity = math::InitializeAutoDiff(x0); AutoDiffVecXd y_autodiff_identity; cost->Eval(x_autodiff_identity, &y_autodiff_identity); EXPECT_TRUE(CompareMatrices(math::ExtractValue(y_autodiff_identity), Vector1<double>(obj_expected), tol)); EXPECT_TRUE(CompareMatrices( math::ExtractGradient(y_autodiff_identity), x0.transpose() * (Q + Q.transpose()) / 2 + b.transpose(), tol)); // Test Eval with empty gradient. const AutoDiffVecXd x_autodiff_empty = x0.cast<AutoDiffXd>(); AutoDiffVecXd y_autodiff_empty; cost->Eval(x_autodiff_empty, &y_autodiff_empty); EXPECT_TRUE(CompareMatrices(math::ExtractValue(y_autodiff_empty), Vector1<double>(obj_expected), tol)); EXPECT_EQ(math::ExtractGradient(y_autodiff_empty).size(), 0); // Test Eval/CheckSatisfied using Expression. { const VectorX<Variable> x_sym{ symbolic::MakeVectorContinuousVariable(2, "x")}; VectorX<Expression> y_sym; cost->Eval(x_sym, &y_sym); EXPECT_EQ(y_sym.size(), 1); const Variable& x_0{x_sym[0]}; const Variable& x_1{x_sym[1]}; EXPECT_PRED2(ExprEqual, y_sym[0].Expand(), // 0.5 x'Qx + bx (0.5 * (x_0 * x_0 + (2 + 3) * x_0 * x_1 + 4 * x_1 * x_1) + 5 * x_0 + 6 * x_1) .Expand()); } // Update with an asymmetric Q cost->UpdateCoefficients(2 * Q, b); EXPECT_TRUE(CompareMatrices(cost->Q(), (Q + Q.transpose()), 1E-10, MatrixCompareType::absolute)); EXPECT_FALSE(cost->is_convex()); // Update with a constant term. const double c = 100; cost->UpdateCoefficients(Q, b, c); cost->Eval(x0, &y); EXPECT_NEAR(y(0), obj_expected + c, tol); EXPECT_THROW(cost->UpdateCoefficients(Eigen::Matrix3d::Identity(), b, c), runtime_error); EXPECT_THROW(cost->UpdateCoefficients(Q, Eigen::Vector3d::Ones(), c), runtime_error); // Reconstruct the same cost with the constant term. auto new_cost = make_shared<QuadraticCost>(Q, b, c); new_cost->Eval(x0, &y); EXPECT_NEAR(y(0), obj_expected + c, tol); // Now construct cost with is_hessian_psd=false. cost = std::make_shared<QuadraticCost>(Q, b, 0., false); EXPECT_FALSE(cost->is_convex()); // Now update the Hessian such that it is PSD. // UpdateCoefficients function will check if the new Hessian is PSD. cost->UpdateCoefficients(Q + 100 * Eigen::Matrix2d::Identity(), Eigen::Vector2d::Zero()); EXPECT_TRUE(cost->is_convex()); // By specifying is_hessian_psd=true, UpdateCoefficients() function will // bypass checking if the new Hessian is PSD. cost->UpdateCoefficients(Q + 100 * Eigen::Matrix2d::Identity(), Eigen::Vector2d::Zero(), 0., true); EXPECT_TRUE(cost->is_convex()); // By specifying is_hessian_psd=false, UpdateCoefficients() function will // bypass checking if the new Hessian is PSD. Although the new Hessian is // truly PSD, our code takes is_hessian_psd at a face value, and skip the PSD // check entirely. The user should never lie about is_hessian_psd flag, we do // it here just to check if the code behaves as we expect when that lie // occurs. cost->UpdateCoefficients(Q + 100 * Eigen::Matrix2d::Identity(), Eigen::Vector2d::Zero(), 0., false); EXPECT_FALSE(cost->is_convex()); } GTEST_TEST(TestQuadraticCost, ConvexCost) { Eigen::Matrix2d Q; Q << 1, 2, 3, 10; const Eigen::Vector2d b(5, 6); auto cost = std::make_shared<QuadraticCost>(Q, b, 0.5); EXPECT_TRUE(cost->is_convex()); cost = std::make_shared<QuadraticCost>(Q, b, 0.5, true); EXPECT_TRUE(cost->is_convex()); // Call UpdateCoefficients(). This function determines if the new Hessian is // psd. cost->UpdateCoefficients(-Q, b, 0.1); EXPECT_FALSE(cost->is_convex()); // Call UpdateCoefficients() and tell the function that the new Hessian is not // psd. cost->UpdateCoefficients(-Q, b, 0.1, false); EXPECT_FALSE(cost->is_convex()); // Call UpdateCoefficients() and tell the function that the new Hessian is // psd by setting is_hessian_psd=true. Although the actual Hessian is not psd, // our function will take the face value of is_hessian_psd and bypass the // matrix psd check. cost->UpdateCoefficients(-Q, b, 0.1, true); EXPECT_TRUE(cost->is_convex()); // Call Make2NormSquaredCost. cost = Make2NormSquaredCost((Eigen::Matrix2d() << 1, 2, 3, 4).finished(), Eigen::Vector2d(2, 3)); EXPECT_TRUE(cost->is_convex()); } // TODO(eric.cousineau): Move QuadraticErrorCost and L2NormCost tests here from // MathematicalProgram. template <typename C, typename BoundType, typename... Args> void VerifyRelatedCost(const Ref<const VectorXd>& x_value, Args&&... args) { // Ensure that a constraint constructed in a particular fashion yields // equivalent results to its shim, and the related cost. const double inf = std::numeric_limits<double>::infinity(); BoundType lb = -BoundType(-inf); BoundType ub = BoundType(inf); C constraint(std::forward<Args>(args)..., lb, ub); typename related_cost<C>::type cost(std::forward<Args>(args)...); VectorXd y_expected, y; constraint.Eval(x_value, &y); cost.Eval(x_value, &y_expected); EXPECT_TRUE(CompareMatrices(y, y_expected)); } GTEST_TEST(testCost, testCostShim) { // Test CostShim's by means of the related constraints. VerifyRelatedCost<LinearConstraint, Vector1d>(Vector1d(2), Vector1d(3)); VerifyRelatedCost<QuadraticConstraint, double>(Vector1d(2), Vector1d(3), Vector1d(4)); const Polynomiald x("x"); const auto poly = (x - 1) * (x - 1); const auto var_mapping = make_vector({x.GetSimpleVariable()}); VerifyRelatedCost<PolynomialConstraint, Vector1d>( Vector1d(2), VectorXPoly::Constant(1, poly), var_mapping); } // Generic dereferencing for a value type, or a managed pointer. template <typename T> const T& deref(const T& x) { return x; } template <typename T> const T& deref(const shared_ptr<T>& x) { return *x; } template <typename T> const T& deref(const unique_ptr<T>& x) { return *x; } // Verifies that FunctionCost form can be constructed correctly. template <typename F> void VerifyFunctionCost(F&& f, const Ref<const VectorXd>& x_value) { // Compute expected value prior to forwarding `f` (which may involve // move'ing `unique_ptr<>` or `shared_ptr<>`, making `f` a nullptr). Eigen::VectorXd y_expected(1); deref(f).eval(x_value, &y_expected); // Construct cost, moving `f`, if applicable. auto cost = MakeFunctionCost(std::forward<F>(f)); EXPECT_TRUE(is_dynamic_castable<Cost>(cost)); // Compare values. Eigen::VectorXd y(1); cost->Eval(x_value, &y); EXPECT_TRUE(CompareMatrices(y, y_expected)); } GTEST_TEST(testCost, testFunctionCost) { // Test that we can construct FunctionCosts with different signatures. Eigen::Vector2d x(1, 2); VerifyFunctionCost(GenericTrivialCost2(), x); // Ensure that we explicitly call the default constructor for a const class. // @ref http://stackoverflow.com/a/28338123/7829525 const GenericTrivialCost2 obj_const{}; VerifyFunctionCost(obj_const, x); VerifyFunctionCost(make_shared<GenericTrivialCost2>(), x); VerifyFunctionCost(make_unique<GenericTrivialCost2>(), x); } GTEST_TEST(TestL1NormCost, Eval) { Matrix<double, 2, 4> A; // clang-format off A << .32, 2.0, 1.3, -4., 2.3, -2.0, 7.1, 1.3; // clang-format on const Vector2d b{.42, -3.2}; L1NormCost cost(A, b); EXPECT_TRUE(CompareMatrices(A, cost.A())); EXPECT_TRUE(CompareMatrices(b, cost.b())); const Vector4d x0{5.2, 3.4, -1.3, 2.1}; const Vector2d z = A * x0 + b; // Test double. { VectorXd y; cost.Eval(x0, &y); EXPECT_NEAR(z.cwiseAbs().sum(), y[0], 1e-15); } // Test AutoDiffXd. { const Vector4<AutoDiffXd> x = math::InitializeAutoDiff(x0); VectorX<AutoDiffXd> y; cost.Eval(x, &y); EXPECT_NEAR(z.cwiseAbs().sum(), math::ExtractValue(y)[0], 1e-15); const Matrix<double, 1, 4> grad_expected = z.cwiseQuotient(z.cwiseAbs()).transpose() * A; EXPECT_TRUE( CompareMatrices(math::ExtractGradient(y), grad_expected, 1e-15)); } // Test Symbolic. { auto x = symbolic::MakeVectorVariable(4, "x"); VectorX<Expression> y; cost.Eval(x, &y); symbolic::Environment env; env.insert(x, x0); EXPECT_NEAR(z.cwiseAbs().sum(), y[0].Evaluate(env), 1e-14); } } GTEST_TEST(TestL1NormCost, UpdateCoefficients) { L1NormCost cost(Matrix2d::Identity(), Vector2d::Zero()); cost.UpdateCoefficients(Matrix<double, 4, 2>::Identity(), Vector4d::Zero()); EXPECT_EQ(cost.A().rows(), 4); EXPECT_EQ(cost.b().rows(), 4); // Can't change the number of variables. EXPECT_THROW(cost.UpdateCoefficients(Matrix3d::Identity(), Vector3d::Zero()), std::exception); // A and b must have the same number of rows. EXPECT_THROW(cost.UpdateCoefficients(Matrix3d::Identity(), Vector4d::Zero()), std::exception); } GTEST_TEST(TestL1NormCost, Display) { L1NormCost cost(Matrix2d::Identity(), Vector2d::Ones()); std::ostringstream os; cost.Display(os, symbolic::MakeVectorContinuousVariable(2, "x")); EXPECT_EQ(fmt::format("{}", os.str()), "L1NormCost (abs((1 + x(0))) + abs((1 + x(1))))"); } GTEST_TEST(TestL2NormCost, Eval) { Matrix<double, 2, 4> A; // clang-format off A << .32, 2.0, 1.3, -4., 2.3, -2.0, 7.1, 1.3; // clang-format on const Vector2d b{.42, -3.2}; L2NormCost cost(A, b); EXPECT_TRUE(CompareMatrices(A, cost.GetDenseA())); EXPECT_TRUE(CompareMatrices(A, cost.get_sparse_A().toDense())); EXPECT_TRUE(CompareMatrices(b, cost.b())); const Vector4d x0{5.2, 3.4, -1.3, 2.1}; const Vector2d z = A * x0 + b; // Test double. { VectorXd y; cost.Eval(x0, &y); EXPECT_NEAR(std::sqrt(z.dot(z)), y[0], 1e-16); } // Test AutoDiffXd. { const Vector4<AutoDiffXd> x = math::InitializeAutoDiff(x0); VectorX<AutoDiffXd> y; cost.Eval(x, &y); EXPECT_NEAR(z.norm(), math::ExtractValue(y)[0], 1e-15); const Matrix<double, 1, 4> grad_expected = (x0.transpose() * A.transpose() * A + b.transpose() * A) / (z.norm()); EXPECT_TRUE( CompareMatrices(math::ExtractGradient(y), grad_expected, 1e-15)); } // Test Symbolic. { auto x = symbolic::MakeVectorVariable(4, "x"); VectorX<Expression> y; cost.Eval(x, &y); symbolic::Environment env; env.insert(x, x0); EXPECT_NEAR(z.norm(), y[0].Evaluate(env), 1e-14); } { // Test constructor with sparse A. L2NormCost cost_sparse(A.sparseView(), b); EXPECT_TRUE(CompareMatrices(cost_sparse.GetDenseA(), A)); EXPECT_TRUE(CompareMatrices(cost_sparse.get_sparse_A().toDense(), A)); EXPECT_TRUE(CompareMatrices(cost_sparse.b(), b)); } } GTEST_TEST(TestL2NormCost, UpdateCoefficients) { L2NormCost cost(Matrix2d::Identity(), Vector2d::Zero()); Matrix<double, 4, 2> new_A = Matrix<double, 4, 2>::Identity(); // Call UpdateCoefficients with a dense A. cost.UpdateCoefficients(new_A, Vector4d::Zero()); EXPECT_TRUE(CompareMatrices(cost.get_sparse_A().toDense(), new_A)); EXPECT_TRUE(CompareMatrices(cost.GetDenseA(), new_A)); EXPECT_EQ(cost.b().rows(), 4); // Call UpdateCoefficients with a sparse A. new_A << 1, 2, 3, 0, 1, 3, 5, 0; cost.UpdateCoefficients(new_A.sparseView(), Vector4d::Zero()); EXPECT_TRUE(CompareMatrices(cost.get_sparse_A().toDense(), new_A)); EXPECT_TRUE(CompareMatrices(cost.GetDenseA(), new_A)); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" EXPECT_TRUE(CompareMatrices(cost.A(), new_A)); #pragma GCC diagnostic pop EXPECT_EQ(cost.b().rows(), 4); // Can't change the number of variables. EXPECT_THROW(cost.UpdateCoefficients(Matrix3d::Identity(), Vector3d::Zero()), std::exception); // A and b must have the same number of rows. EXPECT_THROW(cost.UpdateCoefficients(Matrix3d::Identity(), Vector4d::Zero()), std::exception); } GTEST_TEST(TestL2NormCost, Display) { L2NormCost cost(Matrix2d::Identity(), Vector2d::Ones()); std::ostringstream os; cost.Display(os, symbolic::MakeVectorContinuousVariable(2, "x")); EXPECT_EQ(fmt::format("{}", os.str()), "L2NormCost sqrt((pow((1 + x(0)), 2) + pow((1 + x(1)), 2)))"); } GTEST_TEST(TestLInfNormCost, Eval) { Matrix<double, 2, 4> A; // clang-format off A << .32, 2.0, 1.3, -4., 2.3, -2.0, 7.1, 1.3; // clang-format on const Vector2d b{.42, -3.2}; LInfNormCost cost(A, b); EXPECT_TRUE(CompareMatrices(A, cost.A())); EXPECT_TRUE(CompareMatrices(b, cost.b())); const Vector4d x0{5.2, 3.4, -1.3, 2.1}; const Vector2d z = A * x0 + b; // Test double. { VectorXd y; cost.Eval(x0, &y); EXPECT_NEAR(z.cwiseAbs().maxCoeff(), y[0], 1e-16); } // Test AutoDiffXd. { const Vector4<AutoDiffXd> x = math::InitializeAutoDiff(x0); VectorX<AutoDiffXd> y; cost.Eval(x, &y); int max_row; EXPECT_NEAR(z.cwiseAbs().maxCoeff(&max_row), math::ExtractValue(y)[0], 1e-15); const Matrix<double, 1, 4> grad_expected = (z.cwiseQuotient(z.cwiseAbs()))(max_row)*A.row(max_row); EXPECT_TRUE( CompareMatrices(math::ExtractGradient(y), grad_expected, 1e-15)); } // Test Symbolic. { auto x = symbolic::MakeVectorVariable(4, "x"); VectorX<Expression> y; cost.Eval(x, &y); symbolic::Environment env; env.insert(x, x0); EXPECT_NEAR(z.cwiseAbs().maxCoeff(), y[0].Evaluate(env), 1e-14); } } GTEST_TEST(TestLInfNormCost, UpdateCoefficients) { LInfNormCost cost(Matrix2d::Identity(), Vector2d::Zero()); cost.UpdateCoefficients(Matrix<double, 4, 2>::Identity(), Vector4d::Zero()); EXPECT_EQ(cost.A().rows(), 4); EXPECT_EQ(cost.b().rows(), 4); // Can't change the number of variables. EXPECT_THROW(cost.UpdateCoefficients(Matrix3d::Identity(), Vector3d::Zero()), std::exception); // A and b must have the same number of rows. EXPECT_THROW(cost.UpdateCoefficients(Matrix3d::Identity(), Vector4d::Zero()), std::exception); } GTEST_TEST(TestLInfNormCost, Display) { LInfNormCost cost(Matrix2d::Identity(), Vector2d::Ones()); std::ostringstream os; cost.Display(os, symbolic::MakeVectorContinuousVariable(2, "x")); EXPECT_EQ(fmt::format("{}", os.str()), "LInfNormCost max(abs((1 + x(0))), abs((1 + x(1))))"); } GTEST_TEST(TestPerspectiveQuadraticCost, Eval) { Matrix<double, 2, 4> A; // clang-format off A << .32, 2.0, 1.3, -4., 2.3, -2.0, 7.1, 1.3; // clang-format on const Vector2d b{.42, -3.2}; PerspectiveQuadraticCost cost(A, b); EXPECT_TRUE(CompareMatrices(A, cost.A())); EXPECT_TRUE(CompareMatrices(b, cost.b())); const Vector4d x0{5.2, 3.4, -1.3, 2.1}; const Vector2d z = A * x0 + b; // Test double. { VectorXd y; cost.Eval(x0, &y); EXPECT_DOUBLE_EQ(z(1) * z(1) / z(0), y[0]); } // Test AutoDiffXd. { const Vector4<AutoDiffXd> x = math::InitializeAutoDiff(x0); VectorX<AutoDiffXd> y; cost.Eval(x, &y); EXPECT_DOUBLE_EQ(z(1) * z(1) / z(0), math::ExtractValue(y)[0]); const Matrix<double, 1, 4> grad_expected = RowVector2d(-(z(1) * z(1)) / (z(0) * z(0)), 2 * z(1) / z(0)) * A; EXPECT_TRUE( CompareMatrices(math::ExtractGradient(y), grad_expected, 1e-13)); } // Test Symbolic. { auto x = symbolic::MakeVectorVariable(4, "x"); VectorX<Expression> y; cost.Eval(x, &y); symbolic::Environment env; env.insert(x, x0); EXPECT_DOUBLE_EQ(z(1) * z(1) / z(0), y[0].Evaluate(env)); } } GTEST_TEST(TestPerspectiveQuadraticCost, UpdateCoefficients) { PerspectiveQuadraticCost cost(Matrix2d::Identity(), Vector2d::Zero()); cost.UpdateCoefficients(Matrix<double, 4, 2>::Identity(), Vector4d::Zero()); EXPECT_EQ(cost.A().rows(), 4); EXPECT_EQ(cost.b().rows(), 4); // Can't change the number of variables. EXPECT_THROW(cost.UpdateCoefficients(Matrix3d::Identity(), Vector3d::Zero()), std::exception); // A and b must have the same number of rows. EXPECT_THROW(cost.UpdateCoefficients(Matrix3d::Identity(), Vector4d::Zero()), std::exception); } GTEST_TEST(TestPerspectiveQuadraticCost, Display) { PerspectiveQuadraticCost cost(Matrix2d::Identity(), Vector2d::Ones()); std::ostringstream os; cost.Display(os, symbolic::MakeVectorContinuousVariable(2, "x")); EXPECT_EQ(fmt::format("{}", os.str()), "PerspectiveQuadraticCost (pow((1 + x(1)), 2) / (1 + x(0)))"); } class Evaluator2In1Out : public EvaluatorBase { public: Evaluator2In1Out() : EvaluatorBase(1, 2) {} ~Evaluator2In1Out() override {} private: template <typename T, typename S> void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x, VectorX<S>* y) const { y->resize(1); using std::sin; (*y)(0) = x(0) + sin(x(1)); } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, VectorXd* y) const override { this->DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { this->DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { this->DoEvalGeneric(x, y); } }; class Evaluator3In2Out : public EvaluatorBase { public: Evaluator3In2Out() : EvaluatorBase(3, 2) {} ~Evaluator3In2Out() override {} private: template <typename T, typename S> void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x, VectorX<S>* y) const { y->resize(3); using std::sin; (*y)(0) = x(0) + 3 * x(1) * x(0); (*y)(1) = sin(x(0) + x(1)); (*y)(2) = 2 + x(0); } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, VectorXd* y) const override { this->DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { this->DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { this->DoEvalGeneric(x, y); } }; GTEST_TEST(EvaluatorCost, Eval) { // Test with a single-output evaluator. auto evaluator_2in_1out = std::make_shared<Evaluator2In1Out>(); EvaluatorCost<Evaluator2In1Out> dut1(evaluator_2in_1out); Eigen::Vector2d x1(0.2, 0.3); VectorXd y1; dut1.Eval(x1, &y1); Eigen::VectorXd y1_expected; evaluator_2in_1out->Eval(x1, &y1_expected); EXPECT_TRUE(CompareMatrices(y1, y1_expected)); // Test a linear transformation of the evaluator output. auto evaluator_3in_2out = std::make_shared<Evaluator3In2Out>(); const Eigen::Vector3d a(1, 2, 3); const double b = 4; EvaluatorCost<Evaluator3In2Out> dut2(evaluator_3in_2out, a, b); const Eigen::Vector2d x2(2, 3); Eigen::VectorXd y2; dut2.Eval(x2, &y2); Eigen::VectorXd evaluator2_y; evaluator_3in_2out->Eval(x2, &evaluator2_y); ASSERT_EQ(y2.rows(), 1); EXPECT_NEAR(y2(0), a.dot(evaluator2_y) + b, 1E-12); } GTEST_TEST(ExpressionCost, Basic) { using std::sin; using std::cos; Variable x("x"), y("y"); symbolic::Expression e = x * sin(y); ExpressionCost cost(e); EXPECT_TRUE(e.EqualTo(cost.expression())); EXPECT_EQ(cost.vars().size(), 2); EXPECT_EQ(cost.vars()[0], x); EXPECT_EQ(cost.vars()[1], y); EXPECT_EQ(cost.num_vars(), 2); Vector2d x_d(1.2, 3.5); VectorXd y_d; Vector1d y_expected(1.2 * sin(3.5)); cost.Eval(x_d, &y_d); EXPECT_TRUE(CompareMatrices(y_d, y_expected)); AutoDiffVecXd x_ad = math::InitializeAutoDiff(x_d); AutoDiffVecXd y_ad; RowVector2d y_deriv_expected(sin(3.5), 1.2*cos(3.5)); cost.Eval(x_ad, &y_ad); EXPECT_TRUE(CompareMatrices(math::ExtractValue(y_ad), y_expected)); EXPECT_TRUE(CompareMatrices(math::ExtractGradient(y_ad), y_deriv_expected)); Variable x_test("x"), y_test("y"); Vector2<Variable> x_e(x_test, y_test); VectorX<Expression> y_e; Expression e_expected = x_test * sin(y_test); cost.Eval(x_e, &y_e); EXPECT_EQ(y_e.size(), 1); EXPECT_TRUE(y_e[0].EqualTo(e_expected)); std::ostringstream os; cost.Display(os, x_e); EXPECT_EQ(os.str(), "ExpressionCost (x * sin(y))"); } GTEST_TEST(ToLatex, GenericCost) { test::GenericTrivialCost1 c; c.set_description("test"); Vector3<Variable> vars = symbolic::MakeVectorVariable<3>("x"); EXPECT_EQ(c.ToLatex(vars), "\\text{GenericTrivialCost1}(x_{0}, x_{1}, x_{2}) \\tag{test}"); } GTEST_TEST(ToLatex, LinearCost) { LinearCost c(Vector3d(1, 2, 3), 4); c.set_description("test"); Vector3<Variable> vars = symbolic::MakeVectorVariable<3>("x"); EXPECT_EQ(c.ToLatex(vars), "(4 + x_{0} + 2x_{1} + 3x_{2}) \\tag{test}"); } GTEST_TEST(ToLatex, QuadraticCost) { QuadraticCost c(Matrix3d::Identity(), Vector3d(1, 2, 3), 4); c.set_description("test"); Vector3<Variable> vars = symbolic::MakeVectorVariable<3>("x"); EXPECT_EQ(c.ToLatex(vars), "(4 + x_{0} + 2x_{1} + 3x_{2} + 0.500x_{0}^{2} + 0.500x_{1}^{2} + " "0.500x_{2}^{2}) \\tag{test}"); } GTEST_TEST(ToLatex, L1NormCost) { L1NormCost c(Matrix3d::Identity(), Vector3d(1, 2, 3)); c.set_description("test"); Vector3<Variable> vars = symbolic::MakeVectorVariable<3>("x"); EXPECT_EQ(c.ToLatex(vars), "\\left|\\begin{bmatrix} (1 + x_{0}) \\\\ (2 + x_{1}) \\\\ (3 + " "x_{2}) \\end{bmatrix}\\right|_1 \\tag{test}"); } GTEST_TEST(ToLatex, L2NormCost) { L2NormCost c(Matrix3d::Identity(), Vector3d(1, 2, 3)); c.set_description("test"); Vector3<Variable> vars = symbolic::MakeVectorVariable<3>("x"); EXPECT_EQ(c.ToLatex(vars), "\\left|\\begin{bmatrix} (1 + x_{0}) \\\\ (2 + x_{1}) \\\\ (3 + " "x_{2}) \\end{bmatrix}\\right|_2 \\tag{test}"); } GTEST_TEST(ToLatex, LInfNormCost) { LInfNormCost c(Matrix3d::Identity(), Vector3d(1, 2, 3)); c.set_description("test"); Vector3<Variable> vars = symbolic::MakeVectorVariable<3>("x"); EXPECT_EQ(c.ToLatex(vars), "\\left|\\begin{bmatrix} (1 + x_{0}) \\\\ (2 + x_{1}) \\\\ (3 + " "x_{2}) \\end{bmatrix}\\right|_\\infty \\tag{test}"); } GTEST_TEST(ToLatex, PerspectiveQuadraticCost) { PerspectiveQuadraticCost c(Matrix3d::Identity(), Vector3d(1, 2, 3)); c.set_description("test"); Vector3<Variable> vars = symbolic::MakeVectorVariable<3>("x"); EXPECT_EQ( c.ToLatex(vars), "\\frac{((2 + x_{1})^{2} + (3 + x_{2})^{2})}{(1 + x_{0})} \\tag{test}"); } GTEST_TEST(ToLatex, ExpressionCost) { Variable x("x"), y("y"); Expression e = x * sin(y); ExpressionCost c(e); c.set_description("test"); Vector2<Variable> vars(x, y); EXPECT_EQ(c.ToLatex(vars), "x \\sin{y} \\tag{test}"); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/plot_rotation_mccormick_envelope.cc
/* clang-format off to disable clang-format-includes */ #include "drake/solvers/test/rotation_constraint_visualization.h" /* clang-format on */ #include "drake/common/proto/call_python.h" #include "drake/solvers/rotation_constraint.h" // Plot the McCormick Envelope on the unit sphere, to help developers to // visualize the McCormick Envelope relaxation. namespace drake { namespace solvers { namespace { // This draws all the McCormick Envelope in the first orthant (+++). void DrawAllMcCormickEnvelopes(int num_bins) { for (int i = 0; i < num_bins; ++i) { for (int j = 0; j < num_bins; ++j) { for (int k = 0; k < num_bins; ++k) { Eigen::Vector3d bmin(static_cast<double>(i) / num_bins, static_cast<double>(j) / num_bins, static_cast<double>(k) / num_bins); Eigen::Vector3d bmax(static_cast<double>(i + 1) / num_bins, static_cast<double>(j + 1) / num_bins, static_cast<double>(k + 1) / num_bins); if (bmin.norm() <= 1 && bmax.norm() >= 1) { DrawBoxSphereIntersection(bmin, bmax); DrawBox(bmin, bmax); } } } } } void DoMain() { using common::CallPython; for (int num_bins = 1; num_bins <= 3; ++num_bins) { CallPython("figure", num_bins); CallPython("clf"); CallPython("axis", "equal"); DrawSphere(); DrawAllMcCormickEnvelopes(num_bins); } } } // namespace } // namespace solvers } // namespace drake int main() { drake::solvers::DoMain(); return 0; }
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/gurobi_solver_license_retention_test_helper.cc
#include "drake/solvers/gurobi_solver.h" using drake::solvers::GurobiSolver; /* Acquire a license and report the overall use_count. */ int main() { std::shared_ptr<GurobiSolver::License> license = GurobiSolver::AcquireLicense(); fmt::print("{}\n", license.use_count()); return 0; }
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/mathematical_program_result_test.cc
#include "drake/solvers/mathematical_program_result.h" #include <limits> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/test_utilities/symbolic_test_util.h" #include "drake/solvers/cost.h" #include "drake/solvers/osqp_solver.h" #include "drake/solvers/snopt_solver.h" namespace drake { namespace solvers { namespace { class MathematicalProgramResultTest : public ::testing::Test { public: MathematicalProgramResultTest() : x0_{"x0"}, x1_{"x1"}, decision_variable_index_{} { decision_variable_index_.emplace(x0_.get_id(), 0); decision_variable_index_.emplace(x1_.get_id(), 1); } protected: symbolic::Variable x0_; symbolic::Variable x1_; std::unordered_map<symbolic::Variable::Id, int> decision_variable_index_; }; TEST_F(MathematicalProgramResultTest, DefaultConstructor) { MathematicalProgramResult result; EXPECT_FALSE(result.is_success()); EXPECT_EQ(result.get_x_val().size(), 0); EXPECT_TRUE(std::isnan(result.get_optimal_cost())); EXPECT_EQ(result.num_suboptimal_solution(), 0); DRAKE_EXPECT_THROWS_MESSAGE(result.get_abstract_solver_details(), "The solver_details has not been set yet."); } TEST_F(MathematicalProgramResultTest, Setters) { MathematicalProgramResult result; result.set_decision_variable_index(decision_variable_index_); EXPECT_EQ(result.get_decision_variable_index(), decision_variable_index_); EXPECT_TRUE(CompareMatrices( result.get_x_val(), Eigen::VectorXd::Constant(decision_variable_index_.size(), std::numeric_limits<double>::quiet_NaN()))); result.set_solution_result(SolutionResult::kSolutionFound); EXPECT_TRUE(result.is_success()); const Eigen::Vector2d x_val(0, 1); result.set_x_val(x_val); result.AddSuboptimalSolution(0.1, Eigen::Vector2d(1, 2)); EXPECT_TRUE(CompareMatrices(result.get_x_val(), x_val)); EXPECT_EQ(result.num_suboptimal_solution(), 1); EXPECT_EQ(result.GetSuboptimalSolution(x0_, 0), 1); EXPECT_EQ(result.GetSuboptimalSolution(x1_, 0), 2); EXPECT_EQ(result.get_suboptimal_objective(0), 0.1); DRAKE_EXPECT_THROWS_MESSAGE(result.set_x_val(Eigen::Vector3d::Zero()), "MathematicalProgramResult::set_x_val, the " "dimension of x_val is 3, expected 2"); const double cost = 1; result.set_optimal_cost(cost); result.set_solver_id(SolverId("foo")); EXPECT_EQ(result.get_optimal_cost(), cost); EXPECT_EQ(result.get_solver_id().name(), "foo"); EXPECT_TRUE(CompareMatrices(result.GetSolution(), x_val)); result.SetSolution(x0_, 0.123); EXPECT_EQ(result.GetSolution(x0_), 0.123); symbolic::Variable unregistered("unregistered"); EXPECT_THROW(result.SetSolution(unregistered, 0.456), std::exception); } TEST_F(MathematicalProgramResultTest, GetSolution) { // Test GetSolution function. MathematicalProgramResult result; result.set_decision_variable_index(decision_variable_index_); result.set_solution_result(SolutionResult::kSolutionFound); const Eigen::Vector2d x_val(0, 1); result.set_x_val(x_val); EXPECT_EQ(result.GetSolution(x0_), x_val(0)); EXPECT_EQ(result.GetSolution(x1_), x_val(1)); EXPECT_EQ(result.GetSolution(Vector2<symbolic::Variable>(x0_, x1_)), x_val); EXPECT_TRUE(CompareMatrices(result.get_x_val(), x_val)); EXPECT_TRUE(CompareMatrices(result.GetSolution(), x_val)); // Getting solution for a variable y not in decision_variable_index_. symbolic::Variable y("y"); DRAKE_EXPECT_THROWS_MESSAGE( result.GetSolution(y), "GetVariableValue: y is not captured by the variable_index map."); // Get a solution of an Expression (with additional Variables). const symbolic::Variable x_extra{"extra"}; const symbolic::Expression e{x0_ + x_extra}; EXPECT_TRUE( result.GetSolution(e).EqualTo(symbolic::Expression{x_val(0) + x_extra})); const Vector2<symbolic::Expression> m{x0_ + x_extra, x1_ * x_extra}; const Vector2<symbolic::Expression> msol = result.GetSolution(m); EXPECT_TRUE(msol[0].EqualTo(x_val(0) + x_extra)); EXPECT_TRUE(msol[1].EqualTo(x_val(1) * x_extra)); } TEST_F(MathematicalProgramResultTest, GetSolutionPolynomial) { // Test GetSolution on symbolic::Polynomial. MathematicalProgramResult result; result.set_decision_variable_index(decision_variable_index_); const Eigen::Vector2d x_val(2, 1); result.set_x_val(x_val); // t1 and t2 are indeterminates. symbolic::Variable t1{"t1"}; symbolic::Variable t2{"t2"}; // p1 doesn't contain any decision variable. Its coefficients are constant. const symbolic::Polynomial p1(2 * t1 * t1 + t2, {t1, t2}); EXPECT_PRED2(symbolic::test::PolyEqual, p1, result.GetSolution(p1)); // p2's coefficients are expressions of x0 and x1 const symbolic::Polynomial p2( (1 + x0_ * x1_) * t1 * t1 + 2 * sin(x1_) * t1 * t2 + 3 * x0_, {t1, t2}); EXPECT_PRED2( symbolic::test::PolyEqual, symbolic::Polynomial( {{symbolic::Monomial(t1, 2), 1 + x_val(0) * x_val(1)}, {symbolic::Monomial({{t1, 1}, {t2, 1}}), 2 * std::sin(x_val(1))}, {symbolic::Monomial(), 3 * x_val(0)}}), result.GetSolution(p2)); // p3's indeterminates contain x0, expect to throw an error. DRAKE_EXPECT_THROWS_MESSAGE( result.GetSolution(symbolic::Polynomial(x0_ * t1 + 1, {x0_, t1})), ".*x0 is an indeterminate in the polynomial.*"); } TEST_F(MathematicalProgramResultTest, DualSolution) { MathematicalProgramResult result; auto bb_con = std::make_shared<BoundingBoxConstraint>(Eigen::Vector2d(0, 1), Eigen::Vector2d(2, 4)); Binding<BoundingBoxConstraint> binding1( bb_con, Vector2<symbolic::Variable>(x0_, x1_)); const Eigen::Vector2d dual_solution1(5, 6); result.set_dual_solution(binding1, dual_solution1); EXPECT_TRUE( CompareMatrices(result.GetDualSolution(binding1), dual_solution1)); auto lin_con = std::make_shared<LinearConstraint>(Eigen::Matrix2d::Identity(), Eigen::Vector2d(-1, -3), Eigen::Vector2d(2, 4)); Binding<LinearConstraint> binding2(lin_con, Vector2<symbolic::Variable>(x0_, x1_)); const Eigen::Vector2d dual_solution2(3, -2); result.set_dual_solution(binding2, dual_solution2); EXPECT_TRUE( CompareMatrices(result.GetDualSolution(binding2), dual_solution2)); auto lin_eq_con = std::make_shared<LinearEqualityConstraint>( Eigen::Matrix2d::Identity(), Eigen::Vector2d(2, 4)); Binding<LinearEqualityConstraint> binding3( lin_eq_con, Vector2<symbolic::Variable>(x0_, x1_)); const Eigen::Vector2d dual_solution3(4, -1); result.set_dual_solution(binding3, dual_solution3); EXPECT_TRUE( CompareMatrices(result.GetDualSolution(binding3), dual_solution3)); // GetDualSolution for a binding whose dual solution has not been set yet. Binding<LinearEqualityConstraint> binding4( lin_eq_con, Vector2<symbolic::Variable>(x1_, x0_)); DRAKE_EXPECT_THROWS_MESSAGE( result.GetDualSolution(binding4), fmt::format("Either this constraint does not belong to the " "mathematical program for which the result is obtained, or " "{} does not currently support getting dual solution yet.", result.get_solver_id())); } struct DummySolverDetails { int data{0}; }; struct DummySolver { using Details = DummySolverDetails; }; TEST_F(MathematicalProgramResultTest, SetSolverDetails) { MathematicalProgramResult result; result.set_decision_variable_index(decision_variable_index_); const int data = 1; DummySolverDetails& dummy_solver_details = result.SetSolverDetailsType<DummySolverDetails>(); dummy_solver_details.data = data; EXPECT_EQ(result.get_solver_details<DummySolver>().data, data); // Now we test if we call SetSolverDetailsType again, it doesn't allocate new // memory. First we check that the address is unchanged. const AbstractValue* details = &(result.get_abstract_solver_details()); dummy_solver_details = result.SetSolverDetailsType<DummySolverDetails>(); EXPECT_EQ(details, &(result.get_abstract_solver_details())); // Now we check that the value in the details is unchanged, note that the // default value for data is 0, as in the constructor of Details, so if the // constructor were called, dummy_solver_details.data won't be equal to 1. dummy_solver_details = result.SetSolverDetailsType<DummySolverDetails>(); EXPECT_EQ(result.get_solver_details<DummySolver>().data, data); } TEST_F(MathematicalProgramResultTest, EvalBinding) { MathematicalProgramResult result; result.set_decision_variable_index(decision_variable_index_); const Eigen::Vector2d x_val(0, 1); result.set_x_val(x_val); const Binding<LinearCost> cost{std::make_shared<LinearCost>(Vector1d(2), 0), Vector1<symbolic::Variable>(x1_)}; EXPECT_TRUE(CompareMatrices(result.EvalBinding(cost), Vector1d(2))); } GTEST_TEST(TestMathematicalProgramResult, InfeasibleProblem) { // Test if we can query the information in the result when the problem is // infeasible. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint(x(0) + x(1) <= 1); prog.AddLinearConstraint(x(0) >= 1); prog.AddLinearConstraint(x(1) >= 1); prog.AddQuadraticCost(x.dot(x.cast<symbolic::Expression>())); MathematicalProgramResult result; OsqpSolver osqp_solver; if (osqp_solver.available()) { const Eigen::VectorXd x_guess = Eigen::Vector2d::Zero(); osqp_solver.Solve(prog, x_guess, {}, &result); EXPECT_TRUE(CompareMatrices( result.GetSolution(x), Eigen::Vector2d::Constant(std::numeric_limits<double>::quiet_NaN()))); EXPECT_TRUE(std::isnan(result.GetSolution(x(0)))); EXPECT_TRUE(std::isnan(result.GetSolution(x(1)))); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kGlobalInfeasibleCost); } } GTEST_TEST(TestMathematicalProgramResult, GetInfeasibleConstraintNames) { if (SnoptSolver::is_available() && SnoptSolver::is_enabled()) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<1>(); auto b0 = prog.AddBoundingBoxConstraint(0, 0, x); auto b1 = prog.AddBoundingBoxConstraint(1, 1, x); SnoptSolver solver; MathematicalProgramResult result = solver.Solve(prog, {}, {}); EXPECT_FALSE(result.is_success()); std::vector<std::string> infeasible = result.GetInfeasibleConstraintNames(prog); EXPECT_EQ(infeasible.size(), 1); // If no description is set, we should see the NiceTypeName of the // Constraint. auto matcher = [](const std::string& s, const std::string& re) { return std::regex_match(s, std::regex(re)); }; EXPECT_PRED2(matcher, infeasible[0], "drake::solvers::BoundingBoxConstraint.*"); // If a description for the constraint has been set, then that description // should be returned instead. There is no reason a priori for b0 or b1 to // be the infeasible one, so set both descriptions. b0.evaluator()->set_description("Test"); b1.evaluator()->set_description("Test"); infeasible = result.GetInfeasibleConstraintNames(prog); EXPECT_PRED2(matcher, infeasible[0], "Test.*"); } } GTEST_TEST(TestMathematicalProgramResult, GetInfeasibleConstraintBindings) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); // Choose constraint values such that x=0 should violate all constraints. const Eigen::Vector2d value1 = Eigen::Vector2d::Constant(10); const Eigen::Vector3d value2 = Eigen::Vector3d::Constant(100); auto constraint1 = prog.AddBoundingBoxConstraint(value1, value1, x.head<2>()); auto constraint2 = prog.AddBoundingBoxConstraint(value2, value2, x); SnoptSolver solver; if (solver.is_available() && solver.is_enabled()) { const auto result = solver.Solve(prog); EXPECT_FALSE(result.is_success()); const double tol = 1e-4; using Bindings = std::vector<Binding<Constraint>>; const Bindings infeasible_bindings = result.GetInfeasibleConstraints(prog, tol); const Eigen::Vector3d x_sol = result.GetSolution(x); const bool violates_constraint1 = !constraint1.evaluator()->CheckSatisfied(x_sol.head<2>(), tol); const bool violates_constraint2 = !constraint2.evaluator()->CheckSatisfied(x_sol, tol); // At least one of the constraints should be violated. EXPECT_TRUE(violates_constraint1 || violates_constraint2); // Ensure we only have one occurrence of each in the order in which we // added them. Bindings bindings_expected; if (violates_constraint1) { bindings_expected.push_back(constraint1); } if (violates_constraint2) { bindings_expected.push_back(constraint2); } EXPECT_EQ(infeasible_bindings, bindings_expected); // If I relax the tolerance, then GetInfeasibleConstraintBindings returns an // empty vector. const std::vector<Binding<Constraint>> infeasible_bindings_relaxed = result.GetInfeasibleConstraints(prog, 1000); EXPECT_EQ(infeasible_bindings_relaxed.size(), 0); } } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/solver_options_test.cc
#include "drake/solvers/solver_options.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_no_throw.h" #include "drake/common/test_utilities/expect_throws_message.h" namespace drake { namespace solvers { GTEST_TEST(SolverOptionsTest, SetGetOption) { SolverOptions dut; EXPECT_EQ(to_string(dut), "{SolverOptions empty}"); EXPECT_EQ(dut.get_print_file_name(), ""); EXPECT_EQ(dut.get_print_to_console(), false); const SolverId id1("id1"); const SolverId id2("id2"); dut.SetOption(id1, "some_double", 1.1); dut.SetOption(id1, "some_before", 1.2); dut.SetOption(id1, "some_int", 2); dut.SetOption(id2, "some_int", "3"); dut.SetOption(id2, "some_string", "foo"); dut.SetOption(CommonSolverOption::kPrintFileName, "foo.txt"); dut.SetOption(CommonSolverOption::kPrintToConsole, 1); EXPECT_EQ(to_string(dut), "{SolverOptions," " CommonSolverOption::kPrintFileName=foo.txt," " CommonSolverOption::kPrintToConsole=1," " id1:some_before=1.2," " id1:some_double=1.1," " id1:some_int=2," " id2:some_int=3," " id2:some_string=foo}"); EXPECT_EQ(dut.get_print_file_name(), "foo.txt"); EXPECT_EQ(dut.get_print_to_console(), true); const std::unordered_map<CommonSolverOption, std::variant<double, int, std::string>> common_options_expected( {{CommonSolverOption::kPrintToConsole, 0}, {CommonSolverOption::kPrintFileName, "foo.txt"}}); // TODO(hongkai.dai): Test GetOption<double>() and `GetOptionDouble()` when // a CommonSolverOption takes a double value. } GTEST_TEST(SolverOptionsTest, Ids) { using Set = std::unordered_set<SolverId>; SolverOptions dut; EXPECT_EQ(dut.GetSolverIds(), Set{}); // Each type (double, int, string) can affect the "known IDs" result. const SolverId id1("id1"); dut.SetOption(id1, "some_double", 0.0); EXPECT_EQ(dut.GetSolverIds(), Set({id1})); const SolverId id2("id2"); dut.SetOption(id2, "some_int", 1); EXPECT_EQ(dut.GetSolverIds(), Set({id1, id2})); const SolverId id3("id3"); dut.SetOption(id3, "some_string", "foo"); EXPECT_EQ(dut.GetSolverIds(), Set({id1, id2, id3})); // Having the same ID used by in more than one type is okay. dut.SetOption(id1, "some_int", 2); dut.SetOption(id1, "some_string", "bar"); dut.SetOption(id1, "some_double", 1.0); EXPECT_EQ(dut.GetSolverIds(), Set({id1, id2, id3})); } GTEST_TEST(SolverOptionsTest, Merge) { const SolverId id1("foo1"); const SolverId id2("foo2"); SolverOptions dut, dut_expected; SolverOptions foo; foo.SetOption(id1, "key1", 1); dut.Merge(foo); dut_expected.SetOption(id1, "key1", 1); EXPECT_EQ(dut, dut_expected); // Duplicate solver and key. No-op foo.SetOption(id1, "key1", 2); dut.Merge(foo); EXPECT_EQ(dut, dut_expected); // foo contains a key that is not contained in dut. foo.SetOption(id1, "key2", 2); dut.Merge(foo); dut_expected.SetOption(id1, "key2", 2); EXPECT_EQ(dut, dut_expected); // foo contains a solver that is not contained in dut. foo.SetOption(id2, "key1", 1); dut.Merge(foo); dut_expected.SetOption(id2, "key1", 1); EXPECT_EQ(dut, dut_expected); // foo contains a non-empty drake_solver_option map foo.SetOption(CommonSolverOption::kPrintFileName, "bar.txt"); dut.Merge(foo); dut_expected.SetOption(CommonSolverOption::kPrintFileName, "bar.txt"); EXPECT_EQ(dut, dut_expected); // Duplicate drake_solver_option map, no-op. foo.SetOption(CommonSolverOption::kPrintFileName, "bar_new.txt"); dut.Merge(foo); EXPECT_EQ(dut, dut_expected); } GTEST_TEST(SolverOptionsTest, CheckOptionKeysForSolver) { const SolverId id1("id1"); const SolverId id2("id2"); SolverOptions solver_options; solver_options.SetOption(id1, "key1", 1.2); solver_options.SetOption(id1, "key2", 1); solver_options.SetOption(id1, "key3", "foo"); // First check a solver id not in solver_options. DRAKE_EXPECT_NO_THROW(solver_options.CheckOptionKeysForSolver( id2, {"key1"}, {"key2"}, {"key3"})); // Check the solver id in solver_options. DRAKE_EXPECT_NO_THROW(solver_options.CheckOptionKeysForSolver( id1, {"key1"}, {"key2"}, {"key3"})); // Check an option not set for id1. solver_options.SetOption(id1, "key2", 1.3); DRAKE_EXPECT_THROWS_MESSAGE( solver_options.CheckOptionKeysForSolver(id1, {"key1"}, {"key2"}, {"key3"}), "key2 is not allowed in the SolverOptions for id1."); DRAKE_EXPECT_NO_THROW(solver_options.CheckOptionKeysForSolver( id1, {"key1", "key2"}, {"key2"}, {"key3"})); } GTEST_TEST(SolverOptionsTest, SetOptionError) { SolverOptions solver_options; DRAKE_EXPECT_THROWS_MESSAGE( solver_options.SetOption(CommonSolverOption::kPrintFileName, 1), "SolverOptions::SetOption support kPrintFileName only with std::string " "value."); DRAKE_EXPECT_THROWS_MESSAGE( solver_options.SetOption(CommonSolverOption::kPrintToConsole, 2), "kPrintToConsole expects value either 0 or 1"); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/program_attribute_test.cc
#include "drake/solvers/program_attribute.h" #include <string> #include <tuple> #include <vector> #include <gtest/gtest.h> namespace drake { namespace solvers { namespace test { namespace { GTEST_TEST(ProgramAttributeTest, ToString) { const ProgramAttributes attrs{ProgramAttribute::kGenericCost, ProgramAttribute::kGenericConstraint}; EXPECT_EQ(to_string(ProgramAttribute::kGenericCost), "GenericCost"); EXPECT_EQ(to_string(attrs), "{ProgramAttributes: GenericCost, GenericConstraint}"); std::ostringstream os; os << ProgramAttribute::kGenericCost; EXPECT_EQ(os.str(), "GenericCost"); os = std::ostringstream{}; os << attrs; EXPECT_EQ(os.str(), "{ProgramAttributes: GenericCost, GenericConstraint}"); } GTEST_TEST(ProgramAttributeTest, Supported) { // Define some helpful abbreviations. const ProgramAttributes lin_cons{ProgramAttribute::kLinearConstraint}; const ProgramAttributes quad_cost{ProgramAttribute::kQuadraticCost}; const ProgramAttributes quad_cost_cons{ ProgramAttribute::kQuadraticCost, ProgramAttribute::kQuadraticConstraint}; const ProgramAttributes lin_cons_quad_cost{ ProgramAttribute::kLinearConstraint, ProgramAttribute::kQuadraticCost}; const ProgramAttributes quad_cost_cons_generic_cost{ ProgramAttribute::kQuadraticCost, ProgramAttribute::kQuadraticConstraint, ProgramAttribute::kGenericCost}; // List out all of our test cases, formatted as tuples of: // - required attributes, // - supported attributes, // - expected unsupported message (if any). std::vector<std::tuple<ProgramAttributes, ProgramAttributes, std::string>> cases{ {quad_cost, quad_cost, ""}, {quad_cost, quad_cost_cons, ""}, {quad_cost, quad_cost_cons_generic_cost, ""}, {quad_cost_cons, quad_cost_cons, ""}, {quad_cost_cons, quad_cost_cons_generic_cost, ""}, {lin_cons, quad_cost, "a LinearConstraint was declared but is not supported"}, {lin_cons_quad_cost, quad_cost_cons, "a LinearConstraint was declared but is not supported"}, {quad_cost_cons_generic_cost, quad_cost, "a GenericCost and QuadraticConstraint were declared" " but are not supported"}, {quad_cost_cons_generic_cost, lin_cons, "a GenericCost, QuadraticCost, and QuadraticConstraint were declared" " but are not supported"}, }; // Run all of the tests. for (const auto& one_case : cases) { const auto& required = std::get<0>(one_case); const auto& supported = std::get<1>(one_case); const auto& expected_message = std::get<2>(one_case); const bool expected_is_supported = expected_message.empty(); SCOPED_TRACE(to_string(required) + " vs " + to_string(supported)); const bool is_supported_1 = AreRequiredAttributesSupported(required, supported); EXPECT_EQ(is_supported_1, expected_is_supported); std::string message{"this should be clobbered"}; const bool is_supported_2 = AreRequiredAttributesSupported(required, supported, &message); EXPECT_EQ(is_supported_2, expected_is_supported); EXPECT_EQ(message, expected_message); } } GTEST_TEST(ProgramTypeTest, tostring) { EXPECT_EQ(to_string(ProgramType::kLP), "linear programming"); EXPECT_EQ(to_string(ProgramType::kQP), "quadratic programming"); EXPECT_EQ(to_string(ProgramType::kSOCP), "second order cone programming"); EXPECT_EQ(to_string(ProgramType::kSDP), "semidefinite programming"); EXPECT_EQ(to_string(ProgramType::kGP), "geometric programming"); EXPECT_EQ(to_string(ProgramType::kCGP), "conic geometric programming"); EXPECT_EQ(to_string(ProgramType::kMILP), "mixed-integer linear programming"); EXPECT_EQ(to_string(ProgramType::kMIQP), "mixed-integer quadratic programming"); EXPECT_EQ(to_string(ProgramType::kMISOCP), "mixed-integer second order cone programming"); EXPECT_EQ(to_string(ProgramType::kMISDP), "mixed-integer semidefinite programming"); EXPECT_EQ(to_string(ProgramType::kQuadraticCostConicConstraint), "conic-constrained quadratic programming"); EXPECT_EQ(to_string(ProgramType::kNLP), "nonlinear programming"); EXPECT_EQ(to_string(ProgramType::kLCP), "linear complementarity programming"); EXPECT_EQ(to_string(ProgramType::kUnknown), "uncategorized mathematical programming type"); } } // namespace } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/semidefinite_program_examples.cc
#include "drake/solvers/test/semidefinite_program_examples.h" #include <algorithm> #include <array> #include <limits> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/matrix_util.h" #include "drake/solvers/test/mathematical_program_test_util.h" namespace drake { namespace solvers { namespace test { using Eigen::Matrix3d; using Eigen::Matrix4d; using Eigen::Vector2d; using Eigen::Vector3d; using symbolic::Expression; const double kInf = std::numeric_limits<double>::infinity(); void TestTrivialSDP(const SolverInterface& solver, double tol) { MathematicalProgram prog; auto S = prog.NewSymmetricContinuousVariables<2>("S"); // S is p.s.d prog.AddPositiveSemidefiniteConstraint(S); // S(1, 0) = 1 prog.AddBoundingBoxConstraint(1, 1, S(1, 0)); // Min S.trace() prog.AddLinearCost(S.cast<symbolic::Expression>().trace()); const MathematicalProgramResult result = RunSolver(prog, solver); auto S_value = result.GetSolution(S); EXPECT_TRUE(CompareMatrices(S_value, Eigen::Matrix2d::Ones(), tol)); EXPECT_NEAR(result.get_optimal_cost(), 2.0, tol); } void FindCommonLyapunov(const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol) { MathematicalProgram prog; auto P = prog.NewSymmetricContinuousVariables<3>("P"); const double psd_epsilon{1E-3}; prog.AddPositiveSemidefiniteConstraint(P - psd_epsilon * Matrix3d::Identity()); Eigen::Matrix3d A1; // clang-format off A1 << -1, -1, -2, 0, -1, -3, 0, 0, -1; // clang-format on auto binding1 = prog.AddPositiveSemidefiniteConstraint( -A1.transpose() * P - P * A1 - psd_epsilon * Matrix3d::Identity()); Eigen::Matrix3d A2; // clang-format off A2 << -1, -1.2, -1.8, 0, -0.7, -2, 0, 0, -0.4; // clang-format on auto binding2 = prog.AddPositiveSemidefiniteConstraint( -A2.transpose() * P - P * A2 - psd_epsilon * Matrix3d::Identity()); const MathematicalProgramResult result = RunSolver(prog, solver, {}, solver_options); const Matrix3d P_value = result.GetSolution(P); const auto Q1_flat_value = result.GetSolution(binding1.variables()); const auto Q2_flat_value = result.GetSolution(binding2.variables()); const Eigen::Map<const Matrix3d> Q1_value(&Q1_flat_value(0)); const Eigen::Map<const Matrix3d> Q2_value(&Q2_flat_value(0)); Eigen::SelfAdjointEigenSolver<Matrix3d> eigen_solver_P(P_value); // The comparison tolerance is set as 1E-8, to match the Mosek default // feasibility tolerance 1E-8. EXPECT_TRUE(CompareMatrices(P_value, P_value.transpose(), std::numeric_limits<double>::epsilon(), MatrixCompareType::absolute)); EXPECT_GE(eigen_solver_P.eigenvalues().minCoeff(), 0); Eigen::SelfAdjointEigenSolver<Matrix3d> eigen_solver_Q1(Q1_value); EXPECT_GE(eigen_solver_Q1.eigenvalues().minCoeff(), 0); Eigen::SelfAdjointEigenSolver<Matrix3d> eigen_solver_Q2(Q2_value); EXPECT_GE(eigen_solver_Q2.eigenvalues().minCoeff(), 0); EXPECT_TRUE(CompareMatrices(A1.transpose() * P_value + P_value * A1 + psd_epsilon * Matrix3d::Identity(), -Q1_value, tol, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(A2.transpose() * P_value + P_value * A2 + psd_epsilon * Matrix3d::Identity(), -Q2_value, tol, MatrixCompareType::absolute)); } void FindOuterEllipsoid(const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol) { std::array<Matrix3d, 3> Q; std::array<Vector3d, 3> b; Q[0] = Matrix3d::Identity(); b[0] = Vector3d::Zero(); // clang-format off Q[1] << 1, 0.2, 0.3, 0.2, 2, 0.6, 0.3, 0.6, 3; b[1] << 0.3, 2, 1; Q[2] << 1, -0.1, 0.2, -0.1, 4, 0.3, 0.2, 0.3, 3; b[2] << 2, -1, 3; // clang-format on MathematicalProgram prog; auto P = prog.NewSymmetricContinuousVariables<3>("P"); prog.AddPositiveSemidefiniteConstraint(P); auto s = prog.NewContinuousVariables<3>("s"); prog.AddBoundingBoxConstraint(0, kInf, s); auto c = prog.NewContinuousVariables<3>("c"); for (int i = 0; i < 3; ++i) { Eigen::Matrix<symbolic::Expression, 4, 4> M{}; // clang-format off M << s(i) * Q[i] - P, s(i) * b[i] - c, s(i) * b[i].transpose() - c.transpose(), 1 - s(i); // clang-format on prog.AddPositiveSemidefiniteConstraint(M); } prog.AddLinearCost(-P.cast<symbolic::Expression>().trace()); const MathematicalProgramResult result = RunSolver(prog, solver, {}, solver_options); const auto P_value = result.GetSolution(P); const auto s_value = result.GetSolution(s); const auto c_value = result.GetSolution(c); EXPECT_NEAR(-P_value.trace(), result.get_optimal_cost(), tol); const Eigen::SelfAdjointEigenSolver<Matrix3d> es_P(P_value); EXPECT_TRUE((es_P.eigenvalues().array() >= -tol).all()); // The minimal eigen value of M should be 0, since the optimality happens at // the boundary of the PSD cone. double M_min_eigenvalue = kInf; for (int i = 0; i < 3; ++i) { Matrix4d M_value; // clang-format off M_value << s_value(i) * Q[i] - P_value, s_value(i) * b[i] - c_value, s_value(i) * b[i].transpose() - c_value.transpose(), 1 - s_value(i); // clang-format on Eigen::SelfAdjointEigenSolver<Matrix4d> es_M(M_value); EXPECT_TRUE((es_M.eigenvalues().array() >= -tol).all()); M_min_eigenvalue = std::min(M_min_eigenvalue, es_M.eigenvalues().minCoeff()); } EXPECT_NEAR(M_min_eigenvalue, 0, tol); } void SolveEigenvalueProblem(const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); Matrix3d F1; // clang-format off F1 << 1, 0.2, 0.3, 0.2, 2, -0.1, 0.3, -0.1, 4; Matrix3d F2; F2 << 2, 0.4, 0.7, 0.4, -1, 0.1, 0.7, 0.1, 5; // clang-format on auto z = prog.NewContinuousVariables<1>("z"); prog.AddLinearMatrixInequalityConstraint( {Matrix3d::Zero(), Matrix3d::Identity(), -F1, -F2}, {z, x}); const Vector2d x_lb(0.1, 1); const Vector2d x_ub(2, 3); prog.AddBoundingBoxConstraint(x_lb, x_ub, x); prog.AddLinearCost(z(0)); const MathematicalProgramResult result = RunSolver(prog, solver, {}, solver_options); const double z_value = result.GetSolution(z(0)); const auto x_value = result.GetSolution(x); const auto xF_sum = x_value(0) * F1 + x_value(1) * F2; EXPECT_NEAR(z_value, result.get_optimal_cost(), tol); Eigen::SelfAdjointEigenSolver<Matrix3d> eigen_solver_xF(xF_sum); EXPECT_NEAR(z_value, eigen_solver_xF.eigenvalues().maxCoeff(), tol); EXPECT_TRUE(((x_value - x_lb).array() >= -tol).all()); EXPECT_TRUE(((x_value - x_ub).array() <= tol).all()); } void SolveSDPwithSecondOrderConeExample1(const SolverInterface& solver, double tol) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); auto x = prog.NewContinuousVariables<3>(); Eigen::Matrix3d C0; // clang-format off C0 << 2, 1, 0, 1, 2, 1, 0, 1, 2; // clang-format on prog.AddLinearCost((C0 * X.cast<symbolic::Expression>()).trace() + x(0)); prog.AddLinearConstraint( (Matrix3d::Identity() * X.cast<Expression>()).trace() + x(0) == 1); prog.AddLinearConstraint( (Matrix3d::Ones() * X.cast<Expression>()).trace() + x(1) + x(2) == 0.5); prog.AddPositiveSemidefiniteConstraint(X); prog.AddLorentzConeConstraint(x.cast<symbolic::Expression>()); MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); const auto X_val = result.GetSolution(X); const auto x_val = result.GetSolution(x); EXPECT_NEAR((C0 * X_val).trace() + x_val(0), result.get_optimal_cost(), tol); EXPECT_NEAR((Eigen::Matrix3d::Identity() * X_val).trace() + x_val(0), 1, tol); EXPECT_NEAR((Eigen::Matrix3d::Ones() * X_val).trace() + x_val(1) + x_val(2), 0.5, tol); EXPECT_GE(x_val(0), std::sqrt(x_val(1) * x_val(1) + x_val(2) * x_val(2)) - tol); } void SolveSDPwithSecondOrderConeExample2(const SolverInterface& solver, double tol) { MathematicalProgram prog; const auto X = prog.NewSymmetricContinuousVariables<3>(); const auto x = prog.NewContinuousVariables<1>()(0); prog.AddLinearCost(X(0, 0) + X(1, 1) + x); prog.AddBoundingBoxConstraint(0, kInf, x); prog.AddLinearConstraint(X(0, 0) + 2 * X(1, 1) + X(2, 2) + 3 * x == 3); Vector3<symbolic::Expression> lorentz_cone_expr; lorentz_cone_expr << X(0, 0), X(1, 1) + x, X(1, 1) + X(2, 2); prog.AddLorentzConeConstraint(lorentz_cone_expr); prog.AddLinearConstraint(X(1, 0) + X(2, 1) == 1); prog.AddPositiveSemidefiniteConstraint(X); MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); const auto X_val = result.GetSolution(X); const auto x_val = result.GetSolution(x); EXPECT_NEAR(result.get_optimal_cost(), X_val(0, 0) + X_val(1, 1) + x_val, tol); Eigen::SelfAdjointEigenSolver<Matrix3d> es(X_val); EXPECT_TRUE((es.eigenvalues().array() >= -tol).all()); EXPECT_NEAR(X_val(0, 0) + 2 * X_val(1, 1) + X_val(2, 2) + 3 * x_val, 3, tol); EXPECT_GE(X_val(0, 0), std::sqrt(std::pow(X_val(1, 1) + x_val, 2) + std::pow(X_val(1, 1) + X_val(2, 2), 2)) - tol); EXPECT_NEAR(X_val(1, 0) + X_val(2, 1), 1, tol); EXPECT_GE(x_val, -tol); } void SolveSDPwithOverlappingVariables(const SolverInterface& solver, double tol) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); prog.AddPositiveSemidefiniteConstraint( (Matrix2<symbolic::Variable>() << x(0), x(1), x(1), x(0)).finished()); prog.AddPositiveSemidefiniteConstraint( (Matrix2<symbolic::Variable>() << x(0), x(2), x(2), x(0)).finished()); prog.AddBoundingBoxConstraint(1, 1, x(1)); prog.AddLinearCost(2 * x(0) + x(2)); MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.GetSolution(x), Eigen::Vector3d(1, 1, -1), tol)); EXPECT_NEAR(result.get_optimal_cost(), 1, tol); } void SolveSDPwithQuadraticCosts(const SolverInterface& solver, double tol) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); const Matrix2<symbolic::Variable> X1 = (Matrix2<symbolic::Variable>() << x(0), x(1), x(1), x(0)).finished(); auto psd_constraint1 = prog.AddPositiveSemidefiniteConstraint(X1); const Matrix2<symbolic::Variable> X2 = (Matrix2<symbolic::Variable>() << x(0), x(2), x(2), x(0)).finished(); auto psd_constraint2 = prog.AddPositiveSemidefiniteConstraint(X2); prog.AddBoundingBoxConstraint(1, 1, x(1)); prog.AddQuadraticCost(x(0) * x(0)); prog.AddLinearCost(2 * x(0) + x(2)); MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.GetSolution(x), Eigen::Vector3d(1, 1, -1), tol)); EXPECT_NEAR(result.get_optimal_cost(), 2, tol); // Check the complementarity condition for the PSD constraint. const auto psd_dual1 = math::ToSymmetricMatrixFromLowerTriangularColumns( result.GetDualSolution(psd_constraint1)); const auto psd_dual2 = math::ToSymmetricMatrixFromLowerTriangularColumns( result.GetDualSolution(psd_constraint2)); const auto X1_sol = result.GetSolution(X1); const auto X2_sol = result.GetSolution(X2); EXPECT_NEAR((psd_dual1 * X1_sol).trace(), 0, tol); EXPECT_NEAR((psd_dual2 * X2_sol).trace(), 0, tol); } void TestSDPDualSolution1(const SolverInterface& solver, double tol) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<2>(); auto psd_con = prog.AddPositiveSemidefiniteConstraint(X); auto bb_con = prog.AddBoundingBoxConstraint( Eigen::Vector2d(kInf, kInf), Eigen::Vector2d(4, 1), Vector2<symbolic::Variable>(X(0, 0), X(1, 1))); prog.AddLinearCost(X(1, 0)); MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); const auto X_sol = result.GetSolution(X); EXPECT_TRUE(CompareMatrices( X_sol, (Eigen::Matrix2d() << 4, -2, -2, 1).finished(), tol)); // The optimal cost is -sqrt(x0 * x2), hence the sensitivity to the // bounding box constraint on x0 is -.25, and the sensitivity to the bounding // box constraint on x2 is -1. const Eigen::Vector2d bb_con_dual_expected(-0.25, -1); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(bb_con), bb_con_dual_expected, tol)); const auto psd_dual = math::ToSymmetricMatrixFromLowerTriangularColumns( result.GetDualSolution(psd_con)); // Complementarity condition ensures the inner product of X and its dual is 0. EXPECT_NEAR((X_sol * psd_dual).trace(), 0, tol); // The problem in the primal form is // min [0 0.5] ● X // [0.5 0] // s.t [1 0] ● X <= 4 // [0 0] // // [0 0] ● X <= 1 // [0 1] // The problem in the dual form (LMI) is // max 4*y1 + y2 // s.t [-y1 0.5] is psd (1) // [0.5 -y2] // The optimal solution is to the dual is y1 = -0.25, y2 = -1. Plug in this // dual solution to the left hand side of (1) is what Mosek/SCS returns as the // dual solution. Eigen::Matrix2d psd_dual_expected; // clang-format off psd_dual_expected << 0.25, 0.5, 0.5, 1; // clang-format on EXPECT_TRUE(CompareMatrices(psd_dual, psd_dual_expected, tol)); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/aggregate_costs_constraints_test.cc
#include "drake/solvers/aggregate_costs_constraints.h" #include <limits> #include <fmt/format.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/symbolic_test_util.h" using ::testing::HasSubstr; namespace drake { namespace solvers { const double kInf = std::numeric_limits<double>::infinity(); class TestAggregateCostsAndConstraints : public ::testing::Test { public: TestAggregateCostsAndConstraints() { for (int i = 0; i < 4; ++i) { x_.push_back(symbolic::Variable(fmt::format("x{}", i))); } } protected: std::vector<symbolic::Variable> x_; }; TEST_F(TestAggregateCostsAndConstraints, TestQuadraticCostsOnly) { // Test a single quadratic cost. std::vector<Binding<QuadraticCost>> quadratic_costs; Eigen::Matrix2d Q1; // clang-format off Q1 << 1, 2, 2, 3; // clang-format on const Eigen::Vector2d b1(5, 0.); const double c1{2}; const Vector2<symbolic::Variable> vars1(x_[0], x_[2]); quadratic_costs.emplace_back(std::make_shared<QuadraticCost>(Q1, b1, c1), vars1); Eigen::SparseMatrix<double> Q_lower; Eigen::SparseVector<double> linear_coeff; VectorX<symbolic::Variable> quadratic_vars; VectorX<symbolic::Variable> linear_vars; double constant_cost; AggregateQuadraticAndLinearCosts(quadratic_costs, {}, &Q_lower, &quadratic_vars, &linear_coeff, &linear_vars, &constant_cost); EXPECT_EQ(quadratic_vars.rows(), 2); EXPECT_EQ(quadratic_vars(0).get_id(), x_[0].get_id()); EXPECT_EQ(quadratic_vars(1).get_id(), x_[2].get_id()); EXPECT_TRUE( CompareMatrices(Eigen::MatrixXd(Q_lower), Eigen::MatrixXd(Q1.triangularView<Eigen::Lower>()))); EXPECT_TRUE(CompareMatrices(Eigen::VectorXd(linear_coeff), Vector1d(5))); EXPECT_EQ(linear_vars.rows(), 1); EXPECT_EQ(linear_vars(0).get_id(), x_[0].get_id()); EXPECT_EQ(constant_cost, c1); // Now test multiple costs. These costs share variables. Eigen::Matrix3d Q2; // clang-format off Q2 << 10, 20, 30, 20, 40, 0, 30, 0, 50; // clang-format on const Eigen::Vector3d b2(10, 0, 50); const double c2 = 40; const Vector3<symbolic::Variable> vars2(x_[2], x_[1], x_[3]); quadratic_costs.emplace_back(std::make_shared<QuadraticCost>(Q2, b2, c2), vars2); AggregateQuadraticAndLinearCosts(quadratic_costs, {}, &Q_lower, &quadratic_vars, &linear_coeff, &linear_vars, &constant_cost); EXPECT_EQ(quadratic_vars.rows(), 4); EXPECT_EQ(quadratic_vars(0).get_id(), x_[0].get_id()); EXPECT_EQ(quadratic_vars(1).get_id(), x_[2].get_id()); EXPECT_EQ(quadratic_vars(2).get_id(), x_[1].get_id()); EXPECT_EQ(quadratic_vars(3).get_id(), x_[3].get_id()); Eigen::Matrix4d Q_expected; // [x(0); x(2)] * Q1 * [x0; x(2)] + [x(2), x(1), x(3)] * Q2 * [x(2), x(1), // x(3)] = [x(0); x(2); x(1); x(3)] * Q_expected * [x(0); x(2); x(1); x(3)] // clang-format off Q_expected << 1, 0, 0, 0, 2, 13, 0, 0, 0, 20, 40, 0, 0, 30, 0, 50; // clang-format on EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(Q_lower), Q_expected)); EXPECT_TRUE(CompareMatrices(Eigen::VectorXd(linear_coeff), Eigen::Vector3d(5, 10, 50))); EXPECT_EQ(linear_vars.rows(), 3); EXPECT_EQ(linear_vars(0).get_id(), x_[0].get_id()); EXPECT_EQ(linear_vars(1).get_id(), x_[2].get_id()); EXPECT_EQ(linear_vars(2).get_id(), x_[3].get_id()); EXPECT_EQ(constant_cost, c1 + c2); // Add another quadratic cost. Eigen::Matrix2d Q3; Q3 << 0, 0, 0, 1; const Eigen::Vector2d b3(0.1, 0.5); const double c3 = 0.5; const Vector2<symbolic::Variable> vars3(x_[2], x_[1]); quadratic_costs.emplace_back(std::make_shared<QuadraticCost>(Q3, b3, c3), vars3); AggregateQuadraticAndLinearCosts(quadratic_costs, {}, &Q_lower, &quadratic_vars, &linear_coeff, &linear_vars, &constant_cost); // Check if the aggregated cost (in symbolic form) is correct. EXPECT_PRED2( symbolic::test::ExprEqual, quadratic_vars .dot(Eigen::MatrixXd( Eigen::MatrixXd(Q_lower).selfadjointView<Eigen::Lower>()) * quadratic_vars) .Expand(), (vars1.dot(Q1 * vars1) + vars2.dot(Q2 * vars2) + vars3.dot(Q3 * vars3)) .Expand()); EXPECT_PRED2(symbolic::test::ExprEqual, Eigen::VectorXd(linear_coeff).dot(linear_vars), (b1.dot(vars1) + b2.dot(vars2) + b3.dot(vars3)).Expand()); EXPECT_EQ(constant_cost, c1 + c2 + c3); } TEST_F(TestAggregateCostsAndConstraints, LinearCostsOnly) { // Test a single cost. This cost has a sparse linear coefficient. std::vector<Binding<LinearCost>> linear_costs; const Eigen::Vector3d a1(1, 0, 2); const double b1{3}; const Vector3<symbolic::Variable> var1(x_[0], x_[2], x_[1]); linear_costs.emplace_back(std::make_shared<LinearCost>(a1, b1), var1); Eigen::SparseVector<double> linear_coeff; VectorX<symbolic::Variable> vars; double constant_cost; AggregateLinearCosts(linear_costs, &linear_coeff, &vars, &constant_cost); EXPECT_TRUE( CompareMatrices(Eigen::VectorXd(linear_coeff), Eigen::Vector2d(1, 2))); EXPECT_EQ(vars.rows(), 2); EXPECT_EQ(vars(0).get_id(), x_[0].get_id()); EXPECT_EQ(vars(1).get_id(), x_[1].get_id()); EXPECT_EQ(constant_cost, 3); // Add a second cost. This second cost shares some variables with the first // cost. const Eigen::Vector3d a2(0, 20, 30); const double b2{40}; const Vector3<symbolic::Variable> var2(x_[2], x_[0], x_[1]); linear_costs.emplace_back(std::make_shared<LinearCost>(a2, b2), var2); AggregateLinearCosts(linear_costs, &linear_coeff, &vars, &constant_cost); EXPECT_TRUE( CompareMatrices(Eigen::VectorXd(linear_coeff), Eigen::Vector2d(21, 32))); EXPECT_EQ(vars.rows(), 2); EXPECT_EQ(vars(0).get_id(), x_[0].get_id()); EXPECT_EQ(vars(1).get_id(), x_[1].get_id()); EXPECT_EQ(constant_cost, 43); // Check if the symbolic expression is the same. EXPECT_PRED2(symbolic::test::ExprEqual, Eigen::VectorXd(linear_coeff).dot(vars), (a1.dot(var1) + a2.dot(var2)).Expand()); } TEST_F(TestAggregateCostsAndConstraints, QuadraticAndLinearCosts) { std::vector<Binding<QuadraticCost>> quadratic_costs; std::vector<Binding<LinearCost>> linear_costs; // One quadratic and one linear cost. Eigen::Matrix3d Q1; // clang-format off Q1 << 1, 2, 0, 2, 3, 4, 0, 4, 5; // clang-format on const Eigen::Vector3d b1(1, 0, 2); const double c1{3}; const Vector3<symbolic::Variable> vars1(x_[0], x_[2], x_[1]); quadratic_costs.emplace_back(std::make_shared<QuadraticCost>(Q1, b1, c1), vars1); const Eigen::Vector3d b2(2, -1, 0); const double c2{1}; const Vector3<symbolic::Variable> vars2(x_[0], x_[1], x_[3]); linear_costs.emplace_back(std::make_shared<LinearCost>(b2, c2), vars2); Eigen::SparseMatrix<double> Q_lower; VectorX<symbolic::Variable> quadratic_vars, linear_vars; Eigen::SparseVector<double> linear_coeff; double constant_cost; AggregateQuadraticAndLinearCosts(quadratic_costs, linear_costs, &Q_lower, &quadratic_vars, &linear_coeff, &linear_vars, &constant_cost); EXPECT_TRUE( CompareMatrices(Eigen::MatrixXd(Q_lower), Eigen::MatrixXd(Q1.triangularView<Eigen::Lower>()))); EXPECT_EQ(quadratic_vars.rows(), 3); EXPECT_EQ(quadratic_vars(0).get_id(), vars1(0).get_id()); EXPECT_EQ(quadratic_vars(1).get_id(), vars1(1).get_id()); EXPECT_EQ(quadratic_vars(2).get_id(), vars1(2).get_id()); EXPECT_TRUE( CompareMatrices(Eigen::VectorXd(linear_coeff), Eigen::Vector2d(3, 1))); EXPECT_EQ(linear_vars.rows(), 2); EXPECT_EQ(linear_vars(0).get_id(), x_[0].get_id()); EXPECT_EQ(linear_vars(1).get_id(), x_[1].get_id()); EXPECT_EQ(constant_cost, c1 + c2); // More quadratic and linear costs. Eigen::Matrix2d Q3; // clang-format off Q3 << 10, 30, 30, 40; // clang-format on const Eigen::Vector2d b3(20, 30); const double c3{40}; const Vector2<symbolic::Variable> vars3(x_[3], x_[1]); quadratic_costs.emplace_back(std::make_shared<QuadraticCost>(Q3, b3, c3), vars3); const Eigen::Vector4d b4(20, 0, 30, 40); const double c4{10}; const Vector4<symbolic::Variable> vars4(x_[2], x_[1], x_[3], x_[0]); linear_costs.emplace_back(std::make_shared<LinearCost>(b4, c4), vars4); AggregateQuadraticAndLinearCosts(quadratic_costs, linear_costs, &Q_lower, &quadratic_vars, &linear_coeff, &linear_vars, &constant_cost); Eigen::Matrix4d Q_lower_expected; // clang-format off Q_lower_expected << 1, 0, 0, 0, 2, 3, 0, 0, 0, 4, 45, 0, 0, 0, 30, 10; // clang-format on EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(Q_lower), Eigen::MatrixXd(Q_lower_expected))); EXPECT_EQ(quadratic_vars.rows(), 4); EXPECT_EQ(quadratic_vars(0).get_id(), x_[0].get_id()); EXPECT_EQ(quadratic_vars(1).get_id(), x_[2].get_id()); EXPECT_EQ(quadratic_vars(2).get_id(), x_[1].get_id()); EXPECT_EQ(quadratic_vars(3).get_id(), x_[3].get_id()); EXPECT_TRUE(CompareMatrices(Eigen::VectorXd(linear_coeff), Eigen::Vector4d(43, 31, 50, 20))); EXPECT_EQ(linear_vars.rows(), 4); EXPECT_EQ(linear_vars(0).get_id(), x_[0].get_id()); EXPECT_EQ(linear_vars(1).get_id(), x_[1].get_id()); EXPECT_EQ(linear_vars(2).get_id(), x_[3].get_id()); EXPECT_EQ(linear_vars(3).get_id(), x_[2].get_id()); EXPECT_EQ(constant_cost, c1 + c2 + c3 + c4); } TEST_F(TestAggregateCostsAndConstraints, AggregateBoundingBoxConstraints1) { // Test AggregateBoundingBoxConstraints with input being // std::vector<Binding<BoundingBoxConstraint>> std::vector<Binding<BoundingBoxConstraint>> bounding_box_constraints{}; auto result = AggregateBoundingBoxConstraints(bounding_box_constraints); EXPECT_EQ(result.size(), 0); // 1 <= x0 <= 2 // 3 <= x2 <= 5 bounding_box_constraints.emplace_back( std::make_shared<BoundingBoxConstraint>(Eigen::Vector2d(1, 3), Eigen::Vector2d(2, 5)), Vector2<symbolic::Variable>(x_[0], x_[2])); result = AggregateBoundingBoxConstraints(bounding_box_constraints); EXPECT_EQ(result.size(), 2); EXPECT_EQ(result.at(x_[0]).lower, 1); EXPECT_EQ(result.at(x_[0]).upper, 2); EXPECT_EQ(result.at(x_[2]).lower, 3); EXPECT_EQ(result.at(x_[2]).upper, 5); // 2 <= x2 <= 4 // 1.5 <= x0 <= inf // 4 <= x1 <= inf bounding_box_constraints.emplace_back( std::make_shared<BoundingBoxConstraint>(Eigen::Vector3d(2, 1.5, 4), Eigen::Vector3d(4, kInf, kInf)), Vector3<symbolic::Variable>(x_[2], x_[0], x_[1])); result = AggregateBoundingBoxConstraints(bounding_box_constraints); EXPECT_EQ(result.size(), 3); EXPECT_EQ(result.at(x_[0]).lower, 1.5); EXPECT_EQ(result.at(x_[0]).upper, 2); EXPECT_EQ(result.at(x_[1]).lower, 4); EXPECT_EQ(result.at(x_[1]).upper, kInf); EXPECT_EQ(result.at(x_[2]).lower, 3); EXPECT_EQ(result.at(x_[2]).upper, 4); // -inf <= x1 <= 2. The returned bounds for x1 should be 4 <= x1 <= 2. This // test that we can return the bounds even if the lower bound is higher than // the upper bound. bounding_box_constraints.emplace_back( std::make_shared<BoundingBoxConstraint>(Vector1d(-kInf), Vector1d(2)), Vector1<symbolic::Variable>(x_[1])); result = AggregateBoundingBoxConstraints(bounding_box_constraints); EXPECT_EQ(result.size(), 3); // Only the bound of x_[1] should change, the rest should be the same. EXPECT_EQ(result.at(x_[0]).lower, 1.5); EXPECT_EQ(result.at(x_[0]).upper, 2); EXPECT_EQ(result.at(x_[1]).lower, 4); EXPECT_EQ(result.at(x_[1]).upper, 2); EXPECT_EQ(result.at(x_[2]).lower, 3); EXPECT_EQ(result.at(x_[2]).upper, 4); } TEST_F(TestAggregateCostsAndConstraints, AggregateBoundingBoxConstraints2) { // Test AggregateBoundingBoxConstraints with input being MathematicalPorgram. MathematicalProgram prog; auto x = prog.NewContinuousVariables<4>(); prog.AddBoundingBoxConstraint(1, 3, x.tail<2>()); prog.AddBoundingBoxConstraint(-1, 2, x(0)); prog.AddBoundingBoxConstraint(-kInf, 2, x(3)); Eigen::VectorXd lower, upper; AggregateBoundingBoxConstraints(prog, &lower, &upper); EXPECT_TRUE(CompareMatrices(lower, Eigen::Vector4d(-1, -kInf, 1, 1))); EXPECT_TRUE(CompareMatrices(upper, Eigen::Vector4d(2, kInf, 3, 2))); std::vector<double> lower_vec, upper_vec; AggregateBoundingBoxConstraints(prog, &lower_vec, &upper_vec); EXPECT_TRUE(CompareMatrices( Eigen::Map<Eigen::VectorXd>(lower_vec.data(), lower_vec.size()), Eigen::Vector4d(-1, -kInf, 1, 1))); EXPECT_TRUE(CompareMatrices( Eigen::Map<Eigen::VectorXd>(upper_vec.data(), upper_vec.size()), Eigen::Vector4d(2, kInf, 3, 2))); } void CheckAggregateDuplicateVariables(const Eigen::SparseMatrix<double>& A, const VectorX<symbolic::Variable>& vars) { Eigen::SparseMatrix<double> A_new; VectorX<symbolic::Variable> vars_new; AggregateDuplicateVariables(A, vars, &A_new, &vars_new); EXPECT_EQ(A.rows(), A_new.rows()); for (int i = 0; i < A.rows(); ++i) { EXPECT_PRED2(symbolic::test::ExprEqual, A.toDense().row(i).dot(vars).Expand(), A_new.toDense().row(i).dot(vars_new).Expand()); } // Make sure vars_new doesn't have duplicated variables. std::unordered_set<symbolic::Variable::Id> vars_new_set; for (int i = 0; i < vars_new.rows(); ++i) { EXPECT_EQ(vars_new_set.find(vars_new(i).get_id()), vars_new_set.end()); vars_new_set.insert(vars_new(i).get_id()); } } TEST_F(TestAggregateCostsAndConstraints, AggregateDuplicateVariables) { Eigen::SparseMatrix<double> A = Eigen::RowVector3d(1, 2, 3).sparseView(); // No duplication. CheckAggregateDuplicateVariables( A, Vector3<symbolic::Variable>(x_[0], x_[1], x_[2])); // A is a row vector, vars has duplication. CheckAggregateDuplicateVariables( A, Vector3<symbolic::Variable>(x_[0], x_[1], x_[0])); CheckAggregateDuplicateVariables( A, Vector3<symbolic::Variable>(x_[0], x_[0], x_[0])); // A is a matrix. A = (Eigen::Matrix<double, 2, 3>() << 0, 1, 2, 3, 4, 0) .finished() .sparseView(); CheckAggregateDuplicateVariables( A, Vector3<symbolic::Variable>(x_[1], x_[0], x_[1])); } GTEST_TEST(TestFindNonconvexQuadraticCost, Test) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto convex_cost1 = prog.AddQuadraticCost(x(0) * x(0) + 1); auto convex_cost2 = prog.AddQuadraticCost(x(1) * x(1) + 2 * x(0) + 2); auto nonconvex_cost1 = prog.AddQuadraticCost(-x(0) * x(0) + 2 * x(1)); auto nonconvex_cost2 = prog.AddQuadraticCost(-x(0) * x(0) + x(1) * x(1)); EXPECT_EQ(internal::FindNonconvexQuadraticCost({convex_cost1, convex_cost2}), nullptr); EXPECT_EQ( internal::FindNonconvexQuadraticCost({convex_cost1, nonconvex_cost1}) ->evaluator() .get(), nonconvex_cost1.evaluator().get()); EXPECT_EQ(internal::FindNonconvexQuadraticCost( {convex_cost1, nonconvex_cost1, nonconvex_cost2}) ->evaluator() .get(), nonconvex_cost1.evaluator().get()); } GTEST_TEST(TestFindNonconvexQuadraticConstraint, Test) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto convex_constraint1 = prog.AddQuadraticConstraint(x(0) * x(0) + 1, -kInf, 1); auto convex_constraint2 = prog.AddQuadraticConstraint(x(1) * x(1) + 2 * x(0) + 2, -kInf, 3); auto nonconvex_constraint1 = prog.AddQuadraticConstraint(-x(0) * x(0) + 2 * x(1), 0, 0); auto nonconvex_constraint2 = prog.AddQuadraticConstraint(-x(0) * x(0) + x(1) * x(1), 1, 2); EXPECT_EQ(internal::FindNonconvexQuadraticConstraint( {convex_constraint1, convex_constraint2}), nullptr); EXPECT_EQ(internal::FindNonconvexQuadraticConstraint( {convex_constraint1, nonconvex_constraint1}) ->evaluator() .get(), nonconvex_constraint1.evaluator().get()); EXPECT_EQ( internal::FindNonconvexQuadraticConstraint( {convex_constraint1, nonconvex_constraint1, nonconvex_constraint2}) ->evaluator() .get(), nonconvex_constraint1.evaluator().get()); } namespace internal { GTEST_TEST(CheckConvexSolverAttributes, Test) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto convex_cost = prog.AddQuadraticCost(x(0) * x(0) + x(1)); // Requires linear cost, but program has a quadratic cost. ProgramAttributes required_capabilities{ProgramAttribute::kLinearCost}; EXPECT_FALSE( CheckConvexSolverAttributes(prog, required_capabilities, "foo", nullptr)); std::string explanation; EXPECT_FALSE(CheckConvexSolverAttributes(prog, required_capabilities, "foo", &explanation)); EXPECT_THAT(explanation, HasSubstr("foo is unable to solve because a QuadraticCost was " "declared but is not supported")); // Test when the required capabilities matches with the program. required_capabilities = {ProgramAttribute::kQuadraticCost}; EXPECT_TRUE( CheckConvexSolverAttributes(prog, required_capabilities, "foo", nullptr)); EXPECT_TRUE(CheckConvexSolverAttributes(prog, required_capabilities, "foo", &explanation)); EXPECT_TRUE(explanation.empty()); // program has a non-convex quadratic cost. auto nonconvex_cost = prog.AddQuadraticCost(-x(1) * x(1)); // Use a description that would never be mistaken as any other part of the // error message. const std::string description{"lorem ipsum"}; nonconvex_cost.evaluator()->set_description(description); EXPECT_FALSE( CheckConvexSolverAttributes(prog, required_capabilities, "foo", nullptr)); EXPECT_FALSE(CheckConvexSolverAttributes(prog, required_capabilities, "foo", &explanation)); EXPECT_THAT(explanation, HasSubstr("is non-convex")); EXPECT_THAT(explanation, HasSubstr("foo")); EXPECT_THAT(explanation, HasSubstr(description)); // program has a non-convex quadratic constraint. prog.RemoveCost(convex_cost); prog.RemoveCost(nonconvex_cost); auto nonconvex_constraint = prog.AddQuadraticConstraint(x(1) * x(1), 1, kInf); // Use a description that would never be mistaken as any other part of the // error message. const std::string nonconvex_quadratic_constraint_description{"alibaba ipsum"}; nonconvex_constraint.evaluator()->set_description( nonconvex_quadratic_constraint_description); required_capabilities = {ProgramAttribute::kQuadraticConstraint}; EXPECT_FALSE( CheckConvexSolverAttributes(prog, required_capabilities, "foo", nullptr)); EXPECT_FALSE(CheckConvexSolverAttributes(prog, required_capabilities, "foo", &explanation)); EXPECT_THAT(explanation, HasSubstr("is non-convex")); EXPECT_THAT(explanation, HasSubstr("foo")); EXPECT_THAT(explanation, HasSubstr(nonconvex_quadratic_constraint_description)); } GTEST_TEST(ParseLinearCosts, Test) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>(); const auto y = prog.NewContinuousVariables<3>(); prog.AddLinearCost(x[0] + 2 * y[0] + 1); prog.AddLinearCost(x[1] - 2 * x[0] + 3 * y[1] - y[0] + 2); std::vector<double> c(prog.num_vars(), 0); double constant = 0; ParseLinearCosts(prog, &c, &constant); // The aggregated costs are -x[0] + x[1] + y[0] + 3y[1] + 3 Eigen::Matrix<double, 5, 1> coeff = (Eigen::Matrix<double, 5, 1>() << -1, 1, 1, 3, 0).finished(); EXPECT_TRUE(CompareMatrices(Eigen::Map<Eigen::Matrix<double, 5, 1>>(c.data()), coeff)); EXPECT_EQ(constant, 3); // Now start with a non-zero c and constant. c = {1, 2, 3, 4, 5}; constant = 2; Eigen::Matrix<double, 5, 1> c_expected = coeff + Eigen::Map<Eigen::Matrix<double, 5, 1>>(c.data()); double constant_expected = constant + 3; ParseLinearCosts(prog, &c, &constant); EXPECT_TRUE(CompareMatrices(Eigen::Map<Eigen::Matrix<double, 5, 1>>(c.data()), c_expected)); EXPECT_EQ(constant, constant_expected); } GTEST_TEST(ParseLinearEqualityConstraints, Test) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>(); const auto y = prog.NewContinuousVariables<2>(); prog.AddLinearEqualityConstraint( Eigen::RowVector3d(1, 2, 4), 1, Vector3<symbolic::Variable>(x(0), x(0), y(1))); prog.AddLinearEqualityConstraint((Eigen::Matrix2d() << 1, 2, 3, 4).finished(), Eigen::Vector2d(2, 3), Vector2<symbolic::Variable>(x(1), y(0))); std::vector<Eigen::Triplet<double>> A_triplets; std::vector<double> b; int A_row_count = 0; std::vector<int> linear_eq_y_start_indices; int num_linear_equality_constraints_rows = 0; ParseLinearEqualityConstraints(prog, &A_triplets, &b, &A_row_count, &linear_eq_y_start_indices, &num_linear_equality_constraints_rows); Eigen::SparseMatrix<double> A(3, prog.num_vars()); A.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::MatrixXd A_expected(3, prog.num_vars()); // clang-format off A_expected << 3, 0, 0, 4, 0, 1, 2, 0, 0, 3, 4, 0; // clang-format on EXPECT_TRUE(CompareMatrices(A.toDense(), A_expected)); EXPECT_TRUE(CompareMatrices(Eigen::Map<Eigen::Vector3d>(b.data()), Eigen::Vector3d(1, 2, 3))); EXPECT_EQ(A_row_count, 3); std::vector<int> linear_eq_y_start_indices_expected{0, 1}; EXPECT_EQ(linear_eq_y_start_indices, linear_eq_y_start_indices_expected); EXPECT_EQ(num_linear_equality_constraints_rows, 3); // Use a non-zero A_row_count. The row indices should be offset by the initial // A_row_count. const int A_rows_offset = 2; A_row_count = A_rows_offset; A_triplets.clear(); b = std::vector<double>{0, 0}; linear_eq_y_start_indices.clear(); ParseLinearEqualityConstraints(prog, &A_triplets, &b, &A_row_count, &linear_eq_y_start_indices, &num_linear_equality_constraints_rows); Eigen::SparseMatrix<double> A2(A_rows_offset + 3, prog.num_vars()); A2.setFromTriplets(A_triplets.begin(), A_triplets.end()); EXPECT_TRUE(CompareMatrices(A2.toDense().bottomRows(3), A_expected)); EXPECT_TRUE( CompareMatrices(Eigen::Map<Eigen::Vector3d>(b.data() + A_rows_offset), Eigen::Vector3d(1, 2, 3))); EXPECT_EQ(A_row_count, A_rows_offset + 3); linear_eq_y_start_indices_expected = std::vector<int>{A_rows_offset, A_rows_offset + 1}; EXPECT_EQ(linear_eq_y_start_indices, linear_eq_y_start_indices_expected); EXPECT_EQ(num_linear_equality_constraints_rows, 3); } GTEST_TEST(ParseLinearConstraints, Test) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<2>(); const auto y = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint( (Eigen::Matrix3d() << 1, 2, 3, 4, 5, 6, 7, 8, 9).finished(), Eigen::Vector3d(-kInf, 3, 2), Eigen::Vector3d(1, kInf, 4), Vector3<symbolic::Variable>(x(0), y(0), x(0))); prog.AddLinearConstraint(Eigen::RowVector3d(1, 2, 3), -1, 3, Vector3<symbolic::Variable>(y(0), y(1), x(1))); std::vector<Eigen::Triplet<double>> A_triplets; std::vector<double> b; int A_row_count = 0; std::vector<std::vector<std::pair<int, int>>> linear_constraint_dual_indices; int num_linear_constraint_rows; ParseLinearConstraints(prog, &A_triplets, &b, &A_row_count, &linear_constraint_dual_indices, &num_linear_constraint_rows); EXPECT_EQ(num_linear_constraint_rows, 6); Eigen::SparseMatrix<double> A(6, prog.num_vars()); A.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::MatrixXd A_expected(6, prog.num_vars()); // clang-format off A_expected << 4, 0, 2, 0, -10, 0, -5, 0, -16, 0, -8, 0, 16, 0, 8, 0, 0, -3, -1, -2, 0, 3, 1, 2; // clang-format on EXPECT_TRUE(CompareMatrices(A.toDense(), A_expected)); EXPECT_TRUE(CompareMatrices(Eigen::Map<Vector6d>(b.data()), (Vector6d() << 1, -3, -2, 4, 1, 3).finished())); EXPECT_EQ(A_row_count, 6); std::vector<std::vector<std::pair<int, int>>> linear_constraint_dual_indices_expected; linear_constraint_dual_indices_expected.push_back({{-1, 0}, {1, -1}, {2, 3}}); linear_constraint_dual_indices_expected.push_back({{4, 5}}); EXPECT_EQ(linear_constraint_dual_indices, linear_constraint_dual_indices_expected); EXPECT_EQ(num_linear_constraint_rows, 6); } GTEST_TEST(ParseQuadraticCosts, Test) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); prog.AddQuadraticCost((Eigen::Matrix2d() << 1, 3, 2, 4).finished(), Eigen::Vector2d(1, 2), 1, x.tail<2>()); prog.AddQuadraticCost( (Eigen::Matrix3d() << 1, 2, 3, 4, 5, 6, 7, 8, 9).finished(), Eigen::Vector3d(2, 3, 4), 2, Vector3<symbolic::Variable>(x(0), x(1), x(0))); std::vector<Eigen::Triplet<double>> P_upper_triplets; std::vector<double> c(prog.num_vars(), 0); double constant; ParseQuadraticCosts(prog, &P_upper_triplets, &c, &constant); // The total cost is 0.5 * (20*x0^2 + 6*x1^2 + 4*x2^2 + 5*x1*x2 + 20*x0*x1) + // 6*x0 + 4*x1 + 2*x(2) + 3 Eigen::SparseMatrix<double> P_upper(prog.num_vars(), prog.num_vars()); P_upper.setFromTriplets(P_upper_triplets.begin(), P_upper_triplets.end()); Eigen::Matrix3d P_upper_expected; // clang-format off P_upper_expected << 20, 10, 0, 0, 6, 2.5, 0, 0, 4; // clang-format on EXPECT_TRUE(CompareMatrices(P_upper.toDense(), P_upper_expected)); } GTEST_TEST(ParseL2NormCosts, Test) { MathematicalProgram prog{}; auto x = prog.NewContinuousVariables<3>(); Eigen::Matrix<double, 3, 2> A1; A1 << 1, 2, 3, 4, 5, 6; const Eigen::Vector3d b1(-1, -2, -3); auto cost1 = prog.AddL2NormCost(A1, b1, x.tail<2>()); int num_solver_variables = prog.num_vars(); std::vector<Eigen::Triplet<double>> A_triplets; std::vector<double> b; int A_row_count = 0; std::vector<int> second_order_cone_length; std::vector<int> lorentz_cone_y_start_indices; std::vector<double> cost_coeffs(prog.num_vars(), 0.0); std::vector<int> t_slack_indices; // First test with a single L2NormCost. ParseL2NormCosts(prog, &num_solver_variables, &A_triplets, &b, &A_row_count, &second_order_cone_length, &lorentz_cone_y_start_indices, &cost_coeffs, &t_slack_indices); EXPECT_EQ(num_solver_variables, 1 + prog.num_vars()); Eigen::SparseMatrix<double> A(1 + A1.rows(), prog.num_vars() + 1); A.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::MatrixXd A_expected(1 + A1.rows(), prog.num_vars() + 1); A_expected.setZero(); A_expected(0, prog.num_vars()) = -1; A_expected.block(1, 1, A1.rows(), A1.cols()) = -A1; EXPECT_TRUE(CompareMatrices(A.toDense(), A_expected)); Eigen::VectorXd b_expected(1 + b1.rows()); b_expected.setZero(); b_expected.tail(b1.rows()) = b1; EXPECT_TRUE(CompareMatrices(Eigen::Map<Eigen::VectorXd>(b.data(), b.size()), b_expected)); EXPECT_EQ(A_row_count, 1 + A1.rows()); EXPECT_EQ(second_order_cone_length.size(), 1); EXPECT_EQ(second_order_cone_length[0], A1.rows() + 1); EXPECT_EQ(lorentz_cone_y_start_indices.size(), 1); EXPECT_EQ(lorentz_cone_y_start_indices[0], 0); Eigen::VectorXd cost_coeffs_expected(prog.num_vars() + 1); cost_coeffs_expected.setZero(); cost_coeffs_expected(prog.num_vars()) = 1; EXPECT_TRUE(CompareMatrices( Eigen::Map<Eigen::VectorXd>(cost_coeffs.data(), cost_coeffs.size()), cost_coeffs_expected)); EXPECT_EQ(t_slack_indices.size(), 1); EXPECT_EQ(t_slack_indices[0], prog.num_vars()); // Test with multiple L2NormCost. num_solver_variables = prog.num_vars(); A_row_count = 0; A_triplets.clear(); b.clear(); second_order_cone_length.clear(); lorentz_cone_y_start_indices.clear(); cost_coeffs = std::vector<double>(prog.num_vars(), 0); t_slack_indices.clear(); Eigen::Matrix<double, 2, 2> A2; A2 << -1, -3, -5, -7; const Eigen::Vector2d b2(5, 10); auto cost2 = prog.AddL2NormCost(A2, b2, x.head<2>()); ParseL2NormCosts(prog, &num_solver_variables, &A_triplets, &b, &A_row_count, &second_order_cone_length, &lorentz_cone_y_start_indices, &cost_coeffs, &t_slack_indices); EXPECT_EQ(num_solver_variables, prog.num_vars() + 2); A_expected.resize(2 + A1.rows() + A2.rows(), prog.num_vars() + 2); A_expected.setZero(); A_expected(0, prog.num_vars()) = -1; A_expected.block(1, 1, A1.rows(), 2) = -A1; A_expected(A1.rows() + 1, prog.num_vars() + 1) = -1; A_expected.block(2 + A1.rows(), 0, A2.rows(), 2) = -A2; A.resize(2 + A1.rows() + A2.rows(), 2 + prog.num_vars()); A.setFromTriplets(A_triplets.begin(), A_triplets.end()); EXPECT_TRUE(CompareMatrices(A.toDense(), A_expected)); b_expected.resize(A1.rows() + A2.rows() + 2); b_expected.setZero(); b_expected.segment(1, A1.rows()) = b1; b_expected.segment(2 + A1.rows(), A2.rows()) = b2; EXPECT_TRUE(CompareMatrices(Eigen::Map<Eigen::VectorXd>(b.data(), b.size()), b_expected)); EXPECT_EQ(A_row_count, 2 + A1.rows() + A2.rows()); EXPECT_EQ(second_order_cone_length.size(), 2); EXPECT_EQ(second_order_cone_length[0], A1.rows() + 1); EXPECT_EQ(second_order_cone_length[1], A2.rows() + 1); EXPECT_EQ(lorentz_cone_y_start_indices.size(), 2); EXPECT_EQ(lorentz_cone_y_start_indices[0], 0); EXPECT_EQ(lorentz_cone_y_start_indices[1], 1 + A1.rows()); cost_coeffs_expected.resize(prog.num_vars() + 2); cost_coeffs_expected.setZero(); cost_coeffs_expected(prog.num_vars()) = 1; cost_coeffs_expected(prog.num_vars() + 1) = 1; EXPECT_TRUE(CompareMatrices( Eigen::Map<Eigen::VectorXd>(cost_coeffs.data(), cost_coeffs.size()), cost_coeffs_expected)); EXPECT_EQ(t_slack_indices.size(), 2); EXPECT_EQ(t_slack_indices[0], prog.num_vars()); EXPECT_EQ(t_slack_indices[1], prog.num_vars() + 1); } GTEST_TEST(ParseSecondOrderConeConstraints, LorentzCone) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); prog.AddLorentzConeConstraint( (Eigen::Matrix<double, 4, 3>() << 1, 0, 2, -1, 2, 3, 1, 2, 4, -2, 1, 2) .finished(), Eigen::Vector4d(1, 2, 3, 4), Vector3<symbolic::Variable>(x(1), x(0), x(1))); prog.AddLorentzConeConstraint( (Eigen::Matrix<double, 4, 2>() << 1, 2, 3, 4, 5, 6, 7, 8).finished(), Eigen::Vector4d(-1, -2, -3, -4), Vector2<symbolic::Variable>(x(2), x(0))); std::vector<Eigen::Triplet<double>> A_triplets; std::vector<double> b; int A_row_count{0}; std::vector<int> second_order_cone_length; std::vector<int> lorentz_cone_y_start_indices; std::vector<int> rotated_lorentz_cone_y_start_indices; ParseSecondOrderConeConstraints( prog, &A_triplets, &b, &A_row_count, &second_order_cone_length, &lorentz_cone_y_start_indices, &rotated_lorentz_cone_y_start_indices); EXPECT_EQ(A_row_count, 8); Eigen::SparseMatrix<double> A(8, prog.num_vars()); A.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::MatrixXd A_expected(8, prog.num_vars()); // clang-format off A_expected << 0, -3, 0, -2, -2, 0, -2, -5, 0, -1, 0, 0, -2, 0, -1, -4, 0, -3, -6, 0, -5, -8, 0, -7; // clang-format on EXPECT_TRUE(CompareMatrices(A.toDense(), A_expected)); Eigen::Matrix<double, 8, 1> b_expected; b_expected << 1, 2, 3, 4, -1, -2, -3, -4; EXPECT_TRUE(CompareMatrices(Eigen::Map<Eigen::Matrix<double, 8, 1>>(b.data()), b_expected)); EXPECT_EQ(second_order_cone_length, std::vector<int>({4, 4})); EXPECT_EQ(lorentz_cone_y_start_indices, std::vector<int>({0, 4})); EXPECT_EQ(rotated_lorentz_cone_y_start_indices, std::vector<int>()); } GTEST_TEST(ParseSecondOrderConeConstraints, RotatedLorentzConeConstraint) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); prog.AddRotatedLorentzConeConstraint( (Eigen::Matrix<double, 4, 3>() << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) .finished(), Eigen::Vector4d(0, 1, 2, 3), Vector3<symbolic::Variable>(x(1), x(0), x(1))); prog.AddRotatedLorentzConeConstraint( (Eigen::Matrix<double, 3, 4>() << -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12) .finished(), Eigen::Vector3d(5, 6, 7), Vector4<symbolic::Variable>(x(1), x(0), x(0), x(2))); std::vector<Eigen::Triplet<double>> A_triplets; std::vector<double> b; int A_row_count{0}; std::vector<int> second_order_cone_length; std::vector<int> lorentz_cone_y_start_indices; std::vector<int> rotated_lorentz_cone_y_start_indices; ParseSecondOrderConeConstraints( prog, &A_triplets, &b, &A_row_count, &second_order_cone_length, &lorentz_cone_y_start_indices, &rotated_lorentz_cone_y_start_indices); EXPECT_EQ(A_row_count, 7); Eigen::SparseMatrix<double> A(7, prog.num_vars()); A.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::MatrixXd A_expected(7, prog.num_vars()); // clang-format off A_expected << -3.5, -7, 0, 1.5, 3, 0, -8, -16, 0, -11, -22, 0, 9, 3, 6, -4, -2, -2, 21, 9, 12; // clang-format on EXPECT_TRUE(CompareMatrices(A.toDense(), A_expected)); Eigen::Matrix<double, 7, 1> b_expected; b_expected << 0.5, -0.5, 2, 3, 5.5, -0.5, 7; EXPECT_TRUE(CompareMatrices(Eigen::Map<Eigen::Matrix<double, 7, 1>>(b.data()), b_expected)); EXPECT_EQ(second_order_cone_length, std::vector<int>({4, 3})); EXPECT_EQ(lorentz_cone_y_start_indices, std::vector<int>()); EXPECT_EQ(rotated_lorentz_cone_y_start_indices, std::vector<int>({0, 4})); } GTEST_TEST(ParseExponentialConeConstraints, Test) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); prog.AddExponentialConeConstraint( (Eigen::Matrix<double, 3, 4>() << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) .finished() .sparseView(), Eigen::Vector3d(1, 2, 3), Vector4<symbolic::Variable>(x(1), x(0), x(2), x(0))); std::vector<Eigen::Triplet<double>> A_triplets; std::vector<double> b; int A_row_count = 0; ParseExponentialConeConstraints(prog, &A_triplets, &b, &A_row_count); EXPECT_EQ(A_row_count, 3); Eigen::SparseMatrix<double> A(3, prog.num_vars()); A.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::Matrix3d A_expected; // clang-format off A_expected << -22, -9, -11, -14, -5, -7, -6, -1, -3; // clang-format on EXPECT_TRUE(CompareMatrices(A.toDense(), A_expected)); EXPECT_EQ(b.size(), 3); EXPECT_TRUE(CompareMatrices(Eigen::Map<Eigen::Vector3d>(b.data()), Eigen::Vector3d(3, 2, 1))); } GTEST_TEST(ParsePositiveSemidefiniteConstraints, TestPsd) { // Test parsing prog.positive_semidefinite_constraints. MathematicalProgram prog; const auto X = prog.NewSymmetricContinuousVariables<3>(); prog.AddPositiveSemidefiniteConstraint(X); const auto Y = prog.NewSymmetricContinuousVariables<2>(); prog.AddPositiveSemidefiniteConstraint(Y); auto check_psd = [&prog](bool upper_triangular) { SCOPED_TRACE(fmt::format("upper_triangular = {}", upper_triangular)); std::vector<Eigen::Triplet<double>> A_triplets; // Assume that A*x+s = b already contain `A_row_count_old` number of // constraints. We check if the new constraints are appended to A*x+s = b. int A_row_count_old = 2; std::vector<double> b(A_row_count_old); int A_row_count = A_row_count_old; std::vector<int> psd_cone_length; ParsePositiveSemidefiniteConstraints(prog, upper_triangular, &A_triplets, &b, &A_row_count, &psd_cone_length); EXPECT_EQ(psd_cone_length, std::vector<int>({3, 2})); // We add 3 * (3+1) / 2 = 6 rows in A for "X is psd", and 2 * (2+1) / 2 = 3 // rows in A for "Y is psd". EXPECT_EQ(A_row_count, A_row_count_old + 3 * (3 + 1) / 2 + 2 * (2 + 1) / 2); const double sqrt2 = std::sqrt(2); Eigen::SparseMatrix<double> A(A_row_count, prog.num_vars()); A.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::MatrixXd A_expected(A_row_count_old + 9, 9); A_expected.setZero(); // [1 √2 √2] // [√2 1 √2] // [√2 √2 1] // and // [1 √2] // [√2 1] if (upper_triangular) { // If we use the upper triangular part of the symmetric matrix, to impose // the constraint that 3 by 3 matrix X is psd, we need the constraint // -X(0, 0) + s(0) = 0 // -√2X(0, 1) + s(1) = 0 // -X(1, 1) + s(2) = 0 // -√2X(0, 2) + s(3) = 0 // -√2X(1, 2) + s(4) = 0 // -X(2, 2) + s(5) = 0 // and // [s(0) s(1) s(3)] // [s(1) s(2) s(4)] is psd. // [s(3) s(4) s(5)] // Below we write // A_expected(A_row_count_old + s_index, X_index) = -X_coeff. A_expected(A_row_count_old + 0, 0 /* X(0, 0) */) = -1; A_expected(A_row_count_old + 1, 1 /* X(0, 1) */) = -sqrt2; A_expected(A_row_count_old + 2, 3 /* X(1, 1) */) = -1; A_expected(A_row_count_old + 3, 2 /* X(0, 2) */) = -sqrt2; A_expected(A_row_count_old + 4, 4 /* X(1, 2) */) = -sqrt2; A_expected(A_row_count_old + 5, 5 /* X(2, 2) */) = -1; // For the 2 by 2 matrix Y to be psd, we need the constraint // -Y(0, 0) + s(6) = 0 // -√2Y(0, 1) + s(7) = 0 // -Y(1, 1) + s(8) = 0 // and // [s(6) s(7)] is psd // [s(7) s(8)] A_expected(A_row_count_old + 6, 6) = -1; A_expected(A_row_count_old + 7, 7) = -sqrt2; A_expected(A_row_count_old + 8, 8) = -1; } else { // If we use the lower triangular part of the symmetric matrix, to impose // the constraint that 3 by 3 matrix X is psd, we need the constraint // -X(0, 0) + s(0) = 0 // -√2X(1, 0) + s(1) = 0 // -√2X(2, 0) + s(2) = 0 // -X(1, 1) + s(3) = 0 // -√2X(2, 1) + s(4) = 0 // -X(2, 2) + s(5) = 0 // and // [s(0) s(1) s(2)] // [s(1) s(3) s(4)] is psd. // [s(2) s(4) s(5)] // Below we write // A_expected(A_row_count_old + s_index, X_index) = -X_coeff. A_expected(A_row_count_old + 0, 0) = -1; A_expected(A_row_count_old + 1, 1) = -sqrt2; A_expected(A_row_count_old + 2, 2) = -sqrt2; A_expected(A_row_count_old + 3, 3) = -1; A_expected(A_row_count_old + 4, 4) = -sqrt2; A_expected(A_row_count_old + 5, 5) = -1; // For the 2 by 2 matrix Y to be psd, we need the constraint // -Y(0, 0) + s(6) = 0 // -√2Y(0, 1) + s(7) = 0 // -Y(1, 1) + s(8) = 0 // and // [s(6) s(7)] is psd // [s(7) s(8)] A_expected(A_row_count_old + 6, 6) = -1; A_expected(A_row_count_old + 7, 7) = -sqrt2; A_expected(A_row_count_old + 8, 8) = -1; } EXPECT_TRUE(CompareMatrices(A.toDense(), A_expected)); EXPECT_EQ(b.size(), A_row_count); for (int i = A_row_count_old; i < A_row_count; ++i) { EXPECT_EQ(b[i], 0); } }; check_psd(true); check_psd(false); } GTEST_TEST(ParsePositiveSemidefiniteConstraints, TestLmi) { // Test parsing prog.linear_matrix_inequality_constraints. MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); auto symmetrize_matrix = [](const Eigen::Ref<const Eigen::MatrixXd>& A) { return (A + A.transpose()) / 2; }; const auto lmi_constraint = prog.AddLinearMatrixInequalityConstraint( {symmetrize_matrix( (Eigen::Matrix3d() << 1, 2, 3, 4, 5, 6, 7, 8, 9).finished()), symmetrize_matrix( (Eigen::Matrix3d() << 1, 3, 5, 7, 9, 2, 4, 6, 8).finished()), symmetrize_matrix( (Eigen::Matrix3d() << -1, -2, 3, 4, 5, -6, -7, -8, 9).finished()), Eigen::Matrix3d::Identity()}, x); auto check_lmi = [&prog, &lmi_constraint](bool upper_triangular) { SCOPED_TRACE(fmt::format("upper_triangular = {}", upper_triangular)); std::vector<Eigen::Triplet<double>> A_triplets; // Assume A*x+s=b already contains `A_row_count_old` rows. We check if the // new PSD constraints are appended to the existing A*x+s=b. const int A_row_count_old = 2; std::vector<double> b(A_row_count_old, 0); int A_row_count = A_row_count_old; std::vector<int> psd_cone_length; ParsePositiveSemidefiniteConstraints(prog, upper_triangular, &A_triplets, &b, &A_row_count, &psd_cone_length); EXPECT_EQ(A_row_count, A_row_count_old + 3 * (3 + 1) / 2); EXPECT_EQ(psd_cone_length, std::vector<int>({3})); Eigen::SparseMatrix<double> A(A_row_count_old + 6, prog.num_vars()); A.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::MatrixXd A_expected(A_row_count_old + 6, prog.num_vars()); A_expected.setZero(); const std::vector<Eigen::MatrixXd> F = lmi_constraint.evaluator()->F(); const double sqrt2 = std::sqrt(2); if (upper_triangular) { // clang-format off A_expected.bottomRows<6>() << -F[1](0, 0), -F[2](0, 0), -F[3](0, 0), -sqrt2 * F[1](0, 1), -sqrt2 * F[2](1, 0), -sqrt2 * F[3](1, 0), -F[1](1, 1), -F[2](1, 1), -F[3](1, 1), -sqrt2*F[1](0, 2), -sqrt2*F[2](0, 2), -sqrt2*F[3](0, 2), -sqrt2 * F[1](1, 2), -sqrt2 * F[2](1, 2), -sqrt2 * F[3](1, 2), -F[1](2, 2), -F[2](2, 2), -F[3](2, 2); // clang-format on } else { // clang-format off A_expected.bottomRows<6>() << -F[1](0, 0), -F[2](0, 0), -F[3](0, 0), -sqrt2 * F[1](1, 0), -sqrt2 * F[2](1, 0), -sqrt2 * F[3](1, 0), -sqrt2 * F[1](2, 0), -sqrt2 * F[2](2, 0), -sqrt2 * F[3](2, 0), -F[1](1, 1), -F[2](1, 1), -F[3](1, 1), -sqrt2 * F[1](2, 1), -sqrt2 * F[2](2, 1), -sqrt2 * F[3](2, 1), -F[1](2, 2), -F[2](2, 2), -F[3](2, 2); // clang-format on } Eigen::VectorXd b_expected(A_row_count); if (upper_triangular) { b_expected << 0, 0, F[0](0, 0), sqrt2 * F[0](0, 1), F[0](1, 1), sqrt2 * F[0](0, 2), sqrt2 * F[0](1, 2), F[0](2, 2); } else { b_expected << 0, 0, F[0](0, 0), sqrt2 * F[0](1, 0), sqrt2 * F[0](2, 0), F[0](1, 1), sqrt2 * F[0](2, 1), F[0](2, 2); } EXPECT_TRUE(CompareMatrices(A.toDense(), A_expected, 1E-12)); EXPECT_EQ(b.size(), A_row_count); EXPECT_TRUE(CompareMatrices(Eigen::Map<Eigen::VectorXd>(b.data(), b.size()), b_expected, 1E-12)); }; check_lmi(true); check_lmi(false); } } // namespace internal } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/sparse_and_dense_matrix_test.cc
#include "drake/solvers/sparse_and_dense_matrix.h" #include <limits> #include <thread> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" namespace drake { namespace solvers { namespace internal { namespace { const double kInf = std::numeric_limits<double>::infinity(); void CheckGetDense(const SparseAndDenseMatrix* dut, const Eigen::Ref<const Eigen::MatrixXd>& dense_expected) { EXPECT_TRUE(CompareMatrices(dut->GetAsDense(), dense_expected)); } void CheckGetDenseThread( const SparseAndDenseMatrix& dut, const Eigen::Ref<const Eigen::MatrixXd>& dense_expected) { std::vector<std::thread> threads; for (int i = 0; i < 4; ++i) { // SparseAndDenseMatrix is not movable, hence I cannot pass dut but have to // pass its pointer threads.emplace_back(CheckGetDense, &dut, dense_expected); } for (auto& thread : threads) { thread.join(); } } GTEST_TEST(SparseAndDenseMatrix, constructor_sparse) { // Constructed from a sparse matrix. std::vector<Eigen::Triplet<double>> triplets; triplets.emplace_back(0, 1, 2.0); triplets.emplace_back(1, 0, 1.0); Eigen::SparseMatrix<double> sparse(3, 2); sparse.setFromTriplets(triplets.begin(), triplets.end()); const SparseAndDenseMatrix dut(sparse); EXPECT_EQ(dut.get_as_sparse().nonZeros(), sparse.nonZeros()); EXPECT_FALSE(dut.is_dense_constructed()); EXPECT_TRUE(CompareMatrices(dut.get_as_sparse().toDense(), sparse.toDense())); EXPECT_TRUE(CompareMatrices(dut.GetAsDense(), sparse.toDense())); EXPECT_TRUE(dut.is_dense_constructed()); CheckGetDenseThread(dut, sparse.toDense()); } GTEST_TEST(SparseAndDenseMatrix, constructor_dense) { Eigen::Matrix<double, 2, 3> dense; dense.setZero(); dense(0, 1) = 2; dense(1, 0) = 1; const SparseAndDenseMatrix dut(dense); EXPECT_EQ(dut.get_as_sparse().nonZeros(), 2); EXPECT_TRUE(dut.is_dense_constructed()); EXPECT_TRUE(CompareMatrices(dut.get_as_sparse().toDense(), dense)); EXPECT_TRUE(CompareMatrices(dut.GetAsDense(), dense)); CheckGetDenseThread(dut, dense); } GTEST_TEST(SparseAndDenseMatrix, assign) { Eigen::Matrix<double, 2, 3> dense; dense.setZero(); dense(0, 1) = 2; SparseAndDenseMatrix dut(dense); // Now assign from another dense matrix. Eigen::Matrix<double, 3, 3> dense_new; dense_new.setZero(); dense_new(1, 0) = 3; dut = dense_new; EXPECT_EQ(dut.get_as_sparse().nonZeros(), 1); EXPECT_TRUE(CompareMatrices(dut.get_as_sparse().toDense(), dense_new)); EXPECT_TRUE(CompareMatrices(dut.GetAsDense(), dense_new)); // Now assign from a sparse matrix. std::vector<Eigen::Triplet<double>> triplets; triplets.emplace_back(0, 1, 2.0); triplets.emplace_back(1, 0, 1.0); Eigen::SparseMatrix<double> sparse(3, 2); sparse.setFromTriplets(triplets.begin(), triplets.end()); dut = sparse; EXPECT_EQ(dut.get_as_sparse().nonZeros(), 2); EXPECT_TRUE(CompareMatrices(dut.get_as_sparse().toDense(), sparse.toDense())); EXPECT_TRUE(CompareMatrices(dut.GetAsDense(), sparse.toDense())); } GTEST_TEST(SparseAndDenseMatrix, IsFinite) { std::vector<Eigen::Triplet<double>> triplets; triplets.emplace_back(0, 1, 2.0); triplets.emplace_back(1, 0, 1.0); Eigen::SparseMatrix<double> sparse(3, 2); sparse.setFromTriplets(triplets.begin(), triplets.end()); SparseAndDenseMatrix dut(sparse); EXPECT_TRUE(dut.IsFinite()); sparse.coeffRef(0, 1) = kInf; dut = sparse; EXPECT_FALSE(dut.IsFinite()); sparse.coeffRef(0, 1) = NAN; dut = sparse; EXPECT_FALSE(dut.IsFinite()); } } // namespace } // namespace internal } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/solver_type_converter_test.cc
#include "drake/solvers/solver_type_converter.h" #include <gtest/gtest.h> #include "drake/common/drake_assert.h" namespace drake { namespace solvers { namespace { // We use this as a way to ensure we hit all SolverTypes. The switch statement // will complain if someone adds an enumeration value without an update here. std::optional<SolverType> successor(std::optional<SolverType> solver_type) { if (solver_type == std::nullopt) { return SolverType::kClp; } switch (*solver_type) { case SolverType::kClp: return SolverType::kCsdp; case SolverType::kCsdp: return SolverType::kEqualityConstrainedQP; case SolverType::kEqualityConstrainedQP: return SolverType::kGurobi; case SolverType::kGurobi: return SolverType::kIpopt; case SolverType::kIpopt: return SolverType::kLinearSystem; case SolverType::kLinearSystem: return SolverType::kMobyLCP; case SolverType::kMobyLCP: return SolverType::kMosek; case SolverType::kMosek: return SolverType::kNlopt; case SolverType::kNlopt: return SolverType::kOsqp; case SolverType::kOsqp: return SolverType::kScs; case SolverType::kScs: return SolverType::kSnopt; case SolverType::kSnopt: return SolverType::kUnrevisedLemke; case SolverType::kUnrevisedLemke: return std::nullopt; } DRAKE_UNREACHABLE(); } GTEST_TEST(SolverId, RoundTrip) { // Iterate over all known solver types. int iterations = 0; for (auto solver_type = successor(std::nullopt); solver_type != std::nullopt; solver_type = successor(solver_type)) { ++iterations; // Convert type -> id -> type and check for equality. const SolverId id = SolverTypeConverter::TypeToId(*solver_type); const std::optional<SolverType> round_trip = SolverTypeConverter::IdToType(id); ASSERT_TRUE(round_trip != std::nullopt); EXPECT_EQ(*round_trip, *solver_type); // Names of the well-known IDs shouldn't be empty. EXPECT_FALSE(id.name().empty()); } // This should track the number of SolverType values, if we add any. EXPECT_EQ(iterations, 13); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/get_program_type_test.cc
#include "drake/solvers/get_program_type.h" #include <gtest/gtest.h> namespace drake { namespace solvers { // We don't exhaustively test for "false positives" in these tests for // GetProgramType(). The argument for not doing so is based on the idea that // mathematical programs are uniquely characterized as a single type. It is // impossible for a program that would classify as one type to ever provide a // misclassificaiton as a different type. We rely on the sampling of // mathematical programs to provide sufficient coverage of meaningful // mathematical programs to render testing false positives unnecessary (as those // candidates for false positives test positively elsewhere). GTEST_TEST(GetProgramTypeTest, LP) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddLinearConstraint(x[0] + x[1] == 1); EXPECT_EQ(GetProgramType(prog), ProgramType::kLP); prog.AddLinearCost(x[0] + x[1]); EXPECT_EQ(GetProgramType(prog), ProgramType::kLP); prog.AddLinearConstraint(x[0] >= 0); EXPECT_EQ(GetProgramType(prog), ProgramType::kLP); prog.AddQuadraticCost(x[0] * x[0]); EXPECT_NE(GetProgramType(prog), ProgramType::kLP); } GTEST_TEST(GetProgramTypeTest, QP) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddQuadraticCost(x[0] * x[0] + x[1], true); EXPECT_EQ(GetProgramType(prog), ProgramType::kQP); prog.AddLinearConstraint(x[0] + x[1] == 1); EXPECT_EQ(GetProgramType(prog), ProgramType::kQP); prog.AddLinearCost(x[0] + x[1]); EXPECT_EQ(GetProgramType(prog), ProgramType::kQP); // Add a non-convex quadratic cost. auto nonconvex_cost = prog.AddQuadraticCost(-x[1] * x[1], false /* non-convex */); EXPECT_NE(GetProgramType(prog), ProgramType::kQP); prog.RemoveCost(nonconvex_cost); EXPECT_EQ(GetProgramType(prog), ProgramType::kQP); prog.AddLorentzConeConstraint( Vector3<symbolic::Expression>(x[0] + 2, 2 * x[0] + 1, x[0] + x[1])); EXPECT_NE(GetProgramType(prog), ProgramType::kQP); } GTEST_TEST(GetProgramTypeTest, SOCP) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<4>(); prog.AddLorentzConeConstraint(x.cast<symbolic::Expression>()); EXPECT_EQ(GetProgramType(prog), ProgramType::kSOCP); prog.AddRotatedLorentzConeConstraint(x.cast<symbolic::Expression>()); EXPECT_EQ(GetProgramType(prog), ProgramType::kSOCP); prog.AddLinearConstraint(x[0] >= 1); EXPECT_EQ(GetProgramType(prog), ProgramType::kSOCP); auto quadratic_cost = prog.AddQuadraticCost(x[0] * x[0]); EXPECT_NE(GetProgramType(prog), ProgramType::kSOCP); prog.RemoveCost(quadratic_cost); EXPECT_EQ(GetProgramType(prog), ProgramType::kSOCP); prog.AddPositiveSemidefiniteConstraint(x[0] * Eigen::Matrix2d::Identity() + x[1] * Eigen::Matrix2d::Ones()); EXPECT_NE(GetProgramType(prog), ProgramType::kSOCP); } GTEST_TEST(GetProgramTypeTest, SDP) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); prog.AddPositiveSemidefiniteConstraint(X); prog.AddLinearCost(X(0, 0) + X(1, 1)); EXPECT_EQ(GetProgramType(prog), ProgramType::kSDP); prog.AddLorentzConeConstraint( Vector3<symbolic::Expression>(X(0, 0) + 1, X(1, 1), X(1, 2) + 2)); EXPECT_EQ(GetProgramType(prog), ProgramType::kSDP); auto x = prog.NewContinuousVariables<2>(); prog.AddLinearMatrixInequalityConstraint( {Eigen::Matrix2d::Identity(), Eigen::Matrix2d::Ones(), 2 * Eigen::Matrix2d::Ones()}, x); EXPECT_EQ(GetProgramType(prog), ProgramType::kSDP); auto quadratic_cost = prog.AddQuadraticCost(x[0] * x[0]); EXPECT_NE(GetProgramType(prog), ProgramType::kSDP); } GTEST_TEST(GetProgramTypeTest, GP) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); Eigen::SparseMatrix<double> A(3, 3); A.setIdentity(); prog.AddExponentialConeConstraint(A, Eigen::Vector3d(0, 1, 2), x); EXPECT_EQ(GetProgramType(prog), ProgramType::kGP); // Adding a Lorentz cone constraint, now this program cannot be modelled as // GP, but a CGP. prog.AddLorentzConeConstraint(x.cast<symbolic::Expression>()); EXPECT_NE(GetProgramType(prog), ProgramType::kGP); EXPECT_EQ(GetProgramType(prog), ProgramType::kCGP); } GTEST_TEST(GetProgramTypeTest, NLP) { { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto quadratic_cost = prog.AddQuadraticCost(x(0) * x(0) - x(1) * x(1), false); EXPECT_EQ(GetProgramType(prog), ProgramType::kNLP); } { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddPolynomialCost(x(0) * x(0) * x(1) + 2 * x(1)); EXPECT_EQ(GetProgramType(prog), ProgramType::kNLP); } { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddConstraint( std::make_shared<QuadraticConstraint>(Eigen::Matrix2d::Identity(), Eigen::Vector2d(1, 0), 0, 1), x); EXPECT_EQ(GetProgramType(prog), ProgramType::kNLP); auto b = prog.NewBinaryVariables<2>(); EXPECT_NE(GetProgramType(prog), ProgramType::kNLP); } { // A problem with linear complementarity constraint and a cost. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddConstraint(std::make_shared<LinearComplementarityConstraint>( Eigen::Matrix2d::Identity(), Eigen::Vector2d(1, 1)), x); prog.AddLinearCost(x(0) + x(1)); EXPECT_EQ(GetProgramType(prog), ProgramType::kNLP); } { // A problem with linear complementarity constraint and a lorentz cone // constraint. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); prog.AddConstraint( std::make_shared<LinearComplementarityConstraint>( Eigen::Matrix3d::Identity(), Eigen::Vector3d(1, 1, 0)), x); prog.AddLorentzConeConstraint(x); EXPECT_EQ(GetProgramType(prog), ProgramType::kNLP); } } GTEST_TEST(GetProgramTypeTest, LCP) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddLinearComplementarityConstraint(Eigen::Matrix2d::Identity(), Eigen::Vector2d(1, 2), x); EXPECT_EQ(GetProgramType(prog), ProgramType::kLCP); // LCP doesn't accept linear constraint. prog.AddLinearConstraint(x[0] + x[1] >= 1); EXPECT_EQ(GetProgramType(prog), ProgramType::kNLP); } GTEST_TEST(GetProgramTypeTest, MILP) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto b = prog.NewBinaryVariables<2>(); prog.AddLinearConstraint(x[0] + x[1] + b[1] + b[0] == 3); prog.AddLinearCost(x[0] + x[1]); EXPECT_EQ(GetProgramType(prog), ProgramType::kMILP); prog.AddQuadraticCost(x[0] * x[0]); EXPECT_NE(GetProgramType(prog), ProgramType::kMILP); } GTEST_TEST(GetProgramTypeTest, MIQP) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto b = prog.NewBinaryVariables<2>(); prog.AddLinearConstraint(x[0] + x[1] + b[1] + b[0] == 3); prog.AddLinearCost(x[0] + x[1]); prog.AddQuadraticCost(x[0] * x[0], true); EXPECT_EQ(GetProgramType(prog), ProgramType::kMIQP); // Add a non-convex quadratic cost. prog.AddQuadraticCost(-x[1] * x[1], false /* non-convex */); EXPECT_NE(GetProgramType(prog), ProgramType::kMIQP); } GTEST_TEST(GetProgramTypeTest, MISOCP) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto b = prog.NewBinaryVariables<2>(); prog.AddLinearConstraint(x[0] + x[1] + b[1] + b[0] == 3); prog.AddLorentzConeConstraint(x.cast<symbolic::Expression>()); prog.AddLinearCost(x[0] + x[1]); EXPECT_EQ(GetProgramType(prog), ProgramType::kMISOCP); prog.AddPositiveSemidefiniteConstraint(x[0] * Eigen::Matrix2d::Identity() + b[0] * Eigen::Matrix2d::Ones()); EXPECT_NE(GetProgramType(prog), ProgramType::kMISOCP); } GTEST_TEST(GetProgramTypeTest, MISDP) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto b = prog.NewBinaryVariables<2>(); prog.AddLinearConstraint(x[0] + x[1] + b[1] + b[0] == 3); prog.AddLorentzConeConstraint(x.cast<symbolic::Expression>()); prog.AddLinearCost(x[0] + x[1]); auto X = prog.NewSymmetricContinuousVariables<3>(); prog.AddPositiveSemidefiniteConstraint(X); EXPECT_EQ(GetProgramType(prog), ProgramType::kMISDP); prog.AddQuadraticCost(x[0] * x[0], true); EXPECT_NE(GetProgramType(prog), ProgramType::kMISDP); } GTEST_TEST(GetProgramTypeTest, QuadraticCostConicConstraint) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<4>(); prog.AddLorentzConeConstraint(x.cast<symbolic::Expression>()); prog.AddRotatedLorentzConeConstraint(x.cast<symbolic::Expression>()); auto quadratic_cost = prog.AddQuadraticCost(x(0) * x(0) + x(3) * x(3), true); EXPECT_EQ(GetProgramType(prog), ProgramType::kQuadraticCostConicConstraint); prog.RemoveCost(quadratic_cost); EXPECT_NE(GetProgramType(prog), ProgramType::kQuadraticCostConicConstraint); } GTEST_TEST(GetProgramTypeTest, Unknown) { // Nonlinear constraint with binary variables. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); prog.AddConstraint(x[0] * x[0] * x[1] + 3 * x[1] * x[0] * x[2] == 1); auto b = prog.NewBinaryVariables<1>(); prog.AddLinearComplementarityConstraint(Eigen::Matrix3d::Identity(), Eigen::Vector3d::Ones(), x); EXPECT_EQ(GetProgramType(prog), ProgramType::kUnknown); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/sos_examples.h
#pragma once #include "drake/solvers/mathematical_program.h" #include "drake/solvers/mathematical_program_result.h" namespace drake { namespace solvers { /** * This is example 3.35 from Semidefinite Optimization and Convex Algebraic * Geometry by G. Blekherman, P. Parrilo and R. Thomas. Solve a semidefinite * programming problem to verify that the univariate quartic polynomial p(x) * = x⁴+4x³+6x²+4x+5 is sum-of-squares (sos). */ class UnivariateQuarticSos { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(UnivariateQuarticSos) UnivariateQuarticSos(); const MathematicalProgram& prog() const { return prog_; } void CheckResult(const MathematicalProgramResult& result, double tol) const; private: MathematicalProgram prog_; symbolic::Polynomial p_; MatrixXDecisionVariable gram_; VectorX<symbolic::Monomial> monomial_basis_; }; /** * This is example 3.38 from Semidefinite Optimization and Convex Algebraic * Geometry by G. Blekherman, P. Parrilo and R. Thomas. Solve a semidefinite * programming problem to verify that the bivariate quartic polynomial p(x, y) = * 2x⁴+5y⁴−2x²y²+2x³y+2x+2 is sum-of-squares (sos). */ class BivariateQuarticSos { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(BivariateQuarticSos) BivariateQuarticSos(); const MathematicalProgram& prog() const { return prog_; } void CheckResult(const MathematicalProgramResult& result, double tol) const; private: MathematicalProgram prog_; symbolic::Polynomial p_; MatrixXDecisionVariable gram_; VectorX<symbolic::Monomial> monomial_basis_; }; /** * This is example 3.50 from Semidefinite Optimization and Convex Algebraic * Geometry by G. Blekherman, P. Parrilo and R. Thomas. Solve a simple sos * program * max a + b * s.t x⁴ + ax + 2+b is sos * (a-b+1)x² + bx + 1 is sos */ class SimpleSos1 { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SimpleSos1) SimpleSos1(); const MathematicalProgram& prog() const { return prog_; } void CheckResult(const MathematicalProgramResult& result, double tol) const; private: MathematicalProgram prog_; symbolic::Variable a_; symbolic::Variable b_; symbolic::Variable x_; symbolic::Polynomial p1_; symbolic::Polynomial p2_; MatrixXDecisionVariable gram1_; MatrixXDecisionVariable gram2_; VectorX<symbolic::Monomial> monomial_basis1_; VectorX<symbolic::Monomial> monomial_basis2_; }; /** * Prove that the Motzkin polynomial m(x, y) = x⁴y² + x²y⁴ + 1 − 3x²y² is * always non-negative. * One ceritificate for the proof is the existence of a polynomial r(x, y) * satisfying r(x, y) being sos and r(x, y) > 0 for all x, y ≠ 0, such that * r(x, y) * m(x, y) is sos. * So we solve the following problem * find r(x, y) * s.t r(x, y) - x² − y² is sos * r(x, y) * m(x, y) is sos */ class MotzkinPolynomial { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MotzkinPolynomial) MotzkinPolynomial(); const MathematicalProgram& prog() const { return prog_; } void CheckResult(const MathematicalProgramResult& result, double tol) const; private: MathematicalProgram prog_; symbolic::Variable x_; symbolic::Variable y_; symbolic::Polynomial m_; symbolic::Polynomial r_; MatrixXDecisionVariable gram1_; MatrixXDecisionVariable gram2_; VectorX<symbolic::Monomial> monomial_basis1_; VectorX<symbolic::Monomial> monomial_basis2_; }; /** * Solve the following optimization problem for a univariate polynomial * max a + b + c * s.t p(x) = x⁴+ax³+bx²+c+1>=0 for all x >= 0 * p(1) = 1 * According to theorem 3.71 in Semidefinite Optimization and Convex Algebraic * Geometry by G. Blekherman, P. Parrilo and R. Thomas, this is equivalent to * the following SOS problem * max a + b + c * s.t p(x) = s(x) + x * t(x) * p(1) = 1 * s(x) is sos * t(x) is sos */ class UnivariateNonnegative1 { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(UnivariateNonnegative1) UnivariateNonnegative1(); const MathematicalProgram& prog() const { return prog_; } void CheckResult(const MathematicalProgramResult& result, double tol) const; private: MathematicalProgram prog_; symbolic::Variable a_; symbolic::Variable b_; symbolic::Variable c_; symbolic::Variable x_; symbolic::Polynomial p_; symbolic::Polynomial s_; symbolic::Polynomial t_; MatrixXDecisionVariable gram_s_; MatrixXDecisionVariable gram_t_; }; } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/linear_program_examples.h
#pragma once #include <memory> #include <optional> #include <ostream> #include <tuple> #include <vector> #include "drake/common/drake_copyable.h" #include "drake/solvers/test/optimization_examples.h" namespace drake { namespace solvers { namespace test { /// Test a simple linear programming problem with zero cost, i.e. a feasibility /// problem /// 0 <= x0 + 2x1 + 3x2 <= 10 /// -inf <= x1 - 2x2 <= 3 /// -1 <= 0x0+ 0x1 + 0x2 <= 0 /// x1 >= 1 class LinearFeasibilityProgram : public OptimizationProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearFeasibilityProgram) explicit LinearFeasibilityProgram(ConstraintForm constraint_form); ~LinearFeasibilityProgram() override = default; void CheckSolution(const MathematicalProgramResult& result) const override; private: VectorDecisionVariable<3> x_; }; /// Adapt from the linear programming example /// http://cvxopt.org/examples/tutorial/lp.html /// Solve the following linear program /// min 2x0 + x1 + 4 /// s.t -inf <= -x0 + x1 <= 1 /// 2 <= x0 + x1 <=inf /// -inf <= x0 - 2x1 <= 4 /// x1 >= 2 /// x0 >= 0 /// The optimal solution is x0 = 1, x1 = 2 class LinearProgram0 : public OptimizationProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearProgram0) LinearProgram0(CostForm cost_form, ConstraintForm constraint_form); ~LinearProgram0() override = default; void CheckSolution(const MathematicalProgramResult& result) const override; private: VectorDecisionVariable<2> x_; Eigen::Vector2d x_expected_; }; // Test a simple linear programming problem with only bounding box constraint // on x. // min x0 - 2*x1 + 3 // 0 <= x0 <= 2 // -1 <= x1 <= 4 // The optimal solution is (0, 4) class LinearProgram1 : public OptimizationProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearProgram1) LinearProgram1(CostForm cost_form, ConstraintForm constraint_form); ~LinearProgram1() override = default; void CheckSolution(const MathematicalProgramResult& result) const override; private: VectorDecisionVariable<2> x_; Eigen::Vector2d x_expected_; }; // Test a simple linear programming problem // Adapted from https://docs.mosek.com/10.1/capi/tutorial-lo-shared.html // min -3x0 - x1 - 5x2 - x3 // s.t 3x0 + x1 + 2x2 = 30 // 15 <= 2x0 + x1 + 3x2 + x3 <= inf // -inf<= 2x1 + 3x3 <= 25 // -inf <= x0 + 2x1 + x3 <= inf // -100 <= x0 + 2x2 <= 40 // 0 <= x0 <= inf // 0 <= x1 <= 10 // 0 <= x2 <= inf // 0 <= x3 <= inf // The optimal solution is at (0, 0, 15, 25/3) class LinearProgram2 : public OptimizationProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearProgram2) LinearProgram2(CostForm cost_form, ConstraintForm constraint_form); ~LinearProgram2() override = default; void CheckSolution(const MathematicalProgramResult& result) const override; private: VectorDecisionVariable<4> x_; Eigen::Vector4d x_expected_; }; // Test a simple linear programming problem // Adapt from http://people.brunel.ac.uk/~mastjjb/jeb/or/morelp.html // min 4x0 + 5x1 + 6x2 // s.t. // x0 + x1 >= 11 // x0 - x1 <= 5 // x2 - x0 - x1 = 0 // 7x0 >= 35 - 12x1 // x0 >= 0 x1 >= 0 x2 >= 0 // The optimal solution is at (8, 3, 11) class LinearProgram3 : public OptimizationProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearProgram3) LinearProgram3(CostForm cost_form, ConstraintForm constraint_form); ~LinearProgram3() override = default; void CheckSolution(const MathematicalProgramResult& result) const override; private: VectorDecisionVariable<3> x_; Eigen::Vector3d x_expected_; }; enum class LinearProblems { kLinearFeasibilityProgram = 0, kLinearProgram0 = 1, kLinearProgram1 = 2, kLinearProgram2 = 3, kLinearProgram3 = 4, }; std::ostream& operator<<(std::ostream& os, LinearProblems value); class LinearProgramTest : public ::testing::TestWithParam< std::tuple<CostForm, ConstraintForm, LinearProblems>> { public: LinearProgramTest(); OptimizationProgram* prob() const { return prob_.get(); } private: std::unique_ptr<OptimizationProgram> prob_; }; std::vector<LinearProblems> linear_problems(); /** * An infeasible linear program. * max x0 + x1 * s.t x0 + 2 * x1 <= 3; * 2 * x0 + x1 == 4 * x0 >= 0, x1 >= 2 */ class InfeasibleLinearProgramTest0 : public ::testing::Test { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(InfeasibleLinearProgramTest0) InfeasibleLinearProgramTest0(); ~InfeasibleLinearProgramTest0() override {} protected: std::unique_ptr<MathematicalProgram> prog_; }; /** * An unbounded linear program. * max x0 + x1 * s.t 2 * x0 + x1 >= 4 * x0 >= 0, x1 >= 2 */ class UnboundedLinearProgramTest0 : public ::testing::Test { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(UnboundedLinearProgramTest0) UnboundedLinearProgramTest0(); ~UnboundedLinearProgramTest0() override {} protected: std::unique_ptr<MathematicalProgram> prog_; Vector2<symbolic::Variable> x_; }; /** * An unbounded linear program. * min x0 + 2*x1 + 3*x2 + 2.5*x3 + 2 * s.t x0 + x1 - x2 + x3 <= 3 * 1 <= x0 + 2 * x1 - 2 * x2 + 4 * x3 <= 3 * 0 <= x0, x2 <= 1 */ class UnboundedLinearProgramTest1 : public ::testing::Test { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(UnboundedLinearProgramTest1) UnboundedLinearProgramTest1(); ~UnboundedLinearProgramTest1() override {} protected: std::unique_ptr<MathematicalProgram> prog_; }; /** When adding constraints and costs, we intentionally put duplicated variables in each constraint/cost binding, so as to test if Drake's solver wrapper can handle duplicated variables correctly. min x0 + 3 * x1 + 4 * x2 + 3 s.t x0 + 2 * x1 + x2 <= 3 x0 + 2 * x2 = 1 1 <= 2 * x0 + x1 <= 3 x0 + 2x1 + 3x2 >= 0 */ class DuplicatedVariableLinearProgramTest1 : public ::testing::Test { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DuplicatedVariableLinearProgramTest1) DuplicatedVariableLinearProgramTest1(); void CheckSolution( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options = std::nullopt, double tol = 1E-7) const; protected: std::unique_ptr<MathematicalProgram> prog_; Vector3<symbolic::Variable> x_; }; /** * Test getting dual solution for LP. * This LP has inequality constraints. */ void TestLPDualSolution1(const SolverInterface& solver, double tol = 1e-6); /** This LP has only bounding box constraints. */ void TestLPDualSolution2(const SolverInterface& solver, double tol = 1e-6); /** This LP has only bounding box constraints. The decision variable is * scaled.*/ void TestLPDualSolution2Scaled(const SolverInterface& solver, double tol = 1e-6); /** This LP has only bounding box constraints. */ void TestLPDualSolution3(const SolverInterface& solver, double tol = 1e-6); /** This LP has only linear equality constraints. */ void TestLPDualSolution4(const SolverInterface& solver, double tol = 1E-6); /** Test LP with BoundingBoxConstraint, with some lower bounds equal to the * upper bounds. */ void TestLPDualSolution5(const SolverInterface& solver, double tol = 1E-6); /** This test confirms that the solver can solve problems with poorly scaled * data. See github issue https://github.com/RobotLocomotion/drake/issues/15341 * for more discussion. Mathematically this program finds the point with the * smallest infinity norm to (0.99, 1.99). The point is within the convex hull * of four points (eps, eps), (1, 1), (eps, 2), (1, 2). */ void TestLPPoorScaling1( const SolverInterface& solver, bool expect_success = true, double tol = 1E-12, const std::optional<SolverOptions>& options = std::nullopt); /** This test confirms that the solver can solve problems with poorly scaled * data. See github issue https://github.com/RobotLocomotion/drake/issues/15341 * for more discussion. * The optimal solution isn't computed analytically, hence we take a loose * tolerance. */ void TestLPPoorScaling2( const SolverInterface& solver, bool expect_success = true, double tol = 1E-4, const std::optional<SolverOptions>& options = std::nullopt); } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/rotation_constraint_visualization.h
#pragma once #include <Eigen/Core> namespace drake { namespace solvers { /** * Draw a unit sphere * @param color The rgb color of the surface to be plotted. @default is [0, 0.5, * 0.5] */ void DrawSphere(const Eigen::RowVector3d& color = Eigen::RowVector3d(0, 0.5, 0.5)); /** * Draw the box bmin <= x <= bmax, where the inequality is elementwise. * @param bmin The innermost corner of the box * @param bmax The outermost corner of the box * @param color The rgb color of the surface to be plotted. * @default is [0.5, 0.2, 0.3] * @pre bmin >= 0 and bmax >= 0. The inequality is elementwise. */ void DrawBox(const Eigen::Vector3d& bmin, const Eigen::Vector3d& bmax, const Eigen::RowVector3d& color = Eigen::RowVector3d(0.5, 0.2, 0.3)); /** * Draw the boundary of the intersection region, between the box * bmin <= x <= bmax, and the unit sphere. * Currently we only accept the box in the first orthant. * @param bmin The innermost corner of the box. * @param bmax The outermost corner of the box. * @param color The rgb color of the boundary to be plotted. @default is red. */ void DrawBoxSphereIntersection( const Eigen::Vector3d& bmin, const Eigen::Vector3d& bmax, const Eigen::RowVector3d& color = Eigen::RowVector3d(1, 0, 0)); } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/sos_examples.cc
#include "drake/solvers/test/sos_examples.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { namespace solvers { namespace { void CheckSymmetricMatrixPSD(const Eigen::Ref<const Eigen::MatrixXd>& mat, double tol) { Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigen_solver; eigen_solver.compute(mat); EXPECT_TRUE((eigen_solver.eigenvalues().array() >= Eigen::ArrayXd::Constant(mat.rows(), -tol)) .all()); } } // namespace UnivariateQuarticSos::UnivariateQuarticSos() : prog_() { auto x = prog_.NewIndeterminates<1>()(0); p_ = symbolic::Monomial(x, 4) + 4 * symbolic::Monomial(x, 3) + 6 * symbolic::Monomial(x, 2) + 4 * symbolic::Monomial(x, 1) + 5; std::tie(gram_, monomial_basis_) = prog_.AddSosConstraint(p_); } void UnivariateQuarticSos::CheckResult(const MathematicalProgramResult& result, double tol) const { EXPECT_TRUE(result.is_success()); const Eigen::MatrixXd gram_val = result.GetSolution(gram_); EXPECT_TRUE(symbolic::test::PolynomialEqual( p_, monomial_basis_.dot(gram_val * monomial_basis_), tol)); CheckSymmetricMatrixPSD(gram_val, tol); } BivariateQuarticSos::BivariateQuarticSos() : prog_() { auto x = prog_.NewIndeterminates<1>()(0); auto y = prog_.NewIndeterminates<1>()(0); p_ = 2 * symbolic::Monomial(x, 4) + 5 * symbolic::Monomial(y, 4) - 2 * symbolic::Monomial(x, 2) * symbolic::Monomial(y, 2) + 2 * symbolic::Monomial(x, 3) * symbolic::Monomial(y, 1) + 2 * symbolic::Monomial(x, 1) + 2; std::tie(gram_, monomial_basis_) = prog_.AddSosConstraint(p_); } void BivariateQuarticSos::CheckResult(const MathematicalProgramResult& result, double tol) const { EXPECT_TRUE(result.is_success()); const Eigen::MatrixXd gram_val = result.GetSolution(gram_); EXPECT_TRUE(symbolic::test::PolynomialEqual( p_, monomial_basis_.dot(gram_val * monomial_basis_), tol)); CheckSymmetricMatrixPSD(gram_val, tol); } SimpleSos1::SimpleSos1() : prog_{} { a_ = prog_.NewContinuousVariables<1>("a")(0); b_ = prog_.NewContinuousVariables<1>("b")(0); x_ = prog_.NewIndeterminates<1>("x")(0); prog_.AddLinearCost(-a_ - b_); p1_ = symbolic::Monomial(x_, 4) + a_ * symbolic::Monomial(x_, 1) + 2 + b_; std::tie(gram1_, monomial_basis1_) = prog_.AddSosConstraint(p1_); p2_ = symbolic::Polynomial({{symbolic::Monomial(x_, 2), a_ - b_ + 1}, {symbolic::Monomial(x_, 1), 1}, {symbolic::Monomial(), 1}}); std::tie(gram2_, monomial_basis2_) = prog_.AddSosConstraint(p2_); } void SimpleSos1::CheckResult(const MathematicalProgramResult& result, double tol) const { EXPECT_TRUE(result.is_success()); const Eigen::MatrixXd gram1_val = result.GetSolution(gram1_); const Eigen::MatrixXd gram2_val = result.GetSolution(gram2_); EXPECT_TRUE(symbolic::test::PolynomialEqual( result.GetSolution(p1_), monomial_basis1_.dot(gram1_val * monomial_basis1_), tol)); EXPECT_TRUE(symbolic::test::PolynomialEqual( result.GetSolution(p2_), monomial_basis2_.dot(gram2_val * monomial_basis2_), tol)); CheckSymmetricMatrixPSD(gram1_val, tol); CheckSymmetricMatrixPSD(gram2_val, tol); } MotzkinPolynomial::MotzkinPolynomial() : prog_{} { x_ = prog_.NewIndeterminates<1>()(0); y_ = prog_.NewIndeterminates<1>()(0); m_ = symbolic::Polynomial({{symbolic::Monomial({{x_, 4}, {y_, 2}}), 1}, {symbolic::Monomial({{x_, 2}, {y_, 4}}), 1}, {symbolic::Monomial(), 1}, {symbolic::Monomial({{x_, 2}, {y_, 2}}), -3}}); r_ = prog_.NewFreePolynomial({x_, y_}, 2); std::tie(gram1_, monomial_basis1_) = prog_.AddSosConstraint( r_ - symbolic::Polynomial({{symbolic::Monomial(x_, 2), 1}, {symbolic::Monomial(y_, 2), 1}})); std::tie(gram2_, monomial_basis2_) = prog_.AddSosConstraint(m_ * r_); } void MotzkinPolynomial::CheckResult(const MathematicalProgramResult& result, double tol) const { EXPECT_TRUE(result.is_success()); const symbolic::Polynomial m_result = symbolic::Polynomial(result.GetSolution(m_.ToExpression()), {x_, y_}); const symbolic::Polynomial r_result = symbolic::Polynomial(result.GetSolution(r_.ToExpression()), {x_, y_}); const Eigen::MatrixXd gram1_val = result.GetSolution(gram1_); const Eigen::MatrixXd gram2_val = result.GetSolution(gram2_); EXPECT_TRUE(symbolic::test::PolynomialEqual( r_result - symbolic::Polynomial(x_ * x_ + y_ * y_, {x_, y_}), monomial_basis1_.dot(gram1_val * monomial_basis1_), tol)); EXPECT_TRUE(symbolic::test::PolynomialEqual( m_result * r_result, monomial_basis2_.dot(gram2_val * monomial_basis2_), tol)); CheckSymmetricMatrixPSD(gram1_val, tol); CheckSymmetricMatrixPSD(gram2_val, tol); } UnivariateNonnegative1::UnivariateNonnegative1() : prog_{} { a_ = prog_.NewContinuousVariables<1>()(0); b_ = prog_.NewContinuousVariables<1>()(0); c_ = prog_.NewContinuousVariables<1>()(0); x_ = prog_.NewIndeterminates<1>()(0); p_ = symbolic::Polynomial({{symbolic::Monomial(x_, 4), 1}, {symbolic::Monomial(x_, 3), a_}, {symbolic::Monomial(x_, 2), b_}, {symbolic::Monomial(x_, 1), c_}, {symbolic::Monomial(), 1}}); prog_.AddLinearEqualityConstraint(2 + a_ + b_ + c_ == 1); prog_.AddLinearCost(-a_ - b_ - c_); std::tie(s_, gram_s_) = prog_.NewSosPolynomial({x_}, 4); std::tie(t_, gram_t_) = prog_.NewSosPolynomial({x_}, 2); prog_.AddEqualityConstraintBetweenPolynomials(p_, s_ + x_ * t_); } void UnivariateNonnegative1::CheckResult( const MathematicalProgramResult& result, double tol) const { EXPECT_TRUE(result.is_success()); const symbolic::Polynomial p_result = symbolic::Polynomial(result.GetSolution(p_.ToExpression()), {x_}); const symbolic::Polynomial s_result = symbolic::Polynomial(result.GetSolution(s_.ToExpression()), {x_}); const symbolic::Polynomial t_result = symbolic::Polynomial(result.GetSolution(t_.ToExpression()), {x_}); EXPECT_TRUE( symbolic::test::PolynomialEqual(p_result, s_result + x_ * t_result, tol)); const double a_val = result.GetSolution(a_); const double b_val = result.GetSolution(b_); const double c_val = result.GetSolution(c_); EXPECT_NEAR(result.get_optimal_cost(), -a_val - b_val - c_val, tol); CheckSymmetricMatrixPSD(result.GetSolution(gram_s_), tol); CheckSymmetricMatrixPSD(result.GetSolution(gram_t_), tol); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/sdpa_free_format_test.cc
#include "drake/solvers/sdpa_free_format.h" #include <filesystem> #include <fstream> #include <limits> #include <utility> #include <gtest/gtest.h> #include "drake/common/temp_directory.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/solvers/csdp_solver_internal.h" #include "drake/solvers/test/csdp_test_examples.h" namespace drake { namespace solvers { const double kInf = std::numeric_limits<double>::infinity(); namespace internal { void CompareProgVarInSdpa(const SdpaFreeFormat& sdpa_free_format, int variable_index, double val_expected) { const double val = std::get<double>(sdpa_free_format.prog_var_in_sdpa()[variable_index]); EXPECT_EQ(val, val_expected); } void CompareProgVarInSdpa(const SdpaFreeFormat& sdpa_free_format, int variable_index, SdpaFreeFormat::FreeVariableIndex s_index_expected) { const SdpaFreeFormat::FreeVariableIndex s_index = std::get<SdpaFreeFormat::FreeVariableIndex>( sdpa_free_format.prog_var_in_sdpa()[variable_index]); EXPECT_EQ(s_index, s_index_expected); } void CompareProgVarInSdpa(const SdpaFreeFormat& sdpa_free_format, int variable_index, const DecisionVariableInSdpaX& val_expected) { const auto val = std::get<DecisionVariableInSdpaX>( sdpa_free_format.prog_var_in_sdpa()[variable_index]); EXPECT_EQ(val.coeff_sign, val_expected.coeff_sign); EXPECT_EQ(val.offset, val_expected.offset); EXPECT_EQ(val.entry_in_X.block_index, val_expected.entry_in_X.block_index); EXPECT_EQ(val.entry_in_X.row_index_in_block, val_expected.entry_in_X.row_index_in_block); EXPECT_EQ(val.entry_in_X.column_index_in_block, val_expected.entry_in_X.column_index_in_block); EXPECT_EQ(val.entry_in_X.X_start_row, val_expected.entry_in_X.X_start_row); } void CompareBlockInX(const BlockInX& block1, const BlockInX& block2) { EXPECT_EQ(block1.block_type, block2.block_type); EXPECT_EQ(block1.num_rows, block2.num_rows); } void CompareTriplets(const std::vector<Eigen::Triplet<double>>& triplets1, const std::vector<Eigen::Triplet<double>>& triplets2, int matrix_rows, int matrix_cols) { EXPECT_EQ(triplets1.size(), triplets2.size()); Eigen::SparseMatrix<double> mat1(matrix_rows, matrix_cols); mat1.setFromTriplets(triplets1.begin(), triplets1.end()); Eigen::SparseMatrix<double> mat2(matrix_rows, matrix_cols); mat2.setFromTriplets(triplets2.begin(), triplets2.end()); EXPECT_TRUE( CompareMatrices(Eigen::MatrixXd(mat1), Eigen::MatrixXd(mat2), 1E-12)); } TEST_F(SDPwithOverlappingVariables1, TestSdpaFreeFormatConstructor) { const SdpaFreeFormat dut(*prog_); ASSERT_EQ(dut.num_X_rows(), 6); ASSERT_EQ(dut.num_free_variables(), 0); ASSERT_EQ(dut.X_blocks().size(), 3); CompareBlockInX(dut.X_blocks()[0], BlockInX(BlockType::kMatrix, 2)); CompareBlockInX(dut.X_blocks()[1], BlockInX(BlockType::kMatrix, 2)); CompareBlockInX(dut.X_blocks()[2], BlockInX(BlockType::kDiagonal, 2)); ASSERT_EQ(dut.prog_var_in_sdpa().size(), 3); CompareProgVarInSdpa(dut, prog_->FindDecisionVariableIndex(x_(0)), DecisionVariableInSdpaX(Sign::kPositive, 0, 0, 0, 0, 0)); CompareProgVarInSdpa(dut, prog_->FindDecisionVariableIndex(x_(1)), DecisionVariableInSdpaX(Sign::kPositive, 0, 0, 0, 1, 0)); CompareProgVarInSdpa(dut, prog_->FindDecisionVariableIndex(x_(2)), DecisionVariableInSdpaX(Sign::kPositive, 0, 1, 0, 1, 2)); // Check A_triplets. ASSERT_EQ(dut.A_triplets().size(), 6); CompareTriplets( dut.A_triplets()[0], {Eigen::Triplet<double>(0, 0, 1.0), Eigen::Triplet<double>(1, 1, -1.0)}, dut.num_X_rows(), dut.num_X_rows()); CompareTriplets( dut.A_triplets()[1], {Eigen::Triplet<double>(0, 0, 1.0), Eigen::Triplet<double>(2, 2, -1.0)}, dut.num_X_rows(), dut.num_X_rows()); CompareTriplets( dut.A_triplets()[2], {Eigen::Triplet<double>(0, 0, 1.0), Eigen::Triplet<double>(3, 3, -1.0)}, dut.num_X_rows(), dut.num_X_rows()); // The constraint x0 >= 0.5, we add a slack variable y0 >= 0 with constraint // x0 - y0 = 0.5 CompareTriplets(dut.A_triplets()[3], {Eigen::Triplet<double>(0, 0, 1.), Eigen::Triplet(4, 4, -1.)}, dut.num_X_rows(), dut.num_X_rows()); // The constraint that x1 = 1 CompareTriplets( dut.A_triplets()[4], {Eigen::Triplet<double>(0, 1, 0.5), Eigen::Triplet<double>(1, 0, 0.5)}, dut.num_X_rows(), dut.num_X_rows()); // The constraint x2 <= 2. We add a slack variable y2 >= 0 with the constraint // x2 + y2 = 2 CompareTriplets( dut.A_triplets()[5], {Eigen::Triplet<double>(2, 3, 0.5), Eigen::Triplet<double>(3, 2, 0.5), Eigen::Triplet<double>(5, 5, 1)}, dut.num_X_rows(), dut.num_X_rows()); Vector6d g_expected; g_expected << 0, 0, 0, 0.5, 1, 2; EXPECT_TRUE(CompareMatrices(dut.g(), g_expected)); EXPECT_EQ(dut.B_triplets().size(), 0); // Now check the cost. CompareTriplets( dut.C_triplets(), {Eigen::Triplet<double>(0, 0, -2), Eigen::Triplet<double>(2, 3, -0.5), Eigen::Triplet<double>(3, 2, -0.5)}, dut.num_X_rows(), dut.num_X_rows()); EXPECT_EQ(dut.d_triplets().size(), 0); EXPECT_EQ(dut.constant_min_cost_term(), 0); } TEST_F(SDPwithOverlappingVariables2, TestSdpaFreeFormatConstructor) { const SdpaFreeFormat dut(*prog_); ASSERT_EQ(dut.num_X_rows(), 5); ASSERT_EQ(dut.num_free_variables(), 0); ASSERT_EQ(dut.X_blocks().size(), 2); CompareBlockInX(dut.X_blocks()[0], BlockInX(BlockType::kMatrix, 2)); CompareBlockInX(dut.X_blocks()[1], BlockInX(BlockType::kDiagonal, 3)); ASSERT_EQ(dut.prog_var_in_sdpa().size(), 2); CompareProgVarInSdpa(dut, prog_->FindDecisionVariableIndex(x_(0)), DecisionVariableInSdpaX(Sign::kPositive, 0, 0, 0, 0, 0)); CompareProgVarInSdpa(dut, prog_->FindDecisionVariableIndex(x_(1)), DecisionVariableInSdpaX(Sign::kPositive, 0, 0, 0, 1, 0)); // Check A_triplets. ASSERT_EQ(dut.A_triplets().size(), 4); CompareTriplets( dut.A_triplets()[0], {Eigen::Triplet<double>(0, 0, 1.0), Eigen::Triplet<double>(1, 1, -1.0)}, dut.num_X_rows(), dut.num_X_rows()); // The constraint 2 <= x0 <= 3, we add a slack variable y0 >= 0 with // constraint x0 - y0 = 2, and slack variable y1 >= 0 with constraint x0 + y1 // = 3 CompareTriplets( dut.A_triplets()[1], {Eigen::Triplet<double>(0, 0, 1.), Eigen::Triplet<double>(2, 2, -1.)}, dut.num_X_rows(), dut.num_X_rows()); CompareTriplets( dut.A_triplets()[2], {Eigen::Triplet<double>(0, 0, 1.), Eigen::Triplet<double>(3, 3, 1.)}, dut.num_X_rows(), dut.num_X_rows()); // The constraint that x1 >= 1 CompareTriplets( dut.A_triplets()[3], {Eigen::Triplet<double>(0, 1, 0.5), Eigen::Triplet<double>(1, 0, 0.5), Eigen::Triplet<double>(4, 4, -1)}, dut.num_X_rows(), dut.num_X_rows()); Eigen::Vector4d g_expected(0, 2, 3, 1); EXPECT_TRUE(CompareMatrices(dut.g(), g_expected)); EXPECT_EQ(dut.B_triplets().size(), 0); // Now check the cost. CompareTriplets( dut.C_triplets(), {Eigen::Triplet<double>(0, 0, -2), Eigen::Triplet<double>(0, 1, -0.5), Eigen::Triplet<double>(1, 0, -0.5)}, dut.num_X_rows(), dut.num_X_rows()); EXPECT_EQ(dut.d_triplets().size(), 0); EXPECT_EQ(dut.constant_min_cost_term(), 0); } TEST_F(CsdpDocExample, TestSdpaFreeFormatConstructor) { SdpaFreeFormat dut(*prog_); EXPECT_EQ(dut.num_X_rows(), 7); EXPECT_EQ(dut.num_free_variables(), 0); EXPECT_EQ(dut.X_blocks().size(), 3); CompareBlockInX(dut.X_blocks()[0], BlockInX(BlockType::kMatrix, 2)); CompareBlockInX(dut.X_blocks()[1], BlockInX(BlockType::kMatrix, 3)); CompareBlockInX(dut.X_blocks()[2], BlockInX(BlockType::kDiagonal, 2)); EXPECT_EQ(dut.prog_var_in_sdpa().size(), prog_->num_vars()); CompareProgVarInSdpa(dut, prog_->FindDecisionVariableIndex(X1_(0, 0)), DecisionVariableInSdpaX(Sign::kPositive, 0, 0, 0, 0, 0)); CompareProgVarInSdpa(dut, prog_->FindDecisionVariableIndex(X1_(1, 0)), DecisionVariableInSdpaX(Sign::kPositive, 0, 0, 0, 1, 0)); CompareProgVarInSdpa(dut, prog_->FindDecisionVariableIndex(X1_(1, 1)), DecisionVariableInSdpaX(Sign::kPositive, 0, 0, 1, 1, 0)); for (int j = 0; j < 3; ++j) { for (int i = 0; i <= j; ++i) { CompareProgVarInSdpa( dut, prog_->FindDecisionVariableIndex(X2_(i, j)), DecisionVariableInSdpaX(Sign::kPositive, 0, 1, i, j, 2)); } } for (int i = 0; i < 2; ++i) { CompareProgVarInSdpa( dut, prog_->FindDecisionVariableIndex(y_(i)), DecisionVariableInSdpaX(Sign::kPositive, 0, 2, i, i, 5)); } // Check the cost. CompareTriplets( dut.C_triplets(), {Eigen::Triplet<double>(0, 0, 2), Eigen::Triplet<double>(0, 1, 1), Eigen::Triplet<double>(1, 0, 1), Eigen::Triplet<double>(1, 1, 2), Eigen::Triplet<double>(2, 2, 3), Eigen::Triplet<double>(3, 3, 2), Eigen::Triplet<double>(2, 4, 1), Eigen::Triplet<double>(4, 2, 1), Eigen::Triplet<double>(4, 4, 3)}, dut.num_X_rows(), dut.num_X_rows()); EXPECT_EQ(dut.d_triplets().size(), 0); EXPECT_EQ(dut.constant_min_cost_term(), 0); // Check the constraints. EXPECT_EQ(dut.A_triplets().size(), 2); CompareTriplets( dut.A_triplets()[0], {Eigen::Triplet<double>(0, 0, 3), Eigen::Triplet<double>(0, 1, 1), Eigen::Triplet<double>(1, 0, 1), Eigen::Triplet<double>(1, 1, 3), Eigen::Triplet<double>(5, 5, 1)}, dut.num_X_rows(), dut.num_X_rows()); CompareTriplets( dut.A_triplets()[1], {Eigen::Triplet<double>(2, 2, 3), Eigen::Triplet<double>(3, 3, 4), Eigen::Triplet<double>(2, 4, 1), Eigen::Triplet<double>(4, 2, 1), Eigen::Triplet<double>(4, 4, 5), Eigen::Triplet<double>(6, 6, 1)}, dut.num_X_rows(), dut.num_X_rows()); EXPECT_EQ(dut.B_triplets().size(), 0); EXPECT_TRUE(CompareMatrices(dut.g(), Eigen::Vector2d(1, 2))); } TEST_F(LinearProgramBoundingBox1, TestSdpaFreeFormatConstructor) { // Test if we can correctly register decision variables with bounding box // constraints. SdpaFreeFormat dut(*prog_); EXPECT_EQ(dut.num_X_rows(), 7); EXPECT_EQ(dut.num_free_variables(), 1); EXPECT_EQ(dut.X_blocks().size(), 1); CompareBlockInX(dut.X_blocks()[0], BlockInX(BlockType::kDiagonal, 7)); EXPECT_EQ(dut.prog_var_in_sdpa().size(), prog_->num_vars()); CompareProgVarInSdpa(dut, 0, DecisionVariableInSdpaX(Sign::kPositive, 0, 0, 0, 0, 0)); CompareProgVarInSdpa(dut, 1, DecisionVariableInSdpaX(Sign::kPositive, 0, 0, 1, 1, 0)); CompareProgVarInSdpa( dut, 2, DecisionVariableInSdpaX(Sign::kPositive, -1, 0, 3, 3, 0)); CompareProgVarInSdpa( dut, 3, DecisionVariableInSdpaX(Sign::kNegative, 10, 0, 4, 4, 0)); CompareProgVarInSdpa( dut, 4, DecisionVariableInSdpaX(Sign::kPositive, -2, 0, 5, 5, 0)); CompareProgVarInSdpa(dut, 5, 0.0); CompareProgVarInSdpa(dut, 6, 1.0); CompareProgVarInSdpa(dut, 7, SdpaFreeFormat::FreeVariableIndex(0)); // Constraining 0 <= x(1) <= 5 Eigen::Vector2d g_expected; CompareTriplets( dut.A_triplets()[0], {Eigen::Triplet<double>(1, 1, 1), Eigen::Triplet<double>(2, 2, 1)}, dut.num_X_rows(), dut.num_X_rows()); g_expected(0) = 5; // Constraining -2 <= x(4) <= 5 CompareTriplets( dut.A_triplets()[1], {Eigen::Triplet<double>(5, 5, 1), Eigen::Triplet<double>(6, 6, 1)}, dut.num_X_rows(), dut.num_X_rows()); g_expected(1) = 7; EXPECT_EQ(dut.B_triplets().size(), 0); EXPECT_TRUE(CompareMatrices(dut.g(), g_expected)); // Check the cost max -x(0) + x(1) - 2 * x(2) + 3 * x(3) + x(4) + 1 CompareTriplets( dut.C_triplets(), {Eigen::Triplet<double>(0, 0, -1), Eigen::Triplet<double>(1, 1, 1), Eigen::Triplet<double>(3, 3, -2), Eigen::Triplet<double>(4, 4, -3), Eigen::Triplet<double>(5, 5, 1)}, dut.num_X_rows(), dut.num_X_rows()); EXPECT_EQ(dut.constant_min_cost_term(), -31); } TEST_F(CsdpLinearProgram2, TestSdpaFreeFormatConstructor) { // This tests adding linear constraint. const SdpaFreeFormat dut(*prog_); EXPECT_EQ(dut.num_X_rows(), 4); EXPECT_EQ(dut.num_free_variables(), 3); EXPECT_EQ(dut.prog_var_in_sdpa().size(), 3); for (int i = 0; i < 3; ++i) { CompareProgVarInSdpa(dut, i, SdpaFreeFormat::FreeVariableIndex(i)); } EXPECT_EQ(dut.X_blocks().size(), 1); CompareBlockInX(dut.X_blocks()[0], BlockInX(BlockType::kDiagonal, 4)); // Check the linear constraints. EXPECT_EQ(dut.A_triplets().size(), 6); std::vector<Eigen::Triplet<double>> B_triplets_expected; Vector6<double> g_expected; // 2 * x(0) + 3 * x(1) + x(2) = 1 B_triplets_expected.emplace_back(0, 0, 2); B_triplets_expected.emplace_back(0, 1, 3); B_triplets_expected.emplace_back(0, 2, 1); g_expected(0) = 1; // -2 * x(2) + x(0) <= -1 EXPECT_EQ(dut.A_triplets()[0].size(), 0); std::vector<Eigen::Triplet<double>> A1_triplets_expected; A1_triplets_expected.emplace_back(0, 0, 1); CompareTriplets(dut.A_triplets()[1], A1_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(1, 0, 1); B_triplets_expected.emplace_back(1, 2, -2); g_expected(1) = -1; // 2 * x(1) + x(0) >= -2 std::vector<Eigen::Triplet<double>> A2_triplets_expected; A2_triplets_expected.emplace_back(1, 1, -1); CompareTriplets(dut.A_triplets()[2], A2_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(2, 0, 1); B_triplets_expected.emplace_back(2, 1, 2); g_expected(2) = -2; // -2 <= -x(0) + 3 * x(2) <= 3 std::vector<Eigen::Triplet<double>> A3_triplets_expected; A3_triplets_expected.emplace_back(2, 2, -1); CompareTriplets(dut.A_triplets()[3], A3_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(3, 0, -1); B_triplets_expected.emplace_back(3, 2, 3); g_expected(3) = -2; std::vector<Eigen::Triplet<double>> A4_triplets_expected; A4_triplets_expected.emplace_back(3, 3, 1); CompareTriplets(dut.A_triplets()[4], A4_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(4, 0, -1); B_triplets_expected.emplace_back(4, 2, 3); g_expected(4) = 3; // x(0) + x(1) + 4 * x(2) = 3 EXPECT_EQ(dut.A_triplets()[5].size(), 0); B_triplets_expected.emplace_back(5, 0, 1); B_triplets_expected.emplace_back(5, 1, 1); B_triplets_expected.emplace_back(5, 2, 4); g_expected(5) = 3; CompareTriplets(dut.B_triplets(), B_triplets_expected, 6, dut.num_free_variables()); EXPECT_TRUE(CompareMatrices(dut.g(), g_expected)); // Check the cost min x(0) + 2 * x(1) + 3 * x(2) EXPECT_EQ(dut.C_triplets().size(), 0); std::vector<Eigen::Triplet<double>> d_triplets_expected; d_triplets_expected.emplace_back(0, 0, -1); d_triplets_expected.emplace_back(1, 0, -2); d_triplets_expected.emplace_back(2, 0, -3); CompareTriplets(dut.d_triplets(), d_triplets_expected, 3, 1); } TEST_F(CsdpLinearProgram3, TestSdpaFreeFormatConstructor) { const SdpaFreeFormat dut(*prog_); EXPECT_EQ(dut.num_X_rows(), 7); EXPECT_EQ(dut.num_free_variables(), 1); EXPECT_EQ(dut.prog_var_in_sdpa().size(), 3); CompareProgVarInSdpa( dut, 0, DecisionVariableInSdpaX(Sign::kPositive, -1, 0, 0, 0, 0)); CompareProgVarInSdpa(dut, 1, DecisionVariableInSdpaX(Sign::kNegative, 8, 0, 2, 2, 0)); CompareProgVarInSdpa(dut, 2, SdpaFreeFormat::FreeVariableIndex(0)); EXPECT_EQ(dut.X_blocks().size(), 2); CompareBlockInX(dut.X_blocks()[0], BlockInX(BlockType::kDiagonal, 3)); CompareBlockInX(dut.X_blocks()[1], BlockInX(BlockType::kDiagonal, 4)); // Check the cost 2x(0) + 3x(1) + 4x(2) + 3 CompareTriplets( dut.C_triplets(), {Eigen::Triplet<double>(0, 0, 2), Eigen::Triplet<double>(2, 2, -3)}, dut.num_X_rows(), dut.num_X_rows()); CompareTriplets(dut.d_triplets(), {Eigen::Triplet<double>(0, 0, 4)}, 1, 1); EXPECT_EQ(dut.constant_min_cost_term(), -25); EXPECT_EQ(dut.A_triplets().size(), 6); Vector6<double> g_expected; std::vector<Eigen::Triplet<double>> B_triplets_expected; // Check the constraint x(0) <= 10 CompareTriplets( dut.A_triplets()[0], {Eigen::Triplet<double>(0, 0, 1), Eigen::Triplet<double>(1, 1, 1)}, dut.num_X_rows(), dut.num_X_rows()); g_expected(0) = 11; // Check the constraint x(0) + 2x(1) + 3x(2) = 3 CompareTriplets( dut.A_triplets()[1], {Eigen::Triplet<double>(0, 0, 1), Eigen::Triplet<double>(2, 2, -2)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(1, 0, 3); g_expected(1) = -12; // Check the constraint 2x(0) - x(2)>= -1 CompareTriplets( dut.A_triplets()[2], {Eigen::Triplet<double>(0, 0, 2), Eigen::Triplet<double>(3, 3, -1)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(2, 0, -1); g_expected(2) = 1; // Check the constraint x(1) - 3x(2) <= 5 CompareTriplets( dut.A_triplets()[3], {Eigen::Triplet<double>(2, 2, -1), Eigen::Triplet<double>(4, 4, 1)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(3, 0, -3); g_expected(3) = -3; // Check the constraint -4 <= x(0) + x(2) <= 9 CompareTriplets( dut.A_triplets()[4], {Eigen::Triplet<double>(0, 0, 1), Eigen::Triplet<double>(5, 5, -1)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(4, 0, 1); g_expected(4) = -3; CompareTriplets( dut.A_triplets()[5], {Eigen::Triplet<double>(0, 0, 1), Eigen::Triplet<double>(6, 6, 1)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(5, 0, 1); g_expected(5) = 10; CompareTriplets(dut.B_triplets(), B_triplets_expected, dut.g().rows(), dut.num_free_variables()); EXPECT_TRUE(CompareMatrices(dut.g(), g_expected)); } TEST_F(TrivialSDP1, TestSdpaFreeFormatConstructor) { // Test SdpaFreeFormat constructor with both PSD constraint and linear // constraint. const SdpaFreeFormat dut(*prog_); EXPECT_EQ(dut.num_X_rows(), 4); EXPECT_EQ(dut.num_free_variables(), 0); EXPECT_EQ(dut.X_blocks().size(), 2); CompareBlockInX(dut.X_blocks()[0], BlockInX(BlockType::kMatrix, 3)); CompareBlockInX(dut.X_blocks()[1], BlockInX(BlockType::kDiagonal, 1)); for (int j = 0; j < 3; ++j) { for (int i = 0; i <= j; ++i) { CompareProgVarInSdpa( dut, prog_->FindDecisionVariableIndex(X1_(i, j)), DecisionVariableInSdpaX(Sign::kPositive, 0, 0, i, j, 0)); } } EXPECT_EQ(dut.A_triplets().size(), 2); Eigen::Vector2d g_expected(1, 0); // X1(0, 0) + X1(1, 1) + X1(2, 2) = 1 std::vector<Eigen::Triplet<double>> A0_triplets_expected; A0_triplets_expected.emplace_back(0, 0, 1); A0_triplets_expected.emplace_back(1, 1, 1); A0_triplets_expected.emplace_back(2, 2, 1); CompareTriplets(dut.A_triplets()[0], A0_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); // X1(0, 1) + X1(1, 2) - 2 * X1(0, 2) <= 0 std::vector<Eigen::Triplet<double>> A1_triplets_expected; A1_triplets_expected.emplace_back(0, 1, 0.5); A1_triplets_expected.emplace_back(1, 0, 0.5); A1_triplets_expected.emplace_back(1, 2, 0.5); A1_triplets_expected.emplace_back(2, 1, 0.5); A1_triplets_expected.emplace_back(0, 2, -1); A1_triplets_expected.emplace_back(2, 0, -1); A1_triplets_expected.emplace_back(3, 3, 1); CompareTriplets(dut.A_triplets()[1], A1_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); EXPECT_TRUE(CompareMatrices(dut.g(), g_expected)); EXPECT_EQ(dut.B_triplets().size(), 0); // Cost max X1(0, 1) + X1(1, 2) std::vector<Eigen::Triplet<double>> C_triplets_expected; C_triplets_expected.emplace_back(0, 1, 0.5); C_triplets_expected.emplace_back(1, 0, 0.5); C_triplets_expected.emplace_back(1, 2, 0.5); C_triplets_expected.emplace_back(2, 1, 0.5); CompareTriplets(dut.C_triplets(), C_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); EXPECT_EQ(dut.d_triplets().size(), 0); } TEST_F(TrivialSDP2, TestSdpaFreeFormatConstructor) { // Test constructor with linear matrix inequality constraint. const SdpaFreeFormat dut(*prog_); EXPECT_EQ(dut.num_X_rows(), 4); EXPECT_EQ(dut.num_free_variables(), 1); EXPECT_EQ(dut.X_blocks().size(), 2); CompareBlockInX(dut.X_blocks()[0], BlockInX(BlockType::kMatrix, 2)); CompareBlockInX(dut.X_blocks()[1], BlockInX(BlockType::kMatrix, 2)); for (int j = 0; j < 2; ++j) { for (int i = 0; i <= j; ++i) { CompareProgVarInSdpa( dut, prog_->FindDecisionVariableIndex(X1_(i, j)), DecisionVariableInSdpaX(Sign::kPositive, 0, 0, i, j, 0)); } } CompareProgVarInSdpa(dut, prog_->FindDecisionVariableIndex(y_), SdpaFreeFormat::FreeVariableIndex(0)); // Check linear constraint EXPECT_EQ(dut.A_triplets().size(), 4); std::vector<Eigen::Triplet<double>> B_triplets_expected; Eigen::Vector4d g_expected; // X1(0, 0) + 2 * X1(1, 1) + 3 * y = 1 std::vector<Eigen::Triplet<double>> A0_triplets_expected; A0_triplets_expected.emplace_back(0, 0, 1); A0_triplets_expected.emplace_back(1, 1, 2); CompareTriplets(dut.A_triplets()[0], A0_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(0, 0, 3); g_expected(0) = 1; // I + F1 * y + F2 * X1(0, 0) is psd. // where F1 = [1 2; 2 3], F2 = [2 0; 0 4] // 1 + y + 2 * X1(0, 0) = X_slack(0, 0) std::vector<Eigen::Triplet<double>> A1_triplets_expected; A1_triplets_expected.emplace_back(0, 0, 2); A1_triplets_expected.emplace_back(2, 2, -1); CompareTriplets(dut.A_triplets()[1], A1_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(1, 0, 1); g_expected(1) = -1; // 2*y = X_slack(0, 1) std::vector<Eigen::Triplet<double>> A2_triplets_expected; A2_triplets_expected.emplace_back(2, 3, -0.5); A2_triplets_expected.emplace_back(3, 2, -0.5); CompareTriplets(dut.A_triplets()[2], A2_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(2, 0, 2); g_expected(2) = 0; // 1 + 3*y + 4*X1_(0, 0) = X_slack(1, 1) std::vector<Eigen::Triplet<double>> A3_triplets_expected; A3_triplets_expected.emplace_back(0, 0, 4); A3_triplets_expected.emplace_back(3, 3, -1); CompareTriplets(dut.A_triplets()[3], A3_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(3, 0, 3); g_expected(3) = -1; CompareTriplets(dut.B_triplets(), B_triplets_expected, 4, 1); EXPECT_TRUE(CompareMatrices(dut.g(), g_expected)); // Check the cost max y EXPECT_EQ(dut.C_triplets().size(), 0); std::vector<Eigen::Triplet<double>> d_triplets_expected; d_triplets_expected.emplace_back(0, 0, 1); CompareTriplets(dut.d_triplets(), d_triplets_expected, 1, 1); } TEST_F(TrivialSOCP1, TestSdpaFreeFormatConstructor) { const SdpaFreeFormat dut(*prog_); EXPECT_EQ(dut.num_X_rows(), 5); EXPECT_EQ(dut.num_free_variables(), 1); EXPECT_EQ(dut.X_blocks().size(), 2); CompareBlockInX(dut.X_blocks()[0], BlockInX(BlockType::kDiagonal, 2)); CompareBlockInX(dut.X_blocks()[1], BlockInX(BlockType::kMatrix, 3)); CompareProgVarInSdpa(dut, 0, SdpaFreeFormat::FreeVariableIndex(0)); for (int i = 0; i < 2; ++i) { CompareProgVarInSdpa( dut, i + 1, DecisionVariableInSdpaX(Sign::kPositive, 0, 0, i, i, 0)); } // Check the cost max x(0). EXPECT_EQ(dut.C_triplets().size(), 0); EXPECT_TRUE(CompareMatrices(Eigen::VectorXd(dut.d()), Vector1d(1))); EXPECT_EQ(dut.A_triplets().size(), 7); std::vector<Eigen::Triplet<double>> B_triplets_expected; Eigen::Matrix<double, 7, 1> g_expected; // Check the first constraint x(0) + x(1) + x(2) = 10 std::vector<Eigen::Triplet<double>> A0_triplets_expected; A0_triplets_expected.emplace_back(0, 0, 1); A0_triplets_expected.emplace_back(1, 1, 1); CompareTriplets(dut.A_triplets()[0], A0_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(0, 0, 1); g_expected(0) = 10; // The equality constraints arising from the Lorentz cone. 2x(0) + 1 == // X_blocks()[1](i, i) for i = 0, 1, 2. std::vector<Eigen::Triplet<double>> A_diagonal_triplets_expected; for (int i = 0; i < 3; ++i) { if (!A_diagonal_triplets_expected.empty()) { A_diagonal_triplets_expected.pop_back(); } A_diagonal_triplets_expected.emplace_back(2 + i, 2 + i, -1); CompareTriplets(dut.A_triplets()[1 + i], A_diagonal_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(1 + i, 0, 2); g_expected(1 + i) = -1; } // The equality constraint arising from the Lorentz cone. 3x(1) + 2 = // X_blocks()[1](0, 1). std::vector<Eigen::Triplet<double>> A4_triplets_expected; A4_triplets_expected.emplace_back(0, 0, 3); A4_triplets_expected.emplace_back(2, 3, -0.5); A4_triplets_expected.emplace_back(3, 2, -0.5); CompareTriplets(dut.A_triplets()[4], A4_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); g_expected(4) = -2; // The equality constraint arising from the Lorentz cone. x(0) + x(2) + 3 = // X_blocks()[1](0, 2). std::vector<Eigen::Triplet<double>> A5_triplets_expected; A5_triplets_expected.emplace_back(1, 1, 1); A5_triplets_expected.emplace_back(2, 4, -0.5); A5_triplets_expected.emplace_back(4, 2, -0.5); CompareTriplets(dut.A_triplets()[5], A5_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(5, 0, 1); g_expected(5) = -3; // The equality constraint arising from the Lorentz cone X_blocks()[1](1, 2) = // 0. std::vector<Eigen::Triplet<double>> A6_triplets_expected; A6_triplets_expected.emplace_back(3, 4, 0.5); A6_triplets_expected.emplace_back(4, 3, 0.5); CompareTriplets(dut.A_triplets()[6], A6_triplets_expected, dut.num_X_rows(), dut.num_X_rows()); g_expected(6) = 0; CompareTriplets(dut.B_triplets(), B_triplets_expected, dut.g().rows(), dut.num_free_variables()); EXPECT_TRUE(CompareMatrices(dut.g(), g_expected)); } TEST_F(TrivialSOCP2, TestSdpaFreeFormatConstructor) { const SdpaFreeFormat dut(*prog_); EXPECT_EQ(dut.num_X_rows(), 3); EXPECT_EQ(dut.num_free_variables(), 2); EXPECT_EQ(dut.X_blocks().size(), 1); CompareBlockInX(dut.X_blocks()[0], BlockInX(BlockType::kMatrix, 3)); for (int i = 0; i < 2; ++i) { CompareProgVarInSdpa(dut, i, SdpaFreeFormat::FreeVariableIndex(i)); } // Check the cost. EXPECT_EQ(dut.C_triplets().size(), 0); CompareTriplets(dut.d_triplets(), {Eigen::Triplet<double>(1, 0, 1)}, 2, 1); EXPECT_EQ(dut.A_triplets().size(), 6); std::vector<Eigen::Triplet<double>> B_triplets_expected; Vector6<double> g_expected; // Check the linear equality constraint arising from Lorentz cone. X(i, i) = // x(0) + 2 for i = 0, 1, 2. for (int i = 0; i < 3; ++i) { CompareTriplets(dut.A_triplets()[i], {Eigen::Triplet<double>(i, i, -1)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(i, 0, 1); g_expected(i) = -2; } // Check the linear equality constraint arising from Lorentz cone, X(0, 1) = // x(0) + x(1) + 1. CompareTriplets( dut.A_triplets()[3], {Eigen::Triplet<double>(0, 1, -0.5), Eigen::Triplet<double>(1, 0, -0.5)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(3, 0, 1); B_triplets_expected.emplace_back(3, 1, 1); g_expected(3) = -1; // Check the linear equality constraint arising from Lorentz cone, X(0, 2) = // x(0) - x(1) + 1. CompareTriplets( dut.A_triplets()[4], {Eigen::Triplet<double>(0, 2, -0.5), Eigen::Triplet<double>(2, 0, -0.5)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(4, 0, 1); B_triplets_expected.emplace_back(4, 1, -1); g_expected(4) = -1; // Check the linear equality constraint arising from Lorentz cone, X(1, 2) = // 0. CompareTriplets( dut.A_triplets()[5], {Eigen::Triplet<double>(1, 2, 0.5), Eigen::Triplet<double>(2, 1, 0.5)}, dut.num_X_rows(), dut.num_X_rows()); g_expected(5) = 0; CompareTriplets(dut.B_triplets(), B_triplets_expected, dut.g().rows(), dut.num_free_variables()); EXPECT_TRUE(CompareMatrices(dut.g(), g_expected)); } TEST_F(TrivialSOCP3, TestSdpaFreeFormatConstructor) { const SdpaFreeFormat dut(*prog_); EXPECT_EQ(dut.num_X_rows(), 3); EXPECT_EQ(dut.num_free_variables(), 2); EXPECT_EQ(dut.X_blocks().size(), 1); CompareBlockInX(dut.X_blocks()[0], BlockInX(BlockType::kMatrix, 3)); for (int i = 0; i < 2; ++i) { CompareProgVarInSdpa(dut, i, SdpaFreeFormat::FreeVariableIndex(i)); } // Check the cost max -x(1). EXPECT_EQ(dut.C_triplets().size(), 0); CompareTriplets(dut.d_triplets(), {Eigen::Triplet<double>(1, 0, -1)}, 2, 1); EXPECT_EQ(dut.A_triplets().size(), 6); std::vector<Eigen::Triplet<double>> B_triplets_expected; Vector6<double> g_expected; // Check the equality constraint arising from rotated Lorentz cone // 2x(0) + 2 = X(0, 0). CompareTriplets(dut.A_triplets()[0], {Eigen::Triplet<double>(0, 0, -1)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(0, 0, 2); g_expected(0) = -2; // Check the equality constraint arising from rotated Lorentz cone // x(0) + 2 = X(0, 1). CompareTriplets( dut.A_triplets()[1], {Eigen::Triplet<double>(0, 1, -0.5), Eigen::Triplet<double>(1, 0, -0.5)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(1, 0, 1); g_expected(1) = -2; // Check the equality constraint arising from rotated Lorentz cone // 3x(0) + x(1) + 1 = X(0, 2). CompareTriplets( dut.A_triplets()[2], {Eigen::Triplet<double>(0, 2, -0.5), Eigen::Triplet<double>(2, 0, -0.5)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(2, 0, 3); B_triplets_expected.emplace_back(2, 1, 1); g_expected(2) = -1; // Check the equality constraint arising from rotated Lorentz cone // 3x(1) + 4 = X(1, 1) and 3x(1) + 4 = X(2, 2). for (int i = 0; i < 2; ++i) { CompareTriplets(dut.A_triplets()[3 + i], {Eigen::Triplet<double>(i + 1, i + 1, -1)}, dut.num_X_rows(), dut.num_X_rows()); B_triplets_expected.emplace_back(3 + i, 1, 3); g_expected(3 + i) = -4; } // Check the equality constraint arising from rotated Lorentz cone // X(1, 2) = 0. CompareTriplets( dut.A_triplets()[5], {Eigen::Triplet<double>(1, 2, 0.5), Eigen::Triplet<double>(2, 1, 0.5)}, dut.num_X_rows(), dut.num_X_rows()); g_expected(5) = 0; CompareTriplets(dut.B_triplets(), B_triplets_expected, dut.g().rows(), dut.num_X_rows()); EXPECT_TRUE(CompareMatrices(dut.g(), g_expected)); } void CheckRemoveFreeVariableByNullspaceApproach( const SdpaFreeFormat& dut, const Eigen::SparseMatrix<double>& C_hat, const std::vector<Eigen::SparseMatrix<double>>& A_hat, const Eigen::VectorXd& rhs_hat, const Eigen::VectorXd& y_hat, const Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>& QR_B, double tol) { EXPECT_EQ(y_hat.rows(), static_cast<int>(dut.A().size())); // Check Bᵀ * ŷ = d EXPECT_TRUE(CompareMatrices(Eigen::VectorXd(dut.B().transpose() * y_hat), Eigen::VectorXd(dut.d()), tol)); // Check Ĉ = C -∑ᵢ ŷᵢAᵢ Eigen::SparseMatrix<double> C_hat_expected = dut.C(); for (int i = 0; i < y_hat.rows(); ++i) { C_hat_expected -= y_hat(i) * dut.A()[i]; } EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(C_hat), Eigen::MatrixXd(C_hat_expected), tol)); // N is the null space of Bᵀ. Namely if we do a QR decomposition on B, then // N = Q₂. Eigen::SparseMatrix<double> Q; Q = QR_B.matrixQ(); const Eigen::SparseMatrix<double> N = Q.rightCols(dut.B().rows() - QR_B.rank()); EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(dut.B().transpose() * N), Eigen::MatrixXd::Zero(dut.B().cols(), N.cols()), tol)); // Check rhs_hat = Nᵀ * rhs EXPECT_TRUE( CompareMatrices(rhs_hat, Eigen::VectorXd(N.transpose() * dut.g()), tol)); // Check Âᵢ = ∑ⱼNⱼᵢAⱼ EXPECT_EQ(static_cast<int>(A_hat.size()), N.cols()); for (int i = 0; i < N.cols(); ++i) { Eigen::SparseMatrix<double> A_hat_expected(dut.num_X_rows(), dut.num_X_rows()); A_hat_expected.setZero(); for (int j = 0; j < static_cast<int>(dut.A().size()); ++j) { A_hat_expected += N.coeff(j, i) * dut.A()[j]; } EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(A_hat[i]), Eigen::MatrixXd(A_hat_expected), tol)); } } void TestRemoveFreeVariableByNullspaceApproach( const MathematicalProgram& prog) { const SdpaFreeFormat dut(prog); Eigen::SparseMatrix<double> C_hat; std::vector<Eigen::SparseMatrix<double>> A_hat; Eigen::VectorXd rhs_hat, y_hat; Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> QR_B; dut.RemoveFreeVariableByNullspaceApproach(&C_hat, &A_hat, &rhs_hat, &y_hat, &QR_B); CheckRemoveFreeVariableByNullspaceApproach(dut, C_hat, A_hat, rhs_hat, y_hat, QR_B, 1E-10); } TEST_F(LinearProgramBoundingBox1, RemoveFreeVariableByNullspaceApproach) { const SdpaFreeFormat dut(*prog_); Eigen::SparseMatrix<double> C_hat; std::vector<Eigen::SparseMatrix<double>> A_hat; Eigen::VectorXd rhs_hat, y_hat; Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> QR_B; dut.RemoveFreeVariableByNullspaceApproach(&C_hat, &A_hat, &rhs_hat, &y_hat, &QR_B); CheckRemoveFreeVariableByNullspaceApproach(dut, C_hat, A_hat, rhs_hat, y_hat, QR_B, 1E-10); // Now try to call CSDP to solve this problem. csdp::blockmatrix C_csdp; double* rhs_csdp{nullptr}; csdp::constraintmatrix* constraints_csdp{nullptr}; ConvertSparseMatrixFormatToCsdpProblemData(dut.X_blocks(), C_hat, A_hat, rhs_hat, &C_csdp, &rhs_csdp, &constraints_csdp); struct csdp::blockmatrix X_csdp, Z; double* y{nullptr}; csdp::cpp_initsoln(dut.num_X_rows(), rhs_hat.rows(), C_csdp, rhs_csdp, constraints_csdp, &X_csdp, &y, &Z); double pobj{0}; double dobj{0}; const int ret = csdp::cpp_easy_sdp( nullptr, dut.num_X_rows(), rhs_hat.rows(), C_csdp, rhs_csdp, constraints_csdp, -dut.constant_min_cost_term() + dut.g().dot(y_hat), &X_csdp, &y, &Z, &pobj, &dobj); EXPECT_EQ(ret, 0 /* 0 is for success */); Eigen::SparseMatrix<double> X_hat(dut.num_X_rows(), dut.num_X_rows()); ConvertCsdpBlockMatrixtoEigen(X_csdp, &X_hat); // Now compute the free variable values. Eigen::VectorXd AX(dut.A().size()); for (int i = 0; i < AX.rows(); ++i) { AX(i) = (dut.A()[i].cwiseProduct(X_hat)).sum(); } Eigen::VectorXd s_val; s_val = QR_B.solve(dut.g() - AX); const double tol = 1E-6; EXPECT_NEAR(pobj, 43, tol); EXPECT_EQ(X_csdp.nblocks, 1); EXPECT_EQ(X_csdp.blocks[1].blockcategory, csdp::blockcat::DIAG); EXPECT_EQ(X_csdp.blocks[1].blocksize, 7); std::vector<double> block_val({0, 5, 0, 0, 0, 7, 0}); for (int i = 0; i < 7; ++i) { EXPECT_NEAR(X_csdp.blocks[1].data.vec[i + 1], block_val[i], tol); } csdp::cpp_free_prob(dut.num_X_rows(), rhs_hat.rows(), C_csdp, rhs_csdp, constraints_csdp, X_csdp, y, Z); } TEST_F(CsdpLinearProgram2, RemoveFreeVariableByNullspaceApproach) { TestRemoveFreeVariableByNullspaceApproach(*prog_); } TEST_F(TrivialSDP2, RemoveFreeVariableByNullspaceApproach) { TestRemoveFreeVariableByNullspaceApproach(*prog_); } TEST_F(TrivialSOCP1, RemoveFreeVariableByNullspaceApproach) { TestRemoveFreeVariableByNullspaceApproach(*prog_); } void TestRemoveFreeVariableByTwoSlackVariablesApproach( const MathematicalProgram& prog) { const SdpaFreeFormat dut(prog); std::vector<internal::BlockInX> X_hat_blocks; std::vector<Eigen::SparseMatrix<double>> A_hat; Eigen::SparseMatrix<double> C_hat; dut.RemoveFreeVariableByTwoSlackVariablesApproach(&X_hat_blocks, &A_hat, &C_hat); EXPECT_EQ(X_hat_blocks.size(), dut.X_blocks().size() + 1); for (int i = 0; i < static_cast<int>(dut.X_blocks().size()); ++i) { EXPECT_EQ(X_hat_blocks[i].block_type, dut.X_blocks()[i].block_type); EXPECT_EQ(X_hat_blocks[i].num_rows, dut.X_blocks()[i].num_rows); } EXPECT_EQ(X_hat_blocks[X_hat_blocks.size() - 1].block_type, BlockType::kDiagonal); EXPECT_EQ(X_hat_blocks[X_hat_blocks.size() - 1].num_rows, dut.num_free_variables() * 2); EXPECT_EQ(A_hat.size(), dut.A().size()); const int num_X_hat_rows = dut.num_X_rows() + 2 * dut.num_free_variables(); for (int i = 0; i < static_cast<int>(A_hat.size()); ++i) { Eigen::MatrixXd A_hat_expected = Eigen::MatrixXd::Zero(num_X_hat_rows, num_X_hat_rows); A_hat_expected.block(0, 0, dut.A()[i].rows(), dut.A()[i].cols()) = dut.A()[i]; Eigen::VectorXd bi = dut.B().row(i).transpose(); A_hat_expected.block(dut.A()[i].rows(), dut.A()[i].cols(), dut.B().cols(), dut.B().cols()) = bi.asDiagonal(); A_hat_expected.bottomRightCorner(dut.num_free_variables(), dut.num_free_variables()) = (-bi).asDiagonal(); EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(A_hat[i]), A_hat_expected)); } Eigen::MatrixXd C_hat_expected = Eigen::MatrixXd::Zero(num_X_hat_rows, num_X_hat_rows); C_hat_expected.topLeftCorner(dut.num_X_rows(), dut.num_X_rows()) = dut.C(); C_hat_expected.block(dut.num_X_rows(), dut.num_X_rows(), dut.num_free_variables(), dut.num_free_variables()) = Eigen::VectorXd(dut.d()).asDiagonal(); C_hat_expected.bottomRightCorner(dut.num_free_variables(), dut.num_free_variables()) = Eigen::VectorXd(-dut.d()).asDiagonal(); EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(C_hat), C_hat_expected)); } TEST_F(LinearProgramBoundingBox1, RemoveFreeVariableByTwoSlackVariablesApproach) { TestRemoveFreeVariableByTwoSlackVariablesApproach(*prog_); } TEST_F(CsdpLinearProgram2, RemoveFreeVariableByTwoSlackVariablesApproach) { TestRemoveFreeVariableByTwoSlackVariablesApproach(*prog_); } TEST_F(TrivialSDP2, RemoveFreeVariableByTwoSlackVariablesApproach) { TestRemoveFreeVariableByTwoSlackVariablesApproach(*prog_); } TEST_F(TrivialSOCP1, RemoveFreeVariableByTwoSlackVariablesApproach) { TestRemoveFreeVariableByTwoSlackVariablesApproach(*prog_); } void TestRemoveFreeVariableByLorentzConeSlackApproach( const MathematicalProgram& prog) { const SdpaFreeFormat dut(prog); std::vector<internal::BlockInX> X_hat_blocks; std::vector<Eigen::SparseMatrix<double>> A_hat; Eigen::VectorXd rhs_hat; Eigen::SparseMatrix<double> C_hat; dut.RemoveFreeVariableByLorentzConeSlackApproach(&X_hat_blocks, &A_hat, &rhs_hat, &C_hat); EXPECT_EQ(X_hat_blocks.size(), dut.X_blocks().size() + 1); for (int i = 0; i < static_cast<int>(dut.X_blocks().size()); ++i) { EXPECT_EQ(X_hat_blocks[i].block_type, dut.X_blocks()[i].block_type); EXPECT_EQ(X_hat_blocks[i].num_rows, dut.X_blocks()[i].num_rows); } EXPECT_EQ(X_hat_blocks[X_hat_blocks.size() - 1].block_type, BlockType::kMatrix); EXPECT_EQ(X_hat_blocks[X_hat_blocks.size() - 1].num_rows, dut.num_free_variables() + 1); EXPECT_EQ(A_hat.size(), dut.A().size() + dut.num_free_variables() * (dut.num_free_variables() + 1) / 2); EXPECT_EQ(rhs_hat.rows(), A_hat.size()); Eigen::VectorXd rhs_hat_expected = Eigen::VectorXd::Zero(A_hat.size()); rhs_hat_expected.head(dut.A().size()) = dut.g(); EXPECT_TRUE(CompareMatrices(rhs_hat, rhs_hat_expected)); const int num_X_hat_rows = dut.num_X_rows() + dut.num_free_variables() + 1; for (int i = 0; i < static_cast<int>(dut.A().size()); ++i) { Eigen::MatrixXd A_hat_expected = Eigen::MatrixXd::Zero(num_X_hat_rows, num_X_hat_rows); A_hat_expected.block(0, 0, dut.A()[i].rows(), dut.A()[i].cols()) = dut.A()[i]; const Eigen::VectorXd bi = dut.B().row(i).transpose(); A_hat_expected.block(dut.A()[i].rows(), dut.A()[i].cols() + 1, 1, dut.B().cols()) = bi.transpose() / 2; A_hat_expected.block(dut.A()[i].rows() + 1, dut.A()[i].cols(), dut.B().cols(), 1) = bi / 2; EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(A_hat[i]), A_hat_expected)); } // Now check the newly added linear equality constraint. // Y(i, i) = Y(0, 0) and Y(i, j) = 0 for j > i >= 1 int A_hat_count = dut.A().size(); for (int i = 1; i < dut.num_free_variables() + 1; ++i) { Eigen::MatrixXd A_hat_expected = Eigen::MatrixXd::Zero(num_X_hat_rows, num_X_hat_rows); A_hat_expected(dut.num_X_rows() + i, dut.num_X_rows() + i) = 1; A_hat_expected(dut.num_X_rows(), dut.num_X_rows()) = -1; EXPECT_TRUE( CompareMatrices(Eigen::MatrixXd(A_hat[A_hat_count++]), A_hat_expected)); for (int j = i + 1; j < dut.num_free_variables() + 1; ++j) { A_hat_expected.setZero(); A_hat_expected(dut.num_X_rows() + i, dut.num_X_rows() + j) = 0.5; A_hat_expected(dut.num_X_rows() + j, dut.num_X_rows() + i) = 0.5; EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(A_hat[A_hat_count++]), A_hat_expected)); } } Eigen::MatrixXd C_hat_expected = Eigen::MatrixXd::Zero(num_X_hat_rows, num_X_hat_rows); C_hat_expected.topLeftCorner(dut.num_X_rows(), dut.num_X_rows()) = dut.C(); C_hat_expected.block(dut.num_X_rows(), dut.num_X_rows() + 1, 1, dut.num_free_variables()) = Eigen::VectorXd(dut.d()).transpose() / 2; C_hat_expected.block(dut.num_X_rows() + 1, dut.num_X_rows(), dut.num_free_variables(), 1) = Eigen::VectorXd(dut.d()) / 2; EXPECT_TRUE(CompareMatrices(Eigen::MatrixXd(C_hat), C_hat_expected)); } TEST_F(LinearProgramBoundingBox1, RemoveFreeVariableByLorentzConeSlackApproach) { TestRemoveFreeVariableByLorentzConeSlackApproach(*prog_); } TEST_F(CsdpLinearProgram2, RemoveFreeVariableByLorentzConeSlackApproach) { TestRemoveFreeVariableByLorentzConeSlackApproach(*prog_); } TEST_F(TrivialSDP2, RemoveFreeVariableByLorentzConeSlackApproach) { TestRemoveFreeVariableByLorentzConeSlackApproach(*prog_); } TEST_F(TrivialSOCP1, RemoveFreeVariableByLorentzConeSlackApproach) { TestRemoveFreeVariableByLorentzConeSlackApproach(*prog_); } GTEST_TEST(SdpaFreeFormatTest, EmptyConstraint) { // Tests a program that contains an empty constraint 0 == 0. // Construct SdpaFreeFormat with and without the empty constraint, they should // be the same. MathematicalProgram prog{}; const auto X = prog.NewSymmetricContinuousVariables<2>(); prog.AddPositiveSemidefiniteConstraint(X); const auto x = prog.NewContinuousVariables<1>(); prog.AddBoundingBoxConstraint(-1, 1, x); SdpaFreeFormat dut_no_empty_constraint(prog); prog.AddLinearEqualityConstraint(Vector1d(0), 0, x); SdpaFreeFormat dut_empty_constraint(prog); EXPECT_EQ(dut_empty_constraint.num_X_rows(), dut_no_empty_constraint.num_X_rows()); EXPECT_EQ(dut_empty_constraint.num_free_variables(), dut_no_empty_constraint.num_free_variables()); EXPECT_EQ(dut_empty_constraint.constant_min_cost_term(), dut_no_empty_constraint.constant_min_cost_term()); EXPECT_EQ(dut_empty_constraint.A().size(), dut_no_empty_constraint.A().size()); for (int i = 0; i < static_cast<int>(dut_empty_constraint.A().size()); ++i) { EXPECT_TRUE(CompareMatrices(dut_empty_constraint.A()[i].toDense(), dut_no_empty_constraint.A()[i].toDense())); } EXPECT_TRUE(CompareMatrices(dut_empty_constraint.C().toDense(), dut_no_empty_constraint.C().toDense())); EXPECT_TRUE(CompareMatrices(dut_empty_constraint.B().toDense(), dut_no_empty_constraint.B().toDense())); EXPECT_TRUE(CompareMatrices(dut_empty_constraint.d().toDense(), dut_no_empty_constraint.d().toDense())); // Now add an infeasible empty constraint, expect an exception. prog.AddLinearConstraint(Eigen::RowVector2d(0, 0), 1, kInf, Vector2<symbolic::Variable>(X(0, 0), X(1, 1))); DRAKE_EXPECT_THROWS_MESSAGE(SdpaFreeFormat(prog), ".* the problem is infeasible as it contains.*"); } } // namespace internal GTEST_TEST(SdpaFreeFormatTest, GenerateSDPA1) { // This is the sample program from http://plato.asu.edu/ftp/sdpa_format.txt MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto X = prog.NewSymmetricContinuousVariables<2>(); prog.AddBoundingBoxConstraint(0, kInf, x); prog.AddPositiveSemidefiniteConstraint(X); prog.AddLinearCost(-x(0) - 2 * x(1) - 3 * X(0, 0) - 4 * X(1, 1)); prog.AddLinearEqualityConstraint(x(0) + x(1), 10); prog.AddLinearEqualityConstraint( x(1) + 5 * X(0, 0) + 4 * X(0, 1) + 6 * X(1, 1), 20); const std::string file_name = temp_directory() + "/sdpa"; EXPECT_TRUE(GenerateSDPA(prog, file_name)); EXPECT_TRUE(std::filesystem::exists({file_name + ".dat-s"})); std::ifstream infile(file_name + ".dat-s"); ASSERT_TRUE(infile.is_open()); std::string line; std::getline(infile, line); EXPECT_EQ(line, "2"); std::getline(infile, line); EXPECT_EQ(line, "2"); std::getline(infile, line); EXPECT_EQ(line, "2 -2 "); std::getline(infile, line); EXPECT_EQ(line, "10.0 20.0"); std::getline(infile, line); EXPECT_EQ(line, "0 1 1 1 3.0"); std::getline(infile, line); EXPECT_EQ(line, "0 1 2 2 4.0"); std::getline(infile, line); EXPECT_EQ(line, "0 2 1 1 1.0"); std::getline(infile, line); EXPECT_EQ(line, "0 2 2 2 2.0"); std::getline(infile, line); EXPECT_EQ(line, "1 2 1 1 1.0"); std::getline(infile, line); EXPECT_EQ(line, "1 2 2 2 1.0"); std::getline(infile, line); EXPECT_EQ(line, "2 1 1 1 5.0"); std::getline(infile, line); EXPECT_EQ(line, "2 1 1 2 2.0"); std::getline(infile, line); EXPECT_EQ(line, "2 1 2 2 6.0"); std::getline(infile, line); EXPECT_EQ(line, "2 2 2 2 1.0"); EXPECT_FALSE(std::getline(infile, line)); infile.close(); } GTEST_TEST(SdpaFreeFormatTest, GenerateInvalidSDPA) { // Test the program that cannot be formulated in SDPA format. MathematicalProgram prog1; prog1.NewBinaryVariables<2>(); EXPECT_THROW(GenerateSDPA(prog1, "tmp"), std::invalid_argument); } GTEST_TEST(SdpaFreeFormatTest, GenerateSDPA_remove_free_variables_two_slack) { // Test GenerateSDPA with prog that has free variables. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto X = prog.NewSymmetricContinuousVariables<2>(); prog.AddPositiveSemidefiniteConstraint(X); prog.AddLinearEqualityConstraint(X(0, 0) + x(0) + x(1), 1); prog.AddLinearCost(X(0, 1) + 2 * x(1)); internal::SdpaFreeFormat dut(prog); EXPECT_GT(dut.num_free_variables(), 0); const std::string file_name = temp_directory() + "/sdpa_free1"; EXPECT_TRUE(GenerateSDPA(prog, file_name, RemoveFreeVariableMethod::kTwoSlackVariables)); EXPECT_TRUE(std::filesystem::exists({file_name + ".dat-s"})); std::ifstream infile(file_name + ".dat-s"); ASSERT_TRUE(infile.is_open()); std::string line; std::getline(infile, line); EXPECT_EQ(line, "1"); std::getline(infile, line); EXPECT_EQ(line, "2"); std::getline(infile, line); EXPECT_EQ(line, "2 -4 "); std::getline(infile, line); EXPECT_EQ(line, "1.0"); std::getline(infile, line); EXPECT_EQ(line, "0 1 1 2 -0.5"); std::getline(infile, line); EXPECT_EQ(line, "0 2 2 2 -2.0"); std::getline(infile, line); EXPECT_EQ(line, "0 2 4 4 2.0"); std::getline(infile, line); EXPECT_EQ(line, "1 1 1 1 1.0"); std::getline(infile, line); EXPECT_EQ(line, "1 2 1 1 1.0"); std::getline(infile, line); EXPECT_EQ(line, "1 2 2 2 1.0"); std::getline(infile, line); EXPECT_EQ(line, "1 2 3 3 -1.0"); std::getline(infile, line); EXPECT_EQ(line, "1 2 4 4 -1.0"); EXPECT_FALSE(std::getline(infile, line)); infile.close(); } GTEST_TEST(SdpaFreeFormatTest, GenerateSDPA_remove_free_variables_null_space) { // Test GenerateSDPA with prog that has free variables. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto X = prog.NewSymmetricContinuousVariables<2>(); prog.AddPositiveSemidefiniteConstraint(X); prog.AddLinearEqualityConstraint(X(0, 0) + x(0) + x(1), 1); internal::SdpaFreeFormat dut(prog); EXPECT_GT(dut.num_free_variables(), 0); const std::string file_name = temp_directory() + "/sdpa_free2"; EXPECT_TRUE( GenerateSDPA(prog, file_name, RemoveFreeVariableMethod::kNullspace)); EXPECT_TRUE(std::filesystem::exists({file_name + ".dat-s"})); std::ifstream infile(file_name + ".dat-s"); ASSERT_TRUE(infile.is_open()); std::string line; std::getline(infile, line); // The null space approach completely removes the constraint. EXPECT_EQ(line, "0"); std::getline(infile, line); EXPECT_EQ(line, "1"); std::getline(infile, line); EXPECT_EQ(line, "2 "); std::getline(infile, line); // The constraint is empty. EXPECT_EQ(line, ""); infile.close(); } GTEST_TEST(SdpaFreeFormatTest, GenerateSDPA_remove_free_variables_lorentz_slack) { // Test GenerateSDPA with prog that has free variables. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto X = prog.NewSymmetricContinuousVariables<2>(); prog.AddPositiveSemidefiniteConstraint(X); prog.AddLinearEqualityConstraint(X(0, 0) + x(0) + x(1), 1); prog.AddLinearCost(X(0, 1) + 2 * x(1)); internal::SdpaFreeFormat dut(prog); EXPECT_GT(dut.num_free_variables(), 0); const std::string file_name = temp_directory() + "/sdpa_free3"; EXPECT_TRUE(GenerateSDPA(prog, file_name, RemoveFreeVariableMethod::kLorentzConeSlack)); EXPECT_TRUE(std::filesystem::exists({file_name + ".dat-s"})); std::ifstream infile(file_name + ".dat-s"); ASSERT_TRUE(infile.is_open()); std::string line; std::getline(infile, line); // number of constraints. EXPECT_EQ(line, "4"); std::getline(infile, line); // nblocks EXPECT_EQ(line, "2"); std::getline(infile, line); // block sizes EXPECT_EQ(line, "2 3 "); std::getline(infile, line); // constraint rhs EXPECT_EQ(line, "1.0 0.0 0.0 0.0"); // Each non-zero entry in C std::getline(infile, line); EXPECT_EQ(line, "0 1 1 2 -0.5"); std::getline(infile, line); EXPECT_EQ(line, "0 2 1 3 -1.0"); // Each non-zero entry in Ai std::getline(infile, line); EXPECT_EQ(line, "1 1 1 1 1.0"); std::getline(infile, line); EXPECT_EQ(line, "1 2 1 2 0.5"); std::getline(infile, line); EXPECT_EQ(line, "1 2 1 3 0.5"); std::getline(infile, line); EXPECT_EQ(line, "2 2 1 1 -1.0"); std::getline(infile, line); EXPECT_EQ(line, "2 2 2 2 1.0"); std::getline(infile, line); EXPECT_EQ(line, "3 2 2 3 0.5"); std::getline(infile, line); EXPECT_EQ(line, "4 2 1 1 -1.0"); std::getline(infile, line); EXPECT_EQ(line, "4 2 3 3 1.0"); EXPECT_FALSE(std::getline(infile, line)); infile.close(); } GTEST_TEST(SdpaFreeFormatTest, EnumToString) { // We just spot-check one item to make sure the function exists. The // implementation is obvious enough that we don't need to cover every // single item. EXPECT_EQ(fmt::to_string(RemoveFreeVariableMethod::kTwoSlackVariables), "kTwoSlackVariables"); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/gurobi_solver_license_retention_test.py
import copy import os from pathlib import Path import subprocess import unittest class TestGurobiSolverLicenseRetention(unittest.TestCase): def _subprocess_license_use_count(self, license_file_content): """Sets GRB_LICENSE_FILE to a temp file with the given content, runs our test helper, and then returns the license pointer use_count. """ # Create a dummy license file. Note that the license filename is magic. # The License code in gurobi_solver.cc treats this filename specially. tmpdir = Path(os.environ["TEST_TMPDIR"]) license_file = tmpdir / "DRAKE_UNIT_TEST_NO_LICENSE.lic" with open(license_file, "w", encoding="utf-8") as f: f.write(license_file_content) # Override the built-in license file. env = copy.copy(os.environ) env["GRB_LICENSE_FILE"] = str(license_file) # Run the helper and return the pointer use_count. output = subprocess.check_output( ["solvers/gurobi_solver_license_retention_test_helper"]) return int(output) def test_local_license(self): """When the file named by GRB_LICENSE_FILE contains 'HOSTID', the license object is held in two places: the test helper main(), and a global variable within GurobiSolver::AcquireLicense. """ content = "HOSTID=foobar\n" self.assertEqual(self._subprocess_license_use_count(content), 2) def test_nonlocal_license(self): """When the file named by GRB_LICENSE_FILE doesn't contain 'HOSTID', the license object is only held by main(), not any global variable. """ content = "TOKENSERVER=foobar.invalid.\n" self.assertEqual(self._subprocess_license_use_count(content), 1)
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/diagonally_dominant_dual_cone_matrix_test.cc
#include <vector> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solve.h" namespace drake { namespace solvers { namespace { // Returns the first index of the extreme ray v for which vᵀXv < 0. If no such // index exists, returns -1 and X is in DD*. int TestIn2by2DiagonallyDominantDualCone(const Eigen::Matrix2d& X) { // These are the extreme rays of the diagonally dominant matrices of size 2 // (minus the extreme points with the same parity). Eigen::MatrixXd extreme_rays(2, 4); extreme_rays << Eigen::Matrix2d::Identity(2, 2), Eigen::Vector2d::Ones(), Eigen::Vector2d(1, -1); for (int c = 0; c < extreme_rays.cols(); ++c) { if (extreme_rays.col(c).transpose() * X * extreme_rays.col(c) < -1e-10) { return c; } } return -1; } // Returns the first index of the extreme ray v for which vᵀXv < 0. If no such // index exists, returns -1 and X is in DD*. int TestIn3by3DiagonallyDominantDualCone(const Eigen::Matrix3d& X) { // These are the extreme rays of the diagonally dominant matrices of size 2 // (minus the extreme points with the same parity). Eigen::MatrixXd extreme_rays(3, 9); extreme_rays << Eigen::Matrix3d::Identity(), Eigen::Vector3d(1, 1, 0), Eigen::Vector3d(1, -1, 0), Eigen::Vector3d(0, 1, 1), Eigen::Vector3d(0, 1, -1), Eigen::Vector3d(1, 0, 1), Eigen::Vector3d(1, 0, -1); for (int c = 0; c < extreme_rays.cols(); ++c) { if (extreme_rays.col(c).transpose() * X * extreme_rays.col(c) < -1e-10) { return c; } } return -1; } GTEST_TEST(DiagonallyDominantMatrixDualConeConstraint, FeasibilityVariableCheck2by2) { // Test that DD* matrices are feasible. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<2>(); auto dual_cone_constraint = prog.AddPositiveDiagonallyDominantDualConeMatrixConstraint(X); // The dual cone constraint should be a single linear constraint with n² // inequalities where n is the number of rows in X. EXPECT_EQ(dual_cone_constraint.evaluator()->get_sparse_A().rows(), X.rows() * X.rows()); // There are n rows with one non-zero entry in the row, and 2 * (n choose 2) // rows with 4 non-zero entries in the row. This requires 4*n*n-3*n non-zero // entries. EXPECT_EQ(dual_cone_constraint.evaluator()->get_sparse_A().nonZeros(), 4 * X.rows() * X.rows() - 3 * X.rows()); // Ensure that a sparse constraint is constructed. EXPECT_FALSE(dual_cone_constraint.evaluator()->is_dense_A_constructed()); auto X_constraint = prog.AddBoundingBoxConstraint( Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(), VectorDecisionVariable<3>(X(0, 0), X(0, 1), X(1, 1))); auto set_X_value = [&X_constraint](const Eigen::Vector3d& x_upper_triangle) { X_constraint.evaluator()->UpdateLowerBound(x_upper_triangle); X_constraint.evaluator()->UpdateUpperBound(x_upper_triangle); Eigen::Matrix2d ret; ret << x_upper_triangle(0), x_upper_triangle(1), x_upper_triangle(1), x_upper_triangle(2); return ret; }; // [1, 0.9; 0.9 2] is in DD* and DD. set_X_value(Eigen::Vector3d(1, 0.9, 2)); MathematicalProgramResult result = Solve(prog); EXPECT_TRUE(result.is_success()); EXPECT_EQ(TestIn2by2DiagonallyDominantDualCone(result.GetSolution(X)), -1); // [1, -1.2; -1.2 2] is in DD* but not DD. set_X_value(Eigen::Vector3d(1, -1.2, 2)); result = Solve(prog); EXPECT_TRUE(result.is_success()); EXPECT_EQ(TestIn2by2DiagonallyDominantDualCone(result.GetSolution(X)), -1); // X_num = [2, -4; -4, 3] is not in DD*. The matrix Y = [1, 0.75; 0.75, 0.9] // is in DD, but 〈 X, Y 〉< 0 const Eigen::Matrix2d X_bad = set_X_value(Eigen::Vector3d(2, -4, 3)); result = Solve(prog); EXPECT_FALSE(result.is_success()); EXPECT_GE(TestIn2by2DiagonallyDominantDualCone(X_bad), 0); } GTEST_TEST(DiagonallyDominantMatrixDualConeConstraint, FeasibilityExpressionCheck2by2) { // Test that DD* matrices are feasible. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<2>(); auto Y = prog.NewSymmetricContinuousVariables<2>(); MatrixX<symbolic::Expression> Z(2, 2); Z = 2. * X + 3. * Y; auto GetZResult = [&Z](const MathematicalProgramResult& result) -> Eigen::MatrixXd { return result.GetSolution(Z).unaryExpr([](const symbolic::Expression& x) { return x.Evaluate(); }); }; auto dual_cone_constraint = prog.AddPositiveDiagonallyDominantDualConeMatrixConstraint(Z); // The dual cone constraint should be a single linear constraint with n² // inequalities where n is the number of rows in Z. EXPECT_EQ(dual_cone_constraint.evaluator()->get_sparse_A().rows(), Z.rows() * Z.rows()); // Ensure that a sparse constraint is constructed. EXPECT_FALSE(dual_cone_constraint.evaluator()->is_dense_A_constructed()); VectorX<symbolic::Expression> z_upper(3); z_upper << Z(0, 0), Z(0, 1), Z(1, 1); auto Z_constraint = prog.AddLinearEqualityConstraint(z_upper, Eigen::Vector3d::Zero()); auto set_Z_value = [&Z_constraint](const Eigen::Vector3d& z_upper_triangle) { Z_constraint.evaluator()->UpdateLowerBound(z_upper_triangle); Z_constraint.evaluator()->UpdateUpperBound(z_upper_triangle); Eigen::Matrix2d ret; ret << z_upper_triangle(0), z_upper_triangle(1), z_upper_triangle(1), z_upper_triangle(2); return ret; }; // [1, 0.9; 0.9 2] is in DD* and DD. set_Z_value(Eigen::Vector3d(1, 0.9, 2)); MathematicalProgramResult result = Solve(prog); EXPECT_TRUE(result.is_success()); EXPECT_EQ(TestIn2by2DiagonallyDominantDualCone(GetZResult(result)), -1); // [1, -1.2; -1.2 2] is in DD* but not DD. set_Z_value(Eigen::Vector3d(1, -1.2, 2)); result = Solve(prog); EXPECT_TRUE(result.is_success()); EXPECT_EQ(TestIn2by2DiagonallyDominantDualCone(GetZResult(result)), -1); // Z_num = [2, -4; -4, 3] is not in DD*. The matrix Y = [1, 0.75; 0.75, 0.9] // is in DD, but 〈 X, Y 〉< 0 const Eigen::Matrix2d Z_bad = set_Z_value(Eigen::Vector3d(2, -4, 3)); result = Solve(prog); EXPECT_FALSE(result.is_success()); EXPECT_GE(TestIn2by2DiagonallyDominantDualCone(Z_bad), 0); } GTEST_TEST(DiagonallyDominantMatrixDualConeConstraint, ThreeByThreeVerticesVariable) { // For a matrix to be in DD*, we have to have that Xₖₖ + Xⱼⱼ ≥ 2|Xₖⱼ+ Xⱼₖ| // I can manually compute the vertices of the polytope of (a, b, c) // to make // [1 a+b b+c] // A = [a+b 2 a+c] // [b+c a+c 3] // be in DD*. These vertices are // ±(0.5, 1, 3), ±(1,0.5,1.5), ±(1.5,-3,1), ±(1.5, -3, 0.5) // By optimizing the LP // min nᵀ* (a, b, c) // s.t A is in DD* // with different vector n, we can recover the vertices of the polytope as // the optimal solution to this LP. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); auto a = prog.NewContinuousVariables<1>("a")(0); auto b = prog.NewContinuousVariables<1>("b")(0); auto c = prog.NewContinuousVariables<1>("c")(0); prog.AddLinearEqualityConstraint(X(0, 1) - (a + b), 0); prog.AddLinearEqualityConstraint(X(0, 2) - (b + c), 0); prog.AddLinearEqualityConstraint(X(1, 2) - (a + c), 0); prog.AddBoundingBoxConstraint(Eigen::Vector3d(1, 2, 3), Eigen::Vector3d(1, 2, 3), X.diagonal()); auto dual_cone_constraint = prog.AddPositiveDiagonallyDominantDualConeMatrixConstraint(X); // The dual cone constraint should be a single linear constraint with n² // inequalities where n is the number of rows in X. EXPECT_EQ(dual_cone_constraint.evaluator()->get_sparse_A().rows(), X.rows() * X.rows()); // There are n rows with one non-zero entry in the row, and 2 * (n choose 2) // rows with 4 non-zero entries in the row. This requires 4*n*n-3*n non-zero // entries. EXPECT_EQ(dual_cone_constraint.evaluator()->get_sparse_A().nonZeros(), 4 * X.rows() * X.rows() - 3 * X.rows()); // Ensure that a sparse constraint is constructed. EXPECT_FALSE(dual_cone_constraint.evaluator()->is_dense_A_constructed()); auto cost = prog.AddLinearCost(Eigen::Vector3d::Zero(), 0, VectorDecisionVariable<3>(a, b, c)); auto solve_and_check = [&prog, &X, &a, &b, &c]( const Eigen::Vector3d& sol_expected, double tol) { const auto result = Solve(prog); EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.GetSolution(VectorDecisionVariable<3>(a, b, c)), sol_expected, tol)); // The matrix should be positive in DD*. const Eigen::Matrix3d X_sol = result.GetSolution(X); EXPECT_EQ(TestIn3by3DiagonallyDominantDualCone(X_sol), -1); }; const double tol{1E-6}; // The costs are chosen to make the optimal solution visit each vertex. cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(1, 1, -0.5)); solve_and_check(Eigen::Vector3d(-0.5, -1, 3), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0.33, 0.33, 1.33)); solve_and_check(Eigen::Vector3d(0.5, 1, -3), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(-0.53, -0.58, -0.45)); solve_and_check(Eigen::Vector3d(1, 0.5, 1.5), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0.82, 0.82, 0.82)); solve_and_check(Eigen::Vector3d(-1, -0.5, -1.5), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0.44, 1.27, 0.44)); solve_and_check(Eigen::Vector3d(1.5, -3, 1), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0.87, -0.58, 0.95)); solve_and_check(Eigen::Vector3d(-1.5, 3, -1), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(-0.53, 0.86, 1.0)); solve_and_check(Eigen::Vector3d(3, -1.5, -0.5), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(1.29, 0.40, 0.40)); solve_and_check(Eigen::Vector3d(-3, 1.5, 0.5), tol); } GTEST_TEST(DiagonallyDominantMatrixDualConeConstraint, ThreeByThreeVerticesExpression) { // For a matrix to be in DD*, we have to have that Xₖₖ + Xⱼⱼ ≥ 2|Xₖⱼ+ Xⱼₖ| // I can manually compute the vertices of the polytope of (a, b, c) // to make // [1 a+b b+c] // A = [a+b 2 a+c] // [b+c a+c 3] // be in DD*. These vertices are // ±(0.5, 1, 3), ±(1,0.5,1.5), ±(1.5,-3,1), ±(1.5, -3, 0.5) // By optimizing the LP // min nᵀ* (a, b, c) // s.t A is in DD* // with different vector n, we can recover the vertices of the polytope as // the optimal solution to this LP. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); auto Y = prog.NewSymmetricContinuousVariables<3>(); MatrixX<symbolic::Expression> Z(3, 3); Z = 2. * X + 3. * Y; auto GetZResult = [&Z](const MathematicalProgramResult& result) -> Eigen::MatrixXd { return result.GetSolution(Z).unaryExpr([](const symbolic::Expression& x) { return x.Evaluate(); }); }; auto a = prog.NewContinuousVariables<1>("a")(0); auto b = prog.NewContinuousVariables<1>("b")(0); auto c = prog.NewContinuousVariables<1>("c")(0); prog.AddLinearEqualityConstraint(Z(0, 1) - (a + b), 0); prog.AddLinearEqualityConstraint(Z(0, 2) - (b + c), 0); prog.AddLinearEqualityConstraint(Z(1, 2) - (a + c), 0); prog.AddLinearEqualityConstraint(Z.diagonal(), Eigen::Vector3d(1, 2, 3)); auto dual_cone_constraint = prog.AddPositiveDiagonallyDominantDualConeMatrixConstraint(Z); // The dual cone constraint should be a single linear constraint with n² // inequalities where n is the number of rows in X. EXPECT_EQ(dual_cone_constraint.evaluator()->get_sparse_A().rows(), Z.rows() * Z.rows()); // Ensure that a sparse constraint is constructed. EXPECT_FALSE(dual_cone_constraint.evaluator()->is_dense_A_constructed()); auto cost = prog.AddLinearCost(Eigen::Vector3d::Zero(), 0, VectorDecisionVariable<3>(a, b, c)); auto solve_and_check = [&prog, &GetZResult, &a, &b, &c]( const Eigen::Vector3d& sol_expected, double tol) { const auto result = Solve(prog); EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.GetSolution(VectorDecisionVariable<3>(a, b, c)), sol_expected, tol)); // The matrix should be positive in DD*. const Eigen::Matrix3d Z_sol = GetZResult(result); EXPECT_EQ(TestIn3by3DiagonallyDominantDualCone(Z_sol), -1); }; const double tol{1E-6}; // The costs are chosen to make the optimal solution visit each vertex. cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(1, 1, -0.5)); solve_and_check(Eigen::Vector3d(-0.5, -1, 3), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0.33, 0.33, 1.33)); solve_and_check(Eigen::Vector3d(0.5, 1, -3), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(-0.53, -0.58, -0.45)); solve_and_check(Eigen::Vector3d(1, 0.5, 1.5), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0.82, 0.82, 0.82)); solve_and_check(Eigen::Vector3d(-1, -0.5, -1.5), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0.44, 1.27, 0.44)); solve_and_check(Eigen::Vector3d(1.5, -3, 1), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0.87, -0.58, 0.95)); solve_and_check(Eigen::Vector3d(-1.5, 3, -1), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(-0.53, 0.86, 1.0)); solve_and_check(Eigen::Vector3d(3, -1.5, -0.5), tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(1.29, 0.40, 0.40)); solve_and_check(Eigen::Vector3d(-3, 1.5, 0.5), tol); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/binding_test.cc
#include "drake/solvers/binding.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/symbolic_test_util.h" #include "drake/common/text_logging.h" #include "drake/solvers/constraint.h" #include "drake/solvers/cost.h" namespace drake { namespace solvers { namespace test { using drake::symbolic::test::VarEqual; class TestBinding : public ::testing::Test { public: TestBinding() {} protected: const symbolic::Variable x1_{"x1"}; const symbolic::Variable x2_{"x2"}; const symbolic::Variable x3_{"x3"}; }; TEST_F(TestBinding, TestConstraintConstruction) { auto bb_con1 = std::make_shared<BoundingBoxConstraint>( Eigen::Vector3d::Zero(), Eigen::Vector3d::Ones()); // Checks if the bound variables are stored in the right order. Binding<BoundingBoxConstraint> binding1( bb_con1, {VectorDecisionVariable<2>(x3_, x1_), VectorDecisionVariable<1>(x2_)}); EXPECT_EQ(binding1.GetNumElements(), 3u); VectorDecisionVariable<3> var1_expected(x3_, x1_, x2_); for (int i = 0; i < 3; ++i) { EXPECT_PRED2(VarEqual, binding1.variables()(i), var1_expected(i)); } // Creates a binding with a single VectorDecisionVariable. Binding<BoundingBoxConstraint> binding2( bb_con1, VectorDecisionVariable<3>(x3_, x1_, x2_)); EXPECT_EQ(binding2.GetNumElements(), 3u); for (int i = 0; i < 3; ++i) { EXPECT_PRED2(VarEqual, binding2.variables()(i), var1_expected(i)); } } TEST_F(TestBinding, TestPrinting) { auto bb_con1 = std::make_shared<BoundingBoxConstraint>( Eigen::Vector3d::Zero(), Eigen::Vector3d::Ones()); // Checks if the bound variables are stored in the right order. Binding<BoundingBoxConstraint> binding1( bb_con1, {VectorDecisionVariable<2>(x3_, x1_), VectorDecisionVariable<1>(x2_)}); bb_con1->set_description("dummy bb"); const std::string str_expected1 = "BoundingBoxConstraint described as 'dummy bb'\n" "0 <= x3 <= 1\n" "0 <= x1 <= 1\n" "0 <= x2 <= 1\n"; EXPECT_EQ(fmt::format("{}", binding1), str_expected1); // Test to_string() for LinearEqualityConstraint binding. Eigen::Matrix2d Aeq; Aeq << 1, 2, 3, 4; auto linear_eq_constraint = std::make_shared<LinearEqualityConstraint>(Aeq, Eigen::Vector2d(1, 2)); Binding<LinearEqualityConstraint> linear_eq_binding( linear_eq_constraint, VectorDecisionVariable<2>(x1_, x2_)); const std::string str_expected2 = "LinearEqualityConstraint\n(x1 + 2 * x2) == 1\n(3 * x1 + 4 * x2) == 2\n"; EXPECT_EQ(fmt::format("{}", linear_eq_binding), str_expected2); EXPECT_EQ(linear_eq_binding.to_string(), str_expected2); const Eigen::Matrix2d Ain = Aeq; auto linear_ineq_constraint = std::make_shared<LinearConstraint>( Ain, Eigen::Vector2d(1, 2), Eigen::Vector2d(2, 3)); Binding<LinearConstraint> linear_binding( linear_ineq_constraint, Vector2<symbolic::Variable>(x1_, x2_)); const std::string str_expected3 = "LinearConstraint\n1 <= (x1 + 2 * x2) <= 2\n2 <= (3 * x1 + 4 * x2) <= " "3\n"; EXPECT_EQ(fmt::format("{}", linear_binding), str_expected3); EXPECT_EQ(linear_binding.to_string(), str_expected3); // Test ToLatex(). EXPECT_EQ(linear_binding.ToLatex(1), "\\begin{bmatrix} 1 \\\\ 2 \\end{bmatrix} \\le \\begin{bmatrix} 1 " "& 2 \\\\ 3 & 4 \\end{bmatrix} \\begin{bmatrix} x1 \\\\ x2 " "\\end{bmatrix} \\le \\begin{bmatrix} 2 \\\\ 3 \\end{bmatrix}"); } TEST_F(TestBinding, TestHash) { auto bb_con1 = std::make_shared<BoundingBoxConstraint>( Eigen::Vector3d::Zero(), Eigen::Vector3d::Ones()); Binding<BoundingBoxConstraint> binding1( bb_con1, {VectorDecisionVariable<2>(x3_, x1_), VectorDecisionVariable<1>(x2_)}); EXPECT_EQ(binding1, binding1); // Creates a binding with a single VectorDecisionVariable. Binding<BoundingBoxConstraint> binding2( bb_con1, VectorDecisionVariable<3>(x3_, x1_, x2_)); EXPECT_EQ(binding1, binding2); // Cast both binding1 and binding2 to Binding<LinearConstraint>. They should // be equal after casting. const Binding<LinearConstraint> binding1_cast = internal::BindingDynamicCast<LinearConstraint>(binding1); const Binding<LinearConstraint> binding2_cast = internal::BindingDynamicCast<LinearConstraint>(binding2); EXPECT_EQ(binding1_cast, binding2_cast); // binding3 has different variables. Binding<BoundingBoxConstraint> binding3( bb_con1, VectorDecisionVariable<3>(x3_, x2_, x1_)); EXPECT_NE(binding1, binding3); // bb_con2 has different address from bb_con1, although they have the same // bounds. auto bb_con2 = std::make_shared<BoundingBoxConstraint>( Eigen::Vector3d::Zero(), Eigen::Vector3d::Ones()); EXPECT_TRUE(CompareMatrices(bb_con2->lower_bound(), bb_con1->lower_bound())); EXPECT_TRUE(CompareMatrices(bb_con2->upper_bound(), bb_con1->upper_bound())); Binding<BoundingBoxConstraint> binding4( bb_con2, VectorDecisionVariable<3>(x3_, x1_, x2_)); EXPECT_NE(binding4, binding1); EXPECT_NE(binding4, binding2); // Test using Binding as unordered_map key. std::unordered_map<Binding<BoundingBoxConstraint>, int> map; map.emplace(binding1, 1); EXPECT_EQ(map.at(binding1), 1); EXPECT_EQ(map.at(binding2), 1); EXPECT_EQ(map.find(binding3), map.end()); map.emplace(binding3, 3); EXPECT_EQ(map.at(binding3), 3); } TEST_F(TestBinding, TestCost) { // Tests binding with a cost. const VectorDecisionVariable<3> x(x1_, x2_, x3_); // Test a linear cost binding. auto cost1 = std::make_shared<LinearCost>(Eigen::Vector3d(1, 2, 3), 1); Binding<LinearCost> binding1(cost1, x); EXPECT_EQ(binding1.evaluator().get(), cost1.get()); EXPECT_EQ(binding1.evaluator()->num_outputs(), 1); EXPECT_EQ(binding1.GetNumElements(), 3); for (int i = 0; i < 3; ++i) { EXPECT_PRED2(VarEqual, binding1.variables()(i), x(i)); } EXPECT_EQ(fmt::format("{}", binding1), "LinearCost (1 + x1 + 2 * x2 + 3 * x3)"); // Test a quadratic cost binding. auto cost2 = std::make_shared<QuadraticCost>(Eigen::Matrix2d::Identity(), Eigen::Vector2d(2, 3), 1); Binding<QuadraticCost> binding2(cost2, x.head<2>()); EXPECT_EQ(fmt::format("{}", binding2), "QuadraticCost (1 + 2 * x1 + 3 * x2 + 0.5 * pow(x1, 2) + 0.5 * " "pow(x2, 2))"); } class DummyEvaluator : public EvaluatorBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DummyEvaluator) DummyEvaluator() : EvaluatorBase(2, 3) {} protected: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { y->resize(2); (*y)(0) = x(1) * x(2); (*y)(1) = x(0) - x(1); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { y->resize(2); (*y)(0) = x(1) * x(2); (*y)(1) = x(0) - x(1); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { y->resize(2); (*y)(0) = x(1) * x(2); (*y)(1) = x(0) - x(1); } }; TEST_F(TestBinding, TestEvaluator) { // Tests binding with an evaluator. const VectorDecisionVariable<3> x(x1_, x2_, x3_); const auto evaluator = std::make_shared<DummyEvaluator>(); evaluator->set_description("dummy"); Binding<DummyEvaluator> binding(evaluator, x); EXPECT_EQ(binding.evaluator().get(), evaluator.get()); EXPECT_EQ(binding.evaluator()->num_outputs(), 2); EXPECT_EQ(binding.GetNumElements(), 3); EXPECT_EQ(fmt::format("{}", binding), "DummyEvaluator described as 'dummy' with 3 decision variables " "x1 x2 x3\n"); for (int i = 0; i < 3; ++i) { EXPECT_PRED2(VarEqual, binding.variables()(i), x(i)); } } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/diagonally_dominant_matrix_test.cc
#include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/snopt_solver.h" #include "drake/solvers/solve.h" namespace drake { namespace solvers { GTEST_TEST(DiagonallyDominantMatrixConstraint, ReturnYTest) { // Test the returned variables Y. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<5>(); auto Y = prog.AddPositiveDiagonallyDominantMatrixConstraint( X.cast<symbolic::Expression>()); EXPECT_EQ(Y.rows(), 5); EXPECT_EQ(Y.cols(), 5); for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { if (i != j) { EXPECT_EQ(Y(i, j), Y(j, i)); } else { EXPECT_EQ(Y(i, i), X(i, i)); } } } } GTEST_TEST(DiagonallyDominantMatrixConstraint, FeasibilityCheck) { MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<2>(); auto Y = prog.AddPositiveDiagonallyDominantMatrixConstraint( X.cast<symbolic::Expression>()); EXPECT_EQ(Y(0, 1), Y(1, 0)); EXPECT_EQ(Y(0, 0), X(0, 0)); EXPECT_EQ(Y(1, 1), X(1, 1)); auto X_constraint = prog.AddBoundingBoxConstraint( Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(), VectorDecisionVariable<3>(X(0, 0), X(0, 1), X(1, 1))); auto set_X_value = [&X_constraint](const Eigen::Vector3d& x_upper_triangle) { X_constraint.evaluator()->UpdateLowerBound(x_upper_triangle); X_constraint.evaluator()->UpdateUpperBound(x_upper_triangle); }; // [1 0.9;0.9 2] is diagonally dominant set_X_value(Eigen::Vector3d(1, 0.9, 2)); MathematicalProgramResult result = Solve(prog); EXPECT_TRUE(result.is_success()); // [1 -0.9; -0.9 2] is diagonally dominant set_X_value(Eigen::Vector3d(1, -0.9, 2)); result = Solve(prog); EXPECT_TRUE(result.is_success()); // [1 1.1; 1.1 2] is not diagonally dominant set_X_value(Eigen::Vector3d(1, 1.1, 2)); result = Solve(prog); EXPECT_FALSE(result.is_success()); EXPECT_TRUE( result.get_solution_result() == SolutionResult::kInfeasibleConstraints || result.get_solution_result() == SolutionResult::kInfeasibleOrUnbounded); // [1 -1.1; -1.1 2] is not diagonally dominant set_X_value(Eigen::Vector3d(1, -1.1, 2)); result = Solve(prog); EXPECT_FALSE(result.is_success()); EXPECT_TRUE( result.get_solution_result() == SolutionResult::kInfeasibleConstraints || result.get_solution_result() == SolutionResult::kInfeasibleOrUnbounded); } GTEST_TEST(DiagonallyDominantMatrixConstraint, three_by_three_vertices) { // I can manually compute the polytope of (a, b, c) to make // [1 a b] // A = [a 2 c] // [b c 3] // to be a diagonally dominant matrix. The vertices of the polytope are // (0, ±1, 0), (±1, 0, 0), (0, ±1, ±2), (±1, 0, ±1), (0, 0, ±2) // By optimizing the LP // min nᵀ* (a, b, c) // s.t A is diagonally dominant // with different vector n, we can recover the vertices of the polytope as // the optimal solution to this LP. MathematicalProgram prog; auto X = prog.NewSymmetricContinuousVariables<3>(); prog.AddBoundingBoxConstraint(Eigen::Vector3d(1, 2, 3), Eigen::Vector3d(1, 2, 3), X.diagonal()); prog.AddPositiveDiagonallyDominantMatrixConstraint( X.cast<symbolic::Expression>()); auto cost = prog.AddLinearCost(Eigen::Vector3d::Zero(), 0, VectorDecisionVariable<3>(X(0, 1), X(0, 2), X(1, 2))); auto solve_and_check = [&prog, &X]( const Eigen::Vector3d& sol_expected, double psd_tol, // tolerance for checking whether a matrix is psd double cost_equality_tol // tolerance for checking that two solutions // achieve the same cost ) { const auto result = Solve(prog); auto prog_expected = prog.Clone(); prog_expected->AddLinearEqualityConstraint(X(0, 1), sol_expected(0)); prog_expected->AddLinearEqualityConstraint(X(0, 2), sol_expected(1)); prog_expected->AddLinearEqualityConstraint(X(1, 2), sol_expected(2)); const auto result_expected = Solve(*prog_expected); if (result.get_solver_id() != SnoptSolver::id()) { // Do not check when we use SNOPT. It is known that our SnoptSolver // wrapper doesn't solve this problem correctly, see // https://github.com/RobotLocomotion/drake/pull/9382 // TODO(hongkai.dai): fix the problem in SnoptSolver wrapper and // enable this test with Snopt. // Check that expected solution is feasible and achieves the same cost // as the optimal solution. This avoids the issue of the expected // solution potentially being one of many possible solutions to the // optimization problem. EXPECT_TRUE(result.is_success()); EXPECT_TRUE(result_expected.is_success()); EXPECT_NEAR(result.get_optimal_cost(), result_expected.get_optimal_cost(), cost_equality_tol); // The matrix should be positive semidefinite. const Eigen::Matrix3d X_sol_expected = result_expected.GetSolution(X); Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver_expected( X_sol_expected); EXPECT_TRUE( (eigen_solver_expected.eigenvalues().array() >= -psd_tol).all()); const Eigen::Matrix3d X_sol = result.GetSolution(X); Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver(X_sol); EXPECT_TRUE((eigen_solver.eigenvalues().array() >= -psd_tol).all()); } }; const double psd_tol{1E-6}; const double cost_equality_tol{1E-8}; cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(1, 0, 0)); solve_and_check(Eigen::Vector3d(-1, 0, 0), psd_tol, cost_equality_tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(-1, 0, 0)); solve_and_check(Eigen::Vector3d(1, 0, 0), psd_tol, cost_equality_tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0, 1, 0)); solve_and_check(Eigen::Vector3d(0, -1, 0), psd_tol, cost_equality_tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0, -1, 0)); solve_and_check(Eigen::Vector3d(0, 1, 0), psd_tol, cost_equality_tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0, 0, 1)); solve_and_check(Eigen::Vector3d(0, 0, -2), psd_tol, cost_equality_tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(0, 0, -1)); solve_and_check(Eigen::Vector3d(0, 0, 2), psd_tol, cost_equality_tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(1, 1, 1)); solve_and_check(Eigen::Vector3d(0, -1, -2), psd_tol, cost_equality_tol); cost.evaluator()->UpdateCoefficients(Eigen::Vector3d(2, 0, 1)); solve_and_check(Eigen::Vector3d(-1, 0, -1), psd_tol, cost_equality_tol); } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/decision_variable_test.cc
#include "drake/solvers/decision_variable.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { namespace solvers { namespace test { using drake::symbolic::test::VarEqual; GTEST_TEST(TestDecisionVariable, TestVariableListRef) { symbolic::Variable x1("x1"); symbolic::Variable x2("x2"); symbolic::Variable x3("x3"); symbolic::Variable x4("x4"); VectorDecisionVariable<2> x_vec1(x3, x1); VectorDecisionVariable<2> x_vec2(x2, x4); VariableRefList var_list{x_vec1, x_vec2}; VectorXDecisionVariable stacked_vars = ConcatenateVariableRefList(var_list); EXPECT_EQ(stacked_vars.rows(), 4); EXPECT_PRED2(VarEqual, stacked_vars(0), x3); EXPECT_PRED2(VarEqual, stacked_vars(1), x1); EXPECT_PRED2(VarEqual, stacked_vars(2), x2); EXPECT_PRED2(VarEqual, stacked_vars(3), x4); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/moby_lcp_solver_test.cc
#include "drake/solvers/moby_lcp_solver.h" #include <memory> #include <vector> #include <gtest/gtest.h> #include <unsupported/Eigen/AutoDiff> #include "drake/common/test_utilities/eigen_matrix_compare.h" namespace drake { namespace solvers { namespace { const double epsilon = 1e-6; const bool verbose = false; /// Run all non-regularized solvers. If @p expected_z is an empty /// vector, outputs will only be compared against each other. template <typename Derived> void RunBasicLcp(const Eigen::MatrixBase<Derived>& M, const Eigen::VectorXd& q, const Eigen::VectorXd& expected_z_in, bool expect_fast_pass) { MobyLCPSolver<double> l; l.SetLoggingEnabled(verbose); Eigen::VectorXd expected_z = expected_z_in; // NOTE: We don't necessarily expect the unregularized fast solver to succeed, // hence we don't test the result. Eigen::VectorXd fast_z; bool result = l.SolveLcpFast(M, q, &fast_z); EXPECT_GT(l.get_num_pivots(), 0); if (expected_z.size() == 0) { ASSERT_TRUE(expect_fast_pass) << "Expected Z not provided and expect_fast_pass unset."; expected_z = fast_z; } else { if (expect_fast_pass) { EXPECT_TRUE(CompareMatrices(fast_z, expected_z, epsilon, MatrixCompareType::absolute)); } else { EXPECT_FALSE(CompareMatrices(fast_z, expected_z, epsilon, MatrixCompareType::absolute)); } } Eigen::VectorXd lemke_z; result = l.SolveLcpLemke(M, q, &lemke_z); EXPECT_TRUE(result); EXPECT_TRUE(CompareMatrices(lemke_z, expected_z, epsilon, MatrixCompareType::absolute)); EXPECT_GT(l.get_num_pivots(), 0); } /// Run all regularized solvers. If @p expected_z is an empty /// vector, outputs will only be compared against each other. template <typename Derived> void RunRegularizedLcp(const Eigen::MatrixBase<Derived>& M, const Eigen::VectorXd& q, const Eigen::VectorXd& expected_z_in, bool expect_fast_pass) { MobyLCPSolver<double> l; l.SetLoggingEnabled(verbose); Eigen::VectorXd expected_z = expected_z_in; Eigen::VectorXd fast_z; bool result = l.SolveLcpFastRegularized(M, q, &fast_z); if (expected_z.size() == 0) { expected_z = fast_z; } else { if (expect_fast_pass) { ASSERT_TRUE(result); EXPECT_TRUE(CompareMatrices(fast_z, expected_z, epsilon, MatrixCompareType::absolute)); } else { EXPECT_FALSE(CompareMatrices(fast_z, expected_z, epsilon, MatrixCompareType::absolute)); } } Eigen::VectorXd lemke_z; result = l.SolveLcpLemkeRegularized(M, q, &lemke_z); EXPECT_TRUE(CompareMatrices(lemke_z, expected_z, epsilon, MatrixCompareType::absolute)); } /// Run all solvers. If @p expected_z is an empty /// vector, outputs will only be compared against each other. template <typename Derived> void runLCP(const Eigen::MatrixBase<Derived>& M, const Eigen::VectorXd& q, const Eigen::VectorXd& expected_z_in, bool expect_fast_pass) { RunBasicLcp(M, q, expected_z_in, expect_fast_pass); RunRegularizedLcp(M, q, expected_z_in, expect_fast_pass); } GTEST_TEST(testMobyLCP, testTrivial) { Eigen::Matrix<double, 9, 9> M; // clang-format off M << 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9; // clang-format on Eigen::Matrix<double, 9, 1> q; q << -1, -1, -1, -1, -1, -1, -1, -1, -1; Eigen::VectorXd empty_z; RunBasicLcp(M, q, empty_z, true); // Mangle the input matrix so that some regularization occurs. M(0, 8) = 10; RunRegularizedLcp(M, q, empty_z, true); } GTEST_TEST(testMobyLCP, testAutoDiffTrivial) { typedef Eigen::AutoDiffScalar<Vector1d> Scalar; Eigen::Matrix<Scalar, 9, 9> M; // clang-format off M << 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9; // clang-format on // Set the LCP vector and indicate that we are interested in how the solution // changes as the first element changes. VectorX<Scalar> q(9); q << -1, -1, -1, -1, -1, -1, -1, -1, -1; q(0).derivatives()(0) = 1; VectorX<Scalar> fast_z, lemke_z; // Attempt to compute the solution using both "fast" and Lemke algorithms. MobyLCPSolver<Scalar> l; l.SetLoggingEnabled(verbose); bool result = l.SolveLcpFast(M, q, &fast_z); EXPECT_TRUE(result); result = l.SolveLcpLemke(M, q, &lemke_z); EXPECT_TRUE(result); // Since the LCP matrix is diagonal and the first number is 1.0, a unit // increase in q(0) will result in a unit decrease in z(0). const double tol = std::numeric_limits<double>::epsilon(); EXPECT_NEAR(fast_z(0).value(), 1.0, tol); EXPECT_NEAR(fast_z(0).derivatives()(0), -1, tol); // Check the solutions. EXPECT_NEAR(fast_z[0].value(), lemke_z[0].value(), tol); EXPECT_NEAR(fast_z[1].value(), lemke_z[1].value(), tol); EXPECT_NEAR(fast_z[2].value(), lemke_z[2].value(), tol); EXPECT_NEAR(fast_z[3].value(), lemke_z[3].value(), tol); EXPECT_NEAR(fast_z[4].value(), lemke_z[4].value(), tol); EXPECT_NEAR(fast_z[5].value(), lemke_z[5].value(), tol); EXPECT_NEAR(fast_z[6].value(), lemke_z[6].value(), tol); EXPECT_NEAR(fast_z[7].value(), lemke_z[7].value(), tol); EXPECT_NEAR(fast_z[8].value(), lemke_z[8].value(), tol); // Mangle the input matrix so that some regularization occurs. fast_z.setZero(); lemke_z.setZero(); M(0, 8) = 10; result = l.SolveLcpFastRegularized(M, q, &fast_z); EXPECT_TRUE(result); result = l.SolveLcpLemkeRegularized(M, q, &lemke_z); EXPECT_TRUE(result); EXPECT_NEAR(fast_z[0].value(), lemke_z[0].value(), tol); EXPECT_NEAR(fast_z[1].value(), lemke_z[1].value(), tol); EXPECT_NEAR(fast_z[2].value(), lemke_z[2].value(), tol); EXPECT_NEAR(fast_z[3].value(), lemke_z[3].value(), tol); EXPECT_NEAR(fast_z[4].value(), lemke_z[4].value(), tol); EXPECT_NEAR(fast_z[5].value(), lemke_z[5].value(), tol); EXPECT_NEAR(fast_z[6].value(), lemke_z[6].value(), tol); EXPECT_NEAR(fast_z[7].value(), lemke_z[7].value(), tol); EXPECT_NEAR(fast_z[8].value(), lemke_z[8].value(), tol); } GTEST_TEST(testMobyLCP, testProblem1) { // Problem from example 10.2.1 in "Handbook of Test Problems in // Local and Global Optimization". Eigen::Matrix<double, 16, 16> M; M.setIdentity(); for (int i = 0; i < M.rows() - 1; i++) { for (int j = i + 1; j < M.cols(); j++) { M(i, j) = 2; } } Eigen::Matrix<double, 1, 16> q; q.fill(-1); Eigen::Matrix<double, 1, 16> z; z.setZero(); z(15) = 1; runLCP(M, q, z, false); } GTEST_TEST(testMobyLCP, testProblem2) { // Problem from example 10.2.2 in "Handbook of Test Problems in // Local and Global Optimization". Eigen::Matrix<double, 2, 2> M; M.fill(1); Eigen::Matrix<double, 1, 2> q; q.fill(-1); // This problem also has valid solutions (0, 1) and (0.5, 0.5). Eigen::Matrix<double, 1, 2> z; z << 1, 0; runLCP(M, q, z, true); } GTEST_TEST(testMobyLCP, testProblem3) { // Problem from example 10.2.3 in "Handbook of Test Problems in // Local and Global Optimization". Eigen::Matrix<double, 3, 3> M; // clang-format off M << 0, -1, 2, 2, 0, -2, -1, 1, 0; // clang-format on Eigen::Matrix<double, 1, 3> q; q << -3, 6, -1; Eigen::Matrix<double, 1, 3> z; z << 0, 1, 3; runLCP(M, q, z, true); } GTEST_TEST(testMobyLCP, testProblem4) { // Problem from example 10.2.4 in "Handbook of Test Problems in // Local and Global Optimization". Eigen::Matrix<double, 4, 4> M; // clang-format off M << 0, 0, 10, 20, 0, 0, 30, 15, 10, 20, 0, 0, 30, 15, 0, 0; // clang-format on Eigen::Matrix<double, 1, 4> q; q.fill(-1); // This solution is the third in the book, which it explicitly // states cannot be found using the Lemke-Howson algorithm. Eigen::VectorXd z(4); z << 1. / 90., 2. / 45., 1. / 90., 2. / 45.; MobyLCPSolver<double> l; l.SetLoggingEnabled(verbose); Eigen::VectorXd fast_z; bool result = l.SolveLcpFast(M, q, &fast_z); EXPECT_TRUE(CompareMatrices(fast_z, z, epsilon, MatrixCompareType::absolute)); // TODO(sammy-tri) the Lemke solvers find no solution at all, however. fast_z.setZero(); result = l.SolveLcpLemke(M, q, &fast_z); EXPECT_FALSE(result); } GTEST_TEST(testMobyLCP, testProblem6) { // Problem from example 10.2.9 in "Handbook of Test Problems in // Local and Global Optimization". Eigen::Matrix<double, 4, 4> M; // clang-format off M << 11, 0, 10, -1, 0, 11, 10, -1, 10, 10, 21, -1, 1, 1, 1, 0; // Note that the (3, 3) position is incorrectly // shown in the book with the value 1. // clang-format on // Pick a couple of arbitrary points in the [0, 23] range. for (double l = 1; l <= 23; l += 15) { Eigen::Matrix<double, 1, 4> q; q << 50, 50, l, -6; Eigen::Matrix<double, 1, 4> z; // clang-format off z << (l + 16.) / 13., (l + 16.) / 13., (2. * (23 - l)) / 13., (1286. - (9. * l)) / 13; // clang-format on runLCP(M, q, z, true); } // Try again with a value > 23 and see that we've hit the limit as // described. The fast solver has stopped working in this case // without regularization. Eigen::Matrix<double, 1, 4> q; q << 50, 50, 100, -6; Eigen::Matrix<double, 1, 4> z; z << 3, 3, 0, 83; runLCP(M, q, z, true); } GTEST_TEST(testMobyLCP, testEmpty) { Eigen::MatrixXd empty_M(0, 0); Eigen::VectorXd empty_q(0); Eigen::VectorXd z; MobyLCPSolver<double> l; l.SetLoggingEnabled(verbose); bool result = l.SolveLcpFast(empty_M, empty_q, &z); EXPECT_TRUE(result); EXPECT_EQ(z.size(), 0); result = l.SolveLcpLemke(empty_M, empty_q, &z); EXPECT_TRUE(result); EXPECT_EQ(z.size(), 0); result = l.SolveLcpFastRegularized(empty_M, empty_q, &z); EXPECT_TRUE(result); EXPECT_EQ(z.size(), 0); result = l.SolveLcpLemkeRegularized(empty_M, empty_q, &z); EXPECT_TRUE(result); EXPECT_EQ(z.size(), 0); } // Verifies that z is zero on LCP solver failure. GTEST_TEST(testMobyLCP, testFailure) { Eigen::MatrixXd neg_M(1, 1); Eigen::VectorXd neg_q(1); // This LCP is unsolvable: -z - 1 cannot be greater than zero when z is // restricted to be non-negative. neg_M(0, 0) = -1; neg_q[0] = -1; Eigen::VectorXd z; MobyLCPSolver<double> l; l.SetLoggingEnabled(verbose); bool result = l.SolveLcpFast(neg_M, neg_q, &z); EXPECT_FALSE(result); ASSERT_EQ(z.size(), neg_q.size()); EXPECT_EQ(z[0], 0.0); LinearComplementarityConstraint constraint(neg_M, neg_q); EXPECT_FALSE(constraint.CheckSatisfied(z)); result = l.SolveLcpLemke(neg_M, neg_q, &z); EXPECT_FALSE(result); ASSERT_EQ(z.size(), neg_q.size()); EXPECT_EQ(z[0], 0.0); EXPECT_FALSE(constraint.CheckSatisfied(z)); // Note: we do not test regularized solvers here, as we're specifically // interested in algorithm failure and the regularized solvers are designed // not to fail. } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/rotation_constraint_visualization.cc
#include "drake/solvers/test/rotation_constraint_visualization.h" #include "drake/common/proto/call_python.h" #include "drake/solvers/mixed_integer_rotation_constraint.h" #include "drake/solvers/mixed_integer_rotation_constraint_internal.h" #include "drake/solvers/rotation_constraint.h" namespace drake { namespace solvers { namespace { // Draw an arc between two end points on the unit sphere. The two end points // are the vertices of the intersection region, between the box and the surface // of the sphere. // This requires that // arc_end0(fixed_axis) = arc_end1(fixed_axis) = x(fixed_axis), // where `x` is a point on the arc. // Draws the shorter arc between the two points. void DrawArcBoundaryOfBoxSphereIntersection(const Eigen::Vector3d& arc_end0, const Eigen::Vector3d& arc_end1, int fixed_axis, const Eigen::RowVector3d& color) { DRAKE_DEMAND(std::abs(arc_end0(fixed_axis) - arc_end1(fixed_axis)) < 1E-3); DRAKE_DEMAND(std::abs(arc_end0.norm() - 1) < 1E-3); DRAKE_DEMAND(std::abs(arc_end1.norm() - 1) < 1E-3); int free_axis0 = (fixed_axis + 1) % 3; int free_axis1 = (fixed_axis + 2) % 3; if (arc_end0(free_axis0) * arc_end1(free_axis0) < 0 || arc_end0(free_axis1) * arc_end1(free_axis1) < 0) { // The two end points have to be in the same orthant. throw std::runtime_error( "The end points of the boundary arc are not in the same orthant."); } const int kNumViaPoints = 20; Eigen::Matrix<double, 3, kNumViaPoints> via_pts; via_pts.row(fixed_axis) = Eigen::Matrix<double, 1, kNumViaPoints>::Constant(arc_end0(fixed_axis)); Eigen::Vector3d start_via_pts, end_via_pts; // Eigen::LinSpaced requires the smaller number being the first argument. So // find out whether arc_end0(free_axis0) or arc_end1(free_axis0) is smaller. if (arc_end0(free_axis0) < arc_end1(free_axis0)) { start_via_pts = arc_end0; end_via_pts = arc_end1; } else { start_via_pts = arc_end1; end_via_pts = arc_end0; } via_pts.row(free_axis0) = Eigen::Matrix<double, 1, kNumViaPoints>::LinSpaced( kNumViaPoints, start_via_pts(free_axis0), end_via_pts(free_axis0)); via_pts(free_axis1, 0) = start_via_pts(free_axis1); via_pts(free_axis1, kNumViaPoints - 1) = end_via_pts(free_axis1); bool positive_free_axis1 = arc_end0(free_axis1) > 0 || arc_end1(free_axis1) > 0; for (int i = 1; i < kNumViaPoints - 1; ++i) { // A point `x` on the arc satisfies // x(free_axis0)^2 + x(free_axis1)^2 = 1 - x(fixed_axis)^2 via_pts(free_axis1, i) = std::sqrt(1 - std::pow(via_pts(fixed_axis, i), 2) - std::pow(via_pts(free_axis0, i), 2)); if (!positive_free_axis1) { via_pts(free_axis1, i) *= -1; } } using common::CallPython; using common::ToPythonKwargs; CallPython("plot3", via_pts.row(0).transpose(), via_pts.row(1).transpose(), via_pts.row(2).transpose(), ToPythonKwargs("color", color.transpose())); } } // namespace void DrawSphere(const Eigen::RowVector3d& color) { using common::CallPython; using common::ToPythonKwargs; CallPython("sphere", 40, ToPythonKwargs("alpha", 0.2, "color", color.transpose(), "linestyle", "None")); } void DrawBox(const Eigen::Vector3d& bmin, const Eigen::Vector3d& bmax, const Eigen::RowVector3d& color) { using common::CallPython; using common::ToPythonKwargs; if ((bmin.array() < 0).any()) { throw std::runtime_error("bmin should be in the first orthant in DrawBox."); } if ((bmax.array() < 0).any()) { throw std::runtime_error("bmax should be in the first orthant in DrawBox."); } if (bmin.norm() <= 1 && bmax.norm() >= 1) { // The box and the sphere has intersections. CallPython("box", bmin, bmax, ToPythonKwargs("alpha", 0.2, "color", color.transpose(), "linestyle", "None")); } } void DrawBoxSphereIntersection(const Eigen::Vector3d& bmin, const Eigen::Vector3d& bmax, const Eigen::RowVector3d& color) { DRAKE_DEMAND((bmax.array() > bmin.array()).all()); // First convert bmin and bmax to the first orthant. Eigen::Vector3d orthant_bmin; Eigen::Vector3d orthant_bmax; // orthant_sign(i) = 1 if the i'th axis of the box is positive, otherwise it // is -1. Eigen::Vector3i orthant_sign; for (int i = 0; i < 3; ++i) { if (bmin(i) >= 0) { orthant_bmin(i) = bmin(i); orthant_bmax(i) = bmax(i); orthant_sign(i) = 1; } else if (bmax(i) <= 0) { orthant_bmin(i) = -bmax(i); orthant_bmax(i) = -bmin(i); orthant_sign(i) = -1; } else { throw std::runtime_error( "The box bmin <= x <= bmax should satisfy either bmin(i) >=0 or " "bmax(i) <= 0"); } } // Compute the intersection points between the sphere in the first orthant, // with the box orthant_bmin <= x <= orthant_bmax auto intersection_pts = internal::ComputeBoxEdgesAndSphereIntersection( orthant_bmin, orthant_bmax); // Now convert the intersection point back to the right orthant. for (int i = 0; i < static_cast<int>(intersection_pts.size()); ++i) { for (int j = 0; j < 3; ++j) { intersection_pts[i](j) *= orthant_sign(j); } } // Draw the line that connects adjacent intersection points. // For each intersection point, find out the neighbouring points, and then // draw the arc between these two points. The neighbouring points should have // one axis same as the queried intersection point. Also, the neighbouring // points should be on the facet of the box as the queried intersection point. for (int i = 0; i < static_cast<int>(intersection_pts.size()); ++i) { for (int j = i + 1; j < static_cast<int>(intersection_pts.size()); ++j) { for (int dim = 0; dim < 3; ++dim) { if (std::abs(intersection_pts[i](dim) - intersection_pts[j](dim)) < 1E-3 && (std::abs(intersection_pts[i](dim) - bmin(dim)) < 1E-3 || std::abs(intersection_pts[i](dim) - bmax(dim)) < 1E-3)) { // Determine if two intersection points are the neighbouring boundary // points of the intersection region. DrawArcBoundaryOfBoxSphereIntersection( intersection_pts[i], intersection_pts[j], dim, color); } } } } } } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/mixed_integer_rotation_constraint_corner_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/solvers/mixed_integer_rotation_constraint.h" /* clang-format on */ #include <gtest/gtest.h> #include "drake/common/drake_assert.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/gray_code.h" #include "drake/solvers/integer_optimization_util.h" #include "drake/solvers/mosek_solver.h" #include "drake/solvers/rotation_constraint.h" #include "drake/solvers/solve.h" using drake::symbolic::Expression; namespace drake { namespace solvers { namespace { enum RotationMatrixIntervalBinning { kLinear, ///< Same as IntervalBining::kLinear, used by /// MixedIntegerRotationMatrixGenerator. kLogarithmic, ///< Same as IntervalBinning::kLogarithmic, used by /// MixedIntegerRotationMatrixGenerator. kPosNegLinear, ///< Used by AddRotationMatrixBoxSphereIntersection. It uses /// linear binning for positive and negative axis /// respectively. }; // Test some corner cases of box-sphere intersection. // The corner cases happens when either the innermost or the outermost corner // of the box bmin <= x <= bmax lies on the surface of the unit sphere. class TestBoxSphereCorner : public ::testing::TestWithParam< std::tuple<int, bool, int, RotationMatrixIntervalBinning>> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(TestBoxSphereCorner) TestBoxSphereCorner() : prog_(), R_(NewRotationMatrixVars(&prog_)), Cpos_(), Cneg_(), orthant_(std::get<0>(GetParam())), is_bmin_(std::get<1>(GetParam())), col_idx_(std::get<2>(GetParam())), r_interval_binning_(std::get<3>(GetParam())) { DRAKE_DEMAND(orthant_ >= 0); DRAKE_DEMAND(orthant_ <= 7); const int N = 3; // num_interval_per_half_axis = 3 if (r_interval_binning_ == RotationMatrixIntervalBinning::kLinear || r_interval_binning_ == RotationMatrixIntervalBinning::kLogarithmic) { const IntervalBinning interval_binning = r_interval_binning_ == RotationMatrixIntervalBinning::kLinear ? IntervalBinning::kLinear : IntervalBinning::kLogarithmic; const MixedIntegerRotationConstraintGenerator rotation_generator( MixedIntegerRotationConstraintGenerator::Approach:: kBoxSphereIntersection, N, interval_binning); const auto ret = rotation_generator.AddToProgram(R_, &prog_); Cpos_.resize(N); Cneg_.resize(N); const auto gray_codes = math::CalculateReflectedGrayCodes<3>(); for (int k = 0; k < N; ++k) { if (interval_binning == IntervalBinning::kLogarithmic) { Cpos_[k] = prog_.NewContinuousVariables<3, 3>().cast<Expression>(); Cneg_[k] = prog_.NewContinuousVariables<3, 3>().cast<Expression>(); } for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (interval_binning == IntervalBinning::kLinear) { Cpos_[k](i, j) = ret.B_[i][j](N + k); Cneg_[k](i, j) = ret.B_[i][j](N - k - 1); } else { // logarithmic binning. prog_.AddConstraint(CreateBinaryCodeMatchConstraint( ret.B_[i][j].cast<Expression>(), gray_codes.row(N + k).transpose(), Cpos_[k](i, j))); prog_.AddConstraint(CreateBinaryCodeMatchConstraint( ret.B_[i][j].cast<Expression>(), gray_codes.row(N - k - 1).transpose(), Cneg_[k](i, j))); } } } } } else { const auto ret = AddRotationMatrixBoxSphereIntersectionMilpConstraints(R_, N, &prog_); Cpos_ = ret.CRpos; Cneg_ = ret.CRneg; } } ~TestBoxSphereCorner() override {} protected: MathematicalProgram prog_; MatrixDecisionVariable<3, 3> R_; std::vector<Eigen::Matrix<Expression, 3, 3>> Cpos_; std::vector<Eigen::Matrix<Expression, 3, 3>> Cneg_; int orthant_; // Index of the orthant that R_.col(col_idx_) is in. bool is_bmin_; // If true, then the box bmin <= x <= bmax intersects with the // surface of the unit sphere at the unique point bmin; // otherwise it intersects at the unique point bmax; int col_idx_; // R_.col(col_idx_) will be fixed to a vertex of the box, and // also this point is on the surface of the unit sphere. RotationMatrixIntervalBinning r_interval_binning_; }; TEST_P(TestBoxSphereCorner, TestOrthogonal) { // box_pt is a vertex of the box, and also lies exactly on the surface of // the unit sphere. Eigen::Vector3d box_pt(1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0); for (int axis = 0; axis < 3; ++axis) { if (orthant_ & 1 << axis) { box_pt(axis) *= -1; } } int free_axis0 = (col_idx_ + 1) % 3; int free_axis1 = (col_idx_ + 2) % 3; // If R_.col(i) == box_pt, and box_pt is on the surface of the unit sphere, // while also being either bmin or bmax of the box bmin <= x <= bmax, then // the solution should satisfy R.col(j) ⊥ box_pt and R.col(k) ⊥ box_pt prog_.AddBoundingBoxConstraint(box_pt, box_pt, R_.col(col_idx_)); // If bmin is the unique intersection point, here we document when the box is // in the first orthant (+++) // Cpos[1](0, col_idx_) = 1 => 1 / 3 <= R_(0, col_idx_) <= 2 / 3 // Cpos[2](1, col_idx_) = 1 => 2 / 3 <= R_(1, col_idx_) <= 1 // Cpos[2](2, col_idx_) = 1 => 2 / 3 <= R_(2, col_idx_) <= 1 // If bmax is the unique intersection point, here we document when the box is // in the first orthant (+++) // Cpos[0](0, col_idx_) = 1 => 0 <= R_(0, col_idx_) <= 1 / 3 // Cpos[1](1, col_idx_) = 1 => 1 / 3 <= R_(1, col_idx_) <= 2 / 3 // Cpos[1](2, col_idx_) = 1 => 1 / 3 <= R_(2, col_idx_) <= 2 / 3 // orthant_C[i](j) is either Cpos[i](j, col_idx_) or Cneg[i](j, col_idx_), // depending on the orthant. std::array<Eigen::Matrix<Expression, 3, 1>, 3> orthant_C; for (int i = 0; i < 3; ++i) { for (int axis = 0; axis < 3; ++axis) { if (orthant_ & 1 << axis) { orthant_C[i](axis) = Cneg_[i](axis, col_idx_); } else { orthant_C[i](axis) = Cpos_[i](axis, col_idx_); } } } if (is_bmin_) { prog_.AddLinearConstraint(1 == orthant_C[1](0)); prog_.AddLinearConstraint(Eigen::Vector2d::Ones() == orthant_C[2].block<2, 1>(1, 0)); } else { prog_.AddLinearConstraint(1 == orthant_C[0](0)); prog_.AddLinearConstraint(Eigen::Vector2d::Ones() == orthant_C[1].block<2, 1>(1, 0)); } // Add a cost function to try to make the column of R not perpendicular. prog_.AddLinearCost(R_.col(free_axis0).dot(box_pt) + R_.col(free_axis1).dot(box_pt)); const auto result = Solve(prog_); EXPECT_TRUE(result.is_success()); const auto R_val = result.GetSolution(R_); std::vector<Eigen::Matrix3d> Bpos_val(3); std::vector<Eigen::Matrix3d> Bneg_val(3); EXPECT_NEAR(R_val.col(free_axis0).dot(box_pt), 0, 1E-4); EXPECT_NEAR(R_val.col(free_axis1).dot(box_pt), 0, 1E-4); EXPECT_TRUE(CompareMatrices(box_pt.cross(R_val.col(free_axis0)), R_val.col(free_axis1), 1E-4, MatrixCompareType::absolute)); } // It takes too long time to run the test under debug mode. #ifdef DRAKE_ASSERT_IS_ARMED INSTANTIATE_TEST_SUITE_P( RotationTest, TestBoxSphereCorner, ::testing::Combine( ::testing::ValuesIn<std::vector<int>>({0}), // Orthant ::testing::ValuesIn<std::vector<bool>>({true}), // bmin or bmax ::testing::ValuesIn<std::vector<int>>({0}), // column index ::testing::ValuesIn<std::vector<RotationMatrixIntervalBinning>>( {RotationMatrixIntervalBinning::kPosNegLinear}))); #else INSTANTIATE_TEST_SUITE_P( RotationTest, TestBoxSphereCorner, ::testing::Combine( ::testing::ValuesIn<std::vector<int>>({0, 1, 2, 3, 4, 5, 6, 7}), // Orthant ::testing::ValuesIn<std::vector<bool>>({true, false}), // bmin or bmax ::testing::ValuesIn<std::vector<int>>({0, 1, 2}), // column index ::testing::ValuesIn<std::vector<RotationMatrixIntervalBinning>>( {RotationMatrixIntervalBinning::kLinear, RotationMatrixIntervalBinning::kLogarithmic, RotationMatrixIntervalBinning::kPosNegLinear}))); #endif } // namespace } // namespace solvers } // namespace drake int main(int argc, char** argv) { // Ensure that we have the MOSEK license for the entire duration of this test, // so that we do not have to release and re-acquire the license for every // test. auto mosek_license = drake::solvers::MosekSolver::AcquireLicense(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/integer_inequality_solver_test.cc
#include "drake/solvers/integer_inequality_solver.h" #include <gtest/gtest.h> namespace drake { namespace solvers { namespace { // Compare in Lexicographical (Lex) order struct VectorLexCompare { bool operator()(const Eigen::VectorXi& v, const Eigen::VectorXi& w) const { for (int i = 0; i < v.size(); ++i) { if (v(i) < w(i)) return true; if (v(i) > w(i)) return false; } return false; } }; typedef std::set<Eigen::VectorXi, VectorLexCompare> IntegerSet; IntegerSet MatrixToSet(const Eigen::MatrixXi& M) { IntegerSet M_set; for (int i = 0; i < M.rows(); i++) { M_set.insert(M.row(i)); } return M_set; } class IntegerLatticeTest : public ::testing::Test { public: IntegerSet EnumerationSolutions() { const auto y = EnumerateIntegerSolutions(A_, b_, lower_bound_, upper_bound_); return MatrixToSet(y); } void SetDimensions(int num_ineq, int num_var) { int m = num_ineq; int n = num_var; A_.resize(m, n); b_.resize(m); lower_bound_.resize(n); upper_bound_.resize(n); } protected: Eigen::MatrixXi A_; Eigen::VectorXi b_; Eigen::VectorXi lower_bound_; Eigen::VectorXi upper_bound_; }; TEST_F(IntegerLatticeTest, EqualComponents) { SetDimensions(2, 2); A_ << 1, -1, -1, 1; b_ << 0, 0; lower_bound_ << 0, 0; upper_bound_ << 2, 2; IntegerSet ref; ref.insert(Eigen::VectorXi::Constant(2, 0)); ref.insert(Eigen::VectorXi::Constant(2, 1)); ref.insert(Eigen::VectorXi::Constant(2, 2)); EXPECT_EQ(EnumerationSolutions(), ref); } TEST_F(IntegerLatticeTest, SumToConstant) { SetDimensions(2, 2); A_ << 1, 1, -1, -1; b_ << 2, -2; lower_bound_ << 0, 0; upper_bound_ << 2, 2; Eigen::MatrixXi ref_mat(3, 2); ref_mat << 0, 2, 2, 0, 1, 1; EXPECT_EQ(EnumerationSolutions(), MatrixToSet(ref_mat)); } TEST_F(IntegerLatticeTest, Empty) { SetDimensions(1, 2); A_ << 1, 0; b_ << 0; lower_bound_ << 1, 0; upper_bound_ << 2, 0; IntegerSet ref; EXPECT_EQ(EnumerationSolutions(), ref); } TEST_F(IntegerLatticeTest, Singleton) { SetDimensions(1, 4); A_ << 0, 0, 0, 0; b_ << 0; lower_bound_ << 1, 2, 3, 4; upper_bound_ << 1, 2, 3, 4; IntegerSet ref; ref.insert(lower_bound_); EXPECT_EQ(EnumerationSolutions(), ref); } TEST_F(IntegerLatticeTest, InfeasProp) { // Tests that EnumerateIntegerSolutions avoids exhaustive enumeration of m^n // points for intractable choice of m and n. This is enabled by the // infeasibility propapation feature of EnumerateIntegerSolutions. int n = 10; int m = 8; SetDimensions(1, n); // These bounds define a box B with m^n points. lower_bound_ << Eigen::VectorXi::Constant(n, 1); upper_bound_ << lower_bound_ * m; // This constraint is satisfied by one point in B. A_ << Eigen::MatrixXi::Constant(1, n, 1); b_ << A_ * lower_bound_; IntegerSet ref; ref.insert(lower_bound_); EXPECT_EQ(EnumerationSolutions(), ref); } TEST_F(IntegerLatticeTest, EntireBoxFeasible) { SetDimensions(2, 2); // clang-format off A_ << 1, 1, 2, 2; // clang-format on b_ << 10, 20; lower_bound_ << 0, 0; upper_bound_ << 1, 2; Eigen::MatrixXi ref_mat(6, 2); // clang-format off ref_mat << 0, 0, 0, 1, 0, 2, 1, 0, 1, 1, 1, 2; // clang-format on EXPECT_EQ(EnumerationSolutions(), MatrixToSet(ref_mat)); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/plot_feasible_rotation_matrices.cc
#include <iostream> #include <limits> #include "drake/common/proto/call_python.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/mixed_integer_rotation_constraint.h" #include "drake/solvers/rotation_constraint.h" #include "drake/solvers/solve.h" /// Provides a simple utility for developers to visualize (slices of) the /// rotation matrix relaxations. Sets up the problem: /// min_R max_(i,j) |R(i,j) - R_sample(i,j)| /// subject to [ chosen list of constraints on R ] /// It then evaluates this program over a large number of samples and plots the /// points (using call_python) for which R==R_sample (within some tol). using Eigen::Matrix3d; using Eigen::Vector3d; namespace drake { namespace solvers { namespace { // Use this method to change the feasibility envelope for all of the plotting // tools. void AddTestConstraints(MathematicalProgram* prog, const MatrixDecisionVariable<3, 3>& R) { // Add your favorite constraints here. AddRotationMatrixBoxSphereIntersectionMilpConstraints(R, 1, prog); } bool IsFeasible( const MathematicalProgram& prog, const std::shared_ptr<LinearEqualityConstraint>& feasibility_constraint, const Eigen::Ref<const Eigen::MatrixXd>& R_sample) { Eigen::Map<const Eigen::VectorXd> R_sample_vec(R_sample.data(), R_sample.size()); feasibility_constraint->UpdateLowerBound(R_sample_vec); feasibility_constraint->UpdateUpperBound(R_sample_vec); return Solve(prog).is_success(); } void DrawCircle(double radius = 1.0) { const int N = 100; Eigen::Matrix2Xd points(2, N); // Draw circle. for (int i = 0; i < N; i++) { const double theta = i * 2.0 * M_PI / (N - 1); points.col(i) = Eigen::Vector2d(radius * std::cos(theta), radius * std::sin(theta)); } common::CallPython("plot", points.row(0), points.row(1), "k", "linewidth", 4.0); } void PlotFeasiblePoints(const Eigen::Matrix2Xd& points, double radius = 1.0, int fig_num = 1) { using common::CallPython; CallPython("figure", fig_num); CallPython("clf"); CallPython("plot", points.row(0), points.row(1), ".", "markersize", 20.0); DrawCircle(radius); CallPython("xlim", Eigen::RowVector2d(-1.1, 1.1)); CallPython("ylim", Eigen::RowVector2d(-1.1, 1.1)); CallPython("axis", "equal"); } void PlotColumnVectorXYSlice(double z = 0.0, int fig_num = 1) { Vector3d sample(0, 0, z); MathematicalProgram prog; MatrixDecisionVariable<3, 3> R = NewRotationMatrixVars(&prog); AddTestConstraints(&prog, R); // Add a feasibility constraint. std::shared_ptr<LinearEqualityConstraint> feasibility_constraint = prog.AddLinearEqualityConstraint(Eigen::Matrix3d::Identity(), Eigen::Vector3d::Zero(), R.col(0)) .evaluator(); const int num_samples_per_axis = 50; Eigen::Matrix2Xd feasible_points(2, num_samples_per_axis * num_samples_per_axis); int num_feasible = 0; double minval = -1.0, maxval = 1.0; for (int i = 0; i < num_samples_per_axis; i++) { double x = minval + i * (maxval - minval) / (num_samples_per_axis - 1); sample(0) = x; for (int j = 0; j < num_samples_per_axis; j++) { double y = minval + j * (maxval - minval) / (num_samples_per_axis - 1); sample(1) = y; if (IsFeasible(prog, feasibility_constraint, sample)) feasible_points.col(num_feasible++) = Eigen::Vector2d(x, y); } std::cout << "." << std::flush; } feasible_points.conservativeResize(2, num_feasible); PlotFeasiblePoints(feasible_points, std::sqrt(1 - sample(2) * sample(2)), fig_num); using common::CallPython; CallPython("xlabel", "R(0,0)"); CallPython("ylabel", "R(1,0)"); CallPython("title", "R(2,0) = " + std::to_string(z)); } void DoMain() { // Make some plots // Plots z=0 slice of the first column. // To plot z=0.25, set R0(2,0) = 0.25. PlotColumnVectorXYSlice(0.0); } } // namespace } // namespace solvers } // namespace drake int main() { drake::solvers::DoMain(); return 0; }
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/csdp_test_examples.h
#pragma once #include <memory> #include <gtest/gtest.h> #include "drake/solvers/mathematical_program.h" namespace drake { namespace solvers { /** * min 2x0 + x2 * s.t ⎡x0 x1⎤ is psd, * ⎣x1 x0⎦ * ⎡x0 x2⎤ is psd, and * ⎣x2 x0⎦ * x1 == 1. * x0 >= 0.5 * x2 <= 2 * The optimal solution is x = (1, 1, -1). */ class SDPwithOverlappingVariables1 : public ::testing::Test { public: SDPwithOverlappingVariables1(); protected: std::unique_ptr<MathematicalProgram> prog_; Vector3<symbolic::Variable> x_; }; /** * min 2x0 + x1 * s.t ⎡x0 x1⎤ is psd, * ⎣x1 x0⎦ * 2 <= x0 <= 3 * 1 <= x1 * The optimal solution is x = (2, 1). */ class SDPwithOverlappingVariables2 : public ::testing::Test { public: SDPwithOverlappingVariables2(); protected: std::unique_ptr<MathematicalProgram> prog_; Vector2<symbolic::Variable> x_; }; /** * This is the example in CSDP 6.2.0 User's Guide * max tr(C1 * X1) + tr(C2 * X2) * s.t tr(A1 * X1) + y(0) = 1 * tr(A2 * X2) + y(1) = 2 * X1, X2 are psd. * y(0), y(1) ≥ 0 * where C1 = ⎡2 1⎤ * ⎣1 2⎦ * C2 = ⎡3 0 1⎤ * ⎢0 2 0⎥ * ⎣1 0 3⎦ * A1 = ⎡3 1⎤ * ⎣1 3⎦ * A2 = ⎡3 0 1⎤ * ⎢0 4 0⎥ * ⎣1 0 5⎦ */ class CsdpDocExample : public ::testing::Test { public: CsdpDocExample(); protected: std::unique_ptr<MathematicalProgram> prog_; Matrix2<symbolic::Variable> X1_; Matrix3<symbolic::Variable> X2_; Vector2<symbolic::Variable> y_; }; /** * A simple linear program without only bounding box constraint. * max -x(0) + x(1) - 2 *x(2) + 3 * x(3) + x(4) + 1 * 0 ≤ x(0) * 0 ≤ x(1) ≤ 5; * -1 ≤ x(2) * x(3) ≤ 10 * -2 ≤ x(4) ≤ 5 * 0 ≤ x(5) ≤ 0 * 1 ≤ x(6) ≤ 1 * -inf≤x(7) ≤ inf */ class LinearProgramBoundingBox1 : public ::testing::Test { public: LinearProgramBoundingBox1(); protected: std::unique_ptr<MathematicalProgram> prog_; Eigen::Matrix<symbolic::Variable, 8, 1> x_; }; /** * A simple linear program. * min x(0) + 2x(1) + 3x(2) * s.t 2x(0) + 3x(1) + x(2) = 1 * -2x(2) + x(0) ≤ -1 * 2x(1) + x(0) ≥ -2 * -2 ≤ -x(0) + 3x(2) ≤ 3 * x(0) + x(1) + 4x(2) = 3 * The optimal solution is x = (5 / 13, -2 / 13, 9 / 13). The optimal cost is * (28 / 13). */ class CsdpLinearProgram2 : public ::testing::Test { public: CsdpLinearProgram2(); protected: std::unique_ptr<MathematicalProgram> prog_; Vector3<symbolic::Variable> x_; }; /** * A linear program with both linear (in)equality constraints and bounding box * constraint. * max 2x(0) + 3x(1) + 4x(2) + 3 * s.t x(0) + 2x(1) + 3x(2) = 3 * 2x(0) - x(2) ≥ -1 * x(1) - 3x(2) ≤ 5 * -4 ≤ x(0) + x(2) ≤ 9 * -1 ≤ x(0) ≤ 10 * x(1) ≤ 8 * The optimal solution is (10, -2/3, -17/9), the optimal cost is 121 / 9 */ class CsdpLinearProgram3 : public ::testing::Test { public: CsdpLinearProgram3(); protected: std::unique_ptr<MathematicalProgram> prog_; Vector3<symbolic::Variable> x_; }; /** * A trivial SDP * max X1(0, 1) + X1(1, 2) * s.t X1 ∈ ℝ³ˣ³ is psd * X1(0, 0) + X1(1, 1) + X1(2, 2) = 1 * X1(0, 1) + X1(1, 2) - 2 * X1(0, 2) ≤ 0 */ class TrivialSDP1 : public ::testing::Test { public: TrivialSDP1(); protected: std::unique_ptr<MathematicalProgram> prog_; Matrix3<symbolic::Variable> X1_; }; /** * max y * X1 ∈ ℝ²ˣ² is psd * I + F1 * y + F2 * X1(0, 0) is psd. * X1(0, 0) + 2 * X1(1, 1) + 3 * y = 1 * where F1 = [1 2; 2 3], F2 = [2 0; 0 4] * The optimal solution is X1 = [0 0; 0 0], y = 1 / 3, The optimal cost is 1/3. */ class TrivialSDP2 : public ::testing::Test { public: TrivialSDP2(); protected: std::unique_ptr<MathematicalProgram> prog_; Matrix2<symbolic::Variable> X1_; symbolic::Variable y_; }; /** * Test a problem with LorentzConeConstraint * max x(0) * s.t 2x(0) + 1 >= sqrt((3x(1)+2)² + (x(2)+x(0)+3)²) * x(0) + x(1) + x(2) = 10 * x(1) >= 0 * x(2) >= 0 * The optimal solution is (10, 0, 0). */ class TrivialSOCP1 : public ::testing::Test { public: TrivialSOCP1(); protected: std::unique_ptr<MathematicalProgram> prog_; Vector3<symbolic::Variable> x_; }; /** * max x(1) * s.t x(0) + 2 >= sqrt((x(0) + x(1) + 1)² + (x(0) - x(1) + 1)²) * The optimal solution is (0, 1) */ class TrivialSOCP2 : public ::testing::Test { public: TrivialSOCP2(); protected: std::unique_ptr<MathematicalProgram> prog_; Vector2<symbolic::Variable> x_; }; /** * max -x(1) * s.t (2x(0) + 2)(3x(1) + 4) >= sqrt((x(0) + 2)² + (3x(0) + x(1) + 1)²) * 2x(0) + 2 >= 0 * 3x(1) + 4 >= 0 * The optimal solution is at (-0.1, 2 - sqrt(7.1)) */ class TrivialSOCP3 : public ::testing::Test { public: TrivialSOCP3(); protected: std::unique_ptr<MathematicalProgram> prog_; Vector2<symbolic::Variable> x_; }; } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/non_convex_optimization_util_test.cc
#include "drake/solvers/non_convex_optimization_util.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/symbolic_test_util.h" #include "drake/solvers/solve.h" namespace drake { using symbolic::test::ExprEqual; using symbolic::test::FormulaEqual; using symbolic::test::PolynomialEqual; namespace solvers { namespace { GTEST_TEST(DecomposeNonConvexQuadraticForm, Test0) { // Decomposes a PSD matrix Q. This should yield Q1 = Q and Q2 = 0. Eigen::Matrix3d Q1, Q2; Eigen::Matrix3d Q = Eigen::Matrix3d::Identity(); std::tie(Q1, Q2) = DecomposeNonConvexQuadraticForm(Q); EXPECT_TRUE(CompareMatrices(Q1, Q, 1E-5, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(Q2, Eigen::Matrix3d::Zero(), 1E-5, MatrixCompareType::absolute)); } GTEST_TEST(DecomposeNonConvexQuadraticForm, Test1) { // Decomposes a negative definite matrix Q. This should yield Q1 = 0, and Q2 = // -Q. Eigen::Matrix3d Q1, Q2; Eigen::Matrix3d Q = -Eigen::Matrix3d::Identity(); std::tie(Q1, Q2) = DecomposeNonConvexQuadraticForm(Q); EXPECT_TRUE(CompareMatrices(Q1, Eigen::Matrix3d::Zero(), 1E-5, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(Q2, -Q, 1E-5, MatrixCompareType::absolute)); } GTEST_TEST(DecomposeNonConvexQuadraticForm, Test2) { // Decomposes an indefinite matrix Q, [0, 1; 1 0]. // This should yield Q1 = [1 1; 1 1]/2, Q2 = [1 -1; -1 1]/2. Eigen::Matrix2d Q1, Q2; Eigen::Matrix2d Q; Q << 0, 1, 1, 0; std::tie(Q1, Q2) = DecomposeNonConvexQuadraticForm(Q); Eigen::Matrix2d Q1_expected, Q2_expected; Q1_expected << 1.0 / 2, 1.0 / 2, 1.0 / 2, 1.0 / 2; Q2_expected << 1.0 / 2, -1.0 / 2, -1.0 / 2, 1.0 / 2; EXPECT_TRUE( CompareMatrices(Q1, Q1_expected, 1E-5, MatrixCompareType::absolute)); EXPECT_TRUE( CompareMatrices(Q2, Q2_expected, 1E-5, MatrixCompareType::absolute)); // Decomposes another indefinite matrix Q, [0, 2; 0, 0], this matrix has the // same quadratic form as [0, 1; 1 0], so it should give the same Q1 and Q2. Q << 0, 2, 0, 0; std::tie(Q1, Q2) = DecomposeNonConvexQuadraticForm(Q); EXPECT_TRUE( CompareMatrices(Q1, Q1_expected, 1E-5, MatrixCompareType::absolute)); EXPECT_TRUE( CompareMatrices(Q2, Q2_expected, 1E-5, MatrixCompareType::absolute)); } GTEST_TEST(DecomposeNonConvexQuadraticForm, Test3) { // Decomposes an indefinite matrix Q = [1 3; 1, 1]. // This should yield Q1 = [1.5 1.5; 1.5 1.5], Q2 = [0.5 -0.5; -0.5 0.5] Eigen::Matrix2d Q1, Q2; Eigen::Matrix2d Q; Q << 1, 3, 1, 1; std::tie(Q1, Q2) = DecomposeNonConvexQuadraticForm(Q); Eigen::Matrix2d Q1_expected, Q2_expected; Q1_expected << 1.5, 1.5, 1.5, 1.5; Q2_expected << 0.5, -0.5, -0.5, 0.5; EXPECT_TRUE( CompareMatrices(Q1, Q1_expected, 1E-5, MatrixCompareType::absolute)); EXPECT_TRUE( CompareMatrices(Q2, Q2_expected, 1E-5, MatrixCompareType::absolute)); } void CheckRelaxNonConvexQuadraticConstraintInTrustRegion( MathematicalProgram* prog, const Eigen::Ref<const VectorXDecisionVariable>& x, const Eigen::Ref<const Eigen::MatrixXd>& Q1, const Eigen::Ref<const Eigen::MatrixXd>& Q2, const Eigen::Ref<const Eigen::VectorXd>& p, const Eigen::Ref<const VectorXDecisionVariable>& y, double lower_bound, double upper_bound, const Eigen::Ref<const Eigen::VectorXd>& linearization_point, double trust_region_gap) { const auto& x0 = linearization_point; const auto result = AddRelaxNonConvexQuadraticConstraintInTrustRegion( prog, x, Q1, Q2, y, p, lower_bound, upper_bound, linearization_point, trust_region_gap); Binding<LinearConstraint> linear_constraint = std::get<0>(result); EXPECT_EQ(std::get<1>(result).size(), 2); Binding<RotatedLorentzConeConstraint> rotated_lorentz_cone_constraint1 = std::get<1>(result)[0]; Binding<RotatedLorentzConeConstraint> rotated_lorentz_cone_constraint2 = std::get<1>(result)[1]; VectorDecisionVariable<2> z = std::get<2>(result); Vector3<symbolic::Expression> linear_constraint_expr = linear_constraint.evaluator()->GetDenseA() * linear_constraint.variables(); Vector3<symbolic::Expression> linear_constraint_expr_expected; linear_constraint_expr_expected << z(0) - z(1) + p.dot(y), z(0) - 2 * x0.dot(Q1 * x), z(1) - 2 * x0.dot(Q2 * x); const double poly_tol{1E-10}; for (int i = 0; i < 3; ++i) { EXPECT_TRUE(PolynomialEqual( symbolic::Polynomial(linear_constraint_expr(i)), symbolic::Polynomial(linear_constraint_expr_expected(i)), poly_tol) || PolynomialEqual( symbolic::Polynomial(linear_constraint_expr(i)), symbolic::Polynomial(-linear_constraint_expr_expected(i)), poly_tol)); } const VectorX<symbolic::Expression> y_lorentz1 = rotated_lorentz_cone_constraint1.evaluator()->A() * rotated_lorentz_cone_constraint1.variables() + rotated_lorentz_cone_constraint1.evaluator()->b(); EXPECT_TRUE( PolynomialEqual(symbolic::Polynomial(y_lorentz1(0) * y_lorentz1(1)), symbolic::Polynomial(z(0)), poly_tol)); EXPECT_TRUE( PolynomialEqual(symbolic::Polynomial( y_lorentz1.tail(y_lorentz1.rows() - 2).squaredNorm()), symbolic::Polynomial(x.dot(Q1 * x)), poly_tol)); const VectorX<symbolic::Expression> y_lorentz2 = rotated_lorentz_cone_constraint2.evaluator()->A() * rotated_lorentz_cone_constraint2.variables() + rotated_lorentz_cone_constraint2.evaluator()->b(); EXPECT_TRUE( PolynomialEqual(symbolic::Polynomial(y_lorentz2(0) * y_lorentz2(1)), symbolic::Polynomial(z(1)), poly_tol)); EXPECT_TRUE( PolynomialEqual(symbolic::Polynomial( y_lorentz2.tail(y_lorentz2.rows() - 2).squaredNorm()), symbolic::Polynomial(x.dot(Q2 * x)), poly_tol)); } Eigen::Matrix<double, 2, 10> GenerateCostDirection() { Eigen::Matrix<double, 2, 10> c; // clang-format off c << 1, 1, 1, 0, 0, 0, -1, -1, -1, 1, 0, -1, 1, 1, 0, -1, 1, 0, -1, 2; // clang-format on return c; } class TestRelaxNonConvexQuadraticConstraintInTrustRegion : public ::testing::Test { public: TestRelaxNonConvexQuadraticConstraintInTrustRegion() : prog_{}, x_{prog_.NewContinuousVariables<2>()} {} protected: MathematicalProgram prog_; VectorDecisionVariable<2> x_; }; TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, Test0) { Eigen::Matrix2d Q1 = Eigen::Matrix2d::Identity(); Eigen::Matrix2d Q2; Q2 << 1, 0.2, 0.2, 1; Eigen::Vector2d p(1, 2); const double lower_bound{0}; const double upper_bound{0.1}; const Eigen::Vector2d linearization_point(1, 2); const double trust_region_gap{1}; CheckRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Q1, Q2, p, x_, lower_bound, upper_bound, linearization_point, trust_region_gap); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, Test1) { Eigen::Matrix2d Q1; Q1 << 1, 0.2, 0.2, 2; Eigen::Matrix2d Q2; Q2 << 1, 0.3, 0.3, 4; Eigen::Vector2d p(3, 2); const double lower_bound{-1}; const double upper_bound{-0.1}; const Eigen::Vector2d linearization_point(-1, 2); const double trust_region_gap{1}; CheckRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Q1, Q2, p, x_, lower_bound, upper_bound, linearization_point, trust_region_gap); // Check the case in which the variable y in the linear term is not the same // as the variable x in the quadratic term. auto x_prime = prog_.NewContinuousVariables<2>(); const Eigen::Vector3d p_prime(3, 2, 1); VectorDecisionVariable<3> y{x_(0), x_prime(0), x_prime(1)}; CheckRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Q1, Q2, p_prime, y, lower_bound, upper_bound, linearization_point, trust_region_gap); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, TestRuntimeError) { Eigen::Matrix2d non_positive_Q; non_positive_Q << 1, 1.5, 1.5, 1; Eigen::Matrix2d positive_Q; positive_Q << 1, 0.2, 0.2, 1; // Q1 not being positive semidefinite. EXPECT_THROW(AddRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, non_positive_Q, positive_Q, x_, Eigen::Vector2d(1, 0), -1, 0.1, Eigen::Vector2d(1, 2), 1), std::runtime_error); // Q2 not being positive semidefinite. EXPECT_THROW(AddRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, positive_Q, non_positive_Q, x_, Eigen::Vector2d(1, 0), -1, 0.1, Eigen::Vector2d(1, 2), 1), std::runtime_error); // Negative trust region gap. EXPECT_THROW(AddRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, positive_Q, positive_Q, x_, Eigen::Vector2d(1, 0), -1, 0.1, Eigen::Vector2d(1, 2), -0.1), std::runtime_error); } void SolveRelaxNonConvexQuadraticConstraintInTrustRegion( MathematicalProgram* prog, const Eigen::Ref<const VectorXDecisionVariable>& x, const Eigen::Ref<const Eigen::MatrixXd>& Q1, const Eigen::Ref<const Eigen::MatrixXd>& Q2, const Eigen::Ref<const VectorXDecisionVariable>& y, const Eigen::Ref<const Eigen::VectorXd>& p, double lower_bound, double upper_bound, const Eigen::Ref<const Eigen::VectorXd>& x0, double trust_region_gap, const Eigen::Ref<const Eigen::MatrixXd>& c) { const auto relaxed_constraints = AddRelaxNonConvexQuadraticConstraintInTrustRegion( prog, x, Q1, Q2, y, p, lower_bound, upper_bound, x0, trust_region_gap); VectorDecisionVariable<2> z = std::get<2>(relaxed_constraints); auto cost = prog->AddLinearCost(x.cast<symbolic::Expression>().sum()); for (int i = 0; i < c.cols(); ++i) { cost.evaluator()->UpdateCoefficients(c.col(i).transpose()); auto result = Solve(*prog); EXPECT_TRUE(result.is_success()); auto x_sol = result.GetSolution(x); auto y_sol = result.GetSolution(y); auto z_sol = result.GetSolution(z); const double check_tol{1E-5}; EXPECT_GE(z_sol(0) - z_sol(1) + p.dot(y_sol), lower_bound - check_tol); EXPECT_LE(z_sol(0) - z_sol(1) + p.dot(y_sol), upper_bound + check_tol); EXPECT_LE(z_sol(0), 2 * x0.dot(Q1 * x_sol) - x0.dot(Q1 * x0) + trust_region_gap + check_tol); EXPECT_LE(z_sol(1), 2 * x0.dot(Q2 * x_sol) - x0.dot(Q2 * x0) + trust_region_gap + check_tol); EXPECT_GE(z_sol(0), x_sol.dot(Q1 * x_sol) - check_tol); EXPECT_GE(z_sol(1), x_sol.dot(Q2 * x_sol) - check_tol); const double original_constraint_value{x_sol.dot((Q1 - Q2) * x_sol) + p.dot(y_sol)}; EXPECT_LE(original_constraint_value, upper_bound + trust_region_gap + check_tol); EXPECT_GE(original_constraint_value, lower_bound - trust_region_gap - check_tol); } } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, SolveProblem0) { // For a problem // max c'x // s.t 1 <= x(0)² - x(1)² <= 2 // The relaxation of the constraint is // 1 <= z(0) - z(1) <= 2 // z(0) <= 2x₀(0)x(0) - x₀(0)² + d // z(1) <= 2x₀(1)x(1) - x₀(1)² + d // z(0) >= x(0)² // z(1) >= x(1)² Eigen::Matrix2d Q1, Q2; Q1 << 1, 0, 0, 0; Q2 << 0, 0, 0, 1; // We linearize it about x = (2, 1). If we set the violation d to 0.5, within // the trust region, there should be a solution. const double trust_region_gap{0.5}; const double lb{1}; const double ub{2}; const auto c = GenerateCostDirection(); SolveRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Q1, Q2, x_, Eigen::Vector2d::Zero(), lb, ub, Eigen::Vector2d(2, 1), trust_region_gap, c); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, SolveProblem1) { Eigen::Matrix2d Q1, Q2; Q1 << 1, 0, 0, 2; Q2 << 2, 0.1, 0.1, 1; const double trust_region_gap{0.5}; const double lb{1}; const double ub{2}; const auto c = GenerateCostDirection(); SolveRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Q1, Q2, x_, Eigen::Vector2d(1, 3), lb, ub, Eigen::Vector2d(2, 1), trust_region_gap, c); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, SolveProblem2) { // The variable y in the linear term is not the same as the variable x in the // quadratic term. Eigen::Matrix2d Q1, Q2; Q1 << 1, 0, 0, 2; Q2 << 2, 0.1, 0.1, 1; const double trust_region_gap{0.5}; const double lb{1}; const double ub{2}; const auto c = GenerateCostDirection(); auto x_prime = prog_.NewContinuousVariables<2>(); VectorDecisionVariable<3> y{x_(0), x_prime(0), x_prime(1)}; prog_.AddBoundingBoxConstraint(-1, 1, x_prime); SolveRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Q1, Q2, y, Eigen::Vector3d(1, 2, 3), lb, ub, Eigen::Vector2d(2, 1), trust_region_gap, c); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, SolveInfeasibleProblem0) { // The non-convex problem is infeasible. With small relaxation gap, the // relaxed problem should also be infeasible. // x(0) = 0 // x(0)² - x(1)² = 1 prog_.AddBoundingBoxConstraint(0, 0, x_(0)); const Eigen::Matrix2d Q1 = Eigen::Vector2d(1, 0).asDiagonal(); const Eigen::Matrix2d Q2 = Eigen::Vector2d(0, 1).asDiagonal(); AddRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Q1, Q2, x_, Eigen::Vector2d::Zero(), 1, 1, Eigen::Vector2d(1, 0), 0.1); auto result = Solve(prog_).get_solution_result(); EXPECT_TRUE(result == SolutionResult::kInfeasibleOrUnbounded || result == SolutionResult::kInfeasibleConstraints); } GTEST_TEST(TestRelaxNonConvexQuadraticConstraintInTrustRegionInfeasible, SolveInfeasibleProblem1) { // The non-convex problem is feasible, but the solution is far away from the // linearization point, so the relaxed problem is infeasible within the trust // region. // x(0)² - 2 * x(1)² = 1 // x(0) >= x(1) + 2 // There is not a solution near x = (-5, 3) MathematicalProgram prog1; auto x1 = prog1.NewContinuousVariables<2>(); prog1.AddLinearConstraint(x1(0) >= x1(1) + 2); Eigen::Matrix2d Q1 = Eigen::Vector2d(1, 0).asDiagonal(); Eigen::Matrix2d Q2 = Eigen::Vector2d(0, 2).asDiagonal(); const auto relaxed_constraint = AddRelaxNonConvexQuadraticConstraintInTrustRegion( &prog1, x1, Q1, Q2, x1, Eigen::Vector2d::Zero(), 1, 1, Eigen::Vector2d(-5, -3), 0.1); auto result = Solve(prog1).get_solution_result(); EXPECT_TRUE(result == SolutionResult::kInfeasibleConstraints || result == SolutionResult::kInfeasibleOrUnbounded); // If we linearize the problem at about (7, -5), then the relaxed problem has // a solution around the linearization point. MathematicalProgram prog2; auto x2 = prog2.NewContinuousVariables<2>(); prog2.AddLinearConstraint(x2(0) >= x2(1) + 2); const auto c = GenerateCostDirection(); SolveRelaxNonConvexQuadraticConstraintInTrustRegion( &prog2, x2, Q1, Q2, x2, Eigen::Vector2d::Zero(), 1, 1, Eigen::Vector2d(7, -5), 1.5, c); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, ZeroQ1Q2) { // Should throw a runtime error. // Both Q1 and Q2 are 0 EXPECT_THROW(AddRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Eigen::Matrix2d::Zero(), Eigen::Matrix2d::Zero(), x_, Eigen::Vector2d(1, 2), 1, 2, Eigen::Vector2d(2, 1), 1), std::runtime_error); // Q1 is zero and upper_bound is infinity. EXPECT_THROW( AddRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Eigen::Matrix2d::Zero(), Eigen::Matrix2d::Identity(), x_, Eigen::Vector2d(1, 2), 1, std::numeric_limits<double>::infinity(), Eigen::Vector2d(2, 1), 1), std::runtime_error); // Q2 is zero and lower_bound is -infinity. EXPECT_THROW( AddRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Eigen::Matrix2d::Identity(), Eigen::Matrix2d::Zero(), x_, Eigen::Vector2d(1, 2), -std::numeric_limits<double>::infinity(), 1, Eigen::Vector2d(2, 1), 1), std::runtime_error); // lower_bound is larger than upper_bound EXPECT_THROW(AddRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Eigen::Matrix2d::Identity(), 0.1 * Eigen::Matrix2d::Identity(), x_, Eigen::Vector2d(1, 2), 2, 1, Eigen::Vector2d(2, 1), 1), std::runtime_error); } void SolveRelaxNonConvexQuadraticConstraintInTrustRegionWithZeroQ1orQ2( MathematicalProgram* prog, const Eigen::Ref<const VectorXDecisionVariable>& x, const Eigen::Ref<const Eigen::MatrixXd>& Q, const Eigen::Ref<const VectorXDecisionVariable>& y, const Eigen::Ref<const Eigen::VectorXd>& p, double lb, double ub, const Eigen::Ref<const Eigen::VectorXd>& x0, double trust_region_gap, bool Q1_is_zero, const Eigen::Ref<const Eigen::MatrixXd>& c) { Eigen::MatrixXd Q1, Q2; if (Q1_is_zero) { Q1 = Eigen::MatrixXd::Zero(x.rows(), x.rows()); Q2 = Q; } else { Q1 = Q; Q2 = Eigen::MatrixXd::Zero(x.rows(), x.rows()); } const auto relaxed_constraints = AddRelaxNonConvexQuadraticConstraintInTrustRegion( prog, x, Q1, Q2, y, p, lb, ub, x0, trust_region_gap); const Binding<LinearConstraint> linear_constraint = std::get<0>(relaxed_constraints); EXPECT_EQ(std::get<1>(relaxed_constraints).size(), 1); const Binding<RotatedLorentzConeConstraint> lorentz_cone1 = std::get<1>(relaxed_constraints)[0]; const VectorDecisionVariable<1> z = std::get<2>(relaxed_constraints); Vector2<symbolic::Expression> linear_expr, linear_expr_expected; linear_expr = linear_constraint.evaluator()->GetDenseA() * linear_constraint.variables(); Eigen::Vector2d linear_lb_expected, linear_ub_expected; linear_lb_expected << x0.dot(Q * x0) - trust_region_gap, lb; linear_ub_expected << std::numeric_limits<double>::infinity(), ub; if (Q1_is_zero) { linear_expr_expected << 2 * x0.dot(Q2 * x) - z(0), p.dot(y) - z(0); } else { linear_expr_expected << 2 * x0.dot(Q1 * x) - z(0), p.dot(y) + z(0); } EXPECT_TRUE(CompareMatrices(linear_constraint.evaluator()->lower_bound(), linear_lb_expected, 1E-15, MatrixCompareType::absolute)); EXPECT_TRUE(CompareMatrices(linear_constraint.evaluator()->upper_bound(), linear_ub_expected, 1E-15, MatrixCompareType::absolute)); const double poly_tol{1E-10}; for (int i = 0; i < 2; ++i) { EXPECT_TRUE(PolynomialEqual(symbolic::Polynomial(linear_expr(i)), symbolic::Polynomial(linear_expr_expected(i)), poly_tol)); } VectorX<symbolic::Expression> y1 = lorentz_cone1.evaluator()->A() * lorentz_cone1.variables() + lorentz_cone1.evaluator()->b(); EXPECT_TRUE(PolynomialEqual(symbolic::Polynomial(y1(0) * y1(1)), symbolic::Polynomial(z(0)), poly_tol)); EXPECT_TRUE(PolynomialEqual( symbolic::Polynomial(y1.tail(y1.rows() - 2).squaredNorm()), symbolic::Polynomial(x.dot(Q * x)), poly_tol)); auto cost = prog->AddLinearCost(x.cast<symbolic::Expression>().sum()); const double z_sign = Q1_is_zero ? -1 : 1; const double Q_sign = Q1_is_zero ? -1 : 1; for (int i = 0; i < c.cols(); ++i) { cost.evaluator()->UpdateCoefficients(c.col(i).transpose()); auto result = Solve(*prog); EXPECT_TRUE(result.is_success()); const double z_sol = result.GetSolution(z(0)); const Eigen::Vector2d x_sol = result.GetSolution(x); const Eigen::VectorXd y_sol = result.GetSolution(y); const double tol{1E-5}; EXPECT_GE(z_sign * z_sol + p.dot(y_sol), lb - tol); EXPECT_LE(z_sign * z_sol + p.dot(y_sol), ub + tol); EXPECT_LE(z_sol, 2 * x0.dot(Q * x_sol) - x0.dot(Q * x0) + trust_region_gap + tol); EXPECT_GE(z_sol, x_sol.dot(Q * x_sol) - tol); const double original_constraint_val{x_sol.dot(Q_sign * Q * x_sol) + p.dot(y_sol)}; EXPECT_GE(original_constraint_val, lb - trust_region_gap - tol); EXPECT_LE(original_constraint_val, ub + trust_region_gap + tol); } } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, ZeroQ1Test0) { // -x(0)² - x(1)² - x(0)x(1) + 2*x(0) <= 1 Eigen::Matrix2d Q; Q << 1, 0.5, 0.5, 1; const auto c = GenerateCostDirection(); SolveRelaxNonConvexQuadraticConstraintInTrustRegionWithZeroQ1orQ2( &prog_, x_, Q, x_, Eigen::Vector2d(2, 0), -std::numeric_limits<double>::infinity(), 1, Eigen::Vector2d(1, 2), 1, true, c); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, ZeroQ1Test1) { // -1 <= -x(0)² - 4x(1)² - 2x(0)x(1) + 3x(0) + 2x(1) <= 4 Eigen::Matrix2d Q; Q << 1, 1, 1, 4; const auto c = GenerateCostDirection(); SolveRelaxNonConvexQuadraticConstraintInTrustRegionWithZeroQ1orQ2( &prog_, x_, Q, x_, Eigen::Vector2d(3, 2), -1, 4, Eigen::Vector2d(1, 0), 1, true, c); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, ZeroQ1Test2) { // The original non-convex problem is infeasible. // -4 <= -x(0)² - x(1)² <= -1 // x(0) + x(1) >= 10 Eigen::Matrix2d Q2; Q2 << 1, 0, 0, 1; prog_.AddLinearConstraint(x_(0) + x_(1) >= 10); AddRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Eigen::Matrix2d::Zero(), Q2, x_, Eigen::Vector2d::Zero(), -4, -1, Eigen::Vector2d(0, 1), 1); auto result = Solve(prog_).get_solution_result(); EXPECT_TRUE(result == SolutionResult::kInfeasibleOrUnbounded || result == SolutionResult::kInfeasibleConstraints); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, ZeroQ1Test3) { // The variable y in the linear term is not the same as the variable x in the // quadratic term. // -1 <= -x(0)² - 4x(1)² - 2x(0)x(1) + 2x(1) + 3z(0) + 2z(1) <= 4 // -1 <= z(0) <= 1 // -1 <= z(1) <= 1 auto z = prog_.NewContinuousVariables<2>(); prog_.AddBoundingBoxConstraint(-1, 1, z); Eigen::Matrix2d Q; Q << 1, 1, 1, 4; VectorDecisionVariable<3> y(x_(1), z(0), z(1)); const auto c = GenerateCostDirection(); SolveRelaxNonConvexQuadraticConstraintInTrustRegionWithZeroQ1orQ2( &prog_, x_, Q, y, Eigen::Vector3d(2, 3, 2), -1, 4, Eigen::Vector2d(1, 0), 1, true, c); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, ZeroQ2Test0) { // 1 <= x(0)² + x(1)² + x(0)x(1) + 2x(0) <= 4 Eigen::Matrix2d Q; Q << 1, 0.5, 0.5, 1; const auto c = GenerateCostDirection(); SolveRelaxNonConvexQuadraticConstraintInTrustRegionWithZeroQ1orQ2( &prog_, x_, Q, x_, Eigen::Vector2d(1, 0), 1, 4, Eigen::Vector2d(1, -1), 0.5, false, c); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, ZeroQ2Test1) { // -1 <= x(0)² + 3x(1)² + x(0)x(1) + 2x(0) + 4x(1) <= 4 Eigen::Matrix2d Q; Q << 1, 0.5, 0.5, 3; const auto c = GenerateCostDirection(); SolveRelaxNonConvexQuadraticConstraintInTrustRegionWithZeroQ1orQ2( &prog_, x_, Q, x_, Eigen::Vector2d(2, 4), 1, 4, Eigen::Vector2d(1, -1), 0.5, false, c); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, ZeroQ2Test2) { // The original non-convex problem is infeasible. // 1 <= x(0)² + x(1)² <= 4 // x(0) + x(1) >= 10 Eigen::Matrix2d Q1; Q1 << 1, 0, 0, 1; prog_.AddLinearConstraint(x_(0) + x_(1) >= 10); AddRelaxNonConvexQuadraticConstraintInTrustRegion( &prog_, x_, Q1, Eigen::Matrix2d::Zero(), x_, Eigen::Vector2d::Zero(), 1, 4, Eigen::Vector2d(0, 1), 1); auto result = Solve(prog_).get_solution_result(); EXPECT_TRUE(result == SolutionResult::kInfeasibleOrUnbounded || result == SolutionResult::kInfeasibleConstraints); } TEST_F(TestRelaxNonConvexQuadraticConstraintInTrustRegion, ZeroQ2Test3) { // The variable y in the linear term is not the same as the variable x in the // quadratic term. // -1 <= x(0)² + 3x(1)² + x(0)x(1) + 2x(0) + 4x(1) + 3y(0) <= 4 // -1 <= y(0) <= 1 Eigen::Matrix2d Q; Q << 1, 0.5, 0.5, 3; const auto c = GenerateCostDirection(); auto x_prime = prog_.NewContinuousVariables<1>(); const VectorDecisionVariable<3> y(x_(0), x_(1), x_prime(0)); SolveRelaxNonConvexQuadraticConstraintInTrustRegionWithZeroQ1orQ2( &prog_, x_, Q, y, Eigen::Vector3d(2, 4, 3), 1, 4, Eigen::Vector2d(1, -1), 0.5, false, c); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/optimization_examples.h
#pragma once #include <limits> #include <memory> #include <optional> #include <ostream> #include <set> #include <tuple> #include <vector> #include <gtest/gtest.h> #include "drake/common/drake_copyable.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solver_interface.h" #include "drake/solvers/solver_type.h" namespace drake { namespace solvers { namespace test { enum class CostForm { kGeneric = 0, kNonSymbolic = 1, kSymbolic = 2, }; std::ostream& operator<<(std::ostream& os, CostForm value); enum class ConstraintForm { kGeneric = 0, kNonSymbolic = 1, kSymbolic = 2, kFormula = 3, }; std::ostream& operator<<(std::ostream& os, ConstraintForm value); void ExpectSolutionCostAccurate(const MathematicalProgram& prog, const MathematicalProgramResult& result, double tol); class OptimizationProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(OptimizationProgram) OptimizationProgram(CostForm cost_form, ConstraintForm constraint_form); virtual ~OptimizationProgram() {} CostForm cost_form() const { return cost_form_; } ConstraintForm constraint_form() const { return constraint_form_; } MathematicalProgram* prog() const { return prog_.get(); } virtual const std::optional<Eigen::VectorXd>& initial_guess() const { return initial_guess_; } virtual void CheckSolution(const MathematicalProgramResult& result) const = 0; double GetSolverSolutionDefaultCompareTolerance(SolverId solver_id) const; void RunProblem(SolverInterface* solver); private: CostForm cost_form_; ConstraintForm constraint_form_; std::unique_ptr<MathematicalProgram> prog_; std::optional<Eigen::VectorXd> initial_guess_; }; /** * Simple example x = b */ class LinearSystemExample1 { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearSystemExample1) LinearSystemExample1(); virtual ~LinearSystemExample1() {} MathematicalProgram* prog() const { return prog_.get(); } const VectorDecisionVariable<4>& x() const { return x_; } const Eigen::Vector4d b() const { return b_; } const Eigen::Vector4d& initial_guess() const { return initial_guess_; } std::shared_ptr<LinearEqualityConstraint> con() const { return con_; } virtual void CheckSolution(const MathematicalProgramResult& result) const; protected: double tol() const { return 1E-10; } private: std::unique_ptr<MathematicalProgram> prog_; VectorDecisionVariable<4> x_; Eigen::Vector4d initial_guess_; Eigen::Vector4d b_; std::shared_ptr<LinearEqualityConstraint> con_; }; /** * Simple linear system * x = b * 2 * y(0) = b(0) * 2 * y(1) = b(1) */ class LinearSystemExample2 : public LinearSystemExample1 { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearSystemExample2) LinearSystemExample2(); ~LinearSystemExample2() override {} Vector6<double> initial_guess() const { return Vector6<double>::Zero(); } VectorDecisionVariable<2> y() const { return y_; } void CheckSolution(const MathematicalProgramResult& result) const override; private: VectorDecisionVariable<2> y_; }; /** * Simple linear system * 3 * x = b * 2 * y(0) = b(0) * 2 * y(1) = b(1) */ class LinearSystemExample3 : public LinearSystemExample2 { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearSystemExample3) LinearSystemExample3(); ~LinearSystemExample3() override {} void CheckSolution(const MathematicalProgramResult& result) const override; }; /** * For a stable linear system ẋ = A x, find its Lyapunov function by solving * the Lyapunov equality on the symmetric matrix X * Aᵀ * X + X * A = -E */ class LinearMatrixEqualityExample { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LinearMatrixEqualityExample) LinearMatrixEqualityExample(); MathematicalProgram* prog() const { return prog_.get(); } void CheckSolution(const MathematicalProgramResult& result) const; private: std::unique_ptr<MathematicalProgram> prog_; MatrixDecisionVariable<3, 3> X_; Eigen::Matrix3d A_; }; /// This test comes from Section 2.2 of /// Handbook of Test Problems in Local and Global Optimization. /// © 1999 /// ISBN 978-1-4757-3040-1 class NonConvexQPproblem1 { /// This is a non-convex quadratic program with inequality constraints. /// We choose to add the cost and constraints through different forms, /// to test different solvers, and whether MathematicalProgram can parse /// constraints in different forms. public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(NonConvexQPproblem1) static std::vector<CostForm> cost_forms() { std::vector<CostForm> costs{CostForm::kGeneric, CostForm::kNonSymbolic}; return costs; } static ::std::vector<ConstraintForm> constraint_forms() { std::vector<ConstraintForm> cnstr{ConstraintForm::kSymbolic, ConstraintForm::kNonSymbolic}; return cnstr; } NonConvexQPproblem1(CostForm cost_form, ConstraintForm constraint_form); MathematicalProgram* prog() const { return prog_.get(); } Eigen::Matrix<double, 5, 1> initial_guess() const; void CheckSolution(const MathematicalProgramResult& result) const; private: class TestProblem1Cost { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(TestProblem1Cost) TestProblem1Cost() = default; static size_t numInputs() { return 5; } static size_t numOutputs() { return 1; } template <typename ScalarType> void eval(internal::VecIn<ScalarType> const& x, internal::VecOut<ScalarType>* y) const { DRAKE_ASSERT(static_cast<size_t>(x.rows()) == numInputs()); DRAKE_ASSERT(static_cast<size_t>(y->rows()) == numOutputs()); (*y)(0) = (-50.0 * x(0) * x(0)) + (42 * x(0)) - (50.0 * x(1) * x(1)) + (44 * x(1)) - (50.0 * x(2) * x(2)) + (45 * x(2)) - (50.0 * x(3) * x(3)) + (47 * x(3)) - (50.0 * x(4) * x(4)) + (47.5 * x(4)); } }; void AddConstraint(); void AddSymbolicConstraint(); void AddQuadraticCost(); std::unique_ptr<MathematicalProgram> prog_; VectorDecisionVariable<5> x_; Eigen::Matrix<double, 5, 1> x_expected_; }; /// This test comes from Section 2.3 of /// Handbook of Test Problems in Local and Global Optimization. /// © 1999 /// ISBN 978-1-4757-3040-1 class NonConvexQPproblem2 { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(NonConvexQPproblem2) static std::vector<CostForm> cost_forms() { std::vector<CostForm> costs{CostForm::kGeneric, CostForm::kNonSymbolic}; return costs; } static std::vector<ConstraintForm> constraint_forms() { std::vector<ConstraintForm> cnstr{ConstraintForm::kNonSymbolic, ConstraintForm::kSymbolic}; return cnstr; } NonConvexQPproblem2(CostForm cost_form, ConstraintForm constraint_form); Vector6<double> initial_guess() const; void CheckSolution(const MathematicalProgramResult& result) const; MathematicalProgram* prog() const { return prog_.get(); } private: class TestProblem2Cost { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(TestProblem2Cost) TestProblem2Cost() = default; static size_t numInputs() { return 6; } static size_t numOutputs() { return 1; } template <typename ScalarType> void eval(internal::VecIn<ScalarType> const& x, internal::VecOut<ScalarType>* y) const { DRAKE_ASSERT(static_cast<size_t>(x.rows()) == numInputs()); DRAKE_ASSERT(static_cast<size_t>(y->rows()) == numOutputs()); (*y)(0) = (-50.0 * x(0) * x(0)) + (-10.5 * x(0)) - (50.0 * x(1) * x(1)) + (-7.5 * x(1)) - (50.0 * x(2) * x(2)) + (-3.5 * x(2)) - (50.0 * x(3) * x(3)) + (-2.5 * x(3)) - (50.0 * x(4) * x(4)) + (-1.5 * x(4)) + (-10.0 * x(5)); } }; void AddQuadraticCost(); void AddNonSymbolicConstraint(); void AddSymbolicConstraint(); std::unique_ptr<MathematicalProgram> prog_; Eigen::Matrix<symbolic::Variable, 6, 1> x_; Vector6d x_expected_; }; /// This test comes from Section 3.4 of /// Handbook of Test Problems in Local and Global Optimization. /// © 1999 /// ISBN 978-1-4757-3040-1 class LowerBoundedProblem { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LowerBoundedProblem) static std::vector<ConstraintForm> constraint_forms() { std::vector<ConstraintForm> cnstr{ConstraintForm::kNonSymbolic, ConstraintForm::kSymbolic}; return cnstr; } explicit LowerBoundedProblem(ConstraintForm constraint_form); void CheckSolution(const MathematicalProgramResult& result) const; MathematicalProgram* prog() { return prog_.get(); } Vector6<double> initial_guess1() const; Vector6<double> initial_guess2() const; private: class LowerBoundTestCost { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(LowerBoundTestCost) LowerBoundTestCost() = default; static size_t numInputs() { return 6; } static size_t numOutputs() { return 1; } template <typename ScalarType> void eval(internal::VecIn<ScalarType> const& x, internal::VecOut<ScalarType>* y) const { DRAKE_ASSERT(static_cast<size_t>(x.rows()) == numInputs()); DRAKE_ASSERT(static_cast<size_t>(y->rows()) == numOutputs()); (*y)(0) = -25 * (x(0) - 2) * (x(0) - 2) + (x(1) - 2) * (x(1) - 2) - (x(2) - 1) * (x(2) - 1) - (x(3) - 4) * (x(3) - 4) - (x(4) - 1) * (x(4) - 1) - (x(5) - 4) * (x(5) - 4); } }; class LowerBoundTestConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(LowerBoundTestConstraint) LowerBoundTestConstraint(int i1, int i2) : Constraint( 1, Eigen::Dynamic, Vector1d::Constant(4), Vector1d::Constant(std::numeric_limits<double>::infinity())), i1_(i1), i2_(i2) {} protected: // For just these two types, implementing this locally is almost cleaner... void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { EvalImpl(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { // Check that the autodiff vector was initialized to the proper (minimal) // size. EXPECT_EQ(x.size(), x(0).derivatives().size()); EvalImpl(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&, VectorX<symbolic::Expression>*) const override { throw std::logic_error( "LowerBoundTestConstraint does not support symbolic evaluation."); } private: template <typename ScalarType> void EvalImpl( const Eigen::Ref<const Eigen::Matrix<ScalarType, Eigen::Dynamic, 1>>& x, Eigen::Matrix<ScalarType, Eigen::Dynamic, 1>* y) const { y->resize(1); (*y)(0) = (x(i1_) - 3) * (x(i1_) - 3) + x(i2_); } int i1_; int i2_; }; void AddSymbolicConstraint(); void AddNonSymbolicConstraint(); std::unique_ptr<MathematicalProgram> prog_; Eigen::Matrix<symbolic::Variable, 6, 1> x_; Vector6d x_expected_; }; /// gloptiPolyConstrainedMinimization /// @brief From section 5.8.2 of the gloptipoly3 documentation. /// /// Which is from section 3.5 in /// Handbook of Test Problems in Local and Global Optimization /// © 1999 /// ISBN 978-1-4757-3040-1 /// We deliberately duplicate the problem, with the same constraints and /// costs on decision variables x and y, so as to test out program works /// correctly with multiple decision variables. class GloptiPolyConstrainedMinimizationProblem { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GloptiPolyConstrainedMinimizationProblem) static std::vector<CostForm> cost_forms() { std::vector<CostForm> costs{CostForm::kGeneric, CostForm::kNonSymbolic, CostForm::kSymbolic}; return costs; } static std::vector<ConstraintForm> constraint_forms() { std::vector<ConstraintForm> cnstr{ConstraintForm::kNonSymbolic, ConstraintForm::kSymbolic}; return cnstr; } GloptiPolyConstrainedMinimizationProblem(CostForm cost_form, ConstraintForm constraint_form); MathematicalProgram* prog() const { return prog_.get(); } void CheckSolution(const MathematicalProgramResult& result) const; Vector6<double> initial_guess() const; private: class GloptipolyConstrainedExampleCost { public: DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(GloptipolyConstrainedExampleCost) GloptipolyConstrainedExampleCost() = default; static size_t numInputs() { return 3; } static size_t numOutputs() { return 1; } template <typename ScalarType> void eval(internal::VecIn<ScalarType> const& x, internal::VecOut<ScalarType>* y) const { DRAKE_ASSERT(static_cast<size_t>(x.rows()) == numInputs()); DRAKE_ASSERT(static_cast<size_t>(y->rows()) == numOutputs()); (*y)(0) = -2 * x(0) + x(1) - x(2); } }; class GloptipolyConstrainedExampleConstraint : public Constraint { // Want to also support deriving directly from // constraint without going through Function. public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GloptipolyConstrainedExampleConstraint) GloptipolyConstrainedExampleConstraint() : Constraint( 1, 3, Vector1d::Constant(0), Vector1d::Constant(std::numeric_limits<double>::infinity())) {} protected: // For just these two types, implementing this locally is almost cleaner. void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { EvalImpl(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { EvalImpl(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&, VectorX<symbolic::Expression>*) const override { throw std::logic_error( "GloptipolyConstrainedExampleConstraint does not support symbolic " "evaluation."); } private: template <typename ScalarType> void EvalImpl( const Eigen::Ref<const Eigen::Matrix<ScalarType, Eigen::Dynamic, 1>>& x, Eigen::Matrix<ScalarType, Eigen::Dynamic, 1>* y) const { y->resize(1); (*y)(0) = 24 - 20 * x(0) + 9 * x(1) - 13 * x(2) + 4 * x(0) * x(0) - 4 * x(0) * x(1) + 4 * x(0) * x(2) + 2 * x(1) * x(1) - 2 * x(1) * x(2) + 2 * x(2) * x(2); } }; void AddGenericCost(); void AddSymbolicCost(); void AddNonSymbolicCost(); void AddNonSymbolicConstraint(); void AddSymbolicConstraint(); std::unique_ptr<MathematicalProgram> prog_; VectorDecisionVariable<3> x_; VectorDecisionVariable<3> y_; Eigen::Vector3d expected_; }; /// An SOCP with Lorentz cone and rotated Lorentz cone constraints. /// The objective is to find the smallest distance from a hyperplane /// A * x = b to the origin. /// We can solve the following SOCP with Lorentz cone constraint /// min t /// s.t t >= sqrt(xᵀ*x) /// A * x = b. /// Alternatively, we can solve the following SOCP with rotated Lorentz cone /// constraint /// min t /// s.t t >= xᵀ*x /// A * x = b. /// /// The optimal solution of this equality constrained QP can be found using /// Lagrangian method. The optimal solution x* and Lagrangian multiplier z* /// satisfy /// A_hat * [x*; z*] = [b; 0] /// where A_hat = [A 0; 2*I Aᵀ]. class MinDistanceFromPlaneToOrigin { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MinDistanceFromPlaneToOrigin) static std::vector<CostForm> cost_forms() { std::vector<CostForm> costs{CostForm::kNonSymbolic, CostForm::kSymbolic}; return costs; } static std::vector<ConstraintForm> constraint_forms() { std::vector<ConstraintForm> cnstr{ConstraintForm::kNonSymbolic, ConstraintForm::kSymbolic}; return cnstr; } MinDistanceFromPlaneToOrigin(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, CostForm cost_form, ConstraintForm constraint_form); MathematicalProgram* prog_lorentz() const { return prog_lorentz_.get(); } MathematicalProgram* prog_rotated_lorentz() const { return prog_rotated_lorentz_.get(); } Eigen::VectorXd prog_lorentz_initial_guess() const; Eigen::VectorXd prog_rotated_lorentz_initial_guess() const; void CheckSolution(const MathematicalProgramResult& result, bool is_rotated_cone) const; private: void AddNonSymbolicConstraint(); void AddSymbolicConstraint(); Eigen::MatrixXd A_; Eigen::VectorXd b_; std::unique_ptr<MathematicalProgram> prog_lorentz_; std::unique_ptr<MathematicalProgram> prog_rotated_lorentz_; VectorDecisionVariable<1> t_lorentz_; VectorXDecisionVariable x_lorentz_; VectorDecisionVariable<1> t_rotated_lorentz_; VectorXDecisionVariable x_rotated_lorentz_; Eigen::VectorXd x_expected_; }; /** * A simple convex optimization program * min -12 * x + x³ * s.t x >= 0 * Notice the objective function is convex in the feasible region x >= 0 * The optimal solution is x = 2. */ class ConvexCubicProgramExample : public MathematicalProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ConvexCubicProgramExample) ConvexCubicProgramExample(); ~ConvexCubicProgramExample() override = default; void CheckSolution(const MathematicalProgramResult& result) const; private: VectorDecisionVariable<1> x_; }; /** * A simple non-convex problem with a quadratic equality constraint * min 0 * s.t xᵀx = 1 * This test is meant to verify that we can add a quadratic constraint to a * program, and solve it through nonlinear optimization. */ class UnitLengthProgramExample : public MathematicalProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(UnitLengthProgramExample) UnitLengthProgramExample(); ~UnitLengthProgramExample() override = default; void CheckSolution(const MathematicalProgramResult& result, double tolerance) const; private: VectorDecisionVariable<4> x_; }; // Finds a point Q outside a tetrahedron, and with a specified distance to the // tetrahedron. The tetrahedron's shape is fixed. Both the point and the // tetrahedron can move in space. // We pick this problem to break SNOPT 7.6, as explained in // https://github.com/snopt/snopt-interface/issues/19#issuecomment-410346280 // This is just a feasibility problem, without a cost. class DistanceToTetrahedronExample : public MathematicalProgram { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DistanceToTetrahedronExample) explicit DistanceToTetrahedronExample(double distance_expected); ~DistanceToTetrahedronExample() override {} const VectorDecisionVariable<18>& x() const { return x_; } const Eigen::Matrix<double, 4, 3> A_tetrahedron() const { return A_tetrahedron_; } const Eigen::Vector4d b_tetrahedron() const { return b_tetrahedron_; } private: // TODO(hongkai.dai): explain the mathematical formulation of this constraint. class DistanceToTetrahedronNonlinearConstraint : public Constraint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DistanceToTetrahedronNonlinearConstraint) DistanceToTetrahedronNonlinearConstraint( const Eigen::Matrix<double, 4, 3>& A_tetrahedron, const Eigen::Vector4d& b_tetrahedron); ~DistanceToTetrahedronNonlinearConstraint() override {} private: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const { DRAKE_DEMAND(x.size() == 18); y->resize(15); using ScalarX = typename DerivedX::Scalar; Vector3<ScalarX> p_WB = x.template head<3>(); Vector3<ScalarX> p_WQ = x.template segment<3>(3); Vector3<ScalarX> n_W = x.template segment<3>(6); Vector4<ScalarX> quat_WB = x.template segment<4>(9); Vector3<ScalarX> p_WP = x.template segment<3>(13); ScalarX d = x(16); ScalarX phi = x(17); // p_BV are the vertices of the tetrahedron in the body frame B. Eigen::Matrix<double, 4, 3> p_BV; // clang-format off p_BV << 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1; // clang-format on (*y)(0) = quat_WB.dot(quat_WB); (*y)(1) = n_W.dot(n_W); (*y)(2) = n_W.dot(p_WP) - d; (*y)(3) = phi - n_W.dot(p_WQ - p_WP); y->template segment<3>(4) = n_W * phi - p_WQ + p_WP; const ScalarX ww = quat_WB(0) * quat_WB(0); const ScalarX xx = quat_WB(1) * quat_WB(1); const ScalarX yy = quat_WB(2) * quat_WB(2); const ScalarX zz = quat_WB(3) * quat_WB(3); const ScalarX wx = quat_WB(0) * quat_WB(1); const ScalarX wy = quat_WB(0) * quat_WB(2); const ScalarX wz = quat_WB(0) * quat_WB(3); const ScalarX xy = quat_WB(1) * quat_WB(2); const ScalarX xz = quat_WB(1) * quat_WB(3); const ScalarX yz = quat_WB(2) * quat_WB(3); Matrix3<ScalarX> R_WB; // clang-format off R_WB << ww + xx - yy - zz, 2 * xy - 2 * wz, 2 * xz + 2 * wy, 2 * xy + 2 * wz, ww + yy - xx - zz, 2 * yz - 2 * wx, 2 * xz - 2 * wy, 2 * yz + 2 * wx, ww + zz - xx - yy; // clang-format on for (int i = 0; i < 4; ++i) { const Vector3<ScalarX> p_WVi = p_WB + R_WB * p_BV.row(i).transpose(); (*y)(7 + i) = n_W.dot(p_WVi) - d; } // A * (R_WBᵀ * (p_WQ - p_WB)) y->template segment<4>(11) = A_tetrahedron_ * R_WB.transpose() * (p_WQ - p_WB); } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { DoEvalGeneric(x.cast<symbolic::Expression>(), y); } private: Eigen::Matrix<double, 4, 3> A_tetrahedron_; }; VectorDecisionVariable<18> x_; // The tetrahedron can be described as A_tetrahedron * x<=b_tetrahedron, where // x is the position of a point within the tetrahedron, in the tetrahedron // body frame B. Eigen::Matrix<double, 4, 3> A_tetrahedron_; Eigen::Vector4d b_tetrahedron_; }; /** * This problem is taken from Pseudo-complementary algorithms for mathematical * programming by U. Eckhardt in Numerical Methods for Nonlinear Optimization, * 1972. This problem has a sparse gradient. * max x0 * s.t x1 - exp(x0) >= 0 * x2 - exp(x1) >= 0 * 0 <= x0 <= 100 * 0 <= x1 <= 100 * 0 <= x2 <= 10 */ class EckhardtProblem { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(EckhardtProblem) explicit EckhardtProblem(bool set_sparsity_pattern); void CheckSolution(const MathematicalProgramResult& result, double tol) const; const MathematicalProgram& prog() const { return *prog_; } private: class EckhardtConstraint : public Constraint { public: explicit EckhardtConstraint(bool set_sparsity_pattern); private: template <typename T> void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x, VectorX<T>* y) const { using std::exp; y->resize(2); (*y)(0) = x(1) - exp(x(0)); (*y)(1) = x(2) - exp(x(1)); } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { DoEvalGeneric<symbolic::Expression>(x.cast<symbolic::Expression>(), y); } }; std::unique_ptr<MathematicalProgram> prog_; Vector3<symbolic::Variable> x_; }; /** * Test dual solution for Eckhardt problem. */ void TestEckhardtDualSolution(const SolverInterface& solver, const Eigen::Ref<const Eigen::VectorXd>& x_init, double tol = 1e-6); /** * This is problem 106 from Test examples for Nonlinear Programming * Codes by Will Hock and Klaus Schittkowski, Springer. The constraint of this * problem has sparse gradient. */ class HeatExchangerDesignProblem { public: HeatExchangerDesignProblem(); void CheckSolution(const MathematicalProgramResult& result, double tol) const; const MathematicalProgram& prog() const { return *prog_; } private: class HeatExchangerDesignConstraint1 : public solvers::Constraint { public: HeatExchangerDesignConstraint1(); ~HeatExchangerDesignConstraint1() override {} private: template <typename T> void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x, VectorX<T>* y) const { y->resize(1); (*y)(0) = x(0) * x(5) - 833.33252 * x(3) - 100 * x(0) + 83333.333; } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { DoEvalGeneric<symbolic::Expression>(x.cast<symbolic::Expression>(), y); } }; class HeatExchangerDesignConstraint2 : public solvers::Constraint { public: HeatExchangerDesignConstraint2(); ~HeatExchangerDesignConstraint2() override {} private: template <typename T> void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x, VectorX<T>* y) const { y->resize(2); (*y)(0) = x(0) * x(5) - 1250 * x(3) - x(0) * x(2) + 1250 * x(2); (*y)(1) = x(1) * x(6) - 1250000 - x(1) * x(3) + 2500 * x(3); } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { DoEvalGeneric<symbolic::Expression>(x.cast<symbolic::Expression>(), y); } }; std::unique_ptr<MathematicalProgram> prog_; Eigen::Matrix<symbolic::Variable, 8, 1> x_; }; /// In Eigen's autodiff, when the derivatives() vector has empty size, it is /// interpreted as 0 gradient (i.e., the gradient has value 0, with the size of /// the gradient matrix being arbitrary). On the other hand, many solvers /// interpret empty size gradient in a different way, that the variable to be /// taken derivative with has 0 size. This test guarantees that when Eigen /// autodiff returns an empty size gradient, we can manually set the gradient /// size to be the right size. This class represents the following trivial /// problem /// <pre> /// min f(x) /// s.t g(x) <= 0 /// </pre> /// where f(x) = 1 and g(x) = 0. x.rows() == 2. /// When evaluating f(x) and g(x), autodiff returns an empty gradient. But the /// solvers expect to see gradient ∂f/∂x = [0 0] and ∂g/∂x = [0 0], namely /// matrices of size 1 x 2, not empty size matrix. This test shows that we can /// automatically set the gradient to the right size, although Eigen's autodiff /// returns an empty size gradient. class EmptyGradientProblem { public: EmptyGradientProblem(); const MathematicalProgram& prog() const { return *prog_; } void CheckSolution(const MathematicalProgramResult& result) const; private: class EmptyGradientCost : public Cost { public: EmptyGradientCost() : Cost(2) {} private: template <typename T> void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>&, VectorX<T>* y) const { y->resize(1); (*y)(0) = T(1); } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, VectorX<double>* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { DoEvalGeneric<symbolic::Expression>(x.cast<symbolic::Expression>(), y); } }; class EmptyGradientConstraint : public Constraint { public: EmptyGradientConstraint(); private: template <typename T> void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>&, VectorX<T>* y) const { y->resize(1); (*y)(0) = T(0); } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, VectorX<double>* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { DoEvalGeneric<symbolic::Expression>(x.cast<symbolic::Expression>(), y); } }; std::unique_ptr<MathematicalProgram> prog_; Vector2<symbolic::Variable> x_; }; void TestL2NormCost(const SolverInterface& solver, double tol); std::set<CostForm> linear_cost_form(); std::set<CostForm> quadratic_cost_form(); std::set<ConstraintForm> linear_constraint_form(); // Test a nonlinear program whose costs and constraints are intentionally // imposed using duplicated variables. class DuplicatedVariableNonlinearProgram1 : public ::testing::Test { // max x0² + 4x0x1 + 4x1² // s.t x0² + x1² = 1 // x0 >= 0 // The optimal solution is x0 = 1/sqrt(5), x1 = 2/sqrt(5). public: DuplicatedVariableNonlinearProgram1(); void CheckSolution( const SolverInterface& solver, const Eigen::Vector2d& x_init, const std::optional<SolverOptions>& solver_options = std::nullopt, double tol = 1E-7) const; protected: std::unique_ptr<MathematicalProgram> prog_; Vector2<symbolic::Variable> x_; }; // Test a nonlinear program with quadratic constraints. // max x + 2*y // s.t x² + y² = 1 class QuadraticEqualityConstrainedProgram1 : public ::testing::Test { public: QuadraticEqualityConstrainedProgram1(); void CheckSolution( const SolverInterface& solver, const Eigen::Vector2d& x_init, const std::optional<SolverOptions>& solver_options = std::nullopt, double tol = 1E-7, bool check_dual = true) const; protected: std::unique_ptr<MathematicalProgram> prog_; Vector2<symbolic::Variable> x_; }; } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/l2norm_cost_examples.h
#pragma once #include <array> #include <optional> #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solver_interface.h" namespace drake { namespace solvers { namespace test { // Test a program without constraints // min |x-p1|₂ + |x-p2|₂ + |x-p3|₂ class ShortestDistanceToThreePoints { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ShortestDistanceToThreePoints) ShortestDistanceToThreePoints(); const MathematicalProgram& prog() const { return prog_; } void CheckSolution( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options = std::nullopt, double tol = 1E-5) const; private: MathematicalProgram prog_; Vector3<symbolic::Variable> x_; std::array<Eigen::Vector3d, 3> pts_; }; // Compute the shortest distance from a cylinder to a point in 3D. // min |x - pt|₂ // -1 <= x[2] <= 1 // x[0]² + x[1]² <= 4 // This tests L2NormCost with Lorentz cone and bounding box constraints. class ShortestDistanceFromCylinderToPoint { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ShortestDistanceFromCylinderToPoint) ShortestDistanceFromCylinderToPoint(); void CheckSolution( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options = std::nullopt, double tol = 1E-5) const; private: MathematicalProgram prog_; Vector3<symbolic::Variable> x_; Eigen::Vector3d pt_; }; // Compute the shortest distance on a plane to two points // min |A * x - pt0|₂ + |A * x - pt1|₂ // s.t cᵀ*(A*x) = d // This tests L2NormCost with linear constraints. class ShortestDistanceFromPlaneToTwoPoints { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ShortestDistanceFromPlaneToTwoPoints) ShortestDistanceFromPlaneToTwoPoints(); void CheckSolution( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options = std::nullopt, double tol = 1E-5) const; private: MathematicalProgram prog_; Vector3<symbolic::Variable> x_; std::array<Eigen::Vector3d, 2> pts_; Eigen::Vector3d plane_normal_; Eigen::Vector3d plane_pt_; Eigen::Matrix3d A_; }; } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/clp_solver_test.cc
#include "drake/solvers/clp_solver.h" #include <gtest/gtest.h> #include "drake/solvers/test/linear_program_examples.h" #include "drake/solvers/test/quadratic_program_examples.h" namespace drake { namespace solvers { namespace test { TEST_P(LinearProgramTest, TestLP) { ClpSolver solver; prob()->RunProblem(&solver); } INSTANTIATE_TEST_SUITE_P( ClpTest, LinearProgramTest, ::testing::Combine(::testing::ValuesIn(linear_cost_form()), ::testing::ValuesIn(linear_constraint_form()), ::testing::ValuesIn(linear_problems()))); TEST_F(InfeasibleLinearProgramTest0, TestInfeasible) { ClpSolver solver; if (solver.available()) { auto result = solver.Solve(*prog_, {}, {}); auto& details = result.get_solver_details<ClpSolver>(); if (details.clp_version == "1.17.8") { // This version of CLP is buggy and reports the wrong answer. return; } EXPECT_EQ(result.get_solution_result(), SolutionResult::kInfeasibleConstraints); EXPECT_TRUE(std::isinf(result.get_optimal_cost())); EXPECT_GT(result.get_optimal_cost(), 0.); // This code is defined in ClpModel::status() const int CLP_INFEASIBLE = 1; EXPECT_EQ(details.status, CLP_INFEASIBLE); } } TEST_F(UnboundedLinearProgramTest0, TestUnbounded) { ClpSolver solver; if (solver.available()) { auto result = solver.Solve(*prog_, {}, {}); EXPECT_FALSE(result.is_success()); EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded); EXPECT_TRUE(std::isinf(result.get_optimal_cost())); EXPECT_LT(result.get_optimal_cost(), 0.); // This code is defined in ClpModel::status() const int CLP_UNBOUNDED = 2; EXPECT_EQ(result.get_solver_details<ClpSolver>().status, CLP_UNBOUNDED); } } TEST_F(DuplicatedVariableLinearProgramTest1, Test) { ClpSolver solver; if (solver.available()) { CheckSolution(solver); } } GTEST_TEST(TestDual, DualSolution1) { ClpSolver solver; if (solver.available()) { TestLPDualSolution1(solver); } } GTEST_TEST(TestDual, DualSolution2) { ClpSolver solver; if (solver.available()) { TestLPDualSolution2(solver); } } GTEST_TEST(TestDual, DualSolution3) { ClpSolver solver; if (solver.available()) { TestLPDualSolution3(solver); } } GTEST_TEST(TestDual, DualSolution4) { ClpSolver solver; if (solver.available()) { TestLPDualSolution4(solver); } } GTEST_TEST(TestDual, DualSolution5) { ClpSolver solver; TestLPDualSolution5(solver); } GTEST_TEST(QPtest, TestUnconstrainedQP) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>("x"); prog.AddQuadraticCost(x(0) * x(0)); ClpSolver solver; if (solver.available()) { auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); const double tol = 1E-10; EXPECT_NEAR(result.GetSolution(x(0)), 0, tol); EXPECT_NEAR(result.get_optimal_cost(), 0, tol); EXPECT_EQ(result.get_solver_details<ClpSolver>().status, 0); } // Add additional quadratic costs prog.AddQuadraticCost((x(1) + x(2) - 2) * (x(1) + x(2) - 2)); if (solver.available()) { auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); const double tol = 1E-10; EXPECT_NEAR(result.GetSolution(x(0)), 0, tol); EXPECT_NEAR(result.GetSolution(x(1)) + result.GetSolution(x(2)), 2, tol); EXPECT_NEAR(result.get_optimal_cost(), 0, tol); EXPECT_EQ(result.get_solver_details<ClpSolver>().status, 0); } // Add linear costs. prog.AddLinearCost(4 * x(0) + 5); // Now the cost is (x₀ + 2)² + (x₁ + x₂ - 2)² + 1 if (solver.available()) { auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); const double tol = 1E-10; EXPECT_NEAR(result.GetSolution(x(0)), -2, tol); EXPECT_NEAR(result.GetSolution(x(1)) + result.GetSolution(x(2)), 2, tol); EXPECT_NEAR(result.get_optimal_cost(), 1, tol); EXPECT_EQ(result.get_solver_details<ClpSolver>().status, 0); } } TEST_P(QuadraticProgramTest, TestQP) { ClpSolver solver; prob()->RunProblem(&solver); } INSTANTIATE_TEST_SUITE_P( ClpTest, QuadraticProgramTest, ::testing::Combine(::testing::ValuesIn(quadratic_cost_form()), ::testing::ValuesIn(linear_constraint_form()), ::testing::ValuesIn(quadratic_problems()))); GTEST_TEST(QPtest, TestUnitBallExample) { ClpSolver solver; if (solver.available()) { TestQPonUnitBallExample(solver); } } GTEST_TEST(QPtest, TestInfeasible) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddQuadraticCost(x(0) * x(0) + 2 * x(1) * x(1)); prog.AddLinearConstraint(x(0) + 2 * x(1) == 2); prog.AddLinearConstraint(x(0) >= 1); prog.AddLinearConstraint(x(1) >= 2); ClpSolver solver; // The program is infeasible. if (solver.available()) { auto result = solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kInfeasibleConstraints); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kGlobalInfeasibleCost); EXPECT_EQ(result.get_solver_details<ClpSolver>().status, 1); } } GTEST_TEST(ClpSolverTest, Version) { ClpSolver solver; MathematicalProgram prog; MathematicalProgramResult result = solver.Solve(prog); if (solver.available()) { auto& details = result.get_solver_details<ClpSolver>(); EXPECT_NE(details.clp_version, ""); } } GTEST_TEST(ClpSolverTest, DualSolution1) { // Test GetDualSolution(). ClpSolver solver; TestQPDualSolution1(solver); } GTEST_TEST(ClpSolverTest, DualSolution2) { // Test GetDualSolution(). // This QP has non-zero dual solution for linear inequality constraint. ClpSolver solver; TestQPDualSolution2(solver); } GTEST_TEST(ClpSolverTest, DualSolution3) { // Test GetDualSolution(). // This QP has non-zero dual solution for the bounding box constraint. ClpSolver solver; TestQPDualSolution3(solver, 0.0, 1.0e-4); } GTEST_TEST(ClpSolverTest, EqualityConstrainedQPDualSolution1) { ClpSolver solver; TestEqualityConstrainedQPDualSolution1(solver); } GTEST_TEST(ClpSolverTest, EqualityConstrainedQPDualSolution2) { ClpSolver solver; TestEqualityConstrainedQPDualSolution2(solver); } GTEST_TEST(ClpSolverTest, TestNonconvexQP) { ClpSolver solver; if (solver.available()) { TestNonconvexQP(solver, true); } } // This is a code coverage test, not a functional test. If the code that // handles verbosity options has a segfault or always throws an exception, // then this would catch it. GTEST_TEST(ClpSolverTest, TestVerbosity) { LinearProgram0 example(CostForm::kSymbolic, ConstraintForm::kSymbolic); const MathematicalProgram& prog = *example.prog(); SolverOptions options; options.SetOption(CommonSolverOption::kPrintToConsole, 1); ClpSolver solver; if (solver.available()) { // This will print stuff to the console, but we don't have any // easy way to check that. solver.Solve(prog, {}, options); } } GTEST_TEST(ClpSolverTest, TestNumericalScaling) { ClpSolver solver; TestLPPoorScaling1(solver); TestLPPoorScaling2(solver); // Try another scaling option. Set scaling equal to 2. Somehow in CLP with // this scaling mode, the problem is not solved successfully. SolverOptions solver_options; solver_options.SetOption(ClpSolver::id(), "scaling", 2); TestLPPoorScaling1(solver, false, 1E-14, solver_options); TestLPPoorScaling2(solver, false, 1E-4, solver_options); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/linear_program_examples.cc
#include "drake/solvers/test/linear_program_examples.h" #include <limits> #include <gtest/gtest.h> #include "drake/common/drake_assert.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/ipopt_solver.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/mosek_solver.h" #include "drake/solvers/test/mathematical_program_test_util.h" using drake::symbolic::Expression; using Eigen::Matrix2d; using Eigen::Matrix3d; using Eigen::Matrix4d; using Eigen::Vector2d; using Eigen::Vector3d; using Eigen::Vector4d; using std::numeric_limits; namespace drake { namespace solvers { namespace test { const double kInf = std::numeric_limits<double>::infinity(); LinearFeasibilityProgram::LinearFeasibilityProgram( ConstraintForm constraint_form) : OptimizationProgram(CostForm::kSymbolic, constraint_form), x_() { x_ = prog()->NewContinuousVariables<3>(); switch (constraint_form) { case ConstraintForm::kNonSymbolic: { Matrix3d A; // clang-format off A << 1, 2, 3, 0, 1, -2, 0, 0, 0; // clang-format on Vector3d b_lb(0, -std::numeric_limits<double>::infinity(), -1); Vector3d b_ub(10, 3, 0); prog()->AddLinearConstraint(A, b_lb, b_ub, x_); prog()->AddBoundingBoxConstraint(1.0, numeric_limits<double>::infinity(), x_(1)); break; } case ConstraintForm::kSymbolic: { Vector2<Expression> expr; // clang-format off expr << x_(0) + 2 * x_(1) + 3 * x_(2), x_(1) - 2 * x_(2); // clang-format on prog()->AddLinearConstraint( expr, Eigen::Vector2d(0, -numeric_limits<double>::infinity()), Vector2d(10, 3)); prog()->AddBoundingBoxConstraint(1, numeric_limits<double>::infinity(), x_(1)); break; } case ConstraintForm::kFormula: { prog()->AddLinearConstraint(x_(0) + 2 * x_(1) + 3 * x_(2), 0, 10); prog()->AddLinearConstraint(x_(1) - 2 * x_(2) <= 3); prog()->AddLinearConstraint(+x_(1) >= 1); break; } default: { throw std::runtime_error("Unknown constraint form"); } } } void LinearFeasibilityProgram::CheckSolution( const MathematicalProgramResult& result) const { auto x_val = result.GetSolution(x_); Vector3d A_times_x(x_val(0) + 2 * x_val(1) + 3 * x_val(2), x_val(1) - 2 * x_val(2), 0); EXPECT_GE(A_times_x(0), 0 - 1e-10); EXPECT_LE(A_times_x(0), 10 + 1e-10); EXPECT_LE(A_times_x(1), 3 + 1E-10); EXPECT_LE(A_times_x(2), 0 + 1E-10); EXPECT_GE(A_times_x(2), 0 - 1E-10); EXPECT_GE(result.GetSolution(x_(1)), 1 - 1E-10); } LinearProgram0::LinearProgram0(CostForm cost_form, ConstraintForm constraint_form) : OptimizationProgram(cost_form, constraint_form), x_(), x_expected_(1, 2) { x_ = prog()->NewContinuousVariables<2>(); switch (cost_form) { case CostForm::kNonSymbolic: { prog()->AddLinearCost(Vector2d(2.0, 1.0), 4, x_); break; } case CostForm::kSymbolic: { prog()->AddLinearCost(2 * x_(0) + x_(1) + 4); break; } default: { throw std::runtime_error("Un-supported cost form."); } } Vector3d b_lb(-numeric_limits<double>::infinity(), 2.0, -numeric_limits<double>::infinity()); Vector3d b_ub(1.0, numeric_limits<double>::infinity(), 4.0); switch (constraint_form) { case ConstraintForm::kNonSymbolic: { Eigen::Matrix<double, 3, 2> A; // clang-format off A << -1, 1, 1, 1, 1, -2; // clang-format on prog()->AddLinearConstraint(A, b_lb, b_ub, x_); prog()->AddBoundingBoxConstraint( Vector2d(0, 2), Vector2d::Constant(numeric_limits<double>::infinity()), x_); break; } case ConstraintForm::kSymbolic: { Vector3<Expression> expr1; // clang-format off expr1 << -x_(0) + x_(1), x_(0) + x_(1), x_(0) - 2 * x_(1); // clang-format on prog()->AddLinearConstraint(expr1, b_lb, b_ub); prog()->AddBoundingBoxConstraint( Vector2d(0, 2), Vector2d::Constant(numeric_limits<double>::infinity()), x_); break; } case ConstraintForm::kFormula: { prog()->AddLinearConstraint(-x_(0) + x_(1) <= 1); prog()->AddLinearConstraint(x_(0) + x_(1) >= 2); prog()->AddLinearConstraint(x_(0) - 2 * x_(1) <= 4); prog()->AddLinearConstraint(+x_(1) >= 2); prog()->AddLinearConstraint(+x_(0) >= 0); break; } default: { throw std::runtime_error("Unsupported constraint form."); } } } void LinearProgram0::CheckSolution( const MathematicalProgramResult& result) const { const double tol = GetSolverSolutionDefaultCompareTolerance(result.get_solver_id()); EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), x_expected_, tol, MatrixCompareType::absolute)); ExpectSolutionCostAccurate(*prog(), result, tol); } LinearProgram1::LinearProgram1(CostForm cost_form, ConstraintForm constraint_form) : OptimizationProgram(cost_form, constraint_form), x_{}, x_expected_(0, 4) { x_ = prog()->NewContinuousVariables<2>(); switch (cost_form) { case CostForm::kNonSymbolic: { prog()->AddLinearCost(Vector2d(1.0, -2.0), 3, x_); break; } case CostForm::kSymbolic: { prog()->AddLinearCost(x_(0) - 2 * x_(1) + 3); break; } default: throw std::runtime_error("Unsupported cost form."); } switch (constraint_form) { case ConstraintForm::kNonSymbolic: case ConstraintForm::kSymbolic: { prog()->AddBoundingBoxConstraint(Vector2d(0, -1), Vector2d(2, 4), x_); break; } case ConstraintForm::kFormula: { prog()->AddLinearConstraint(+x_(0) >= 0); prog()->AddLinearConstraint(+x_(0) <= 2); prog()->AddLinearConstraint(+x_(1) >= -1); prog()->AddLinearConstraint(+x_(1) <= 4); break; } default: throw std::runtime_error("Unsupported constraint form."); } } void LinearProgram1::CheckSolution( const MathematicalProgramResult& result) const { const double tol = GetSolverSolutionDefaultCompareTolerance(result.get_solver_id()); EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), x_expected_, tol, MatrixCompareType::absolute)); ExpectSolutionCostAccurate(*prog(), result, tol); } LinearProgram2::LinearProgram2(CostForm cost_form, ConstraintForm constraint_form) : OptimizationProgram(cost_form, constraint_form), x_(), x_expected_(0, 0, 15, 25.0 / 3.0) { x_ = prog()->NewContinuousVariables<4>(); switch (cost_form) { case CostForm::kNonSymbolic: { prog()->AddLinearCost(Vector3d(-3, -1, -4), x_.head<3>()); prog()->AddLinearCost(Vector2d(-1, -1), x_.tail<2>()); break; } case CostForm::kSymbolic: { prog()->AddLinearCost(-3 * x_(0) - x_(1) - 4 * x_(2)); prog()->AddLinearCost(-x_(2) - x_(3)); break; } default: throw std::runtime_error("Unsupported cost term."); } Vector4d b_lb(15, -numeric_limits<double>::infinity(), -numeric_limits<double>::infinity(), -100); Vector4d b_ub(numeric_limits<double>::infinity(), 25, numeric_limits<double>::infinity(), 40); switch (constraint_form) { case ConstraintForm::kNonSymbolic: { prog()->AddLinearEqualityConstraint(Eigen::RowVector3d(3, 1, 2), 30, x_.head<3>()); Matrix4d A; // clang-format off A << 2, 1, 3, 1, 0, 2, 0, 3, 1, 2, 0, 1, 1, 0, 0, 2; // clang-format on prog()->AddLinearConstraint(A, b_lb, b_ub, x_); prog()->AddBoundingBoxConstraint(0, numeric_limits<double>::infinity(), x_); prog()->AddBoundingBoxConstraint(0, 10, x_.segment<1>(1)); break; } case ConstraintForm::kSymbolic: { prog()->AddLinearEqualityConstraint(3 * x_(0) + x_(1) + 2 * x_(2), 30); Eigen::Matrix<Expression, 4, 1> expr; // clang-format off expr << 2 * x_(0) + x_(1) + 3 * x_(2) + x_(3), 2 * x_(1) + 3 * x_(3), x_(0) + 2 * x_(1) + x_(3), x_(0) + 2 * x_(2); // clang-format on prog()->AddLinearConstraint(expr, b_lb, b_ub); prog()->AddBoundingBoxConstraint(0, numeric_limits<double>::infinity(), x_); prog()->AddBoundingBoxConstraint(0, 10, x_.segment<1>(1)); break; } case ConstraintForm::kFormula: { prog()->AddLinearConstraint(3 * x_(0) + x_(1) + 2 * x_(2) == 30); prog()->AddLinearConstraint(2 * x_(0) + x_(1) + 3 * x_(2) + x_(3) >= 15); prog()->AddLinearConstraint(2 * x_(1) + 3 * x_(3) <= 25); // TODO(hongkai.dai) : uncomment the next line when the bug expression >= // -inf is fixed. // prog()->AddLinearConstraint(x_(0) + 2 * x_(1) + x_(3) >= // -numeric_limits<double>::infinity()); prog()->AddLinearConstraint(x_(0) + 2 * x_(2) <= 40); prog()->AddLinearConstraint(x_(0) + 2 * x_(2) >= -100); prog()->AddLinearConstraint(+x_(0) >= 0); prog()->AddLinearConstraint(+x_(1) >= 0); prog()->AddLinearConstraint(+x_(2) >= 0); prog()->AddLinearConstraint(+x_(3) >= 0); prog()->AddLinearConstraint(+x_(1) <= 10); break; } default: throw std::runtime_error("Unsupported constraint form."); } } void LinearProgram2::CheckSolution( const MathematicalProgramResult& result) const { const double tol = GetSolverSolutionDefaultCompareTolerance(result.get_solver_id()); EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), x_expected_, tol, MatrixCompareType::absolute)); ExpectSolutionCostAccurate(*prog(), result, tol); } LinearProgram3::LinearProgram3(CostForm cost_form, ConstraintForm constraint_form) : OptimizationProgram(cost_form, constraint_form), x_(), x_expected_(8, 3, 11) { x_ = prog()->NewContinuousVariables<3>("x"); switch (cost_form) { case CostForm::kNonSymbolic: { prog()->AddLinearCost(Eigen::Vector3d(4, 5, 6), x_); break; } case CostForm::kSymbolic: { prog()->AddLinearCost(4 * x_(0) + 5 * x_(1) + 6 * x_(2)); break; } default: throw std::runtime_error("Unsupported cost form."); } Eigen::Vector3d b_lb(11, -numeric_limits<double>::infinity(), 35); Eigen::Vector3d b_ub(numeric_limits<double>::infinity(), 5, numeric_limits<double>::infinity()); switch (constraint_form) { case ConstraintForm::kNonSymbolic: { prog()->AddLinearEqualityConstraint(Eigen::RowVector3d(1, -1, -1), 0, {x_.segment<1>(2), x_.head<2>()}); Eigen::Matrix<double, 3, 2> A; // clang-format off A << 1, 1, 1, -1, 7, 12; // clang-format on prog()->AddLinearConstraint(A, b_lb, b_ub, x_.head<2>()); prog()->AddBoundingBoxConstraint(0, numeric_limits<double>::infinity(), x_); break; } case ConstraintForm::kSymbolic: { prog()->AddLinearEqualityConstraint(x_(2) - x_(0) - x_(1), 0); Vector3<Expression> expr; // clang-format off expr << x_(0) + x_(1), x_(0) - x_(1), 7 * x_(0) + 12 * x_(1); // clang-format on prog()->AddLinearConstraint(expr, b_lb, b_ub); prog()->AddBoundingBoxConstraint(0, numeric_limits<double>::infinity(), x_); break; } case ConstraintForm::kFormula: { prog()->AddLinearConstraint(x_(2) - x_(0) - x_(1) == 0); prog()->AddLinearConstraint(x_(0) + x_(1) >= 11); prog()->AddLinearConstraint(x_(0) - x_(1) <= 5); prog()->AddLinearConstraint(7 * x_(0) >= 35 - 12 * x_(1)); prog()->AddLinearConstraint(+x_(0) >= 0); prog()->AddLinearConstraint(+x_(1) >= 0); prog()->AddLinearConstraint(+x_(2) >= 0); break; } default: throw std::runtime_error("Unsupported constraint form."); } } void LinearProgram3::CheckSolution( const MathematicalProgramResult& result) const { // Mosek has a looser tolerance. double tol = GetSolverSolutionDefaultCompareTolerance(result.get_solver_id()); if (result.get_solver_id() == MosekSolver::id()) { tol = 1E-6; } // Ipopt has a looser objective tolerance double cost_tol = tol; if (result.get_solver_id() == IpoptSolver::id()) { cost_tol = 1E-5; } EXPECT_TRUE(CompareMatrices(result.GetSolution(x_), x_expected_, tol, MatrixCompareType::absolute)); ExpectSolutionCostAccurate(*prog(), result, cost_tol); } std::ostream& operator<<(std::ostream& os, LinearProblems value) { os << "LinearProblems::"; switch (value) { case LinearProblems::kLinearFeasibilityProgram: { os << "kLinearFeasibilityProgram"; return os; } case LinearProblems::kLinearProgram0: { os << "kLinearFeasibilityProgram0"; return os; } case LinearProblems::kLinearProgram1: { os << "kLinearFeasibilityProgram1"; return os; } case LinearProblems::kLinearProgram2: { os << "kLinearFeasibilityProgram2"; return os; } case LinearProblems::kLinearProgram3: { os << "kLinearFeasibilityProgram3"; return os; } } DRAKE_UNREACHABLE(); } LinearProgramTest::LinearProgramTest() { auto cost_form = std::get<0>(GetParam()); auto constraint_form = std::get<1>(GetParam()); switch (std::get<2>(GetParam())) { case LinearProblems::kLinearFeasibilityProgram: { prob_ = std::make_unique<LinearFeasibilityProgram>(constraint_form); break; } case LinearProblems::kLinearProgram0: { prob_ = std::make_unique<LinearProgram0>(cost_form, constraint_form); break; } case LinearProblems::kLinearProgram1: { prob_ = std::make_unique<LinearProgram1>(cost_form, constraint_form); break; } case LinearProblems::kLinearProgram2: { prob_ = std::make_unique<LinearProgram2>(cost_form, constraint_form); break; } case LinearProblems::kLinearProgram3: { prob_ = std::make_unique<LinearProgram3>(cost_form, constraint_form); break; } default: throw std::runtime_error("Un-recognized linear problem."); } } std::vector<LinearProblems> linear_problems() { return std::vector<LinearProblems>{ LinearProblems::kLinearFeasibilityProgram, LinearProblems::kLinearProgram0, LinearProblems::kLinearProgram1, LinearProblems::kLinearProgram2, LinearProblems::kLinearProgram3}; } InfeasibleLinearProgramTest0::InfeasibleLinearProgramTest0() : prog_(std::make_unique<MathematicalProgram>()) { auto x = prog_->NewContinuousVariables<2>("x"); prog_->AddLinearCost(-x(0) - x(1)); prog_->AddLinearConstraint(x(0) + 2 * x(1) <= 3); prog_->AddLinearConstraint(2 * x(0) + x(1) == 4); prog_->AddLinearConstraint(x(0) >= 0); prog_->AddLinearConstraint(x(1) >= 2); } UnboundedLinearProgramTest0::UnboundedLinearProgramTest0() : prog_(std::make_unique<MathematicalProgram>()) { x_ = prog_->NewContinuousVariables<2>("x"); prog_->AddLinearCost(-x_(0) - x_(1)); prog_->AddLinearConstraint(2 * x_(0) + x_(1) >= 4); prog_->AddLinearConstraint(x_(0) >= 0); prog_->AddLinearConstraint(x_(1) >= 2); } UnboundedLinearProgramTest1::UnboundedLinearProgramTest1() : prog_(std::make_unique<MathematicalProgram>()) { auto x = prog_->NewContinuousVariables<4>("x"); prog_->AddCost(x(0) + 2 * x(1) + 3 * x(2) + 2.5 * x(3) + 2); prog_->AddLinearConstraint(x(0) + x(1) - x(2) + x(3) <= 3); prog_->AddLinearConstraint(x(0) + 2 * x(1) - 2 * x(2) + 4 * x(3), 1, 3); prog_->AddBoundingBoxConstraint(0, 1, VectorDecisionVariable<2>(x(0), x(2))); } DuplicatedVariableLinearProgramTest1::DuplicatedVariableLinearProgramTest1() : prog_{std::make_unique<MathematicalProgram>()} { x_ = prog_->NewContinuousVariables<3>(); // Intentionally add the cost with duplicated entries x_(1). prog_->AddLinearCost(Eigen::Vector4d(1, 2, 1, 4), Vector4<symbolic::Variable>(x_(0), x_(1), x_(1), x_(2))); prog_->AddLinearCost(Eigen::Vector2d(2, -2), 3, Vector2<symbolic::Variable>(x_(0), x_(0))); prog_->AddLinearEqualityConstraint( Eigen::RowVector3d(2, 2, -1), Vector1d(1), Vector3<symbolic::Variable>(x_(0), x_(2), x_(0))); Eigen::Matrix<double, 2, 5> A; // A * vars = [x0 + 2*x1 + x2] // [2*x0 + x1 ] // clang-format off A << -1, 1, 3, 2, -1, 2, 2, -1, 1, -1; // clang-format on Eigen::Matrix<symbolic::Variable, 5, 1> vars; vars << x_(2), x_(0), x_(2), x_(1), x_(2); prog_->AddLinearConstraint(A, Eigen::Vector2d(-kInf, 1), Eigen::Vector2d(3, 3), vars); prog_->AddLinearConstraint( Eigen::RowVector4d(2, 3, 2, -1), Vector1d(0), Vector1d(kInf), Vector4<symbolic::Variable>(x_(1), x_(2), x_(0), x_(0))); } void DuplicatedVariableLinearProgramTest1::CheckSolution( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol) const { if (solver.available()) { MathematicalProgramResult result; solver.Solve(*prog_, std::nullopt, solver_options, &result); EXPECT_TRUE(result.is_success()); const Eigen::Vector3d x_sol = result.GetSolution(x_); EXPECT_NEAR(result.get_optimal_cost(), x_sol(0) + 3 * x_sol(1) + 4 * x_sol(2) + 3, tol); EXPECT_LE(x_sol(0) + 2 * x_sol(1) + x_sol(2), 3 + tol); EXPECT_NEAR(x_sol(0) + 2 * x_sol(2), 1, tol); EXPECT_GE(2 * x_sol(0) + x_sol(1), 1 - tol); EXPECT_LE(2 * x_sol(0) + x_sol(1), 3 + tol); EXPECT_GE(x_sol(0) + 2 * x_sol(1) + 3 * x_sol(2), -tol); } } void TestLPDualSolution1(const SolverInterface& solver, double tol) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); Eigen::Matrix<double, 5, 2> A; // clang-format off A << 1, 2, 3, 4, 2, 1, 1, 5, 3, 2; // clang-format on Eigen::Matrix<double, 5, 1> lb, ub; lb << -kInf, -2, -3, -kInf, 4; ub << 3, kInf, 4, kInf, 5; auto constraint = prog.AddLinearConstraint(A, lb, ub, x); auto cost = prog.AddLinearCost(2 * x[0] + 3 * x[1]); if (solver.available()) { MathematicalProgramResult result1; solver.Solve(prog, {}, {}, &result1); EXPECT_TRUE(result1.is_success()); Eigen::Matrix<double, 5, 1> dual_solution_expected; // This dual solution is computed by first finding the active constraint at // the optimal solution, denoted as Aeq * x = beq, then the dual solution // equals to cᵀAeq⁻¹. dual_solution_expected << 0, 0.8, -0.2, 0, 0; EXPECT_TRUE(CompareMatrices(result1.GetDualSolution(constraint), dual_solution_expected, tol)); cost.evaluator()->UpdateCoefficients(Eigen::Vector2d(-3, -4)); MathematicalProgramResult result2; solver.Solve(prog, {}, {}, &result2); EXPECT_TRUE(result2.is_success()); Eigen::Matrix2d Aeq; Aeq.row(0) = A.row(0); Aeq.row(1) = A.row(4); dual_solution_expected << -1.5, 0, 0, 0, -0.5; EXPECT_TRUE(CompareMatrices(result2.GetDualSolution(constraint), dual_solution_expected, tol)); } } void TestLPDualSolution2(const SolverInterface& solver, double tol) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto constraint = prog.AddBoundingBoxConstraint(Eigen::Vector2d(-1, 2), Eigen::Vector2d(3, 5), x); prog.AddLinearCost(x[0] - x[1]); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint), Eigen::Vector2d(1, -1), tol)); } } void TestLPDualSolution2Scaled(const SolverInterface& solver, double tol) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto constraint = prog.AddBoundingBoxConstraint(Eigen::Vector2d(-1, 2), Eigen::Vector2d(3, 5), x); prog.AddLinearCost(x[0] - x[1]); prog.SetVariableScaling(x[0], 10); prog.SetVariableScaling(x[1], 0.1); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint), Eigen::Vector2d(1, -1), tol)); } } void TestLPDualSolution3(const SolverInterface& solver, double tol) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); auto constraint1 = prog.AddBoundingBoxConstraint(-2, 1, x); auto constraint2 = prog.AddBoundingBoxConstraint(-1, 2, x[1]); auto constraint3 = prog.AddBoundingBoxConstraint(-1, 3, x[0]); prog.AddLinearCost(-x[0] + x[1]); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, {}, {}, &result); EXPECT_TRUE(result.is_success()); // The optimal solution is (1, -1). // constraint1 has an upper bound x(0) <= 1 being active. EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint1), Eigen::Vector2d(-1, 0), tol)); // constraint2 has a lower bound x(1) >= -1 being active. EXPECT_TRUE( CompareMatrices(result.GetDualSolution(constraint2), Vector1d(1), tol)); // constraint 3 is not active. EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint3), Vector1d::Zero(), tol)); } } void TestLPDualSolution4(const SolverInterface& solver, double tol) { unused(tol); MathematicalProgram prog; auto x = prog.NewContinuousVariables<4>(); auto constraint1 = prog.AddLinearEqualityConstraint(x(0) + 2 * x(1) + 3 * x(3) == 4); Eigen::Matrix2d A2; A2 << 1, 3, -2, 2; auto constraint2 = prog.AddLinearEqualityConstraint(A2, Eigen::Vector2d(2, 5), x.segment<2>(1)); prog.AddLinearCost(x(0) + 5 * x(1) - 7 * x(2) + 3 * x(3)); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, std::nullopt, std::nullopt, &result); ASSERT_TRUE(result.is_success()); const Eigen::VectorXd dual1 = result.GetDualSolution(constraint1); EXPECT_TRUE(CompareMatrices(dual1, Vector1d(1), tol)); const Eigen::VectorXd dual2 = result.GetDualSolution(constraint2); EXPECT_TRUE(CompareMatrices(dual2, Vector2d(-1, -2), tol)); } } void TestLPDualSolution5(const SolverInterface& solver, double tol) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); // 1 <= x(1) <= 3 // 2 <= x(2) <= 2 auto bbcon1 = prog.AddBoundingBoxConstraint( Eigen::Vector2d(1, 2), Eigen::Vector2d(3, 2), x.tail<2>()); // -1 <= x(0) <= -1 // -2 <= x(1) <= 1 // // Note that after aggregating all bounds, the bounds on x(1) are 1 <= x(1) <= // 1, but its lower bound comes from bbcon1, while its upper bound comes from // bbcon2. This will have implication on its dual solution, as we explain // later. auto bbcon2 = prog.AddBoundingBoxConstraint( Eigen::Vector2d(-1, -2), Eigen::Vector2d(-1, 1), x.head<2>()); prog.AddLinearCost(x(0) + 2 * x(1) + 3 * x(2)); MathematicalProgramResult result; if (solver.available()) { solver.Solve(prog, std::nullopt, std::nullopt, &result); EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.GetSolution(x), Eigen::Vector3d(-1, 1, 2), tol)); const Eigen::Vector2d bbcon1_dual_sol = result.GetDualSolution(bbcon1); const Eigen::Vector2d bbcon2_dual_sol = result.GetDualSolution(bbcon2); // The dual solution is the coefficient of the variable in the cost. EXPECT_NEAR(bbcon1_dual_sol(1), 3, tol); EXPECT_NEAR(bbcon2_dual_sol(0), 1, tol); // The dual solution for the constraint x(1) >= 1 is bbcon1_dual_sol(0), the // dual solution for the constraint x(1) <= 1 is bbcon2_dual_sol(1). 1 <= // x(1) <= 1 is equivalent to x(1) = 1. We know the dual solution for x(1) = // 1 is 2. The dual solution for x(1) >= 1 and x(1) <= 1 is not unique, but // it will have the invariance that the sum of their dual solution is // equivalent to the dual solution of x(1) = 1, which is 2. EXPECT_NEAR(bbcon1_dual_sol(0) + bbcon2_dual_sol(1), 2, tol); } } void TestLPPoorScaling1(const SolverInterface& solver, bool expect_success, double tol, const std::optional<SolverOptions>& options) { MathematicalProgram prog; const auto alpha = prog.NewContinuousVariables<4>(); const auto z = prog.NewContinuousVariables<1>()(0); const double eps = 5.5511151231257827e-17; Eigen::Matrix<double, 2, 4> vertices; // clang-format off vertices << eps, 1, eps, 1, eps, 1, 2, 2; // clang-format on const Eigen::Vector2d pt(0.99, 1.99); prog.AddLinearConstraint(-z + vertices.row(0).dot(alpha) <= pt(0)); prog.AddLinearConstraint(-z + vertices.row(1).dot(alpha) <= pt(1)); prog.AddLinearConstraint(z + vertices.row(0).dot(alpha) >= pt(0)); prog.AddLinearConstraint(z + vertices.row(1).dot(alpha) >= pt(1)); prog.AddBoundingBoxConstraint(0, 1, alpha); prog.AddLinearCost(z); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, std::nullopt, options, &result); const auto alpha_sol = result.GetSolution(alpha); ASSERT_TRUE(result.is_success()); if (expect_success) { EXPECT_TRUE(CompareMatrices(vertices * alpha_sol, pt, tol)); EXPECT_NEAR(result.GetSolution(z), 0, tol); } else { EXPECT_GT(result.GetSolution(z), tol); } } } void TestLPPoorScaling2(const SolverInterface& solver, bool expect_success, double tol, const std::optional<SolverOptions>& options) { Eigen::Matrix<double, 10, 3> A; A.topRows<3>() = Eigen::Matrix3d::Identity(); A.middleRows<3>(3) = -Eigen::Matrix3d::Identity(); // clang-format off A.bottomRows<4>() << 9.99400723e-01, -1.75186298e-21, 3.46149414e-02, 9.82328785e-01, 1.82238474e-20, -1.87163452e-01, 9.68599420e-01, -2.48626556e-01, -1.27003703e-12, 9.68599420e-01, 2.48626556e-01, -1.27003703e-12; // clang-format on Eigen::Matrix<double, 10, 1> b; b << 1.0, 0.5, 1.0, -0.0, 0.5, -0.0, 0.46783912, 0.39023174, 0.50647967, 0.50647967; MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); auto r = prog.NewContinuousVariables<1>()(0); for (int i = 0; i < A.rows(); ++i) { prog.AddLinearConstraint(A.row(i).dot(x) + A.row(i).norm() * r <= b(i)); } prog.AddBoundingBoxConstraint(0, kInf, r); prog.AddLinearCost(-r); if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog, std::nullopt, options, &result); ASSERT_TRUE(result.is_success()); const Eigen::Vector3d x_expected(0.2282, 0, 0.3323); if (expect_success) { EXPECT_TRUE(CompareMatrices(result.GetSolution(x), x_expected, tol)); } else { EXPECT_GT((result.GetSolution(x) - x_expected).norm(), tol); } } } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/augmented_lagrangian_test.cc
#include "drake/solvers/augmented_lagrangian.h" #include <limits> #include <gtest/gtest.h> #include "drake/common/extract_double.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/math/autodiff_gradient.h" #include "drake/solvers/aggregate_costs_constraints.h" #include "drake/solvers/mathematical_program.h" namespace drake { namespace solvers { namespace { const double kInf = std::numeric_limits<double>::infinity(); // This function is only used in AugmentedLagrangian.TestEmptyProg. template <typename AL> void TestEmptyProg(const AL& dut) { EXPECT_EQ(dut.lagrangian_size(), 0); EXPECT_TRUE(dut.is_equality().empty()); Eigen::Vector2d x_val(1, 2); // Now the program has no cost nor constraint. Its augmented Lagrangian is // zero. Eigen::VectorXd constraint_residue; double cost; double al_val; if constexpr (std::is_same_v<AL, AugmentedLagrangianNonsmooth>) { al_val = dut.template Eval<double>(x_val, Eigen::VectorXd(0), 0.5, &constraint_residue, &cost); } else { al_val = dut.template Eval<double>(x_val, Eigen::VectorXd(0), Eigen::VectorXd(0), 0.5, &constraint_residue, &cost); } EXPECT_EQ(al_val, 0); EXPECT_EQ(constraint_residue.rows(), 0); EXPECT_EQ(cost, 0); EXPECT_TRUE(CompareMatrices(dut.x_lo(), Eigen::Vector2d::Constant(-kInf))); EXPECT_TRUE(CompareMatrices(dut.x_up(), Eigen::Vector2d::Constant(kInf))); } GTEST_TEST(AugmentedLagrangian, TestEmptyProg) { // Construct an un-constrained program. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); const AugmentedLagrangianNonsmooth dut_nonsmooth(&prog, false); TestEmptyProg(dut_nonsmooth); const AugmentedLagrangianSmooth dut_smooth(&prog, false); TestEmptyProg(dut_smooth); } template <typename AL> void TestObjective(const AL& dut) { EXPECT_EQ(dut.lagrangian_size(), 0); EXPECT_TRUE(dut.is_equality().empty()); // Now evaluate the augmented Lagrangian, it should just be the same as the // costs. Eigen::Vector2d x_val(1, 2); double cost_expected = 0; for (const auto& binding : dut.prog().GetAllCosts()) { cost_expected += dut.prog().EvalBinding(binding, x_val)(0); } Eigen::VectorXd constraint_residue; double cost; double al_val; if constexpr (std::is_same_v<AL, AugmentedLagrangianNonsmooth>) { al_val = dut.template Eval<double>(x_val, Eigen::VectorXd(0), 0.5, &constraint_residue, &cost); } else { al_val = dut.template Eval<double>(x_val, Eigen::VectorXd(0), Eigen::VectorXd(0), 0.5, &constraint_residue, &cost); } EXPECT_EQ(al_val, cost_expected); EXPECT_EQ(cost, cost_expected); EXPECT_EQ(constraint_residue.rows(), 0); // Now evaluate the augmented Lagrangian with autodiff. VectorX<AutoDiffXd> constraint_residue_ad; AutoDiffXd cost_ad; AutoDiffXd al_ad; const auto x_ad = math::InitializeAutoDiff(x_val); if constexpr (std::is_same_v<AL, AugmentedLagrangianNonsmooth>) { al_ad = dut.template Eval<AutoDiffXd>(x_ad, Eigen::VectorXd(0), 0.5, &constraint_residue_ad, &cost_ad); } else { al_ad = dut.template Eval<AutoDiffXd>(x_ad, AutoDiffVecXd(0), Eigen::VectorXd(0), 0.5, &constraint_residue_ad, &cost_ad); } AutoDiffXd al_expected(0); for (const auto& binding : dut.prog().GetAllCosts()) { al_expected += dut.prog().EvalBinding(binding, x_ad)(0); } EXPECT_EQ(ExtractDoubleOrThrow(al_ad), ExtractDoubleOrThrow(al_expected)); EXPECT_TRUE(CompareMatrices(al_ad.derivatives(), al_expected.derivatives())); EXPECT_EQ(cost_ad.value(), al_expected.value()); EXPECT_TRUE( CompareMatrices(cost_ad.derivatives(), al_expected.derivatives())); EXPECT_EQ(constraint_residue_ad.rows(), 0); } GTEST_TEST(AugmentedLagrangian, TestObjective1) { // Test with an empty program. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); for (bool include_x_bounds : {false, true}) { const AugmentedLagrangianNonsmooth dut_nonsmooth(&prog, include_x_bounds); TestObjective(dut_nonsmooth); const AugmentedLagrangianSmooth dut_smooth(&prog, include_x_bounds); TestObjective(dut_smooth); } } GTEST_TEST(AugmentedLagrangian, TestObjective2) { // Test a program with costs but no constraints. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); // Now add costs auto cost1 = prog.AddQuadraticCost(x[0] * x[0] + 2 * x[1] + 3); auto cost2 = prog.AddLinearCost(x[0] * 3 + 4); for (bool include_x_bounds : {false, true}) { const AugmentedLagrangianNonsmooth dut_nonsmooth(&prog, include_x_bounds); TestObjective(dut_nonsmooth); const AugmentedLagrangianSmooth dut_smooth(&prog, include_x_bounds); TestObjective(dut_smooth); } } class DummyConstraint final : public solvers::Constraint { public: DummyConstraint() : Constraint(4, 2, Eigen::Vector4d(1, 2, 3, 4), Eigen::Vector4d(1, 2, 3, 4)) {} using Constraint::set_bounds; protected: template <typename T> void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x, VectorX<T>* y) const { y->resize(num_constraints()); (*y)(0) = x(0) * x(1) + 1; (*y)(1) = x(0) + x(1); (*y)(2) = 2 * x(0) + 3; (*y)(3) = 2 * x(0) / x(1) + 4; } void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { DoEvalGeneric<double>(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric<AutoDiffXd>(x, y); } void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>& x, VectorX<symbolic::Expression>* y) const override { DoEvalGeneric<symbolic::Expression>(x.cast<symbolic::Expression>(), y); } }; template <typename T> void CompareAlResult(const T& al, const T& al_expected, const VectorX<T>& constraint_residue, const VectorX<T>& constraint_residue_expected, const T& cost, const T& cost_expected, double tol) { if constexpr (std::is_same_v<T, double>) { EXPECT_NEAR(al, al_expected, tol); EXPECT_TRUE( CompareMatrices(constraint_residue, constraint_residue_expected, tol)); EXPECT_NEAR(cost, cost_expected, tol); } else { EXPECT_NEAR(al.value(), al_expected.value(), tol); EXPECT_TRUE( CompareMatrices(al.derivatives(), al_expected.derivatives(), tol)); EXPECT_TRUE(CompareMatrices(math::ExtractValue(constraint_residue), math::ExtractValue(constraint_residue_expected), tol)); EXPECT_TRUE(CompareMatrices( math::ExtractGradient(constraint_residue), math::ExtractGradient(constraint_residue_expected), tol)); EXPECT_NEAR(cost.value(), cost_expected.value(), tol); EXPECT_TRUE( CompareMatrices(cost.derivatives(), cost_expected.derivatives(), tol)); } } template <typename T> T al_equality(const Eigen::Ref<const VectorX<T>>& lhs, const Eigen::Ref<const Eigen::VectorXd>& lambda, double mu) { return -lambda.dot(lhs) + mu / 2 * lhs.array().square().sum(); } // This function is only used inside the test // AugmentedLagrangianNonsmooth.EqualityConstraints. Next time we are making // any changes here, consider moving it to live directly within that test case // as a templated lambda. template <typename T> void CheckAugmentedLagrangianEqualityConstraint( const MathematicalProgram& prog, const Binding<Constraint>& constraint, const Vector3<T>& x_val, const Eigen::Vector4d& lambda_val, double mu_val, double tol_val, bool smooth_flag) { VectorX<T> constraint_residue; T cost; for (bool include_x_bounds : {false, true}) { T al_val; if (smooth_flag) { const AugmentedLagrangianSmooth dut(&prog, include_x_bounds); EXPECT_EQ(dut.lagrangian_size(), 4); EXPECT_EQ(dut.is_equality(), std::vector<bool>({true, true, true, true})); EXPECT_EQ(dut.s_size(), 0); al_val = dut.Eval<T>(x_val, VectorX<T>(0), lambda_val, mu_val, &constraint_residue, &cost); } else { const AugmentedLagrangianNonsmooth dut(&prog, include_x_bounds); EXPECT_EQ(dut.lagrangian_size(), 4); EXPECT_EQ(dut.is_equality(), std::vector<bool>({true, true, true, true})); al_val = dut.Eval<T>(x_val, lambda_val, mu_val, &constraint_residue, &cost); } const auto constraint_val = prog.EvalBinding(constraint, x_val); const auto& constraint_bound = constraint.evaluator()->lower_bound(); const T al_expected = al_equality<T>(constraint_val - constraint_bound, lambda_val, mu_val); EXPECT_EQ(constraint_residue.rows(), lambda_val.rows()); CompareAlResult<T>(al_val, al_expected, constraint_residue, constraint_val - constraint_bound, cost, T{0}, tol_val); } } GTEST_TEST(AugmentedLagrangian, EqualityConstraints) { // Test a program with on equality constraints. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); auto constraint = prog.AddConstraint(std::make_shared<DummyConstraint>(), x.head<2>()); const double tol = 1E-10; for (bool smooth_flag : {false, true}) { CheckAugmentedLagrangianEqualityConstraint( prog, constraint, Eigen::Vector3d(0.5, 1.5, 2), Eigen::Vector4d(1, 3, -2, 4), 0.2, tol, smooth_flag); CheckAugmentedLagrangianEqualityConstraint( prog, constraint, Eigen::Vector3d(-0.5, 2.5, 2), Eigen::Vector4d(-1, 2, 3, -2), 0.6, tol, smooth_flag); CheckAugmentedLagrangianEqualityConstraint( prog, constraint, math::InitializeAutoDiff(Eigen::Vector3d(0.5, 0.3, 0.2)), Eigen::Vector4d(1, 2, -3, -1), 0.5, tol, smooth_flag); } } // Refer to equation 17.55 of Numerical Optimization by Jorge Nocedal and // Stephen Wright, Edition 1, 1999 (This equation is not presented in Edition // 2). We use the alternative way to compute s first, and then compute psi. Note // that what we use for mu here is 1/μ in equation 17.55. template <typename T> T psi(const T& c, double lambda, double mu) { T s = c - lambda / mu; if (ExtractDoubleOrThrow(s) < 0) { s = T(0); } return -lambda * (c - s) + mu / 2 * (c - s) * (c - s); } template <typename T> void CheckAugmentedLagrangianNonsmoothInequalityConstraint( const MathematicalProgram& prog, const Binding<Constraint>& constraint, const Vector3<T>& x_val, const Eigen::Matrix<double, 5, 1>& lambda_val, double mu_val, double tol_val) { VectorX<T> constraint_residue; T cost; for (const bool include_x_bounds : {false, true}) { const AugmentedLagrangianNonsmooth dut(&prog, include_x_bounds); EXPECT_EQ(dut.lagrangian_size(), 5); EXPECT_EQ(dut.is_equality(), std::vector<bool>({true, false, false, false, false})); const T al = dut.Eval<T>(x_val, lambda_val, mu_val, &constraint_residue, &cost); const auto constraint_val = prog.EvalBinding(constraint, x_val); const auto& lb = constraint.evaluator()->lower_bound(); const auto& ub = constraint.evaluator()->upper_bound(); using std::pow; T al_expected = -lambda_val(0) * (constraint_val(0) - lb(0)) + mu_val / 2 * pow(constraint_val(0) - lb(0), 2) + psi(constraint_val(1) - lb(1), lambda_val(1), mu_val) + psi(ub(1) - constraint_val(1), lambda_val(2), mu_val) + psi(ub(2) - constraint_val(2), lambda_val(3), mu_val) + psi(constraint_val(3) - lb(3), lambda_val(4), mu_val); EXPECT_EQ(constraint_residue.rows(), lambda_val.rows()); VectorX<T> constraint_residue_expected(constraint_residue.rows()); constraint_residue_expected << constraint_val(0) - lb(0), constraint_val(1) - lb(1), ub(1) - constraint_val(1), ub(2) - constraint_val(2), constraint_val(3) - lb(3); CompareAlResult<T>(al, al_expected, constraint_residue, constraint_residue_expected, cost, T(0), tol_val); } } template <typename T> void CheckAugmentedLagrangianSmoothInequalityConstraint( const MathematicalProgram& prog, const Binding<Constraint>& constraint, const Vector3<T>& x_val, const Vector4<T>& s_val, const Eigen::Matrix<double, 5, 1>& lambda_val, double mu_val, double tol_val) { VectorX<T> constraint_residue; T cost; for (const bool include_x_bounds : {false, true}) { const AugmentedLagrangianSmooth dut(&prog, include_x_bounds); EXPECT_EQ(dut.lagrangian_size(), 5); EXPECT_EQ(dut.s_size(), 4); EXPECT_EQ(dut.is_equality(), std::vector<bool>({true, false, false, false, false})); const T al = dut.Eval<T>(x_val, s_val, lambda_val, mu_val, &constraint_residue, &cost); const auto constraint_val = prog.EvalBinding(constraint, x_val); const auto& lb = constraint.evaluator()->lower_bound(); const auto& ub = constraint.evaluator()->upper_bound(); using std::pow; Eigen::Matrix<T, 5, 1> lhs; lhs << constraint_val(0) - lb(0), constraint_val(1) - lb(1) - s_val(0), ub(1) - constraint_val(1) - s_val(1), ub(2) - constraint_val(2) - s_val(2), constraint_val(3) - lb(3) - s_val(3); T al_expected = al_equality<T>(lhs, lambda_val, mu_val); EXPECT_EQ(constraint_residue.rows(), lambda_val.rows()); VectorX<T> constraint_residue_expected = lhs; CompareAlResult<T>(al, al_expected, constraint_residue, constraint_residue_expected, cost, T(0), tol_val); } } GTEST_TEST(AugmentedLagrangian, InequalityConstraint) { // Test with inequality constraints. MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); auto constraint_evaluator = std::make_shared<DummyConstraint>(); constraint_evaluator->set_bounds(Eigen::Vector4d(1, -1, -kInf, 2), Eigen::Vector4d(1, 2, 3, kInf)); auto constraint = prog.AddConstraint(constraint_evaluator, x.tail<2>()); const double tol = 1E-10; CheckAugmentedLagrangianNonsmoothInequalityConstraint( prog, constraint, Eigen::Vector3d(1, 3, 2), (Eigen::Matrix<double, 5, 1>() << 0.5, 0.4, 1.5, 0.2, 3).finished(), 0.5, tol); CheckAugmentedLagrangianNonsmoothInequalityConstraint( prog, constraint, Eigen::Vector3d(-1, 3, -5), (Eigen::Matrix<double, 5, 1>() << -.5, 1.4, 1.5, 0.5, 3).finished(), 0.2, tol); CheckAugmentedLagrangianNonsmoothInequalityConstraint( prog, constraint, math::InitializeAutoDiff(Eigen::Vector3d(-1, 3, -5)), (Eigen::Matrix<double, 5, 1>() << -.5, 1.4, 1.5, 0.5, 3).finished(), 0.2, tol); CheckAugmentedLagrangianSmoothInequalityConstraint( prog, constraint, Eigen::Vector3d(1, 3, 2), Eigen::Vector4d(3, -1, -2, 1), (Eigen::Matrix<double, 5, 1>() << 0.5, 0.4, 1.5, 0.2, 3).finished(), 0.5, tol); CheckAugmentedLagrangianSmoothInequalityConstraint( prog, constraint, math::InitializeAutoDiff(Eigen::Vector3d(1, 3, 2)), Vector4<AutoDiffXd>(AutoDiffXd(3), AutoDiffXd(-1), AutoDiffXd(-2), AutoDiffXd(1)), (Eigen::Matrix<double, 5, 1>() << 0.5, 0.4, 1.5, 0.2, 3).finished(), 0.5, tol); } template <typename T> void CheckAugmentedLagrangianNonsmoothBoundingBoxConstraint( const MathematicalProgram& prog, const Vector4<T>& x_val, const Eigen::Matrix<double, 5, 1>& lambda, double mu, double tol_val) { const AugmentedLagrangianNonsmooth dut(&prog, true); EXPECT_EQ(dut.lagrangian_size(), 5); EXPECT_EQ(dut.is_equality(), std::vector<bool>({true, false, false, false, false})); VectorX<T> constraint_residue; T cost; const T al = dut.Eval<T>(x_val, lambda, mu, &constraint_residue, &cost); EXPECT_EQ(constraint_residue.rows(), lambda.rows()); Eigen::VectorXd x_lb, x_ub; AggregateBoundingBoxConstraints(prog, &x_lb, &x_ub); const T al_expected = -lambda(0) * (x_val(0) - x_lb(0)) + mu / 2 * (x_val(0) - x_lb(0)) * (x_val(0) - x_lb(0)) + psi(x_val(1) - x_lb(1), lambda(1), mu) + psi(x_ub(2) - x_val(2), lambda(2), mu) + psi(x_val(3) - x_lb(3), lambda(3), mu) + psi(x_ub(3) - x_val(3), lambda(4), mu); Eigen::Matrix<T, 5, 1> constraint_residue_expected; constraint_residue_expected << x_val(0) - x_lb(0), x_val(1) - x_lb(1), x_ub(2) - x_val(2), x_val(3) - x_lb(3), x_ub(3) - x_val(3); CompareAlResult<T>(al, al_expected, constraint_residue, constraint_residue_expected, cost, T(0), tol_val); Eigen::VectorXd x_lo_expected, x_up_expected; AggregateBoundingBoxConstraints(prog, &x_lo_expected, &x_up_expected); EXPECT_TRUE(CompareMatrices(dut.x_lo(), x_lo_expected)); EXPECT_TRUE(CompareMatrices(dut.x_up(), x_up_expected)); } template <typename T> void CheckAugmentedLagrangianSmoothBoundingBoxConstraint( const MathematicalProgram& prog, const Vector4<T>& x_val, const Vector4<T>& s_val, const Eigen::Matrix<double, 5, 1>& lambda, double mu, double tol_val) { const AugmentedLagrangianSmooth dut(&prog, true); EXPECT_EQ(dut.lagrangian_size(), 5); EXPECT_EQ(dut.s_size(), 4); EXPECT_EQ(dut.is_equality(), std::vector<bool>({true, false, false, false, false})); VectorX<T> constraint_residue; T cost; const T al = dut.Eval<T>(x_val, s_val, lambda, mu, &constraint_residue, &cost); EXPECT_EQ(constraint_residue.rows(), lambda.rows()); Eigen::VectorXd x_lb, x_ub; AggregateBoundingBoxConstraints(prog, &x_lb, &x_ub); Eigen::Matrix<T, 5, 1> lhs; lhs << x_val(0) - x_lb(0), x_val(1) - x_lb(1) - s_val(0), x_ub(2) - x_val(2) - s_val(1), x_val(3) - x_lb(3) - s_val(2), x_ub(3) - x_val(3) - s_val(3); const T al_expected = al_equality<T>(lhs, lambda, mu); Eigen::Matrix<T, 5, 1> constraint_residue_expected = lhs; CompareAlResult<T>(al, al_expected, constraint_residue, constraint_residue_expected, cost, T(0), tol_val); Eigen::VectorXd x_lo_expected, x_up_expected; AggregateBoundingBoxConstraints(prog, &x_lo_expected, &x_up_expected); EXPECT_TRUE(CompareMatrices(dut.x_lo(), x_lo_expected)); EXPECT_TRUE(CompareMatrices(dut.x_up(), x_up_expected)); } // This function should only be called inside // EvalAugmentedLagrangian.BoundingBoxConstraint when include_x_bounds=false. template <typename AL> void CheckBoundingBoxConstraintEmpty(const AL& dut) { DRAKE_DEMAND(dut.include_x_bounds() == false); EXPECT_EQ(dut.lagrangian_size(), 0); EXPECT_TRUE(dut.is_equality().empty()); VectorX<double> constraint_residue; double cost; double al_val; if constexpr (std::is_same_v<AL, AugmentedLagrangianNonsmooth>) { al_val = dut.template Eval<double>(Eigen::Vector4d(1, 2, 3, 4), Eigen::VectorXd(0), 0.5, &constraint_residue, &cost); } else { al_val = dut.template Eval<double>(Eigen::Vector4d(1, 2, 3, 4), Eigen::VectorXd(0), Eigen::VectorXd(0), 0.5, &constraint_residue, &cost); EXPECT_EQ(dut.s_size(), 0); } EXPECT_EQ(al_val, 0); EXPECT_EQ(constraint_residue.rows(), 0); Eigen::VectorXd x_lo_expected, x_up_expected; AggregateBoundingBoxConstraints(dut.prog(), &x_lo_expected, &x_up_expected); EXPECT_TRUE(CompareMatrices(dut.x_lo(), x_lo_expected)); EXPECT_TRUE(CompareMatrices(dut.x_up(), x_up_expected)); } GTEST_TEST(EvalAugmentedLagrangian, BoundingBoxConstraint) { // Test with bounding box constraint. MathematicalProgram prog; auto x = prog.NewContinuousVariables<4>(); auto constraint1 = prog.AddBoundingBoxConstraint( Eigen::Vector4d(1, 3, -kInf, 0), Eigen::Vector4d(2, kInf, -1, 5), x); auto constraint2 = prog.AddBoundingBoxConstraint( Eigen::Vector4d(2, 1, -kInf, 1), Eigen::Vector4d(5, kInf, -1, 3), x); const double tol = 1E-10; CheckAugmentedLagrangianNonsmoothBoundingBoxConstraint( prog, Eigen::Vector4d(1, 3, 5, 2), (Eigen::Matrix<double, 5, 1>() << 0.5, 0.3, 1.5, 2, 1).finished(), 0.5, tol); CheckAugmentedLagrangianNonsmoothBoundingBoxConstraint( prog, math::InitializeAutoDiff(Eigen::Vector4d(1, 3, 5, 2)), (Eigen::Matrix<double, 5, 1>() << 0.5, 0.3, 1.5, 2, 1).finished(), 0.5, tol); CheckAugmentedLagrangianSmoothBoundingBoxConstraint( prog, Eigen::Vector4d(1, 3, 5, 2), Eigen::Vector4d(2, 1, -2, 3), (Eigen::Matrix<double, 5, 1>() << 0.5, 0.3, 1.5, 2, 1).finished(), 0.5, tol); CheckAugmentedLagrangianSmoothBoundingBoxConstraint( prog, math::InitializeAutoDiff(Eigen::Vector4d(1, 3, 5, 2)), math::InitializeAutoDiff(Eigen::Vector4d(2, 1, -2, 3)), (Eigen::Matrix<double, 5, 1>() << 0.5, 0.3, 1.5, 2, 1).finished(), 0.5, tol); // Test include_x_bounds = false, the augmented lagrangian is 0. const AugmentedLagrangianNonsmooth dut_nonsmooth(&prog, false); CheckBoundingBoxConstraintEmpty(dut_nonsmooth); const AugmentedLagrangianSmooth dut_smooth(&prog, false); CheckBoundingBoxConstraintEmpty(dut_smooth); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/equality_constrained_qp_solver_test.cc
#include "drake/solvers/equality_constrained_qp_solver.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solve.h" #include "drake/solvers/test/mathematical_program_test_util.h" #include "drake/solvers/test/quadratic_program_examples.h" using Eigen::Matrix2d; using Eigen::MatrixXd; using Eigen::Vector2d; using Eigen::VectorXd; namespace drake { namespace solvers { namespace test { // // Test how an unconstrained QP is dispatched and solved: // - on the problem (x1 - 1)^2 + (x2 - 1)^2, with a min at // at (x1=1, x2=1). // - on the same problem plus the additional problem // (x2 - 3)^2 + (2*x3 - 4)^2, which, when combined // with the first problem, has min at (x1=1, x2=2, x3=2) // The first case tests a single quadratic cost, and the // second case tests multiple quadratic costs affecting // different variable views. All fall under the // umbrella of the Equality Constrained QP Solver. GTEST_TEST(testEqualityConstrainedQPSolver, testUnconstrainedQPDispatch) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>(); prog.AddCost(pow(x(0) - 1, 2) + pow(x(1) - 1, 2)); MathematicalProgramResult result = Solve(prog); VectorXd expected_answer(2); expected_answer << 1.0, 1.0; auto x_value = result.GetSolution(x); EXPECT_TRUE(CompareMatrices(expected_answer, x_value, 1e-10, MatrixCompareType::absolute)); EXPECT_NEAR(0.0, result.get_optimal_cost(), 1e-10); // There are no inequality constraints, and only quadratic costs, // so this should hold: EXPECT_EQ(result.get_solver_id(), EqualityConstrainedQPSolver::id()); // Add one more variable and constrain a view into them. auto y = prog.NewContinuousVariables<1>("y"); prog.AddCost(pow(x(1) - 3, 2) + pow(2 * y(0) - 4, 2)); prog.SetInitialGuessForAllVariables(Eigen::Vector3d::Zero()); result = Solve(prog); expected_answer.resize(3); expected_answer << 1.0, 2.0, 2.0; VectorXd actual_answer(3); x_value = result.GetSolution(x); const auto& y_value = result.GetSolution(y); actual_answer << x_value, y_value; EXPECT_TRUE(CompareMatrices(expected_answer, actual_answer, 1e-10, MatrixCompareType::absolute)); EXPECT_NEAR(2.0, result.get_optimal_cost(), 1e-10); // Problem still has only quadratic costs, so solver should be the same. EXPECT_EQ(result.get_solver_id(), EqualityConstrainedQPSolver::id()); } // Test how an equality-constrained QP is dispatched // - on the problem (x1 - 1)^2 + (x2 - 1)^2, with a min at // at (x1=1, x2=1), constrained with (x1 + x2 = 1). // The resulting constrained min is at (x1=0.5, x2=0.5). // - on the same problem with an additional variable x3, // with (2*x1 - x3 = 0). Resulting solution should be // (x1=0.5, x2=0.5, x3=1.0) GTEST_TEST(testEqualityConstrainedQPSolver, testLinearlyConstrainedQPDispatch) { MathematicalProgram prog; auto x = prog.NewContinuousVariables(2); prog.AddCost(pow(x(0) - 1, 2) + pow(x(1) - 1, 2)); // x1 + x2 = 1 auto constraint1 = prog.AddLinearConstraint(x(0) + x(1) == 1); prog.SetInitialGuessForAllVariables(Eigen::Vector2d::Zero()); MathematicalProgramResult result = Solve(prog); VectorXd expected_answer(2); expected_answer << 0.5, 0.5; auto x_value = result.GetSolution(x); EXPECT_TRUE(CompareMatrices(expected_answer, x_value, 1e-10, MatrixCompareType::absolute)); EXPECT_NEAR(0.5, result.get_optimal_cost(), 1e-10); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint1), Vector1d(-1), 1e-14)); // This problem is now an Equality Constrained QP and should // use this solver: EXPECT_EQ(result.get_solver_id(), EqualityConstrainedQPSolver::id()); // Add one more variable and constrain it in a different way auto y = prog.NewContinuousVariables(1); // 2*x1 - y = 0, so y should wind up as 1.0 auto constraint2 = prog.AddLinearConstraint(2 * x(0) - y(0) == 0); prog.SetInitialGuessForAllVariables(Eigen::Vector3d::Zero()); result = Solve(prog, Eigen::Vector3d::Zero()); expected_answer.resize(3); expected_answer << 0.5, 0.5, 1.0; VectorXd actual_answer(3); x_value = result.GetSolution(x); auto y_value = result.GetSolution(y); actual_answer << x_value, y_value; EXPECT_TRUE(CompareMatrices(expected_answer, actual_answer, 1e-10, MatrixCompareType::absolute)); EXPECT_NEAR(0.5, result.get_optimal_cost(), 1e-10); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint1), Vector1d(-1), 1e-14)); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint2), Vector1d(0.), 1e-14)); } GTEST_TEST(testEqualityConstrainedQPSolver, testNotStrictlyPositiveDefiniteHessianQP) { // Cost is x(0)² - x(0). The Hessian is positive semidefinite, but not // strictly positive definite, as it has an eigen value equal to 0. // The problem has infinitely many optimal solutions, as (0.5, ANYTHING), and // a unique optimal cost -0.25. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost((x(0) - 1) * x(0)); EqualityConstrainedQPSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); EXPECT_NEAR(result.GetSolution(x(0)), 0.5, 1E-10); EXPECT_NEAR(result.get_optimal_cost(), -0.25, 1E-10); } GTEST_TEST(testEqualityConstrainedQPSolver, testNonPositiveSemidefiniteHessianQP) { // Cost is x(0)² - x(1)². The Hessian has a negative eigen value, the problem // is unbounded. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost(x(0) * x(0) - x(1) * x(1)); EqualityConstrainedQPSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kUnboundedCost); } GTEST_TEST(testEqualityConstrainedQPSolver, testUnboundedQP) { // Cost is x(0)² - 2 * x(1). The Hessian is positive semidefinite, but not // strictly positive definite, as it has an eigen value equal to 0. // The problem is unbounded, since x(1) can be as large as possible. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost(x(0) * x(0) - 2 * x(1)); EqualityConstrainedQPSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kUnboundedCost); } GTEST_TEST(testEqualityConstrainedQPSolver, testNegativeDefiniteHessianQP) { // Cost is -x(0)² - 2 * x(1). The Hessian is negative semidefinite. // The problem is unbounded. MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost(-x(0) * x(0) - 2 * x(1)); EqualityConstrainedQPSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kUnboundedCost); } // Test a QP with positive definite Hessian, but infeasible constraint. // min x(0)² + 2 * x(1)² + x(0) * x(1) // s.t x(0) + 2 * x(1) = 1 // x(0) - x(1) = 3 // 2 * x(0) + x(1) = 2 GTEST_TEST(testEqualityConstrainedQPSolver, testPositiveHessianInfeasibleConstraint) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost(x(0) * x(0) + 2 * x(1) * x(1) + x(0) * x(1)); prog.AddLinearConstraint(x(0) + 2 * x(1) == 1 && x(0) - x(1) == 3 && 2 * x(0) + x(1) == 2); EqualityConstrainedQPSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kInfeasibleConstraints); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kGlobalInfeasibleCost); } // Test a QP with indefinite Hessian, but unique minimum. // min x(0)² - x(1)² // s.t x(1) = 1 GTEST_TEST(testEqualityConstrainedQPSolver, testIndefiniteHessian) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost(x(0) * x(0) - x(1) * x(1)); auto constraint = prog.AddLinearConstraint(x(1) == 1); EqualityConstrainedQPSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); EXPECT_TRUE(CompareMatrices(result.GetSolution(x), Eigen::Vector2d(0, 1), 1E-12, MatrixCompareType::absolute)); EXPECT_NEAR(result.get_optimal_cost(), -1, 1E-12); EXPECT_TRUE( CompareMatrices(result.GetDualSolution(constraint), Vector1d(-2), 1E-12)); } // Test a QP with positive semidefinite Hessian, but unbounded objective. // min x(0)² - 2 * x(1) // s.t x(0) = 1 GTEST_TEST(testEqualityConstrainedQPSolver, testPSDhessianUnbounded) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost(x(0) * x(0) - 2 * x(1)); prog.AddLinearConstraint(x(0) == 1); EqualityConstrainedQPSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kUnboundedCost); } // Test a QP with negative definite Hessian, but with a unique optimum. // min -x(0)² - x(1)² // s.t x(0) + x(1) = 2 // x(0) - x(1) = 3 GTEST_TEST(testEqualityConstrainedQPSolver, testNegativeHessianUniqueOptimum) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost(-x(0) * x(0) - x(1) * x(1)); Eigen::Matrix2d Aeq; Aeq << 1, 1, 1, -1; auto constraint = prog.AddLinearEqualityConstraint(Aeq, Eigen::Vector2d(2, 3), x); EqualityConstrainedQPSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); EXPECT_TRUE(CompareMatrices(result.GetSolution(x), Eigen::Vector2d(2.5, -0.5), 1E-12, MatrixCompareType::absolute)); EXPECT_NEAR(result.get_optimal_cost(), -6.5, 1E-12); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint), Eigen::Vector2d(-2, -3), 1e-12)); } // Test a QP with negative definite Hessian, and an unbounded objective. // min -x(0)² - x(1)² // s.t x(0) + x(1) == 1 GTEST_TEST(testEqualityConstrainedQPSolver, testNegativeHessianUnbounded) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost(-x(0) * x(0) - x(1) * x(1)); prog.AddLinearConstraint(x(0) + x(1) == 1); EqualityConstrainedQPSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kUnbounded); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kUnboundedCost); } // Test a QP with positive semidefinite Hessian (not strictly positive // definite), and a unique minimum. // min x(0)² + 2 * x(0) + 3 * x(1) // s.t x(0) + 2 * x(1) == 1 GTEST_TEST(testEqualityConstrainedQPSolver, testPSDHessianUniqueOptimal) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost(x(0) * x(0) + 2 * x(0) + 3 * x(1)); auto constraint = prog.AddLinearConstraint(x(0) + 2 * x(1) == 1); EqualityConstrainedQPSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); EXPECT_TRUE(CompareMatrices(result.GetSolution(x), Eigen::Vector2d(-1.0 / 4, 5.0 / 8), 1E-12, MatrixCompareType::absolute)); EXPECT_NEAR(result.get_optimal_cost(), 23.0 / 16.0, 1E-12); EXPECT_TRUE(CompareMatrices(result.GetDualSolution(constraint), Vector1d(1.5), 1e-12)); } // Test a QP with indefinite Hessian and infeasible constraints // min x(0)² - 2 * x(1)² // s.t x(0) + 2 * x(1) = 1 // -x(0) + 3 * x(1) = 2 // 2 * x(0) - 3 * x(1) = 3 GTEST_TEST(testEqualityConstrainedQPSolver, testIndefiniteHessianInfeasible) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost(x(0) * x(0) - 2 * x(1) * x(1)); prog.AddLinearConstraint(x(0) + 2 * x(1) == 1 && -x(0) + 3 * x(1) == 2 && 2 * x(0) - 3 * x(1) == 3); EqualityConstrainedQPSolver solver; auto result = solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kInfeasibleConstraints); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kGlobalInfeasibleCost); } // Test changing the feasibility tolerance. // For a problem // min x(0)² + 2 * x(1)² // s.t x(0) + 2 * x(1) = 1 // x(0) - x(1) = -2 // x(0) + x(1) = 1E-6 // when the feasibility tolerance is 1E-7, the problem is infeasible. // when we increase the feasibility tolerance, the problem is feasible. GTEST_TEST(testEqualityConstrainedQPSolver, testFeasibilityTolerance) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddCost(x(0) * x(0) + 2 * x(1) * x(1)); prog.AddLinearConstraint(x(0) + 2 * x(1) == 1 && x(0) - x(1) == -2 && x(0) + x(1) == 1E-6); EqualityConstrainedQPSolver solver; prog.SetSolverOption(EqualityConstrainedQPSolver::id(), "FeasibilityTol", 1E-7); auto result = solver.Solve(prog, {}, {}); EXPECT_EQ(result.get_solution_result(), SolutionResult::kInfeasibleConstraints); EXPECT_EQ(result.get_optimal_cost(), MathematicalProgram::kGlobalInfeasibleCost); // Now increase the feasibility tolerance. double tol = 1E-6; prog.SetSolverOption(EqualityConstrainedQPSolver::id(), EqualityConstrainedQPSolver::FeasibilityTolOptionName(), tol); result = solver.Solve(prog, {}, {}); EXPECT_TRUE(result.is_success()); const Eigen::Vector2d x_val = result.GetSolution(x); const Eigen::Vector3d cnstr_val(x_val(0) + 2 * x_val(1), x_val(0) - x_val(1), x_val(0) + x_val(1)); EXPECT_TRUE(CompareMatrices(cnstr_val, Eigen::Vector3d(1, -2, 1E-6), tol, MatrixCompareType::absolute)); EXPECT_NEAR(result.get_optimal_cost(), 3, 1E-6); // Now solve with a low feasibility tolerance again by passing the option in // the Solver function. The result should be infeasible. MathematicalProgramResult math_prog_result; SolverOptions solver_options; // The input solver option (1E-7) in `Solve` function takes priority over the // option stored in the prog (1E-6). solver_options.SetOption( EqualityConstrainedQPSolver::id(), EqualityConstrainedQPSolver::FeasibilityTolOptionName(), 0.1 * tol); solver.Solve(prog, {}, solver_options, &math_prog_result); EXPECT_FALSE(math_prog_result.is_success()); } // min x'*x + x0 + x1 + 1 // The solution is x0 = x1 = -.5, with optimal value .5. GTEST_TEST(testEqualityConstrainedQPSolver, testLinearCost) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<2>("x"); prog.AddQuadraticCost(x.transpose() * x); prog.AddLinearCost(x(0) + x(1) + 1); MathematicalProgramResult result; result = Solve(prog); EXPECT_TRUE(result.is_success()); EXPECT_TRUE( CompareMatrices(result.GetSolution(x), Eigen::Vector2d(-.5, -.5), 1e-6)); EXPECT_EQ(result.get_optimal_cost(), .5); } class EqualityConstrainedQPSolverTest : public ::testing::Test { public: EqualityConstrainedQPSolverTest() : prog_{}, x_{prog_.NewContinuousVariables<2>()}, solver_{}, result_{}, solver_options_{} { prog_.AddLinearEqualityConstraint(x_(0) + x_(1), 1); prog_.AddQuadraticCost(x_(0) * x_(0) + x_(1) * x_(1)); } protected: MathematicalProgram prog_; VectorDecisionVariable<2> x_; EqualityConstrainedQPSolver solver_; MathematicalProgramResult result_; SolverOptions solver_options_; }; TEST_F(EqualityConstrainedQPSolverTest, WrongSolverOptions1) { solver_options_.SetOption(solver_.solver_id(), "Foo", 0.1); DRAKE_EXPECT_THROWS_MESSAGE_IF_ARMED( solver_.Solve(prog_, {}, solver_options_, &result_), "Foo is not allowed in the SolverOptions for EqConstrainedQP."); } TEST_F(EqualityConstrainedQPSolverTest, WrongSolverOptions2) { solver_options_.SetOption(solver_.solver_id(), "FeasibilityTol", -0.1); DRAKE_EXPECT_THROWS_MESSAGE( solver_.Solve(prog_, {}, solver_options_, &result_), "FeasibilityTol should be a non-negative number."); } GTEST_TEST(TestEqualityConstrainedQP1, Test) { EqualityConstrainedQPSolver solver; TestEqualityConstrainedQP1(solver); } GTEST_TEST(EqualityConstrainedQPSolverDualSolutionTest, DualSolution1) { EqualityConstrainedQPSolver solver; TestEqualityConstrainedQPDualSolution1(solver); } GTEST_TEST(EqualityConstrainedQPSolverDualSolutionTest, DualSolution2) { EqualityConstrainedQPSolver solver; TestEqualityConstrainedQPDualSolution2(solver); } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/gurobi_solver_internal_test.cc
#include "drake/solvers/gurobi_solver_internal.h" #include <limits> #include <gtest/gtest.h> #include "drake/solvers/gurobi_solver.h" namespace drake { namespace solvers { namespace internal { const double kInf = std::numeric_limits<double>::infinity(); template <typename C> void ExpectVectorEqual(const std::vector<C>& vec1, const std::vector<C>& vec2) { EXPECT_EQ(vec1.size(), vec2.size()); for (int i = 0; i < ssize(vec1); ++i) { EXPECT_EQ(vec1[i], vec2[i]); } } GTEST_TEST(AddL2NormCostVariables, Test) { MathematicalProgram prog; auto x = prog.NewContinuousVariables<3>(); Eigen::Matrix<double, 3, 2> A0; A0 << 1, 2, 3, 4, 5, 6; const Eigen::Vector3d b0(1, 4, 7); auto cost0 = prog.AddL2NormCost(A0, b0, x.tail<2>()); Eigen::Matrix2d A1; A1 << -1, -2, -3, -4; const Eigen::Vector2d b1(-1, -4); auto cost1 = prog.AddL2NormCost(A1, b1, x.head<2>()); std::vector<bool> is_new_variable(prog.num_vars(), false); int num_gurobi_vars = prog.num_vars(); std::vector<std::vector<int>> lorentz_cone_variable_indices; std::vector<char> gurobi_var_type(prog.num_vars(), GRB_CONTINUOUS); std::vector<double> xlow(prog.num_vars(), -kInf); std::vector<double> xupp(prog.num_vars(), kInf); AddL2NormCostVariables(prog.l2norm_costs(), &is_new_variable, &num_gurobi_vars, &lorentz_cone_variable_indices, &gurobi_var_type, &xlow, &xupp); ExpectVectorEqual(is_new_variable, std::vector<bool>{{false, false, false, true, true, true, true, true, true, true}}); EXPECT_EQ(num_gurobi_vars, prog.num_vars() + (1 + cost0.evaluator()->get_sparse_A().rows()) + (1 + cost1.evaluator()->get_sparse_A().rows())); EXPECT_EQ(lorentz_cone_variable_indices.size(), 2); ExpectVectorEqual(lorentz_cone_variable_indices[0], std::vector<int>{{3, 4, 5, 6}}); ExpectVectorEqual(lorentz_cone_variable_indices[1], std::vector<int>{{7, 8, 9}}); ExpectVectorEqual(gurobi_var_type, std::vector<char>(num_gurobi_vars, GRB_CONTINUOUS)); ExpectVectorEqual(xlow, std::vector<double>{{-kInf, -kInf, -kInf, 0, -kInf, -kInf, -kInf, 0, -kInf, -kInf}}); ExpectVectorEqual(xupp, std::vector<double>(num_gurobi_vars, kInf)); } GTEST_TEST(AddL2NormCosts, Test) { MathematicalProgram prog; const auto x = prog.NewContinuousVariables<3>(); Eigen::Matrix<double, 3, 2> A0; A0 << 1, 2, 3, 4, 5, 6; const Eigen::Vector3d b0(4, 5, 6); const auto cost0 = prog.AddL2NormCost(A0, b0, x.tail<2>()); Eigen::Matrix<double, 2, 3> A1; A1 << -1, -3, -5, -2, -4, -6; const Eigen::Vector2d b1(10, 11); const auto cost1 = prog.AddL2NormCost(A1, b1, x); std::vector<bool> is_new_variable(prog.num_vars(), false); int num_gurobi_vars = prog.num_vars(); std::vector<std::vector<int>> lorentz_cone_variable_indices; std::vector<char> gurobi_var_type(prog.num_vars(), GRB_CONTINUOUS); std::vector<double> xlow(prog.num_vars(), -kInf); std::vector<double> xupp(prog.num_vars(), kInf); AddL2NormCostVariables(prog.l2norm_costs(), &is_new_variable, &num_gurobi_vars, &lorentz_cone_variable_indices, &gurobi_var_type, &xlow, &xupp); GRBenv* env{nullptr}; GRBmodel* model{nullptr}; GRBemptyenv(&env); GRBstartenv(env); GRBnewmodel(env, &model, "model", num_gurobi_vars, nullptr, &xlow[0], &xupp[0], gurobi_var_type.data(), nullptr); int num_gurobi_linear_constraints{0}; int error = AddL2NormCosts(prog, lorentz_cone_variable_indices, model, &num_gurobi_linear_constraints); GRBupdatemodel(model); EXPECT_EQ(error, 0); EXPECT_EQ(num_gurobi_linear_constraints, cost0.evaluator()->get_sparse_A().rows() + cost1.evaluator()->get_sparse_A().rows()); double cost_coeff{0}; GRBgetdblattrelement(model, "Obj", lorentz_cone_variable_indices[0][0], &cost_coeff); EXPECT_EQ(cost_coeff, 1); GRBgetdblattrelement(model, "Obj", lorentz_cone_variable_indices[1][0], &cost_coeff); EXPECT_EQ(cost_coeff, 1); int num_q_constrs; GRBgetintattr(model, "NumQConstrs", &num_q_constrs); EXPECT_EQ(num_q_constrs, 2); GRBfreemodel(model); GRBfreeenv(env); } } // namespace internal } // namespace solvers } // namespace drake int main(int argc, char** argv) { // Ensure that we have the Gurobi license for the entire duration of this // test, so that we do not have to release and re-acquire the license for // every test. auto gurobi_license = drake::solvers::GurobiSolver::AcquireLicense(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/csdp_cpp_wrapper_test.cc
#include "drake/solvers/csdp_cpp_wrapper.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/expect_throws_message.h" namespace drake { namespace solvers { namespace internal { // Try to solve a malformed program (k==0), expect an exception. // This is a test for exit/setjmp/longjmp handling. See #16732. GTEST_TEST(CsdpSolverInterrnalTest, ExitHandling) { csdp::blockmatrix C{}; struct csdp::blockmatrix X, Z; double* y{}; double pobj{}, dobj{}; DRAKE_EXPECT_THROWS_MESSAGE( csdp::cpp_easy_sdp(nullptr, 0, 0, C, nullptr, nullptr, 0, &X, &y, &Z, &pobj, &dobj), ".*CSDP.*fatal exception.*"); } } // namespace internal } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/l2norm_cost_examples.cc
#include "drake/solvers/test/l2norm_cost_examples.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" namespace drake { namespace solvers { namespace test { ShortestDistanceToThreePoints::ShortestDistanceToThreePoints() : prog_{} { x_ = prog_.NewContinuousVariables<3>(); pts_[0] = Eigen::Vector3d(1, 2, 3); pts_[1] = Eigen::Vector3d(4, 5, 6); pts_[2] = Eigen::Vector3d(4, -1, -9); for (int i = 0; i < 3; ++i) { prog_.AddL2NormCost(Eigen::Matrix3d::Identity(), -pts_[i], x_); } } void ShortestDistanceToThreePoints::CheckSolution( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol) const { MathematicalProgramResult result; if (solver.available() && solver.enabled()) { solver.Solve(prog_, std::nullopt, solver_options, &result); EXPECT_TRUE(result.is_success()); const Eigen::Vector3d x_sol = result.GetSolution(x_); // The solution of x is the Fermat point of the triangle. If the triangle // has an angle greater than 120 degrees, then the Fermat point is sited at // the obtuse-angled vertex. Here we constructed pts_[0] to be such vertex. // We verify that the angle at pts_[0] is larger than 120 degrees. if ((pts_[1] - pts_[0]).dot(pts_[2] - pts_[0]) / ((pts_[1] - pts_[0]).norm() * (pts_[2] - pts_[0]).norm()) > cos(M_PI / 3 * 2)) { throw std::runtime_error( "The angle at pts_[0] is less than 120 degrees, check whether pts_ " "is set correctly."); } const Eigen::Vector3d x_sol_expected = pts_[0]; EXPECT_TRUE(CompareMatrices(x_sol, x_sol_expected, tol)); EXPECT_NEAR(result.get_optimal_cost(), (pts_[0] - x_sol_expected).norm() + (pts_[1] - x_sol_expected).norm() + (pts_[2] - x_sol_expected).norm(), tol); } } ShortestDistanceFromCylinderToPoint::ShortestDistanceFromCylinderToPoint() : prog_{} { x_ = prog_.NewContinuousVariables<3>(); prog_.AddBoundingBoxConstraint(-1, 1, x_[2]); prog_.AddLorentzConeConstraint( Vector3<symbolic::Expression>(2, x_[0] * 1, x_[1] * 1)); pt_ = Eigen::Vector3d(1, 2, 5); prog_.AddL2NormCost(Eigen::Matrix3d::Identity(), -pt_, x_); } void ShortestDistanceFromCylinderToPoint::CheckSolution( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol) const { MathematicalProgramResult result; if (solver.available() && solver.enabled()) { solver.Solve(prog_, std::nullopt, solver_options, &result); const Eigen::Vector3d x_sol = result.GetSolution(x_); const Eigen::Vector3d x_sol_expected(2 / std::sqrt(5), 4 / std::sqrt(5), 1); EXPECT_TRUE(CompareMatrices(x_sol, x_sol_expected, tol)); EXPECT_NEAR(result.get_optimal_cost(), (x_sol_expected - pt_).norm(), tol); } } ShortestDistanceFromPlaneToTwoPoints::ShortestDistanceFromPlaneToTwoPoints() : prog_{} { x_ = prog_.NewContinuousVariables<3>(); // pts_[0] and pts_[1] are on the same side of the plane. pts_[0] = Eigen::Vector3d(1, 2, 3); pts_[1] = Eigen::Vector3d(-1, 3, 5); plane_normal_ = Eigen::Vector3d(2, 1, -2).normalized(); plane_pt_ = Eigen::Vector3d(2, 1, -1); // clang-format off A_ << 1, 3, -2, 2, 1, 4, 0, 1, 0; // clang-format on prog_.AddL2NormCost(A_, -pts_[0], x_); prog_.AddL2NormCost(A_, -pts_[1], x_); prog_.AddLinearEqualityConstraint(plane_normal_.transpose() * A_, plane_normal_.dot(plane_pt_), x_); } void ShortestDistanceFromPlaneToTwoPoints::CheckSolution( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol) const { MathematicalProgramResult result; if (solver.available() && solver.enabled()) { solver.Solve(prog_, std::nullopt, solver_options, &result); EXPECT_TRUE(result.is_success()); // To compute the optimal solution in the closed form, we first compute y = // A_ * x. y should be on the plane plane_normal.dot(y) = // plane_normal.dot(plane_pt). It is the intersection between the plane and // the line passing through pt0 and the mirroring of pt1 across the plane. const Eigen::Vector3d pt1_mirror = pts_[1] - (pts_[1] - plane_pt_).dot(plane_normal_) * plane_normal_ * 2; const Eigen::Vector3d x_sol = result.GetSolution(x_); const Eigen::Vector3d y = A_ * x_sol; EXPECT_NEAR(plane_normal_.dot(y), plane_normal_.dot(plane_pt_), tol); EXPECT_TRUE(CompareMatrices((pt1_mirror - y).cross(y - pts_[0]), Eigen::Vector3d::Zero(), tol)); EXPECT_NEAR(result.get_optimal_cost(), (y - pts_[0]).norm() + (y - pts_[1]).norm(), tol); } } } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/semidefinite_relaxation_test.cc
#include "drake/solvers/semidefinite_relaxation.h" #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/math/matrix_util.h" namespace drake { namespace solvers { namespace internal { using Eigen::Matrix2d; using Eigen::Matrix3d; using Eigen::MatrixXd; using Eigen::Vector2d; using Eigen::Vector3d; using Eigen::VectorXd; using symbolic::Variable; using symbolic::Variables; namespace { void SetRelaxationInitialGuess(const Eigen::Ref<const VectorXd>& y_expected, MathematicalProgram* relaxation) { const int N = y_expected.size() + 1; MatrixX<Variable> X = Eigen::Map<const MatrixX<Variable>>( relaxation->positive_semidefinite_constraints()[0].variables().data(), N, N); VectorXd x_expected(N); x_expected << y_expected, 1; const MatrixXd X_expected = x_expected * x_expected.transpose(); relaxation->SetInitialGuess(X, X_expected); } void SetRelaxationInitialGuess( const std::map<Variable, double>& expected_values, MathematicalProgram* relaxation) { for (const auto& [var, val] : expected_values) { relaxation->SetInitialGuess(var, val); } for (const auto& constraint : relaxation->positive_semidefinite_constraints()) { const int n = constraint.evaluator()->matrix_rows(); VectorXd x_expected(n); const MatrixX<Variable> X_var = Eigen::Map<const MatrixX<Variable>>( constraint.variables().data(), n, n); for (int i = 0; i < n - 1; ++i) { x_expected(i) = expected_values.at(X_var(i, n - 1)); } x_expected(n - 1) = 1; const MatrixXd X_expected = x_expected * x_expected.transpose(); relaxation->SetInitialGuess(X_var, X_expected); } } int NChoose2(int n) { return (n * (n - 1)) / 2; } const double kInf = std::numeric_limits<double>::infinity(); } // namespace GTEST_TEST(MakeSemidefiniteRelaxationTest, NoCostsNorConstraints) { MathematicalProgram prog; const auto y = prog.NewContinuousVariables<2>("y"); const auto relaxation = MakeSemidefiniteRelaxation(prog); // X is 3x3 symmetric. EXPECT_EQ(relaxation->num_vars(), 6); // X ≽ 0. EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); // X(-1,-1) = 1. EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2); } GTEST_TEST(MakeSemidefiniteRelaxationTest, UnsupportedCost) { MathematicalProgram prog; const auto y = prog.NewContinuousVariables<2>("y"); prog.AddCost(sin(y[0])); DRAKE_EXPECT_THROWS_MESSAGE( MakeSemidefiniteRelaxation(prog), ".*GenericCost was declared but is not supported."); } GTEST_TEST(MakeSemidefiniteRelaxationTest, UnsupportedConstraint) { MathematicalProgram prog; const auto y = prog.NewContinuousVariables<2>("y"); prog.AddConstraint(sin(y[0]) >= 0.2); DRAKE_EXPECT_THROWS_MESSAGE( MakeSemidefiniteRelaxation(prog), ".*GenericConstraint was declared but is not supported."); } GTEST_TEST(MakeSemidefiniteRelaxationTest, LinearCost) { MathematicalProgram prog; const auto y = prog.NewContinuousVariables<2>("y"); const Vector2d a(0.5, 0.7); const double b = 1.3; prog.AddLinearCost(a, b, y); auto relaxation = MakeSemidefiniteRelaxation(prog); EXPECT_EQ(relaxation->num_vars(), 6); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2); EXPECT_EQ(relaxation->linear_costs().size(), 1); const Vector2d y_test(1.3, 0.24); SetRelaxationInitialGuess(y_test, relaxation.get()); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess(relaxation->linear_costs()[0])[0], a.transpose() * y_test + b, 1e-12); // Confirm that the decision variables of prog are also decision variables of // the relaxation. std::vector<int> indices = relaxation->FindDecisionVariableIndices(y); EXPECT_EQ(indices.size(), 2); } GTEST_TEST(MakeSemidefiniteRelaxationTest, QuadraticCost) { MathematicalProgram prog; const auto y = prog.NewContinuousVariables<2>("y"); const Vector2d yd(0.5, 0.7); prog.AddQuadraticErrorCost(Matrix2d::Identity(), yd, y); auto relaxation = MakeSemidefiniteRelaxation(prog); EXPECT_EQ(relaxation->num_vars(), 6); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2); EXPECT_EQ(relaxation->linear_costs().size(), 1); SetRelaxationInitialGuess(yd, relaxation.get()); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess(relaxation->linear_costs()[0])[0], 0, 1e-12); } GTEST_TEST(MakeSemidefiniteRelaxationTest, BoundingBoxConstraint) { MathematicalProgram prog; const int N_VARS = 2; const auto y = prog.NewContinuousVariables<2>("y"); VectorXd lb(N_VARS); lb << -1.5, -2.0; VectorXd ub(N_VARS); ub << kInf, 2.3; prog.AddBoundingBoxConstraint(lb, ub, y); auto relaxation = MakeSemidefiniteRelaxation(prog); // We have 1 bounding box constraint. EXPECT_EQ(relaxation->bounding_box_constraints().size(), 1); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); // We have 1 linear constraint due to the product of the bounding box // constraints. EXPECT_EQ(relaxation->linear_constraints().size(), 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), 4); auto bbox_evaluator = relaxation->bounding_box_constraints()[0].evaluator(); EXPECT_TRUE(CompareMatrices(lb, bbox_evaluator->lower_bound())); EXPECT_TRUE(CompareMatrices(ub, bbox_evaluator->upper_bound())); const int N_CONSTRAINTS = 3; VectorXd b(N_CONSTRAINTS); b << -lb[0], -lb[1], ub[1]; // all the finite lower/upper bounds. MatrixXd A(N_CONSTRAINTS, 2); // Rows of A: // 1. Lower bound y[0] // 2. Lower bound y[1] // 3. Upper bound y[1] A << -1, 0, 0, -1, 0, 1; const Vector2d y_test(1.3, 0.24); SetRelaxationInitialGuess(y_test, relaxation.get()); // First linear constraint (in the new decision variables) is 0 ≤ // (Ay-b)(Ay-b)ᵀ, where A and b represent all of the constraints stacked. auto linear_constraint = relaxation->linear_constraints()[0]; VectorXd value = relaxation->EvalBindingAtInitialGuess(linear_constraint); MatrixXd expected_mat = (A * y_test - b) * (A * y_test - b).transpose() - b * b.transpose(); VectorXd expected = math::ToLowerTriangularColumnsFromMatrix(expected_mat); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); value = linear_constraint.evaluator()->lower_bound(); expected = math::ToLowerTriangularColumnsFromMatrix(-b * b.transpose()); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); } GTEST_TEST(MakeSemidefiniteRelaxationTest, LinearConstraint) { MathematicalProgram prog; const auto y = prog.NewContinuousVariables<2>("y"); MatrixXd A0(3, 2); A0 << 0.5, 0.7, -0.2, 0.4, -2.3, -4.5; const Vector3d lb0(1.3, -kInf, 0.25); const Vector3d ub0(5.6, 0.1, kInf); prog.AddLinearConstraint(A0, lb0, ub0, y); Matrix2d A1; A1 << 0.2, 1.2, 0.24, -0.1; const Vector2d lb1(-0.74, -0.3); const Vector2d ub1(-0.75, 0.9); prog.AddLinearConstraint(A1, lb1, ub1, Vector2<Variable>(y[1], y[0])); Matrix2d A1_reordered; A1_reordered.col(0) = A1.col(1); A1_reordered.col(1) = A1.col(0); auto relaxation = MakeSemidefiniteRelaxation(prog); EXPECT_EQ(relaxation->num_vars(), 6); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); EXPECT_EQ(relaxation->linear_constraints().size(), 3); EXPECT_EQ(relaxation->GetAllConstraints().size(), 5); const Vector2d y_test(1.3, 0.24); SetRelaxationInitialGuess(y_test, relaxation.get()); // First linear constraint is lb0 ≤ A0y ≤ ub0. EXPECT_TRUE(CompareMatrices( A0, relaxation->linear_constraints()[0].evaluator()->GetDenseA())); EXPECT_TRUE(CompareMatrices( lb0, relaxation->linear_constraints()[0].evaluator()->lower_bound())); EXPECT_TRUE(CompareMatrices( ub0, relaxation->linear_constraints()[0].evaluator()->upper_bound())); // Second linear constraint is lb1 ≤ A1 y ≤ ub1. EXPECT_TRUE(CompareMatrices( A1, relaxation->linear_constraints()[1].evaluator()->GetDenseA())); EXPECT_TRUE(CompareMatrices( lb1, relaxation->linear_constraints()[1].evaluator()->lower_bound())); EXPECT_TRUE(CompareMatrices( ub1, relaxation->linear_constraints()[1].evaluator()->upper_bound())); // Third linear (in the new decision variables) constraint is 0 ≤ // (Ay-b)(Ay-b)ᵀ, where A and b represent all of the constraints stacked. VectorXd b(8); // all of the finite lower/upper bounds. b << -lb0[0], ub0[0], ub0[1], -lb0[2], -lb1[0], ub1[0], -lb1[1], ub1[1]; MatrixXd A(8, 2); A << -A0.row(0), A0.row(0), A0.row(1), -A0.row(2), -A1_reordered.row(0), A1_reordered.row(0), -A1_reordered.row(1), A1_reordered.row(1); int expected_size = (b.size() * (b.size() + 1)) / 2; EXPECT_EQ(relaxation->linear_constraints()[2].evaluator()->num_constraints(), expected_size); VectorXd value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[2]); MatrixXd expected_mat = (A * y_test - b) * (A * y_test - b).transpose() - b * b.transpose(); VectorXd expected = math::ToLowerTriangularColumnsFromMatrix(expected_mat); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); value = relaxation->linear_constraints()[2].evaluator()->lower_bound(); expected = math::ToLowerTriangularColumnsFromMatrix(-b * b.transpose()); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); } GTEST_TEST(MakeSemidefiniteRelaxationTest, LinearEqualityConstraint) { MathematicalProgram prog; const auto y = prog.NewContinuousVariables<2>("y"); MatrixXd A(3, 2); A << 0.5, 0.7, -0.2, 0.4, -2.3, -4.5; const Vector3d b(1.3, -0.24, 0.25); prog.AddLinearEqualityConstraint(A, b, y); auto relaxation = MakeSemidefiniteRelaxation(prog); EXPECT_EQ(relaxation->num_vars(), 6); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 4); EXPECT_EQ(relaxation->GetAllConstraints().size(), 5); const Vector2d y_test(1.3, 0.24); SetRelaxationInitialGuess(y_test, relaxation.get()); // First constraint is (Ay-b)=0. MatrixXd expected = A * y_test - b; VectorXd value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[0]) - relaxation->linear_equality_constraints()[0].evaluator()->lower_bound(); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); // The second constraint is X(-1,-1) = 1. expected = Eigen::VectorXd::Ones(1); value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[1]); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); for (int i = 2; i < 4; ++i) { // Linear constraints are (Ay - b)*y_i = 0. expected = (A * y_test - b) * y_test[i - 2]; value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[i]); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); } } GTEST_TEST(MakeSemidefiniteRelaxationTest, NonConvexQuadraticConstraint) { MathematicalProgram prog; const auto y = prog.NewContinuousVariables<2>("y"); Matrix2d Q; Q << 1, 2, 3, 4; const Vector2d b(0.2, 0.4); const double lb = -0.4, ub = 0.5; prog.AddQuadraticConstraint(Q, b, lb, ub, y); auto relaxation = MakeSemidefiniteRelaxation(prog); EXPECT_EQ(relaxation->num_vars(), 6); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); EXPECT_EQ(relaxation->linear_constraints().size(), 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), 3); const Vector2d y_test(1.3, 0.24); SetRelaxationInitialGuess(y_test, relaxation.get()); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[0])[0], (0.5 * y_test.transpose() * Q * y_test + b.transpose() * y_test)[0], 1e-12); EXPECT_EQ(relaxation->linear_constraints()[0].evaluator()->lower_bound()[0], lb); EXPECT_EQ(relaxation->linear_constraints()[0].evaluator()->upper_bound()[0], ub); } // This test checks that repeated variables in a quadratic constraint are // handled correctly. GTEST_TEST(MakeSemidefiniteRelaxationTest, QuadraticConstraint2) { MathematicalProgram prog; const auto y = prog.NewContinuousVariables<1>("y"); prog.AddQuadraticConstraint(Eigen::Matrix2d::Ones(), Eigen::Vector2d::Zero(), 0, 1, Vector2<Variable>(y(0), y(0))); auto relaxation = MakeSemidefiniteRelaxation(prog); EXPECT_EQ(relaxation->num_vars(), 3); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); EXPECT_EQ(relaxation->linear_constraints().size(), 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), 3); const Vector1d y_test(1.3); SetRelaxationInitialGuess(y_test, relaxation.get()); EXPECT_NEAR(relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[0])[0], 2 * y_test(0) * y_test(0), 1e-12); EXPECT_EQ(relaxation->linear_constraints()[0].evaluator()->lower_bound()[0], 0.0); EXPECT_EQ(relaxation->linear_constraints()[0].evaluator()->upper_bound()[0], 1.0); } class MakeSemidefiniteRelaxationVariableGroupTest : public ::testing::Test { protected: void SetUp() override { x_ = prog_.NewContinuousVariables<3>("x"); y_ = prog_.NewContinuousVariables<2>("y"); x_vars_ = Variables(x_); y_vars_ = Variables(y_); x0_y0_y1_vars_ = Variables{x_(0), y_(0), y_(1)}; x0_x2_y1_vars_ = Variables{x_(0), x_(2), y_(1)}; } MathematicalProgram prog_; VectorIndeterminate<3> x_; VectorIndeterminate<2> y_; Variables x_vars_; Variables y_vars_; Variables x0_y0_y1_vars_; Variables x0_x2_y1_vars_; }; // This test checks that constraints and costs which are not a subset of any // variable group do not get relaxed. Also checks that non-convex quadratics // that are not relaxed throw errors. TEST_F(MakeSemidefiniteRelaxationVariableGroupTest, EmptyVariableGroup) { // Make prog_ a convex program. prog_.AddLinearCost(y_[0]); prog_.AddQuadraticCost(y_[0] * y_[0] + y_[1] * y_[1], true /* a convex cost*/); prog_.AddLinearConstraint(x_[0] >= x_[1]); prog_.AddLinearEqualityConstraint(x_[1] == x_[2]); prog_.AddQuadraticConstraint( x_[0] * x_[0] + x_[1] * x_[1], -kInf, 1, QuadraticConstraint::HessianType::kPositiveSemidefinite); // Since prog_ is convex and we have no variable groups, then the relaxation // should be exactly the original program, with one more variable representing // the "1" homogenization variable. const auto relaxation_empty = MakeSemidefiniteRelaxation(prog_, std::vector<Variables>()); // The relaxation has includes same variables as the original program, as well // as the "1" homogenization variable. Variables relax_vars{relaxation_empty->decision_variables()}; Variables prog_vars{prog_.decision_variables()}; EXPECT_TRUE(prog_vars.IsSubsetOf(relax_vars)); EXPECT_EQ(prog_vars.size() + 1, relax_vars.size()); // The relaxation has the same costs. EXPECT_EQ(relaxation_empty->linear_costs().size(), prog_.linear_costs().size()); EXPECT_EQ(relaxation_empty->quadratic_costs().size(), prog_.quadratic_costs().size()); EXPECT_EQ(relaxation_empty->GetAllCosts().size(), prog_.GetAllCosts().size()); // The relaxation has the same constraints except for the 1 homogenization // constraint. EXPECT_EQ(relaxation_empty->linear_constraints().size(), prog_.linear_constraints().size()); EXPECT_EQ(relaxation_empty->linear_equality_constraints().size(), prog_.linear_equality_constraints().size() + 1); EXPECT_EQ(relaxation_empty->quadratic_constraints().size(), prog_.quadratic_constraints().size()); // This confirms that we don't have any PSD constraints. EXPECT_EQ(relaxation_empty->GetAllConstraints().size(), prog_.GetAllConstraints().size() + 1); // Now add a non-convex quadratic cost and expect a throw. auto non_convex_quadratic_cost = prog_.AddQuadraticCost(x_[0] * y_[1], false); DRAKE_EXPECT_THROWS_MESSAGE( MakeSemidefiniteRelaxation(prog_, std::vector<Variables>()), ".*non-convex.*"); prog_.RemoveCost(non_convex_quadratic_cost); // Make sure that after removing the non-convex cost, we can construct the // relaxation successfully. This ensures that the next test does not throw for // the wrong reason (i.e. forgot to delete the non-convex quadratic cost). EXPECT_NO_THROW(MakeSemidefiniteRelaxation(prog_, std::vector<Variables>())); // Now add a non-convex quadratic constraint and expect a throw. auto non_convex_quadratic_constraint = prog_.AddQuadraticConstraint( x_[0] * y_[1], 0, 1, QuadraticConstraint::HessianType::kIndefinite); DRAKE_EXPECT_THROWS_MESSAGE( MakeSemidefiniteRelaxation(prog_, std::vector<Variables>()), ".*non-convex.*"); } // Checks that the number of semidefinite matrix variables is always the same as // the number of variable groups and that the number of rows of each // semidefinite matrix variable is the size of the corresponding group + 1. TEST_F(MakeSemidefiniteRelaxationVariableGroupTest, EmptyProgramWithVariableGroups) { // Only relaxes the x_ variables. auto relaxation = MakeSemidefiniteRelaxation(prog_, std::vector{x_vars_}); // The variables which get relaxed are [x(0), x(1), x(2), 1]. The remaining // variables that do not get relaxed are [y(0), y(1)]. So there are (5 // choose 2) + 2 variables in the program. EXPECT_EQ(relaxation->num_vars(), 2 + NChoose2(5)); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 4); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2); const Eigen::MatrixX<Variable> X = Eigen::Map<const MatrixX<Variable>>( relaxation->positive_semidefinite_constraints()[0].variables().data(), x_.size() + 1, x_.size() + 1); for (int i = 0; i < x_.size(); ++i) { EXPECT_TRUE(X(i, X.cols() - 1).equal_to(x_[i])); } relaxation = MakeSemidefiniteRelaxation(prog_, std::vector{x0_y0_y1_vars_, y_vars_}); // The variables which get relaxed are [x(0), y(0), y(1), 1] and [y(0), y(1), // 1]. The remaining variables that do not get relaxed are [x(1), x(2)]. The // variables [y(0), y(1), 1] get double counted So there are (5 choose 2) + (4 // choose 2) + 2 - 3 variables in the program. EXPECT_EQ(relaxation->num_vars(), NChoose2(5) + NChoose2(4) + 2 - 3); // One linear equality constraints from the 1 variables being equal to 1 and // one linear equality constraint that the minors corresponding [y0, y1] are // the same in the two psd variables. EXPECT_EQ(relaxation->linear_equality_constraints().size(), 2); // Two psd constraints. EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 2); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 4); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[1] .evaluator() ->matrix_rows(), 3); // No costs are added. EXPECT_EQ(relaxation->linear_costs().size(), 0); EXPECT_EQ(relaxation->GetAllCosts().size(), 0); const std::map<Variable, double> test_point{ {x_(0), 1.1}, {x_(1), 0.24}, {x_(2), -2.2}, {y_(0), -0.7}, {y_(1), -3.1}}; SetRelaxationInitialGuess(test_point, relaxation.get()); // Check the equality constraints are correct. The first one is that "1" // equals 1. EXPECT_NEAR(relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[0])[0], 1, 1e-12); // The second one is that the submatrices corresponding to [y0, y1] are the // same. auto constraint = relaxation->linear_equality_constraints()[1]; const Eigen::MatrixX<Variable> X0 = Eigen::Map<const MatrixX<Variable>>( relaxation->positive_semidefinite_constraints()[0].variables().data(), x0_y0_y1_vars_.size() + 1, x0_y0_y1_vars_.size() + 1); const Eigen::MatrixX<Variable> X1 = Eigen::Map<const MatrixX<Variable>>( relaxation->positive_semidefinite_constraints()[1].variables().data(), y_vars_.size() + 1, y_vars_.size() + 1); Eigen::MatrixXd X0_y0_y1(2, 2); Eigen::MatrixXd X1_y0_y1(2, 2); // clang-format off X0_y0_y1 << relaxation->GetInitialGuess(X0(1, 1)), relaxation->GetInitialGuess(X0(1, 2)), relaxation->GetInitialGuess(X0(1, 2)), relaxation->GetInitialGuess(X0(2, 2)); X1_y0_y1 << relaxation->GetInitialGuess(X1(0, 0)), relaxation->GetInitialGuess(X1(0, 1)), relaxation->GetInitialGuess(X1(0, 1)), relaxation->GetInitialGuess(X1(1, 1)); // clang-format on EXPECT_TRUE(CompareMatrices(X0_y0_y1, X1_y0_y1)); const Variables overlap_variables{X0(1, 1), X0(1, 2), X0(2, 2), X1(0, 0), X1(0, 1), X1(1, 1)}; EXPECT_EQ(Variables{constraint.variables()}, overlap_variables); EXPECT_TRUE(CompareMatrices(relaxation->EvalBindingAtInitialGuess(constraint), Eigen::Vector3d::Zero())); } TEST_F(MakeSemidefiniteRelaxationVariableGroupTest, LinearCost) { const std::map<Variable, double> test_point{ {x_(0), 1.1}, {x_(1), 0.24}, {x_(2), -2.2}, {y_(0), -0.7}, {y_(1), -3.1}}; prog_.AddLinearCost(x_[0] + x_[2] + y_[1]); // Only relaxes the x_ variables. auto relaxation = MakeSemidefiniteRelaxation(prog_, std::vector<Variables>{x0_x2_y1_vars_}); EXPECT_EQ(relaxation->linear_costs().size(), 1); EXPECT_EQ(relaxation->GetAllCosts().size(), 1); // The variables which get relaxed are [x(0), x(1), x(2), 1]. The remaining // variables that do not get relaxed are [y(0), y(1)]. So there are (5 // choose 2) + 2 variables in the program. EXPECT_EQ(relaxation->num_vars(), 2 + NChoose2(5)); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 4); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2); EXPECT_EQ(relaxation->linear_costs().size(), 1); EXPECT_EQ(relaxation->GetAllCosts().size(), 1); SetRelaxationInitialGuess(test_point, relaxation.get()); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess(relaxation->linear_costs()[0])[0], test_point.at(x_(0)) + test_point.at(x_(2)) + test_point.at(y_(1)), 1e-12); // Relax an overlapping set of variables which both have the cost as a subset. // The cost should only be added once. const Variables x_vars_plus_y1{x_(0), x_(1), x_(2), y_(1)}; relaxation = MakeSemidefiniteRelaxation( prog_, std::vector<Variables>{x_vars_plus_y1, x0_x2_y1_vars_}); EXPECT_EQ(relaxation->linear_costs().size(), 1); EXPECT_EQ(relaxation->GetAllCosts().size(), 1); // The variables which get relaxed are [x(0), x(1), x(2), y(1), 1] and [x(0), // x(2), y(1), 1]. The remaining variable that does not get relaxed is [y(0)]. // So there are (6 choose 2) + (5 choose 2) + 1 - 4 variables in the program. EXPECT_EQ(relaxation->num_vars(), NChoose2(6) + NChoose2(5) + 1 - 4); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 5); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[1] .evaluator() ->matrix_rows(), 4); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 2); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 2); EXPECT_EQ(relaxation->GetAllConstraints().size(), 4); EXPECT_EQ(relaxation->linear_costs().size(), 1); EXPECT_EQ(relaxation->GetAllCosts().size(), 1); SetRelaxationInitialGuess(test_point, relaxation.get()); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess(relaxation->linear_costs()[0])[0], test_point.at(x_(0)) + test_point.at(x_(2)) + test_point.at(y_(1)), 1e-12); } TEST_F(MakeSemidefiniteRelaxationVariableGroupTest, QuadraticCost) { const std::map<Variable, double> test_point{ {x_(0), 0.1}, {x_(1), -3.24}, {x_(2), 4.2}, {y_(0), -1.7}, {y_(1), -7.7}}; auto cost = prog_.AddQuadraticCost(x_[0] * x_[1]); // Only relaxes the x_ variables. auto relaxation = MakeSemidefiniteRelaxation(prog_, std::vector<Variables>{x_vars_}); EXPECT_EQ(relaxation->linear_costs().size(), 1); EXPECT_EQ(relaxation->GetAllCosts().size(), 1); // The variables which get relaxed are [x(0), x(1), x(2), 1]. The remaining // variables that do not get relaxed are [y(0), y(1)]. So there are (5 // choose 2) + 2 variables in the program. EXPECT_EQ(relaxation->num_vars(), 2 + NChoose2(5)); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 4); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2); EXPECT_EQ(relaxation->linear_costs().size(), 1); EXPECT_EQ(relaxation->GetAllCosts().size(), 1); SetRelaxationInitialGuess(test_point, relaxation.get()); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess(relaxation->linear_costs()[0])[0], test_point.at(x_(0)) * test_point.at(x_(1)), 1e-12); // Relax an overlapping set of variables. The cost should only be added once. const Variables y_vars_plus_x0_x1{x_(0), x_(1), y_(0), y_(1)}; relaxation = MakeSemidefiniteRelaxation( prog_, std::vector<Variables>{x_vars_, y_vars_plus_x0_x1}); // Both variable groups contain the quadratic cost, but the cost should only // get added once. EXPECT_EQ(relaxation->linear_costs().size(), 1); EXPECT_EQ(relaxation->GetAllCosts().size(), 1); // The variables which get relaxed are [x(0), x(1), x(2), 1] and [x(0), x(1), // y(0), y(1), 1]. The remaining variable that does not get relaxed is [x(2)]. // So there are (5 choose 2) + (6 choose 2) + 1 - 4 variables in the program. EXPECT_EQ(relaxation->num_vars(), NChoose2(5) + NChoose2(6) + 1 - 4); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 4); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[1] .evaluator() ->matrix_rows(), 5); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 2); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 2); EXPECT_EQ(relaxation->GetAllConstraints().size(), 4); EXPECT_EQ(relaxation->linear_costs().size(), 1); EXPECT_EQ(relaxation->GetAllCosts().size(), 1); SetRelaxationInitialGuess(test_point, relaxation.get()); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess(relaxation->linear_costs()[0])[0], test_point.at(x_(0)) * test_point.at(x_(1)), 1e-12); // Now we test that a convex quadratic cost isn't relaxed to a linear cost if // there is no semidefinite variable which contains the variables of the cost. prog_.RemoveCost(cost); cost = prog_.AddQuadraticCost(y_(0) * y_(0)); relaxation = MakeSemidefiniteRelaxation(prog_, std::vector<Variables>{x_vars_}); // The variables which get relaxed are [x(0), x(1), x(2), 1]. The remaining // variable that does not get relaxed is [y(0), y(1)]. So there are // (5 choose 2) + 2 variables in the program. EXPECT_EQ(relaxation->num_vars(), NChoose2(5) + 2); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 4); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 1); EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2); // The only cost is a single quadratic cost. EXPECT_EQ(relaxation->quadratic_costs().size(), 1); EXPECT_EQ(relaxation->GetAllCosts().size(), 1); SetRelaxationInitialGuess(test_point, relaxation.get()); EXPECT_NEAR(relaxation->EvalBindingAtInitialGuess( relaxation->quadratic_costs()[0])[0], test_point.at(y_(0)) * test_point.at(y_(0)), 1e-12); } TEST_F(MakeSemidefiniteRelaxationVariableGroupTest, QuadraticConstraint) { const std::map<Variable, double> test_point{ {x_(0), 0.3}, {x_(1), -1.9}, {x_(2), -1.4}, {y_(0), -2.3}, {y_(1), -6.3}}; // An indefinite Q for the (x_(0), x_(2)) variables. // clang-format off const Matrix2d Qx{{-3.3, -0.8}, {-1.1, -1.7}}; // clang-format on const Vector2d bx(-0.2, -3.1); const double lbx = -0.7, ubx = 1.5; // These are intentionally placed out of order with respect to the // ordering that happens in MakeSemidefiniteRelaxation. VectorX<Variable> out_of_order_x_vars(2); out_of_order_x_vars << x_(2), x_(0); prog_.AddQuadraticConstraint(Qx, bx, lbx, ubx, out_of_order_x_vars); // A convex quadratic constraint for the y_ variables. Q is PSD since it is // diagonally dominant. // clang-format off const Matrix2d Qy{{1.7, -0.8}, {-0.8, 4.6}}; // clang-format on const Vector2d by(-1.3, -0.4); const double lby = -kInf, uby = 4.7; prog_.AddQuadraticConstraint( Qy, by, lby, uby, y_, QuadraticConstraint::HessianType::kPositiveSemidefinite); // Relaxes the x_ and y_ variables separately. auto relaxation = MakeSemidefiniteRelaxation( prog_, std::vector<Variables>{x_vars_, y_vars_}); SetRelaxationInitialGuess(test_point, relaxation.get()); EXPECT_EQ(relaxation->GetAllCosts().size(), 0); // The variables which get relaxed are [x(0), x(1), x(2), 1] and // [y(0), y(1), 1]. So there are (5 choose 2) + (4 choose 2) - 1 variables in // the program. EXPECT_EQ(relaxation->num_vars(), NChoose2(5) + NChoose2(4) - 1); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 2); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 4); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[1] .evaluator() ->matrix_rows(), 3); // The constraints that the "1" in the psd variables is equal to 1. EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); // 2 original quadratic constraints. EXPECT_EQ(relaxation->linear_constraints().size(), 2); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2 + 1 + 2); const Vector2d x_test(test_point.at(x_(2)), test_point.at(x_(0))); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[0])[0], (0.5 * x_test.transpose() * Qx * x_test + bx.transpose() * x_test)[0], 1e-12); EXPECT_EQ(relaxation->linear_constraints()[0].evaluator()->lower_bound()[0], lbx); EXPECT_EQ(relaxation->linear_constraints()[0].evaluator()->upper_bound()[0], ubx); const Vector2d y_test(test_point.at(y_(0)), test_point.at(y_(1))); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[1])[0], (0.5 * y_test.transpose() * Qy * y_test + by.transpose() * y_test)[0], 1e-12); EXPECT_EQ(relaxation->linear_constraints()[1].evaluator()->lower_bound()[0], lby); EXPECT_EQ(relaxation->linear_constraints()[1].evaluator()->upper_bound()[0], uby); // These variable groups are both supersets of both the quadratic constraints. // Ensure that the quadratic constraints are added on each variable group, and // that the linear equality constraints between the variable groups are added. std::vector<Variables> groups{ Variables{x_(0), x_(2), y_(0), y_(1)}, Variables{x_(0), x_(1), x_(2), y_(0), y_(1)}, }; relaxation = MakeSemidefiniteRelaxation(prog_, groups); SetRelaxationInitialGuess(test_point, relaxation.get()); EXPECT_EQ(relaxation->GetAllCosts().size(), 0); // The variables which get relaxed are [x_(0), x_(2), y_(0), y_(1), 1] and // [x_(0), x_(1), x_(2), y_(0), y_(1), 1]. The variables [x_(0), x_(2), y_(0), // y_(1), 1] get double counted So there are (6 choose 2) + (7 choose 2) - 5 // variables in the program. EXPECT_EQ(relaxation->num_vars(), NChoose2(6) + NChoose2(7) - 5); // One linear equality constraints from the 1 variables being equal to 1 and // one linear equality constraint that the minors corresponding [x_(0), x_(2), // y_(0), y_(1)] are the same in the two psd variables. EXPECT_EQ(relaxation->linear_equality_constraints().size(), 2); // Two psd constraints. EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 2); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 6); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[1] .evaluator() ->matrix_rows(), 5); // Both quadratic constraints get added to both variable groups as linear // constraints. EXPECT_EQ(relaxation->linear_constraints().size(), 4); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2 + 2 + 4); // Check the linear constraints. EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[0])[0], (0.5 * x_test.transpose() * Qx * x_test + bx.transpose() * x_test)[0], 1e-12); EXPECT_EQ(relaxation->linear_constraints()[0].evaluator()->lower_bound()[0], lbx); EXPECT_EQ(relaxation->linear_constraints()[0].evaluator()->upper_bound()[0], ubx); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[1])[0], (0.5 * y_test.transpose() * Qy * y_test + by.transpose() * y_test)[0], 1e-12); EXPECT_EQ(relaxation->linear_constraints()[1].evaluator()->lower_bound()[0], lby); EXPECT_EQ(relaxation->linear_constraints()[1].evaluator()->upper_bound()[0], uby); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[2])[0], (0.5 * x_test.transpose() * Qx * x_test + bx.transpose() * x_test)[0], 1e-12); EXPECT_EQ(relaxation->linear_constraints()[2].evaluator()->lower_bound()[0], lbx); EXPECT_EQ(relaxation->linear_constraints()[2].evaluator()->upper_bound()[0], ubx); EXPECT_NEAR( relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[3])[0], (0.5 * y_test.transpose() * Qy * y_test + by.transpose() * y_test)[0], 1e-12); EXPECT_EQ(relaxation->linear_constraints()[3].evaluator()->lower_bound()[0], lby); EXPECT_EQ(relaxation->linear_constraints()[3].evaluator()->upper_bound()[0], uby); // Now do the relaxation so that both variable group relaxes the first // quadratic constraint, but neither variable group relaxes the second // quadratic constraint. relaxation = MakeSemidefiniteRelaxation( prog_, std::vector<Variables>{x_vars_, x0_x2_y1_vars_}); SetRelaxationInitialGuess(test_point, relaxation.get()); EXPECT_EQ(relaxation->GetAllCosts().size(), 0); // The variables which get relaxed are [x_(0), x_(1), x_(2), 1] and // [x_(0), x_(2), y_(1), 1]. The variable y_(0) is not part of any group and // [x_(0), x_(2), 1] get double counted So there are (5 choose 2) + (5 // choose 2) + 1 - 3 variables in the program. EXPECT_EQ(relaxation->num_vars(), NChoose2(5) + NChoose2(5) + 1 - 3); // One linear equality constraints from the 1 variables being equal to 1 and // one linear equality constraint that the minors corresponding [x_(0), x_(2)] // are the same in the two psd variables. EXPECT_EQ(relaxation->linear_equality_constraints().size(), 2); // Two psd constraints. EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 2); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 4); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[1] .evaluator() ->matrix_rows(), 4); // The first quadratic constraints get added to both variable groups as a // linear constraint. EXPECT_EQ(relaxation->linear_constraints().size(), 2); // The second quadratic constraint does not get relaxed. EXPECT_EQ(relaxation->quadratic_constraints().size(), 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2 + 2 + 2 + 1); } TEST_F(MakeSemidefiniteRelaxationVariableGroupTest, LinearConstraint) { const std::map<Variable, double> test_point{ {x_(0), 1.1}, {x_(1), 0.27}, {x_(2), -1.2}, {y_(0), -0.99}, {y_(1), 9.1}}; MatrixXd Ax(2, 3); // clang-format off Ax << 2, 0, 3.1, -1, -1.7, 2.1; // clang-format on const Vector2d lbx(1.3, -kInf); const Vector2d ubx(kInf, 0.1); VectorX<Variable> x_out_of_order(3); x_out_of_order << x_(1), x_(0), x_(2); prog_.AddLinearConstraint(Ax, lbx, ubx, x_out_of_order); MatrixXd Ay(3, 2); // clang-format off Ay << 1.1, 2.7, 0.27, -9.1, -1.2, -0.99; // clang-format on const Vector3d lby(1.3, -kInf, kInf); const Vector3d uby(kInf, 0.1, 7.2); VectorX<Variable> y_out_of_order(2); y_out_of_order << y_(1), y_(0); prog_.AddLinearConstraint(Ay, lby, uby, y_out_of_order); // Relaxes the x_ and y_ variables separately. auto relaxation = MakeSemidefiniteRelaxation( prog_, std::vector<Variables>{x_vars_, y_vars_}); SetRelaxationInitialGuess(test_point, relaxation.get()); EXPECT_EQ(relaxation->GetAllCosts().size(), 0); // The variables which get relaxed are [x(0), x(1), x(2), 1] and // [y(0), y(1), 1]. So there are (5 choose 2) + (4 choose 2) - 1 variables in // the program. EXPECT_EQ(relaxation->num_vars(), NChoose2(5) + NChoose2(4) - 1); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 2); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 4); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[1] .evaluator() ->matrix_rows(), 3); // The constraint that the "1" in the psd variables is equal to 1. EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1); // Each variable group is a superset of only 1 of the original linear // constraints, each of which gets relaxed into one product constraint. // Therefore, there are 4 total linear constraints. EXPECT_EQ(relaxation->linear_constraints().size(), 4); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2 + 1 + 4); // First 2 linear constraints are lbx ≤ Ax * x ≤ ubx, and lby ≤ Ay * y ≤ uby. EXPECT_TRUE(CompareMatrices( Ax, relaxation->linear_constraints()[0].evaluator()->GetDenseA())); EXPECT_TRUE(CompareMatrices( lbx, relaxation->linear_constraints()[0].evaluator()->lower_bound())); EXPECT_TRUE(CompareMatrices( ubx, relaxation->linear_constraints()[0].evaluator()->upper_bound())); EXPECT_TRUE(CompareMatrices( Ay, relaxation->linear_constraints()[1].evaluator()->GetDenseA())); EXPECT_TRUE(CompareMatrices( lby, relaxation->linear_constraints()[1].evaluator()->lower_bound())); EXPECT_TRUE(CompareMatrices( uby, relaxation->linear_constraints()[1].evaluator()->upper_bound())); // Third linear (in the new decision variables) constraint is 0 ≤ // (A*x_-b)(A*x_-b)ᵀ, where A and b represent all of the on x_ constraints // stacked. VectorXd b(2); // all of the finite lower/upper bounds. b << -lbx[0], ubx[1]; MatrixXd A(2, 3); A << -Ax.row(0), Ax.row(1); int expected_size = (b.size() * (b.size() + 1)) / 2; EXPECT_EQ(relaxation->linear_constraints()[2].evaluator()->num_constraints(), expected_size); const Vector3d x_test(test_point.at(x_(1)), test_point.at(x_(0)), test_point.at(x_(2))); VectorXd value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[2]); MatrixXd expected_mat = (A * x_test - b) * (A * x_test - b).transpose() - b * b.transpose(); VectorXd expected = math::ToLowerTriangularColumnsFromMatrix(expected_mat); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); value = relaxation->linear_constraints()[2].evaluator()->lower_bound(); expected = math::ToLowerTriangularColumnsFromMatrix(-b * b.transpose()); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); // Fourth linear (in the new decision variables) constraint is 0 ≤ // (A*y-b)(A*y-b)ᵀ, where A and b represent all of the on y_ constraints // stacked. b.resize(3); // all of the finite lower/upper bounds. b << -lby[0], uby[1], uby[2]; A.resize(3, 2); A << -Ay.row(0), Ay.row(1), Ay.row(2); expected_size = (b.size() * (b.size() + 1)) / 2; EXPECT_EQ(relaxation->linear_constraints()[3].evaluator()->num_constraints(), expected_size); const Vector2d y_test(test_point.at(y_(1)), test_point.at(y_(0))); value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[3]); expected_mat = (A * y_test - b) * (A * y_test - b).transpose() - b * b.transpose(); expected = math::ToLowerTriangularColumnsFromMatrix(expected_mat); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); value = relaxation->linear_constraints()[3].evaluator()->lower_bound(); expected = math::ToLowerTriangularColumnsFromMatrix(-b * b.transpose()); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); // We add a third linear constraint and use variable groups which overlap on // this third constraint only. MatrixXd A_overlap(1, 2); // clang-format off A_overlap << -1.9, 2.7; // clang-format on const Vector1d lb_overlap(1.7); const Vector1d ub_overlap(2.3); VectorX<Variable> overlap_vars(2); overlap_vars << x_(1), y_(1); prog_.AddLinearConstraint(A_overlap, lb_overlap, ub_overlap, overlap_vars); std::vector<Variables> groups{Variables{x_(0), x_(1), x_(2), y_(1)}, Variables{x_(1), y_(0), y_(1)}}; relaxation = MakeSemidefiniteRelaxation(prog_, groups); SetRelaxationInitialGuess(test_point, relaxation.get()); EXPECT_EQ(relaxation->GetAllCosts().size(), 0); // The variables which get relaxed are [x(0), x(1), x(2), y(1), 1] and // [x(1), y(0), y(1), 1]. These two groups of variables overlap in 3 places. // So there are (6 choose 2) + (5 choose 2) - 3 variables in the program EXPECT_EQ(relaxation->num_vars(), NChoose2(6) + NChoose2(5) - 3); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 2); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 5); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[1] .evaluator() ->matrix_rows(), 4); // The constraint that the "1" in the psd variables are equal to 1 plus // the one constraints that the minors indexed by [x(1), y(1)] are equal. // EXPECT_EQ(relaxation->linear_equality_constraints().size(), 2); // Check that the linear equality constraints are the claimed ones. EXPECT_EQ(relaxation->linear_equality_constraints().size(), 2); EXPECT_TRUE(CompareMatrices(relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[0]), Eigen::VectorXd::Ones(1))); auto psd_agree_constraint = relaxation->linear_equality_constraints()[1]; EXPECT_TRUE(CompareMatrices( relaxation->EvalBindingAtInitialGuess(psd_agree_constraint), Eigen::VectorXd::Zero( psd_agree_constraint.evaluator()->num_constraints()))); // 3 original linear constraints and 2 big linear constraints for the product // constraints. EXPECT_EQ(relaxation->linear_constraints().size(), 3 + 2); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2 + 2 + 5); // First 3 linear constraints are lbx ≤ Ax * x ≤ ubx, and lby ≤ Ay * y ≤ uby // and lb_overlap ≤ A_overlap * overlap_vars ≤ ub_overlap. int constraint_ind = 0; EXPECT_TRUE( CompareMatrices(Ax, relaxation->linear_constraints()[constraint_ind] .evaluator() ->GetDenseA())); EXPECT_TRUE( CompareMatrices(lbx, relaxation->linear_constraints()[constraint_ind] .evaluator() ->lower_bound())); EXPECT_TRUE( CompareMatrices(ubx, relaxation->linear_constraints()[constraint_ind] .evaluator() ->upper_bound())); ++constraint_ind; EXPECT_TRUE( CompareMatrices(Ay, relaxation->linear_constraints()[constraint_ind] .evaluator() ->GetDenseA())); EXPECT_TRUE( CompareMatrices(lby, relaxation->linear_constraints()[constraint_ind] .evaluator() ->lower_bound())); EXPECT_TRUE( CompareMatrices(uby, relaxation->linear_constraints()[constraint_ind] .evaluator() ->upper_bound())); ++constraint_ind; EXPECT_TRUE(CompareMatrices(A_overlap, relaxation->linear_constraints()[constraint_ind] .evaluator() ->GetDenseA())); EXPECT_TRUE(CompareMatrices(lb_overlap, relaxation->linear_constraints()[constraint_ind] .evaluator() ->lower_bound())); EXPECT_TRUE(CompareMatrices(ub_overlap, relaxation->linear_constraints()[constraint_ind] .evaluator() ->upper_bound())); ++constraint_ind; ASSERT_EQ(constraint_ind, 3); // Fourth linear (in the new decision variables) constraint is 0 ≤ // (A*x-b)(A*x-b)ᵀ, where A and b represent all of the on x_ and the overlap // constraints stacked. b.resize(4); // all of the finite lower/upper bounds. b << -lbx[0], ubx[1], -lb_overlap[0], ub_overlap[0]; A.resize(4, 4); // We need to reshuffle to columns of Ax, as they are out of order. // clang-format off A << -Ax(0,1), -Ax(0,0), -Ax(0,2), 0, // NOLINT Ax(1,1), Ax(1,0), Ax(1,2), 0, // NOLINT 0, -A_overlap(0, 0), 0, -A_overlap(0, 1), // NOLINT 0, A_overlap(0, 0), 0, A_overlap(0, 1); // NOLINT // clang-format on expected_size = (b.size() * (b.size() + 1)) / 2; EXPECT_EQ(relaxation->linear_constraints()[constraint_ind] .evaluator() ->num_constraints(), expected_size); VectorXd test_vec(4); test_vec << test_point.at(x_(0)), test_point.at(x_(1)), test_point.at(x_(2)), test_point.at(y_(1)); value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[constraint_ind]); expected_mat = (A * test_vec - b) * (A * test_vec - b).transpose() - b * b.transpose(); expected = math::ToLowerTriangularColumnsFromMatrix(expected_mat); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); value = relaxation->linear_constraints()[constraint_ind] .evaluator() ->lower_bound(); expected = math::ToLowerTriangularColumnsFromMatrix(-b * b.transpose()); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); ++constraint_ind; // Fifth linear (in the new decision variables) constraint is 0 ≤ // (A*x-b)(A*x-b)ᵀ, where A and b represent all of the on y_ and the overlap // constraints stacked. b.resize(5); // all of the finite lower/upper bounds. b << -lby[0], uby[1], uby[2], -lb_overlap[0], ub_overlap[0]; A.resize(5, 3); // We need to reshuffle to columns of Ay, as they are out of order. // clang-format off A << 0, -Ay(0,1), -Ay(0,0), // NOLINT 0, Ay(1,1), Ay(1,0), // NOLINT 0, Ay(2,1), Ay(2,0), // NOLINT -A_overlap(0, 0), 0, -A_overlap(0, 1), // NOLINT A_overlap(0, 0), 0, A_overlap(0, 1); // NOLINT // clang-format on expected_size = (b.size() * (b.size() + 1)) / 2; EXPECT_EQ(relaxation->linear_constraints()[constraint_ind] .evaluator() ->num_constraints(), expected_size); test_vec.resize(3); test_vec << test_point.at(x_(1)), test_point.at(y_(0)), test_point.at(y_(1)); value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_constraints()[constraint_ind]); expected_mat = (A * test_vec - b) * (A * test_vec - b).transpose() - b * b.transpose(); expected = math::ToLowerTriangularColumnsFromMatrix(expected_mat); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); value = relaxation->linear_constraints()[constraint_ind] .evaluator() ->lower_bound(); expected = math::ToLowerTriangularColumnsFromMatrix(-b * b.transpose()); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); ++constraint_ind; ASSERT_EQ(constraint_ind, 5); } TEST_F(MakeSemidefiniteRelaxationVariableGroupTest, LinearEqualityConstraint) { const std::map<Variable, double> test_point{ {x_(0), -0.6}, {x_(1), 3.8}, {x_(2), 4.7}, {y_(0), 9.9}, {y_(1), 3.4}}; // clang-format off const Matrix3d Ax{{0.8, -2.3, 0.7}, {-2.1, 2.9, 2.2}, {-2.8, 0.5, 5.2}}; // clang-format on const Vector3d bx(3.58, -4.26, -2.61); prog_.AddLinearEqualityConstraint(Ax, bx, x_); MatrixXd Ay(3, 2); // clang-format off Ay << -0.08, 1.62, 5.17, -6.47, 0.93, -2.97; // clang-format on const Vector3d by(4.6, -0.1, 0.7); const Vector3d uby(kInf, 0.1, 7.2); prog_.AddLinearEqualityConstraint(Ay, by, y_); // Relaxes the x_ and y_ variables separately. auto relaxation = MakeSemidefiniteRelaxation( prog_, std::vector<Variables>{x_vars_, y_vars_}); SetRelaxationInitialGuess(test_point, relaxation.get()); EXPECT_EQ(relaxation->GetAllCosts().size(), 0); // The variables which get relaxed are [x(0), x(1), x(2), 1] and // [y(0), y(1), 1]. So there are (5 choose 2) + (4 choose 2) - 1 variables in // the program. EXPECT_EQ(relaxation->num_vars(), NChoose2(5) + NChoose2(4) - 1); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 2); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 4); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[1] .evaluator() ->matrix_rows(), 3); // The constraint that the "1" in the psd variables is equal to 1. // Additionally, the relaxation of each groups causes one extra product // constraint for each of the column of the resulting PSD matrices. EXPECT_EQ(relaxation->linear_equality_constraints().size(), 1 + 4 + 3); EXPECT_EQ(relaxation->GetAllConstraints().size(), 2 + 8); int cur_constraint = 0; // The first two constraints are the linear constraints inherited from prog_. auto CompareLinearEqualityConstraintsAtIdx = [&](const int idx) { EXPECT_TRUE(CompareMatrices( relaxation->linear_equality_constraints()[idx].evaluator()->GetDenseA(), prog_.linear_equality_constraints()[idx].evaluator()->GetDenseA())); EXPECT_TRUE(CompareMatrices( relaxation->linear_equality_constraints()[idx] .evaluator() ->lower_bound(), prog_.linear_equality_constraints()[idx].evaluator()->lower_bound())); }; CompareLinearEqualityConstraintsAtIdx(cur_constraint++); CompareLinearEqualityConstraintsAtIdx(cur_constraint++); ASSERT_EQ(cur_constraint, 2); // This equality constraint is due to "1" being equal to 1. EXPECT_TRUE(CompareMatrices( relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[cur_constraint++]), Eigen::VectorXd::Ones(1))); // This next set of equality constraints are due to the relaxation of the x_ // variables. const Vector3d x_test(test_point.at(x_(0)), test_point.at(x_(1)), test_point.at(x_(2))); VectorXd expected; VectorXd value; int start = cur_constraint; for (; cur_constraint < start + 3; ++cur_constraint) { // Linear constraints are (Ax*x_ - bx)*x_i = 0. expected = (Ax * x_test - bx) * x_test[cur_constraint - start]; value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[cur_constraint]); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); } ASSERT_EQ(cur_constraint, 6); // This set of equality constraints are due to the relaxation of the y_ // variables. const Vector2d y_test(test_point.at(y_(0)), test_point.at(y_(1))); start = cur_constraint; for (; cur_constraint < start + 2; ++cur_constraint) { // Linear constraints are (Ay*y_ - b)*y_i = 0. expected = (Ay * y_test - by) * y_test[cur_constraint - start]; value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[cur_constraint]); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); } // At this point, we should have tested all the linear equality constraints. ASSERT_EQ(cur_constraint, relaxation->linear_equality_constraints().size()); // Now construct variable groups and equality constraints which overlap. MatrixXd A_overlap(1, 2); // clang-format off A_overlap << -7.9, 2.4; // clang-format on const Vector1d b_overlap(0.7); VectorXDecisionVariable overlap_vars(2); // These variables are not sorted according to their id intentionally. overlap_vars << y_(0), x_(2); const Vector2d overlap_test_vec{test_point.at(y_(0)), test_point.at(x_(2))}; prog_.AddLinearEqualityConstraint(A_overlap, b_overlap, overlap_vars); MatrixXd A_overlap_sorted(A_overlap.rows(), A_overlap.cols()); A_overlap_sorted << A_overlap(0, 1), A_overlap(0, 0); VectorXDecisionVariable overlap_vars_sorted(2); overlap_vars_sorted << x_(2), y_(0); const Vector2d overlap_test_vec_sorted(test_point.at(x_(2)), test_point.at(y_(0))); // Make sure the sorted and non-sorted version of this constraint are the // same. EXPECT_TRUE( CompareMatrices(A_overlap * overlap_test_vec - b_overlap, A_overlap_sorted * overlap_test_vec_sorted - b_overlap)); std::vector<Variables> groups{Variables{x_(0), x_(1), x_(2), y_(0)}, Variables{x_(2), y_(0), y_(1)}}; VectorXd group_1_test_vec(4); group_1_test_vec << test_point.at(x_(0)), test_point.at(x_(1)), test_point.at(x_(2)), test_point.at(y_(0)); VectorXd group_2_test_vec(3); group_2_test_vec << test_point.at(x_(2)), test_point.at(y_(0)), test_point.at(y_(1)); relaxation = MakeSemidefiniteRelaxation(prog_, groups); SetRelaxationInitialGuess(test_point, relaxation.get()); cur_constraint = 0; // The variables which get relaxed are [x(0), x(1), x(2), y(0), 1] and // [x(2), y(0), y(1), 1]. These two groups of variables overlap in 3 places. // So there are (6 choose 2) + (5 choose 2) - 3 variables in the program EXPECT_EQ(relaxation->num_vars(), NChoose2(6) + NChoose2(5) - 3); EXPECT_EQ(relaxation->positive_semidefinite_constraints().size(), 2); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[0] .evaluator() ->matrix_rows(), 5); EXPECT_EQ(relaxation->positive_semidefinite_constraints()[1] .evaluator() ->matrix_rows(), 4); // Three linear equality constraints in the original program, then one // constraint that the "1" in the psd variables are equal to 1. Additionally, // the relaxation of each groups causes one extra product constraint for each // linear equality constraint and for each of the column of the // resulting PSD matrices minus 1. Finally, one more equality constraint for // the agreement of the PSD matrices. EXPECT_EQ(relaxation->linear_equality_constraints().size(), 3 + 1 + 2 * 4 + 2 * 3 + 1); EXPECT_EQ(relaxation->GetAllConstraints().size(), relaxation->positive_semidefinite_constraints().size() + relaxation->linear_equality_constraints().size()); // The first three constraints are the linear constraints inherited from // prog_. CompareLinearEqualityConstraintsAtIdx(cur_constraint++); CompareLinearEqualityConstraintsAtIdx(cur_constraint++); CompareLinearEqualityConstraintsAtIdx(cur_constraint++); ASSERT_EQ(cur_constraint, 3); // This next set of equality constraints are due to the relaxation of // [x(0), x(1), x(2), y(0), 1]. EXPECT_TRUE(CompareMatrices( relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[cur_constraint++]), Eigen::VectorXd::Ones(1))); start = cur_constraint; for (; cur_constraint < start + 4; ++cur_constraint) { // Linear constraints are (Ax*x_ - bx)*x_i = 0. expected = (Ax * x_test - bx) * group_1_test_vec[cur_constraint - start]; value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[cur_constraint]); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); } start = cur_constraint; for (; cur_constraint < start + 4; ++cur_constraint) { // Linear constraints are (A_overlap*[x_(2), y_(0)] - b_overlap)*[x(0), // x(1), x(2), y(0)] = 0. expected = (A_overlap_sorted * overlap_test_vec_sorted - b_overlap) * group_1_test_vec[cur_constraint - start]; value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[cur_constraint]); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); } ASSERT_EQ(cur_constraint, 12); // This next set of equality constraints are due to the relaxation of // [x(2), y(0), y(1), 1]. start = cur_constraint; for (; cur_constraint < start + 3; ++cur_constraint) { // Linear constraints are (Ay*y_ - by)*[x(2), y(0), y(1)]. = 0. expected = (Ay * y_test - by) * group_2_test_vec[cur_constraint - start]; value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[cur_constraint]); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); } start = cur_constraint; for (; cur_constraint < start + 3; ++cur_constraint) { // Linear constraints are (A_overlap*[x_(2), y_(0)] - // b_overlap)*[x_(2), y_(0), y_(1)] = 0. expected = (A_overlap_sorted * overlap_test_vec_sorted - b_overlap) * group_2_test_vec[cur_constraint - start]; value = relaxation->EvalBindingAtInitialGuess( relaxation->linear_equality_constraints()[cur_constraint]); EXPECT_TRUE(CompareMatrices(value, expected, 1e-12)); } ASSERT_EQ(cur_constraint, 18); auto psd_agree_constraint = relaxation->linear_equality_constraints()[cur_constraint++]; EXPECT_TRUE(CompareMatrices( relaxation->EvalBindingAtInitialGuess(psd_agree_constraint), Eigen::VectorXd::Zero( psd_agree_constraint.evaluator()->num_constraints()))); // All linear equality constraints have been checked. ASSERT_EQ(cur_constraint, relaxation->linear_equality_constraints().size()); } } // namespace internal } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/constraint_test.cc
#include "drake/solvers/constraint.h" #include <limits> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "drake/common/symbolic/expression.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/common/test_utilities/symbolic_test_util.h" #include "drake/math/autodiff.h" #include "drake/math/autodiff_gradient.h" #include "drake/solvers/test/generic_trivial_constraints.h" using Eigen::Matrix2d; using Eigen::MatrixXd; using Eigen::Vector2d; using Eigen::Vector3d; using Eigen::VectorXd; using ::testing::HasSubstr; using ::testing::Not; namespace drake { using symbolic::test::ExprEqual; using symbolic::test::FormulaEqual; namespace solvers { using symbolic::Environment; using symbolic::Expression; using symbolic::Formula; using symbolic::Variable; namespace { const double kInf = std::numeric_limits<double>::infinity(); // Given a list of variables [x₀, ..., xₙ] and a list of values [v₀, ..., vₙ], // returns an environment {x₀ ↦ v₀, ..., xₙ ↦ vₙ}. Environment BuildEnvironment(const VectorX<Variable>& vars, const VectorXd& values) { Environment env; for (int i = 0; i < vars.size(); ++i) { env.insert(vars[i], values[i]); } return env; } GTEST_TEST(TestConstraint, BoundSizeCheck) { DRAKE_EXPECT_THROWS_MESSAGE( LinearConstraint(Eigen::Matrix3d::Identity(), Eigen::Vector2d(1., 2), Eigen::Vector3d(2., 3, 4.)), "Constraint expects lower and upper bounds of size 3, got lower " "bound of size 2 and upper bound of size 3."); } GTEST_TEST(TestConstraint, LinearConstraintSparse) { // Construct LinearConstraint with sparse A matrix. std::vector<Eigen::Triplet<double>> A_triplets; A_triplets.emplace_back(0, 1, 0.5); A_triplets.emplace_back(1, 0, 1.5); Eigen::SparseMatrix<double> A_sparse(2, 3); A_sparse.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::Vector2d lb(0, 1); Eigen::Vector2d ub(1, 2); LinearConstraint dut(A_sparse, lb, ub); EXPECT_EQ(dut.num_vars(), 3); EXPECT_EQ(dut.num_constraints(), 2); // We expect the sparse constructor to not construct the dense A matrix. EXPECT_FALSE(dut.is_dense_A_constructed()); EXPECT_EQ(dut.get_sparse_A().nonZeros(), A_sparse.nonZeros()); EXPECT_TRUE( CompareMatrices(dut.get_sparse_A().toDense(), A_sparse.toDense())); EXPECT_TRUE(CompareMatrices(dut.GetDenseA(), A_sparse.toDense())); // Now that the dense version of A has been accessed, we expect A to have been // constructed. EXPECT_TRUE(dut.is_dense_A_constructed()); EXPECT_TRUE(CompareMatrices(dut.lower_bound(), lb)); EXPECT_TRUE(CompareMatrices(dut.upper_bound(), ub)); // Call UpdateCoefficients with sparse A; A_triplets.emplace_back(1, 2, 2.5); Eigen::SparseMatrix<double> A_sparse_new(2, 3); A_sparse_new.setFromTriplets(A_triplets.begin(), A_triplets.end()); lb << 1, 4; ub << 2, 5; dut.UpdateCoefficients(A_sparse_new, lb, ub); EXPECT_EQ(dut.get_sparse_A().nonZeros(), A_sparse_new.nonZeros()); EXPECT_TRUE( CompareMatrices(dut.get_sparse_A().toDense(), A_sparse_new.toDense())); EXPECT_TRUE(CompareMatrices(dut.GetDenseA(), A_sparse_new.toDense())); EXPECT_TRUE(CompareMatrices(dut.lower_bound(), lb)); EXPECT_TRUE(CompareMatrices(dut.upper_bound(), ub)); } GTEST_TEST(TestConstraint, LinearConstraintInfiniteEntries) { std::vector<Eigen::Triplet<double>> A_triplets; A_triplets.emplace_back(0, 1, 0.5); A_triplets.emplace_back(1, 0, 1.5); A_triplets.emplace_back(2, 0, kInf); Eigen::SparseMatrix<double> A_sparse_bad(3, 3); Eigen::Vector3d lb(0, 1, -2); Eigen::Vector3d ub(1, 2, 3); A_sparse_bad.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::Vector2d bound(0, 1); Eigen::Vector3d bound_bad(0, 1, kInf); DRAKE_EXPECT_THROWS_MESSAGE(LinearConstraint(A_sparse_bad, lb, ub), ".*IsFinite().*"); DRAKE_EXPECT_THROWS_MESSAGE(LinearConstraint(A_sparse_bad.toDense(), lb, ub), ".*allFinite().*"); } GTEST_TEST(TestConstraint, LinearEqualityConstraintSparse) { std::vector<Eigen::Triplet<double>> A_triplets; A_triplets.emplace_back(0, 1, 0.5); A_triplets.emplace_back(1, 0, 1.5); Eigen::SparseMatrix<double> A_sparse(2, 3); A_sparse.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::Vector2d bound(0, 1); LinearEqualityConstraint dut(A_sparse, bound); // We expect the sparse constructor to not construct the dense A matrix. EXPECT_FALSE(dut.is_dense_A_constructed()); EXPECT_EQ(dut.get_sparse_A().nonZeros(), A_sparse.nonZeros()); EXPECT_TRUE( CompareMatrices(dut.get_sparse_A().toDense(), A_sparse.toDense())); EXPECT_TRUE(CompareMatrices(dut.GetDenseA(), A_sparse.toDense())); // Now that the dense version of A has been accessed, we expect a dense A to // be available. EXPECT_TRUE(dut.is_dense_A_constructed()); EXPECT_TRUE(CompareMatrices(dut.lower_bound(), bound)); EXPECT_TRUE(CompareMatrices(dut.upper_bound(), bound)); } GTEST_TEST(TestConstraint, LinearEqualityConstraintInfiniteEntries) { std::vector<Eigen::Triplet<double>> A_triplets; A_triplets.emplace_back(0, 1, 0.5); A_triplets.emplace_back(1, 0, 1.5); Eigen::SparseMatrix<double> A_sparse(2, 3); A_sparse.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::SparseMatrix<double> A_sparse_bad(3, 3); A_triplets.emplace_back(2, 0, kInf); A_sparse_bad.setFromTriplets(A_triplets.begin(), A_triplets.end()); Eigen::Vector2d bound(0, 1); Eigen::Vector3d bound_bad(0, 1, kInf); EXPECT_THROW(LinearEqualityConstraint(A_sparse_bad, bound), std::exception); EXPECT_THROW(LinearEqualityConstraint(A_sparse, bound_bad), std::exception); EXPECT_THROW(LinearEqualityConstraint(A_sparse_bad.toDense(), bound), std::exception); EXPECT_THROW(LinearEqualityConstraint(A_sparse.toDense(), bound_bad), std::exception); DRAKE_EXPECT_THROWS_MESSAGE( LinearEqualityConstraint(A_sparse.toDense().row(0), kInf), ".*allFinite().*"); DRAKE_EXPECT_THROWS_MESSAGE( LinearEqualityConstraint(A_sparse_bad.toDense().row(2), 0), ".*allFinite().*"); } GTEST_TEST(TestConstraint, testLinearConstraintUpdate) { // Update the coefficients or the bound of the linear constraint, and check // the updated constraint. const Eigen::Matrix2d A = Eigen::Matrix2d::Identity(); const Eigen::Vector2d b(1, 2); LinearEqualityConstraint constraint(A, b); EXPECT_TRUE(CompareMatrices(constraint.lower_bound(), b)); EXPECT_TRUE(CompareMatrices(constraint.upper_bound(), b)); EXPECT_TRUE(CompareMatrices(constraint.GetDenseA(), A)); EXPECT_EQ(constraint.num_constraints(), 2); // Test Eval/CheckSatisfied using Expression. const VectorX<Variable> x_sym{symbolic::MakeVectorContinuousVariable(2, "x")}; VectorX<Expression> y_sym; constraint.Eval(x_sym, &y_sym); EXPECT_EQ(y_sym.size(), 2); EXPECT_PRED2(ExprEqual, y_sym[0], x_sym[0]); EXPECT_PRED2(ExprEqual, y_sym[1], x_sym[1]); EXPECT_PRED2(FormulaEqual, constraint.CheckSatisfied(x_sym), 1 == x_sym[0] && 2 == x_sym[1]); // Update with a new matrix A2 with three columns. This should cause a runtime // error, since the number of variables do not match. const Eigen::Matrix<double, 2, 3> A2 = Eigen::Matrix<double, 2, 3>::Ones(); const Eigen::Vector2d b2(1, 2); EXPECT_THROW(constraint.UpdateCoefficients(A2, b2), std::runtime_error); // Update with a new matrix A3 with size 3 x 2. const Eigen::Matrix<double, 3, 2> A3 = Eigen::Matrix<double, 3, 2>::Ones(); const Eigen::Vector3d b3(1, 2, 3); constraint.UpdateCoefficients(A3, b3); EXPECT_TRUE(CompareMatrices(constraint.lower_bound(), b3)); EXPECT_TRUE(CompareMatrices(constraint.upper_bound(), b3)); EXPECT_TRUE(CompareMatrices(constraint.GetDenseA(), A3)); EXPECT_TRUE(CompareMatrices(constraint.get_sparse_A().toDense(), A3)); EXPECT_EQ(constraint.num_constraints(), 3); } GTEST_TEST(TestConstraint, testLinearConstraintUpdateErrors) { // Update the coefficients or the bound of the linear constraint, and check // the updated constraint. const Eigen::Matrix2d A = Eigen::Matrix2d::Identity(); Eigen::Matrix2d A_bad = Eigen::Matrix2d::Identity(); A_bad(0, 1) = kInf; const Eigen::Vector2d b(1, 2); const Eigen::Vector2d b_bad(0, kInf); LinearEqualityConstraint constraint(A, b); EXPECT_TRUE(CompareMatrices(constraint.lower_bound(), b)); EXPECT_TRUE(CompareMatrices(constraint.upper_bound(), b)); EXPECT_TRUE(CompareMatrices(constraint.GetDenseA(), A)); EXPECT_EQ(constraint.num_constraints(), 2); EXPECT_THROW(constraint.UpdateCoefficients(A_bad, b), std::exception); EXPECT_THROW(constraint.UpdateCoefficients(A_bad.sparseView(), b), std::exception); EXPECT_THROW(constraint.UpdateCoefficients(A, b_bad), std::exception); } GTEST_TEST(testConstraint, testRemoveTinyCoefficient) { Eigen::Matrix<double, 2, 3> A; const double tol = 1E-8; // clang-format off A << 0.5 * tol, -0.5 * tol, 0, 1.5, -0.1 * tol, 0; // clang-format on Eigen::Vector2d lb(-0.1 * tol, 0); Eigen::Vector2d ub(2, 0.1 * tol); LinearConstraint dut(A, lb, ub); dut.RemoveTinyCoefficient(tol); Eigen::Matrix<double, 2, 3> A_expected; // clang-format off A_expected << 0, 0, 0, 1.5, 0, 0; // clang-format on EXPECT_TRUE(CompareMatrices(dut.get_sparse_A().toDense(), A_expected)); EXPECT_TRUE(CompareMatrices(dut.GetDenseA(), A_expected)); EXPECT_TRUE(CompareMatrices(dut.lower_bound(), lb)); EXPECT_TRUE(CompareMatrices(dut.upper_bound(), ub)); DRAKE_EXPECT_THROWS_MESSAGE(dut.RemoveTinyCoefficient(-1), ".*tol should be non-negative"); } GTEST_TEST(testConstraint, testQuadraticConstraintHessian) { // Check if the getters in the QuadraticConstraint are right. Eigen::Matrix2d Q; Eigen::Vector2d b; // clang-format off Q << 1, 0, 0, 1; // clang-format on b << 1, 2; // Constructs a constraint with a symmetric Q. QuadraticConstraint constraint1(Q, b, 0, 1); EXPECT_TRUE(CompareMatrices(constraint1.Q(), Q)); EXPECT_TRUE(CompareMatrices(constraint1.b(), b)); EXPECT_EQ(constraint1.hessian_type(), QuadraticConstraint::HessianType::kPositiveSemidefinite); // The constraint is non-convex due to the lower bound not being -inf. EXPECT_FALSE(constraint1.is_convex()); std::ostringstream os; constraint1.Display(os, symbolic::MakeVectorContinuousVariable(2, "x")); EXPECT_EQ(os.str(), "QuadraticConstraint\n" "0 <= (x(0) + 2 * x(1) + 0.5 * pow(x(0), 2) + 0.5 * pow(x(1), 2)) " "<= 1\n"); // Test Eval/CheckSatisfied using Expression. const VectorX<Variable> x_sym{symbolic::MakeVectorContinuousVariable(2, "x")}; const Variable& x0{x_sym[0]}; const Variable& x1{x_sym[1]}; VectorX<Expression> y_sym; constraint1.Eval(x_sym, &y_sym); EXPECT_EQ(y_sym.size(), 1); EXPECT_PRED2(ExprEqual, y_sym[0], 0.5 * x0 * x0 + 0.5 * x1 * x1 + x0 + 2 * x1); EXPECT_PRED2(FormulaEqual, constraint1.CheckSatisfied(x_sym), 0 <= y_sym[0] && y_sym[0] <= 1); // Updates constraint with a non-symmetric negative definite Hessian. // clang-format off Q << -1, 1, 0, -1; // clang-format on b << 1, 2; constraint1.UpdateCoefficients(Q, b); EXPECT_TRUE(CompareMatrices(constraint1.Q(), (Q + Q.transpose()) / 2)); EXPECT_TRUE(CompareMatrices(constraint1.b(), b)); EXPECT_EQ(constraint1.hessian_type(), QuadraticConstraint::HessianType::kNegativeSemidefinite); EXPECT_FALSE(constraint1.is_convex()); // Constructs a constraint with a non-symmetric Hessian. QuadraticConstraint constraint2( Q, b, 0, kInf, QuadraticConstraint::HessianType::kNegativeSemidefinite); EXPECT_TRUE(CompareMatrices(constraint2.Q(), (Q + Q.transpose()) / 2)); EXPECT_TRUE(CompareMatrices(constraint2.b(), b)); EXPECT_EQ(constraint2.hessian_type(), QuadraticConstraint::HessianType::kNegativeSemidefinite); EXPECT_TRUE(constraint2.is_convex()); // Updates constraints with an indefinite Hessian. // clang-format off Q << 1, 2, 2, 3; // clang-format on constraint2.UpdateCoefficients(Q, b); EXPECT_EQ(constraint2.hessian_type(), QuadraticConstraint::HessianType::kIndefinite); EXPECT_FALSE(constraint2.is_convex()); // Updates constraint with a specified Hessian type. constraint2.UpdateCoefficients( Eigen::Matrix2d::Identity(), b, QuadraticConstraint::HessianType::kPositiveSemidefinite); EXPECT_EQ(constraint2.hessian_type(), QuadraticConstraint::HessianType::kPositiveSemidefinite); EXPECT_FALSE(constraint2.is_convex()); // Construct a constraint with psd Hessian and lower bound being -inf. QuadraticConstraint constraint3(Eigen::Matrix2d::Identity(), b, -kInf, 1); EXPECT_TRUE(constraint3.is_convex()); } GTEST_TEST(testConstraint, QudraticConstraintLDLtFailute) { Eigen::Matrix2d Q; Eigen::Vector2d b; // This matrix has eigenvalues 0.5 and -0.5 and so is indefinite. However, if // we use Eigen's LDLT to determine the definiteness of this matrix, the // LDLT construction fails due to numerical issues. // clang-format off Q << 0, 0.5, 0.5, 0; // clang-format on b << 0, 0; Eigen::LDLT<Eigen::MatrixXd> ldlt_solver; ldlt_solver.compute(Q); // Check that the LDLT solver fails. If Eigen were to update in such a way // that the LDLT construction were to succeed, then this test would become // irrelevant and thus we could either remove it, or would need to find a new // Q matrix which causes the LDLT to fail. EXPECT_EQ(ldlt_solver.info(), Eigen::NumericalIssue); // The construction of the constraint calls UpdateHessian() which currently // calls Eigen's LDLT solver which fails on this simplex example. QuadraticConstraint constraint(Q, b, -kInf, 1); EXPECT_FALSE(constraint.is_convex()); EXPECT_EQ(constraint.hessian_type(), QuadraticConstraint::HessianType::kIndefinite); } void TestLorentzConeEvalConvex(const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::VectorXd>& b, const VectorXd& x_test) { LorentzConeConstraint cnstr1(A, b, LorentzConeConstraint::EvalType::kConvex); LorentzConeConstraint cnstr2(A, b, LorentzConeConstraint::EvalType::kConvexSmooth); EXPECT_EQ(cnstr1.eval_type(), LorentzConeConstraint::EvalType::kConvex); EXPECT_EQ(cnstr2.eval_type(), LorentzConeConstraint::EvalType::kConvexSmooth); EXPECT_EQ(cnstr1.num_constraints(), 1); EXPECT_EQ(cnstr2.num_constraints(), 1); EXPECT_TRUE(CompareMatrices(cnstr1.lower_bound(), Vector1d(0))); EXPECT_TRUE(CompareMatrices(cnstr2.lower_bound(), Vector1d(0))); EXPECT_TRUE(CompareMatrices(cnstr1.upper_bound(), Vector1d(kInf))); EXPECT_TRUE(CompareMatrices(cnstr2.upper_bound(), Vector1d(kInf))); VectorXd y1, y2; cnstr1.Eval(x_test, &y1); cnstr2.Eval(x_test, &y2); VectorXd z = A * x_test + b; Vector1d y_expected(z(0) - z.tail(z.rows() - 1).norm()); EXPECT_TRUE(CompareMatrices(y1, y_expected, 1e-12)); EXPECT_TRUE(CompareMatrices(y2, y_expected, 1e-12)); std::ostringstream os; cnstr1.Display( os, symbolic::MakeVectorContinuousVariable(cnstr1.num_vars(), "x")); EXPECT_THAT(os.str(), HasSubstr("LorentzConeConstraint\n")); EXPECT_THAT(os.str(), HasSubstr("pow")); EXPECT_THAT(os.str(), HasSubstr("sqrt")); Eigen::MatrixXd dx_test(x_test.rows(), 2); dx_test.col(0) = Eigen::VectorXd::LinSpaced(x_test.rows(), 0, 1); dx_test.col(1) = Eigen::VectorXd::LinSpaced(x_test.rows(), 1, 2); const AutoDiffVecXd x_autodiff = math::InitializeAutoDiff(x_test, dx_test); AutoDiffVecXd y_autodiff1, y_autodiff2; cnstr1.Eval(x_autodiff, &y_autodiff1); cnstr2.Eval(x_autodiff, &y_autodiff2); EXPECT_TRUE( CompareMatrices(y_expected, math::ExtractValue(y_autodiff1), 1e-12)); EXPECT_TRUE( CompareMatrices(y_expected, math::ExtractValue(y_autodiff2), 1e-12)); // With eval_type = kConvexSmooth, we approximate the gradient with some // smooth function, which introduces larger error (2e-12). EXPECT_TRUE(CompareMatrices(math::ExtractGradient(y_autodiff1), math::ExtractGradient(y_autodiff2), 2e-12)); } // Tests if the Lorentz Cone constraint (with non-convex eval) is imposed // correctly. void TestLorentzConeEvalNonconvex(const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::VectorXd>& b, const VectorXd& x_test, bool is_in_cone) { LorentzConeConstraint cnstr(A, b, LorentzConeConstraint::EvalType::kNonconvex); EXPECT_EQ(cnstr.num_constraints(), 2); EXPECT_TRUE(CompareMatrices(cnstr.lower_bound(), Eigen::Vector2d::Zero())); EXPECT_TRUE( CompareMatrices(cnstr.upper_bound(), Eigen::Vector2d::Constant(kInf))); VectorXd y; // Test Eval with VectorXd. cnstr.Eval(x_test, &y); Vector2d y_expected; VectorXd z = A * x_test + b; y_expected(0) = z(0); y_expected(1) = z(0) * z(0) - z.tail(z.size() - 1).squaredNorm(); EXPECT_TRUE( CompareMatrices(y, y_expected, 1E-10, MatrixCompareType::absolute)); bool is_in_cone_expected = (y(0) >= 0) && (y(1) >= 0); EXPECT_EQ(is_in_cone, is_in_cone_expected); EXPECT_EQ(cnstr.CheckSatisfied(x_test), is_in_cone_expected); std::ostringstream os; cnstr.Display(os, symbolic::MakeVectorContinuousVariable(cnstr.num_vars(), "x")); EXPECT_THAT(os.str(), HasSubstr("LorentzConeConstraint\n")); EXPECT_THAT(os.str(), HasSubstr("pow")); EXPECT_THAT(os.str(), Not(HasSubstr("sqrt"))); auto tx = drake::math::InitializeAutoDiff(x_test); AutoDiffVecXd x_taylor = tx; AutoDiffVecXd y_taylor; // Test Eval with AutoDiff. cnstr.Eval(x_taylor, &y_taylor); EXPECT_TRUE(CompareMatrices(y, math::ExtractValue(y_taylor))); EXPECT_EQ(cnstr.CheckSatisfied(x_taylor), is_in_cone_expected); // Test Eval/CheckSatisfied using Expression. const VectorX<Variable> x_sym{ symbolic::MakeVectorContinuousVariable(x_test.size(), "x")}; VectorX<Expression> y_sym; cnstr.Eval(x_sym, &y_sym); const Environment env{BuildEnvironment(x_sym, x_test)}; EXPECT_TRUE(CompareMatrices(Evaluate(y_sym, env), y_expected, 1E-10, MatrixCompareType::absolute)); EXPECT_EQ(cnstr.CheckSatisfied(x_sym).Evaluate(env), is_in_cone_expected); } void TestRotatedLorentzConeEval(const Eigen::Ref<const Eigen::MatrixXd> A, const Eigen::Ref<const Eigen::VectorXd> b, const VectorXd& x_test, bool is_in_cone) { RotatedLorentzConeConstraint cnstr(A, b); VectorXd y; cnstr.Eval(x_test, &y); Eigen::VectorXd z = A * x_test + b; Vector3d y_expected(z(0), z(1), z(0) * z(1) - z.tail(z.size() - 2).squaredNorm()); EXPECT_TRUE( CompareMatrices(y, y_expected, 1E-10, MatrixCompareType::absolute)); bool is_in_cone_expected = (z(0) >= 0) && (z(1) >= 0) && (z(0) * z(1) >= z.tail(z.size() - 2).norm()); EXPECT_EQ(is_in_cone, is_in_cone_expected); EXPECT_EQ(cnstr.CheckSatisfied(x_test), is_in_cone_expected); // Eval with taylor var. auto tx = drake::math::InitializeAutoDiff(x_test); AutoDiffVecXd x_taylor = tx; AutoDiffVecXd y_taylor; cnstr.Eval(x_taylor, &y_taylor); EXPECT_TRUE(CompareMatrices(y, math::ExtractValue(y_taylor))); EXPECT_EQ(cnstr.CheckSatisfied(x_taylor), is_in_cone_expected); std::ostringstream os; cnstr.Display(os, symbolic::MakeVectorContinuousVariable(cnstr.num_vars(), "x")); EXPECT_THAT(os.str(), HasSubstr("RotatedLorentzConeConstraint\n")); EXPECT_THAT(os.str(), HasSubstr("pow")); // Test Eval/CheckSatisfied using Expression. const VectorX<Variable> x_sym{ symbolic::MakeVectorContinuousVariable(x_test.size(), "x")}; VectorX<Expression> y_sym; cnstr.Eval(x_sym, &y_sym); const Environment env{BuildEnvironment(x_sym, x_test)}; EXPECT_TRUE(CompareMatrices(Evaluate(y_sym, env), y_expected, 1E-10, MatrixCompareType::absolute)); EXPECT_EQ(cnstr.CheckSatisfied(x_sym).Evaluate(env), is_in_cone_expected); } GTEST_TEST(testConstraint, testLorentzConeConstraint) { // [3;1;1] is in the interior of the Lorentz cone. Eigen::Vector3d x1(3.0, 1.0, 1.0); TestLorentzConeEvalConvex(Eigen::Matrix3d::Identity(), Eigen::Vector3d::Zero(), x1); TestLorentzConeEvalNonconvex(Eigen::Matrix3d::Identity(), Eigen::Vector3d::Zero(), x1, true); // [3;2;2;1] is on the boundary of the Lorentz cone. Eigen::Vector2d x2(1, 3); Eigen::Matrix<double, 4, 2> A2; // clang-format off A2 << 1, 0, 1, 1, -1, 1, 1, -2; // clang-format on Eigen::Vector4d b2(2, -2, 0, 6); TestLorentzConeEvalConvex(A2, b2, x2); TestLorentzConeEvalNonconvex(A2, b2, x2, true); // [3; 3; 1] is outside of the Lorentz cone. Eigen::Vector4d x3(1, -1, 2, 3); Eigen::Matrix<double, 3, 4> A3; // clang-format off A3 << 1, 0, -1, 2, -1, 2, 0, 1, 0, -2, 3, 1; // clang-format on Eigen::Vector3d b3 = Eigen::Vector3d(3, 3, 1) - A3 * x3; TestLorentzConeEvalConvex(A3, b3, x3); TestLorentzConeEvalNonconvex(A3, b3, x3, false); // [-3; 1; 1] is outside of the Lorentz cone. Vector1d x4 = Vector1d::Constant(4); Eigen::Vector3d A4(-1, 3, 2); Eigen::Vector3d b4 = Eigen::Vector3d(-3, 1, 1) - A4 * x4; TestLorentzConeEvalConvex(A4, b4, x4); TestLorentzConeEvalNonconvex(A4, b4, x4, false); } GTEST_TEST(testConstraint, testLorentzConeConstraintAtZeroZ) { // Test LorentzConeConstraint with smoothed approximated gradient evaluated // at z = 0 Vector2d x(1, 2); Eigen::Matrix<double, 3, 2> A; A << 1, 2, -2, -1, 2, 3; Eigen::Vector3d b = -A * x; LorentzConeConstraint cnstr(A, b, LorentzConeConstraint::EvalType::kConvexSmooth); AutoDiffVecXd y_autodiff; cnstr.Eval(math::InitializeAutoDiff(x), &y_autodiff); EXPECT_TRUE(CompareMatrices(math::ExtractValue(y_autodiff), Vector1d(0))); const Eigen::MatrixXd y_gradient = math::ExtractGradient(y_autodiff); // The gradient of dy/dz is [1, 0, 0], so the dy/dx = dy/dz * dz/dx = dy/dz * // A = A.row(0). EXPECT_TRUE(CompareMatrices(y_gradient, A.row(0))); } GTEST_TEST(testConstraint, LorentzConeConstraintUpdateCoefficients) { Eigen::Matrix<double, 3, 2> A; A << 1, 2, -2, -1, 2, 3; Eigen::Vector3d b(1, 2, 3); LorentzConeConstraint constraint( A, b, LorentzConeConstraint::EvalType::kConvexSmooth); const int num_constraints = constraint.num_constraints(); A *= 2; b *= 3; constraint.UpdateCoefficients(A, b); EXPECT_TRUE(CompareMatrices(constraint.A().toDense(), A)); EXPECT_TRUE(CompareMatrices(constraint.A_dense(), A)); EXPECT_TRUE(CompareMatrices(constraint.b(), b)); // Now try A with different number of rows. UpdateCoefficients should still // work. Eigen::Matrix<double, 4, 2> new_A; new_A << Eigen::Matrix2d::Identity(), Eigen::Matrix2d::Identity(); Eigen::Vector4d new_b = Eigen::Vector4d::Zero(); constraint.UpdateCoefficients(new_A, new_b); EXPECT_EQ(constraint.num_vars(), 2); EXPECT_EQ(constraint.num_constraints(), num_constraints); DRAKE_EXPECT_THROWS_MESSAGE( constraint.UpdateCoefficients(Eigen::Matrix3d::Identity(), Eigen::Vector3d::Zero()), ".*UpdateCoefficients uses new_A with 3 columns to update a constraint " "with 2 variables."); } GTEST_TEST(testConstraint, testRotatedLorentzConeConstraint) { // [1;2;1] is in the interior of the rotated lorentz cone. TestRotatedLorentzConeEval(Eigen::Matrix3d::Identity(), Eigen::Vector3d::Zero(), Vector3d(1, 2, 1), true); // [1;2;1;1] is on the boundary of the rotated Lorentz cone. Eigen::Vector2d x2(1, 2); Eigen::Matrix<double, 4, 2> A2; // clang-format off A2 << 1, -1, 0, 2, -1, 3, -2, 4; // clang-format on Eigen::Vector4d b2 = Eigen::Vector4d(1, 2, 1, 1) - A2 * x2; TestRotatedLorentzConeEval(A2, b2, x2, true); // [1;2;2;2] is outside of the rotated Lorentz cone. Eigen::Vector4d x3(1, 3, -1, 2); Eigen::Matrix4d A3; // clang-format off A3 << 1, 2, 3, 4, -1, 2, 4, 2, -3, 2, 1, 4, 2, 1, 3, 2; // clang-format on Eigen::Vector4d b3 = Eigen::Vector4d(1, 2, 2, 2) - A3 * x3; TestRotatedLorentzConeEval(A3, b3, x3, false); // [-1; -2; 1] is outside of the rotated Lorentz cone. Vector1d x4 = Vector1d::Constant(10); Eigen::Vector3d A4(1, 3, 2); Eigen::Vector3d b4 = Eigen::Vector3d(-1, -2, 1) - A4 * x4; TestRotatedLorentzConeEval(A4, b4, x4, false); } GTEST_TEST(testConstraint, RotatedLorentzConeConstraintUpdateCoefficients) { Eigen::Matrix<double, 3, 2> A; A << 1, 2, -2, -1, 2, 3; Eigen::Vector3d b(1, 2, 3); RotatedLorentzConeConstraint constraint(A, b); const int num_constraints = constraint.num_constraints(); A *= 2; b *= 3; constraint.UpdateCoefficients(A, b); EXPECT_TRUE(CompareMatrices(constraint.A().toDense(), A)); EXPECT_TRUE(CompareMatrices(constraint.A_dense(), A)); EXPECT_TRUE(CompareMatrices(constraint.b(), b)); EXPECT_EQ(constraint.num_vars(), 2); // Now try A with different number of rows. UpdateCoefficients should still // work. Eigen::Matrix<double, 4, 2> new_A; new_A << Eigen::Matrix2d::Identity(), Eigen::Matrix2d::Identity(); Eigen::Vector4d new_b = Eigen::Vector4d::Zero(); constraint.UpdateCoefficients(new_A, new_b); EXPECT_EQ(constraint.num_vars(), 2); EXPECT_EQ(constraint.num_constraints(), num_constraints); DRAKE_EXPECT_THROWS_MESSAGE( constraint.UpdateCoefficients(Eigen::Matrix3d::Identity(), Eigen::Vector3d::Zero()), ".*UpdateCoefficients uses new_A with 3 columns to update a constraint " "with 2 variables."); } GTEST_TEST(testConstraint, testPositiveSemidefiniteConstraint) { PositiveSemidefiniteConstraint cnstr(3); Eigen::Matrix<double, 9, 1> X1; // clang-format off X1 << 1, 0, 0, 0, 1, 0, 0, 0, 1; // clang-format on Eigen::VectorXd y; cnstr.Eval(X1, &y); EXPECT_TRUE((y.array() >= cnstr.lower_bound().array()).all()); EXPECT_TRUE((y.array() <= cnstr.upper_bound().array()).all()); EXPECT_TRUE(cnstr.CheckSatisfied(X1)); Eigen::Matrix<double, 9, 1> X2; // clang-format off X2 << 1, 2, 0, 2, -2, -1, 0, -1, -2; // clang-format on cnstr.Eval(X2, &y); EXPECT_TRUE((y.array() < cnstr.lower_bound().array()).any() || (y.array() > cnstr.upper_bound().array()).any()); EXPECT_EQ(cnstr.matrix_rows(), 3); EXPECT_FALSE(cnstr.CheckSatisfied(X2)); // Test Eval/CheckSatisfied using Expression. const VectorX<Variable> x_sym{ symbolic::MakeVectorContinuousVariable(X1.size(), "x")}; VectorX<Expression> y_sym; EXPECT_THROW(cnstr.Eval(x_sym, &y_sym), std::logic_error); EXPECT_THROW(cnstr.CheckSatisfied(x_sym), std::logic_error); } GTEST_TEST(testConstraint, testLinearMatrixInequalityConstraint) { Eigen::Matrix2d F0 = 2 * Eigen::Matrix2d::Identity(); Eigen::Matrix2d F1; F1 << 1, 1, 1, 1; Eigen::Matrix2d F2; F2 << 1, 2, 2, 1; LinearMatrixInequalityConstraint cnstr({F0, F1, F2}); EXPECT_TRUE(CompareMatrices(cnstr.F()[0], F0)); EXPECT_TRUE(CompareMatrices(cnstr.F()[1], F1)); EXPECT_TRUE(CompareMatrices(cnstr.F()[2], F2)); // [4, 3] // [3, 4] is positive semidefinite Eigen::VectorXd y; Eigen::Vector2d x1(1, 1); cnstr.Eval(x1, &y); EXPECT_TRUE((y.array() >= cnstr.lower_bound().array()).all()); EXPECT_TRUE((y.array() <= cnstr.upper_bound().array()).all()); EXPECT_TRUE(cnstr.CheckSatisfied(x1)); // [1 -2] // [-2 1] is not p.s.d Eigen::Vector2d x2(0, -1); cnstr.Eval(x2, &y); EXPECT_TRUE((y.array() < cnstr.lower_bound().array()).any() || (y.array() > cnstr.upper_bound().array()).any()); EXPECT_FALSE(cnstr.CheckSatisfied(x2)); // Test Eval/CheckSatisfied using Expression. const VectorX<Variable> x_sym{ symbolic::MakeVectorContinuousVariable(x1.size(), "x")}; VectorX<Expression> y_sym; EXPECT_THROW(cnstr.Eval(x_sym, &y_sym), std::logic_error); EXPECT_THROW(cnstr.CheckSatisfied(x_sym), std::logic_error); } GTEST_TEST(testConstraint, testExpressionConstraint) { Variable x0{"x0"}; Variable x1{"x1"}; Variable x2{"x2"}; Vector3<Variable> vars{x0, x1, x2}; Vector2<Expression> e{1. + x0 * x0, x1 * x1 + x2}; ExpressionConstraint constraint(e, Vector2d::Zero(), 2. * Vector2d::Ones()); const VectorX<symbolic::Expression>& expressions{constraint.expressions()}; ASSERT_EQ(expressions.size(), 2); EXPECT_TRUE(e[0].EqualTo(expressions[0])); EXPECT_TRUE(e[1].EqualTo(expressions[1])); std::ostringstream os; constraint.Display(os, vars); EXPECT_EQ(os.str(), "ExpressionConstraint\n" "0 <= (1 + pow(x0, 2)) <= 2\n" "0 <= (x2 + pow(x1, 2)) <= 2\n"); const Vector3d x{.2, .4, .6}; VectorXd y; const Vector2d y_expected{1.04, .76}; constraint.Eval(x, &y); EXPECT_TRUE(CompareMatrices(y, y_expected)); AutoDiffVecXd x_autodiff = drake::math::InitializeAutoDiff(x); AutoDiffVecXd y_autodiff; Eigen::Matrix<double, 2, 3> y_gradient_expected; // clang-format off y_gradient_expected << .4, 0., 0., 0., .8, 1.; // clang-format on constraint.Eval(x_autodiff, &y_autodiff); EXPECT_TRUE(CompareMatrices(math::ExtractValue(y_autodiff), y_expected)); EXPECT_TRUE( CompareMatrices(math::ExtractGradient(y_autodiff), y_gradient_expected)); // Test Eval/CheckSatisfied using Expression. VectorX<Expression> y_sym; constraint.Eval(vars, &y_sym); EXPECT_EQ(y_sym.size(), e.size()); EXPECT_PRED2(ExprEqual, y_sym[0], e[0]); EXPECT_PRED2(ExprEqual, y_sym[1], e[1]); EXPECT_PRED2(FormulaEqual, constraint.CheckSatisfied(vars), 0 <= e[0] && e[0] <= 2 && 0 <= e[1] && e[1] <= 2); } // Test that the Eval() method of LinearComplementarityConstraint correctly // returns the slack. GTEST_TEST(testConstraint, testSimpleLCPConstraintEval) { Eigen::Matrix2d M = Eigen::Matrix2d::Identity(); Eigen::Vector2d q(-1, -1); LinearComplementarityConstraint c(M, q); Eigen::VectorXd w; Eigen::Vector2d x1(1, 1); c.Eval(x1, &w); EXPECT_TRUE( CompareMatrices(w, Vector2d(0, 0), 1e-4, MatrixCompareType::absolute)); EXPECT_TRUE(c.CheckSatisfied(x1)); Eigen::Vector2d x2(1, 2); c.Eval(x2, &w); EXPECT_TRUE( CompareMatrices(w, Vector2d(0, 1), 1e-4, MatrixCompareType::absolute)); EXPECT_FALSE(c.CheckSatisfied(x2)); // Test Eval/CheckSatisfied using Expression. const VectorX<Variable> x_sym{ symbolic::MakeVectorContinuousVariable(x1.size(), "x")}; const Variable& x_0{x_sym[0]}; const Variable& x_1{x_sym[1]}; VectorX<Expression> y_sym; c.Eval(x_sym, &y_sym); // y = Mx + q = Ix + [-1, -1]. EXPECT_EQ(y_sym.size(), 2); EXPECT_PRED2(ExprEqual, y_sym[0], x_0 - 1); EXPECT_PRED2(ExprEqual, y_sym[1], x_1 - 1); // 1. Mx + q = Ix + [-1 -1] >= 0 // 2. x >= 0 // 3. x'(Mx + q) = x₀(x₀ - 1) + x₁(x₁ - 1) == 0 EXPECT_PRED2(FormulaEqual, c.CheckSatisfied(x_sym), x_0 - 1.0 >= 0 && x_1 - 1.0 >= 0 && x_0 >= 0.0 && x_1 >= 0.0 && x_0 * (x_0 - 1.0) + x_1 * (x_1 - 1.0) == 0.0); } class SimpleEvaluator : public EvaluatorBase { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(SimpleEvaluator) SimpleEvaluator() : EvaluatorBase(2, 3) { c_.resize(2, 3); // clang-format off c_ << 1, 2, 3, 4, 5, 6; // clang-format on } protected: void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const override { DoEvalGeneric(x, y); } void DoEval(const Eigen::Ref<const VectorX<Variable>>& x, VectorX<Expression>* y) const override { DoEvalGeneric(x, y); } private: template <typename DerivedX, typename ScalarY> void DoEvalGeneric(const Eigen::MatrixBase<DerivedX>& x, VectorX<ScalarY>* y) const { *y = c_ * x.template cast<ScalarY>(); } Eigen::MatrixXd c_; }; GTEST_TEST(testConstraint, testEvaluatorConstraint) { const VectorXd lb = VectorXd::Constant(2, -1); const VectorXd ub = VectorXd::Constant(2, 1); EvaluatorConstraint<> constraint(std::make_shared<SimpleEvaluator>(), lb, ub); EXPECT_EQ(3, constraint.num_vars()); EXPECT_EQ(2, constraint.num_constraints()); EXPECT_EQ(lb, constraint.lower_bound()); EXPECT_EQ(ub, constraint.upper_bound()); VectorXd x(3); x << 7, 8, 9; VectorXd y(2); MatrixXd c(2, 3); // clang-format off c << 1, 2, 3, 4, 5, 6; // clang-format on const VectorXd y_expected = c * x; constraint.Eval(x, &y); EXPECT_EQ(y_expected, y); // Test Eval/CheckSatisfied using Expression. const VectorX<Variable> x_sym{symbolic::MakeVectorContinuousVariable(3, "x")}; const Variable& x_0{x_sym[0]}; const Variable& x_1{x_sym[1]}; const Variable& x_2{x_sym[2]}; VectorX<Expression> y_sym; constraint.Eval(x_sym, &y_sym); // y = c * x EXPECT_EQ(y_sym.size(), 2); EXPECT_PRED2(ExprEqual, y_sym[0], 1 * x_0 + 2 * x_1 + 3 * x_2); EXPECT_PRED2(ExprEqual, y_sym[1], 4 * x_0 + 5 * x_1 + 6 * x_2); EXPECT_PRED2( FormulaEqual, constraint.CheckSatisfied(x_sym), -1 <= y_sym[0] && y_sym[0] <= 1 && -1 <= y_sym[1] && y_sym[1] <= 1); } GTEST_TEST(testConstraint, testExponentialConeConstraint) { Eigen::SparseMatrix<double> A(3, 2); A.coeffRef(0, 0) = 2; A.coeffRef(1, 1) = 3; A.coeffRef(2, 0) = 1; Eigen::Vector3d b(1, 2, 3); ExponentialConeConstraint constraint(A, b); Eigen::Vector2d x(3, 4); Eigen::VectorXd y; constraint.Eval(x, &y); // Now evaluate z manually. const Eigen::Vector3d z = A * x + b; Eigen::Vector2d y_expected; y_expected(0) = z(0) - z(1) * std::exp(z(2) / z(1)); y_expected(1) = z(1); const double tol = 8.0 * std::numeric_limits<double>::epsilon(); EXPECT_TRUE(CompareMatrices(y, y_expected, tol)); // Check autodiff evaluation. Eigen::MatrixXd dx(2, 1); dx << 1, 1; const auto x_autodiff = math::InitializeAutoDiff(Eigen::VectorXd(x), dx); AutoDiffVecXd y_autodiff; constraint.Eval(x_autodiff, &y_autodiff); // Now compute the gradient manually. const AutoDiffVecXd z_autodiff = A * x_autodiff + b; AutoDiffVecXd y_autodiff_expected(2); y_autodiff_expected(0) = z_autodiff(0) - z_autodiff(1) * exp(z_autodiff(2) / z_autodiff(1)); y_autodiff_expected(1) = z_autodiff(1); EXPECT_TRUE(CompareMatrices(math::ExtractValue(y_autodiff), y_expected, tol)); EXPECT_TRUE(CompareMatrices(math::ExtractGradient(y_autodiff), math::ExtractGradient(y_autodiff_expected), tol)); } /* Note: To render the latex string output with the most relevant engine, open a jupyter notebook and run, e.g.: ``` from IPython.display import Markdown, display latex = "0 \\le (1.2 + x_{0} + 2x_{1})" display(Markdown(f"$${latex}$$")) ``` with the appropriate latex string. */ GTEST_TEST(ToLatex, GenericConstraint) { test::GenericTrivialConstraint1 c; c.set_description("test"); Vector3<Variable> vars = symbolic::MakeVectorVariable<3>("x"); EXPECT_EQ( c.ToLatex(vars), "\\text{GenericTrivialConstraint1}(x_{0}, x_{1}, x_{2}) \\tag{test}"); } GTEST_TEST(ToLatex, LinearConstraint) { Matrix2d A; A << 1, 2, 3, 4; const Vector2d lb(-1, -2); const Vector2d ub(1, kInf); LinearConstraint c(A, lb, ub); c.set_description("test"); Vector2<Variable> vars = symbolic::MakeVectorVariable<2>("x"); EXPECT_EQ(c.ToLatex(vars), "\\begin{bmatrix} -1 \\\\ -2 \\end{bmatrix} \\le \\begin{bmatrix} " "1 & 2 \\\\ 3 & 4 \\end{bmatrix} \\begin{bmatrix} x_{0} \\\\ x_{1} " "\\end{bmatrix} \\le \\begin{bmatrix} 1 \\\\ \\infty " "\\end{bmatrix} \\tag{test}"); // Trivial lower or upper bounds are not displayed. LinearConstraint c_no_lb(A, Vector2d::Constant(-kInf), ub); EXPECT_EQ(c_no_lb.ToLatex(vars), "\\begin{bmatrix} 1 & 2 \\\\ 3 & 4 \\end{bmatrix} \\begin{bmatrix} " "x_{0} \\\\ x_{1} \\end{bmatrix} \\le \\begin{bmatrix} 1 \\\\ " "\\infty \\end{bmatrix}"); LinearConstraint c_no_ub(A, lb, Vector2d::Constant(kInf)); EXPECT_EQ(c_no_ub.ToLatex(vars), "\\begin{bmatrix} -1 \\\\ -2 \\end{bmatrix} \\le \\begin{bmatrix} " "1 & 2 \\\\ 3 & 4 \\end{bmatrix} \\begin{bmatrix} x_{0} \\\\ x_{1} " "\\end{bmatrix}"); // LinearEqualityConstraint sets lb == ub. LinearEqualityConstraint c_eq(A, lb); EXPECT_EQ( c_eq.ToLatex(vars), "\\begin{bmatrix} 1 & 2 \\\\ 3 & 4 \\end{bmatrix} \\begin{bmatrix} x_{0} " "\\\\ x_{1} \\end{bmatrix} = \\begin{bmatrix} -1 \\\\ -2 \\end{bmatrix}"); // Scalar constraints are a special case. LinearConstraint c_scalar(A.row(0), Vector1d{-1}, Vector1d{1}); EXPECT_EQ(c_scalar.ToLatex(vars), "-1 \\le (x_{0} + 2x_{1}) \\le 1"); } GTEST_TEST(ToLatex, BoundingBoxConstraint) { const Vector2d lb(-1, -2); const Vector2d ub(1, kInf); BoundingBoxConstraint c(lb, ub); c.set_description("test"); Vector2<Variable> vars = symbolic::MakeVectorVariable<2>("x"); EXPECT_EQ(c.ToLatex(vars), "\\begin{bmatrix} -1 \\\\ -2 \\end{bmatrix} \\le \\begin{bmatrix} " "x_{0} \\\\ x_{1} \\end{bmatrix} \\le \\begin{bmatrix} 1 \\\\ " "\\infty \\end{bmatrix} \\tag{test}"); // Scalar constraints are a special case. BoundingBoxConstraint c_scalar(Vector1d{-1}, Vector1d{1}); EXPECT_EQ(c_scalar.ToLatex(vars.head<1>()), "-1 \\le x_{0} \\le 1"); } GTEST_TEST(ToLatex, QuadraticConstraint) { Matrix2d Q; Q << 1, 2, 2, 4; Vector2d b{3, 5}; const double lb = -1; const double ub = 1; QuadraticConstraint c(Q, b, lb, ub); c.set_description("test"); Vector2<Variable> vars = symbolic::MakeVectorVariable<2>("x"); EXPECT_EQ(c.ToLatex(vars), "-1 \\le \\begin{bmatrix} x_{0} \\\\ x_{1} \\end{bmatrix}^T " "\\begin{bmatrix} 0.500 & 1 \\\\ 1 & 2 \\end{bmatrix} " "\\begin{bmatrix} x_{0} " "\\\\ x_{1} \\end{bmatrix} + (3x_{0} + 5x_{1}) \\le 1 \\tag{test}"); // xᵀx = 1. QuadraticConstraint c_eq(2 * Matrix2d::Identity(), Vector2d::Zero(), 1, 1); EXPECT_EQ(c_eq.ToLatex(vars), "\\begin{bmatrix} x_{0} \\\\ x_{1} \\end{bmatrix}^T " "\\begin{bmatrix} 1 & 0 \\\\ 0 & 1 \\end{bmatrix} \\begin{bmatrix} " "x_{0} \\\\ x_{1} \\end{bmatrix} = 1"); } GTEST_TEST(ToLatex, PolynomialConstraint) { const Polynomiald x("x"); const Polynomiald y("y"); const Polynomiald poly = (x - 1) * (x - 1) + (y + 2) * (y + 2); const std::vector<Polynomiald::VarType> var_mapping = {x.GetSimpleVariable(), y.GetSimpleVariable()}; PolynomialConstraint c(Vector1<Polynomiald>(poly), var_mapping, Vector1d{-1}, Vector1d{1}); c.set_description("test"); Vector2<Variable> vars = symbolic::MakeVectorVariable<2>("x"); // TODO(russt): Improve this (or perhaps even deprecate the constraint type). // PolynomialConstraint doesn't currently support Expression. EXPECT_EQ(c.ToLatex(vars), "\\text{PolynomialConstraint}(x_{0}, x_{1}) \\tag{test}"); } GTEST_TEST(ToLatex, LorentzConeConstraints) { MatrixXd A(4, 2); // clang-format off A << 1, 2, 3, 4, 5, 6, 7, 8; // clang-format on VectorXd b(4); b << 1.2, 3.4, 5.6, 7.8; LorentzConeConstraint lc(A, b); lc.set_description("test"); Vector2<Variable> vars = symbolic::MakeVectorVariable<2>("x"); EXPECT_EQ(lc.ToLatex(vars, 1), "\\left|\\begin{bmatrix} (3.4 + 3x_{0} + 4x_{1}) \\\\ (5.6 + " "5x_{0} + 6x_{1}) \\\\ (7.8 + 7x_{0} + 8x_{1}) " "\\end{bmatrix}\\right|_2 \\le (1.2 + x_{0} + 2x_{1}) \\tag{test}"); RotatedLorentzConeConstraint rlc(A, b); rlc.set_description("test"); EXPECT_EQ(rlc.ToLatex(vars, 1), "0 \\le (1.2 + x_{0} + 2x_{1}),\\\\ 0 \\le (3.4 + 3x_{0} + " "4x_{1}),\\\\ \\left|\\begin{bmatrix} (5.6 + 5x_{0} + 6x_{1}) \\\\ " "(7.8 + 7x_{0} + 8x_{1}) \\end{bmatrix}\\right|_2^2 \\le (1.2 + " "x_{0} + 2x_{1}) (3.4 + 3x_{0} + 4x_{1}) \\tag{test}"); } GTEST_TEST(ToLatex, LinearComplementarityConstraint) { Eigen::Matrix2d M = Eigen::Matrix2d::Identity(); Eigen::Vector2d q(-1, -1); LinearComplementarityConstraint c(M, q); c.set_description("test"); Vector2<Variable> vars = symbolic::MakeVectorVariable<2>("x"); EXPECT_EQ(c.ToLatex(vars), "0 \\le \\begin{bmatrix} x_{0} \\\\ x_{1} \\end{bmatrix} \\perp " "\\begin{bmatrix} (-1 + x_{0}) \\\\ (-1 + x_{1}) \\end{bmatrix} " "\\ge 0 \\tag{test}"); } GTEST_TEST(ToLatex, PositiveSemidefiniteConstraint) { Variable x{"x"}, y{"y"}, z{"z"}; Matrix2<Variable> S; S << x, y, y, z; PositiveSemidefiniteConstraint c(2); c.set_description("test"); Vector4<Variable> vars{x, y, y, z}; EXPECT_EQ(c.ToLatex(vars), "\\begin{bmatrix} x & y \\\\ y & z \\end{bmatrix} \\succeq 0 " "\\tag{test}"); } GTEST_TEST(ToLatex, LinearMatrixInequalityConstraint) { Eigen::Matrix2d F0 = 2 * Eigen::Matrix2d::Identity(); Eigen::Matrix2d F1; F1 << 1, 1, 1, 1; Eigen::Matrix2d F2; F2 << 1, 2, 2, 1; LinearMatrixInequalityConstraint c({F0, F1, F2}); c.set_description("test"); Vector2<Variable> vars = symbolic::MakeVectorVariable<2>("x"); EXPECT_EQ( c.ToLatex(vars), "\\begin{bmatrix} (2 + x_{0} + x_{1}) & (x_{0} + 2x_{1}) \\\\ (x_{0} + " "2x_{1}) & (2 + x_{0} + x_{1}) \\end{bmatrix} \\succeq 0 \\tag{test}"); } GTEST_TEST(ToLatex, ExpressionConstraint) { Vector2<Variable> x = symbolic::MakeVectorVariable<2>("x"); ExpressionConstraint c_scalar(Vector1<Expression>{1.2 + x(0) + 2 * x(1)}, Vector1d{-1.2}, Vector1d{0.3}); c_scalar.set_description("test"); EXPECT_EQ(c_scalar.ToLatex(c_scalar.vars(), 1), "-1.2 \\le (1.2 + x_{0} + 2x_{1}) \\le 0.3 \\tag{test}"); ExpressionConstraint c_vector( Vector2<Expression>{0.1 + x(0), 3 * x(0) * x(1)}, Vector2d{-1, -2}, Vector2d{1, 2}); EXPECT_EQ(c_vector.ToLatex(c_vector.vars(), 1), "\\begin{bmatrix} -1 \\\\ -2 \\end{bmatrix} \\le \\begin{bmatrix} " "(0.1 + x_{0}) \\\\ 3 x_{0} x_{1} \\end{bmatrix} \\le " "\\begin{bmatrix} 1 \\\\ 2 \\end{bmatrix}"); } GTEST_TEST(ToLatex, ExponentialConeConstraint) { Eigen::SparseMatrix<double> A(3, 2); A.coeffRef(0, 0) = 2; A.coeffRef(1, 1) = 3; A.coeffRef(2, 0) = 1; Eigen::Vector3d b(1, 2, 3); ExponentialConeConstraint c(A, b); c.set_description("test"); Vector2<Variable> vars = symbolic::MakeVectorVariable<2>("x"); EXPECT_EQ(c.ToLatex(vars), "0 \\le (2 + 3x_{1}),\\\\ (1 + 2x_{0}) \\le (2 + 3x_{1}) " "e^{\\frac{(3 + x_{0})}{(2 + 3x_{1})}} \\tag{test}"); } } // namespace } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/second_order_cone_program_examples.h
#pragma once #include <memory> #include <optional> #include <ostream> #include <vector> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/solvers/mathematical_program.h" #include "drake/solvers/solver_interface.h" namespace drake { namespace solvers { namespace test { enum class EllipsoidsSeparationProblem { kProblem0, kProblem1, kProblem2, kProblem3 }; std::ostream& operator<<(std::ostream& os, EllipsoidsSeparationProblem value); std::vector<EllipsoidsSeparationProblem> GetEllipsoidsSeparationProblems(); /// This test is taken from the course notes of EE127A from University of /// California, Berkeley /// The goal is to find a hyperplane, that separates two ellipsoids /// E₁ = x₁ + R₁ * u₁, |u₁| ≤ 1 /// E₂ = x₂ + R₂ * u₂, |u₂| ≤ 1 /// A hyperplane aᵀ * x = b separates these two ellipsoids, if and only if for /// SOCP p* = min t₁ + t₂ /// s.t t₁ ≥ |R₁ᵀ * a| /// t₂ ≥ |R₂ᵀ * a| /// aᵀ(x₂-x₁) = 1 /// the optimal solution p* is no larger than 1. In that case, an appropriate /// value of b is b = 0.5(b₁ + b₂), where /// b₁ = aᵀx₁ + |R₁ᵀ * a| /// b₂ = aᵀx₂ - |R₂ᵀ * a| /// @param x1 the center of ellipsoid 1 /// @param x2 the center of ellipsoid 2 /// @param R1 the shape of ellipsoid 1 /// @param R2 the shape of ellipsoid 2 class TestEllipsoidsSeparation : public ::testing::TestWithParam<EllipsoidsSeparationProblem> { public: TestEllipsoidsSeparation(); void SolveAndCheckSolution( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options = std::nullopt, double tol = 1E-8); private: Eigen::VectorXd x1_; Eigen::VectorXd x2_; Eigen::MatrixXd R1_; Eigen::MatrixXd R2_; MathematicalProgram prog_; VectorDecisionVariable<2> t_; VectorXDecisionVariable a_; }; enum class QPasSOCPProblem { kProblem0, kProblem1 }; std::ostream& operator<<(std::ostream& os, QPasSOCPProblem value); std::vector<QPasSOCPProblem> GetQPasSOCPProblems(); /// This example is taken from the course notes of EE127A from University of /// California, Berkeley /// For a quadratic program /// 0.5 * x' * Q * x + c' * x /// s.t b_lb <= A * x <= b_ub /// It can be casted as an SOCP, as follows /// By introducing a new variable w = Q^{1/2}*x and y, z /// The equivalent SOCP is /// min c'x + y /// s.t 2 * y >= w' * w /// w = Q^{1/2} * x /// b_lb <= A * x <= b_ub /// @param Q A positive definite matrix /// @param c A column vector /// @param A A matrix /// @param b_lb A column vector /// @param b_ub A column vector class TestQPasSOCP : public ::testing::TestWithParam<QPasSOCPProblem> { public: TestQPasSOCP(); void SolveAndCheckSolution(const SolverInterface& solver, double tol = 1E-6); private: Eigen::MatrixXd Q_; Eigen::VectorXd c_; Eigen::MatrixXd A_; Eigen::VectorXd b_lb_; Eigen::VectorXd b_ub_; MathematicalProgram prog_socp_; MathematicalProgram prog_qp_; VectorXDecisionVariable x_socp_; symbolic::Variable y_; VectorXDecisionVariable x_qp_; }; /// This example is taken from the paper /// Applications of second-order cone programming /// By M.S.Lobo, L.Vandenberghe, S.Boyd and H.Lebret, /// Section 3.6 /// http://www.seas.ucla.edu/~vandenbe/publications/socp.pdf /// The problem tries to find the equilibrium state of a mechanical /// system, which consists of n nodes at position (x₁,y₁), (x₂,y₂), ..., /// (xₙ,yₙ) in ℝ². /// The nodes are connected by springs with given coefficient. /// The spring generate force when it is stretched, /// but not when it is compressed. /// Namely, the spring force is /// (spring_length - spring_rest_length) * spring_stiffness, /// if spring_length ≥ spring_rest_length; /// otherwise the spring force is zero. /// weightᵢ is the mass * gravity_acceleration /// of the i'th link. /// The equilibrium point is obtained when the total energy is minimized /// namely min ∑ᵢ weightᵢ * yᵢ + stiffness/2 * tᵢ² /// s.t sqrt((xᵢ - xᵢ₊₁)² + (yᵢ - yᵢ₊₁)²) - spring_rest_length ≤ tᵢ /// 0 ≤ tᵢ /// (x₁,y₁) = end_pos1 /// (xₙ,yₙ) = end_pos2 /// By introducing a slack variable z ≥ t₁² + ... + tₙ₋₁², the problem /// becomes /// an SOCP, with both Lorentz cone and rotated Lorentz cone constraints enum class FindSpringEquilibriumProblem { kProblem0 }; std::ostream& operator<<(std::ostream& os, FindSpringEquilibriumProblem value); std::vector<FindSpringEquilibriumProblem> GetFindSpringEquilibriumProblems(); class TestFindSpringEquilibrium : public ::testing::TestWithParam<FindSpringEquilibriumProblem> { public: TestFindSpringEquilibrium(); void SolveAndCheckSolution( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options = std::nullopt, double tol = 2E-3); private: Eigen::VectorXd weight_; double spring_rest_length_; double spring_stiffness_; Eigen::Vector2d end_pos1_; Eigen::Vector2d end_pos2_; MathematicalProgram prog_; VectorXDecisionVariable x_; VectorXDecisionVariable y_; VectorXDecisionVariable t_; symbolic::Variable z_; }; /** * Solve the following trivial problem * max (2x+3)*(3x+2) * s.t 2x+3 >= 0 * 3x+2 >= 0 * x<= 10 * We formulate this problem as a convex second order cone constraint, by * regarding the cost as the square of geometric mean between 2x+3 and 3x+2. * The optimal is x* = 10. */ class MaximizeGeometricMeanTrivialProblem1 { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MaximizeGeometricMeanTrivialProblem1) MaximizeGeometricMeanTrivialProblem1(); const MathematicalProgram& prog() const { return *prog_; } void CheckSolution(const MathematicalProgramResult& result, double tol); private: std::unique_ptr<MathematicalProgram> prog_; symbolic::Variable x_; std::unique_ptr<Binding<LinearCost>> cost_; }; /** * Solve the following trivial problem * max (2x+3)*(3x+2)*(4x+5) * s.t 2x+3 >= 0 * 3x+2 >= 0 * 4x+5 >= 0 * x<= 10 * We formulate this problem as a convex second order cone constraint, by * regarding the cost as the square of geometric mean between 2x+3, 3x+2 and * 4x+5. The optimal is x* = 10. */ class MaximizeGeometricMeanTrivialProblem2 { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MaximizeGeometricMeanTrivialProblem2) MaximizeGeometricMeanTrivialProblem2(); const MathematicalProgram& prog() const { return *prog_; } void CheckSolution(const MathematicalProgramResult& result, double tol); private: std::unique_ptr<MathematicalProgram> prog_; symbolic::Variable x_; std::unique_ptr<Binding<LinearCost>> cost_; }; /** * Tests maximizing geometric mean through second order cone constraint. * Given some points p₁, p₂, ..., pₖ ∈ ℝⁿ, find the smallest ellipsoid (centered * at the origin, and aligned with the axes) such that the ellipsoid contains * all these points. * This problem can be formulated as * max a(0) * a(1) * ... * a(n-1) * s.t pᵢᵀ diag(a) * pᵢ ≤ 1 for all i. * a(j) > 0 */ class SmallestEllipsoidCoveringProblem { public: // p.col(i) is the point pᵢ. explicit SmallestEllipsoidCoveringProblem( const Eigen::Ref<const Eigen::MatrixXd>& p); virtual ~SmallestEllipsoidCoveringProblem() {} const MathematicalProgram& prog() const { return *prog_; } void CheckSolution(const MathematicalProgramResult& result, double tol) const; protected: const VectorX<symbolic::Variable>& a() const { return a_; } private: // CheckSolution() already checks if the result is successful, and if all the // points are within the ellipsoid, with at least one point on the boundary // of the ellipsoid. CheckSolutionExtra can do extra checks for each specific // problem. virtual void CheckSolutionExtra(const MathematicalProgramResult&, double) const {} std::unique_ptr<MathematicalProgram> prog_; VectorX<symbolic::Variable> a_; Eigen::MatrixXd p_; std::unique_ptr<Binding<LinearCost>> cost_; }; class SmallestEllipsoidCoveringProblem1 : public SmallestEllipsoidCoveringProblem { public: SmallestEllipsoidCoveringProblem1(); ~SmallestEllipsoidCoveringProblem1() override {} private: void CheckSolutionExtra(const MathematicalProgramResult& result, double tol) const override; }; void SolveAndCheckSmallestEllipsoidCoveringProblems( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol); /** * Computes the minimal distance to a point from a sphere. * This problem has a quadratic cost and Lorentz cone constraint. * min (x - pt)² * s.t |x - center| <= radius */ template <int Dim> class MinimalDistanceFromSphereProblem { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(MinimalDistanceFromSphereProblem); /** @param with_linear_cost If set to true, we add the quadratic cost as the * sum of a quadratic and a linear cost. Otherwise we add it as a single * quadratic cost. */ MinimalDistanceFromSphereProblem(const Eigen::Matrix<double, Dim, 1>& pt, const Eigen::Matrix<double, Dim, 1>& center, double radius, bool with_linear_cost) : prog_{}, x_{prog_.NewContinuousVariables<Dim>()}, pt_{pt}, center_{center}, radius_{radius} { if (with_linear_cost) { prog_.AddQuadraticCost(2 * Eigen::Matrix<double, Dim, Dim>::Identity(), Eigen::Matrix<double, Dim, 1>::Zero(), 0.5 * pt_.squaredNorm(), x_); prog_.AddLinearCost(-2 * pt_, 0.5 * pt_.squaredNorm(), x_); } else { prog_.AddQuadraticErrorCost(Eigen::Matrix<double, Dim, Dim>::Identity(), pt_, x_); } VectorX<symbolic::Expression> lorentz_cone_expr(Dim + 1); lorentz_cone_expr(0) = radius_; lorentz_cone_expr.tail(Dim) = x_ - center_; prog_.AddLorentzConeConstraint(lorentz_cone_expr); } MathematicalProgram* get_mutable_prog() { return &prog_; } void SolveAndCheckSolution(const SolverInterface& solver, double tol) const { if (solver.available()) { MathematicalProgramResult result; solver.Solve(prog_, {}, {}, &result); EXPECT_TRUE(result.is_success()); const Eigen::Matrix<double, Dim, 1> x_sol = result.GetSolution(x_); // If pt is inside the sphere, then the optimal solution is x=pt. if ((pt_ - center_).norm() <= radius_) { EXPECT_TRUE(CompareMatrices(x_sol, pt_, tol)); EXPECT_NEAR(result.get_optimal_cost(), 0, tol); } else { // pt should be the intersection of the ray from center to pt, and the // sphere surface. Eigen::Matrix<double, Dim, 1> ray = pt_ - center_; EXPECT_TRUE(CompareMatrices( x_sol, center_ + radius_ * (ray.normalized()), tol)); } } } private: MathematicalProgram prog_; Eigen::Matrix<symbolic::Variable, Dim, 1> x_; Eigen::Matrix<double, Dim, 1> pt_; Eigen::Matrix<double, Dim, 1> center_; const double radius_; }; void TestSocpDualSolution1(const SolverInterface& solver, const SolverOptions& solver_options, double tol); void TestSocpDualSolution2(const SolverInterface& solver, const SolverOptions& solver_options, double tol); // We intentionally use duplicated variables in the second order cone constraint // to test if Drake's solver wrappers can handle duplicated variables. // min x0 + x1 // s.t 4x0²+3x1² ≤ 1 void TestSocpDuplicatedVariable1( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol); // We intentionally use duplicated variables in the second order cone constraint // to test if Drake's solver wrappers can handle duplicated variables. // min x0 + x1 // s.t 4x0²+9x1² ≤ 1 void TestSocpDuplicatedVariable2( const SolverInterface& solver, const std::optional<SolverOptions>& solver_options, double tol); // This SOCP is degenerate, in the sense it can be formulated as an LP. // find x // s.t x(0) >= sqrt( (x(1)-x(1))² + (x(2)-x(2))² ) // We also intentionally impose it in a way to contain duplicated variables in // the LorentzConeConstraint. void TestDegenerateSOCP(const SolverInterface& solver); } // namespace test } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/semidefinite_relaxation_internal_test.cc
#include "drake/solvers/semidefinite_relaxation_internal.h" #include <gtest/gtest.h> #include "drake/common/ssize.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_throws_message.h" #include "drake/math/matrix_util.h" #include "drake/solvers/clarabel_solver.h" #include "drake/solvers/csdp_solver.h" #include "drake/solvers/mosek_solver.h" #include "drake/solvers/scs_solver.h" #include "drake/solvers/solve.h" namespace drake { namespace solvers { namespace internal { using symbolic::Expression; using symbolic::Variable; using symbolic::Variables; GTEST_TEST(MakeSemidefiniteRelaxationInternalTest, TestSparseKron) { Eigen::MatrixXd A(3, 3); // clang-format off A << 1.77, -4.38, -3.63, -2.03, -0.57, 4.56, -1.66, 2.15, 10.02; // clang-format on Eigen::MatrixXd B(2, 2); // clang-format off B << 7.16, 1.8, 2.39, 5.77; // clang-format on Eigen::SparseMatrix<double> C(7, 13); std::vector<Eigen::Triplet<double>> C_triplets; C_triplets.emplace_back(0, 9, 1.77); C_triplets.emplace_back(1, 5, -0.57); C_triplets.emplace_back(2, 3, 4.56); C_triplets.emplace_back(3, 12, -1.66); C_triplets.emplace_back(4, 7, 2.15); C_triplets.emplace_back(5, 6, 10.02); C_triplets.emplace_back(0, 1, -0.45); C.setFromTriplets(C_triplets.begin(), C_triplets.end()); auto TestKron = [](const Eigen::SparseMatrix<double>& A_test, const Eigen::SparseMatrix<double>& B_test) { // AXB = (B.T ⊗ A)vec(X) so we compute this as a numerical sanity check. const Eigen::SparseMatrix<double> M1 = B_test.transpose(); const Eigen::SparseMatrix<double> M2 = A_test; Eigen::SparseMatrix<double> kron = SparseKroneckerProduct(M1, M2); EXPECT_EQ(kron.rows(), M1.rows() * M2.rows()); EXPECT_EQ(kron.cols(), M1.cols() * M2.cols()); EXPECT_EQ(kron.nonZeros(), M1.nonZeros() * M2.nonZeros()); Eigen::MatrixXd testMatrix(A_test.cols(), B_test.rows()); for (int i = 0; i < testMatrix.rows(); ++i) { for (int j = 0; j < testMatrix.cols(); ++j) { // put arbitrary values in testMatrix testMatrix(i, j) = 2 * (i + j) / (i + j + 1); } } Eigen::MatrixXd AXB = A_test * testMatrix * B_test; Eigen::VectorXd kron_vec = kron * Eigen::Map<const Eigen::VectorXd>( testMatrix.data(), testMatrix.size()); EXPECT_TRUE(CompareMatrices( Eigen::Map<const Eigen::VectorXd>(AXB.data(), AXB.size()), kron_vec, 1e-10, MatrixCompareType::absolute)); }; TestKron(A.sparseView(), B.sparseView()); TestKron(B.sparseView(), A.sparseView()); TestKron(C, A.sparseView()); TestKron(B.sparseView(), C); TestKron(C, B.sparseView()); } GTEST_TEST(MakeSemidefiniteRelaxationInternalTest, TestToSymmetricMatrixFromTensorVector) { // Check the 2x2 ⊗ 3x3 case. int num_elts = 3 * 6; // There are 3 elements in 2x2 basis and 6 in the 3x3 basis. VectorX<symbolic::Variable> y(num_elts); for (int i = 0; i < num_elts; ++i) { y(i) = symbolic::Variable("y_" + std::to_string(i)); } Eigen::MatrixX<symbolic::Variable> Y = ToSymmetricMatrixFromTensorVector(y, 2, 3); Eigen::MatrixX<symbolic::Variable> Y_expected(6, 6); // clang-format off Y_expected << y(0), y(1), y(2), y(6), y(7), y(8), y(1), y(3), y(4), y(7), y(9), y(10), y(2), y(4), y(5), y(8), y(10), y(11), y(6), y(7), y(8), y(12), y(13), y(14), y(7), y(9), y(10), y(13), y(15), y(16), y(8), y(10), y(11), y(14), y(16), y(17); // clang-format on EXPECT_EQ(Y.rows(), 6); EXPECT_EQ(Y.cols(), 6); for (int i = 0; i < 6; ++i) { for (int j = 0; j < 6; ++j) { EXPECT_TRUE(Y_expected(i, j).equal_to(Y(i, j))); } } // Check the 4x4 ⊗ 3x3 case. num_elts = 10 * 6; VectorX<symbolic::Variable> x(num_elts); for (int i = 0; i < num_elts; ++i) { x(i) = symbolic::Variable(fmt::format("x({}),", std::to_string(i))); } Eigen::MatrixX<symbolic::Variable> X = ToSymmetricMatrixFromTensorVector(x, 4, 3); Eigen::MatrixX<symbolic::Variable> X_expected(12, 12); // The following was checked by hand. It may seem big, but it is necessary to // check something this large. // clang-format off // NOLINT X_expected << x(0), x(1), x(2), x(6), x(7), x(8), x(12), x(13), x(14), x(18), x(19), x(20),// NOLINT x(1), x(3), x(4), x(7), x(9), x(10), x(13), x(15), x(16), x(19), x(21), x(22),// NOLINT x(2), x(4), x(5), x(8), x(10), x(11), x(14), x(16), x(17), x(20), x(22), x(23),// NOLINT x(6), x(7), x(8), x(24), x(25), x(26), x(30), x(31), x(32), x(36), x(37), x(38),// NOLINT x(7), x(9), x(10), x(25), x(27), x(28), x(31), x(33), x(34), x(37), x(39), x(40),// NOLINT x(8), x(10), x(11), x(26), x(28), x(29), x(32), x(34), x(35), x(38), x(40), x(41),// NOLINT x(12), x(13), x(14), x(30), x(31), x(32), x(42), x(43), x(44), x(48), x(49), x(50),// NOLINT x(13), x(15), x(16), x(31), x(33), x(34), x(43), x(45), x(46), x(49), x(51), x(52),// NOLINT x(14), x(16), x(17), x(32), x(34), x(35), x(44), x(46), x(47), x(50), x(52), x(53),// NOLINT x(18), x(19), x(20), x(36), x(37), x(38), x(48), x(49), x(50), x(54), x(55), x(56),// NOLINT x(19), x(21), x(22), x(37), x(39), x(40), x(49), x(51), x(52), x(55), x(57), x(58),// NOLINT x(20), x(22), x(23), x(38), x(40), x(41), x(50), x(52), x(53), x(56), x(58), x(59);// NOLINT // clang-format on EXPECT_EQ(X.rows(), 12); EXPECT_EQ(X.cols(), 12); for (int i = 0; i < 12; ++i) { for (int j = 0; j < 12; ++j) { EXPECT_TRUE(X_expected(i, j).equal_to(X(i, j))); } } } GTEST_TEST(MakeSemidefiniteRelaxationInternalTest, TestWAdj) { Eigen::MatrixXd Y(5, 5); // clang-format off Y << -3.08, -0.84, 0.32, 0.54, 0.51, -0.84, 2.6 , 1.72, 0.09, 0.79, 0.32, 1.72, 3.09, 1.19, 0.31, 0.54, 0.09, 1.19, -0.37, -2.57, 0.51, 0.79, 0.31, -2.57, -0.08; // clang-format on // The lower triangular part of Y has 15 entries Eigen::VectorXd y_tril(15); y_tril = math::ToLowerTriangularColumnsFromMatrix(Y); Eigen::SparseMatrix<double> W_adj = GetWAdjForTril(6); EXPECT_EQ(W_adj.rows(), 6); EXPECT_EQ(W_adj.cols(), y_tril.size()); EXPECT_EQ(W_adj.nonZeros(), 14 /* 2 * (6-1) + 4 */); Eigen::VectorXd result(6); result = W_adj * y_tril; const double tol{1e-10}; EXPECT_NEAR(result(0), Y.trace(), tol); EXPECT_NEAR(result(1), Y(0, 0) - Y.block(1, 1, 4, 4).trace(), tol); for (int i = 2; i < W_adj.rows(); ++i) { EXPECT_NEAR(result(i), 2 * Y(0, i - 1), tol); } } namespace { // Makes a random vector with all positive entries that is not in the Lorentz // cone. This method does not sample uniformly over all such vectors. Eigen::VectorXd MakeRandomPositiveOrthantNonLorentzVector(const int r, const double scale) { Eigen::VectorXd ret = scale * (Eigen::VectorXd::Random(r) + Eigen::VectorXd::Ones(r)); while (r > 1 && ret(0) > ret.tail(r - 1).norm()) { // This ensures we are not in the Lorentz cone by scaling the first entry to // be too small. ret(0) = 1 / (0.5 * ret.tail(r - 1).norm()) * (Eigen::VectorXd::Random(1)(0) + 1); } return ret; } // Returns true if the vector x has all entries which are positive bool CheckIsPositiveOrthantVector(const Eigen::Ref<const Eigen::VectorXd>& x) { return (x.array() >= 0).all(); } // Construct a random matrix A that is guaranteed to map a positive vector in m // dimensions to another positive vector in r dimensions. This method does not // sample uniformly over all such maps. Eigen::MatrixXd MakeRandomPositiveOrthantPositiveMap(const int r, const int m, const double scale) { Eigen::MatrixXd A(r, m); for (int i = 0; i < m; i++) { A.col(i) = MakeRandomPositiveOrthantNonLorentzVector(r, scale); } return A; } // Constructs a random vector that is in the Lorentz cone, but is not in the // positive orthant. This method does not sample uniformly over all such // vectors. Eigen::VectorXd MakeRandomLorentzNonPositiveOrthantVector(const int r, const double scale) { Eigen::VectorXd ret(r); if (r > 1) { ret.tail(r - 1) = scale * Eigen::VectorXd::Random(r - 1); // Ensures that ret(0) ≥ norm(ret(r-1)) and that ret(0) ≥ 0. do { ret(0) = 2 * scale * (Eigen::VectorXd::Random(1)(0) + 1); } while (ret(0) < ret.tail(r - 1).norm() || ret(0) < 0); // Ensure that ret has at least 1 negative entry so that it is not in the // positive orthant. if (ret(1) > 0) { ret(1) *= -1; } } else { ret(0) = scale * (Eigen::VectorXd::Random(1)(0) + 1); } return ret; } // Returns true if the vector x is in the Lorentz cone bool CheckIsLorentzVector(const Eigen::Ref<const Eigen::VectorXd>& x) { if (x.rows() == 1) { return x(0) >= 0; } return x(0) >= x.tail(x.rows() - 1).norm(); } // Construct a random matrix A that is guaranteed to map a Lorentz vector in m // dimensions to another Lorentz vector in r. This method does not sample // uniformly over all such maps. Eigen::MatrixXd MakeRandomLorentzPositiveMap(const int r, const int m, const double scale) { // Create a map A: (t; x) ↦ (st; A₁x) where s is some positive scaling of t // and A₁ has induced matrix norm less than s. This ensures that A is a // Lorentz positive map, the norm |A₁x| ≤ s and therefore |A₁x| ≤ st Eigen::MatrixXd A = Eigen::MatrixXd::Zero(r, m); // Choose a random, positive scaling larger than 1/2 for the first entry. A(0, 0) = scale * (Eigen::VectorXd::Random(1)(0) + 1.5); if (r > 1 && m > 1) { Eigen::MatrixXd T = Eigen::MatrixXd::Random(r - 1, m - 1); Eigen::JacobiSVD<Eigen::MatrixXd> svd( T, Eigen::ComputeThinU | Eigen::ComputeThinV); // Rescale the singular values so that the matrix norm is less than s/2. const double svd_scaling = A(0, 0) / svd.singularValues().maxCoeff() / 2; const Eigen::VectorXd regularized_singular_values = svd_scaling * svd.singularValues(); A.bottomRightCorner(r - 1, m - 1) = svd.matrixU() * regularized_singular_values.asDiagonal() * svd.matrixV().transpose(); } else if (m == 1) { // Make the last r entries of the column matrix have norm A(0,0) / 2 A.col(0).tail(r - 1) = Eigen::VectorXd::Random(r - 1); A.col(0).tail(r - 1) = A.col(0).tail(r - 1) / A.col(0).tail(r - 1).norm() * (A(0, 0) / 2); } else if (r == 1) { // Make the last m entries of row matrix have norm A(0,0) / 2 A.row(0).tail(m - 1) = Eigen::VectorXd::Random(m - 1); A.row(0).tail(m - 1) = A.row(0).tail(m - 1) / A.row(0).tail(m - 1).norm() * (A(0, 0) / 2); } return A; } bool ProgramSolvedWithoutError(const SolutionResult& result) { return result == kSolutionFound || result == kInfeasibleConstraints || result == kUnbounded || result == kInfeasibleOrUnbounded || result == kDualInfeasible; } enum SupportedTestCone { kPositiveOrthant, kLorentzCone }; } // namespace class Cone1ByCone2SeparabilityTest : public ::testing::TestWithParam<std::tuple<int, int>> { public: Cone1ByCone2SeparabilityTest(const SupportedTestCone cone1, const SupportedTestCone cone2) : prog_(), cone1_(cone1), cone2_(cone2) { // Seed the random generator used by Eigen. std::srand(99); int m, n; std::tie(m, n) = GetParam(); X_ = prog_.NewContinuousVariables(m, n, "X"); } void DoTest(const std::optional<Eigen::MatrixXd>& A_opt = std::nullopt, const std::optional<Eigen::MatrixXd>& B_opt = std::nullopt) { MatrixX<Expression> Y; Eigen::MatrixXd A = A_opt.value_or(Eigen::MatrixXd::Identity(X_.rows(), X_.rows())); Eigen::MatrixXd B = B_opt.value_or(Eigen::MatrixXd::Identity(X_.cols(), X_.cols())); if (!A_opt.has_value() && !B_opt.has_value()) { // Use the Variable variant of the function. Y = X_.template cast<Expression>(); AddCone1ByCone2SeparableConstraint(X_); } else { // Use the Expression variant of the function. Y = A * X_ * B; AddCone1ByCone2SeparableConstraint(Y); } CheckCone1ByCone2SeparableConstraintsAdded(A, B); MakeTestVectors(A, B); // Y is required to be equal to a simple cone1-cone2 separable // tensor therefore this program should be feasible. Eigen::MatrixXd test_matrix = xr_cone1_ * xc_cone2_.transpose(); EXPECT_EQ(DoTestCase(Y, test_matrix), true); // Y is required to be equal to a cone1-cone2 separable tensor // therefore this program should be feasible. test_matrix = (2 * xr_cone1_ * yc_cone2_.transpose() + 3 * yr_cone1_ * xc_cone2_.transpose()); EXPECT_EQ(DoTestCase(Y, test_matrix), true); // Y is required to be equal to something not that is not // cone1-cone2 separable, therefore this should be infeasible. test_matrix = -100 * zr_not_conic_ * zc_not_conic_.transpose(); EXPECT_EQ(DoTestCase(Y, test_matrix), false); // A tensor between a cone1 vector, and non-conic vector. // Y is required to be equal to something not that is not cone1-cone2 // separable therefore this should be infeasible. test_matrix = yr_cone1_ * zc_not_conic_.transpose(); EXPECT_EQ(DoTestCase(Y, test_matrix), false); // A tensor between a non-conic vector and cone2 vector. // Y is required to be equal to something not that is not Lorentz // separable therefore this should be infeasible. test_matrix = zr_not_conic_ * xc_cone2_.transpose(); EXPECT_EQ(DoTestCase(Y, test_matrix), false); // A tensor that is cone1-cone1 separable. This is cone1-cone2 separable if // and only if cone1==cone2. In the case that B is not full row rank, then Y // will generically fail to be separable due to the subspace constraint // imposed by B (i.e. wc_cone1_ is not in the image of B). test_matrix = xr_cone1_ * wc_cone1_.transpose(); EXPECT_EQ(DoTestCase(Y, test_matrix), cone1_ == cone2_ && B.cols() <= B.rows()); // A tensor that is cone2-cone2 separable. This is cone1-cone2 separable if // and only if cone1==cone2. In the case that A is not full column rank, // then Y will generically fail to be separable due to the subspace // constraint imposed by A (i.e. wr_cone2_ is not in the image of A). test_matrix = wr_cone2_ * xc_cone2_.transpose(); EXPECT_EQ(DoTestCase(Y, test_matrix), cone1_ == cone2_ && A.rows() <= A.cols()); // A tensor that is non-conic combination of cone1-cone2 separable tensors // separable tensors. test_matrix = 2 * yr_cone1_ * xc_cone2_.transpose() - 1000 * xr_cone1_ * yc_cone2_.transpose(); EXPECT_EQ(DoTestCase(Y, test_matrix), false); // Now clear out the constraints, so that we can repeatedly call this // method. for (const auto& constraints : prog_.GetAllConstraints()) { prog_.RemoveConstraint(constraints); } ASSERT_EQ(prog_.GetAllConstraints().size(), 0); } protected: // Adds the constraint that Z is Cone 1 by Cone 2 separable to prog_ and // ensures that the right number of constraints and variables have been added // to prog_. virtual void AddCone1ByCone2SeparableConstraint( const MatrixX<Variable>& Z) = 0; // Adds the constraint that Z is Cone 1 by Cone 2 separable to prog_ and // ensures that the right number of constraints and variables have been added // to prog_. virtual void AddCone1ByCone2SeparableConstraint( const MatrixX<Expression>& Z) = 0; // Checks that prog_ has the right number of constraints and variables to // indicate that a matrix is constrained to be Cone1 by Cone2 separable. virtual void CheckCone1ByCone2SeparableConstraintsAdded( const Eigen::MatrixXd& A, const Eigen::MatrixXd& B) = 0; MathematicalProgram prog_; // The matrix we will try to write as a tensor product of elements in cone1 // and cone2. MatrixX<Variable> X_; // A vector guaranteed to be in cone one and in the range of A. Eigen::VectorXd xr_cone1_; // A vector guaranteed to be in cone one and in the range of A. Eigen::VectorXd yr_cone1_; // A vector that is in cone one but NOT guaranteed to // be in the range A. Eigen::VectorXd wr_cone1_; // A vector that is in cone one but NOT guaranteed to be in // the range of Bᵀ. Eigen::VectorXd wc_cone1_; // A vector guaranteed to be in cone two and in the range of Bᵀ. Eigen::VectorXd xc_cone2_; // A vector guaranteed to be in cone two and in the range of Bᵀ. Eigen::VectorXd yc_cone2_; // A vector that is in cone two but NOT guaranteed to // be in the range A. Eigen::VectorXd wr_cone2_; // A vector that is in cone two but NOT guaranteed to // be in the range of Bᵀ. Eigen::VectorXd wc_cone2_; // Two vectors in neither cone. Eigen::VectorXd zr_not_conic_; Eigen::VectorXd zc_not_conic_; private: // Initialize the protected test vectors to be in the requisite cones and in // the image of A and Bᵀ respectively as needed. void MakeTestVectors(const Eigen::Ref<const Eigen::MatrixXd>& A, const Eigen::Ref<const Eigen::MatrixXd>& B) { const double scale = 2.0; const auto initialize_vectors_in_cone_and_image = [&scale, &A, &B](const Eigen::MatrixXd& C, const SupportedTestCone cone, Eigen::VectorXd* x, Eigen::VectorXd* y, Eigen::VectorXd* wr, Eigen::VectorXd* wc) { // Notice that if C is not a cone-positive map, then x and // y will not necessarily be in the cone. switch (cone) { case SupportedTestCone::kPositiveOrthant: *x = C * MakeRandomPositiveOrthantNonLorentzVector(C.cols(), scale); *y = C * MakeRandomPositiveOrthantNonLorentzVector(C.cols(), scale); if (!CheckIsPositiveOrthantVector(*x) || !CheckIsPositiveOrthantVector(*y)) { throw std::logic_error(fmt::format( "C=\n{}\n is not a positive-orthant positive map.", fmt_eigen(C))); } *wr = MakeRandomPositiveOrthantNonLorentzVector(A.rows(), scale); *wc = MakeRandomPositiveOrthantNonLorentzVector(B.cols(), scale); break; case SupportedTestCone::kLorentzCone: *x = C * MakeRandomLorentzNonPositiveOrthantVector(C.cols(), scale); *y = C * MakeRandomLorentzNonPositiveOrthantVector(C.cols(), scale); if (!CheckIsLorentzVector(*x) || !CheckIsLorentzVector(*y)) { throw std::logic_error(fmt::format( "C=\n{}\n is not a Lorentz positive map.", fmt_eigen(C))); } *wr = MakeRandomLorentzNonPositiveOrthantVector(A.rows(), scale); *wc = MakeRandomLorentzNonPositiveOrthantVector(B.cols(), scale); break; } }; initialize_vectors_in_cone_and_image(A, cone1_, &xr_cone1_, &yr_cone1_, &wr_cone1_, &wc_cone1_); initialize_vectors_in_cone_and_image(B.transpose(), cone2_, &xc_cone2_, &yc_cone2_, &wr_cone2_, &wc_cone2_); const auto is_conic_vector = [](const Eigen::VectorXd& z, const SupportedTestCone cone) { switch (cone) { case SupportedTestCone::kPositiveOrthant: return CheckIsPositiveOrthantVector(z); case SupportedTestCone::kLorentzCone: return CheckIsLorentzVector(z); } DRAKE_UNREACHABLE(); }; zr_not_conic_ = Eigen::VectorXd::Random(A.rows()); // Note that all supported cones occupy less (and typically much less) than // 1/2 the volume of the ambient space and therefore this loop is unlikely // to take very long. while (is_conic_vector(zr_not_conic_, cone1_) || is_conic_vector(zr_not_conic_, cone2_)) { zr_not_conic_ = Eigen::VectorXd::Random(A.rows()); } zc_not_conic_ = Eigen::VectorXd::Random(B.cols()); // Note that all supported cones occupy less (and typically much less) than // 1/2 the volume of the ambient space and therefore this loop is unlikely // to take very long. while (is_conic_vector(zc_not_conic_, cone1_) || is_conic_vector(zc_not_conic_, cone2_)) { zc_not_conic_ = Eigen::VectorXd::Random(B.cols()); } } bool DoTestCase(const Eigen::Ref<const MatrixX<Expression>>& Y, const Eigen::Ref<const Eigen::MatrixXd>& test_mat) { auto constraint = prog_.AddLinearEqualityConstraint(Y == test_mat); auto result = Solve(prog_); prog_.RemoveConstraint(constraint); DRAKE_DEMAND(ProgramSolvedWithoutError(result.get_solution_result())); return result.is_success(); } const SupportedTestCone cone1_; const SupportedTestCone cone2_; }; class PositiveOrthantByLorentzSeparabilityTest : public Cone1ByCone2SeparabilityTest { public: PositiveOrthantByLorentzSeparabilityTest() : Cone1ByCone2SeparabilityTest(SupportedTestCone::kPositiveOrthant, SupportedTestCone::kLorentzCone) {} private: void AddCone1ByCone2SeparableConstraint(const MatrixX<Variable>& Z) { AddMatrixIsPositiveOrthantByLorentzSeparableConstraint(Z, &prog_); } void AddCone1ByCone2SeparableConstraint(const MatrixX<Expression>& Z) { AddMatrixIsPositiveOrthantByLorentzSeparableConstraint(Z, &prog_); } void CheckCone1ByCone2SeparableConstraintsAdded(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B) { EXPECT_EQ(ssize(prog_.lorentz_cone_constraints()), A.rows()); EXPECT_EQ(ssize(prog_.GetAllConstraints()), A.rows()); unused(B); } }; TEST_P(PositiveOrthantByLorentzSeparabilityTest, AddMatrixIsPositiveOrthantByLorentzSeparableConstraintVariable) { this->DoTest(); } TEST_P( PositiveOrthantByLorentzSeparabilityTest, AddMatrixIsPositiveOrthantByLorentzSeparableConstraintExpressionKeepSize) { int m, n; std::tie(m, n) = GetParam(); const double scale = 3; // This map needs to be a positive, positive-orthant map. Eigen::MatrixXd A = MakeRandomPositiveOrthantPositiveMap(m, m, scale); // This map needs to be a positive Lorentz map. Eigen::MatrixXd B = MakeRandomLorentzPositiveMap(n, n, scale); this->DoTest(A, B); } TEST_P(PositiveOrthantByLorentzSeparabilityTest, AddMatrixIsPositiveOrthantByLorentzSeparableConstraintChangeSize) { // The subspaces in some of these tests have small dimension, making them // numerically difficult for SDP solvers which do no preprocessing. Therefore, // we only solve these with Mosek as it is the only one which currently gives // reliable results. if (MosekSolver().enabled() && MosekSolver().available()) { int m, n; std::tie(m, n) = GetParam(); const int r1 = m + 5; const int r2 = m - 1; const int c1 = n + 3; const int c2 = n - 2; const double scale = 0.75; // These maps need to be positive, positive-orthant maps. Eigen::MatrixXd A1 = MakeRandomPositiveOrthantPositiveMap(r1, m, scale); Eigen::MatrixXd A2 = MakeRandomPositiveOrthantPositiveMap(r2, m, scale); // These maps need to be positive Lorentz maps. Eigen::MatrixXd B1 = MakeRandomLorentzPositiveMap(n, c1, scale); Eigen::MatrixXd B2 = MakeRandomLorentzPositiveMap(n, c2, scale); this->DoTest(A1, B1); this->DoTest(A1, B2); this->DoTest(A2, B1); this->DoTest(A2, B2); } } INSTANTIATE_TEST_SUITE_P(test, PositiveOrthantByLorentzSeparabilityTest, ::testing::Values(std::pair<int, int>{4, 5}, // m < n std::pair<int, int>{5, 4}, // m > n std::pair<int, int>{6, 6} // m == n // There are no special cases )); // NOLINT class LorentzByPositiveOrthantSeparabilityTest : public Cone1ByCone2SeparabilityTest { public: LorentzByPositiveOrthantSeparabilityTest() : Cone1ByCone2SeparabilityTest(SupportedTestCone::kLorentzCone, SupportedTestCone::kPositiveOrthant) {} private: void AddCone1ByCone2SeparableConstraint(const MatrixX<Variable>& Z) { AddMatrixIsLorentzByPositiveOrthantSeparableConstraint(Z, &prog_); } void AddCone1ByCone2SeparableConstraint(const MatrixX<Expression>& Z) { AddMatrixIsLorentzByPositiveOrthantSeparableConstraint(Z, &prog_); } void CheckCone1ByCone2SeparableConstraintsAdded(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B) { EXPECT_EQ(ssize(prog_.lorentz_cone_constraints()), B.cols()); EXPECT_EQ(ssize(prog_.GetAllConstraints()), B.cols()); unused(A); } }; TEST_P(LorentzByPositiveOrthantSeparabilityTest, AddMatrixIsLorentzByPositiveOrthantSeparableConstraintVariable) { this->DoTest(); } TEST_P( LorentzByPositiveOrthantSeparabilityTest, AddMatrixIsLorentzByPositiveOrthantSeparableConstraintExpressionKeepSize) { int m, n; std::tie(m, n) = GetParam(); const double scale = 3; // This map needs to be a positive, positive-orthant map. Eigen::MatrixXd A = MakeRandomLorentzPositiveMap(m, m, scale); // This map needs to be a positive Lorentz map. Eigen::MatrixXd B = MakeRandomPositiveOrthantPositiveMap(n, n, scale); this->DoTest(A, B); } TEST_P(LorentzByPositiveOrthantSeparabilityTest, AddMatrixIsLorentzByPositiveOrthantSeparableConstraintChangeSize) { // The subspaces in some of these tests have small dimension, making them // numerically difficult for SDP solvers which do no preprocessing. Therefore, // we only solve these with Mosek as it is the only one which currently gives // reliable results. if (MosekSolver().enabled() && MosekSolver().available()) { int m, n; std::tie(m, n) = GetParam(); const int r1 = m + 5; const int r2 = m - 1; const int c1 = n + 3; const int c2 = n - 2; const double scale = 3; // These maps need to be positive, positive-orthant maps. Eigen::MatrixXd A1 = MakeRandomLorentzPositiveMap(r1, m, scale); Eigen::MatrixXd A2 = MakeRandomLorentzPositiveMap(r2, m, scale); // These maps need to be positive Lorentz maps. Eigen::MatrixXd B1 = MakeRandomPositiveOrthantPositiveMap(n, c1, scale); Eigen::MatrixXd B2 = MakeRandomPositiveOrthantPositiveMap(n, c2, scale); this->DoTest(A1, B1); this->DoTest(A1, B2); this->DoTest(A2, B1); this->DoTest(A2, B2); } } INSTANTIATE_TEST_SUITE_P(test, LorentzByPositiveOrthantSeparabilityTest, ::testing::Values(std::pair<int, int>{4, 5}, // m < n std::pair<int, int>{5, 4}, // m > n std::pair<int, int>{6, 6} // m == n // There are no special cases )); // NOLINT class LorentzByLorentzSeparabilityTest : public Cone1ByCone2SeparabilityTest { public: LorentzByLorentzSeparabilityTest() : Cone1ByCone2SeparabilityTest(SupportedTestCone::kLorentzCone, SupportedTestCone::kLorentzCone) {} private: void AddCone1ByCone2SeparableConstraint(const MatrixX<Variable>& Z) { AddMatrixIsLorentzByLorentzSeparableConstraint(Z, &prog_); } void AddCone1ByCone2SeparableConstraint(const MatrixX<Expression>& Z) { AddMatrixIsLorentzByLorentzSeparableConstraint(Z, &prog_); } void CheckCone1ByCone2SeparableConstraintsAdded(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B) { int r = A.rows(); int c = B.cols(); if (r >= 3 && c >= 3) { EXPECT_EQ(ssize(prog_.positive_semidefinite_constraints()), 1); EXPECT_EQ(ssize(prog_.linear_equality_constraints()), 1); EXPECT_EQ(ssize(prog_.GetAllConstraints()), 2); const Binding<PositiveSemidefiniteConstraint> psd_constraint = prog_.positive_semidefinite_constraints()[0]; EXPECT_EQ(psd_constraint.evaluator()->matrix_rows(), (r - 1) * (c - 1)); } else if (r == 1 && c == 1) { // This linear constraints gets parsed as either a bounding box or linear // constraint, but not both. EXPECT_EQ(ssize(prog_.bounding_box_constraints()) + ssize(prog_.linear_constraints()), 1); EXPECT_EQ(ssize(prog_.GetAllConstraints()), 1); } else if (r <= 2 && c <= 2) { EXPECT_EQ(ssize(prog_.linear_constraints()), 1); EXPECT_EQ(ssize(prog_.GetAllConstraints()), 1); } else if (r > 2) { EXPECT_EQ(ssize(prog_.lorentz_cone_constraints()), c); EXPECT_EQ(ssize(prog_.GetAllConstraints()), c); } else { EXPECT_EQ(ssize(prog_.lorentz_cone_constraints()), r); EXPECT_EQ(ssize(prog_.GetAllConstraints()), r); } } }; TEST_P(LorentzByLorentzSeparabilityTest, AddMatrixIsLorentzByLorentzSeparableConstraintVariable) { int m, n; std::tie(m, n) = GetParam(); this->DoTest(); } TEST_P(LorentzByLorentzSeparabilityTest, AddMatrixIsLorentzByLorentzSeparableConstraintExpressionKeepSize) { int m, n; std::tie(m, n) = GetParam(); double scale = 3; // These maps need to be Lorentz-positive maps. Eigen::MatrixXd A = MakeRandomLorentzPositiveMap(m, m, scale); Eigen::MatrixXd B = MakeRandomLorentzPositiveMap(n, n, scale); this->DoTest(A, B); } TEST_P(LorentzByLorentzSeparabilityTest, AddMatrixIsLorentzByLorentzSeparableConstraintExpressionChangeSize) { // The subspaces in some of these tests have small dimension, making them // numerically difficult for SDP solvers which do no preprocessing. Therefore, // we only solve these with Mosek as it is the only one which currently gives // reliable results. if (MosekSolver().enabled() && MosekSolver().available()) { int m, n; std::tie(m, n) = GetParam(); const int r1 = m + 5; const int r2 = std::max(m - 1, 1); const int c1 = n + 3; const int c2 = std::max(n - 2, 1); const double scale = 2; // These maps need to be positive Lorentz maps. Eigen::MatrixXd A1 = MakeRandomLorentzPositiveMap(r1, m, scale); Eigen::MatrixXd A2 = MakeRandomLorentzPositiveMap(r2, m, scale); Eigen::MatrixXd B1 = MakeRandomLorentzPositiveMap(n, c1, scale); Eigen::MatrixXd B2 = MakeRandomLorentzPositiveMap(n, c2, scale); this->DoTest(A1, B1); this->DoTest(A2, B1); this->DoTest(A1, B2); this->DoTest(A2, B2); } } INSTANTIATE_TEST_SUITE_P( test, LorentzByLorentzSeparabilityTest, ::testing::Values(std::pair<int, int>{3, 4}, // m < n std::pair<int, int>{4, 3}, // m > n std::pair<int, int>{5, 5}, // m == n std::pair<int, int>{1, 1}, // special case m = n = 1 std::pair<int, int>{2, 1}, // special case m = 2, n = 1 std::pair<int, int>{1, 2}, // special case m = 1, m = 1 std::pair<int, int>{2, 2}, // special case m = 2, m = 2 std::pair<int, int>{1, 4}, // special case m = 1, n ≥ 3 std::pair<int, int>{2, 5}, // special case m = 2, n ≥ 3 std::pair<int, int>{3, 1}, // special case m ≥ 3, n = 1 std::pair<int, int>{7, 2} // special case m ≥ 3, n = 2 )); // NOLINT } // namespace internal } // namespace solvers } // namespace drake
0
/home/johnshepherd/drake/solvers
/home/johnshepherd/drake/solvers/test/integer_optimization_util_test.cc
#include "drake/solvers/integer_optimization_util.h" #include <gtest/gtest.h> #include "drake/solvers/mathematical_program.h" #include "drake/solvers/osqp_solver.h" #include "drake/solvers/solve.h" namespace drake { namespace solvers { namespace { class IntegerOptimizationUtilTest : public ::testing::Test { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(IntegerOptimizationUtilTest) enum class LogicalOperand { kAnd, kOr, kXor }; IntegerOptimizationUtilTest() : prog_{}, b_{prog_.NewContinuousVariables<2>()}, b_vals_{{Eigen::Vector2i(0, 0), Eigen::Vector2i(0, 1), Eigen::Vector2i(1, 0), Eigen::Vector2i(1, 1)}}, b0_cnstr_{prog_.AddLinearConstraint(b_(0) == 0)}, b1_cnstr_{prog_.AddLinearConstraint(b_(1) == 0)} {} void CheckLogicalOperand(LogicalOperand operand) { // We want to make sure that given that b0 and b1 are fixed, the only // solution to satisfying the constraints, is that // operand_result = b0 operand b1. symbolic::Variable operand_result = prog_.NewContinuousVariables<1>()(0); switch (operand) { case LogicalOperand::kAnd: prog_.AddConstraint(CreateLogicalAndConstraint( symbolic::Expression{b_(0)}, symbolic::Expression{b_(1)}, symbolic::Expression{operand_result})); break; case LogicalOperand::kOr: prog_.AddConstraint(CreateLogicalOrConstraint( symbolic::Expression{b_(0)}, symbolic::Expression{b_(1)}, symbolic::Expression{operand_result})); break; case LogicalOperand::kXor: prog_.AddConstraint(CreateLogicalXorConstraint( symbolic::Expression{b_(0)}, symbolic::Expression{b_(1)}, symbolic::Expression{operand_result})); break; } auto cost = prog_.AddLinearCost(operand_result); // Solve the program // min operand_result // s.t operand_result = b0 operand b1 // b0 = b_vals_[i](0) // b1 = b_vals_[i](1). for (int i = 0; i < 4; ++i) { double operand_result_expected; switch (operand) { case LogicalOperand::kAnd: operand_result_expected = static_cast<double>(b_vals_[i](0) & b_vals_[i](1)); break; case LogicalOperand::kOr: operand_result_expected = static_cast<double>(b_vals_[i](0) | b_vals_[i](1)); break; case LogicalOperand::kXor: operand_result_expected = static_cast<double>(b_vals_[i](0) ^ b_vals_[i](1)); break; } cost.evaluator()->UpdateCoefficients(Vector1d(1)); b0_cnstr_.evaluator()->UpdateLowerBound(Vector1d(b_vals_[i](0))); b0_cnstr_.evaluator()->UpdateUpperBound(Vector1d(b_vals_[i](0))); b1_cnstr_.evaluator()->UpdateLowerBound(Vector1d(b_vals_[i](1))); b1_cnstr_.evaluator()->UpdateUpperBound(Vector1d(b_vals_[i](1))); MathematicalProgramResult result = Solve(prog_); EXPECT_TRUE(result.is_success()); double tol = 1E-3; if (result.get_solver_id() == OsqpSolver::id()) { // OSQP can solve linear program, but it is likely to fail in polishing, // thus the solution is less accurate. tol = 3E-3; } EXPECT_NEAR(result.GetSolution(operand_result), operand_result_expected, tol); // Now update the objective to // min -b_and // The solution should be the same. cost.evaluator()->UpdateCoefficients(Vector1d(-1)); result = Solve(prog_); EXPECT_TRUE(result.is_success()); EXPECT_NEAR(result.GetSolution(operand_result), operand_result_expected, tol); } } protected: MathematicalProgram prog_; VectorDecisionVariable<2> b_; std::array<Eigen::Vector2i, 4> b_vals_; Binding<LinearConstraint> b0_cnstr_; Binding<LinearConstraint> b1_cnstr_; }; TEST_F(IntegerOptimizationUtilTest, TestAnd) { CheckLogicalOperand(LogicalOperand::kAnd); } TEST_F(IntegerOptimizationUtilTest, TestOr) { CheckLogicalOperand(LogicalOperand::kOr); } TEST_F(IntegerOptimizationUtilTest, TestXor) { CheckLogicalOperand(LogicalOperand::kXor); } GTEST_TEST(TestBinaryCodeMatchConstraint, Test) { MathematicalProgram prog; const auto b = prog.NewContinuousVariables<3>(); auto b_constraint = prog.AddBoundingBoxConstraint(0, 1, b); Eigen::Vector3i b_expected{0, 1, 1}; const auto match = prog.NewContinuousVariables<1>()(0); prog.AddConstraint(CreateBinaryCodeMatchConstraint(b, b_expected, match)); auto match_constraint = prog.AddBoundingBoxConstraint(0, 1, match); for (int b0_val : {0, 1}) { for (int b1_val : {0, 1}) { for (int b2_val : {0, 1}) { for (double match_val : {-0.5, 0.0, 0.5, 1.0}) { const Eigen::Vector3d b_val(b0_val, b1_val, b2_val); b_constraint.evaluator()->UpdateLowerBound(b_val); b_constraint.evaluator()->UpdateUpperBound(b_val); match_constraint.evaluator()->UpdateUpperBound(Vector1d(match_val)); match_constraint.evaluator()->UpdateLowerBound(Vector1d(match_val)); const auto result = Solve(prog); if (b0_val == 0 && b1_val == 1 && b2_val == 1) { EXPECT_EQ(result.is_success(), match_val == 1.0); } else { EXPECT_EQ(result.is_success(), match_val == 0.0); } } } } } } } // namespace } // namespace solvers } // namespace drake
0